void plotxsec(TString xsectype/*= "vm"*/, bool ploty/*=kFALSE*/,bool sim/*=kFALSE*/,bool comp/*=kFALSE*/){
  if (setup(xsectype)==kFALSE) return;

  gStyle->SetOptStat(0);

  TString methodB = TString::Format("Yield - Method B {%s}",_topNames[4].Data());
  TString methodA = TString::Format("Yield - Method A");

  TH1F* hYW_Dir[5];
  TH1F* hYW_5D[5];
  TH1F* hYW_TH[5];
  TH1F* hYWnorm_Dir[5];
  TH1F* hYWnorm_5D[5];
  TLegend* l_Dir = new TLegend(0.1,0.7,0.5,0.9);
  TLegend* l_5D  = new TLegend(0.1,0.7,0.5,0.9);
  TString hname_hYW_Dir = TString::Format("hYW_Dir/Varset1/hYW_ACC_CORR");
  TString hname_hYW_5D  = TString::Format("hYW/Varset1/hYW");
  TString hname_hYW_TH  = TString::Format("hYW_Dir/Varset1/hYW_TH");

  TCanvas* c_Dir = new TCanvas(TString::Format("Dir-%s:%s", xsectype.Data(), _q2w_bng.Data()), 
                               TString::Format("Dir-%s:%s", xsectype.Data(), _q2w_bng.Data()) );
  c_Dir->SetGrid(); 
  TCanvas* c_5D = new TCanvas(TString::Format("5D-%s:%s", xsectype.Data(), _q2w_bng.Data()), 
                              TString::Format("5D-%s:%s", xsectype.Data(), _q2w_bng.Data()) );
  c_5D->SetGrid();
  //! For each Top: hYW_Dir,hYW_5D --> hYWnorm_Dir,hYWnorm_5D & then draw
  TFile* fy[5];
  if (sim) memcpy(fy,_fysim,sizeof(_fysim));
  else     memcpy(fy,_fyexp,sizeof(_fyexp));
  for (int iTop=0;iTop<5;iTop++){
    if (fy[iTop]==NULL) continue;
    cout << "Top = " << iTop << endl;
    hYW_Dir[iTop] = (TH1F*)fy[iTop]->Get(hname_hYW_Dir);
    hYW_5D[iTop]  = (TH1F*)fy[iTop]->Get(hname_hYW_5D);
    if(sim) hYW_TH[iTop]  = (TH1F*)fy[iTop]->Get(hname_hYW_TH);
    if (hYW_Dir[iTop]==NULL || hYW_5D[iTop]==NULL) continue;
    hYW_Dir[iTop]->SetMarkerStyle(20+iTop);
    hYW_Dir[iTop]->SetMarkerColor(2+iTop);
    //hYW_Dir[iTop]->SetMaximum(150000);
    hYW_5D[iTop]->SetMarkerStyle(20+iTop); //+5
    hYW_5D[iTop]->SetMarkerColor(2+iTop);  //+5
    //hYW_5D[iTop]->SetMaximum(500000);
    /*if (sim) hYW_TH[iTop]->SetMarkerColor(kFullStar);  
    if (sim) hYW_TH[iTop]->SetMarkerColor(kBlack);*/
    if (sim) hYW_TH[iTop]->SetFillColor(kRed);  
    if (sim) hYW_TH[iTop]->SetFillStyle(3001);
    //Normalize yields to LUM*vgflux*binw_w*binw_q2
    hYWnorm_Dir[iTop] = normalizeYield(hYW_Dir[iTop]);
    hYWnorm_Dir[iTop]->SetMaximum(20);
    hYWnorm_5D[iTop]  = normalizeYield(hYW_5D[iTop]);
    hYWnorm_5D[iTop]->SetMaximum(20);

   if (iTop==0){
     c_5D->cd();
     l_5D->SetHeader( TString::Format("%s - 5D Method", XSECTITLE.Data()) );
     l_5D->AddEntry( hYWnorm_5D[iTop], TString::Format("%s", _topNames[iTop].Data()) );
     hYWnorm_5D[iTop]->SetMinimum(0);
     ploty?hYW_5D[iTop]->Draw("p"):hYWnorm_5D[iTop]->Draw("p");
     if (sim)
     {
      hYW_TH[iTop]->Draw("sames");
      l_5D->AddEntry( hYW_TH[iTop], TString::Format("Thrown") );
     } 

     c_Dir->cd();
     l_Dir->SetHeader( TString::Format("%s - Direct Method", XSECTITLE.Data()) );
     l_Dir->AddEntry( hYWnorm_Dir[iTop], TString::Format("%s", _topNames[iTop].Data()) );
     hYWnorm_Dir[iTop]->SetMinimum(0);
     ploty?hYW_Dir[iTop]->Draw("p"):hYWnorm_Dir[iTop]->Draw("p");
     if (sim)
     {
      hYW_TH[iTop]->Draw("bar sames");
      l_Dir->AddEntry( hYW_TH[iTop], TString::Format("Thrown") );
     }    
   }else{
     c_5D->cd();
     l_5D->AddEntry( hYWnorm_5D[iTop], TString::Format("%s", _topNames[iTop].Data()) );
     ploty?hYW_5D[iTop]->Draw("p sames"):hYWnorm_5D[iTop]->Draw("p sames");
     if (sim)
     {
      hYW_TH[iTop]->Draw("bar sames");
     }

     c_Dir->cd();
     l_Dir->AddEntry( hYWnorm_Dir[iTop], TString::Format("%s", _topNames[iTop].Data()) );
     ploty?hYW_Dir[iTop]->Draw("p sames"):hYWnorm_Dir[iTop]->Draw("p sames");
     if (sim)
     {
      hYW_TH[iTop]->Draw("bar sames");
     }
   }
   c_5D->cd();
   l_5D->Draw("same");
   c_Dir->cd();
   l_Dir->Draw("same"); 
  }
  //new - comp 5D & Dir for Top2 & 5
  if (comp){
    TCanvas* c_comp = new TCanvas(TString::Format("5D_Dir_Cpmp-%s", xsectype.Data()), TString::Format("5D & Dir Comp %s", xsectype.Data()));
    TLegend* l_comp = new TLegend(0.1,0.7,0.5,0.9);
    for (int iTop=0;iTop<5;iTop++){
      if (iTop!=1 && iTop!=4) continue;
      hYW_5D[iTop]->SetMarkerStyle(1);
      hYW_5D[iTop]->SetFillStyle(3001+iTop);
      hYW_5D[iTop]->SetFillColor(hYW_5D[iTop]->GetMarkerColor());
      hYW_5D[iTop]->SetLineColor(hYW_5D[iTop]->GetMarkerColor());
      l_comp->AddEntry(hYW_5D[iTop], TString::Format("5D Method-%s", _topNames[iTop].Data()));
      l_comp->AddEntry(hYW_Dir[iTop], TString::Format("Direct Method-%s", _topNames[iTop].Data()));
      if (iTop==1){
        hYW_5D[iTop]->Draw();
        hYW_Dir[iTop]->Draw("sames");
      }else{
        hYW_5D[iTop]->Draw("sames");
        hYW_Dir[iTop]->Draw("sames");
      }
    }
    l_comp->Draw("same");     
  }
}
Example #2
0
Int_t EventCount(TString inputlist, TString outfile, Int_t nev=-1)
{  

  HLoop* loop = new HLoop   (kTRUE    );  // kTRUE : create Hades  (needed to work with standard eventstructure)
         loop ->addMultFiles(inputlist);

//-----Inicialize-classes-we-need-to-use-----------------
  PidParticle p;
  dEdx        d;
  HMultCorr   cCorr;
//-------------------------------------------------------

//--------------------------------------------------------------------------------------------------------
#include "/u/parfenov/anaflow/EventCountVar.h"     //include all constants and variables we need          
#include "/u/parfenov/anaflow/outsigma.C"          //Declaration of the 3-sigma cuts for our pt & rapidity
TH2F*  hProtPtVsY_Eff;
TFile* foutfile       = new TFile(outfile.Data(), "recreate"); 
TFile* FileProtEff    = new TFile("EffCorrForProtPtVsY_WithWideBetaPcuts_ShieldGosia.root", "read");
       hProtPtVsY_Eff = (TH2F*) FileProtEff->Get("hProtPtVsY_EffSm");
       foutfile->cd();

#include "/u/parfenov/anaflow/EventCountHisto.h"   //include all histograms we need                       

FFlow pfy0pt[NC][NRAPI][NPTRN]; //--flow--9-bins-Yo--12-bins-in-Pt-in-3-centrality-sets--
  for (Int_t i=0; i<NC;i++){
   for(Int_t j=0; j<NRAPI; j++){
     for(Int_t k=0; k<NPTRN; k++){
       //-proton------------------------------------------
       pfy0pt[i][j][k].THDeclare("pCent",i,"Yo",j,"Pt",k);
     }
   }
  }
//--------------------------------------------------------------------------------------------------------

  if(!loop->setInput("-*,+HParticleCand,+HParticleEvtInfo,+HStart2Hit,+HStart2Cal,+HWallHit,+HRpcCluster,+HTofHit,+HWallEventPlane")) { exit(1); }
  loop->printCategories();
  
  TIterator* iterWallHit = 0;
  if (loop->getCategory("HWallHit")  ) iterWallHit   = loop->getCategory("HWallHit")->MakeIterator();
  
  HParticleEvtInfo* evtinfo;
  
  HParticleCand* pParticleCand; HCategory* candCat = (HCategory*)HCategoryManager::getCategory(catParticleCand); if(!candCat){exit(1);}
  HWallHit*      pWallHit;      HCategory* wallCat = (HCategory*)HCategoryManager::getCategory(catWallHit);      if(!wallCat){exit(1);}

  HEnergyLossCorrPar *momCorPar = new HEnergyLossCorrPar();
  momCorPar->setDefaultPar("apr12");
      
  /////////////////////////////////////////////////////////
  //-----Loop-over-events----------------------------------
  /////////////////////////////////////////////////////////
  
  loop->addMultFiles(inputlist);

  Int_t events = loop->getEntries();
  if(nev < events && nev >= 0 ) events = nev;
  
  for (Int_t i=1; i<events;i++){
    
    if (loop->nextEvent(i)<=0){
      cout << "End recieved with IF exit" << endl;
      break;
    }
    if (i%1000 == 0){
      cout << "    event " << i << endl;
    }
    
    if( loop->isNewFile(currFName) ){ 
        currFName = currFName( currFName.Last('/')+1,currFName.Length()-currFName.Last('/')-1 );
        currBeName = currFName(0, 13); //-simply-the-file-name-w/o-EBchunk--
        currFDay = currFName( 4, 3 ); //-we-cut-out-day-number-position-starting-from-4th-digit-with-length-of-3digits--
        DAY_NUM = currFDay.Atoi();
        currTime = currFName( 7, 2 ); //-we-cut-out-day-hour--position-starting-from-4th-digit-with-length-of-3digits--
        HR=currTime.Atoi();
        currTime = currFName( 9, 2 ); //-we-cut-out-day-minute-position-starting-from-4th-digit-with-length-of-3digits--
        MN=currTime.Atoi();
        currTime = currFName(11, 2 ); //-we-cut-out-day-second-position-starting-from-4th-digit-with-length-of-3digits--
        SC=currTime.Atoi();
        AbsMinute = MN + HR*60 + DAY_NUM*24*60;

        #include "/u/parfenov/anaflow/anaKaons_params_gen7_Auto_RC_RW_updated_gen108RminEqZero_11MultRecent.cc" //-for recentering---

        //--Now-we-read-multiplicity-parameters-for-this-beXXXXXXXXXX-file--------------------//
        mulVal = cCorr.getLineValuesAsVectFromCalibFile( currBeName );
        cout<<"mulVal "<< mulVal[0] <<" "<< mulVal[1] <<" "<< mulVal[2] <<" "<< mulVal[3] <<endl;
        fAverageMTS[0]=mulVal[4];  //multiplicity in tracking sector 1
        fAverageMTS[1]=mulVal[5];  //multiplicity in tracking sector 2
        fAverageMTS[2]=mulVal[6];  //...
        fAverageMTS[3]=mulVal[7];
        fAverageMTS[4]=mulVal[8];
        fAverageMTS[5]=mulVal[9];  //multiplicity in tracking sector 6
        printf("fAverageMTS[0,1,2,3,4,5]=[%6.3f,%6.3f,%6.3f,%6.3f,%6.3f,%6.3f,]\n", fAverageMTS[0], fAverageMTS[1], fAverageMTS[2], fAverageMTS[3], fAverageMTS[4], fAverageMTS[5]);
        
        //fTrkMultDay108
        if(mulVal[2]>0.0){
          //-if-correction-is-found-or-if-it-was-not-zero-defined-(in-case-of-not-working-MDCs)---
          fTrkMultScaler = fTrkMultDay108/mulVal[2];
          printf("==>Correction multiplier nTrkMult for this file is: (%f/%f)=%f\n", fTrkMultDay108, mulVal[2], fTrkMultScaler );
        }else{
          //--if-correction-entry-is-not-found-(may-be-not-created-once)------------------
          //--or-if-say-MDCs-were-not-working-and-tracking-multiplicity-was-exectly-zero--
          //-we-keep-correction-as-it-was-in-previous-file-or-if-not-defined-hence-it-would-be-exactly-one=1-or-
          printf("==>Correction multiplier nTrkMult for this file is: (%f/%f)=%f (default or old correction is used)\n", fTrkMultDay108, mulVal[2], fTrkMultScaler);
        }
    }

    HTool::printProgress(i,events,1,"Analyze pairs :");

    evtinfo = HCategoryManager::getObject(evtinfo,catParticleEvtInfo,0);
    
      //-------Get-vertex-from-combined-fit-of-fitted-inner-segments------------
      HVertex            fPrimVertReco = gHades->getCurrentEvent()->getHeader()->getVertexReco();
      vertexX = fPrimVertReco.getX();
      vertexY = fPrimVertReco.getY();
      vertexZ = fPrimVertReco.getZ();
      
      hvertexXZ->Fill(vertexZ,vertexX);
      hvertexXY->Fill(vertexY,vertexX);
      hvertexX ->Fill(vertexX);
      hvertexY ->Fill(vertexY);
      hvertexZ ->Fill(vertexZ);
      
      //------Alexandr's-vertex-cuts---------
      
      tgtChi2 = (Float_t) fPrimVertReco.getChi2();

      hTargChi2->Fill(tgtChi2);


      if( tgtChi2<2.0 || tgtChi2>40.) continue; //-skip-events-with-badly-reconstructed-target-------
      if( vertexZ<-59.|| vertexZ>0. ) continue; //-skip-events-with-primary-vertex-outside-of-target-

      hTargX_EVT->Fill(vertexX);
      hTargY_EVT->Fill(vertexY);
      hTargZ_EVT->Fill(vertexZ);

      if( (vertexX-tgtXc)*(vertexX-tgtXc)+(vertexY-tgtYc)*(vertexY-tgtYc)>R2 ) continue; //-skip-events-with-primary-vertex-far-from-target---
      hCutSteps->Fill(5.5);

      hTargXYsel->Fill(vertexX,vertexY);
      hTargXZsel->Fill(vertexZ,vertexX);
      //---------end-of-Alexandr's-vertex-cut--------------
      
      //------HWall-iteration------------------------------
      if (iterWallHit){
    iterWallHit->Reset();
    HWallHit* pWallHit;
        
    while ( (pWallHit = (HWallHit*)iterWallHit->Next()) != 0 ){
         
         cellNum    = pWallHit->getCell();
             cellTime   = pWallHit->getTime();
             cellCharge = pWallHit->getCharge();
             cellPhi    = pWallHit->getPhi();
         
         hWallHitTIME->Fill(cellNum-0.1, cellTime  );
         hWallHitCHRG->Fill(cellNum-0.1, cellCharge);
         
         if (cellCharge > d.dEdxCut(cellNum)/10. && cellTime > 16. && cellTime < 44.){
           hWallHitTIMEcut->Fill(cellNum-0.1, cellTime  );
           hWallHitCHRGcut->Fill(cellNum-0.1, cellCharge);
         }//end-cut
         
    }//------end-HWall-iteration-----------------------
      }//endif

    if( evtinfo->getSumParticleCandMult()<2 ) continue;  //getSumParticleCandMult()>1
      if(!evtinfo->isGoodEvent(
                               Particle::kGoodVertexClust|
                               Particle::kGoodVertexCand|
                               Particle::kNoPileUpSTART|
                               Particle::kGoodSTART|      
                               Particle::kGoodTRIGGER|    
                               Particle::kNoVETO|         
                               Particle::kGoodSTARTVETO|  
                               Particle::kGoodSTARTMETA
                              )) continue ; // bitwise add flags as suggested by Manuel 
                              
      Mtof = evtinfo->getSumTofMult();
      Mrpc = evtinfo->getSumRpcMult();
      Mult = Mtof+Mrpc;
      
      hmultTofRpc->Fill(Mult);                                   // Fill( name , weight )
      
      
      //---------centrality-classes--------------------------------------------------------------------(begin)--------//
      //-Centrality-selection-for-further-if-selection-statements------------------------//
      Int_t   nTrkMult = getParticleTrkMult();
      Mtr   = nTrkMult;
      Float_t nTrkMultCorr = nTrkMult*fTrkMultScaler;
      MtrC  = nTrkMultCorr; //-after-correction-to-average-day108--

      if( nTrkMultCorr>33 && nTrkMultCorr<=49 ){ FOPI_blue=kTRUE; }else{ FOPI_blue=kFALSE; }        // Berusz's estimate
      if( nTrkMultCorr>49 && nTrkMultCorr<=82 ){ FOPI_gren=kTRUE; }else{ FOPI_gren=kFALSE; }        // based on Glauber model
      if( nTrkMultCorr>82                     ){ FOPI_redd=kTRUE; }else{ FOPI_redd=kFALSE; }        // (lucky me, seems very similar to my naive guess!)--Alexandr-(c)--

      if( FOPI_blue ){ hPhiAB_blue->Fill(fabs(phiAB), wPhiRPA); }
      if( FOPI_gren ){ hPhiAB_gren->Fill(fabs(phiAB), wPhiRPA); }
      if( FOPI_redd ){ hPhiAB_redd->Fill(fabs(phiAB), wPhiRPA); }

      multCand = evtinfo->getSumSelectedParticleCandMult();

      hmultSumSPCand->Fill(multCand);
     
     //--------------------------------------------//
     //--Event plane reconstruction loop-----------//
     //--------------------------------------------// 
      multWall=0;
      cellNum=0;
      cellTime=0.0;
      cellCharge=0.0;
      wallX=0.0,wallY=0.0,wallZ=0.0;
      wallXc=0.0, wallYc=0.0; //corrected-reCentered-
      XfwSmear=0.0, YfwSmear=0.0;
      vect.Set(0.,0.);
      vsum.Set(0.,0.);
      eX  .Set(1.,0.);
      dEdxCut=0.0;
      xyRadius=0.0;
      
      QLx=0.0, QLy=0.0, NL=0; 
      QMx=0.0, QMy=0.0, NM=0;
      QNx=0.0, QNy=0.0, NN=0;

      for(Int_t n=0; n<6; n++){
         Qx[ n]    =0.0; Qy[ n]   =0.0;
         QxRec[n]  =0.0; QyRec[n] =0.0;
         Qax[n]    =0.0; Qay[n]   =0.0;
         Qbx[n]    =0.0; Qby[n]   =0.0;
         phiEP[ n] = -1000.;
         phiEPr[n] = 0.;
      }

      phiA   = -1000;
      phiB   = -1000;
      cellsVect.Reset();
      
      //-weight-for-scalar-product-method-------------------
      wgh = 1.0;  //PCpt; //1.0; //-or-could-be-also-equal-to-Pt---

      nFWhits   = 0;
      nFWspect  = 0;
      nFWunderflow = 0;
      FWdEdxA=0.0;
      FWdEdxB=0.0;

      FWdEdxL=0.0;
      FWdEdxM=0.0;
      FWdEdxN=0.0;

      choiceA = 1; //
      choiceB = 1; // Preparing for A/B subevent method

      //-------------------------------------------iteration-WallHits----(begin)--------------------------------------------------//
      for(Int_t j=0; j<(wallCat->getEntries()); j++){
        pWallHit = HCategoryManager::getObject(pWallHit,wallCat,j);

         cellNum    = pWallHit->getCell();
         cellTime   = pWallHit->getTime();
         cellCharge = pWallHit->getCharge();

         cellChargeCtime = cellTime;
         hFW_TimeCell_0->Fill(cellTime  , cellNum);
         hFW_dEdxCell_0->Fill(cellCharge, cellNum);

         if(cellNum< 144                ){ dEdxCut=Z1_cut_s; }
         if(cellNum>=144 && cellNum<=207){ dEdxCut=Z1_cut_m; }
         if(cellNum> 207                ){ dEdxCut=Z1_cut_l; }

         if(cellTime>T1_cut && cellTime<T2_cut && cellCharge>dEdxCut){
           
           nFWspect++;

           hFW_TimeCell_1->Fill(cellTime  , cellNum);
           hFW_dEdxCell_1->Fill(cellCharge, cellNum);

           pWallHit->getXYZLab(wallX,wallY,wallZ);
           hFWxyCC->Fill(wallX,wallY); //cell centers
           
           for (Int_t im=1;im<12;im++){
            if( (Mtof+Mrpc)>=Mrang[im-1] && (Mtof+Mrpc)<Mrang[im]){ wallXc = wallX - X_shM[12-im]; wallYc = wallY - Y_shM[12-im]; }
           }

           //-here-we-fill-d2N/(dxdy)-inX-band--and--y-band--for-auto-recentering-
           //-this-makes-realistic-distribution-on-FW-face------------------------
           if (cellNum<=143)                 { cellSize = 40;  }
           if (cellNum>=144 && cellNum<=207) { cellSize = 80;  }
           if (cellNum>=210 && cellNum<=301) { cellSize = 160; }
           XfwSmear = wallXc + ( Random.Rndm(1) - 0.5 )*cellSize;
           YfwSmear = wallYc + ( Random.Rndm(1) - 0.5 )*cellSize;

           
           for (Int_t im=0;im<8;im++){
            //-X-beam-center-scan---
            if( (Mtof+Mrpc)>=  Mcent[im] && (Mtof+Mrpc)< Mcent[im+1] ){ hFWxyCCsmearXscanM[im]->Fill(XfwSmear,YfwSmear); }
            //-Y-beam-center-scan---
            if( (Mtof+Mrpc)>=  Mcent[im] && (Mtof+Mrpc)< Mcent[im+1] ){ hFWxyCCsmearYscanM[im]->Fill(XfwSmear,YfwSmear); }
           }


           //-this-cut-was-forgotten-for-Feb2014-HADES-CM-report--//
           //-I-reintroduce-it-14.03.2014----(c)-Sadovsky---------//
           if(  wallXc*wallXc + wallYc*wallYc >= R0_cut*R0_cut  /*50.*50.*/ ){
             hFW_TimeCell_2->Fill(cellTime  , cellNum);
             hFW_dEdxCell_2->Fill(cellCharge, cellNum);


             //-spectators-selected--
             multWall++;

             vect.Set(wallXc, wallYc);
             vect =  vect.Unit();
             vsum += vect;

             //-Qnx-method--for-n=1,2,3,4,5------
             VectPhi_i = TMath::ATan2(YfwSmear,XfwSmear); //-Phi-of-i_th-spectator-particle---
             for(Int_t n=1; n<6; n++){//-loop-over-harmonics-(n)--
               Qx[n] = Qx[n] + wgh*cos(double(n)*VectPhi_i);
               Qy[n] = Qy[n] + wgh*sin(double(n)*VectPhi_i);
             }

             cellsVect.SetCellVect(vect, cellCharge); //-note-[vect]-is-a-unit-vector-this-is-for-further-subevent-(A/B)-split--


             hFWxyCCsmear->Fill(XfwSmear+X_shift,YfwSmear+Y_shift); //cells smeared but not shifted
             hFWxySHsmear->Fill(XfwSmear        ,YfwSmear        ); //cells smeared and shifted as a whole

             //-center-of-gravity-study-as-a-course-of-centrality-----------------------------
             for (Int_t im=0;im<8;im++){
              if( (Mtof+Mrpc)>=Mcent[im] && (Mtof+Mrpc)<Mcent[im+1]){ hFWxyCCsmearM[im]->Fill(XfwSmear,YfwSmear); }
             }
             
           }//-endif-R0_cut--//
           
        }//end-if-cells-cut---
     }//end-for-HitWall-loop---

     VectphiEP =  vsum.DeltaPhi(eX)   *rad2deg;
     VectphiEPr=  vsum.DeltaPhi(eX); //radians
     hPhiEPvect->Fill(VectphiEP);

     //-now-we-go-over-spectators-and-make-calculations-for-A/B-subevents
      NA=0;
      NB=0;
      multFWcells = cellsVect.GetNumbOfCells();

      Float_t choice;
      vectA.Set(0.,0.);
      vectB.Set(0.,0.);
      vsumA.Set(0.,0.);
      vsumB.Set(0.,0.);

      for(Int_t ic=0; ic<multFWcells; ic++){
        choice = Random.Rndm(1);
        //-this-is-(A/B)-subevents-split--(begin)-(c)-Sadovsky-----------------------------
        //-I-can-be-proud-that-my-algorithm-has-more-flat-distribution--:)-(c)-Sadovsky----
        levelA = (multFWcells/2.-choiceA+1.)/Float_t(multFWcells);
        levelB = (multFWcells/2.-choiceB+1.)/Float_t(multFWcells);
        if(choice < levelA/(levelA+levelB)){
           vectA = cellsVect.GetCellVector(ic);
           vsumA += vectA;
           choiceA++;
           NA++;
           vsumA += vectA;
           choiceA++;
           NA++;
           VectPhi_i = vectA.DeltaPhi(eX); //-Phi-of-i_th-spectator-particle-from-subevent-A--
           
           for(Int_t n=1; n<6; n++){//-loop-over-harmonics-(n)--
              Qax[n] = Qax[n] + wgh*cos(double(n)*VectPhi_i);
              Qay[n] = Qay[n] + wgh*sin(double(n)*VectPhi_i);
           }

           FWdEdxA=FWdEdxA + cellsVect.GetCellCharge(ic); //-total-Eloss-from-all-spectators---
           
        }else{

           vectB = cellsVect.GetCellVector(ic);
           vsumB += vectB;
           choiceB++;
           NB++;
           vectB = cellsVect.GetCellVector(ic);
           vsumB += vectB;
           choiceB++;
           NB++;
           VectPhi_i = vectB.DeltaPhi(eX); //-Phi-of-i_th-spectator-particle-from-subevent-B--
           
           for(Int_t n=1; n<6; n++){//-loop-over-harmonics-(n)--
              Qbx[n] = Qbx[n] + wgh*cos(double(n)*VectPhi_i);
              Qby[n] = Qby[n] + wgh*sin(double(n)*VectPhi_i);
           }

           FWdEdxB=FWdEdxB + cellsVect.GetCellCharge(ic); //-total-Eloss-from-all-spectators---
        }//-HWallHit-second-loop-for-reaction-plane-resolution--( end )---//
        //-this-is-(A/B)-subevents-split--( end )------------------------------------------
      }//-endfor-multFWcells-loop--for-A/B-method--

      //-calculating-eventplane-angles---------------
      phiA   = vsumA.DeltaPhi(eX)       *rad2deg;
      phiB   = vsumB.DeltaPhi(eX)       *rad2deg;
      phiAB  = vsumA.DeltaPhi(vsumB)    *rad2deg;
      Mfw = NA+NB;

      if (Mfw > 1){
        for (Int_t n=1;n<6;n++){
            QxRec[n]     = Qx[n] - MeanQx[n];
            QyRec[n]     = Qy[n] - MeanQy[n];
            phiEP[n ]    =  TMath::ATan2(Qy[n],Qx[n])/n       *rad2deg;
            phiEPr[n]    =  TMath::ATan2(Qy[n],Qx[n])/n               ;//radians
            phiEPrec[n]  =  TMath::ATan2(QyRec[n],QxRec[n])/n *rad2deg;
            hPhiEP[n-1]  -> Fill(phiEP[n]);
            hPhiEPrec[n-1]->Fill(phiEPrec[n]);
            hQvX  [n-1]  -> Fill(Qx[n]);
            hQvY  [n-1]  -> Fill(Qy[n]);
            hQvXrec[n-1] -> Fill(QxRec[n]);
            hQvYrec[n-1] -> Fill(QyRec[n]);
        }
        h0PhiEPvect->Fill(VectphiEP);
      }

      if(Mfw>=0){
        h0PhiEP->Fill(VectphiEP);
        h0PhiA ->Fill(phiA);
        h0PhiB ->Fill(phiB);
        h0PhiAB->Fill(phiAB);
      }
      //-extended-version-introduced-at-09.07.15--which-corresponds-to-META-mult-equivalent-to-numTracking-Glauber--//
      if(NA>0 && NB>0){
        hRPA->Fill(VectphiEP);
        for(Int_t im=0;im<11;im++){
            if( (Mtof+Mrpc)>=Mrang[im] && (Mtof+Mrpc)<Mrang[im+1] ){ hRPAy[im] ->Fill(VectphiEP); wPhiRPA = 1./fRPAy[im] ->Eval(VectphiEP); hRPAyc[im] ->Fill(VectphiEP,wPhiRPA); }
        }
        hRPA6Ywc->Fill(VectphiEP,wPhiRPA);
      }

      //-here-we-make-a-control-plot-for-pileup-events--//
      hMfwMmeta->Fill(Mtof+Mrpc, Mfw );
      hMfw     ->Fill(           Mfw );
      hMmeta   ->Fill(Mtof+Mrpc      );
      hMtof    ->Fill(           Mtof);
      hMrpc    ->Fill(           Mrpc);
      
      //-------------------------------------------iteration-WallHits----( end )--------------------------------------------------//


      ////////////////////////////////////////////
      //----getting-ready-to-loop-over-tracks---//
      ////////////////////////////////////////////
                     size = candCat->getEntries();
      Bool_t pimFlag[size];    // pi-
      Bool_t pipFlag[size];    // pi+
      Bool_t proFlag[size];    // proton
      Bool_t kapFlag[size];    // K+ meson        
      
      //note-new-event----------------------------
      for (Int_t icent=0;icent<NC;icent++){
        for (Int_t irpi=0;irpi<NRAPI;irpi++){
            for (Int_t ipt=0;ipt<NPTRN;ipt++){
                pfy0pt[icent][irpi][ipt].NewEvt();
            }
        }
      }   
      
      /////////////////////////////////////////////////////
      //--------Now-lets-try-to-get-tracks-----------------
      /////////////////////////////////////////////////////
      for(Int_t j=0;j<size;j++){
    
    pimFlag[j] = kFALSE;
    pipFlag[j] = kFALSE;
    proFlag[j] = kFALSE;
    kapFlag[j] = kFALSE;
        
    hEntries->Fill(size);
    
    pParticleCand = HCategoryManager::getObject(pParticleCand,candCat,j);
    if(!pParticleCand->isFlagBit(Particle::kIsUsed)) continue;
    
    
    sys      = pParticleCand->getSystem();           // sys == 0 - Rpc, sys == 1 - Tof
    mom      = pParticleCand->getMomentum();         //-later-shall-use: getMomentumPID()---(c)-Alexandr
    charge   = pParticleCand->getCharge();
    metaQa   = pParticleCand->getMetaMatchQuality(); 
    beta     = pParticleCand->getBeta();
    theta    = pParticleCand->getTheta();
    phi      = pParticleCand->getPhi();
    chi2     = pParticleCand->getChi2();
    sec      = pParticleCand->getSector();           // sector is the sixth part of the detector
    chi2In   = pParticleCand->getInnerSegmentChi2(); // chi2 of inner segment
    chi2Out  = pParticleCand->getOuterSegmentChi2(); // chi2 of outer segment
    mass2    = pParticleCand->getMass2();            // mass2 = mom*mom*(1-beta*beta)/(beta*beta);
    mass     = pParticleCand->getMass();             // mass  = sqrt(mass2);
    mdcdEdx  = pParticleCand->getMdcdEdx();
    tofdEdx  = pParticleCand->getTofdEdx();
    metaDx   = pParticleCand->getRkMetaDx();         
    metaDy   = pParticleCand->getRkMetaDy();         
    
    PCr              = pParticleCand->getR();
        PCz              = pParticleCand->getZ();
    
    pz       = mom*cos(theta*hpi/90.)/1000;
    pt0      = mom*sin(theta*hpi/90.)/1000;
    px       = pt0*cos(phi*hpi/90.);
    py       = pt0*sin(phi*hpi/90.);
    
    rapid    = 0.5*TMath::Log((1+beta)/(1-beta));
    eta      =    -TMath::Log(tan(theta/2));
    
    betaL    = beta*cos(theta*hpi/90.);
    rapidity = 0.5*TMath::Log((1+betaL)/(1-betaL));
    Y0       = (rapidity - Ycm)/Ycm;
    dphi     = phi - VectphiEP;
    if (dphi>180.){dphi = dphi - 360.; }
    if (dphi<-180.){dphi = dphi + 360.; }

    hPhi->Fill(phi);
    
        // apply track QA cuts
        if (metaQa>2) continue;
    if (mass2 <0) continue;
    
    hRapidity->Fill(rapidity);
    
    hM2fromM->Fill(mass);
    
    hCharge->Fill(charge);
    
     //-Tetiana's-plots-----------
           hChi2       ->Fill(chi2);
           hChi2In     ->Fill(chi2In);
           hChi2Out    ->Fill(chi2Out);
           //Fill Theta vs Phi Plots
           hthetaPhiAll->Fill(phi,theta);
           //Fill Beta vs Momentum
           hbetaMomAll ->Fill(mom*charge,beta);
           hmommassAll ->Fill(charge*mass,mom);
       
       hsys    ->Fill(sys);
       hmom    ->Fill(mom);
       hmetaQa ->Fill(metaQa);
       hsec    ->Fill(sec);
       hmdcdEdx->Fill(mdcdEdx);
       htofdEdx->Fill(tofdEdx);
       hmetaDx ->Fill(metaDx);
       hmetaDy ->Fill(metaDy);
       hPCr    ->Fill(PCr);
       hPCz    ->Fill(PCz);
       
       hpx     ->Fill(px);
       hpy     ->Fill(py);
       hpz     ->Fill(pz);
       hpt     ->Fill(pt);
       
       hdEdxMAll->Fill(mass/1000,mdcdEdx);
       
       
       //------Now-make-PID-------begin-----------
       
       pimFlag[j] = p.fPID(9, mom,beta,charge);
       pipFlag[j] = p.fPID(8, mom,beta,charge);
       kapFlag[j] = p.fPID(11,mom,beta,charge);
       proFlag[j] = p.fPID(14,mom,beta,charge);
       
       //fill-particle-numeration-integral-----------------------------------------------------
                                      hmassAll->Fill(charge*mass2/1000000);
       if (pipFlag[j] == kTRUE && mdcdEdx < 5) {
         hPIDPip ->Fill(charge*mass2/1000000); 
         pParticleCand->calc4vectorProperties(HPhysicsConstants::mass( 8));
         vector = (*pParticleCand);
         pt     = vector.Pt();
         y      = vector.Rapidity();
         hyPIDPip->Fill(y);
         hRPIDPip->Fill(rapidity);
         npip++;
      } // pi+    selection (Pip);
       if (pimFlag[j] == kTRUE && mdcdEdx < 5) {
         hPIDPim ->Fill(charge*mass2/1000000);
         pParticleCand->calc4vectorProperties(HPhysicsConstants::mass( 9));
         vector = (*pParticleCand);
         pt     = vector.Pt();
         y      = vector.Rapidity();
         hyPIDPim->Fill(y);
         hRPIDPim->Fill(rapidity);
         npim++;
      } // pi-    selection (Pim);
       if (kapFlag[j] == kTRUE && mdcdEdx < 5) { 
         hPIDKap ->Fill(charge*mass2/1000000);
         pParticleCand->calc4vectorProperties(HPhysicsConstants::mass(11));
         vector = (*pParticleCand);
         pt     = vector.Pt();
         y      = vector.Rapidity();
         hyPIDKap->Fill(y);
         hRPIDKap->Fill(rapidity);
         nkap++;
      } // K+     selection (Kap);
       if (proFlag[j] == kTRUE && mdcdEdx < 5) { 
         hPIDPro ->Fill(charge*mass2/1000000);
         pParticleCand->calc4vectorProperties(HPhysicsConstants::mass(14));
         vector = (*pParticleCand);
         pt     = vector.Pt();
         y      = vector.Rapidity();
         hyPIDPro->Fill(y);
         hRPIDPro->Fill(rapidity);
         npro++;
      } // proton selection (Pro);
       //--------------------------------------------------------------------------------------
           
       for (Int_t ipt=0; ipt<npt-1;ipt++){
        
         if (pt0>binpt[ipt] && pt0<binpt[ipt+1]){
                                    hM2Y   [ipt]->Fill(charge*mass2/1000000,rapidity);
         if (pipFlag[j] == kTRUE) { hM2YPip[ipt]->Fill(charge*mass2/1000000,rapidity); }
         if (pimFlag[j] == kTRUE) { hM2YPim[ipt]->Fill(charge*mass2/1000000,rapidity); }
         if (kapFlag[j] == kTRUE) { hM2YKap[ipt]->Fill(charge*mass2/1000000,rapidity); }
         if (proFlag[j] == kTRUE) { hM2YPro[ipt]->Fill(charge*mass2/1000000,rapidity); }
         }
         
         for (Int_t irpdt=0; irpdt<nrpdt-1;irpdt++){
           if (pt0>binpt[ipt] && pt0<binpt[ipt+1] && rapidity>binrpdt[irpdt] && rapidity<binrpdt[irpdt+1]){
         if (                                                                                                       mdcdEdx < 5) { hM2   [ipt][irpdt]->Fill( charge*mass2/1000000);}
             
         if (pipFlag[j] == kTRUE && mass2/1e6<=mass2Pip+sPip[ipt][irpdt] && mass2/1e6>=mass2Pip-sPip[ipt][irpdt] && mdcdEdx < 5) { hM2Pip[ipt][irpdt]->Fill( charge*mass2/1000000);}
         if (pimFlag[j] == kTRUE && mass2/1e6<=mass2Pim+sPim[ipt][irpdt] && mass2/1e6>=mass2Pim-sPim[ipt][irpdt] && mdcdEdx < 5) { hM2Pim[ipt][irpdt]->Fill( charge*mass2/1000000);}
         if (kapFlag[j] == kTRUE && mass2/1e6<=mass2Kap+sKap[ipt][irpdt] && mass2/1e6>=mass2Kap-sKap[ipt][irpdt] && mdcdEdx < 5) { hM2Kap[ipt][irpdt]->Fill( charge*mass2/1000000);}
         if (proFlag[j] == kTRUE && mass2/1e6<=mass2Pro+sPro[ipt][irpdt] && mass2/1e6>=mass2Pro-sPro[ipt][irpdt] && mdcdEdx < 5) { hM2P  [ipt][irpdt]->Fill( charge*mass2/1000000);} 
         
         hdEdxMass[ipt][irpdt]->Fill(charge*mass/1000,mdcdEdx);
         
           }//endif
         }//irpdt
       }//ipt

        for (Int_t ipt=0; ipt<npt-1;ipt++){
        
         if (pt0>binpt[ipt] && pt0<binpt[ipt+1] && (rapidity-Ycm)>=-Ycm && (rapidity-Ycm)<=Ycm){
          v2            = cos(2*((phi-180-VectphiEP)*hpi/90.));
          v2sum [ipt]  += v2;
          ncount[ipt]++;
          hv2phi[ipt]->Fill((phi-180-VectphiEP),v2,wgh);

          hNphi [ipt]->Fill((phi-180-VectphiEP),wgh);
         }
        }
        
        if (mass>600 && mass<1250 && NA>0 && NB>0 && charge>0 && metaQa<5 && chi2<200. && chi2In>0.1 && chi2In<12. && chi2Out>0.1 && chi2Out<12. && sec>=0 && sec<=5 && mdcdEdx>fdEdxVsMomLowLimit(mom)){

            PCp     = pParticleCand->getCorrectedMomentumPID(14);
            PCpz      = PCp*cos(theta*hpi/90.);

            PCE     = sqrt(938.272*938.272 + PCp*PCp );
            PCY     = 0.5*(log((PCE+PCpz)/(PCE-PCpz))); //corrected rapidity for protons
            PCYn    = PCY/(2.*Ycm); //normalized to projectile rapidity Y/Yproj
            PCYo    = (PCY-Ycm)/Ycm; //normalized to projectile rapidity (Y(cm)/Yproj(cm))
            PCpt    = PCp*sin(theta*hpi/90.); //corrected pt

            //---get-track-efficiency-------//
            binX     =   hProtPtVsY_Eff->GetXaxis()->FindBin((Double_t) rapidity );  //-Pt:Y-correction--
            binY     =   hProtPtVsY_Eff->GetYaxis()->FindBin((Double_t) PCpt );  //-Pt:Y-correction--
            TrackEff =   hProtPtVsY_Eff->GetBinContent(binX,binY);
            //------------------------------//
            for (Int_t n=1; n<6; n++){
                hPhiEPc[n-1]->Fill(phiEP[n],wgh*TrackEff);
            }

            CENT=-1;
            if( FOPI_redd ){ CENT=0; }
            if( FOPI_gren ){ CENT=1; }
            if( FOPI_blue ){ CENT=2; }
            RAPI=-1;
            if( PCYo>-0.9 && PCYo<-0.7 ){ RAPI=0; }
            if( PCYo>-0.7 && PCYo<-0.5 ){ RAPI=1; }
            if( PCYo>-0.5 && PCYo<-0.3 ){ RAPI=2; }
            if( PCYo>-0.3 && PCYo<-0.1 ){ RAPI=3; }
            if( PCYo>-0.1 && PCYo< 0.1 ){ RAPI=4; }
            if( PCYo> 0.1 && PCYo< 0.3 ){ RAPI=5; }
            if( PCYo> 0.3 && PCYo< 0.5 ){ RAPI=6; }
            if( PCYo> 0.5 && PCYo< 0.7 ){ RAPI=7; }
            if( PCYo> 0.7 && PCYo< 0.9 ){ RAPI=8; }
            PTRN=-1;
            if( PCpt> 200 && PCpt< 300 ){ PTRN= 0; }
            if( PCpt> 300 && PCpt< 400 ){ PTRN= 1; }
            if( PCpt> 400 && PCpt< 500 ){ PTRN= 2; }
            if( PCpt> 500 && PCpt< 600 ){ PTRN= 3; }
            if( PCpt> 600 && PCpt< 700 ){ PTRN= 4; }
            if( PCpt> 700 && PCpt< 800 ){ PTRN= 5; }
            if( PCpt> 800 && PCpt< 900 ){ PTRN= 6; }
            if( PCpt> 900 && PCpt<1000 ){ PTRN= 7; }
            if( PCpt>1000 && PCpt<1100 ){ PTRN= 8; }
            if( PCpt>1100 && PCpt<1200 ){ PTRN= 9; }
            if( PCpt>1200 && PCpt<1300 ){ PTRN=10; }
            if( PCpt>1300 && PCpt<1400 ){ PTRN=11; }
            if( PCpt>1400 && PCpt<1500 ){ PTRN=12; }
            if( PCpt>1500 && PCpt<1600 ){ PTRN=13; }
            if( PCpt>1600 && PCpt<1700 ){ PTRN=14; }
            if( PCpt>1700 && PCpt<1800 ){ PTRN=15; }
            if( PCpt>1800 && PCpt<1900 ){ PTRN=16; }
            if( PCpt>1900 && PCpt<2000 ){ PTRN=17; }
            if( CENT>=0 && RAPI>=0 && PTRN>=0 ){
                   pfy0pt[CENT][RAPI][PTRN].Fill(dphi, fabs(phiAB), VectphiEP, wgh*TrackEff);
                 }
        }
        
       
       //------Now-make-PID----------end----------
       
      }//j-----Loop-over-entries-----

  }//i-----Loop-over-events----------

  for (Int_t i=0;i<npt-1;i++){
        v2x[i] = binpt[i] + 0.5*(binpt[i+1]-binpt[i]);
        v2w[i] = hv2phi[i]->GetMean(2);
        hv2   -> Fill(v2x[i],v2w[i]);
  }

  Float_t yPID [4] = {hyPIDPim->GetMean(), hyPIDPip->GetMean(), hyPIDKap->GetMean(), hyPIDPro->GetMean()};
  Float_t ybet [4] = {hRPIDPim->GetMean(), hRPIDPip->GetMean(), hRPIDKap->GetMean(), hRPIDPro->GetMean()};
  Float_t dyPID[4] = {hyPIDPim->GetRMS() , hyPIDPip->GetRMS() , hyPIDKap->GetRMS() , hyPIDPro->GetRMS() };
  Float_t dybet[4] = {hRPIDPim->GetRMS() , hRPIDPip->GetRMS() , hRPIDKap->GetRMS() , hRPIDPro->GetRMS() };
  Float_t dy   [4];
  Float_t MeanY = 0.0;
  for (Int_t i=0;i<4;i++){
    dy[i] = 0.5*sqrt(ybet[i]*ybet[i]*dyPID[i]*dyPID[i]+yPID[i]*yPID[i]*dybet[i]*dybet[i])/(ybet[i]*ybet[i]);
    MeanY+=yPID[i]/ybet[i];
  }
  MeanY = MeanY/4;
  
  for (Int_t i=0;i<4;i++){
    hyvsPID ->Fill(i+0.5,yPID[i]/ybet[i]);
    hnormPID->Fill(i+0.5,MeanY);
  }
  
  foutfile->Write();
  foutfile->Close();
  
  return 0;
  
}
Example #3
0
void plot(TChain *tree_data, TChain *tree_mc, const TString &varRD, const TString &varMC, const TString& hName, const TString& xtitle, const TString& ytitle, int nbin, float xlow, float xmax, TCut cutRD, TCut cutMC, TCut cutjet, string name, bool print){

  TCanvas* c = new TCanvas(Form("c_%s_%s",hName.Data(),name),Form("c_%s_%s",hName.Data(),name),1); 
  TLegend *l;

  if(hName.Contains("deposit") || hName.Contains("pT")){ 
    gPad->SetLogy();
    l = new TLegend(0.68,0.78,0.90,0.90);
  }else{
    l = new TLegend(0.18,0.67,0.42,0.82);
  }
  //gPad->SetGrid(1,1);
  
  TH1 *h_data = new TH1D(Form("h_data_%s_%s",hName.Data(),name),"h_data",nbin,xlow,xmax);
  TH1 *h_mc = new TH1D(Form("h_mc_%s_%s",hName.Data(),name),"h_mc",nbin,xlow,xmax);
  h_data->Sumw2();

  tree_mc->Draw(Form("%s>>h_mc_%s_%s",varMC.Data(),hName.Data(),name),cutMC,"");
  tree_data->Draw(Form("%s>>h_data_%s_%s",varRD.Data(),hName.Data(),name),cutRD && cutjet,"Esame");

  double num_data = tree_data->GetEntries();
  double num_mc = tree_mc->GetEntries();
  double scale = num_data/num_mc;

  double pivotal_mc = 0;
  double pivotal_data = 0;
  TH1 *h_mc_eta= new TH1F("h_mc_eta","h_mc_eta",60,-3,3);
  TH1 *h_data_eta= new TH1F("h_data_eta","h_data_eta",60,-3,3);
  tree_mc->Project("h_mc_eta","muon_eta","muon_eta < 2.1 && muon_eta > -2.1");
  tree_data->Project("h_data_eta","random_eta",cutjet);
  pivotal_mc = h_mc_eta->GetEntries();
  pivotal_data = h_data_eta->GetEntries();
  h_mc_eta->Delete();
  h_data_eta->Delete();
  cout << "Data= " << num_data << endl;
  cout << "MC= " << num_mc << endl;
  cout << "CH pivotal data= " << pivotal_data << endl;
  cout << "CH pivotal mc= " << pivotal_mc << endl;

  TLatex *label= new TLatex;
  label->SetNDC();
  label->SetTextSize(0.05);
  label->DrawLatex(0.18,0.87,"CMS Preliminary 2010");

  h_data->SetMarkerStyle(kFullCircle);
  h_data->SetMarkerSize(0.8);//1
  h_data->SetMarkerStyle(8);
  h_data->SetStats(0);
  h_data->GetXaxis()->SetTitle(xtitle.Data());
  h_data->GetYaxis()->SetTitle(ytitle.Data());

  h_mc->SetLineColor(2);
  h_mc->SetLineWidth(2);
  h_mc->SetFillStyle(1001);
  h_mc->SetFillColor(kRed-8);
  h_mc->SetStats(0);
  h_mc->GetXaxis()->SetTitle(xtitle.Data());
  h_mc->GetYaxis()->SetTitle(ytitle.Data());

  h_data->Scale(1/pivotal_data/h_data->GetBinWidth(1));
  h_mc->Scale(1/pivotal_mc/h_mc->GetBinWidth(1));

  h_mc->SetMaximum(4); // 2.5

  //l->AddEntry(h_data,"random cone for MinBias","p");
  l->AddEntry(h_data,"random cone for W #rightarrow #mu#nu","p");
  l->AddEntry(h_mc,"muon for W #rightarrow #mu#nu","F");
  l->SetTextSize(0.04);
  l->SetFillColor(0);
  l->SetLineColor(0);
  l->Draw();
  
  if(print){ 
    c->Print(Form("c_%s_%s_Jun1.pdf",hName.Data(),name));
    c->Print(Form("c_%s_%s_Jun1.eps",hName.Data(),name));
    c->Print(Form("c_%s_%s_Jun1.png",hName.Data(),name));
  }
}
Example #4
0
void AnalysisSparse(Bool_t save_output = kFALSE)
{
  gStyle->SetGridColor(kGray);
  //  TString tmpstr(fname);
  //  if (tmpstr.Contains("data")) {
  //    Printf("!!! Real Data !!!");
  //    mc = kFALSE;
  //  }
  TString gtitle = Form("Monte Carlo, %s", graph_name.Data());
  grapht = graph_name.Data();
  Double_t grx[999], gry[999], gry2[999], gry3[999], gry4[999],
    gry_eff[999], gry_fix[999], grxE[999];
  Double_t gry22[999], gry22E[999], grx22E[999];
  Double_t gry_true[999], gry_true_eff[999], gry_true_effE[999];
  TH1::AddDirectory(kFALSE);
  TFile::SetCacheFileDir(gSystem->HomeDirectory());
  TFile *f = TFile::Open(fname.Data(), "CACHEREAD");
  if (!f) return;
  TList *l; f->GetObject(lname.Data(), l);
  if (!l) return;
  Int_t bf[999], bl[999];
  Int_t nn = FindExactRange(((THnSparse *)(l->FindObject(s1name.Data())))->
                            Projection(1), del_step, bf, bl);
  //  Int_t nn = FindRange5(bf, bl);
  Bool_t binhaluska = kFALSE;
  if (binAnders) {
    nn = 8;
    bf[0] = 6;bf[1] =  9;bf[2] = 11;bf[3] = 16;bf[4] = 21;bf[5] = 26;
    bl[0] = 8;bl[1] = 10;bl[2] = 15;bl[3] = 20;bl[4] = 25;bl[5] = 30;

    bf[6] = 31;bf[7] = 41;
    bl[6] = 40;bl[7] = 50;
  }
  Printf("number of intervals = %d =>", nn);

  Int_t count = 0;
  Double_t ptmean = 0, value = 0;
  Int_t fitStatus = -1;
  gStyle->SetOptStat(0);
  TCanvas *c = new TCanvas("c", "Signal & Background");
  c->Divide(5, 5); c->Modified(); c->Draw();
  TCanvas *c2 = (TCanvas *)c->DrawClone("c2");
  c2->SetTitle("Phi mesons (raw)"); c2->Modified(); c2->Draw();
  TCanvas *c3, *c4;
  if (mc) {
    c3 = (TCanvas *)c->DrawClone("c3");
    c3->SetTitle("Phi mesons (gen)"); c3->Modified(); c3->Draw();
    c4 = (TCanvas *)c->DrawClone("c4");
    c4->SetTitle("Phi mesons (true)"); c4->Modified(); c4->Draw();
  }

  for (Int_t i = 0; i < nn; i++) {
    c->cd(count + 1)->SetGrid();
    h1 = (TH1D *)PullHisto(l, s1name.Data(), bf[i], bl[i], ptmean);
    h1->SetLineColor(kRed);
    h1->GetXaxis()->SetTitle("inv. mass, GeV/c^2");
    h1->Draw("hist");

    h3_p = (TH1D *)PullHisto(l, s3name_p.Data(), bf[i], bl[i], ptmean);
    h3_m = (TH1D *)PullHisto(l, s3name_m.Data(), bf[i], bl[i], ptmean);
    // !!!!!!!!!!!!!!!!!!!!!!!!
    if (count==0) h3_p = h1;
    // !!!!!!!!!!!!!!!!!!!!!!!!
    else {
      h3_p->Add(h3_m);
      //      h3_p->Add((TH1D *)PullHisto(l, smix.Data(), bf[i], bl[i], ptmean));
      //      h3_p->Add((TH1D *)PullHisto(l, smixpp.Data(), bf[i], bl[i], ptmean));
      //      h3_p->Add((TH1D *)PullHisto(l, smixmm.Data(), bf[i], bl[i], ptmean));
      Norm(h1, h3_p, norm[0], norm[1]);
    }
    h3_p->SetLineColor(kBlue);
    h3_p->Draw("hist, same");

    if (mc) {
      c3->cd(count + 1)->SetGrid();
      Printf("%s", s1namegen.Data());
      hg = (TH1D *)PullHisto(l, s1namegen.Data(), bf[i], bl[i], ptmean);
      hg->SetLineColor(kMagenta);
      hg->GetXaxis()->SetTitle("inv. mass, GeV/c^2");
      hg->Draw("hist");
      c4->cd(count + 1)->SetGrid();
      ht = (TH1D *)PullHisto(l, s1nametrue.Data(), bf[i], bl[i], ptmean);
      ht->SetLineColor(kMagenta-5);
      ht->GetXaxis()->SetTitle("inv. mass, GeV/c^2");
      ht->Draw("hist");
    }
    c2->cd(count + 1)->SetGrid();
    TH1 *hh = (TH1 *)h1->Clone("hh");
    hh->SetLineColor(kRed+1);
    hh->Add(h3_p, -1);
    /// !!!!!!!!!!!!!!!!!!!!!!
    //////////    if ((ilist == 3) && (count < 2)) hh->Reset();
    // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    hh->Draw("hist");

    // !!!!!!!!!!!!!!!!!!
    ff->SetParameters(0.1, 1.02, 0.004, -25000., 0., 0., 0.);
    ff->SetLineColor(hh->GetLineColor());
    ff->SetLineWidth(1);
    //    ff->SetLineStyle(kDashed);
    // where fit
    Double_t fmin = 1.02-2*0.004;
    Double_t fmax = 1.02+2*0.004;
    //    Double_t fmin = 0.995;
    //    Double_t fmax = 1.185;
    // !!!!!!!!!!!!!!!!!!
    Bool_t hisfun = kFALSE; // kFALSE = integral from function
    Double_t   hisfun_k = 1.0/hh->GetBinWidth(10);
    // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    if (binhaluska)
      if (i > 9) hisfun_k = 0.5/hh->GetBinWidth(10);
    Printf("======= %f", hisfun_k);
    // !!!!!!!!!!!!!!!!!!
    // wehere integral (his or fun)
    Double_t fmini = 1.02-2*0.004;
    Double_t fmaxi = 1.02+2*0.004;
    hh->Fit(ff, "Q", "", fmin, fmax);
    hh->Fit(ff, "Q", "", fmin, fmax);
    fitStatus = hh->Fit(ff, "Q", "", fmin, fmax);
    TF1 *pp3 = new TF1("pp3", "[0]+x*[1]+x*x*[2]+x*x*x*[3]", fmin, fmax);
    pp3->SetParameters(ff->GetParameter(3), ff->GetParameter(4),
                       ff->GetParameter(5), ff->GetParameter(6));
    pp3->SetLineWidth(1);
    pp3->SetLineColor(h3_p->GetLineColor());
    pp3->Draw("same");
    // ff->SetRange(fmin, fmax);
    // ff->DrawCopy("same");

    value              = hh->Integral(hh->FindBin(fmini), hh->FindBin(fmaxi));
    if (!hisfun) value = ff->Integral(fmini, fmaxi)*hisfun_k -
                   pp3->Integral(fmini, fmaxi)*hisfun_k;
    if (value < 0) value = 0;

    if ((fitStatus != 0) || (ff->GetParameter(2) > 0.1)) {
      printf(" SKIP Data");
      value = 0;
    }
    grx[count] = ptmean;
    if (binhaluska) {
      if (count < 10) grxE[count] = 0.25; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      else            grxE[count] = 0.50; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    }
    else
      //      grxE[count] = (1.30-1.10)/2.0; // !!!!!!!!!!!!!!!!!!!!!!!!!!
      grxE[count] = 0.05;
    gry[count] = value;

    Double_t tmp1 = h1->Integral(h1->FindBin(fmini), h1->FindBin(fmaxi));
    Double_t tmp2 = h3_p->Integral(h3_p->FindBin(fmini), h3_p->FindBin(fmaxi));
    Double_t tmp_sg = tmp1 - tmp2;
    Double_t tmp_bg = tmp2;

    // if ((tmp_sg <= -tmp_bg) || (tmp_bg < 33.0)) {
    //   gry3[count] = 0.0;
    //   gry4[count] = 0.0;
    // }
    // else {
    gry3[count] = tmp_sg/tmp_bg;
    gry4[count] = tmp_sg/TMath::Sqrt(tmp_sg + tmp_bg);
    // }

    //    Printf("%4.2f, %10f, %10f, %10f", ptmean, tmp1, tmp2, gry3[count]);


    if (mc) {
      c3->cd(count + 1);
      // !!!!!!!!!!!!!!!!
      ff->SetParameters(1, 1.02, 0.004, 0., 0., 0., 0.);
      hg->Fit(ff, "Q", "", fmin, fmax);
      hg->Fit(ff, "Q", "", fmin, fmax);
      fitStatus = hg->Fit(ff, "Q", "", fmin, fmax);
      /*      TF1 *pp3 = new TF1("pp3", "[0]+x*[1]+x*x*[2]+x*x*x*[3]", fmin, fmax);
              pp3->SetParameters(ff->GetParameter(3), ff->GetParameter(4),
              ff->GetParameter(5), ff->GetParameter(6));
              pp3->SetLineWidth(1);
              pp3->SetLineColor(h3_p->GetLineColor());
              pp3->Draw("same");
      */

      value              = hg->Integral(hg->FindBin(fmini), hg->FindBin(fmaxi));
      if (!hisfun) value = ff->Integral(fmini, fmaxi)*hisfun_k;
      //!!!!!!!!!!!!!!!!!!!pp3->Integral(fmini, fmaxi)*hisfun_k;
      if (value <= 0) value = -1;

      if ((fitStatus != 0) || (ff->GetParameter(2) > 0.1)) {
        printf(" SKIP MC");
        value = -1;
      }
      gry2[count]    = value;
      Double_t superfactor = CalculateFactor(l, 0.1);
      if (useCF) {
        gry22E[i] = TMath::Sqrt(gry2[i])*superfactor;
        //        gry22E[i] = 0.0001;
        gry22[i]  = gry2[i]*superfactor;
        grx22E[i] = 0.05;
      }
      gry_eff[count] = gry[count]/gry2[count];

      c4->cd(count + 1);
      // !!!!!!!!!!!!!!!!
      ff->SetParameters(1, 1.02, 0.004, 0., 0., 0., 0.);
      ht->Fit(ff, "Q", "", fmin, fmax);
      ht->Fit(ff, "Q", "", fmin, fmax);
      fitStatus = ht->Fit(ff, "Q", "", fmin, fmax);
      /*      TF1 *pp3 = new TF1("pp3", "[0]+x*[1]+x*x*[2]+x*x*x*[3]", fmin, fmax);
              pp3->SetParameters(ff->GetParameter(3), ff->GetParameter(4),
              ff->GetParameter(5), ff->GetParameter(6));
              pp3->SetLineWidth(1);
              pp3->SetLineColor(h3_p->GetLineColor());
              pp3->Draw("same");
      */

      value              = ht->Integral(ht->FindBin(fmini), ht->FindBin(fmaxi));
      if (!hisfun) value = ff->Integral(fmini, fmaxi)*hisfun_k;
      //!!!!!!!!!!!!!!!!!!!pp3->Integral(fmini, fmaxi)*hisfun_k;
      if (value <= 0) value = -1;

      if ((fitStatus != 0) || (ff->GetParameter(2) > 0.1)) {
        printf(" SKIP true");
        value = -1;
      }
      gry_true[count]     = value;
      gry_true_eff[count] = gry_true[count]/gry2[count];
      // Propagation of uncertainty (A/B)
      Double_t AAA  = gry_true[count];
      Double_t AAAE = TMath::Sqrt(AAA);
      Double_t BBB  = gry2[count];
      Double_t BBBE = TMath::Sqrt(BBB);
      Double_t EEE  = TMath::Sqrt((AAAE/AAA)*(AAAE/AAA)+(BBBE/BBB)*(BBBE/BBB));
      EEE = EEE*gry_true_eff[count];
      gry_true_effE[count] = EEE;
    }

    Printf("=> %6.4f", ptmean);
    count++;
  }

  new TCanvas();
  TGraph *gr = new TGraph(count, grx, gry);
  gr->SetMarkerStyle(8);
  gr->SetMarkerColor(hh->GetLineColor());
  gr->GetXaxis()->SetTitle("p_{t}, GeV/c");
  gr->SetTitle(Form("raw phi, %s", gtitle.Data()));
  gr->Draw("AP");

  cc3 = new TCanvas();
  TGraph *gr3 = new TGraph(count, grx, gry3);
  gr3->SetMarkerStyle(22);
  gr3->SetMarkerColor(kBlue+1);
  gr3->GetXaxis()->SetTitle("p_{t}, GeV/c");
  gr3->SetTitle(Form("SIG / BKG, %s", gtitle.Data()));
  gr3->SetMinimum(0);
  gr3->Draw("AP");

  cc4 = new TCanvas();
  TGraph *gr4 = new TGraph(count, grx, gry4);
  gr4->SetMarkerStyle(23);
  gr4->SetMarkerColor(kBlue-1);
  gr4->GetXaxis()->SetTitle("p_{t}, GeV/c");
  gr4->SetTitle(Form("Significance, %s", gtitle.Data()));
  gr4->SetMinimum(0);
  gr4->Draw("AP");

  ccc = new TCanvas("ccc","ccc",0,0,900,300);
  ccc->Divide(2, 1, 0.001, 0.001);
  ccc->cd(1); gr3->Draw("AP");
  ccc->cd(2); gr4->Draw("AP");

  TString blabla = "mc";
  if (!mc) blabla = "data";
  // gr3->SaveAs(Form("SB_%s_%s.C", blabla.Data(), grapht.Data()));
  // gr4->SaveAs(Form("Sig_%s_%s.C", blabla.Data(), grapht.Data()));
  // ccc->SaveAs(Form("%s_%s_2.eps", blabla.Data(), grapht.Data()));
  // c->SaveAs(Form("%s_%s_0.eps", blabla.Data(), grapht.Data()));
  // c2->SaveAs(Form("%s_%s_1.eps", blabla.Data(), grapht.Data()));

  //  cc3->SaveAs(Form("%s_%s_2.eps", blabla.Data(), grapht.Data()));
  //  gr3->SaveAs(Form("sig_bck_%s_%s.C", blabla.Data(), grapht.Data()));

  if (mc) {
    new TCanvas();
    TGraph *gr2 = new TGraph(count, grx, gry2);
    gr2->SetMarkerStyle(8);
    gr2->SetMarkerColor(hg->GetLineColor());
    gr2->GetXaxis()->SetTitle("p_{t}, GeV/c");
    gr2->SetTitle(Form("gen phi, %s", gtitle.Data()));
    gr2->Draw("AP");

    new TCanvas();
    TGraphErrors *gr22 = new TGraphErrors(count, grx, gry22, grx22E, gry22E);
    gr22->SetMarkerStyle(8);
    gr22->SetMarkerColor(kCyan);
    gr22->GetXaxis()->SetTitle("p_{t}, GeV/c");
    gr22->SetTitle(Form("gen phi, %s", gtitle.Data()));
    gr22->Draw("AP");


    c = new TCanvas();
    c->SetGrid();
    TGraph *gr_e = new TGraph(count, grx, gry_eff);
    gr_e->SetMarkerStyle(22);
    gr_e->SetMarkerColor(kBlack);
    gr_e->GetXaxis()->SetTitle("p_{t}, GeV/c");
    gr_e->SetTitle(Form("efficiency (raw), %s", grapht.Data()));
    gr_e->Draw("AP");
    Printf("Save as '\033[1meffi_raw_%s\033[0m' file", grapht.Data());
    for (Int_t i = 0; i < gr_e->GetN(); i++)
      Printf("%f %f", gr_e->GetX()[i], gr_e->GetY()[i]);

    cvb = new TCanvas();
    cvb->cd();
    TGraph *gr_true = new TGraph(count, grx, gry_true);
    gr_true->SetMarkerStyle(8);
    gr_true->SetMarkerColor(ht->GetLineColor());
    gr_true->GetXaxis()->SetTitle("p_{t}, GeV/c");
    gr_true->SetTitle(Form("true phi, %s", gtitle.Data()));
    gr_true->Draw("AP");
    c = new TCanvas();
    c->cd();
    c->SetGrid();
    TGraphErrors *gr_true_eff = new TGraphErrors(count, grx, gry_true_eff,
                                                 grxE, gry_true_effE);
    gr_true_eff->SetMarkerStyle(20);
    //    gr_true_eff->SetMarkerSize(0.75);
    gr_true_eff->SetMarkerColor(kBlack);
    gr_true_eff->GetXaxis()->SetTitle("p_{t}, GeV/c");
    gr_true_eff->SetTitle(Form("efficiency (true), %s", grapht.Data()));
    gr_true_eff->Draw("AEP");
    m_gr->Add(gr_true_eff);
    Printf("Save as '\033[1meffi_true_%s\033[0m' file", grapht.Data());
    TString tout;
    Double_t oux, ouy, ouxe, ouye;
    for (Int_t i = 0; i < gr_true_eff->GetN(); i++) {
      oux = gr_true_eff->GetX()[i];
      ouy = gr_true_eff->GetY()[i];
      ouy = MinusCheck(ouy);
      ouxe = gr_true_eff->GetErrorX(i);
      ouye = gr_true_eff->GetErrorY(i);
      ouye = NanCheck(ouye);
      Printf("%f %f %f %f", gr_true_eff->GetX()[i], gr_true_eff->GetY()[i],
             gr_true_eff->GetErrorX(i), gr_true_eff->GetErrorY(i));
      if (!save_output) continue;
      gSystem->mkdir(dir_prefix.Data());
      tout = Form("%f %f %f %f", oux, ouy, ouxe, ouye);
      if (i == 0)
        tout = Form("Printf(\"%s\"); > %s/effi_%s", tout.Data(),
                    dir_prefix.Data(), grapht.Data());
      else
        tout = Form("Printf(\"%s\"); >> %s/effi_%s", tout.Data(),
                    dir_prefix.Data(), grapht.Data());
      //      Printf(":::::: %s", tout.Data());
      gROOT->ProcessLine(tout.Data());
    }
    // ------------------
    c = new TCanvas("cfinal", "mc_effi", 1200, 450);
    c->Divide(2, 1, 0.001, 0.001); c->Modified(); c->Draw();
    c->cd(1);
    gr_true->SetMinimum(0);
    gr_true->SetTitle(Form("phi (true & raw), %s", gtitle.Data()));
    gr_true->SetMarkerColor(kGreen+1);
    gr_true->Draw("AP");
    gr->SetMarkerColor(kRed+1);
    gr->Draw("P");
    c->cd(2)->SetGrid();
    gr_true_eff->SetMinimum(0);
    gr_true_eff->SetTitle(Form("efficiency, %s", grapht.Data()));
    gr_true_eff->SetMarkerColor(kGreen+1);
    gr_true_eff->Draw("AP");
    gr_e->SetMarkerColor(kRed+1);
    gr_e->Draw("P");
    //    c->SaveAs(Form("%s_%s.eps", blabla.Data(), grapht.Data()));
    return;
  }

  //  TGraph *geff = new TGraph(Form("effi_raw_%s", grapht.Data()));
  //  TGraph *geff = new TGraph(Form("effi_true_%s", grapht.Data()));
  //  TGraph *geff = new TGraph("effi_true_Phi2010_qualityonly");
  TGraph *geff = new TGraph("effi_true_PhiNsigma_qualityonly");
  if (geff->IsZombie()) return;
  geff->SetMarkerStyle(22);
  geff->SetMarkerColor(kBlack);
  geff->GetXaxis()->SetTitle("p_{t}, GeV/c");
  geff->SetTitle(Form("efficiency, %s", grapht.Data()));
  c = new TCanvas();
  c->SetGrid();
  geff->Draw("AP");
  Double_t tpcsigma = 9999.9;
  if (ilist == 1) tpcsigma = 1.0;
  if (ilist == 2) tpcsigma = 1.5;
  if (ilist == 3) tpcsigma = 2.0;
  if (ilist == 4) tpcsigma = 2.5;
  if (ilist == 5) tpcsigma = 3.0;
  Double_t sss = TMath::Erf(tpcsigma/TMath::Sqrt(2.0));
  if (noSigma) sss = 1.0;
  Printf("sigma = %10f", sss);

  // for (Int_t i = 0; i < count; i++)
  //   geff->GetY()[i] = (sss*sss)/(geff->GetY()[i]);
  // geff->SetMaximum(1.0);
  // geff->Draw("AP");

  for (Int_t i = 0; i < count; i++) {
    Double_t deno = geff->Eval(grx[i])*sss*sss;
    if (deno < 0.00001) deno = 1;
    gry_fix[i] = gry[i]/deno;
  }
  new TCanvas;
  TGraph *gr_fix = new TGraph(count, grx, gry_fix);
  gr_fix->SetMarkerStyle(21);
  gr_fix->SetMarkerColor(hh->GetLineColor());
  gr_fix->GetXaxis()->SetTitle("p_{t}, GeV/c");
  gr_fix->SetTitle(Form("corrected phi * #sigma^{2}, %s", gtitle.Data()));
  if (noSigma)
    gr_fix->SetTitle(Form("corrected phi (no #sigma), %s", gtitle.Data()));
  gr_fix->Draw("AP");

  //---------------------
  c = new TCanvas("cfinald", "data_correct", 1200, 450);
  c->Divide(2, 1, 0.001, 0.001); c->Modified(); c->Draw();
  c->cd(1);
  gr->SetMinimum(0);
  gr->SetMarkerColor(kBlack);
  gr->Draw("AP");
  c->cd(2);
  gr_fix->SetMinimum(0);
  gr_fix->SetMarkerColor(kGreen+3);
  gr_fix->Draw("AP");
  TString bla9 = Form("qualityonly_PID2_%s", grapht.Data());
  if (noSigma) bla9 = Form("%s_noSig.C", bla9.Data());
  else         bla9 = Form("%s.C", bla9.Data());
  //  gr_fix->SaveAs(bla9.Data());
  //  TPad *cp = new TPad("cpf", "", 0.45,0.45,0.99,0.92);
  TPad *cp = new TPad("cpf", "", 0.60,0.55,0.99,0.93);
  cp->SetLogy(); cp->Draw(); cp->cd();
  TGraph *cloneg = ((TGraph *)gr_fix->Clone());
  cloneg->SetTitle(); cloneg->SetMarkerSize(0.8);
  cloneg->Draw("AP");
  //  c->SaveAs(Form("%s_%s.eps", blabla.Data(), grapht.Data()));
  f->Close();
}
Example #5
0
void TestSPlot()
{
//This tutorial illustrates the use of class TSPlot and of the sPlots method
//
//It is an example of analysis of charmless B decays, performed for BABAR.
//One is dealing with a data sample in which two species are present:
//the first is termed signal and the second background. 
//A maximum Likelihood fit is performed to obtain the two yields N1 and N2
//The fit relies on two discriminating variables collectively denoted y, 
//which are chosen within three possible variables denoted Mes, dE and F.
//The variable which is not incorporated in y, is used as the control variable x.
//The distributions of discriminating variables and more details about the method 
//can be found in the TSPlot class description
//
// NOTE: This script requires a data file "TestSPlot_toyMC.dat".
//       This data file is not distributed in the standard ROOT binary tar file.
//       You can download it from ftp://root.cern.ch/root/TestSPlot_toyMC.dat
//
//Authors: Anna Kreshuk, Muriel Pivc

   TString dir = gSystem->UnixPathName(gInterpreter->GetCurrentMacroName());
   dir.ReplaceAll("TestSPlot.C","");
   dir.ReplaceAll("/./","/");
   TString dataFile = Form("%sTestSPlot_toyMC.dat",dir.Data());
   
   //Read the data and initialize a TSPlot object
   TTree *datatree = new TTree("datatree", "datatree");
   datatree->ReadFile(dataFile, 
                      "Mes/D:dE/D:F/D:MesSignal/D:MesBackground/D:dESignal/D:dEBackground/D:FSignal/D:FBackground/D",' ');

   TSPlot *splot = new TSPlot(0, 3, 5420, 2, datatree);

   //Set the selection for data tree
   //Note the order of the variables: 
   //first the control variables (not presented in this example),
   //then the 3 discriminating variables, then their probability distribution 
   //functions for the first species(signal) and then their pdfs for the 
   //second species(background)
   splot->SetTreeSelection(
      "Mes:dE:F:MesSignal:dESignal:FSignal:MesBackground:"
      "dEBackground:FBackground");

   //Set the initial estimates of the number of events in each species 
   //- used as initial parameter values for the Minuit likelihood fit
   Int_t ne[2];
   ne[0]=500; ne[1]=5000;
   splot->SetInitialNumbersOfSpecies(ne);

   //Compute the weights
   splot->MakeSPlot();

   //Fill the sPlots
   splot->FillSWeightsHists(25);

   //Now let's look at the sPlots
   //The first two histograms are sPlots for the Mes variable signal and 
   //background. dE and F were chosen as discriminating variables to determine 
   //N1 and N2, through a maximum Likelihood fit, and thus the sPlots for the 
   //control variable Mes, unknown to the fit, was contructed.
   //One can see that the sPlot for signal reproduces the PDF correctly, 
   //even when the latter vanishes.
   //
   //The lower two histograms are sPlots for the F variables signal and 
   //background. dE and Mes were chosen as discriminating variables to 
   //determine N1 and N2, through a maximum Likelihood fit, and thus the 
   //sPlots for the control variable F, unknown to the fit, was contructed.

   TCanvas *myc = new TCanvas("myc", 
   "sPlots of Mes and F signal and background", 800, 600);
   myc->SetFillColor(40);

   TPaveText *pt = new TPaveText(0.02,0.85,0.98,0.98);
   pt->SetFillColor(18);
   pt->SetTextFont(20);
   pt->SetTextColor(4);
   pt->AddText("sPlots of Mes and F signal and background,");
   pt->AddText("obtained by the tutorial TestSPlot.C on BABAR MC "
               "data (sPlot_toyMC.fit)");
   TText *t3=pt->AddText(
      "M. Pivk and F. R. Le Diberder, Nucl.Inst.Meth.A, physics/0402083");
   t3->SetTextColor(1);
   t3->SetTextFont(30);
   pt->Draw();

   TPad* pad1 = new TPad("pad1","Mes signal",0.02,0.43,0.48,0.83,33);
   TPad* pad2 = new TPad("pad2","Mes background",0.5,0.43,0.98,0.83,33);
   TPad* pad3 = new TPad("pad3", "F signal", 0.02, 0.02, 0.48, 0.41,33);
   TPad* pad4 = new TPad("pad4", "F background", 0.5, 0.02, 0.98, 0.41,33);
   pad1->Draw();
   pad2->Draw();
   pad3->Draw();
   pad4->Draw();

   pad1->cd();
   pad1->SetGrid();
   TH1D *sweight00 = splot->GetSWeightsHist(-1, 0, 0);
   sweight00->SetTitle("Mes signal");
   sweight00->SetStats(kFALSE);
   sweight00->Draw("e");
   sweight00->SetMarkerStyle(21);
   sweight00->SetMarkerSize(0.7);
   sweight00->SetMarkerColor(2);
   sweight00->SetLineColor(2);
   sweight00->GetXaxis()->SetLabelSize(0.05);
   sweight00->GetYaxis()->SetLabelSize(0.06);
   sweight00->GetXaxis()->SetLabelOffset(0.02);

   pad2->cd();
   pad2->SetGrid();
   TH1D *sweight10 = splot->GetSWeightsHist(-1, 1, 0);
   sweight10->SetTitle("Mes background");
   sweight10->SetStats(kFALSE);
   sweight10->Draw("e");
   sweight10->SetMarkerStyle(21);
   sweight10->SetMarkerSize(0.7);
   sweight10->SetMarkerColor(2);
   sweight10->SetLineColor(2);
   sweight10->GetXaxis()->SetLabelSize(0.05);
   sweight10->GetYaxis()->SetLabelSize(0.06);
   sweight10->GetXaxis()->SetLabelOffset(0.02);
 
   pad3->cd();
   pad3->SetGrid();
   TH1D *sweight02 = splot->GetSWeightsHist(-1, 0, 2);
   sweight02->SetTitle("F signal");
   sweight02->SetStats(kFALSE);
   sweight02->Draw("e");
   sweight02->SetMarkerStyle(21);
   sweight02->SetMarkerSize(0.7);
   sweight02->SetMarkerColor(2);
   sweight02->SetLineColor(2);
   sweight02->GetXaxis()->SetLabelSize(0.06);
   sweight02->GetYaxis()->SetLabelSize(0.06);
   sweight02->GetXaxis()->SetLabelOffset(0.01);

   pad4->cd();
   pad4->SetGrid();
   TH1D *sweight12 = splot->GetSWeightsHist(-1, 1, 2);
   sweight12->SetTitle("F background");
   sweight12->SetStats(kFALSE);
   sweight12->Draw("e");
   sweight12->SetMarkerStyle(21);
   sweight12->SetMarkerSize(0.7);
   sweight12->SetMarkerColor(2);
   sweight12->SetLineColor(2);
   sweight12->GetXaxis()->SetLabelSize(0.06);
   sweight12->GetYaxis()->SetLabelSize(0.06);
   sweight02->GetXaxis()->SetLabelOffset(0.01);
   myc->cd();
}
void Plot_AM_events_07Sep_Susy_2_auto() {
 TString cutNameBefore = Form("Data/");

 //                            cut_variable 
 TString cutNameAfter  = Form("_2_6_Tot_temp");

 gROOT->LoadMacro("PlotVHqqHggH.C+");
 gInterpreter->ExecuteMacro("LatinoStyle2.C");

 TCanvas* c1 = new TCanvas("events","events",500,600);
 TFile* f = new TFile("~/Cern/Code/VBF/qqHWW/AnalysisPackage_qqHWWlnulnu/out_test_Latinos_07Sep2012_2000_Run2012AB_8TeV_SUSY.root");


 PlotVHqqHggH* hs = new PlotVHqqHggH();

 hs->setLumi(5.063);
 hs->setLabel("event");
 hs->addLabel("    #sqrt{s} = 8 TeV");

 TString name;

 std::vector<int> vectColourBkg;        
 std::vector<double> vectSystBkg;       
 std::vector<std::string> vectNameBkg;  
 std::vector<TH1F*> vectTHBkg;          

 std::vector<int> vectColourSig;      
 std::vector<double> vectSystSig;       
 std::vector<std::string> vectNameSig;  
 std::vector<TH1F*> vectTHSig;          

 ///==== signal (begin) ====

 name = Form("%sT2tt-350-70%s",cutNameBefore.Data(),cutNameAfter.Data());
 vectTHSig.push_back ( (TH1F*) f->Get(name) );
 vectNameSig.push_back ("T2tt-stop350-lsp70");
 vectColourSig.push_back(6);

 name = Form("%sT2tt-500-70%s",cutNameBefore.Data(),cutNameAfter.Data());
 vectTHSig.push_back ( (TH1F*) f->Get(name) );
 vectNameSig.push_back ("T2tt-stop500-lsp70");
 vectColourSig.push_back(97);

 name = Form("%sT2tt-350-100%s",cutNameBefore.Data(),cutNameAfter.Data());
 vectTHSig.push_back ( (TH1F*) f->Get(name) );
 vectNameSig.push_back ("T2tt-stop350-lsp100");
 vectColourSig.push_back(70);

 name = Form("%sT2tt-500-100%s",cutNameBefore.Data(),cutNameAfter.Data());
 vectTHSig.push_back ( (TH1F*) f->Get(name) );
 vectNameSig.push_back ("T2tt-stop500-lsp100");
 vectColourSig.push_back(65);

 name = Form("%sT2tt-500-200%s",cutNameBefore.Data(),cutNameAfter.Data());
 vectTHSig.push_back ( (TH1F*) f->Get(name) );
 vectNameSig.push_back ("T2tt-stop500-lsp200");
 vectColourSig.push_back(5);

 name = Form("%sT2tt-200-0%s",cutNameBefore.Data(),cutNameAfter.Data());
 vectTHSig.push_back ( (TH1F*) f->Get(name) );
 vectNameSig.push_back ("T2tt-stop200-lsp0");
 vectColourSig.push_back(7);

 ///==== signal (end)  ====

 name = Form("%sDATA%s",cutNameBefore.Data(),cutNameAfter.Data());
 hs->setDataHist ((TH1F*)f->Get(name));



 hs->setBlindBinSx(0);
 hs->setBlindBinDx(0);

 hs->setCutSx(-999,">");
 hs->setCutDx(-999,"<");


 ///==== background (begin)  ====

 name = Form("%sH-125%s",cutNameBefore.Data(),cutNameAfter.Data());
 vectTHBkg.push_back ( (TH1F*) f->Get(name) );
 vectNameBkg.push_back ("H-125");
 vectColourBkg.push_back(633);
 vectSystBkg.push_back(0.00);


 name = Form("%sVV%s",cutNameBefore.Data(),cutNameAfter.Data());
 vectTHBkg.push_back ( (TH1F*) f->Get(name) );
 vectNameBkg.push_back ("WZ/ZZ");
 vectColourBkg.push_back(858);
 vectSystBkg.push_back(0.00);

 name = Form("%sWJets%s",cutNameBefore.Data(),cutNameAfter.Data());
 vectTHBkg.push_back ( (TH1F*) f->Get(name) );
 vectNameBkg.push_back ("W+jets");
 vectColourBkg.push_back(921);
 vectSystBkg.push_back(0.36);

 name = Form("%sTop%s",cutNameBefore.Data(),cutNameAfter.Data());
 vectTHBkg.push_back ( (TH1F*) f->Get(name) );
 vectNameBkg.push_back ("top");
 vectColourBkg.push_back(400);
 vectSystBkg.push_back(0.00);

 name = Form("%sZJets%s",cutNameBefore.Data(),cutNameAfter.Data());
 vectTHBkg.push_back ( (TH1F*) f->Get(name) );
 vectNameBkg.push_back ("DY+jets");
 vectColourBkg.push_back(418);
 vectSystBkg.push_back(0.00);
 name = Form("%sWW%s",cutNameBefore.Data(),cutNameAfter.Data());
 vectTHBkg.push_back ( (TH1F*) f->Get(name) );
 vectNameBkg.push_back ("WW");
 vectColourBkg.push_back(851);
 vectSystBkg.push_back(0.00);




 ///==== background (end)  ====


 hs->set_vectTHBkg     (vectTHBkg);      
 hs->set_vectNameBkg   (vectNameBkg);    
 hs->set_vectColourBkg (vectColourBkg);  
 hs->set_vectSystBkg   (vectSystBkg);    

 hs->set_vectTHSig     (vectTHSig);      
 hs->set_vectNameSig   (vectNameSig);    
 hs->set_vectColourSig (vectColourSig);  
 //  hs->set_vectSystSig   (vectSystSig);



 hs->set_addSignal (0); //---- stack signal = 1, no stack signal = 0  


 hs->prepare();


 ///==== draw ====



 hs->Draw(c1,1,true);

 c1->Print("07Sep_Susy_2/events.pdf");
 c1->Print("07Sep_Susy_2/events.png");

 c1->SetLogy();
 hs->Draw(c1,1,true);
 c1->Print("07Sep_Susy_2/events_logy.pdf");
 c1->Print("07Sep_Susy_2/events_logy.png");
}
Example #7
0
void Converts2x2Matrix(TCanvas* c, TCanvas* &c_output,Bool_t transpose){
    
    
    Double_t LimitLeft =0.15; //limit from left margin (15% of size)
    Double_t LimitBottom =0.10; //limit from bottom margin (15% of size)
    Double_t LimitRight =0.08; //limit from right margin (5% of size)
    Double_t LimitTop =0.05; //limit from top margin (5% of size)
    
    if(!c){
        cout << "Cannot read canvas!" << endl; return;
    }
    if(!c_output){
        cout << "output canvas not defined... quitting" << endl; return;
    }
    
    TString inputcanvasname = c->GetName();
    
    TPad * pd1 = (TPad*)c->FindObject(Form("%s_1",inputcanvasname.Data()));
    TPad * pd2 = (TPad*)c->FindObject(Form("%s_2",inputcanvasname.Data()));
    TPad * pd3 = (TPad*)c->FindObject(Form("%s_3",inputcanvasname.Data()));
    TPad * pd4 = (TPad*)c->FindObject(Form("%s_4",inputcanvasname.Data()));
    
    Double_t horizontalwidth=1.*(1-LimitLeft-LimitRight+LimitRight*LimitLeft)/(2-LimitLeft-LimitRight);
    Double_t verticalwidth=1.*(1-LimitBottom-LimitTop+LimitTop*LimitBottom)/(2-LimitBottom-LimitTop);
    
    //Double_t verticalwidth = (1-LimitBottom)*(1-LimitTop);
    
    Double_t x1 = 0;
    Double_t x2 = horizontalwidth/(1-LimitLeft);
    Double_t x3 = x2+horizontalwidth/(1-LimitRight);
    Double_t x4 = -1;
    
    Double_t y1 = 0;
    Double_t y2 = verticalwidth/(1-LimitBottom);
    Double_t y3 = y2+ verticalwidth/(1-LimitTop);
    Double_t y4 = -1;
    
    cout << "x =  " << x1 << "," << x2 <<" ,"<< x3 <<endl;
    cout << "y =  " << y1 << "," << y2 <<" ,"<< y3 <<endl;
    
  
    pd1->SetPad(x1,y3,x2,y2);
    pd2->SetPad(x2,y3,x3,y2);
    pd3->SetPad(x1,y2,x2,y1);
    pd4->SetPad(x2,y2,x3,y1);
    
    pd1->SetMargin(LimitLeft,0,0,LimitTop);
    pd2->SetMargin(0,LimitRight,0,LimitTop);
    pd3->SetMargin(LimitLeft,0,LimitBottom,0);
    pd4->SetMargin(0,LimitRight,LimitBottom,0);
    
    pd1->SetTicks();
    pd2->SetTicks();
    pd3->SetTicks();
    pd4->SetTicks();
    
    c_output->cd();
    pd1->Draw();
    pd2->Draw();
    pd3->Draw();
    pd4->Draw();
    
}
///////////////////////////////////////////////////////////////////////
//         TOOL BOX
//////////////////////////////////////////////////////////////////////
void makeMultiPanelCanvas(TCanvas*& canv,
                          const Int_t columns,
                          const Int_t rows,
                          const Float_t leftOffset,
                          const Float_t bottomOffset,
                          const Float_t leftMargin,
                          const Float_t bottomMargin,
                          const Float_t edge) {
   if (canv==0) {
      Error("makeMultiPanelCanvas","Got null canvas.");
      return;
   }
   canv->Clear();

   TPad* pad[columns][rows];
   Float_t Xlow[columns];
   Float_t Xup[columns];
   Float_t Ylow[rows];
   Float_t Yup[rows];
   Float_t PadWidth =
   (1.0-leftOffset)/((1.0/(1.0-leftMargin)) +
   (1.0/(1.0-edge))+(Float_t)columns-2.0);
   Float_t PadHeight =
   (1.0-bottomOffset)/((1.0/(1.0-bottomMargin)) +
   (1.0/(1.0-edge))+(Float_t)rows-2.0);
   Xlow[0] = leftOffset;
   Xup[0] = leftOffset + PadWidth/(1.0-leftMargin);
   Xup[columns-1] = 1;
   Xlow[columns-1] = 1.0-PadWidth/(1.0-edge);

   Yup[0] = 1;
   Ylow[0] = 1.0-PadHeight/(1.0-edge);
   Ylow[rows-1] = bottomOffset;
   Yup[rows-1] = bottomOffset + PadHeight/(1.0-bottomMargin);

   for(Int_t i=1;i<columns-1;i++) {
      Xlow[i] = Xup[0] + (i-1)*PadWidth;
      Xup[i] = Xup[0] + (i)*PadWidth;
   }
   Int_t ct = 0;
   for(Int_t i=rows-2;i>0;i--) {
      Ylow[i] = Yup[rows-1] + ct*PadHeight;
      Yup[i] = Yup[rows-1] + (ct+1)*PadHeight;
      ct++;
   }
   TString padName;
   for(Int_t i=0;i<columns;i++) {
      for(Int_t j=0;j<rows;j++) {
         canv->cd();
         padName = Form("p_%d_%d",i,j);
         pad[i][j] = new TPad(padName.Data(),padName.Data(),
            Xlow[i],Ylow[j],Xup[i],Yup[j]);
         if(i==0) pad[i][j]->SetLeftMargin(leftMargin);
         else pad[i][j]->SetLeftMargin(0);

         if(i==(columns-1)) pad[i][j]->SetRightMargin(edge);
         else pad[i][j]->SetRightMargin(0);

         if(j==0) pad[i][j]->SetTopMargin(edge);
         else pad[i][j]->SetTopMargin(0);

         if(j==(rows-1)) pad[i][j]->SetBottomMargin(bottomMargin);
         else pad[i][j]->SetBottomMargin(0);

         pad[i][j]->Draw();
         pad[i][j]->cd();
         pad[i][j]->SetNumber(columns*j+i+1);
      }
   }
}
void TriggerInputsForMuonEventCuts ( TString runListFilename, TString selectedInputs="", TString defaultStorage = "raw://" )
{
  AliCDBManager::Instance()->SetDefaultStorage(defaultStorage.Data());
  TObjArray inputsList;
  inputsList.SetOwner();
  
  TObjArray* selectedInputsList = selectedInputs.Tokenize(",");

  // Read input run list
  ifstream inFile(runListFilename.Data());
  TString srun = "";
  if ( inFile.is_open() ) {
    while ( ! inFile.eof() ) {
      srun.ReadLine(inFile,kFALSE);
      if ( ! srun.IsDigit() ) continue;
      
      // For each run, read trigger inputs from OCDB
      Int_t runNumber = srun.Atoi();
      AliCDBManager::Instance()->SetRun(runNumber);
      
      // Get trigger class configuration
      AliCDBEntry* entry = AliCDBManager::Instance()->Get("GRP/CTP/Config");
      if ( ! entry ) continue;
      
      THashList* runInputs = new THashList();
      runInputs->SetOwner();
      runInputs->SetUniqueID((UInt_t)runNumber);
      AliTriggerConfiguration* trigConf = (AliTriggerConfiguration*)entry->GetObject();
      const TObjArray& trigInputsArray = trigConf->GetInputs();
      AliTriggerInput* trigInput = 0x0;
      TIter next(&trigInputsArray);
      while ( ( trigInput = static_cast<AliTriggerInput*>(next()) ) ) {
        if ( selectedInputsList->GetEntriesFast() > 0 && ! selectedInputsList->FindObject(trigInput->GetName()) ) continue;
        Int_t inputId = (Int_t)TMath::Log2(trigInput->GetMask());
        TObjString* currInput = new TObjString(trigInput->GetName());
        currInput->SetUniqueID(inputId);
        runInputs->Add(currInput);
      }
      inputsList.Add(runInputs);
    }
    inFile.close();
  }
  delete selectedInputsList;
  
  // Loop on the trigger inputs
  // and group runs with an equal list of inputs
  Int_t nentries = inputsList.GetEntries();
  TArrayI checkMask(nentries);
  checkMask.Reset(1);
  for ( Int_t irun=0; irun<nentries; irun++ ) {
    if ( checkMask[irun] == 0 ) continue;
    THashList* currList = static_cast<THashList*>(inputsList.At(irun));
    TString runRange = Form("Run range: %u", currList->GetUniqueID());
    for ( Int_t jrun=irun+1; jrun<nentries; jrun++ ) {
      if ( checkMask[jrun] == 0 ) continue;
      THashList* checkList = static_cast<THashList*>(inputsList.At(jrun));
      Bool_t isDifferent = kFALSE;
      for ( Int_t itrig=0; itrig<currList->GetEntries(); itrig++ ) {
        TObjString* currInput = static_cast<TObjString*>(currList->At(itrig));
        TObject* checkInput = checkList->FindObject(currInput->GetName());
        if ( ! checkInput || checkInput->GetUniqueID() != currInput->GetUniqueID() ) {
          isDifferent = kTRUE;
          break;
        }
      } // loop on trigger inputs
      if ( isDifferent ) continue;
      checkMask[jrun] = 0;
      runRange += Form(",%u", checkList->GetUniqueID());
    } // loop on runs
    
    TString outString = "\nSetTrigInputsMap(\"";
    for ( Int_t itrig=0; itrig<currList->GetEntries(); itrig++ ) {
      TObjString* currInput = static_cast<TObjString*>(currList->At(itrig));
      outString += Form("%s:%u,",currInput->GetString().Data(), currInput->GetUniqueID());
    }
    outString.Append("\");\n");
    outString.ReplaceAll(",\"","\"");
    outString += runRange;
    printf("%s\n", outString.Data());
  } // loop on runs
}
Example #10
0
void run(Int_t runNumber)
{
    TStopwatch timer;
    timer.Start();
    
    TString strRunNumber = "run";
    strRunNumber += runNumber;
    const Int_t nev = -1;                                // number of events to read, -1 - untill CTRL+C
    const Int_t trigger = 1;                             // 1 - onspill, 2 - offspill. -1 - all
    TString inDir = "/Users/kresan/data/s438b/lmd/";     // directory with lmd files
    TString outDir = "/Users/kresan/data/s438b/data/";   // output directory

    TString filename = inDir + strRunNumber + "_*.lmd";
    TString outputFileName = outDir + strRunNumber + "_raw.root";                  // name of output file
    TString parFileName = outDir + "params_" + strRunNumber + "_raw.root";         // name of parameter file

    const Int_t updateRate = 150000;
    const Int_t minStats = 10000;                           // minimum number of entries for TCAL calibration
    const Int_t nModules = 800;                             // number of photomultipliers (for TCAL calibration)

    // Create source with unpackers ----------------------------------------------
    TString ntuple_options = "UNPACK:EVENTNO,UNPACK:TRIGGER,RAW";
    TString ucesb_dir = getenv("UCESB_DIR");
    TString ucesb_path = ucesb_dir + "/../upexps/s438b/s438b";

    EXT_STR_h101 ucesb_struct;
    R3BUcesbSource* source = new R3BUcesbSource(filename, ntuple_options,
                                                ucesb_path, &ucesb_struct, sizeof(ucesb_struct));
    source->SetMaxEvents(nev);
    source->AddReader(new R3BUnpackReader((EXT_STR_h101_unpack*)&ucesb_struct.unpack, offsetof(EXT_STR_h101, unpack)));
    source->AddReader(new R3BNeulandTacquilaReader((EXT_STR_h101_raw_nnp*)&ucesb_struct.nnp, offsetof(EXT_STR_h101, nnp)));
    source->AddReader(new R3BLosReader((EXT_STR_h101_LOS*)&ucesb_struct.los, offsetof(EXT_STR_h101, los)));
    // ---------------------------------------------------------------------------

    // Create online run ---------------------------------------------------------
    FairRunOnline* run = new FairRunOnline(source);
    run->SetRunId(runNumber);
    run->SetOutputFile(outputFileName.Data());
    //run->ActivateHttpServer(100000);
    // ---------------------------------------------------------------------------

    // Create ALADIN field map ---------------------------------------------------
    R3BAladinFieldMap* magField = new R3BAladinFieldMap("AladinMaps");
    Double_t fMeasCurrent = 2500.; // I_current [A]
    magField->SetCurrent(fMeasCurrent);
    magField->SetScale(1.);
    run->SetField(magField);
    // ---------------------------------------------------------------------------

    // TCAL ----------------------------------------------------------------------
    R3BNeulandMapped2CalPar* tcalFill = new R3BNeulandMapped2CalPar("TcalFill");
    tcalFill->SetUpdateRate(updateRate);
    tcalFill->SetMinStats(minStats);
    tcalFill->SetTrigger(trigger);
    tcalFill->SetNofModules(nModules);
    run->AddTask(tcalFill);

    R3BLosMapped2CalPar* losTcalFill = new R3BLosMapped2CalPar("LosTcalFill");
    losTcalFill->SetUpdateRate(updateRate);
    losTcalFill->SetMinStats(minStats);
    losTcalFill->SetNofModules(20, 4);
    run->AddTask(losTcalFill);
    // ---------------------------------------------------------------------------

    // Add analysis task ---------------------------------------------------------
    R3BNeulandMappedHist* ana = new R3BNeulandMappedHist("LandRawAna", 1);
    run->AddTask(ana);
    // ---------------------------------------------------------------------------

    // Initialize ----------------------------------------------------------------
    run->Init();
    //((TTree*)gFile->Get("cbmsim"))->SetMaxTreeSize(maxSize);
    FairLogger::GetLogger()->SetLogScreenLevel("INFO");
    // ---------------------------------------------------------------------------

    // Runtime data base ---------------------------------------------------------
    FairRuntimeDb* rtdb = run->GetRuntimeDb();
    R3BFieldPar* fieldPar = (R3BFieldPar*)rtdb->getContainer("R3BFieldPar");
    fieldPar->SetParameters(magField);
    fieldPar->setChanged();
    Bool_t kParameterMerged = kTRUE;
    FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged);
    parOut->open(parFileName);
    rtdb->setOutput(parOut);
    rtdb->print();
    // ---------------------------------------------------------------------------

    // Run -----------------------------------------------------------------------
    if(nev < 0)
    {
        run->Run(nev, 0);
    }
    else
    {
        run->Run(0, nev);
    }
    rtdb->saveOutput();
    delete run;
    // ---------------------------------------------------------------------------

    timer.Stop();
    Double_t rtime = timer.RealTime();
    Double_t ctime = timer.CpuTime();
    cout << endl << endl;
    cout << "Macro finished succesfully." << endl;
    cout << "Output file is " << outputFileName << endl;
    cout << "Parameter file is " << parFileName << endl;
    cout << "Real time " << rtime << " s, CPU time " << ctime << "s" << endl << endl;
}
Example #11
0
void computeAccGenWm(const TString conf,             // input file
                     const TString outputDir,        // output directory
		     const Int_t   charge            // 0 = inclusive, +1 = W+, -1 = W-
) {
  gBenchmark->Start("computeAccGenWm");

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

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

  const Int_t BOSON_ID  = 24;
  Int_t LEPTON_ID = 13;
  if (charge==1) LEPTON_ID=-13;

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

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

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

  // Create output directory
  gSystem->mkdir(outputDir,kTRUE);
  
  // Data structures to store info from TTrees
  baconhep::TGenEventInfo *gen = new baconhep::TGenEventInfo();
  TClonesArray *genPartArr     = new TClonesArray("baconhep::TGenParticle");
  
  TFile *infile=0;
  TTree *eventTree=0;

  // Variables to store acceptances and uncertainties (per input file)
  vector<Double_t> nEvtsv, nSelv, nSelBv, nSelEv;
  vector<Double_t> accv, accBv, accEv;
  vector<Double_t> accErrv, accErrBv, accErrEv;

  //
  // loop through files
  //
  for(UInt_t ifile=0; ifile<fnamev.size(); ifile++) {  

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

    nEvtsv.push_back(0);
    nSelv.push_back(0);
    nSelBv.push_back(0);
    nSelEv.push_back(0);
    
    //
    // loop over events
    //    
    for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {
    //for(UInt_t ientry=0; ientry<10000000; ientry++) {
      genBr->GetEntry(ientry);
      genPartArr->Clear(); partBr->GetEntry(ientry);

      TLorentzVector *vec=0, *lep1=0, *lep2=0;
      if (charge==-1 && toolbox::flavor(genPartArr, -BOSON_ID, vec, lep1, lep2)!=LEPTON_ID) {
        continue;
      }
      if (charge==1 && toolbox::flavor(genPartArr, BOSON_ID, vec, lep1, lep2)!=LEPTON_ID) {
        continue;
      }
      if (charge==0 && fabs(toolbox::flavor(genPartArr, BOSON_ID, vec, lep1, lep2))!=LEPTON_ID) {
        continue;
      }

      Double_t weight=gen->weight;
      nEvtsv[ifile]+=weight;
    
      Bool_t isBarrel=kTRUE;
      if (lep1) {
        if (fabs(lep1->Eta())>ETA_BARREL && fabs(lep1->Eta())<ETA_ENDCAP) continue;
	
        if (lep1->Pt() < PT_CUT) continue;
        if (fabs(lep1->Eta()) > ETA_CUT) continue;
        isBarrel = (fabs(lep1->Eta())<ETA_BARREL) ? kTRUE : kFALSE;
      }
      else if (lep2) {
        if (fabs(lep2->Eta())>ETA_BARREL && fabs(lep2->Eta())<ETA_ENDCAP) continue;

        if (lep2->Pt() < PT_CUT) continue;
        if (fabs(lep2->Eta()) > ETA_CUT) continue;
        isBarrel = (fabs(lep2->Eta())<ETA_BARREL) ? kTRUE : kFALSE;
      }
      else continue;

      nSelv[ifile]+=weight;
      if(isBarrel) nSelBv[ifile]+=weight;
      else         nSelEv[ifile]+=weight;
    }
    
    // compute acceptances
    accv.push_back(nSelv[ifile]/nEvtsv[ifile]);   accErrv.push_back(sqrt(accv[ifile]*(1.-accv[ifile])/nEvtsv[ifile]));
    accBv.push_back(nSelBv[ifile]/nEvtsv[ifile]); accErrBv.push_back(sqrt(accBv[ifile]*(1.-accBv[ifile])/nEvtsv[ifile]));
    accEv.push_back(nSelEv[ifile]/nEvtsv[ifile]); accErrEv.push_back(sqrt(accEv[ifile]*(1.-accEv[ifile])/nEvtsv[ifile]));
    
    delete infile;
    infile=0, eventTree=0;  
  }

  delete gen;
  
    
  //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================
   
  cout << "*" << endl;
  cout << "* SUMMARY" << endl;
  cout << "*--------------------------------------------------" << endl;
  if(charge== 0) cout << " W -> mu nu"  << endl;
  if(charge==-1) cout << " W- -> mu nu" << endl;
  if(charge== 1) cout << " W+ -> mu nu" << endl;
  cout << "  pT > " << PT_CUT << endl;
  cout << "  |eta| < " << ETA_CUT << endl;
  cout << "  Barrel definition: |eta| < " << ETA_BARREL << endl;
  cout << "  Endcap definition: |eta| > " << ETA_ENDCAP << endl;
  cout << endl;
  
  for(UInt_t ifile=0; ifile<fnamev.size(); ifile++) {
    cout << "   ================================================" << endl;
    cout << "    Label: " << labelv[ifile] << endl;
    cout << "     File: " << fnamev[ifile] << endl;
    cout << endl;
    cout << "    *** Acceptance ***" << endl;
    cout << "     barrel: " << setw(12) << nSelBv[ifile] << " / " << nEvtsv[ifile] << " = " << accBv[ifile] << " +/- " << accErrBv[ifile] << endl;
    cout << "     endcap: " << setw(12) << nSelEv[ifile] << " / " << nEvtsv[ifile] << " = " << accEv[ifile] << " +/- " << accErrEv[ifile] << endl;
    cout << "      total: " << setw(12) << nSelv[ifile]  << " / " << nEvtsv[ifile] << " = " << accv[ifile]  << " +/- " << accErrv[ifile] << endl;
    cout << endl;
  }
  
  char txtfname[100];
  sprintf(txtfname,"%s/gen.txt",outputDir.Data());
  ofstream txtfile;
  txtfile.open(txtfname);
  txtfile << "*" << endl;
  txtfile << "* SUMMARY" << endl;
  txtfile << "*--------------------------------------------------" << endl;
  if(charge== 0) txtfile << " W -> mu nu"  << endl;
  if(charge==-1) txtfile << " W- -> mu nu" << endl;
  if(charge== 1) txtfile << " W+ -> mu nu" << endl;
  txtfile << "  pT > " << PT_CUT << endl;
  txtfile << "  |eta| < " << ETA_CUT << endl;
  txtfile << "  Barrel definition: |eta| < " << ETA_BARREL << endl;
  txtfile << "  Endcap definition: |eta| > " << ETA_ENDCAP << endl;
  txtfile << endl;
  
  for(UInt_t ifile=0; ifile<fnamev.size(); ifile++) {
    txtfile << "   ================================================" << endl;
    txtfile << "    Label: " << labelv[ifile] << endl;
    txtfile << "     File: " << fnamev[ifile] << endl;
    txtfile << endl;
    txtfile << "    *** Acceptance ***" << endl;
    txtfile << "     barrel: " << setw(12) << nSelBv[ifile] << " / " << nEvtsv[ifile] << " = " << accBv[ifile] << " +/- " << accErrBv[ifile] << endl;
    txtfile << "     endcap: " << setw(12) << nSelEv[ifile] << " / " << nEvtsv[ifile] << " = " << accEv[ifile] << " +/- " << accErrEv[ifile] << endl;
    txtfile << "      total: " << setw(12) << nSelv[ifile]  << " / " << nEvtsv[ifile] << " = " << accv[ifile]  << " +/- " << accErrv[ifile] << endl;
    txtfile << endl;
  }
  txtfile.close();  
  
  cout << endl;
  cout << "  <> Output saved in " << outputDir << "/" << endl;    
  cout << endl;  
      
  gBenchmark->Show("computeAccGenWm"); 
}
void plotphi(int top, bool phi=kFALSE){
  if (setup("vm","","pol__")==kFALSE) return;
  gStyle->SetOptFit(1111); //pcev = 1111
  //gStyle->SetTitleW(1.5);

  int itop = top-1;
  TFile* fy = _fyexp[itop];

  int nq2wbins = fy->GetNkeys();
  TIter nextkey(fy->GetListOfKeys());
  TKey *key;
  int iq2wbin = 0;
  while (key = (TKey*)nextkey()) {
    TString Q2Wdirname = key->GetName();
    if(Q2Wdirname.EqualTo("hYW_Dir") || Q2Wdirname.EqualTo("hYW"))continue;
    cout << "Q2Wdirname = " << Q2Wdirname << endl;

    THStack* hs[10];
    TF1 *fphi = new TF1("fphi", "([0] + [1]*cos(x*TMath::DegToRad()) + [2]*cos(2*x*TMath::DegToRad()) + [3]*sin(x*TMath::DegToRad()))",0, 360);
    fphi->SetParameter(0,1);
    fphi->SetParameter(1,10);
    fphi->SetParameter(2,20);
    fphi->SetParameter(3,100);
    fphi->SetParName(0, "A");
    fphi->SetParName(1, "B");
    fphi->SetParName(2, "C");
    fphi->SetParName(3, "hPR");
    for (int i = 0; i < 10; i++)
    {
      TString hname_unp = TString::Format("%s/hPhi/Varset1/theta/hphi_%02d",Q2Wdirname.Data(),i+1);
      TString hname_pos = TString::Format("%s/hPhi_POS/Varset1/theta/hphi_%02d",Q2Wdirname.Data(),i+1);
      TString hname_neg = TString::Format("%s/hPhi_NEG/Varset1/theta/hphi_%02d",Q2Wdirname.Data(),i+1);
      cout << "hname_unp = " << hname_unp << endl;
      cout << "hname_pos = " << hname_pos << endl;
      cout << "hname_neg = " << hname_neg << endl;
      TH1D* hunp = (TH1D*)fy->Get(hname_unp);
      TH1D* hpos = (TH1D*)fy->Get(hname_pos);
      TH1D* hneg = (TH1D*)fy->Get(hname_neg);
      if (hunp==NULL || hpos==NULL || hneg==NULL) cout << "histogram not found" << endl;
      hunp->SetLineColor(kBlack);
      hpos->SetLineColor(kRed);
      hneg->SetLineColor(kBlue);
      hunp->Fit(fphi);
      hpos->Fit(fphi);
      hneg->Fit(fphi);

      //! Modify titles
      TObjArray *tarr;
      char t[100];

      TPaveText *ptunp = new TPaveText(0.0, 0.9, 1.0, 1, "NDC");
      TString tunp = hunp->GetTitle();
      tarr = tunp.Tokenize("|");
      sprintf(t, "%s:%s:%s", tarr->At(1)->GetName(), tarr->At(2)->GetName(), tarr->At(3)->GetName());
      ptunp->AddText(tarr->At(0)->GetName());
      ptunp->AddText(t);
      hunp->SetTitle("");

      TPaveText *ptpos = new TPaveText(0.0, 0.9, 1.0, 1, "NDC");
      TString tpos = hpos->GetTitle();
      tarr = tpos.Tokenize("|");
      sprintf(t, "%s:%s:%s", tarr->At(1)->GetName(), tarr->At(2)->GetName(), tarr->At(3)->GetName());
      ptpos->AddText(tarr->At(0)->GetName());
      ptpos->AddText(t);
      hpos->SetTitle("");

      TPaveText *ptneg = new TPaveText(0.0, 0.9, 1.0, 1, "NDC");
      TString tneg = hneg->GetTitle();
      tarr = tneg.Tokenize("|");
      sprintf(t, "%s:%s:%s", tarr->At(1)->GetName(), tarr->At(2)->GetName(), tarr->At(3)->GetName());
      ptneg->AddText(tarr->At(0)->GetName());
      ptneg->AddText(t);
      hneg->SetTitle("");

      //! Draw histograms
      TCanvas *c = new TCanvas(hpos->GetName(),hpos->GetName(),900, 600);
      c->Divide(3,1);
      c->cd(1);
      hunp->Draw();
      ptunp->Draw();
      c->cd(2);
      hpos->Draw();
      ptpos->Draw();
      c->cd(3);
      hneg->Draw();
      ptneg->Draw();
      TString dir = TString::Format("./polobs/top%d/%s/Varset1/theta", top, Q2Wdirname.Data());
      gSystem->mkdir(dir,1);
      c->SaveAs(TString::Format("%s/%s.png", dir.Data(), c->GetName()));
      c->Close();
      c->Delete();
    }
  }
}
void plotcompxsec(TString xsectype/*= "vm"*/, bool ploty/*=kFALSE*/,bool comp/*=kFALSE*/){
  TString methodB = TString::Format("Yield - Method B {%s}",_topNames[4].Data());
  TString methodA = TString::Format("Yield - Method A");

  TH1F* hYW_Dir[5];
  TH1F* hYW_5D[5];
  TH1F* hYWnorm_Dir[5];
  TH1F* hYWnorm_5D[5];
  TLegend* l_Dir = new TLegend(0.1,0.7,0.5,0.9);
  TLegend* l_5D  = new TLegend(0.1,0.7,0.5,0.9);
  TString hname_hYW_Dir  = TString::Format("hYW_Dir/Varset1/hYW_ACC_CORR");
  TString hname_hYW_5D   = TString::Format("hYW/Varset1/hYW");

  TCanvas* c_Dir = new TCanvas(TString::Format("Dir-%s:%s", xsectype.Data(), _q2w_bng.Data()), 
                               TString::Format("Dir-%s:%s", xsectype.Data(), _q2w_bng.Data()) );
  c_Dir->SetGrid(); 
  TCanvas* c_5D = new TCanvas(TString::Format("5D-%s:%s", xsectype.Data(), _q2w_bng.Data()), 
                              TString::Format("5D-%s:%s", xsectype.Data(), _q2w_bng.Data()) );
  c_5D->SetGrid();

  if (setup(xsectype,Q2W_BNG1)==kFALSE) return;

  //! For each Top: hYW_Dir,hYW_5D --> hYWnorm_Dir,hYWnorm_5D & then draw
  for (int iTop=0;iTop<5;iTop++){
    if (iTop!=1 && iTop!=4) continue;
    if (_fyexp[iTop]==NULL) continue;
    cout << "Top = " << iTop << endl;
    hYW_Dir[iTop] = (TH1F*)_fyexp[iTop]->Get(hname_hYW_Dir);
    hYW_5D[iTop]  = (TH1F*)_fyexp[iTop]->Get(hname_hYW_5D);
    if (hYW_Dir[iTop]==NULL || hYW_5D[iTop]==NULL) continue;
    hYW_Dir[iTop]->SetMarkerStyle(20+iTop);
    hYW_Dir[iTop]->SetMarkerColor(2+iTop);
    hYW_Dir[iTop]->SetMaximum(150000);
    hYW_5D[iTop]->SetMarkerStyle(20+iTop); //+5
    hYW_5D[iTop]->SetMarkerColor(2+iTop);  //+5
    hYW_5D[iTop]->SetMaximum(500000);
    //Normalize yields to LUM*vgflux*binw_w*binw_q2
    hYWnorm_Dir[iTop] = normalizeYield(hYW_Dir[iTop]);
    hYWnorm_Dir[iTop]->SetMaximum(10);
    hYWnorm_5D[iTop]  = normalizeYield(hYW_5D[iTop]);
    hYWnorm_5D[iTop]->SetMaximum(10);

   if (iTop==1){
     c_5D->cd();
     l_5D->SetHeader( TString::Format("%s - 5D", XSECTITLE.Data()) );
     l_5D->AddEntry( hYWnorm_5D[iTop], TString::Format("5D-%s", _topNames[iTop].Data()) );
     hYWnorm_5D[iTop]->SetMinimum(0);
     ploty?hYW_5D[iTop]->Draw("p"):hYWnorm_5D[iTop]->Draw("p");

     c_Dir->cd();
     l_Dir->SetHeader( TString::Format("%s - 5D", XSECTITLE.Data()) );
     l_Dir->AddEntry( hYWnorm_Dir[iTop], TString::Format("Direct-%s", _topNames[iTop].Data()) );
     hYWnorm_Dir[iTop]->SetMinimum(0);
     ploty?hYW_Dir[iTop]->Draw("p"):hYWnorm_Dir[iTop]->Draw("p");
   }else{
     c_5D->cd();
     l_5D->AddEntry( hYWnorm_5D[iTop], TString::Format("5D-%s", _topNames[iTop].Data()) );
     ploty?hYW_5D[iTop]->Draw("p sames"):hYWnorm_5D[iTop]->Draw("p sames");

     c_Dir->cd();
     l_Dir->AddEntry( hYWnorm_Dir[iTop], TString::Format("Direct-%s", _topNames[iTop].Data()) );
     ploty?hYW_Dir[iTop]->Draw("p sames"):hYWnorm_Dir[iTop]->Draw("p sames");
   }
   c_5D->cd();
   l_5D->Draw("same");
   c_Dir->cd();
   l_Dir->Draw("same"); 
  }

  if (setup(xsectype,Q2W_BNG2)==kFALSE) return;

  //! For each Top: hYW_Dir,hYW_5D --> hYWnorm_Dir,hYWnorm_5D & then draw
  for (int iTop=0;iTop<5;iTop++){
    if (iTop!=1 && iTop!=4) continue;
    if (_fyexp[iTop]==NULL) continue;
    cout << "Top = " << iTop << endl;
    hYW_Dir[iTop] = (TH1F*)_fyexp[iTop]->Get(hname_hYW_Dir);
    hYW_5D[iTop]  = (TH1F*)_fyexp[iTop]->Get(hname_hYW_5D);
    if (hYW_Dir[iTop]==NULL || hYW_5D[iTop]==NULL) continue;
    hYW_Dir[iTop]->SetMarkerStyle(20+iTop);
    hYW_Dir[iTop]->SetMarkerColor(2+iTop);
    hYW_Dir[iTop]->SetMaximum(150000);
    hYW_5D[iTop]->SetMarkerStyle(20+iTop); //+5
    hYW_5D[iTop]->SetMarkerColor(2+iTop);  //+5
    hYW_5D[iTop]->SetMaximum(500000);
    //Normalize yields to LUM*vgflux*binw_w*binw_q2
    hYWnorm_Dir[iTop] = normalizeYield(hYW_Dir[iTop]);
    hYWnorm_Dir[iTop]->SetMaximum(10);
    hYWnorm_5D[iTop]  = normalizeYield(hYW_5D[iTop]);
    hYWnorm_5D[iTop]->SetMaximum(10);

   /*if (iTop==0){
     c_5D->cd();
     l_5D->SetHeader( TString::Format("%s - 5D", XSECTITLE.Data()) );
     l_5D->AddEntry( hYWnorm_5D[iTop], TString::Format("5D-%s", _topNames[iTop].Data()) );
     hYWnorm_5D[iTop]->SetMinimum(0);
     ploty?hYW_5D[iTop]->Draw("p"):hYWnorm_5D[iTop]->Draw("p");

     c_Dir->cd();
     l_Dir->SetHeader( TString::Format("%s - 5D", XSECTITLE.Data()) );
     l_Dir->AddEntry( hYWnorm_Dir[iTop], TString::Format("Direct-%s", _topNames[iTop].Data()) );
     hYWnorm_Dir[iTop]->SetMinimum(0);
     ploty?hYW_Dir[iTop]->Draw("p"):hYWnorm_Dir[iTop]->Draw("p");
   }else{*/
     c_5D->cd();
     l_5D->AddEntry( hYWnorm_5D[iTop], TString::Format("5D-%s", _topNames[iTop].Data()) );
     ploty?hYW_5D[iTop]->Draw("p sames"):hYWnorm_5D[iTop]->Draw("p sames");

     c_Dir->cd();
     l_Dir->AddEntry( hYWnorm_Dir[iTop], TString::Format("Direct-%s", _topNames[iTop].Data()) );
     ploty?hYW_Dir[iTop]->Draw("p sames"):hYWnorm_Dir[iTop]->Draw("p sames");
   /*}*/
   /*c_5D->cd();
   l_5D->Draw("same");
   c_Dir->cd();
   l_Dir->Draw("same"); */
  }


  //new - comp 5D & Dir for Top2 & 5
  if (comp){
    TCanvas* c_comp = new TCanvas(TString::Format("5D_Dir_Cpmp-%s", xsectype.Data()), TString::Format("5D & Dir Comp %s", xsectype.Data()));
    TLegend* l_comp = new TLegend(0.1,0.7,0.5,0.9);
    for (int iTop=0;iTop<5;iTop++){
      if (iTop!=1 && iTop!=4) continue;
      hYW_5D[iTop]->SetMarkerStyle(1);
      hYW_5D[iTop]->SetFillStyle(3001+iTop);
      hYW_5D[iTop]->SetFillColor(hYW_5D[iTop]->GetMarkerColor());
      hYW_5D[iTop]->SetLineColor(hYW_5D[iTop]->GetMarkerColor());
      l_comp->AddEntry(hYW_5D[iTop], TString::Format("5D-%s", _topNames[iTop].Data()));
      l_comp->AddEntry(hYW_Dir[iTop], TString::Format("Dir-%s", _topNames[iTop].Data()));
      if (iTop==1){
        hYW_5D[iTop]->Draw();
        hYW_Dir[iTop]->Draw("sames");
      }else{
        hYW_5D[iTop]->Draw("sames");
        hYW_Dir[iTop]->Draw("sames");
      }
    }
    l_comp->Draw("same");     
  }
}
Bool_t setup(TString xsectype/*= "vm"*/, TString q2w_bng/*=""*/, bool pol/*=false*/){
  Bool_t ret = kTRUE;

  //gStyle->SetOptStat(0);

  TString pwd = gSystem->pwd();
  cout <<"pwd = "<<pwd << endl;

  TString path;
  if(q2w_bng=="")
  {
    if      (pwd.Contains("1.4-1.5__1.6-1.8"))  _q2w_bng = Q2W_BNG1;    
    else if (pwd.Contains("1.9-2.5__1.3-1.9"))  _q2w_bng = Q2W_BNG2;

    if      (pwd.Contains("experiment"))      _dtype = "exp";
    else if (pwd.Contains("simulation"))      _dtype = "sim";
    path=".";
  }else{
    _q2w_bng=q2w_bng;
    printf("q2wbng = %s\n", _q2w_bng.Data());
    if(_q2w_bng.Contains(Q2W_BNG1))
    {
      path="/data/trivedia/e1f/ana2pi/experiment/e1f.goldenruns.qskim_071513/Q2W__1.4-1.5__1.6-1.8";
    }else if (_q2w_bng.Contains(Q2W_BNG2)){
      path="/data/trivedia/e1f/ana2pi/experiment/e1f.goldenruns.qskim_071513/Q2W__1.9-2.5__1.3-1.9";
    }else 
    {
      printf("Could not determine path\n");
      return kFALSE; 
    }
    _dtype="exp";
  }

  if (pol) _dtype = "pol__exp";
  

  cout << "xsectype = " << xsectype << endl;
  if (xsectype=="at"){
    copy(AT_TOPNAMES,AT_TOPNAMES+5, _topNames);
    _fyexp[0] = TFile::Open(TString::Format("%s/1__%s__%s.root", path.Data(),_q2w_bng.Data(), _dtype.Data()));
    _fyexp[1] = TFile::Open(TString::Format("%s/2__%s__%s.root", path.Data(),_q2w_bng.Data(), _dtype.Data()));
    _fyexp[2] = TFile::Open(TString::Format("%s/3__%s__%s.root", path.Data(),_q2w_bng.Data(), _dtype.Data()));
    _fyexp[3] = TFile::Open(TString::Format("%s/4__%s__%s.root", path.Data(),_q2w_bng.Data(), _dtype.Data()));
    _fyexp[4] = TFile::Open(TString::Format("%s/1:2:3:4__%s__%s.root", path.Data(), _q2w_bng.Data(), _dtype.Data()));
    _fysim[0] = TFile::Open(TString::Format("%s/simdir/1__%s__%s.root", path.Data(),_q2w_bng.Data(), "sim"));
    _fysim[1] = TFile::Open(TString::Format("%s/simdir/2__%s__%s.root", path.Data(),_q2w_bng.Data(), "sim"));
    _fysim[2] = TFile::Open(TString::Format("%s/simdir/3__%s__%s.root", path.Data(),_q2w_bng.Data(), "sim"));
    _fysim[3] = TFile::Open(TString::Format("%s/simdir/4__%s__%s.root", path.Data(),_q2w_bng.Data(), "sim"));
    _fysim[4] = TFile::Open(TString::Format("%s/simdir/1:2:3:4__%s__%s.root", _q2w_bng.Data(), "sim"));
  }else if (xsectype=="vm"){
    copy(VM_TOPNAMES,VM_TOPNAMES+5, _topNames);
    _fyexp[0] = TFile::Open(TString::Format("%s/1__%s__%s.root", path.Data(),_q2w_bng.Data(), _dtype.Data()));
    _fyexp[1] = TFile::Open(TString::Format("%s/2:1__%s__%s.root", path.Data(),_q2w_bng.Data(), _dtype.Data()));
    _fyexp[2] = TFile::Open(TString::Format("%s/3:1__%s__%s.root", path.Data(),_q2w_bng.Data(), _dtype.Data()));
    _fyexp[3] = TFile::Open(TString::Format("%s/4:1__%s__%s.root", path.Data(),_q2w_bng.Data(), _dtype.Data()));
    _fyexp[4] = TFile::Open(TString::Format("%s/1:2:3:4__%s__%s.root", path.Data(),_q2w_bng.Data(), _dtype.Data()));
    _fysim[0] = TFile::Open(TString::Format("%s/simdir/1__%s__%s.root", path.Data(),_q2w_bng.Data(), "sim"));
    _fysim[1] = TFile::Open(TString::Format("%s/simdir/2:1__%s__%s.root", path.Data(),_q2w_bng.Data(), "sim"));
    _fysim[2] = TFile::Open(TString::Format("%s/simdir/3:1__%s__%s.root", path.Data(),_q2w_bng.Data(), "sim"));
    _fysim[3] = TFile::Open(TString::Format("%s/simdir/4:1__%s__%s.root", path.Data(),_q2w_bng.Data(), "sim"));
    _fysim[4] = TFile::Open(TString::Format("%s/simdir/1:2:3:4__%s__%s.root", path.Data(),_q2w_bng.Data(), "sim"));
  }else {
    printf("Could not determine xsectype\n");
    ret=kFALSE;
  }

  TString q2bng = _q2w_bng.Tokenize("__")->At(0)->GetName();
  _q2min = ((TString)q2bng.Tokenize("-")->At(1)->GetName()).Atof();
  _q2max = ((TString)q2bng.Tokenize("-")->At(2)->GetName()).Atof();
  _dq2 = _q2max - _q2min;
  
  return ret;
}
Example #15
0
Int_t SETUP(TList *inputList = NULL) {

  TString aliRootDir, aliPhysicsDir;

  if (gProof && !gProof->IsMaster()) {

    //
    // On client
    //

    gMessTag = "client";
    aliRootDir = gSystem->Getenv("ALICE_ROOT");  // NULL --> ""
    aliPhysicsDir = gSystem->Getenv("ALICE_PHYSICS");  // NULL --> ""

    if (aliRootDir.IsNull()) {
      // ALICE_ROOT is mandatory; ALICE_PHYSICS is optional
      ::Error(gMessTag.Data(), "ALICE_ROOT environment variable not defined on client");
      return -1;
    }

    if (aliPhysicsDir.EqualTo(aliRootDir)) {
      // AliPhysics does not exist if it points to the same directory of AliRoot
      aliPhysicsDir = "";
    }

    ::Info(gMessTag.Data(), "Enabling ALICE software on client");

  }
  else {

    //
    // On master/workers
    //

    gMessTag = gSystem->HostName();
    if (gProof && gProof->IsMaster()) {
      gMessTag.Append("(master)");
    }
    else {
      gMessTag.Append("(worker)");
    }

    // Here we have two working modes: AAF and VAF.
    //  - AAF mode: look for VO_ALICE@(AliRoot|AliPhysics)::<version>
    //  - VAF mode: any other PARfile name

    TString buf;
    buf = gSystem->BaseName(gSystem->pwd());
    TPMERegexp reAaf("^VO_ALICE@(AliRoot|AliPhysics)::(.*)$");

    if (reAaf.Match(buf) == 3) {

      // AliRoot enabled from a metaparfile whose name matches
      // VO_ALICE@AliRoot::<version>: set up ALICE_ROOT environment variable
      // accordingly from there.
      // Note: this is the AAF case.

      TString swName = reAaf[1].Data();
      TString swVer = reAaf[2].Data();

      // Get ALICE_ROOT and ALICE_PHYSICS from the env set by Modules
      buf.Form( ". /cvmfs/alice.cern.ch/etc/login.sh && "
        "eval `alienv printenv VO_ALICE@%s::%s` && "
        "echo \"$ALICE_ROOT\" ; "
        "echo \"$ALICE_PHYSICS\"", swName.Data(), swVer.Data() );
      buf = gSystem->GetFromPipe( buf.Data() );

      // Output on two lines
      TString tok;
      Ssiz_t from = 0;
      UInt_t count = 0;
      while ( buf.Tokenize(tok, from, "\n") ) {
        if (count == 0) {
          aliRootDir = tok;
        }
        else if (count == 1) {
          aliPhysicsDir = tok;
        }
        else {
          break;
        }
        count++;
      }

      // Set (or override) environment for AliRoot and AliPhysics.
      // LD_LIBRARY_PATH: current working directory always has precedence.
      // Note: supports both current $ALICE_ROOT/lib and legacy
      //       $ALICE_ROOT/lib/tgt_<arch> format.
      gSystem->Setenv("ALICE_ROOT", aliRootDir.Data());
      gSystem->SetDynamicPath(
        Form(".:%s/lib:%s/lib/tgt_%s:%s", aliRootDir.Data(), aliRootDir.Data(),
          gSystem->GetBuildArch(), gSystem->GetDynamicPath()) );

      ::Info(gMessTag.Data(),
        "Enabling %s %s on PROOF (AAF mode)...", swName.Data(), swVer.Data());

      if (!aliPhysicsDir.IsNull()) {
        gSystem->Setenv("ALICE_PHYSICS", aliPhysicsDir.Data());
        gSystem->SetDynamicPath(
          Form("%s/lib:%s", aliPhysicsDir.Data(), gSystem->GetDynamicPath()) );
      }

    }
    else {

      // AliRoot enabled from a single metaparfile. Assume that ALICE_ROOT and
      // ALICE_PHYSICS are already defined on master and each worker.
      // Note: this is the VAF case.

      aliRootDir = gSystem->Getenv("ALICE_ROOT");  // NULL --> ""
      aliPhysicsDir = gSystem->Getenv("ALICE_PHYSICS");  // NULL --> ""

      if (aliRootDir.IsNull()) {
        ::Error(gMessTag.Data(),
          "ALICE_ROOT environment variable not defined on PROOF node, and not"
          "loading from a PARfile containing AliRoot version in its name");
        return -1;
      }

      if (aliPhysicsDir.EqualTo(aliRootDir)) {
        // AliPhysics does not exist if it points to the same directory of AliRoot
        aliPhysicsDir = "";
      }

      ::Info(gMessTag.Data(),
        "Enabling ALICE software located on PROOF node (VAF mode)");
    }

  }

  //
  // Where are AliRoot and AliPhysics? Inform user
  //

  ::Info(gMessTag.Data(), ">> ALICE_ROOT=%s", aliRootDir.Data());
  ::Info(gMessTag.Data(), ">> ALICE_PHYSICS=%s", aliPhysicsDir.Data());

  //
  // Common operations on Client and PROOF Master/Workers
  //

  // Add standard AliRoot Core include and macro path
  gSystem->AddIncludePath( Form("-I\"%s/include\"", aliRootDir.Data()) );
  gROOT->SetMacroPath( Form("%s:%s/macros", gROOT->GetMacroPath(), aliRootDir.Data()) );

  // Same for AliPhysics
  if (!aliPhysicsDir.IsNull()) {
    gSystem->AddIncludePath( Form("-I\"%s/include\"", aliPhysicsDir.Data()) );
    gROOT->SetMacroPath( Form("%s:%s/macros", gROOT->GetMacroPath(), aliPhysicsDir.Data()) );
  }

  //
  // Process input parameters
  //

  TString extraLibs, mode;
  Bool_t enableAliEn = kFALSE;

  if (inputList) {
    TIter it(inputList);
    TNamed *pair;
    while ((pair = dynamic_cast<TNamed *>(it.Next()))) {
      if ( strcmp(pair->GetName(), "ALIROOT_EXTRA_LIBS") == 0 )
        extraLibs = pair->GetTitle();
      else if ( strcmp(pair->GetName(), "ALIROOT_ENABLE_ALIEN") == 0 )
        enableAliEn = ( *(pair->GetTitle()) != '\0' );
      else if ( strcmp(pair->GetName(), "ALIROOT_MODE") == 0 )
        mode = pair->GetTitle();
    }
  }

  //
  // Load extra libraries and set AliRoot Core mode
  //

  if (!SETUP_SetAliRootCoreMode(mode, extraLibs)) {
    ::Error(gMessTag.Data(), "Error loading libraries while setting AliRoot mode.");
    ::Error(gMessTag.Data(), "Did you enable the right version of ROOT?");
    return -1;
  }

  //
  // Enable AliEn
  //

  if (enableAliEn) {
    ::Info(gMessTag.Data(), "Connecting to AliEn...");
    TGrid::Connect("alien:");
    if (!gGrid) {
      ::Error(gMessTag.Data(), "Cannot connect to AliEn");
      return -1;
    }
    else {
      ::Info(gMessTag.Data(), "Successfully connected to AliEn");
    }
  }

  return 0;
}
Example #16
0
void Config()
{


  // Get settings from environment variables
  ProcessEnvironmentVars();

  gRandom->SetSeed(seed);
  cerr<<"Seed for random number generation= "<<seed<<endl;

  // Libraries required by geant321
#if defined(__CINT__)
  gSystem->Load("liblhapdf");      // Parton density functions
  gSystem->Load("libEGPythia6");   // TGenerator interface
  if (proc != kPythia6D6T) {
      gSystem->Load("libpythia6");     // Pythia 6.2
  } else {
      gSystem->Load("libqpythia");     // Pythia 6.4
  }
  gSystem->Load("libAliPythia6");  // ALICE specific implementations
  gSystem->Load("libgeant321");
#endif

  new TGeant3TGeo("C++ Interface to Geant3");

  //=======================================================================
  //  Create the output file


  AliRunLoader* rl=0x0;

  cout<<"Config.C: Creating Run Loader ..."<<endl;
  rl = AliRunLoader::Open("galice.root",
			  AliConfig::GetDefaultEventFolderName(),
			  "recreate");
  if (rl == 0x0)
    {
      gAlice->Fatal("Config.C","Can not instatiate the Run Loader");
      return;
    }
  rl->SetCompressionLevel(2);
  rl->SetNumberOfEventsPerFile(1000);
  gAlice->SetRunLoader(rl);
  // gAlice->SetGeometryFromFile("geometry.root");
  // gAlice->SetGeometryFromCDB();

  // Set the trigger configuration: proton-proton
  gAlice->SetTriggerDescriptor("p-p"); 

  //
  //=======================================================================
  // ************* STEERING parameters FOR ALICE SIMULATION **************
  // --- Specify event type to be tracked through the ALICE setup
  // --- All positions are in cm, angles in degrees, and P and E in GeV


    gMC->SetProcess("DCAY",1);
    gMC->SetProcess("PAIR",1);
    gMC->SetProcess("COMP",1);
    gMC->SetProcess("PHOT",1);
    gMC->SetProcess("PFIS",0);
    gMC->SetProcess("DRAY",0);
    gMC->SetProcess("ANNI",1);
    gMC->SetProcess("BREM",1);
    gMC->SetProcess("MUNU",1);
    gMC->SetProcess("CKOV",1);
    gMC->SetProcess("HADR",1);
    gMC->SetProcess("LOSS",2);
    gMC->SetProcess("MULS",1);
    gMC->SetProcess("RAYL",1);

    Float_t cut = 1.e-3;        // 1MeV cut by default
    Float_t tofmax = 1.e10;

    gMC->SetCut("CUTGAM", cut);
    gMC->SetCut("CUTELE", cut);
    gMC->SetCut("CUTNEU", cut);
    gMC->SetCut("CUTHAD", cut);
    gMC->SetCut("CUTMUO", cut);
    gMC->SetCut("BCUTE",  cut);
    gMC->SetCut("BCUTM",  cut);
    gMC->SetCut("DCUTE",  cut);
    gMC->SetCut("DCUTM",  cut);
    gMC->SetCut("PPCUTM", cut);
    gMC->SetCut("TOFMAX", tofmax);

  //======================//
  // Set External decayer //
  //======================//
  TVirtualMCDecayer* decayer = new AliDecayerPythia();
  decayer->SetForceDecay(kAll);
  decayer->Init();
  gMC->SetExternalDecayer(decayer);

  //=========================//
  // Generator Configuration //
  //=========================//
  AliGenerator* gener = 0x0;

  if (proc == kPythia6) {
      gener = MbPythia();
  } else if (proc == kPythia6D6T) {
      gener = MbPythiaTuneD6T();
  } else if (proc == kPhojet) {
      gener = MbPhojet();
  } else if (proc == kFlatJPsi) {
      gener = FlatJPsi();
  } else if (proc == kJPsi7TeV) {
      gener = JPsi7TeV();
  }

  // PRIMARY VERTEX
  //
   Double_t xv = 0;
   Double_t yv = 0;
   Double_t zv = 0;

   Double_t vtxPos[3];
   Double_t vtxErr[3];
   for (Int_t i = 0; i < 3; i++) {
       vtxPos[i] = 0.;
       vtxErr[i] = 0.;
   }
   vtxErr[2] = 4.5;

   if(AliCDBManager::Instance()->IsDefaultStorageSet()){
      AliCDBEntry* entry = AliCDBManager::Instance()->Get("GRP/Calib/MeanVertexSPD");
      AliESDVertex* vertex = dynamic_cast<AliESDVertex*> (entry->GetObject());
      vertex->GetXYZ(vtxPos);
      vertex->GetSigmaXYZ(vtxErr);
    }

    printf("Vertex position from OCDB entry: x = %13.3f, y = %13.3f, z = %13.3f (sigma = %13.3f)\n",
    vtxPos[0], vtxPos[1], vtxPos[2], vtxErr[2]);

  gener->SetOrigin(vtxPos[0], vtxPos[1] + 0.04, vtxPos[2]);   // vertex position
  //
  //
  // Size of the interaction diamond
  // Longitudinal
  Float_t sigmaz  = 5.4 / TMath::Sqrt(2.); // [cm]
  if (energy == 900)
    //sigmaz  = 10.5 / TMath::Sqrt(2.); // [cm]
    //sigmaz = 3.7;
  if (energy == 7000)
    sigmaz  = 6.3 / TMath::Sqrt(2.); // [cm]

    sigmaz = vtxErr[2];
  //
  // Transverse
  Float_t betast  = 10;                 // beta* [m]
  Float_t eps     = 3.75e-6;            // emittance [m]
  Float_t gamma   = energy / 2.0 / 0.938272;  // relativistic gamma [1]
  Float_t sigmaxy = TMath::Sqrt(eps * betast / gamma) / TMath::Sqrt(2.) * 100.;  // [cm]
  printf("\n \n Diamond size x-y: %10.3e z: %10.3e\n \n", sigmaxy, sigmaz);

  gener->SetSigma(sigmaxy, sigmaxy, sigmaz);      // Sigma in (X,Y,Z) (cm) on IP position
  gener->SetCutVertexZ(3.);        // Truncate at 3 sigma
  gener->SetVertexSmear(kPerEvent);
  gener->Init();

  // FIELD
  //
  AliMagF* field = 0x0;
  if (mag == kNoField) {
    comment = comment.Append(" | L3 field 0.0 T");
    field = new AliMagF("Maps","Maps", 0., 0., AliMagF::k5kGUniform,AliMagF::kBeamTypepp, energy/2.0);
  } else if (mag == k5kG) {
    comment = comment.Append(" | L3 field 0.5 T");
    field = new AliMagF("Maps","Maps", -1., -1., AliMagF::k5kG,	AliMagF::kBeamTypepp, energy/2.0);
  }

  printf("\n \n Comment: %s \n \n", comment.Data());

  TGeoGlobalMagField::Instance()->SetField(field);

  rl->CdGAFile();

  Int_t iABSO  = 1;
  Int_t iACORDE= 0;
  Int_t iDIPO  = 1;
  Int_t iEMCAL = 1;
  Int_t iFMD   = 1;
  Int_t iFRAME = 1;
  Int_t iHALL  = 1;
  Int_t iITS   = 1;
  Int_t iMAG   = 1;
  Int_t iMUON  = 1;
  Int_t iPHOS  = 1;
  Int_t iPIPE  = 1;
  Int_t iPMD   = 1;
  Int_t iHMPID = 1;
  Int_t iSHIL  = 1;
  Int_t iT0    = 1;
  Int_t iTOF   = 1;
  Int_t iTPC   = 1;
  Int_t iTRD   = 1;
  Int_t iVZERO = 1;
  Int_t iZDC   = 1;


    //=================== Alice BODY parameters =============================
    AliBODY *BODY = new AliBODY("BODY", "Alice envelop");


    if (iMAG)
    {
        //=================== MAG parameters ============================
        // --- Start with Magnet since detector layouts may be depending ---
        // --- on the selected Magnet dimensions ---
        AliMAG *MAG = new AliMAG("MAG", "Magnet");
    }


    if (iABSO)
    {
        //=================== ABSO parameters ============================
        AliABSO *ABSO = new AliABSOv3("ABSO", "Muon Absorber");
    }

    if (iDIPO)
    {
        //=================== DIPO parameters ============================

        AliDIPO *DIPO = new AliDIPOv3("DIPO", "Dipole version 3");
    }

    if (iHALL)
    {
        //=================== HALL parameters ============================

        AliHALL *HALL = new AliHALLv3("HALL", "Alice Hall");
    }


    if (iFRAME)
    {
        //=================== FRAME parameters ============================

        AliFRAMEv2 *FRAME = new AliFRAMEv2("FRAME", "Space Frame");
	FRAME->SetHoles(1);
    }

    if (iSHIL)
    {
        //=================== SHIL parameters ============================

        AliSHIL *SHIL = new AliSHILv3("SHIL", "Shielding Version 3");
    }


    if (iPIPE)
    {
        //=================== PIPE parameters ============================

        AliPIPE *PIPE = new AliPIPEv3("PIPE", "Beam Pipe");
    }

    if (iITS)
    {
        //=================== ITS parameters ============================

	AliITS *ITS  = new AliITSv11Hybrid("ITS","ITS v11Hybrid");
    }

    if (iTPC)
    {
      //============================ TPC parameters =====================

        AliTPC *TPC = new AliTPCv2("TPC", "Default");
    }


    if (iTOF) {
        //=================== TOF parameters ============================

	AliTOF *TOF = new AliTOFv6T0("TOF", "normal TOF");
    }


    if (iHMPID)
    {
        //=================== HMPID parameters ===========================

        AliHMPID *HMPID = new AliHMPIDv3("HMPID", "normal HMPID");

    }


    if (iZDC)
    {
        //=================== ZDC parameters ============================

        AliZDC *ZDC = new AliZDCv3("ZDC", "normal ZDC");
    }

    if (iTRD)
    {
        //=================== TRD parameters ============================
            // 7 TRDs only : 0, 1, 7, 8, 9, 10, 17
        AliTRD *TRD = new AliTRDv1("TRD", "TRD slow simulator");
        AliTRDgeometry *geoTRD = TRD->GetGeometry();
	// Partial geometry: modules at 0,1,7,8,9,16,17
	// starting at 3h in positive direction
	geoTRD->SetSMstatus(2,0);
	geoTRD->SetSMstatus(3,0);
	geoTRD->SetSMstatus(4,0);
        geoTRD->SetSMstatus(5,0);
	geoTRD->SetSMstatus(6,0);
        geoTRD->SetSMstatus(11,0);
        geoTRD->SetSMstatus(12,0);
        geoTRD->SetSMstatus(13,0);
        geoTRD->SetSMstatus(14,0);
        geoTRD->SetSMstatus(15,0);
        geoTRD->SetSMstatus(16,0);
    }

    if (iFMD)
    {
        //=================== FMD parameters ============================

	AliFMD *FMD = new AliFMDv1("FMD", "normal FMD");
   }

    if (iMUON)
    {
        //=================== MUON parameters ===========================
        // New MUONv1 version (geometry defined via builders)

        AliMUON *MUON = new AliMUONv1("MUON", "default");
    }

    if (iPHOS)
    {
        //=================== PHOS parameters ===========================

        AliPHOS *PHOS = new AliPHOSv1("PHOS", "IHEP");
        //Set simulation parameters different from the default ones.
        AliPHOSSimParam* simEmc = AliPHOSSimParam::GetInstance() ;

        // APD noise of warm (+20C) PHOS:
        // a2 = a1*(Y1/Y2)*(M1/M2), where a1 = 0.012 is APD noise at -25C,
        // Y1 = 4.3 photo-electrons/MeV, Y2 = 1.7 p.e/MeV - light yields at -25C and +20C,
        // M1 = 50, M2 = 50 - APD gain factors chosen for t1 = -25C and t2 = +20C,
        // Y = MeanLightYield*APDEfficiency.

        Float_t apdNoise = 0.012*2.5;
        simEmc->SetAPDNoise(apdNoise);

        //Raw Light Yield at +20C
        simEmc->SetMeanLightYield(18800);

        //ADC channel width at +18C.
        simEmc->SetADCchannelW(0.0125);
    }


    if (iPMD)
    {
        //=================== PMD parameters ============================

        AliPMD *PMD = new AliPMDv1("PMD", "normal PMD");
    }

    if (iT0)
    {
        //=================== T0 parameters ============================
        AliT0 *T0 = new AliT0v1("T0", "T0 Detector");
    }

    if (iEMCAL)
    {
        //=================== EMCAL parameters ============================

        AliEMCAL *EMCAL = new AliEMCALv2("EMCAL", "EMCAL_COMPLETE");
    }

     if (iACORDE)
    {
        //=================== ACORDE parameters ============================

        AliACORDE *ACORDE = new AliACORDEv1("ACORDE", "normal ACORDE");
    }

     if (iVZERO)
    {
        //=================== ACORDE parameters ============================

        AliVZERO *VZERO = new AliVZEROv7("VZERO", "normal VZERO");
    }
}
Example #17
0
Bool_t SETUP_SetAliRootCoreMode(TString &mode, const TString &extraLibs) {

  // Sets a certain AliRoot mode, defining a set of libraries to load. Extra
  // libraries to load can be specified as well. Returns kTRUE on success, or
  // kFALSE in case library loading failed.

  mode.ToLower();
  TString libs = extraLibs;
  Long_t rv = -9999;

  // Load needed ROOT libraries
  if (!SETUP_LoadLibraries("VMC:Tree:Physics:Matrix:Minuit:XMLParser:Gui")) {
    ::Error(gMessTag.Data(), "Loading of extra ROOT libraries failed");
    return kFALSE;
  }

  if (mode == "aliroot") {
    ::Info(gMessTag.Data(), "Loading libraries for AliRoot mode...");
    rv = gROOT->LoadMacro(
      gSystem->ExpandPathName("$ALICE_ROOT/macros/loadlibs.C") );
    if (rv == 0) loadlibs();
  }
  else if (mode == "sim") {
    ::Info(gMessTag.Data(), "Loading libraries for simulation mode...");
    rv = gROOT->LoadMacro(
      gSystem->ExpandPathName("$ALICE_ROOT/macros/loadlibssim.C") );
    if (rv == 0) loadlibssim();
  }
  else if (mode == "rec") {
    ::Info(gMessTag.Data(), "Loading libraries for reconstruction mode...");
    rv = gROOT->LoadMacro(
      gSystem->ExpandPathName("$ALICE_ROOT/macros/loadlibsrec.C") );
    if (rv == 0) loadlibsrec();
  }
  else if (mode == "base") {
    // "Base" mode: load standard libraries, and also fix loading order
    ::Info(gMessTag.Data(), "No mode specified: loading standard libraries...");
    TPMERegexp reLibs("(ANALYSISalice|ANALYSIS|STEERBase|ESD|AOD)(:|$)");
    while (reLibs.Substitute(libs, "")) {}
    libs.Prepend("STEERBase:ESD:AOD:ANALYSIS:ANALYSISalice:");
  }

  // Check status code
  if (rv == 0) {
    ::Info(gMessTag.Data(), "Successfully loaded AliRoot base libraries");
  }
  else if (rv != -9999) {
    ::Error(gMessTag.Data(), "Loading of base AliRoot libraries failed");
    return kFALSE;
  }

  // Load extra AliRoot libraries
  ::Info(gMessTag.Data(), "Loading extra AliRoot libraries...");
  if (!SETUP_LoadLibraries(libs)) {
    ::Error(gMessTag.Data(), "Loading of extra AliRoot libraries failed");
    return kFALSE;
  }
  else {
    ::Info(gMessTag.Data(), "Successfully loaded extra AliRoot libraries");
  }

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

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

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

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

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

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

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

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

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

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

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

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

  return mass;
}
Example #19
0
//______________________________________________________________________________                                                           
void AddAnalysisTasks(){                                                                                                                                          
  // Add all analysis task wagons to the train                                                                                               
   IlcAnalysisManager *mgr = IlcAnalysisManager::GetAnalysisManager();                                                                     

  //
  // Tender and supplies. Needs to be called for every event.
  //
   IlcAnalysisManager::SetCommonFileName("AODQA.root");
   if (useTender) {
      gROOT->LoadMacro("$ILC_ROOT/ANALYSIS/TenderSupplies/AddTaskTender.C");
      // IF V0 tender needed, put kTRUE below
      IlcAnalysisTaskSE *tender = AddTaskTender(useV0tender);
//      tender->SetDebugLevel(2);
   }

   if (usePhysicsSelection) {
   // Physics selection task
      gROOT->LoadMacro("$ILC_ROOT/ANALYSIS/macros/AddTaskPhysicsSelection.C");
      mgr->RegisterExtraFile("event_stat.root");
      IlcPhysicsSelectionTask *physSelTask = AddTaskPhysicsSelection(useMC);
//      IlcOADBPhysicsSelection * oadbDefaultPbPb = CreateOADBphysicsSelection();      
//      physSelTask->GetPhysicsSelection()->SetCustomOADBObjects(oadbDefaultPbPb,0,0);
      mgr->AddStatisticsTask(IlcVEvent::kAny);
   }
   // Centrality (only Pb-Pb)
   if (iCollision && useCentrality) {
      gROOT->LoadMacro("$ILC_ROOT/ANALYSIS/macros/AddTaskCentrality.C");
      IlcCentralitySelectionTask *taskCentrality = AddTaskCentrality();
      taskCentrality->SelectCollisionCandidates(IlcVEvent::kAny);
   }

   if (iESDfilter) {
      //  ESD filter task configuration.
      gROOT->LoadMacro("$ILC_ROOT/ANALYSIS/macros/AddTaskESDFilter.C");
      if (iMUONcopyAOD) {
         printf("Registering delta AOD file\n");
         mgr->RegisterExtraFile("IlcAOD.Muons.root");
         mgr->RegisterExtraFile("IlcAOD.Dimuons.root");
         IlcAnalysisTaskESDfilter *taskesdfilter = AddTaskESDFilter(useKFILTER, kTRUE, kFALSE, kFALSE /*usePhysicsSelection*/,kFALSE,IlcESDpid::kTOF_T0,kTRUE,kFALSE,kFALSE,run_flag);
      } else {
   	   IlcAnalysisTaskESDfilter *taskesdfilter = AddTaskESDFilter(useKFILTER, kFALSE, kFALSE, kFALSE /*usePhysicsSelection*/,kFALSE,IlcESDpid::kTOF_T0,kTRUE,kFALSE,kFALSE,run_flag); // others
      }   
   }   

// ********** PWG3 wagons ******************************************************           
   // PWGHF vertexing
   if (iPWGHFvertexing) {
      gROOT->LoadMacro("$ILC_ROOT/PWGHF/vertexingHF/macros/AddTaskVertexingHF.C");
      if (!iPWGHFd2h) TFile::Cp(gSystem->ExpandPathName(configPWGHFd2h.Data()), "file:ConfigVertexingHF.C");
      IlcAnalysisTaskSEVertexingHF *taskvertexingHF = AddTaskVertexingHF();
      if (!taskvertexingHF) ::Warning("AnalysisTrainNew", "IlcAnalysisTaskSEVertexingHF cannot run for this train conditions - EXCLUDED");
      else mgr->RegisterExtraFile("IlcAOD.VertexingHF.root");
      taskvertexingHF->SelectCollisionCandidates(0);
   }   
      
   // PWGDQ JPSI filtering (only pp)
   if (iPWGDQJPSIfilter && (iCollision==0)) {
      gROOT->LoadMacro("$ILC_ROOT/PWGDQ/dielectron/macros/AddTaskJPSIFilter.C");
      IlcAnalysisTaskSE *taskJPSIfilter = AddTaskJPSIFilter();
      if (!taskJPSIfilter) ::Warning("AnalysisTrainNew", "IlcAnalysisTaskDielectronFilter cannot run for this train conditions - EXCLUDED");
      else mgr->RegisterExtraFile("IlcAOD.Dielectron.root");
      taskJPSIfilter->SelectCollisionCandidates(0);
   }   

   // PWGHF D2h
   if (iPWGHFd2h) {   
     gROOT->LoadMacro("$ILC_ROOT/PWGHF/vertexingHF/AddD2HTrain.C");
     TFile::Cp(gSystem->ExpandPathName(configPWGHFd2h.Data()), "file:ConfigVertexingHF.C");
     AddD2HTrain(kFALSE, 1,0,0,0,0,0,0,0,0,0,0);                                 
   }
   
   // ********** PWG4 wagons ******************************************************
   // Jet analysis

   // Configurations flags, move up?
   TString kDeltaAODJetName = "IlcAOD.Jets.root"; //
   Bool_t  kIsPbPb = (iCollision==0)?false:true; // can be more intlligent checking the name of the data set
   TString kDefaultJetBackgroundBranch = "";
   TString kJetSubtractBranches = "";
   UInt_t kHighPtFilterMask = 128;// from esd filter
   UInt_t iPhysicsSelectionFlag = IlcVEvent::kMB;
   if (iJETAN) {
     gROOT->LoadMacro("$ILC_ROOT/PWGJE/macros/AddTaskJets.C");
     // Default jet reconstructor running on ESD's
     IlcAnalysisTaskJets *taskjets = AddTaskJets("AOD","UA1",0.4,kHighPtFilterMask,1.,0); // no background subtraction     
     if (!taskjets) ::Fatal("AnalysisTrainNew", "IlcAnalysisTaskJets cannot run for this train conditions - EXCLUDED");
     if(kDeltaAODJetName.Length()>0) taskjets->SetNonStdOutputFile(kDeltaAODJetName.Data());
     if (iJETANdelta) {
        //            AddTaskJetsDelta("IlcAOD.Jets.root"); // need to modify this accordingly in the add task jets
        mgr->RegisterExtraFile(kDeltaAODJetName.Data());
        TString cTmp("");
        if(kIsPbPb){
          // UA1 intrinsic background subtraction
          taskjets = AddTaskJets("AOD","UA1",0.4,kHighPtFilterMask,1.,2); // background subtraction
          if(kDeltaAODJetName.Length()>0)taskjets->SetNonStdOutputFile(kDeltaAODJetName.Data());
       }
       // SICONE 
       taskjets = AddTaskJets("AOD","SISCONE",0.4,kHighPtFilterMask,0.15,0); //no background subtration to be done later....                                                                                  
       if(kDeltaAODJetName.Length()>0)taskjets->SetNonStdOutputFile(kDeltaAODJetName.Data());
       cTmp = taskjets->GetNonStdBranch();
       if(cTmp.Length()>0)kJetSubtractBranches += Form("%s ",cTmp.Data());
	 
       // Add the clusters..
       gROOT->LoadMacro("$ILC_ROOT/PWGJE/macros/AddTaskJetCluster.C");
       IlcAnalysisTaskJetCluster *taskCl = 0;
       Float_t fCenUp = 0;
       Float_t fCenLo = 0;
       Float_t fTrackEtaWindow = 0.9;
       taskCl = AddTaskJetCluster("AOD","",kHighPtFilterMask,iPhysicsSelectionFlag,"KT",0.4,0,1, kDeltaAODJetName.Data(),0.15,fTrackEtaWindow,0); // this one is for the background and random jets, random cones with no skip                                                                                 
       taskCl->SetBackgroundCalc(kTRUE);
       taskCl->SetNRandomCones(10);
       taskCl->SetCentralityCut(fCenLo,fCenUp);
       taskCl->SetGhostEtamax(fTrackEtaWindow);
       kDefaultJetBackgroundBranch = Form("%s_%s",IlcAODJetEventBackground::StdBranchName(),taskCl->GetJetOutputBranch());

       taskCl = AddTaskJetCluster("AOD","",kHighPtFilterMask,iPhysicsSelectionFlag,"ANTIKT",0.4,2,1,kDeltaAODJetName.Data(),0.15);
       taskCl->SetCentralityCut(fCenLo,fCenUp);
       if(kIsPbPb)taskCl->SetBackgroundBranch(kDefaultJetBackgroundBranch.Data());
       taskCl->SetNRandomCones(10);
       kJetSubtractBranches += Form("%s ",taskCl->GetJetOutputBranch());

       taskCl = AddTaskJetCluster("AOD","",kHighPtFilterMask,iPhysicsSelectionFlag,"ANTIKT",0.2,0,1,kDeltaAODJetName.Data(),0.15);
       taskCl->SetCentralityCut(fCenLo,fCenUp);
       if(kIsPbPb)taskCl->SetBackgroundBranch(kDefaultJetBackgroundBranch.Data());
       kJetSubtractBranches += Form("%s ",taskCl->GetJetOutputBranch());
	 
       // DO THE BACKGROUND SUBTRACTION
       if(kIsPbPb&&kJetSubtractBranches.Length()){
         gROOT->LoadMacro("$ILC_ROOT/PWGJE/macros/AddTaskJetBackgroundSubtract.C");
         IlcAnalysisTaskJetBackgroundSubtract *taskSubtract = 0;
         taskSubtract = AddTaskJetBackgroundSubtract(kJetSubtractBranches,1,"B0","B%d");
         taskSubtract->SetBackgroundBranch(kDefaultJetBackgroundBranch.Data());
         if(kDeltaAODJetName.Length()>0)taskSubtract->SetNonStdOutputFile(kDeltaAODJetName.Data());
       }
     } 
   }
}
Example #20
0
void Error(TString msg) {
  printf("ERROR: %s\n", msg.Data()); 
}
Example #21
0
void plotLHCPPZHproj(variables var=km) {

  RooRealVar* costheta1 = new RooRealVar("costheta1","cos#theta_{1}",-1.,1.);
  RooRealVar* costheta2 = new RooRealVar("costheta2","cos#theta_{2}",-1.,1.);
  RooRealVar* phi = new RooRealVar("phi","#Phi",-TMath::Pi(),TMath::Pi());
  RooRealVar* m= new RooRealVar("m","m_{VH} [GeV]", 200, 1000);
  RooRealVar* Y= new RooRealVar("Y","Rapidity (VH)", -4, 4);
  // additional variables
  // event weight
  RooRealVar* wt = new RooRealVar("wt", "wt", 0.0, 50);

  vector<RooRealVar*> meas;
  meas.push_back(costheta1);
  meas.push_back(costheta2);
  meas.push_back(phi);
  meas.push_back(m);
  meas.push_back(Y);
  meas.push_back(wt);

  
  int parameterization = 1; 

  RooRealVar* mH = new RooRealVar("mH","m_{H}",125.);
  ScalarPdfFactoryPPZH SMHiggs(costheta1,costheta2,phi,m,Y,mH,parameterization,false);

  ScalarPdfFactoryPPZH psScalar(costheta1,costheta2,phi,m,Y,mH,parameterization,false);
  psScalar.g1Val->setVal(0.0);
  psScalar.g4Val->setVal(1.0);

  ScalarPdfFactoryPPZH f3p5Scalar(costheta1,costheta2,phi,m,Y,mH,parameterization,false);
  f3p5Scalar.g1Val->setVal(1.0);
  f3p5Scalar.g4Val->setVal(0.144708);

  ScalarPdfFactoryPPZH f3p5_90_Scalar(costheta1,costheta2,phi,m,Y,mH,parameterization,false);
  f3p5_90_Scalar.g1Val->setVal(1.0);
  f3p5_90_Scalar.g4ValIm->setVal(0.144708);


  //
  //  Read datasets
  // 
  TChain* SMHtree = new TChain("SelectedTree");
  SMHtree->Add("samples/pp_ZH/pp_ZH_llbb_g1_1M_false.root");
  RooDataSet dataTMPSMH("dataTMPSMH","dataTMPSMH", SMHtree, RooArgSet(*costheta1,*costheta2,*phi,*m,*Y, *wt));
  RooDataSet SMHdata = RooDataSet("SMHData","SMHData",RooArgList(*costheta1,*costheta2,*phi,*m, *Y, *wt), WeightVar("wt"), Import(dataTMPSMH));

  TChain* PStree = new TChain("SelectedTree");
  PStree->Add("samples/pp_ZH/pp_ZH_llbb_g4_1M_false.root");
  RooDataSet dataTMPPS("dataTMPPS","dataTMPPS", PStree, RooArgSet(*costheta1,*costheta2,*phi,*m,*Y, *wt));
  RooDataSet PSdata = RooDataSet("PSData","PSData",RooArgList(*costheta1,*costheta2,*phi,*m, *Y, *wt), WeightVar("wt"), Import(dataTMPPS));

  TChain* f3p5tree = new TChain("SelectedTree");
  f3p5tree->Add("samples/pp_ZH/pp_ZH_llbb_g1_p_g4_1M_false.root");
  RooDataSet dataTMPf3p5("dataTMPf3p5","dataTMPf3p5", f3p5tree, RooArgSet(*costheta1,*costheta2,*phi,*m,*Y, *wt));
  RooDataSet f3p5data = RooDataSet("f3p5Data","f3p5Data",RooArgList(*costheta1,*costheta2,*phi,*m, *Y, *wt), WeightVar("wt"), Import(dataTMPf3p5));

  TChain* f3p5_90_tree = new TChain("SelectedTree");
  f3p5_90_tree->Add("samples/pp_ZH/pp_ZH_llbb_g1_p_ig4_1M_false.root");
  RooDataSet dataTMPf3p5_90("dataTMPf3p5_90","dataTMPf3p5_90", f3p5_90_tree, RooArgSet(*costheta1,*costheta2,*phi,*m,*Y, *wt));
  RooDataSet f3p5_90_data = RooDataSet("f3p5_90Data","f3p5_90Data",RooArgList(*costheta1,*costheta2,*phi,*m, *Y, *wt), WeightVar("wt"), Import(dataTMPf3p5_90));
  
  TString varName = "costheta1";
  const int nbins = 20;
  double xMin =  -1; 
  double xMax = 1.;
  
  if ( var == kcostheta2 ) {
    varName = "costheta2";
  } else if( var == kphi)  {
    varName = "phi";
    xMin = -TMath::Pi();
    xMax = TMath::Pi();
  } else if ( var == km)   {
    varName = "m";
    xMin = 200;
    xMax = 1000.;
  } else if ( var == kY)  {
    varName = "Y";
    xMin = -4;
    xMax = 4;
  }
  // 
  // Do some gymnastics about the plots
  // normalize to 1
  // 
  
  TH1F *h_0p = new TH1F("h_0p", "h_0p", nbins, xMin, xMax);
  SMHtree->Project("h_0p", varName,"wt");
  double rescale_0p = 1./h_0p->Integral();
  h_0p->Scale(rescale_0p);
  // std::cout << "rescale_0p = " << rescale_0p << "\n";
  double ymax = h_0p->GetMaximum();
  
  TH1F *h_0m = new TH1F("h_0m", "h_0m", nbins, xMin, xMax); 
  PStree->Project("h_0m", varName,"wt");
  double rescale_0m = 1./h_0m->Integral();
  // std::cout << "rescale_0m = " << rescale_0m << "\n";
  h_0m->Scale(rescale_0m);
  ymax = h_0m->GetMaximum() > ymax ? h_0m->GetMaximum() : ymax;

  TH1F *h_0mix = new TH1F("h_0mix", "h_0mix", nbins, xMin, xMax);
  f3p5tree->Project("h_0mix", varName,"wt");
  double rescale_0mix = 1./h_0mix->Integral();
  // std::cout << "rescale_0mix = " << rescale_0mix << "\n";
  h_0mix->Scale(rescale_0mix);
  ymax = h_0mix->GetMaximum() > ymax ? h_0mix->GetMaximum() : ymax;

  TH1F *h_0mixphase = new TH1F("h_0mixphase", "h_0mixphase", nbins, xMin, xMax);
  f3p5_90_tree->Project("h_0mixphase", varName,"wt");
  double rescale_0mixphase = 1./h_0mixphase->Integral();
  // std::cout << "rescale_0mixphase = " << rescale_0mixphase << "\n";
  h_0mixphase->Scale(rescale_0mixphase);
  ymax = h_0mixphase->GetMaximum() > ymax ? h_0mixphase->GetMaximum() : ymax;
  

  // create rooplot and plot data/pdfs
  RooPlot* plot = (meas[var])->frame(nbins);
  
  SMHdata.plotOn(plot,MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),XErrorSize(0),DataError(RooAbsData::None), Rescale(rescale_0p));
  SMHiggs.PDF->plotOn(plot,LineColor(kRed),LineWidth(2), Normalization(rescale_0p));

  PSdata.plotOn(plot,MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0),DataError(RooAbsData::None), Rescale(rescale_0m));
  psScalar.PDF->plotOn(plot,LineColor(kBlue),LineWidth(2), Normalization(rescale_0m));

  f3p5data.plotOn(plot,MarkerColor(kGreen+3),MarkerStyle(25),MarkerSize(1.5),XErrorSize(0),DataError(RooAbsData::None), Rescale(rescale_0mix));
  f3p5Scalar.PDF->plotOn(plot,LineColor(kGreen+3),LineWidth(2), Normalization(rescale_0mix));

  f3p5_90_data.plotOn(plot,MarkerColor(kMagenta+1),MarkerStyle(20), MarkerSize(1.5),XErrorSize(0),DataError(RooAbsData::None), Rescale(rescale_0mixphase));
  f3p5_90_Scalar.PDF->plotOn(plot,LineColor(kMagenta+1),LineWidth(2), Normalization(rescale_0mixphase));

  //TGaxis::SetMaxDigits(3);
  plot->SetMaximum(ymax*1.1);
  
  if ( var == km ) 
    plot->SetMaximum(ymax*1.3);

  TCanvas* can = new TCanvas("can","can",600,600);
  // plot styles
  // gStyle->SetPadLeftMargin(0.05);
  plot->GetXaxis()->CenterTitle();
  plot->GetYaxis()->CenterTitle();
  plot->GetYaxis()->SetTitle(" ");
  plot->GetXaxis()->SetNdivisions(505);
  plot->Draw();

  TString plotName = "h1";
  if ( var == kcostheta2) plotName = "h2";
  if ( var == kphi) plotName = "phi";
  if ( var == km) plotName = "mvh";
  if ( var == kY) plotName = "Yvh";
  
  can->SaveAs(Form("paperplots/%s_ppzh_pp_ZH_llbb_accfalse.eps", plotName.Data()));
  can->SaveAs(Form("paperplots/%s_ppzh_pp_ZH_llbb_accfalse.png", plotName.Data()));

  delete h_0p;
  delete h_0m;
  delete h_0mix;
  delete h_0mixphase;
  delete plot;
  delete can;
  delete SMHtree;
  delete PStree;
  delete f3p5tree;  
  delete f3p5_90_tree;
}
Example #22
0
File: Norm.C Project: TJHague/XGT2
/*int main{{{*/
void Check( TString Target_Name){

	/*Define{{{*/
	gROOT->SetStyle("Plain");
	gStyle->SetFillColor(0);
	TString Input_File = ""; 
	Input_File = Form("%s_L_kin5.1_unf.rho",Target_Name.Data()); 
	ifstream infile1(Input_File);
	Input_File = Form("../%s_Yield_L_All.out",Target_Name.Data()); 
	ifstream infile4(Input_File);

	Input_File = Form("%s.rho",Target_Name.Data()); 
	ofstream outfile(Input_File);
	
	const int bin = 60;
	double I1=0.;
	if(Target_Name=="H2"){
		I1=45.0;
	}
	else if(Target_Name=="He3"){
		I1=120.0;
	}
	else if(Target_Name=="He4"){
		I1 = 95.0; 
	}
	else
		cerr<<"***ERROR, Unknow Target!!!"<<endl;

	double *VZ1 = new double[bin];
	double *VZf = new double[bin];
	double *Rho1 = new double[bin];
	double *Rho1_Err = new double[bin];
	double *Rho0 = new double[bin];
	double *Rho0_Err = new double[bin];
	double *Rho0f = new double[bin];
	double *Rho0f_Err = new double[bin];
	double *Rho1f = new double[bin];
	double *Rho1f_Err = new double[bin];
	double *Zero = new double[bin];
	double *BF = new double[bin];
	double *BF_Err = new double[bin];

	double rho1_sum=0., rho0_sum=0.;
    double rho0f_sum=0.,rho1f_sum=0.;
    TString acom; infile4>>acom>>acom>>acom>>acom>>acom;
	/*}}}*/

	double aa=0;
	for(int i=0;i<bin;i++){
		infile1 >> VZ1[i] >> Rho1[i];	Rho1_Err[1]=sqrt(Rho1[i]);
		infile4 >> VZf[i] >> Rho0f[i] >> Rho0f_Err[i] >> BF[i] >> BF_Err[i];	

		Zero[i]=0.0;
		Rho0[i] = Correction_Inverse(Target_Name.Data(), VZ1[i], I1, Rho1[i] ); 
		Rho0_Err[i] = Rho0[i]/Rho1[i]*Rho1_Err[i];

		Rho1f[i] = Correction(Target_Name.Data(), VZf[i], I1, Rho0f[i] ); 
		Rho1f_Err[i] = Rho1f[i]/Rho0f[i]*Rho0f_Err[i];

		if(VZ1[i]>-0.075 && VZ1[i]<0.075){
           rho0_sum+=Rho0[i];
           rho1_sum+=Rho1[i];
		}
		else{
			Rho0[i]=0.0;
			Rho1[i]=0.0;
			Rho0_Err[i]=0.0;
			Rho1_Err[i]=0.0;
		}

		if(VZf[i]>-0.075 && VZf[i]<0.075){
           rho0f_sum+=Rho0f[i];
           rho1f_sum+=Rho1f[i];
		}
		else{
			Rho0f[i]=0.0;
			Rho1f[i]=0.0;
			Rho0f_Err[i]=0.0;
			Rho1f_Err[i]=0.0;
		}
	}
	infile1.close(); 

	cerr<<Form("Rho=%f, Rho1=%f, Rhof=%f, Rho1f=%f", rho0_sum, rho1_sum, rho0f_sum, rho1f_sum)<<endl;

	outfile<<Form("%12s %12s %12s %12s %12s", "VZ","Y0","Y0_Err","BF","BF_Err")<<endl; 
	for(int i=0;i<bin;i++){
		Rho0[i]/=rho0_sum;
		Rho0_Err[i]/=rho0_sum;
		Rho1[i]/=rho1_sum;
		Rho1_Err[i]/=rho1_sum;

		Rho0f[i]/=rho0f_sum;
		Rho0f_Err[i]/=rho0f_sum;
		Rho1f[i]/=rho1f_sum;
		Rho1f_Err[i]/=rho1f_sum;
		
		outfile<<Form("  %12.8f %12.8f %12.8f %12.8f %12.8f",VZf[i],Rho0f[i], Rho0f_Err[i], BF[i],BF_Err[i])<<endl; 
		}	
    outfile.close();

	TCanvas *c1 = new TCanvas("c1","c1",1200,700);
	c1->cd();
	TH2F *h1 = new TH2F("h1","",300,-0.12,0.12,300,-0.01,0.04);
	h1->SetStats(kFALSE);
	h1->SetXTitle("z_{react} (m)");
	h1->GetXaxis()->CenterTitle(1);
	h1->GetXaxis()->SetTitleFont(32);
	h1->GetXaxis()->SetTitleSize(0.06);
	h1->SetYTitle("#rho_{norm}");
	h1->GetYaxis()->CenterTitle(1);
	h1->GetYaxis()->SetTitleFont(32);
	h1->GetYaxis()->SetTitleSize(0.06);
	h1->GetYaxis()->SetTitleOffset(0.8);
	h1->SetLineWidth(1.5);
	h1->Draw();

	TGraphErrors *ex = new TGraphErrors(bin, VZ1, Rho0, Zero, Rho0_Err);
	ex->SetMarkerStyle(20);
	ex->SetMarkerColor(1);
	ex->SetLineColor(1);
	ex->SetLineWidth(1.5);

	TGraphErrors *ex4 = new TGraphErrors(bin, VZf, Rho0f, Zero, Rho0f_Err);
	ex4->SetMarkerStyle(20);
	ex4->SetMarkerColor(6);
	ex4->SetLineColor(6);
	ex4->SetLineWidth(1.5);
	

	TGraphErrors *ex1 = new TGraphErrors(bin, VZ1, Rho1, Zero, Rho1_Err);
	ex1->SetMarkerStyle(21);
	ex1->SetMarkerColor(6);
	ex1->SetLineColor(2);
	ex1->SetLineWidth(1.5);

	TGraphErrors *ex41 = new TGraphErrors(bin, VZf, Rho1f, Zero, Rho1f_Err);
	ex41->SetMarkerStyle(28);
	ex41->SetMarkerColor(4);
	ex41->SetLineColor(2);
	ex41->SetLineWidth(1.5);
	
	TLegend *l1  = new TLegend(0.33,0.2,0.72,0.45,Form("%s Density Profile:",Target_Name.Data()));
	l1->SetTextSize(0.03);
	l1->SetTextFont(32);

	c1->Clear(); h1->Draw();
	ex->Draw("l");
	l1->AddEntry(ex, Form("#rho_{0} calculated from #rho(%d uA) ",(int)(I1)),"l");
	ex4->Draw("p");
	l1->AddEntry(ex4, Form("#rho_{0} from Boiling Fitting"),"p");

	ex1->Draw("l");
	l1->AddEntry(ex1, Form("#rho(%d uA)  from data",(int) (I1)),"l");
	ex41->Draw("p");
	l1->AddEntry(ex41, Form("#rho(%d uA) calculated from Boiling Fitting",(int) (I1)),"p");

	l1->Draw();
//	c1->Print(Form("%s_Check_%d.png",Target_Name.Data(), (int) (I1)));
//	c1->Print(Form("%s_Check_%d.pdf",Target_Name.Data(), (int) (I1)));

	delete VZ1;
	delete VZf;
	delete Rho1;
	delete Rho0;  
	delete Rho1_Err;
	delete Rho0_Err;  
	delete Rho0f;  
	delete Rho1f;  
	delete Rho0f_Err;  
	delete Rho1f_Err;  
	delete Zero;
    delete BF;
    delete BF_Err;	
}
Example #23
0
void SetNameBordel(Int_t fsuf, Int_t qc, Int_t std10or11, Bool_t info=kFALSE,
                   const char *my_fname="AnalysisResults.root")
{
  if (rsn_data == 20130106) {
    fname = Form("root://eos.saske.sk//eos/saske.sk/scratch/ALICE/RSN/RESULTS/Rsn_Phi/pp_2.76/2013-01-06/MC_LHC12i6_146805_ESD/%s/%s", suf[fsuf], my_fname);
    mv_colon = "_";
  }
  else {
    Printf("Wrong input Rsn data !!!");
    return;
  }

  const char *tmp_qc = "";
  if      (qc == 0)  { tmp_qc = "qualityonly"; ilist = 0; sigma = 0.0;
    noSigma = kTRUE; }
  else if (qc == 10) { tmp_qc = "KTPCnsig10";  ilist = 2; sigma = 1.0;
    noSigma = kFALSE; }
  else if (qc == 15) { tmp_qc = "KTPCnsig15";  ilist = 2; sigma = 1.5;
    noSigma = kFALSE; }
  else if (qc == 20) { tmp_qc = "KTPCnsig20";  ilist = 3; sigma = 2.0;
    noSigma = kFALSE; }
  else if (qc == 25) { tmp_qc = "KTPCnsig25";  ilist = 4; sigma = 2.5;
    noSigma = kFALSE; }
  else if (qc == 30) { tmp_qc = "KTPCnsig30";  ilist = 5; sigma = 3.0;
    noSigma = kFALSE; }
  else {
    Printf("Wrong TPC cut !!!");
    return;
  }
  const char *tmp_10or11 = "";
  if      (std10or11 == 2010) tmp_10or11 = "STD2010_PRIMARY";
  else if (std10or11 == 2011) tmp_10or11 = "STD2011_PRIMARY_NCLSTTPC";
  else {
    Printf("Wrong 2010 or 2011 cut !!!");
    return;
  }

  if (fsuf == 0) { // bo Mato
    lname = Form("RsnHistMini_Phi_PhiNsigma%s%s_%s",
                 mv_colon.Data(),tmp_qc, tmp_10or11);
    what  = Form("PhiNsigma_%s_%s",
                 tmp_qc, tmp_10or11);
    graph_name = Form("%s_%s", what, suf[fsuf]);
  }
  else {
    lname = Form("RsnHistMini_Phi_PhiNsigma%s%s_%s_%s",
                 mv_colon.Data(),tmp_qc, tmp_10or11, suf[fsuf]);
    what  = Form("PhiNsigma_%s_%s_%s",
                 tmp_qc, tmp_10or11, suf[fsuf]);
    graph_name = what;
  }

  dir_prefix = "EFFI2";
  if (binAnders) dir_prefix += "_ANDERS";
  dir_prefix += Form("_%s", suf[fsuf]);
  //  graphee_name =
  //    Form("PhiNsigma_qualityonly_%s_%s", tmp_10or11, suf[fsuf]);

  s1name     = Form("RsnMini_phi.%s_Unlike",   what);
  s1namegen  = Form("RsnMini_phi_MCGenphi.%s", what);
  s1nametrue = Form("RsnMini_phi.%s_Trues",    what);
  s3name_p   = Form("RsnMini_phi.%s_LikePP",   what);
  s3name_m   = Form("RsnMini_phi.%s_LikeMM",   what);
  smix       = Form("RsnMini_phi.%s_Mixing",   what);
  smixpp     = Form("RsnMini_phi.%s_MixingPP", what);
  smixmm     = Form("RsnMini_phi.%s_MixingMM", what);

  if (!info) return;
  Printf("file name: %s", fname.Data());
  Printf("list name: %s", lname.Data());
  Printf("\n1 - %s\n2 - %s\n3 - %s\n4 - %s\n5 - %s\n6 - %s\n7 - %s\n8 - %s\n",
         s1name.Data(), s3name_p.Data(), s3name_m.Data(),
         smix.Data(), smixpp.Data(), smixmm.Data(),
         s1nametrue.Data(), s1namegen.Data());
}
int main(int argc, char *argv[])
{
  cout.setf(ios::fixed, ios::floatfield);
  cout.precision(12);

  // Prompt for filename of run numbers
  int iXeRunPeriod;
  cout << "Enter Xenon run period: " << endl;
  cin  >> iXeRunPeriod;
  cout << endl;

  /*bool allResponseClasses = true;
  int numResponseClasses = 0;
  vector <int> responseClasses;
  
  cout << "All Response Classes? (true=1/false=0): " << endl;
  cin  >> allResponseClasses;
  cout << endl;

  if (!allResponseClasses) {
    
    cout << "Enter number of response classes: " << endl;
    cin >> numResponseClasses;
    cout << endl;

    if (numResponseClasses<1 || numResponseClasses>9) {
      cout << "Bad number of response classes to include!!\n";
      exit(1);
    }
    responseClasses.resize(numResponseClasses,0);
    char quest[30];
    for (int i=0; i<numResponseClasses; i++) {
      sprintf(quest,"Enter class #%i: ",i+1);
      cout << quest;
      cin >> responseClasses[i];
      cout << endl;
      
      if (responseClasses[i]<0 || responseClasses[i]>8) {
	cout << "You entered a non-existent response class!\n";
	exit(1);
      }
    }
    }*/


  int nRuns = 0;
  int runList[500];

  char temp[500];
  sprintf(temp, "%s/run_lists/Xenon_Calibration_Run_Period_%i.dat", getenv("ANALYSIS_CODE"),iXeRunPeriod);
  ifstream fileRuns(temp);

  int ii = 0;
  while (fileRuns >> runList[ii]) {
    ii++;
    nRuns++;
  }

  cout << "... Number of runs: " << nRuns << endl;
  for (int i=0; i<nRuns; i++) {
    cout << runList[i] << endl;
  }

  
  double xyBinWidth = 5.; //2.5;
  PositionMap posmap(xyBinWidth,50.);
  posmap.setRCflag(false); //telling the position map to not use the RC choices
  Int_t nBinsXY = posmap.getNbinsXY();
  

  // Open output ntuple
  string tempOutBase;
  string tempOut;
  //sprintf(tempOut, "position_map_%s.root", argv[1]);
  tempOutBase = "position_map_" + itos(iXeRunPeriod);
  /*if (!allResponseClasses) {
    tempOutBase+="_RC_";
    for (int i=0; i< numResponseClasses; i++) {
      tempOutBase+=itos(responseClasses[i]);
    }
    }*/
  tempOut =  getenv("POSITION_MAPS")+tempOutBase+"_"+ftos(xyBinWidth)+"mm.root";
  TFile *fileOut = new TFile(tempOut.c_str(),"RECREATE");

  // Output histograms
  int nPMT = 8;
  int nBinHist = 4100;//1025;

  TH1D *hisxy[nPMT][nBinsXY][nBinsXY];
  char *hisxyName = new char[10];

  for (int p=0; p<nPMT; p++) {
    for (int i=0; i<posmap.getNbinsXY(); i++) {
      for (int j=0; j<posmap.getNbinsXY(); j++) {
        if (p == 0)
          sprintf(hisxyName, "e0_%0.0f_%0.0f", posmap.getBinCenter(i), posmap.getBinCenter(j));
        if (p == 1)
          sprintf(hisxyName, "e1_%0.0f_%0.0f", posmap.getBinCenter(i), posmap.getBinCenter(j));
        if (p == 2)
          sprintf(hisxyName, "e2_%0.0f_%0.0f", posmap.getBinCenter(i), posmap.getBinCenter(j));
        if (p == 3)
          sprintf(hisxyName, "e3_%0.0f_%0.0f", posmap.getBinCenter(i), posmap.getBinCenter(j));
        if (p == 4)
          sprintf(hisxyName, "w0_%0.0f_%0.0f", posmap.getBinCenter(i), posmap.getBinCenter(j));
        if (p == 5)
          sprintf(hisxyName, "w1_%0.0f_%0.0f", posmap.getBinCenter(i), posmap.getBinCenter(j));
        if (p == 6)
          sprintf(hisxyName, "w2_%0.0f_%0.0f", posmap.getBinCenter(i), posmap.getBinCenter(j));
        if (p == 7)
          sprintf(hisxyName, "w3_%0.0f_%0.0f", posmap.getBinCenter(i), posmap.getBinCenter(j));

        hisxy[p][i][j] = new TH1D(hisxyName, "", nBinHist,-100.,4000.0);

      }
    }
  }

  // Loop through input ntuples
  char tempIn[500];
  for (int i=0; i<nRuns; i++) {

    // Open input ntuple
    sprintf(tempIn, "%s/replay_pass2_%i.root",getenv("REPLAY_PASS2"), runList[i]);
    DataTree *t = new DataTree();
    t->setupInputTree(std::string(tempIn),"pass2");

    if ( !t->inputTreeIsGood() ) { 
      std::cout << "Skipping " << tempIn << "... Doesn't exist or couldn't be opened.\n";
      continue;
    }

    int nEvents = t->getEntries();
    cout << "Processing " << runList[i] << " ... " << endl;
    cout << "... nEvents = " << nEvents << endl;


    // Loop over events
    for (int i=0; i<nEvents; i++) {
      t->getEvent(i);  

      // Select Type 0 events
      if (t->PID != 1) continue;
      if (t->Type != 0) continue;

      //Cut out clipped events
      if ( t->Side==0 && ( t->xE.nClipped>0 || t->yE.nClipped>0 || t->xeRC<1 || t->xeRC>4 || t->yeRC<1 || t->yeRC>4 ) ) continue;
      else if ( t->Side==1 && ( t->xW.nClipped>0 || t->yW.nClipped>0 || t->xwRC<1 || t->xwRC>4 || t->ywRC<1 || t->ywRC>4) ) continue;

		
      
      /*bool moveOnX = true, moveOnY=true; // Determining if the event is of the correct response class in x and y
     
	//Swank addition: Wire Chamber Response class. 
	for (int j=0; j<numResponseClasses; j++) {
	  if (t->xeRC == responseClasses[j]) {moveOnX=false;}
	  if (t->yeRC == responseClasses[j]) {moveOnY=false;}
	}
      
	if (moveOnX || moveOnY) continue;*/

      // Type 0 East Trigger
      int intBinX, intBinY; 
      
      if (t->Side == 0) {
	
	intBinX = posmap.getBinNumber(t->xE.center);
        intBinY = posmap.getBinNumber(t->yE.center);

        // Fill PMT histograms
        if (intBinX>-1 && intBinY>-1) hisxy[0][intBinX][intBinY]->Fill(t->ScintE.q1);
        if (intBinX>-1 && intBinY>-1) hisxy[1][intBinX][intBinY]->Fill(t->ScintE.q2);
        if (intBinX>-1 && intBinY>-1) hisxy[2][intBinX][intBinY]->Fill(t->ScintE.q3);
        if (intBinX>-1 && intBinY>-1) hisxy[3][intBinX][intBinY]->Fill(t->ScintE.q4);
      }

      // Type 0 West Trigger
      //moveOnX=moveOnY=true;
      else if (t->Side == 1) {

	//Swank Only Allow triangles!!!	  	
	//for (int j=0; j<numResponseClasses; j++) {
	// if (t->xwRC == responseClasses[j]) {moveOnX=false;}
	// if (t->ywRC == responseClasses[j]) {moveOnY=false;}
	//}
      
	//if (moveOnX || moveOnY) continue;
	
        intBinX = posmap.getBinNumber(t->xW.center);
        intBinY = posmap.getBinNumber(t->yW.center);

	// Fill PMT histograms 
        if (intBinX>-1 && intBinY>-1) hisxy[4][intBinX][intBinY]->Fill(t->ScintW.q1);
        if (intBinX>-1 && intBinY>-1) hisxy[5][intBinX][intBinY]->Fill(t->ScintW.q2);
        if (intBinX>-1 && intBinY>-1) hisxy[6][intBinX][intBinY]->Fill(t->ScintW.q3);
        if (intBinX>-1 && intBinY>-1) hisxy[7][intBinX][intBinY]->Fill(t->ScintW.q4);
      }


    }

    // Close input ntuple
    delete t;

  }


  //Rebinning the histograms based on the mean value...
  for (int p=0; p<nPMT; p++) {
    for (int i=0; i<nBinsXY; i++) {
      for (int j=0; j<nBinsXY; j++) {	

	hisxy[p][i][j]->GetXaxis()->SetRange(1,nBinHist);
	Double_t mean = hisxy[p][i][j]->GetMean();
	hisxy[p][i][j]->GetXaxis()->SetRange(0,nBinHist);
	double nGroup = 4.*mean/200.;
	nGroup = nGroup>1. ? nGroup : 1.;
	hisxy[p][i][j]->Rebin((int)nGroup);
	
      }
    }
  }

  // Extracting mean from 200 keV peak 

  // Define fit ranges
  double xLowBin[nPMT][nBinsXY][nBinsXY];
  double xHighBin[nPMT][nBinsXY][nBinsXY];
  double xLow[nPMT][nBinsXY][nBinsXY];
  double xHigh[nPMT][nBinsXY][nBinsXY];
  int maxBin[nPMT][nBinsXY][nBinsXY];
  double maxCounts[nPMT][nBinsXY][nBinsXY];
  double binCenterMax[nPMT][nBinsXY][nBinsXY];
  double meanVal[nPMT][nBinsXY][nBinsXY]; // Holds the mean of the distribution as defined by first fitting the peak
  double fitMean[nPMT][nBinsXY][nBinsXY]; // Holds the mean of the low energy peak
  double fitSigma[nPMT][nBinsXY][nBinsXY]; // Holds the sigma of the low energy peak
  double endpoint[nPMT][nBinsXY][nBinsXY]; // Holds the endpoint


  /////// First determine roughly where the low energy peak is
  TSpectrum *spec;

  for (int p=0; p<nPMT; p++) {
    for (int i=0; i<nBinsXY; i++) {
      for (int j=0; j<nBinsXY; j++) {	
	
	double r = sqrt(power(posmap.getBinCenter(j),2)+power(posmap.getBinCenter(i),2));
	
        // Find bin with maximum content
	hisxy[p][i][j]->GetXaxis()->SetRange(2,nBinHist);
        maxBin[p][i][j] = hisxy[p][i][j]->GetMaximumBin();
        maxCounts[p][i][j] = hisxy[p][i][j]->GetBinContent(maxBin[p][i][j]);
        binCenterMax[p][i][j] = hisxy[p][i][j]->GetBinCenter(maxBin[p][i][j]);
	
	  
	if (r<=(50.+2*xyBinWidth))
	      {
		spec = new TSpectrum(20);
		Int_t npeaks = spec->Search(hisxy[p][i][j],1.5,"",0.5);
		
		if (npeaks==0)
		  {
		    cout << "No peaks identified at PMT" << p << " position " << posmap.getBinCenter(i) << ", " << posmap.getBinCenter(j) << endl;
		  }
		else
		  {
		    Float_t *xpeaks = spec->GetPositionX(); // Note that newer versions of ROOT return a pointer to double...
		    TAxis *xaxis = (TAxis*)(hisxy[p][i][j]->GetXaxis());
		    Int_t peakBin=0;
		    Double_t BinSum=0.;
		    Double_t BinSumHold = 0.;
		    Int_t maxPeak=0.;
		    for (int pk=0;pk<npeaks;pk++) {
		      peakBin = xaxis->FindBin(xpeaks[pk]);
		      //Sum over 3 center bins of peak and compare to previos BinSum to see which peak is higher
		      BinSum = hisxy[p][i][j]->GetBinContent(peakBin) + hisxy[p][i][j]->GetBinContent(peakBin-1) + hisxy[p][i][j]->GetBinContent(peakBin+1);
		      if (BinSum>BinSumHold) {
			BinSumHold=BinSum;
			maxPeak=pk;
		      }
		    }
		    binCenterMax[p][i][j] = xpeaks[maxPeak];
		  }
		delete spec;
	      }
	xLow[p][i][j] = binCenterMax[p][i][j]*2./3.;
	xHigh[p][i][j] = 1.5*binCenterMax[p][i][j];

	
      }
    }
  }
  
  //////// Now fit the histograms for the peak

  for (int p=0; p<nPMT; p++) {
    for (int i=0; i<nBinsXY; i++) {
      for (int j=0; j<nBinsXY; j++) {	

	if ( hisxy[p][i][j]->Integral() > 500.) {// && r<=(50.+2*xBinWidth)) {

	  SinglePeakHist sing(hisxy[p][i][j], xLow[p][i][j], xHigh[p][i][j], true, 5, 0.8, 1.);

	  if (sing.isGoodFit() && sing.ReturnMean()>xLow[p][i][j] && sing.ReturnMean()<xHigh[p][i][j]) {
	    fitMean[p][i][j] = sing.ReturnMean();
	    fitSigma[p][i][j] = sing.ReturnSigma();
	  }

	  else  {
	    cout << "Can't converge on peak in PMT " << p << " at (" << posmap.getBinCenter(i) << ", " << posmap.getBinCenter(j) << "). Trying one more time......" << endl;
	    sing.SetRangeMin(xLow[p][i][j]);
	    sing.SetRangeMax(xHigh[p][i][j]);
	    sing.FitHist((double)maxBin[p][i][j], hisxy[p][i][j]->GetMean()/5., hisxy[p][i][j]->GetBinContent(maxBin[p][i][j]));

	    if (sing.isGoodFit() && sing.ReturnMean()>xLow[p][i][j] && sing.ReturnMean()<xHigh[p][i][j]) { 
	      fitMean[p][i][j] = sing.ReturnMean();
	      fitSigma[p][i][j] = sing.ReturnSigma();
	    }
	    else {
	      fitMean[p][i][j] = hisxy[p][i][j]->GetMean()/1.8;
	      int meanBin = hisxy[p][i][j]->GetXaxis()->FindBin(fitMean[p][i][j]);
	      int counts_check = hisxy[p][i][j]->GetBinContent(meanBin);
	      int counts = counts_check;
	      int bin=0;
	      if ( counts_check > 10 ) {
		while (counts>0.6*counts_check) {
		  bin++;
		  counts = hisxy[p][i][j]->GetBinContent(meanBin+bin);
		}
	      }
	  
	      xHighBin[p][i][j] = (meanBin+bin) < hisxy[p][i][j]->GetNbinsX()/3 ? (meanBin+bin): meanBin;
	      fitSigma[p][i][j] = hisxy[p][i][j]->GetBinCenter(xHighBin[p][i][j]) - fitMean[p][i][j];

	      cout << "Can't converge on peak in PMT " << p << " at bin (" << posmap.getBinCenter(i) << ", " << posmap.getBinCenter(j) << "). ";
	      cout << "**** replaced fit mean with hist_mean/1.8 " << fitMean[p][i][j] << endl;
	    }
	  }
	}
	else { 
	  fitMean[p][i][j] = hisxy[p][i][j]->GetMean()/1.8;
	  //if ( fitMean[p][i][j]>xLow[p][i][j] && fitMean[p][i][j]<xHigh[p][i][j] ) 
	  cout << "**** replaced fit mean with hist_mean/1.8 " << fitMean[p][i][j] << endl;
	  //else { 
	  //fitMean[p][i][j] = binCenterMax[p][i][j];
	  //cout << "**** replaced fit mean with binCenterMax " << fitMean[p][i][j] << endl;
	  //}
	  int meanBin = hisxy[p][i][j]->GetXaxis()->FindBin(fitMean[p][i][j]);
	  int counts_check = hisxy[p][i][j]->GetBinContent(meanBin);
	  int counts = counts_check;
	  int bin=0;
	  double frac = exp(-1/2.); // This should be the fraction of events for a gaussian at 1 sigma
	  if ( counts_check > 10 ) {
	    while (counts>frac*counts_check) {
	      bin++;
	      counts = hisxy[p][i][j]->GetBinContent(meanBin+bin);
	    }
	  }	  
	  xHighBin[p][i][j] = (meanBin+bin) < hisxy[p][i][j]->GetNbinsX()/3 ? (meanBin+bin): meanBin;
	  fitSigma[p][i][j] = hisxy[p][i][j]->GetBinCenter(xHighBin[p][i][j]) - fitMean[p][i][j];	 
	}

      }
    }
  }

  fileOut->Write(); // Writing the histograms with the peaks to file

  ////////// Now determine the mean of the Xe distribution in every position bin above the peak to avoid
  ////////// trigger effects
  
  double nSigmaFromMean = 1.5; // This is how far over from the peak we are starting the sum of the spectra

  for (int p=0; p<nPMT; p++) {
    for (int i=0; i<nBinsXY; i++) {
      for (int j=0; j<nBinsXY; j++) {

	hisxy[p][i][j]->GetXaxis()->SetRange(hisxy[p][i][j]->GetXaxis()->FindBin(fitMean[p][i][j]+nSigmaFromMean*fitSigma[p][i][j]), hisxy[p][i][j]->GetNbinsX()-1);
	meanVal[p][i][j] = hisxy[p][i][j]->GetMean();
	hisxy[p][i][j]->GetXaxis()->SetRange(0, hisxy[p][i][j]->GetNbinsX()); // Set the range back to the full range

      }
    }
  }

  ////////// Now determine the endpoint of the Xe distribution in every position bin

  double lowerBoundMult = 1.;
  double upperBoundMult = 2.;

  TFile *epfile = new TFile(TString::Format("%s/%s_%smm_endpoints.root",getenv("POSITION_MAPS"),tempOutBase.c_str(),ftos(xyBinWidth).c_str()),"RECREATE");

  TGraphErrors epgraph;
  
  KurieFitter kf;
  
  for (int p=0; p<nPMT; p++) {
    for (int i=0; i<nBinsXY; i++) {
      for (int j=0; j<nBinsXY; j++) {

	kf.FitSpectrum(hisxy[p][i][j], lowerBoundMult*meanVal[p][i][j], upperBoundMult*meanVal[p][i][j], 1.);
	endpoint[p][i][j] = kf.returnK0();

	epgraph = kf.returnKuriePlot();
	epgraph.SetName(TString::Format("pmt%i_x%0.1f_y%0.1f",p,posmap.getBinCenter(i), posmap.getBinCenter(j)));
	epgraph.Write();

      }
    }
  }

  delete epfile;
  delete fileOut;


  ///////////////////////// Extract position maps for meanVal ///////////////////////////////
  double norm[nPMT];
  for (int p=0; p<nPMT; p++) {
    norm[p] = meanVal[p][nBinsXY/2][nBinsXY/2];
    cout << norm[p] << endl;
  }

  //Checking for weird outliers
  for (int p=0; p<nPMT; p++) {
    for (int i=0; i<nBinsXY; i++) {
      for (int j=0; j<nBinsXY; j++) {
	
	if ( meanVal[p][i][j]<(0.1*norm[p]) || meanVal[p][i][j]>(8.*norm[p]) ) 
	  meanVal[p][i][j] = (0.1*norm[p]);

      }
    }
  }

  double positionMap[nPMT][nBinsXY][nBinsXY];
  for (int p=0; p<nPMT; p++) {
    for (int i=0; i<nBinsXY; i++) {
      for (int j=0; j<nBinsXY; j++) {
        positionMap[p][i][j] = meanVal[p][i][j] / norm[p];
      }
    }
  }

  // Write position maps to file
  TString mapFile = TString::Format("%s/%s_%0.1fmm.dat", getenv("POSITION_MAPS"),tempOutBase.c_str(),xyBinWidth);
  ofstream outMap(mapFile.Data());

  for (int i=0; i<nBinsXY; i++) {
    for (int j=0; j<nBinsXY; j++) {
      outMap << posmap.getBinCenter(i) << "  "
             << posmap.getBinCenter(j) << "  "
             << positionMap[0][i][j] << "  "
             << positionMap[1][i][j] << "  "
             << positionMap[2][i][j] << "  "
             << positionMap[3][i][j] << "  "
             << positionMap[4][i][j] << "  "
             << positionMap[5][i][j] << "  "
             << positionMap[6][i][j] << "  "
             << positionMap[7][i][j] << endl;
    }
  }
  outMap.close();

  // Write norms to file
  TString normFile = TString::Format("%s/norm_%s_%0.1fmm.dat", getenv("POSITION_MAPS"),tempOutBase.c_str(),xyBinWidth);
  ofstream outNorm(normFile.Data());

  for (int p=0; p<nPMT; p++) {
    outNorm << norm[p] << endl;
  }
  outNorm.close();

  ///////////////////////// Extract position maps for peaks ///////////////////////////////

  for (int p=0; p<nPMT; p++) {
    norm[p] = fitMean[p][nBinsXY/2][nBinsXY/2];
    cout << norm[p] << endl;
  }

  //Checking for weird outliers
  for (int p=0; p<nPMT; p++) {
    for (int i=0; i<nBinsXY; i++) {
      for (int j=0; j<nBinsXY; j++) {
	
	if ( fitMean[p][i][j]<(0.1*norm[p]) || fitMean[p][i][j]>(8.*norm[p]) ) 
	  fitMean[p][i][j] = (0.1*norm[p]);

      }
    }
  }

  for (int p=0; p<nPMT; p++) {
    for (int i=0; i<nBinsXY; i++) {
      for (int j=0; j<nBinsXY; j++) {
        positionMap[p][i][j] = fitMean[p][i][j] / norm[p];
      }
    }
  }

  // Write position maps to file
  mapFile = TString::Format("%s/%s_%0.1fmm_peakFits.dat", getenv("POSITION_MAPS"),tempOutBase.c_str(),xyBinWidth);
  outMap.open(mapFile.Data());
  

  for (int i=0; i<nBinsXY; i++) {
    for (int j=0; j<nBinsXY; j++) {
      outMap << posmap.getBinCenter(i) << "  "
             << posmap.getBinCenter(j) << "  "
             << positionMap[0][i][j] << "  "
             << positionMap[1][i][j] << "  "
             << positionMap[2][i][j] << "  "
             << positionMap[3][i][j] << "  "
             << positionMap[4][i][j] << "  "
             << positionMap[5][i][j] << "  "
             << positionMap[6][i][j] << "  "
             << positionMap[7][i][j] << endl;
    }
  }
  outMap.close();


  ///////////////////////// Extract position maps for endpoints ///////////////////////////////

  for (int p=0; p<nPMT; p++) {
    norm[p] = endpoint[p][nBinsXY/2][nBinsXY/2];
    cout << norm[p] << endl;
  }

  //Checking for weird outliers
  for (int p=0; p<nPMT; p++) {
    for (int i=0; i<nBinsXY; i++) {
      for (int j=0; j<nBinsXY; j++) {
	
	if ( endpoint[p][i][j]<(0.1*norm[p]) || endpoint[p][i][j]>(8.*norm[p]) ) 
	  endpoint[p][i][j] = (0.1*norm[p]);

      }
    }
  }

  for (int p=0; p<nPMT; p++) {
    for (int i=0; i<nBinsXY; i++) {
      for (int j=0; j<nBinsXY; j++) {
        positionMap[p][i][j] = endpoint[p][i][j] / norm[p];
      }
    }
  }

  // Write position maps to file
  mapFile = TString::Format("%s/%s_%0.1fmm_endpoints.dat", getenv("POSITION_MAPS"),tempOutBase.c_str(),xyBinWidth);
  outMap.open(mapFile.Data());

  for (int i=0; i<nBinsXY; i++) {
    for (int j=0; j<nBinsXY; j++) {
      outMap << posmap.getBinCenter(i) << "  "
             << posmap.getBinCenter(j) << "  "
             << positionMap[0][i][j] << "  "
             << positionMap[1][i][j] << "  "
             << positionMap[2][i][j] << "  "
             << positionMap[3][i][j] << "  "
             << positionMap[4][i][j] << "  "
             << positionMap[5][i][j] << "  "
             << positionMap[6][i][j] << "  "
             << positionMap[7][i][j] << endl;
    }
  }
  outMap.close();



  return 0;
}
Example #25
0
void YieldStudies(TString inputPP="hPtSpectrumDzeroPP.root",TString inputPPMC="hPtSpectrumDzeroPPMCClosure.root")
{
  gStyle->SetOptTitle(0);
  gStyle->SetOptStat(0);
  gStyle->SetEndErrorSize(0);
  gStyle->SetMarkerStyle(20);


  TFile* filesPP=new TFile(inputPP.Data());
  TFile* filesPPMC=new TFile(inputPPMC.Data());
  TH1D* hMeanPP=(TH1D*)filesPP->Get("hMean");
  TH1D* hMeanPPMC=(TH1D*)filesPPMC->Get("hMean");
  TH1D* hSigmaGaus1PP=(TH1D*)filesPP->Get("hSigmaGaus1");
  TH1D* hSigmaGaus1PPMC=(TH1D*)filesPPMC->Get("hSigmaGaus1");
  TH1D* hSigmaGaus2PP=(TH1D*)filesPP->Get("hSigmaGaus2");
  TH1D* hSigmaGaus2PPMC=(TH1D*)filesPPMC->Get("hSigmaGaus2");
  TH1D* hRelMagnGaus1Gaus2PP=(TH1D*)filesPP->Get("hRelMagnGaus1Gaus2");
  TH1D* hRelMagnGaus1Gaus2PPMC=(TH1D*)filesPPMC->Get("hRelMagnGaus1Gaus2");
  
  TH1D* hClosure=(TH1D*)filesPPMC->Get("hPtCor");
  TH1D* hPtGen=(TH1D*)filesPPMC->Get("hPtGen");
  hClosure->Sumw2();
  hClosure->Divide(hPtGen);


  TH2F* hemptySigma1=new TH2F("hemptySigma1","",50,0.,100.,10.,0.,0.1);  
  hemptySigma1->GetXaxis()->CenterTitle();
  hemptySigma1->GetYaxis()->CenterTitle();
  hemptySigma1->GetXaxis()->SetTitle("p_{T} (GeV/c)");
  hemptySigma1->GetYaxis()->SetTitle("#sigma_{1} (GeV/c^{2})");
  hemptySigma1->GetXaxis()->SetTitleOffset(1.);
  hemptySigma1->GetYaxis()->SetTitleOffset(1.4);
  hemptySigma1->GetXaxis()->SetTitleSize(0.045);
  hemptySigma1->GetYaxis()->SetTitleSize(0.05);
  hemptySigma1->GetXaxis()->SetTitleFont(42);
  hemptySigma1->GetYaxis()->SetTitleFont(42);
  hemptySigma1->GetXaxis()->SetLabelFont(42);
  hemptySigma1->GetYaxis()->SetLabelFont(42);
  hemptySigma1->GetXaxis()->SetLabelSize(0.04);
  hemptySigma1->GetYaxis()->SetLabelSize(0.04);  
 
  TH2F* hemptyRelMag=new TH2F("hemptyRelMag","",50,0.,100.,10.,0.,0.3);  
  hemptyRelMag->GetXaxis()->CenterTitle();
  hemptyRelMag->GetYaxis()->CenterTitle();
  hemptyRelMag->GetXaxis()->SetTitle("p_{T} (GeV/c)");
  hemptyRelMag->GetYaxis()->SetTitle("norm(#sigma_1)/norm(#sigma_1)+norm(#sigma_2)");
  hemptyRelMag->GetXaxis()->SetTitleOffset(1.);
  hemptyRelMag->GetYaxis()->SetTitleOffset(1.4);
  hemptyRelMag->GetXaxis()->SetTitleSize(0.045);
  hemptyRelMag->GetYaxis()->SetTitleSize(0.05);
  hemptyRelMag->GetXaxis()->SetTitleFont(42);
  hemptyRelMag->GetYaxis()->SetTitleFont(42);
  hemptyRelMag->GetXaxis()->SetLabelFont(42);
  hemptyRelMag->GetYaxis()->SetLabelFont(42);
  hemptyRelMag->GetXaxis()->SetLabelSize(0.04);
  hemptyRelMag->GetYaxis()->SetLabelSize(0.04);  

  TH2F* hemptySigma2=new TH2F("hemptySigma2","",50,0.,100.,10.,0.,0.03);  
  hemptySigma2->GetXaxis()->CenterTitle();
  hemptySigma2->GetYaxis()->CenterTitle();
  hemptySigma2->GetXaxis()->SetTitle("p_{T} (GeV/c)");
  hemptySigma2->GetYaxis()->SetTitle("#sigma_{2} (GeV/c^{2})");
  hemptySigma2->GetXaxis()->SetTitleOffset(1.);
  hemptySigma2->GetYaxis()->SetTitleOffset(1.4);
  hemptySigma2->GetXaxis()->SetTitleSize(0.045);
  hemptySigma2->GetYaxis()->SetTitleSize(0.05);
  hemptySigma2->GetXaxis()->SetTitleFont(42);
  hemptySigma2->GetYaxis()->SetTitleFont(42);
  hemptySigma2->GetXaxis()->SetLabelFont(42);
  hemptySigma2->GetYaxis()->SetLabelFont(42);
  hemptySigma2->GetXaxis()->SetLabelSize(0.04);
  hemptySigma2->GetYaxis()->SetLabelSize(0.04);  
  
  TH2F* hemptyMean=new TH2F("hemptyMean","",50,0.,110.,10.,1.855,1.88);  
  hemptyMean->GetXaxis()->CenterTitle();
  hemptyMean->GetYaxis()->CenterTitle();
  hemptyMean->GetXaxis()->SetTitle("p_{T} (GeV/c)");
  hemptyMean->GetYaxis()->SetTitle("Mean (GeV/c^{2})");
  hemptyMean->GetXaxis()->SetTitleOffset(1.);
  hemptyMean->GetYaxis()->SetTitleOffset(1.4);
  hemptyMean->GetXaxis()->SetTitleSize(0.045);
  hemptyMean->GetYaxis()->SetTitleSize(0.05);
  hemptyMean->GetXaxis()->SetTitleFont(42);
  hemptyMean->GetYaxis()->SetTitleFont(42);
  hemptyMean->GetXaxis()->SetLabelFont(42);
  hemptyMean->GetYaxis()->SetLabelFont(42);
  hemptyMean->GetXaxis()->SetLabelSize(0.04);
  hemptyMean->GetYaxis()->SetLabelSize(0.04);  

  TCanvas* cYields = new TCanvas("cYields","",1000,1000);
  cYields->Divide(2,2);
  cYields->cd(1);
  hemptyMean->Draw();
  hMeanPP->SetLineWidth(2);
  hMeanPP->Draw("same");
  hMeanPPMC->SetLineColor(2);
  hMeanPPMC->SetLineWidth(2);
  hMeanPPMC->Draw("same");
  TLegend *legendMean=new TLegend(0.4958166,0.7558707,0.7949297,0.9299148,"");
  legendMean->SetBorderSize(0);
  legendMean->SetLineColor(0);
  legendMean->SetFillColor(0);
  legendMean->SetFillStyle(1001);
  legendMean->SetTextFont(42);
  legendMean->SetTextSize(0.045);
  TLegendEntry *ent_MeanPP=legendMean->AddEntry(hMeanPP,"Data","pf");
  ent_MeanPP->SetTextFont(42);
  ent_MeanPP->SetLineColor(1);
  TLegendEntry *ent_MeanPPMC=legendMean->AddEntry(hMeanPPMC,"MC","pf");
  ent_MeanPPMC->SetTextFont(42);
  ent_MeanPPMC->SetLineColor(2);
  legendMean->Draw("same");
  TLine* l = new TLine(5,1.865,100,1.865);
  l->SetLineWidth(2);
  l->SetLineStyle(2);
  l->Draw();
  cYields->cd(2);
  hemptySigma1->Draw();
  hSigmaGaus1PP->SetLineWidth(2);
  hSigmaGaus1PP->Draw("same");
  hSigmaGaus1PPMC->SetLineColor(2);
  hSigmaGaus1PPMC->SetLineWidth(2);
  hSigmaGaus1PPMC->Draw("same");
  TLegend *legendSigma1=new TLegend(0.4958166,0.7558707,0.7949297,0.9299148,"");
  legendSigma1->SetBorderSize(0);
  legendSigma1->SetLineColor(0);
  legendSigma1->SetFillColor(0);
  legendSigma1->SetFillStyle(1001);
  legendSigma1->SetTextFont(42);
  legendSigma1->SetTextSize(0.045);
  TLegendEntry *ent_Sigma1PP=legendSigma1->AddEntry(hSigmaGaus1PP,"Data","pf");
  ent_Sigma1PP->SetTextFont(42);
  ent_Sigma1PP->SetLineColor(1);
  TLegendEntry *ent_Sigma1PPMC=legendSigma1->AddEntry(hSigmaGaus1PPMC,"MC","pf");
  ent_Sigma1PPMC->SetTextFont(42);
  ent_Sigma1PPMC->SetLineColor(2);
  legendSigma1->Draw("same");

  cYields->cd(3);
  hemptySigma2->Draw();
  hSigmaGaus2PP->SetLineWidth(2);
  hSigmaGaus2PP->Draw("same");
  hSigmaGaus2PPMC->SetLineColor(2);
  hSigmaGaus2PPMC->SetLineWidth(2);
  hSigmaGaus2PPMC->Draw("same");
  TLegend *legendSigma2=new TLegend(0.4958166,0.7558707,0.7949297,0.9299148,"");
  legendSigma2->SetBorderSize(0);
  legendSigma2->SetLineColor(0);
  legendSigma2->SetFillColor(0);
  legendSigma2->SetFillStyle(1001);
  legendSigma2->SetTextFont(42);
  legendSigma2->SetTextSize(0.045);
  TLegendEntry *ent_Sigma2PP=legendSigma2->AddEntry(hSigmaGaus2PP,"Data","pf");
  ent_Sigma2PP->SetTextFont(42);
  ent_Sigma2PP->SetLineColor(1);
  TLegendEntry *ent_Sigma2PPMC=legendSigma2->AddEntry(hSigmaGaus2PPMC,"MC","pf");
  ent_Sigma2PPMC->SetTextFont(42);
  ent_Sigma2PPMC->SetLineColor(2);
  legendSigma2->Draw("same");
  cYields->cd(4);
  hemptyRelMag->Draw();
  hRelMagnGaus1Gaus2PP->SetLineWidth(2);
  hRelMagnGaus1Gaus2PP->Draw("same");
  
  TH2F* hemptyClosure=new TH2F("hemptyClosure","",50,0.,100.,10.,0.7,1.3);  
  hemptyClosure->GetXaxis()->CenterTitle();
  hemptyClosure->GetYaxis()->CenterTitle();
  hemptyClosure->GetXaxis()->SetTitle("p_{T} (GeV/c)");
  hemptyClosure->GetYaxis()->SetTitle("Corr. yield/Gen");
  hemptyClosure->GetXaxis()->SetTitleOffset(1.);
  hemptyClosure->GetYaxis()->SetTitleOffset(1.4);
  hemptyClosure->GetXaxis()->SetTitleSize(0.045);
  hemptyClosure->GetYaxis()->SetTitleSize(0.05);
  hemptyClosure->GetXaxis()->SetTitleFont(42);
  hemptyClosure->GetYaxis()->SetTitleFont(42);
  hemptyClosure->GetXaxis()->SetLabelFont(42);
  hemptyClosure->GetYaxis()->SetLabelFont(42);
  hemptyClosure->GetXaxis()->SetLabelSize(0.04);
  hemptyClosure->GetYaxis()->SetLabelSize(0.04);  
  cYields->SaveAs("cYieldStudies.pdf");
  
  TCanvas* cClosure = new TCanvas("cClosure","",500,500);
  cClosure->cd(1);
  hemptyClosure->Draw();
  hClosure->SetLineWidth(2);
  hClosure->Draw("same");
  TLine* lunity = new TLine(5,1,100,1);
  lunity->SetLineWidth(2);
  lunity->SetLineStyle(2);
  lunity->Draw("same");
  cClosure->SaveAs("cClosure.pdf");

  }
Example #26
0
plotLimits(string filename, TString name, TString channel, TString lepton){



TGraph * limit_obs = new TGraph();
  TGraph * limit_exp = new TGraph();
  TGraphAsymmErrors * band_exp1 = new TGraphAsymmErrors();
  TGraphAsymmErrors * band_exp2 = new TGraphAsymmErrors();

TGraph *theory = new TGraph();
theory->SetPoint(0, 1000, 1.3*79.44234);
theory->SetPoint(1, 1500, 1.3*14.73114);
theory->SetPoint(2, 2000, 1.3*3.75938);
theory->SetPoint(3, 2500, 1.3*1.10833);
theory->SetPoint(4, 3000, 1.3*0.35676);
theory->SetPoint(5, 4000, 1.3*0.04393);

ifstream infile(filename.c_str());

gROOT->LoadMacro("CMS_lumi.C");

double mass, exp, obs, up1, up2, dn1, dn2;
int point = 0;

while (!infile.eof()){

	infile >> mass >> obs >> exp >>  dn2 >> up2 >> dn1 >> up1;


        cout << mass << " & " << obs << " & " << exp << " & " << "["<<dn1<<", "<<up1<<"] & ["<<dn2<<", "<<up2<<"] \\" << endl;


	limit_obs->SetPoint(point, mass, obs);
    limit_exp->SetPoint(point, mass, exp);
    band_exp1->SetPoint(point, mass, exp);
    band_exp2->SetPoint(point, mass, exp);

    band_exp1->SetPointEYhigh(point, up1 - exp);
    band_exp1->SetPointEYlow(point, exp - dn1);
    band_exp2->SetPointEYhigh(point, up2 - exp);
    band_exp2->SetPointEYlow(point, exp - dn2);
    point++;

}

double max = 200000.0; //band_exp2->GetHistogram()->GetMaximum()*50;

  TCanvas *canvas = new TCanvas(Form("limit set %s",name.Data()),Form("limit set %s",name.Data()), 500,500);

  limit_exp->SetMinimum(0.01);
  limit_exp->Draw("AL");
  limit_exp->GetXaxis()->SetTitle("M_{Z'} [GeV]");
  limit_exp->GetYaxis()->SetTitle("95 % CL limit on #sigma(Z') [pb]");
  limit_exp->GetYaxis()->SetRangeUser(0.01,2000);

  band_exp2->SetFillColor(5);
  band_exp2->SetLineColor(0);
  //band_exp2->SetFillStyle(4000);
  band_exp2->Draw("3same");

  band_exp1->SetFillColor(3);
  band_exp1->SetLineColor(0);
  //band_exp1->SetFillStyle(4000);
  band_exp1->Draw("3same");

  limit_obs->Draw("Lsame");
  limit_obs->SetLineWidth(2);
  limit_obs->SetMarkerSize(1.0);
  limit_obs->SetMarkerStyle(20);
   
  limit_exp->Draw("Lsame");
  limit_exp->SetLineStyle(2);
  limit_exp->SetLineWidth(2);
  limit_exp->SetMarkerSize(1.0);
  limit_exp->SetMaximum(max);
  limit_exp->SetMinimum(0.001);
  limit_exp->SetMarkerStyle(20);

  double x1 = 595; 
  double y1 = 1.0;
  double x2 = 905;
  double y2 = 1.0;
  TLine * line = new TLine(x1, y1, x2, y2);
  theory->SetLineColor(2);
  theory->SetLineWidth(2);
  theory->Draw("same");

  



  //Legend
  TLegend *l = new TLegend(0.57,0.62,0.88,0.88);
  l->AddEntry(limit_obs,"Observed", "L");
  l->AddEntry(limit_exp,"Expected", "L");
  l->AddEntry(band_exp1,"#pm1 #sigma Exp.", "F");
  l->AddEntry(band_exp2,"#pm2 #sigma Exp.", "F");
  l->AddEntry(theory, "Z' (30% Width)", "L");
  l->SetFillColor(0);
  l->SetLineColor(0);
  l->Draw();

  TLatex * label = new TLatex();
  label->SetNDC();
  //label->DrawLatex(0.2,0.86,"CMS Preliminary, 19.7 fb^{-1}");
  //label->DrawLatex(0.2,0.80,"#sqrt{s} = 8 TeV");
  //label->DrawLatex(0.6,0.80, Form("BR(b'#rightarrow %s) = 1", channel.Data()));
  //label->DrawLatex(0.55,0.80, "BR(b'#rightarrow tW) = 0.5");
  //label->DrawLatex(0.55,0.74, "BR(b'#rightarrow bH) = 0.25");
  //label->DrawLatex(0.55,0.68, "BR(b'#rightarrow bZ) = 0.25");
  //label->DrawLatex(0.2,0.74, lepton.Data());

  canvas->SetLogy(1);
  CMS_lumi(canvas, 4, 10);

  canvas->Print(Form("%s_limit.pdf",name.Data()));
  //canvas->Print(Form("%s_limit.png",name.Data()));

}
Example #27
0
//--------------------------------------------------------------------------------------------------
void runH2gSkim(const char *fileset    = "",
		const char *skim       = "noskim",
		const char *dataset    = "f11--h120gg-gf-v14b-pu",
		const char *book       = "cern/filefi/025",
		const char *catalogDir = "/home/mitprod/catalog",
		const char *outputName = "h2g",
		int         nEvents    = -1)
{
  //------------------------------------------------------------------------------------------------
  // some parameters get passed through the environment
  //------------------------------------------------------------------------------------------------
  char json[1024], overlap[1024];
  float overlapCut = -1;

  if (gSystem->Getenv("MIT_PROD_JSON"))
    sprintf(json,   "%s",gSystem->Getenv("MIT_PROD_JSON"));
  else {
    sprintf(json, "%s", "~");
    //printf(" JSON file was not properly defined. EXIT!\n");
    //return;
  } 

  TString jsonFile = TString("/home/cmsprod/cms/json/") + TString(json);
  Bool_t  isData   = ( (jsonFile.CompareTo("/home/cmsprod/cms/json/~") != 0) );
  
  if (gSystem->Getenv("MIT_PROD_OVERLAP")) {
    sprintf(overlap,"%s",gSystem->Getenv("MIT_PROD_OVERLAP"));
    if (EOF == sscanf(overlap,"%f",&overlapCut)) {
      printf(" Overlap was not properly defined. EXIT!\n");
      return;
    }
  }
  else {
     sprintf(overlap,"%s", "-1.0");
    //printf(" OVERLAP file was not properly defined. EXIT!\n");
    //return;
  } 

  printf("\n Initialization worked. \n\n");

  //------------------------------------------------------------------------------------------------
  // some global setups
  //------------------------------------------------------------------------------------------------
  using namespace mithep;
  gDebugMask  = Debug::kGeneral;
  gDebugLevel = 3;

  //------------------------------------------------------------------------------------------------
  // set up information
  //------------------------------------------------------------------------------------------------
  RunLumiSelectionMod *runLumiSel = new RunLumiSelectionMod;
  runLumiSel->SetAcceptMC(kTRUE);                          // Monte Carlo events are always accepted

  
  // only select on run- and lumisection numbers when valid json file present
  if ((jsonFile.CompareTo("/home/cmsprod/cms/json/~") != 0) &&
      (jsonFile.CompareTo("/home/cmsprod/cms/json/-") != 0)   ) {
    runLumiSel->AddJSONFile(jsonFile.Data());
  }
  if ((jsonFile.CompareTo("/home/cmsprod/cms/json/-") == 0)   ) {
    printf("\n WARNING -- Looking at data without JSON file: always accept.\n\n");
    runLumiSel->SetAbortIfNotAccepted(kFALSE);   // accept all events if there is no valid JSON file
  }


  TwoPhotonSelMod *twophotonsel = new TwoPhotonSelMod;
  twophotonsel->SetPtMin(20.);
  twophotonsel->SetMassMin(55.);

  MCParticleSelMod *mcselmod  = new MCParticleSelMod;
  mcselmod->AddAbsPdgId(11);
  mcselmod->AddAbsPdgId(12);
  mcselmod->AddAbsPdgId(13);
  mcselmod->AddAbsPdgId(14);
  mcselmod->AddAbsPdgId(15);
  mcselmod->AddAbsPdgId(16);
  mcselmod->AddAbsPdgId(23);
  mcselmod->AddAbsPdgId(24);
  mcselmod->AddAbsPdgId(25);


  SkimMod<MCParticle> *skimMod = 0;
  if (! isData) {
    skimMod = new SkimMod<MCParticle>;
    skimMod->SetBranchName("MCParticles");
  }

  OutputMod *outMod = new OutputMod;
  outMod->Keep("*");
  outMod->Drop("CaloTowers");
  outMod->Drop("MCParticles");
  outMod->Drop("*Jets*");
  outMod->Keep("AKT5GenJets");
  outMod->Keep("AKt5PFJets");

  if (! isData)
    outMod->AddNewBranch("SkmMCParticles");


  TString skmRootFile = TString(outputName);
  skmRootFile += TString("_") + TString(dataset) + TString("_") + TString(skim);
  if (TString(fileset) != TString(""))
    skmRootFile += TString("_") + TString(fileset);
  outMod->SetFileName(skmRootFile);
  outMod->SetPathName(".");


  //------------------------------------------------------------------------------------------------
  // making analysis chain
  //------------------------------------------------------------------------------------------------
  // this is how it always starts
  runLumiSel      ->Add(twophotonsel);

  if (isData) { 
    twophotonsel  ->Add(outMod);
  }
  else {
    twophotonsel  ->Add(mcselmod);
    mcselmod      ->Add(skimMod);
    skimMod       ->Add(outMod);  
  }
  
  //------------------------------------------------------------------------------------------------
  // setup analysis
  //------------------------------------------------------------------------------------------------
  Analysis *ana = new Analysis;
  ana->SetUseHLT       (kTRUE);
  ana->SetKeepHierarchy(kTRUE);
  ana->SetSuperModule  (runLumiSel);
  ana->SetPrintScale   (100);
  if (nEvents >= 0)
    ana->SetProcessNEvents(nEvents);

  //------------------------------------------------------------------------------------------------
  // organize input
  //------------------------------------------------------------------------------------------------
  Catalog *c = new Catalog(catalogDir);
  TString skimdataset = TString(dataset)+TString("/") +TString(skim);
  Dataset *d = NULL;
  TString bookstr = book;
  if (TString(skim).CompareTo("noskim") == 0)
    d = c->FindDataset(bookstr,dataset,fileset);
  else 
    d = c->FindDataset(bookstr,skimdataset.Data(),fileset);
  ana->AddDataset(d);
  
  //------------------------------------------------------------------------------------------------
  // organize output
  //------------------------------------------------------------------------------------------------
  TString rootFile = TString(outputName);
  rootFile += TString("_") + TString(dataset) + TString("_") + TString(skim);
  if (TString(fileset) != TString(""))
    rootFile += TString("_") + TString(fileset);
  rootFile += TString(".root");
  //ana->SetOutputName(rootFile.Data());
  //ana->SetCacheSize(64*1024*1024);
  //ana->SetCacheSize(0);

  ana->SetOutputName("test.root");
  
  //------------------------------------------------------------------------------------------------
  // Say what we are doing
  //------------------------------------------------------------------------------------------------
  printf("\n==== PARAMETER SUMMARY FOR THIS JOB ====\n");
  printf("\n JSON file: %s\n  and overlap cut: %f (%s)\n",jsonFile.Data(),overlapCut,overlap);
  printf("\n Rely on Catalog: %s\n",catalogDir);
  printf("  -> Book: %s  Dataset: %s  Skim: %s  Fileset: %s <-\n",book,dataset,skim,fileset);
  printf("\n Root output: %s\n\n",rootFile.Data());  
  printf("\n========================================\n");

  //------------------------------------------------------------------------------------------------
  // run the analysis after successful initialisation
  //------------------------------------------------------------------------------------------------
  ana->Run(!gROOT->IsBatch());

  return;
}
Example #28
0
{    
  TString rfitpath("/afs/cern.ch/cms/slc5_amd64_gcc462/lcg/roofit/5.34.02-cms/include");
  TString path = gSystem->GetIncludePath();
  path += "-I. -I$ROOTSYS/src -I";
  path += rfitpath;
  gSystem->SetIncludePath(path.Data());
  
  gROOT->Macro("Utils/RooVoigtianShape.cc+");
  gROOT->Macro("Utils/RooCMSShape.cc+");
  
  gROOT->Macro("Utils/CPlot.cc++");
  gROOT->Macro("Utils/MitStyleRemix.cc++");  
  // Show which process needs debugging
  gInterpreter->ProcessLine(".! ps |grep root.exe");
}
Example #29
0
void combinefiles(const TString input="temp.txt",
                  const TString outputfile="test.root") {

    // read input file
    TChain *eventChain = new TChain("Events");
    TChain *countChain = new TChain("Count");

    ifstream ifs;
    ifs.open(input.Data());
    assert(ifs.is_open());
    string line;
    getline(ifs,line);
    while(getline(ifs,line)) {
        eventChain->Add(TString(line));
        countChain->Add(TString(line));
    }
    ifs.close();

    Int_t iHmatch1=-1, iHmatch2=-1, iHmatch3=-1, iHmatch4=-1;
    Int_t eventType;
    Int_t genInfo;
    Float_t eventWeight;
    Int_t sampleNo;
    Int_t isBBTT;
    Int_t isBBGG;
    Int_t isBBBB;
    Int_t isVBFTT;
    Int_t isVBF4B;
    Float_t met, metPhi;
    Float_t ppMet, ppMetPhi;
    Float_t pileupMet, pileupMetPhi;
    Int_t nCentral=0, nBtag=0;
    Int_t centB=0;
    Int_t nJets=0;

    Int_t tauCat1=0, tauCat2=0;
    Int_t bTag1=0, bTag2=0, bTag3=0, bTag4=0;
    Int_t jbTag_tt1=0, jbTag_tt2=0, jbTag_6j1=0, jbTag_6j2=0;

    Double_t mt2=0;
    Double_t mt2puppi=0;
    Double_t mt2pileup=0;
    Double_t m_sv=0;
    Double_t m_svpileup=0;
    Double_t m_svpuppi=0;

    Float_t ptTau1, ptTau2, ptTrk1, ptTrk2, ptB1, ptB2, ptB3, ptB4, ptG1, ptG2, ptJet_tt1, ptJet_tt2, ptJet_6j1, ptJet_6j2, tauIso1, tauIso2;
    Float_t etaTau1, etaTau2, etaTrk1, etaTrk2, etaB1, etaB2, etaB3, etaB4, etaG1, etaG2, etaJet_tt1, etaJet_tt2, etaJet_6j1, etaJet_6j2;
    Float_t phiTau1, phiTau2, phiTrk1, phiTrk2, phiB1, phiB2, phiB3, phiB4, phiG1, phiG2, phiJet_tt1, phiJet_tt2, phiJet_6j1, phiJet_6j2;
    Float_t mTau1, mTau2, mTrk1, mTrk2, mB1, mB2, mB3, mB4, eG1, eG2, mJet_tt1, mJet_tt2, mJet_6j1, mJet_6j2;

    Float_t ptTau1_gen, ptTau2_gen, ptB1_gen, ptB2_gen, ptB3_gen, ptB4_gen, ptG1_gen, ptG2_gen, ptJet_tt1_gen, ptJet_tt2_gen, ptJet_6j1_gen, ptJet_6j2_gen;
    Float_t etaTau1_gen, etaTau2_gen, etaB1_gen, etaB2_gen, etaB3_gen, etaB4_gen, etaG1_gen, etaG2_gen, etaJet_tt1_gen, etaJet_tt2_gen, etaJet_6j1_gen, etaJet_6j2_gen;
    Float_t phiTau1_gen, phiTau2_gen, phiB1_gen, phiB2_gen, phiB3_gen, phiB4_gen, phiG1_gen, phiG2_gen, phiJet_tt1_gen, phiJet_tt2_gen, phiJet_6j1_gen, phiJet_6j2_gen;
    Float_t mTau1_gen, mTau2_gen, mB1_gen, mB2_gen, mB3_gen, mB4_gen, eG1_gen, eG2_gen, mJet_tt1_gen, mJet_tt2_gen, mJet_6j1_gen, mJet_6j2_gen;

    Float_t gamIso1, gamIso2;

    Float_t ptH1_gen, etaH1_gen, phiH1_gen, mH1_gen;
    Float_t ptH2_gen, etaH2_gen, phiH2_gen, mH2_gen;

    Float_t ptTau1_genJet, ptTau2_genJet, etaTau1_genJet, etaTau2_genJet, phiTau1_genJet, phiTau2_genJet, mTau1_genJet, mTau2_genJet;

    Float_t ptTT, ptBB1, ptBB2, ptGG, ptJJ_tt, ptJJ_6j, ptHH;
    Float_t etaTT, etaBB1, etaBB2, etaGG, etaJJ_tt, etaJJ_6j, etaHH;
    Float_t phiTT, phiBB1, phiBB2, phiGG, phiJJ_tt, phiJJ_6j, phiHH;
    Float_t mTT, mBB1, mBB2, mGG, mJJ_tt, mJJ_6j, mHH;

    Float_t dEta_tt=0, dEta_6j=0;
    Int_t n;

    Float_t rho_0=0, rho_1=0, rho_2=0;

    Float_t dEtaBB1=0, dEtaTT=0, dEtaHH=0;
    Float_t dPhiBB1=0, dPhiTT=0, dPhiHH=0;
    Float_t dRBB1=0, dRTT=0, dRHH=0;

    Float_t bdtVal=0;

    Float_t chi2=0, corrMet=0, corrMetPhi=0;
    Int_t conv=-999;

    TFile *outFile = new TFile(outputfile, "RECREATE");

    countChain->SetBranchAddress("n", &n);

    Int_t nevents=0;

    for (Int_t i=0; i<countChain->GetEntries(); i++) {
        countChain->GetEntry(i);
        nevents+=n;
    }
    cout << nevents << endl;

    eventChain->SetBranchAddress("eventWeight",    &eventWeight);
    eventChain->SetBranchAddress("sampleNo",       &sampleNo);
    eventChain->SetBranchAddress("genInfo",        &genInfo);
    eventChain->SetBranchAddress("isBBTT",         &isBBTT);
    eventChain->SetBranchAddress("isBBGG",         &isBBGG);
    eventChain->SetBranchAddress("isBBBB",         &isBBBB);
    eventChain->SetBranchAddress("isVBFTT",        &isVBFTT);
    eventChain->SetBranchAddress("isVBF4B",        &isVBF4B);
    eventChain->SetBranchAddress("eventType",      &eventType);

    eventChain->SetBranchAddress("met",            &met);
    eventChain->SetBranchAddress("metPhi",         &metPhi);
    eventChain->SetBranchAddress("pileupmet",      &pileupMet);
    eventChain->SetBranchAddress("pileupmetPhi",   &pileupMetPhi);
    eventChain->SetBranchAddress("puppiMet",       &ppMet);
    eventChain->SetBranchAddress("puppiMetPhi",    &ppMetPhi);

    eventChain->SetBranchAddress("ptTau1",         &ptTau1);
    eventChain->SetBranchAddress("etaTau1",        &etaTau1);
    eventChain->SetBranchAddress("phiTau1",        &phiTau1);
    eventChain->SetBranchAddress("mTau1",          &mTau1);
    eventChain->SetBranchAddress("tauCat1",        &tauCat1);
    eventChain->SetBranchAddress("tauIso1",        &tauIso1);
    eventChain->SetBranchAddress("ptTau2",         &ptTau2);
    eventChain->SetBranchAddress("etaTau2",        &etaTau2);
    eventChain->SetBranchAddress("phiTau2",        &phiTau2);
    eventChain->SetBranchAddress("mTau2",          &mTau2);
    eventChain->SetBranchAddress("tauCat2",        &tauCat2);
    eventChain->SetBranchAddress("tauIso2",        &tauIso2);

    eventChain->SetBranchAddress("ptTrk1",         &ptTrk1);
    eventChain->SetBranchAddress("etaTrk1",        &etaTrk1);
    eventChain->SetBranchAddress("phiTrk1",        &phiTrk1);
    eventChain->SetBranchAddress("mTrk1",          &mTrk1);

    eventChain->SetBranchAddress("ptTrk2",         &ptTrk2);
    eventChain->SetBranchAddress("etaTrk2",        &etaTrk2);
    eventChain->SetBranchAddress("phiTrk2",        &phiTrk2);
    eventChain->SetBranchAddress("mTrk2",          &mTrk2);

    eventChain->SetBranchAddress("ptG1",           &ptG1);
    eventChain->SetBranchAddress("etaG1",          &etaG1);
    eventChain->SetBranchAddress("phiG1",          &phiG1);
    eventChain->SetBranchAddress("eG1",            &eG1);
    //eventChain->SetBranchAddress("gamIso1",        &gamIso1);

    eventChain->SetBranchAddress("ptG2",           &ptG2);
    eventChain->SetBranchAddress("etaG2",          &etaG2);
    eventChain->SetBranchAddress("phiG2",          &phiG2);
    eventChain->SetBranchAddress("eG2",            &eG2);
    //eventChain->SetBranchAddress("gamIso2",        &gamIso2);

    eventChain->SetBranchAddress("ptB1",           &ptB1);
    eventChain->SetBranchAddress("etaB1",          &etaB1);
    eventChain->SetBranchAddress("phiB1",          &phiB1);
    eventChain->SetBranchAddress("mB1",            &mB1);
    eventChain->SetBranchAddress("bTag1",          &bTag1);

    eventChain->SetBranchAddress("ptB2",           &ptB2);
    eventChain->SetBranchAddress("etaB2",          &etaB2);
    eventChain->SetBranchAddress("phiB2",          &phiB2);
    eventChain->SetBranchAddress("mB2",            &mB2);
    eventChain->SetBranchAddress("bTag2",          &bTag2);

    eventChain->SetBranchAddress("ptB3",           &ptB3);
    eventChain->SetBranchAddress("etaB3",          &etaB3);
    eventChain->SetBranchAddress("phiB3",          &phiB3);
    eventChain->SetBranchAddress("mB3",            &mB3);
    eventChain->SetBranchAddress("bTag3",          &bTag3);

    eventChain->SetBranchAddress("ptB4",           &ptB4);
    eventChain->SetBranchAddress("etaB4",          &etaB4);
    eventChain->SetBranchAddress("phiB4",          &phiB4);
    eventChain->SetBranchAddress("mB4",            &mB4);
    eventChain->SetBranchAddress("bTag4",          &bTag4);

    eventChain->SetBranchAddress("ptJet_tt1",      &ptJet_tt1);
    eventChain->SetBranchAddress("etaJet_tt1",     &etaJet_tt1);
    eventChain->SetBranchAddress("phiJet_tt1",     &phiJet_tt1);
    eventChain->SetBranchAddress("mJet_tt1",       &mJet_tt1);
    eventChain->SetBranchAddress("jbTag_tt1",      &jbTag_tt1);

    eventChain->SetBranchAddress("ptJet_tt2",      &ptJet_tt2);
    eventChain->SetBranchAddress("etaJet_tt2",     &etaJet_tt2);
    eventChain->SetBranchAddress("phiJet_tt2",     &phiJet_tt2);
    eventChain->SetBranchAddress("mJet_tt2",       &mJet_tt2);
    eventChain->SetBranchAddress("jbTag_tt2",      &jbTag_tt2);

    eventChain->SetBranchAddress("ptJet_6j1",      &ptJet_6j1);
    eventChain->SetBranchAddress("etaJet_6j1",     &etaJet_6j1);
    eventChain->SetBranchAddress("phiJet_6j1",     &phiJet_6j1);
    eventChain->SetBranchAddress("mJet_6j1",       &mJet_6j1);
    eventChain->SetBranchAddress("jbTag_6j1",      &jbTag_6j1);

    eventChain->SetBranchAddress("ptJet_6j2",      &ptJet_6j2);
    eventChain->SetBranchAddress("etaJet_6j2",     &etaJet_6j2);
    eventChain->SetBranchAddress("phiJet_6j2",     &phiJet_6j2);
    eventChain->SetBranchAddress("mJet_6j2",       &mJet_6j2);
    eventChain->SetBranchAddress("jbTag_6j2",      &jbTag_6j2);

    eventChain->SetBranchAddress("ptTau1_gen",     &ptTau1_gen);
    eventChain->SetBranchAddress("etaTau1_gen",    &etaTau1_gen);
    eventChain->SetBranchAddress("phiTau1_gen",    &phiTau1_gen);
    eventChain->SetBranchAddress("mTau1_gen",      &mTau1_gen);

    eventChain->SetBranchAddress("ptTau2_gen",     &ptTau2_gen);
    eventChain->SetBranchAddress("etaTau2_gen",    &etaTau2_gen);
    eventChain->SetBranchAddress("phiTau2_gen",    &phiTau2_gen);
    eventChain->SetBranchAddress("mTau2_gen",      &mTau2_gen);

    eventChain->SetBranchAddress("ptTau1_genJet",  &ptTau1_genJet);
    eventChain->SetBranchAddress("etaTau1_genJet", &etaTau1_genJet);
    eventChain->SetBranchAddress("phiTau1_genJet", &phiTau1_genJet);
    eventChain->SetBranchAddress("mTau1_genJet",   &mTau1_genJet);

    eventChain->SetBranchAddress("ptTau2_genJet",  &ptTau2_genJet);
    eventChain->SetBranchAddress("etaTau2_genJet", &etaTau2_genJet);
    eventChain->SetBranchAddress("phiTau2_genJet", &phiTau2_genJet);
    eventChain->SetBranchAddress("mTau2_genJet",   &mTau2_genJet);

    eventChain->SetBranchAddress("ptG1_gen",       &ptG1_gen);
    eventChain->SetBranchAddress("etaG1_gen",      &etaG1_gen);
    eventChain->SetBranchAddress("phiG1_gen",      &phiG1_gen);
    eventChain->SetBranchAddress("eG1_gen",        &eG1_gen);

    eventChain->SetBranchAddress("ptG2_gen",       &ptG2_gen);
    eventChain->SetBranchAddress("etaG2_gen",      &etaG2_gen);
    eventChain->SetBranchAddress("phiG2_gen",      &phiG2_gen);
    eventChain->SetBranchAddress("eG2_gen",        &eG2_gen);

    eventChain->SetBranchAddress("ptB1_gen",       &ptB1_gen);
    eventChain->SetBranchAddress("etaB1_gen",      &etaB1_gen);
    eventChain->SetBranchAddress("phiB1_gen",      &phiB1_gen);
    eventChain->SetBranchAddress("mB1_gen",        &mB1_gen);
    eventChain->SetBranchAddress("iHmatch1",       &iHmatch1);

    eventChain->SetBranchAddress("ptB2_gen",       &ptB2_gen);
    eventChain->SetBranchAddress("etaB2_gen",      &etaB2_gen);
    eventChain->SetBranchAddress("phiB2_gen",      &phiB2_gen);
    eventChain->SetBranchAddress("mB2_gen",        &mB2_gen);
    eventChain->SetBranchAddress("iHmatch2",       &iHmatch2);

    eventChain->SetBranchAddress("ptB3_gen",       &ptB3_gen);
    eventChain->SetBranchAddress("etaB3_gen",      &etaB3_gen);
    eventChain->SetBranchAddress("phiB3_gen",      &phiB3_gen);
    eventChain->SetBranchAddress("mB3_gen",        &mB3_gen);
    eventChain->SetBranchAddress("iHmatch3",       &iHmatch3);

    eventChain->SetBranchAddress("ptB4_gen",       &ptB4_gen);
    eventChain->SetBranchAddress("etaB4_gen",      &etaB4_gen);
    eventChain->SetBranchAddress("phiB4_gen",      &phiB4_gen);
    eventChain->SetBranchAddress("mB4_gen",        &mB4_gen);
    eventChain->SetBranchAddress("iHmatch4",       &iHmatch4);

    eventChain->SetBranchAddress("ptH1_gen",       &ptH1_gen);
    eventChain->SetBranchAddress("etaH1_gen",      &etaH1_gen);
    eventChain->SetBranchAddress("phiH1_gen",      &phiH1_gen);
    eventChain->SetBranchAddress("mH1_gen",        &mH1_gen);

    eventChain->SetBranchAddress("ptH2_gen",       &ptH2_gen);
    eventChain->SetBranchAddress("etaH2_gen",      &etaH2_gen);
    eventChain->SetBranchAddress("phiH2_gen",      &phiH2_gen);
    eventChain->SetBranchAddress("mH2_gen",        &mH2_gen);

    eventChain->SetBranchAddress("ptJet_tt1_gen",  &ptJet_tt1_gen);
    eventChain->SetBranchAddress("etaJet_tt1_gen", &etaJet_tt1_gen);
    eventChain->SetBranchAddress("phiJet_tt1_gen", &phiJet_tt1_gen);
    eventChain->SetBranchAddress("mJet_tt1_gen",   &mJet_tt1_gen);

    eventChain->SetBranchAddress("ptJet_tt2_gen",  &ptJet_tt2_gen);
    eventChain->SetBranchAddress("etaJet_tt2_gen", &etaJet_tt2_gen);
    eventChain->SetBranchAddress("phiJet_tt2_gen", &phiJet_tt2_gen);
    eventChain->SetBranchAddress("mJet_tt2_gen",   &mJet_tt2_gen);

    eventChain->SetBranchAddress("ptJet_6j1_gen",  &ptJet_6j1_gen);
    eventChain->SetBranchAddress("etaJet_6j1_gen", &etaJet_6j1_gen);
    eventChain->SetBranchAddress("phiJet_6j1_gen", &phiJet_6j1_gen);
    eventChain->SetBranchAddress("mJet_6j1_gen",   &mJet_6j1_gen);

    eventChain->SetBranchAddress("ptJet_6j2_gen",  &ptJet_6j2_gen);
    eventChain->SetBranchAddress("etaJet_6j2_gen", &etaJet_6j2_gen);
    eventChain->SetBranchAddress("phiJet_6j2_gen", &phiJet_6j2_gen);
    eventChain->SetBranchAddress("mJet_6j2_gen",   &mJet_6j2_gen);

    eventChain->SetBranchAddress("ptTT",           &ptTT);
    eventChain->SetBranchAddress("etaTT",          &etaTT);
    eventChain->SetBranchAddress("phiTT",          &phiTT);
    eventChain->SetBranchAddress("mTT",            &mTT);

    eventChain->SetBranchAddress("ptBB1",          &ptBB1);
    eventChain->SetBranchAddress("etaBB1",         &etaBB1);
    eventChain->SetBranchAddress("phiBB1",         &phiBB1);
    eventChain->SetBranchAddress("mBB1",           &mBB1);

    eventChain->SetBranchAddress("ptBB2",          &ptBB2);
    eventChain->SetBranchAddress("etaBB2",         &etaBB2);
    eventChain->SetBranchAddress("phiBB2",         &phiBB2);
    eventChain->SetBranchAddress("mBB2",           &mBB2);

    eventChain->SetBranchAddress("ptGG",           &ptGG);
    eventChain->SetBranchAddress("etaGG",          &etaGG);
    eventChain->SetBranchAddress("phiGG",          &phiGG);
    eventChain->SetBranchAddress("mGG",            &mGG);

    eventChain->SetBranchAddress("ptJJ_tt",        &ptJJ_tt);
    eventChain->SetBranchAddress("etaJJ_tt",       &etaJJ_tt);
    eventChain->SetBranchAddress("phiJJ_tt",       &phiJJ_tt);
    eventChain->SetBranchAddress("mJJ_tt",         &mJJ_tt);

    eventChain->SetBranchAddress("ptJJ_6j",        &ptJJ_6j);
    eventChain->SetBranchAddress("etaJJ_6j",       &etaJJ_6j);
    eventChain->SetBranchAddress("phiJJ_6j",       &phiJJ_6j);
    eventChain->SetBranchAddress("mJJ_6j",         &mJJ_6j);

    eventChain->SetBranchAddress("ptHH",           &ptHH);
    eventChain->SetBranchAddress("etaHH",          &etaHH);
    eventChain->SetBranchAddress("phiHH",          &phiHH);
    eventChain->SetBranchAddress("mHH",            &mHH);

    eventChain->SetBranchAddress("mt2",            &mt2);
    eventChain->SetBranchAddress("mt2puppi",       &mt2puppi);
    eventChain->SetBranchAddress("mt2pileup",      &mt2pileup);

    eventChain->SetBranchAddress("m_sv",           &m_sv);
    eventChain->SetBranchAddress("m_svpileup",     &m_svpileup);
    eventChain->SetBranchAddress("m_svpuppi",      &m_svpuppi);

    eventChain->SetBranchAddress("nBtag",          &nBtag);
    eventChain->SetBranchAddress("nCentral",       &nCentral);
    eventChain->SetBranchAddress("centB",          &centB);
    eventChain->SetBranchAddress("nJets",          &nJets);

    eventChain->SetBranchAddress("dEta_tt",        &dEta_tt);
    eventChain->SetBranchAddress("dEta_6j",        &dEta_6j);
    eventChain->SetBranchAddress("rho_0",          &rho_0);
    eventChain->SetBranchAddress("rho_1",          &rho_1);
    eventChain->SetBranchAddress("rho_2",          &rho_2);

    eventChain->SetBranchAddress("dEtaBB1",         &dEtaBB1);
    eventChain->SetBranchAddress("dPhiBB1",         &dPhiBB1);
    eventChain->SetBranchAddress("dRBB1",           &dRBB1);

    eventChain->SetBranchAddress("dEtaTT",          &dEtaTT);
    eventChain->SetBranchAddress("dPhiTT",          &dPhiTT);
    eventChain->SetBranchAddress("dRTT",            &dRTT);

    eventChain->SetBranchAddress("dEtaHH",          &dEtaHH);
    eventChain->SetBranchAddress("dPhiHH",          &dPhiHH);
    eventChain->SetBranchAddress("dRHH",            &dRHH);

    eventChain->GetEntry(0);

    TTree *outTree=(TTree*)eventChain->GetTree()->CloneTree(0);

    outTree->Branch("bdtVal", &bdtVal, "bdtVal/f");
    outTree->Branch("chi2", &chi2, "chi2/f");
    outTree->Branch("corrMet", &corrMet, "corrMet/f");
    outTree->Branch("corrMetPhi", &corrMetPhi, "corrMetPhi/f");
    outTree->Branch("conv", &conv, "conv/i");

    //hhMVA::MVAType why1=hhMVA::kTauTau;
    hhMVA::MVAType why2=hhMVA::kMuTau;
    hhMVA::MVAType why3=hhMVA::kElTau;
    hhMVA::MVAType why4=hhMVA::kElMu;

    //hhMVA *ttMVA = new hhMVA();
    hhMVA *mtMVA = new hhMVA();
    hhMVA *etMVA = new hhMVA();
    hhMVA *emMVA = new hhMVA();

    //ttMVA->Intialize(why1);
    mtMVA->Intialize(why2);
    etMVA->Intialize(why3);
    emMVA->Intialize(why4);

    for (Int_t i=0; i<eventChain->GetEntries(); i++) {
        eventChain->GetEntry(i);

        eventWeight/=float(nevents);
        bdtVal=999;

        // hack to fix modified SM samples
        //if (sampleNo>95 && sampleNo<100) eventWeight=2.92/float(nevents);

        if (isBBTT!=1) continue;
        if (ptB1<30 || ptB2<30) continue;
        //if (TMath::Sqrt((etaTau1-etaTau2)*(etaTau1-etaTau2)+(phiTau1-phiTau2)*(phiTau1-phiTau2))<0.4) continue;
        /*
        TLorentzVector v1;
        TLorentzVector v2;

        v1.SetPtEtaPhiM(ptB1, etaB1, phiB1, mB1);
        v2.SetPtEtaPhiM(ptB2, etaB2, phiB2, mB2);

        TMatrixD m1(3,3);
        TMatrixD m2(3,3);

        m1.Zero();
        m2.Zero();
        m1(0,0) = ErrEt (v1.Et(), v1.Eta()); // et
        m1(1,1) = ErrEta(v1.Et(), v1.Eta()); // eta
        m1(2,2) = ErrPhi(v1.Et(), v1.Eta()); // phi
        m2(0,0) = ErrEt (v2.Et(), v2.Eta()); // et
        m2(1,1) = ErrEta(v2.Et(), v2.Eta()); // eta
        m2(2,2) = ErrPhi(v2.Et(), v2.Eta()); // phi

        TFitParticleEtEtaPhi *jet1 = new TFitParticleEtEtaPhi( "Jet1", "Jet1", &v1, &m1 );
        TFitParticleEtEtaPhi *jet2 = new TFitParticleEtEtaPhi( "Jet2", "Jet2", &v2, &m2 );

        TFitConstraintM *mCons1 = new TFitConstraintM( "HMassConstraint", "HMass-Constraint", 0, 0 , 125.);
        mCons1->addParticles1( jet1, jet2 );

        TKinFitter* fitter = new TKinFitter("fitter", "fitter");
        fitter->addMeasParticle( jet1 );
        fitter->addMeasParticle( jet2 );
        fitter->addConstraint( mCons1 );

        //Set convergence criteria
        fitter->setMaxNbIter( 30 );
        fitter->setMaxDeltaS( 1e-2 );
        fitter->setMaxF( 1e-1 );
        fitter->setVerbosity(1);

        TVector2 b1_i; b1_i.SetMagPhi(fitter->get4Vec(0)->Pt(), fitter->get4Vec(0)->Phi());
        TVector2 b2_i; b2_i.SetMagPhi(fitter->get4Vec(1)->Pt(), fitter->get4Vec(1)->Phi());

        //Perform the fit
        conv=fitter->fit();

        chi2=fitter->getS();

        TVector2 metTemp; metTemp.SetMagPhi(pileupMet,pileupMetPhi);
        TVector2 b1_f; b1_f.SetMagPhi(fitter->get4Vec(0)->Pt(), fitter->get4Vec(0)->Phi());
        TVector2 b2_f; b2_f.SetMagPhi(fitter->get4Vec(1)->Pt(), fitter->get4Vec(1)->Phi());

        metTemp=metTemp+b1_i+b2_i-b1_f-b2_f;
        corrMet=metTemp.Mod();
        corrMetPhi=metTemp.Phi();
        */
        if (tauCat1==1 && tauCat2==1 && ptTau1>45 && ptTau2>45) {
            bdtVal=999;//ttMVA->GetBDTValue(mTT, ptTT, mBB1, ptBB1, dRBB1, dRTT);
        }
        else if (tauCat1==1 && tauCat2==3 && ptTau1>30 && ptTau2>20) {
            bdtVal=mtMVA->GetBDTValue(mTT, ptTT, mBB1, ptBB1, mHH, ptHH, mt2pileup, dRBB1, dRTT, dRHH);
        }
        else if (tauCat1==1 && tauCat2==2 && ptTau1>30 && ptTau2>20) {
            bdtVal=etMVA->GetBDTValue(mTT, ptTT, mBB1, ptBB1, mHH, ptHH, mt2pileup, dRBB1, dRTT, dRHH);
        }
        else if (tauCat1==3 && tauCat2==2 && ptTau1>20 && ptTau2>20) {
            bdtVal=emMVA->GetBDTValue(mTT, ptTT, mBB1, ptBB1, mHH, ptHH, mt2pileup, dRBB1, dRTT, dRHH);
        }
        else continue;
        outTree->Fill();
    }

    outFile->Write();
    outFile->Save();

}
Example #30
0
void comp(int s1 = 7, int s2 = 18, TString str1 = "|#eta| < 2.4", TString str2 = "|#eta| < 0.8") {
//	bool bAlice = false;
	bool bAlice = true;

	SetStyle();
	if ( bAlice ) ALICE();
	TFile * f1 = new TFile(Form("%s/out_rebin.root", ftxt[s1]));
	TFile * f2 = new TFile(Form("%s/out_rebin.root", ftxt[s2]));


	TH1D * h3PartSS_Cent1 = (TH1D*) f1->Get("h3PartSS_Cent");
	TH1D * h3PartOS_Cent1 = (TH1D*) f1->Get("h3PartOS_Cent");

	TH1D * h3PartSS_Cent2 = (TH1D*) f2->Get("h3PartSS_Cent");
	TH1D * h3PartOS_Cent2 = (TH1D*) f2->Get("h3PartOS_Cent");

	TCanvas * c1 = MakeCanvas("c1", "c1", 500, 400);
	TH2D * hframe_3part = new TH2D("hframe_3part", "hframe_3part", 1, 0, 200, 1, -0.001, 0.002);
	InitHist(hframe_3part, "Centrality Bin", "cos(#phi_{#alpha}+#phi_{#beta}-2#Psi_{2})");
	hframe_3part->Draw();

	TLine * zero = new TLine(0, 0, 200, 0);
	zero->Draw();

	h3PartSS_Cent1->SetMarkerStyle(kFullCircle);
	h3PartOS_Cent1->SetMarkerStyle(kFullCircle);
	h3PartSS_Cent1->SetMarkerColor(kRed);
	h3PartOS_Cent1->SetMarkerColor(kBlue);
	h3PartSS_Cent1->SetLineColor(kRed);
	h3PartOS_Cent1->SetLineColor(kBlue);

	h3PartSS_Cent2->SetMarkerStyle(kFullSquare);
	h3PartOS_Cent2->SetMarkerStyle(kFullSquare);
	h3PartSS_Cent2->SetMarkerColor(kRed);
	h3PartOS_Cent2->SetMarkerColor(kBlue);
	h3PartSS_Cent2->SetLineColor(kRed);
	h3PartOS_Cent2->SetLineColor(kBlue);


	h3PartSS_Cent1->Draw("same");
	h3PartOS_Cent1->Draw("same");
	h3PartSS_Cent2->Draw("same");
	h3PartOS_Cent2->Draw("same");

	if ( bAlice ) gr_ALICE_3part_tpccumu_os->Draw("psame");
	if ( bAlice ) gr_ALICE_3part_tpccumu_ss->Draw("psame");

	TLegend * leg1 = new TLegend(0.2, 0.5, 0.5, 0.9);
	leg1->SetFillColor(kWhite);
	leg1->SetTextFont(42);
	leg1->SetTextSize(0.06);
	leg1->SetBorderSize(0);

	leg1->AddEntry(h3PartSS_Cent1, Form("SS %s", str1.Data()), "p");
	leg1->AddEntry(h3PartOS_Cent1, Form("OS %s", str1.Data()), "p");
	leg1->AddEntry(h3PartSS_Cent2, Form("SS %s", str2.Data()), "p");
	leg1->AddEntry(h3PartOS_Cent2, Form("OS %s", str2.Data()), "p");

	if ( bAlice ) leg1->AddEntry(gr_ALICE_3part_tpccumu_ss, "ALICE SS", "p");
	else leg1->AddEntry(gr_ALICE_3part_tpccumu_ss, " ", "");
	if ( bAlice ) leg1->AddEntry(gr_ALICE_3part_tpccumu_os, "ALICE OS", "p");
	else leg1->AddEntry(gr_ALICE_3part_tpccumu_os, " ", "");

	leg1->Draw();

	///////////
	TCanvas * c2 = MakeCanvas("c2", "c2", 500, 400);
	TH2D * hframe_2part = new TH2D("hframe_2part", "hframe_2part", 1, 0, 200, 1, -0.01, 0.03);
	InitHist(hframe_2part, "Centrality Bin", "#LTcos(#phi_{#alpha}-#phi_{#beta})#GT");

	TH1D * hQ1pp_Cent1 = (TH1D*) f1->Get("hQ1pp_Cent");
	TH1D * hQ1nn_Cent1 = (TH1D*) f1->Get("hQ1nn_Cent");
	TH1D * hQ1pn_Cent1 = (TH1D*) f1->Get("hQ1pn_Cent");
	TH1D * hQ1ppw_Cent1= (TH1D*) f1->Get("hQ1ppw_Cent");
	TH1D * hQ1nnw_Cent1= (TH1D*) f1->Get("hQ1nnw_Cent");
	TH1D * hQ1pnw_Cent1= (TH1D*) f1->Get("hQ1pnw_Cent");

	TH1D * hQ1pp_Cent2 = (TH1D*) f2->Get("hQ1pp_Cent");
	TH1D * hQ1nn_Cent2 = (TH1D*) f2->Get("hQ1nn_Cent");
	TH1D * hQ1pn_Cent2 = (TH1D*) f2->Get("hQ1pn_Cent");
	TH1D * hQ1ppw_Cent2= (TH1D*) f2->Get("hQ1ppw_Cent");
	TH1D * hQ1nnw_Cent2= (TH1D*) f2->Get("hQ1nnw_Cent");
	TH1D * hQ1pnw_Cent2= (TH1D*) f2->Get("hQ1pnw_Cent");

	hQ1pp_Cent1->Add(hQ1nn_Cent1);
	hQ1ppw_Cent1->Add(hQ1nnw_Cent1);
	hQ1pp_Cent2->Add(hQ1nn_Cent2);
	hQ1ppw_Cent2->Add(hQ1nnw_Cent2);

	hQ1pp_Cent1->Divide(hQ1ppw_Cent1);
	hQ1pp_Cent2->Divide(hQ1ppw_Cent2);
	hQ1pn_Cent1->Divide(hQ1pnw_Cent1);
	hQ1pn_Cent2->Divide(hQ1pnw_Cent2);


	hQ1pp_Cent1->SetMarkerStyle(kFullCircle);
	hQ1pn_Cent1->SetMarkerStyle(kFullCircle);
	hQ1pp_Cent1->SetMarkerColor(kRed);
	hQ1pn_Cent1->SetMarkerColor(kBlue);
	hQ1pp_Cent1->SetLineColor(kRed);
	hQ1pn_Cent1->SetLineColor(kBlue);

	hQ1pp_Cent2->SetMarkerStyle(kFullSquare);
	hQ1pn_Cent2->SetMarkerStyle(kFullSquare);
	hQ1pp_Cent2->SetMarkerColor(kRed);
	hQ1pn_Cent2->SetMarkerColor(kBlue);
	hQ1pp_Cent2->SetLineColor(kRed);
	hQ1pn_Cent2->SetLineColor(kBlue);


	hframe_2part->Draw();
	zero->Draw();
	hQ1pp_Cent1->Draw("same");
	hQ1pn_Cent1->Draw("same");
	hQ1pp_Cent2->Draw("same");
	hQ1pn_Cent2->Draw("same");
	if ( bAlice ) gr_ALICE_2part_tpccumu_os->Draw("psame");
	if ( bAlice ) gr_ALICE_2part_tpccumu_ss->Draw("psame");

	TLegend * leg2 = new TLegend(0.2, 0.5, 0.5, 0.9);
	leg2->SetFillColor(kWhite);
	leg2->SetTextFont(42);
	leg2->SetTextSize(0.06);
	leg2->SetBorderSize(0);

	leg2->AddEntry(hQ1pp_Cent1, Form("SS %s", str1.Data()), "p");
	leg2->AddEntry(hQ1pn_Cent1, Form("OS %s", str1.Data()), "p");
	leg2->AddEntry(hQ1pp_Cent2, Form("SS %s", str2.Data()), "p");
	leg2->AddEntry(hQ1pn_Cent2, Form("OS %s", str2.Data()), "p");

	if ( bAlice ) leg2->AddEntry(gr_ALICE_2part_tpccumu_ss, "ALICE SS", "p");
	else leg2->AddEntry(gr_ALICE_2part_tpccumu_ss, " ", "");
	if ( bAlice ) leg2->AddEntry(gr_ALICE_2part_tpccumu_os, "ALICE OS", "p");
	else leg2->AddEntry(gr_ALICE_2part_tpccumu_os, " ", "");

	leg2->Draw();


	///////////////
	TH1D * hCC_SS1 = (TH1D*)hQ1pp_Cent1->Clone("hCC_SS1");
	TH1D * hCC_OS1 = (TH1D*)hQ1pn_Cent1->Clone("hCC_OS1");
	TH1D * hCC_SS2 = (TH1D*)hQ1pp_Cent2->Clone("hCC_SS2");
	TH1D * hCC_OS2 = (TH1D*)hQ1pn_Cent2->Clone("hCC_OS2");

	hCC_SS1->Add(h3PartSS_Cent1);
	hCC_SS1->Scale(0.5);
	hCC_OS1->Add(h3PartOS_Cent1);
	hCC_OS1->Scale(0.5);
	hCC_SS2->Add(h3PartSS_Cent2);
	hCC_SS2->Scale(0.5);
	hCC_OS2->Add(h3PartOS_Cent2);
	hCC_OS2->Scale(0.5);

	TH1D * hSS_SS1 = (TH1D*)hQ1pp_Cent1->Clone("hSS_SS1");
	TH1D * hSS_OS1 = (TH1D*)hQ1pn_Cent1->Clone("hSS_OS1");
	TH1D * hSS_SS2 = (TH1D*)hQ1pp_Cent2->Clone("hSS_SS2");
	TH1D * hSS_OS2 = (TH1D*)hQ1pn_Cent2->Clone("hSS_OS2");

	hSS_SS1->Add(h3PartSS_Cent1, -1);
	hSS_SS1->Scale(0.5);
	hSS_OS1->Add(h3PartOS_Cent1, -1);
	hSS_OS1->Scale(0.5);
	hSS_SS2->Add(h3PartSS_Cent2, -1);
	hSS_SS2->Scale(0.5);
	hSS_OS2->Add(h3PartOS_Cent2, -1);
	hSS_OS2->Scale(0.5);


	////
	TCanvas * c3 = MakeCanvas("c3", "c3", 500, 400);
	TH2D * hframe_cos = new TH2D("hframe_cos", "hframe_cos", 1, 0, 200, 1, -0.01, 0.02);
	InitHist(hframe_cos, "Centrality Bin", "#LTcos(#Delta#phi_{#alpha})cos(#Delta#phi_{#beta})");

	hframe_cos->Draw();
	zero->Draw();

	hCC_SS1->Draw("same");
	hCC_SS2->Draw("same");
	hCC_OS1->Draw("same");
	hCC_OS2->Draw("same");

	if ( bAlice ) gr_ALICE_coscos_ss->Draw("psame");
	if ( bAlice ) gr_ALICE_coscos_os->Draw("psame");

	TLegend * leg_cos = new TLegend(0.2, 0.5, 0.5, 0.9);
	leg_cos->SetFillColor(kWhite);
	leg_cos->SetTextFont(42);
	leg_cos->SetTextSize(0.06);
	leg_cos->SetBorderSize(0);

	leg_cos->AddEntry(hCC_SS1, Form("SS %s", str1.Data()), "p");
	leg_cos->AddEntry(hCC_OS1, Form("OS %s", str1.Data()), "p");
	leg_cos->AddEntry(hCC_SS2, Form("SS %s", str2.Data()), "p");
	leg_cos->AddEntry(hCC_OS2, Form("OS %s", str2.Data()), "p");

	if ( bAlice ) leg_cos->AddEntry(gr_ALICE_coscos_ss, "ALICE SS", "p");
	else leg_cos->AddEntry(gr_ALICE_coscos_ss, " ", "");
	if ( bAlice ) leg_cos->AddEntry(gr_ALICE_coscos_os, "ALICE OS", "p");
	else leg_cos->AddEntry(gr_ALICE_coscos_os, " ", "");

	leg_cos->Draw();


	///
	TCanvas * c4 = MakeCanvas("c4", "c4", 500, 400);
	TH2D * hframe_sin = new TH2D("hframe_sin", "hframe_sin", 1, 0, 200, 1, -0.01, 0.02);
	InitHist(hframe_sin, "Centrality Bin", "#LTsin(#Delta#phi_{#alpha})sin(#Delta#phi_{#beta})");

	hframe_sin->Draw();
	zero->Draw();

	hSS_SS1->Draw("same");
	hSS_SS2->Draw("same");
	hSS_OS1->Draw("same");
	hSS_OS2->Draw("same");

	if ( bAlice ) gr_ALICE_sinsin_ss->Draw("psame");
	if ( bAlice ) gr_ALICE_sinsin_os->Draw("psame");

	TLegend * leg_sin = new TLegend(0.2, 0.5, 0.5, 0.9);
	leg_sin->SetFillColor(kWhite);
	leg_sin->SetTextFont(42);
	leg_sin->SetTextSize(0.06);
	leg_sin->SetBorderSize(0);

	leg_sin->AddEntry(hSS_SS1, Form("SS %s", str1.Data()), "p");
	leg_sin->AddEntry(hSS_OS1, Form("OS %s", str1.Data()), "p");
	leg_sin->AddEntry(hSS_SS2, Form("SS %s", str2.Data()), "p");
	leg_sin->AddEntry(hSS_OS2, Form("OS %s", str2.Data()), "p");

	if ( bAlice ) leg_sin->AddEntry(gr_ALICE_sinsin_ss, "ALICE SS", "p");
	else leg_sin->AddEntry(gr_ALICE_sinsin_ss, " ", "");
	if ( bAlice ) leg_sin->AddEntry(gr_ALICE_sinsin_os, "ALICE OS", "p");
	else leg_sin->AddEntry(gr_ALICE_sinsin_os, " ", "");

	leg_sin->Draw();




	c1->SaveAs(Form("3part%s_%i_%i.pdf", bAlice?"_Alice":"", s1, s2));
	c2->SaveAs(Form("2part%s_%i_%i.pdf", bAlice?"_Alice":"", s1, s2));
	c3->SaveAs(Form("coscos%s_%i_%i.pdf", bAlice?"_Alice":"", s1, s2));
	c4->SaveAs(Form("sinsin%s_%i_%i.pdf", bAlice?"_Alice":"", s1, s2));


}