コード例 #1
0
void GenerateSusyFile( double flatDummyErr = 10. ) {  //-- flat error in %.  If negative, use MC stat err.

//gluino cross sections in pb.


  TFile prospino("referenceXSecs.root");
  TH1F *gluinoxsec = (TH1F*) prospino.Get("gluino_NLONLL") ;
  if ( gluinoxsec == 0 ) {
     printf("\n\n *** Can't find histogram with name gluino_NLONLL in referenceXSecs.root.\n\n") ;
     return ;
  }
  TH1F *gluinoxsec8TeV = (TH1F*) prospino.Get("gluino8TeV_NLONLL") ;
  if ( gluinoxsec8TeV == 0 ) {
     printf("\n\n *** Can't find histogram with name gluino8TeV_NLONLL in referenceXSecs.root.\n\n") ;
     return ;
  }

// bin 1 = gluino mass = 100 GeV, 2 = 125, 3 = 150, 4 = 175, ...
// so gluino mass = 75+nbin*25; or nbin = (gluinomass-75)/25.

  TChain chainT1bbbb("tree");
  chainT1bbbb.Add("filesHCP_53_v3_QCDweights/T1bbbb.root");

  gROOT->Reset();

  const int nBinsBjets = 3 ;   // this must always be 3
  const int nJetsCut = 3 ;     // #jets >= nJetsCut

  //-- met2-ht1-v1
//const int nBinsMET   = 2 ;
//const int nBinsHT    = 1 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,250.,99999.};
//float Hbins[nBinsHT+1] = {400.,99999.};

////-- met2-ht2-v1
//const int nBinsMET   = 2 ;
//const int nBinsHT    = 2 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,250.,99999.};
//float Hbins[nBinsHT+1] = {400.,600.,99999.};

////-- met2-ht8-v1
//const int nBinsMET   = 2 ;
//const int nBinsHT    = 8 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,250.,99999.};
//float Hbins[nBinsHT+1] = {400.,500.,600.,700.,800.,900.,1000.,1200.,99999.};

  //-- met3-ht2-v1
//const int nBinsMET   = 3 ;
//const int nBinsHT    = 2 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,250.,350.,99999.};
//float Hbins[nBinsHT+1] = {400.,800.,99999.};

//-- met3-ht3-v1
//const int nBinsMET   = 3 ;
//const int nBinsHT    = 3 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,250.,350.,99999.};
//float Hbins[nBinsHT+1] = {400.,600.,1000.,99999.};

////-- met3-ht3-v5
//    const int nBinsMET = 3 ;
//    const int nBinsHT  = 3 ;
//    const int version = 5;
//    float Mbins[nBinsMET+1] = { 125, 200,  350, 99999. } ;
//    float Hbins[nBinsHT+1]  = { 400, 600, 1000, 99999. } ;

//-- met3-ht3-v2
//const int nBinsMET   = 3 ;
//const int nBinsHT    = 3 ;
//    const int version = 2;
//float Mbins[nBinsMET+1] = {150.,250.,350.,99999.};
//float Hbins[nBinsHT+1] = {300.,500.,1000.,99999.};

////-- met3-ht4-v1
//const int nBinsMET   = 3 ;
//const int nBinsHT    = 4 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,250.,350.,99999.};
//float Hbins[nBinsHT+1] = {200, 300.,500.,1000.,99999.};

////-- met3-ht5-v1
//const int nBinsMET   = 3 ;
//const int nBinsHT    = 5 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,250.,350.,99999.};
//float Hbins[nBinsHT+1] = {400.,500.,600.,800.,1000.,99999.};

////-- met4-ht3-v1
//const int nBinsMET   = 4 ;
//const int nBinsHT    = 3 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,250.,350.,500.,99999.};
//float Hbins[nBinsHT+1] = {400.,600.,1000.,99999.};

////-- met4-ht3-v2
//const int nBinsMET   = 4 ;
//const int nBinsHT    = 3 ;
//    const int version = 2;
//float Mbins[nBinsMET+1] = {125, 150.,250.,350.,99999.};
//float Hbins[nBinsHT+1] = {300.,500.,1000.,99999.};

  //-- met5-ht4-v1
//const int nBinsMET   = 5 ;
//const int nBinsHT    = 4 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,200.,250.,300.,350.,99999.};
//float Hbins[nBinsHT+1] = {400.,600.,800.,1000.,99999.};

  //-- met4-ht4-v1
  //   const int nBinsMET   = 4 ;
  //  const int nBinsHT	 = 4 ;
  //  const int version = 1;
  //  float Mbins[nBinsMET+1] = {150.,200.,250.,300.,99999.};
  //  float Hbins[nBinsHT+1] = {400.,500.,600.,800.,99999.};

  //-- met4-ht4-v2
//    const int nBinsMET   = 4 ;
//    const int nBinsHT    = 4 ;
//    const int version = 2;
//    float Mbins[nBinsMET+1] = {150.,250.,350.,450.,99999.};
//    float Hbins[nBinsHT+1] = {400.,500.,600.,800.,99999.};

  //-- met4-ht4-v3
//    const int nBinsMET   = 4 ;
//    const int nBinsHT    = 4 ;
//    const int version = 3;
//    float Mbins[nBinsMET+1] = {150.,200.,250.,300.,99999.};
//    float Hbins[nBinsHT+1] = {400.,600.,800.,1000.,99999.};

  //-- met4-ht4-v4
//    const int nBinsMET   = 4 ;
//    const int nBinsHT    = 4 ;
//    const int version = 4;
//    float Mbins[nBinsMET+1] = {150.,250.,350.,450.,99999.};
//    float Hbins[nBinsHT+1] = {400.,600.,800.,1000.,99999.};

  //-- met4-ht4-v5
//    const int nBinsMET   = 4 ;
//    const int nBinsHT	 = 4 ;
//    const int version = 5;
//    float Mbins[nBinsMET+1] = {150.,175.,200.,400.,99999.};
//    float Hbins[nBinsHT+1] = {400.,450.,550.,850.,99999.};

  //-- met4-ht4-v6
//    const int nBinsMET   = 4 ;
//    const int nBinsHT    = 4 ;
//    const int version = 6;
//    float Mbins[nBinsMET+1] = {150.,200.,350.,450.,99999.};
//    float Hbins[nBinsHT+1] = {400.,550.,800.,950.,99999.};

////-- met4-ht4-v7
//const int nBinsMET   = 4 ;
//const int nBinsHT    = 4 ;
//    const int version = 7;
//float Mbins[nBinsMET+1] = {125, 150.,250.,350.,99999.};
//float Hbins[nBinsHT+1] = {200, 300.,500.,1000.,99999.};

  //-- met4-ht4-v15
      const int nBinsMET   = 4 ;
      const int nBinsHT    = 4 ;
      const int version = 15;
      float Mbins[nBinsMET+1] = {125.,150.,250.,350.,99999.};
      float Hbins[nBinsHT+1] = {400.,500.,800.,1000.,99999.};

////-- met4-ht5-v1
//const int nBinsMET   = 4 ;
//const int nBinsHT    = 5 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,200.,300.,400.,99999.};
//float Hbins[nBinsHT+1] = {400.,600.,800.,1000.,1200.,99999.};

////-- met5-ht5-v1
//const int nBinsMET   = 5 ;
//const int nBinsHT    = 5 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,200.,250.,300.,350.,99999.};
//float Hbins[nBinsHT+1] = {400.,500.,600.,800.,1000.,99999.};

////-- met5-ht3-v1
//const int nBinsMET   = 5 ;
//const int nBinsHT    = 3 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,200.,250.,300.,350.,99999.};
//float Hbins[nBinsHT+1] = {400.,600.,1000.,99999.};

////-- met5-ht3-v2
//const int nBinsMET   = 5 ;
//const int nBinsHT    = 3 ;
//    const int version = 2;
//float Mbins[nBinsMET+1] = {150.,175.,200.,350.,450.,99999.};
//float Hbins[nBinsHT+1] = {400.,550.,800.,99999.};

  //-- met6-ht6-v1
//const int nBinsMET   = 6 ;
//const int nBinsHT    = 6 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,200.,250.,300.,350.,400.,99999.};
//float Hbins[nBinsHT+1] = {400.,500.,600.,700.,800.,900.,99999.};

  //-- met7-ht7-v1
//const int nBinsMET   = 7 ;
//const int nBinsHT    = 7 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,200.,250.,300.,350.,400.,500.,99999.};
//float Hbins[nBinsHT+1] = {400.,500.,600.,700.,800.,900.,1000.,99999.};

////-- met8-ht8-v1
//const int nBinsMET   = 8 ;
//const int nBinsHT    = 8 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,200.,250.,300.,350.,400.,450.,600.,99999.};
//float Hbins[nBinsHT+1] = {400.,500.,600.,700.,800.,900.,1000.,1200.,99999.};

////-- met8-ht2-v1
//const int nBinsMET   = 8 ;
//const int nBinsHT    = 2 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,200.,250.,300.,350.,400.,450.,600.,99999.};
//float Hbins[nBinsHT+1] = {400.,600.,99999.};



//TString sMbins[nBinsMET];
//TString sHbins[nBinsHT];
//TString sBbins[3] = {"_1b","_2b","_3b"};

//TString cMbins[nBinsMET];
//TString cHbins[nBinsHT];
  ////// TString cBbins[3] = {"&&nB==1","&&nB==2","&&nB>=3"};
  TString cBbins[3] = {"nB==1","nB==2","nB>=3"};


  // jet pt thresholds
  double minLeadJetPt = 70. ;
  double min3rdJetPt = 50. ;


  // dummy masses
  int minGlMass = 800 ;
  int maxGlMass = 1210 ;


//double dummyYield = 9.9 ;
  double dummyCorr = 1. ;
  long dummyEvts = 10000 ;

  ofstream inFile;
  char outfile[10000] ;
  sprintf( outfile, "datfiles/T1bbbb-met%d-ht%d-v%d.dat", nBinsMET, nBinsHT, version ) ;
  inFile.open( outfile );

  // loop over gluino masses

  // TH1F* ht = new TH1F("ht","ht",10,0,10000);
  TString cutsSig = "minDelPhiN>4&&nMu==0&&nEl==0&&";
  TString cutsSL =  "minDelPhiN>4&&( (nMu==1&&nEl==0) || (nEl==1&&nMu==0) )&&";
  TString cutsLDP = "minDelPhiN<4&&nMu==0&&nEl==0&&";
  TString jetpt = "pt_1st_leadJet>";
  jetpt+= minLeadJetPt;
  jetpt+= "&&pt_2nd_leadJet>";
  jetpt+= minLeadJetPt;
  jetpt+= "&&pt_3rd_leadJet>";
  jetpt+= min3rdJetPt;
  jetpt+= "&&";
  cutsSig += jetpt;
  cutsSL += jetpt;
  cutsLDP += jetpt;


  TH2F* h_susy_sig[10] ;
  TH2F* h_susy_sl[10] ;
  TH2F* h_susy_ldp[10] ;
  for ( int bi=0; bi<nBinsBjets; bi++ ) {
     char hname[1000] ;
     sprintf( hname, "h_susy_sig_%db", bi+1 ) ;
     h_susy_sig[bi] = new TH2F( hname, hname, nBinsMET, Mbins, nBinsHT, Hbins ) ;
     h_susy_sig[bi] -> Sumw2() ;
     sprintf( hname, "h_susy_sl_%db", bi+1 ) ;
     h_susy_sl[bi] = new TH2F( hname, hname, nBinsMET, Mbins, nBinsHT, Hbins ) ;
     h_susy_sl[bi] -> Sumw2() ;
     sprintf( hname, "h_susy_ldp_%db", bi+1 ) ;
     h_susy_ldp[bi] = new TH2F( hname, hname, nBinsMET, Mbins, nBinsHT, Hbins ) ;
     h_susy_ldp[bi] -> Sumw2() ;
  }


  stringstream njcut ; njcut << nJetsCut;
  TString cutsNjets = "&&nJets>=";
  cutsNjets += njcut.str();

  float xsec = -1.;
  float xsec8TeV = -1. ;
  for ( int mGl = minGlMass ; mGl < maxGlMass ; mGl = mGl + 100 ) {

    int theBin = gluinoxsec->FindBin( mGl ) ;					      
    if ( theBin <=0 || theBin > gluinoxsec->GetNbinsX() ) {			      
       printf("\n\n *** can't find bin for mgl=%d.  Returned %d\n\n", mGl, theBin ) ; 
       return ; 								      
    }										      
    xsec = gluinoxsec->GetBinContent( theBin ) ;				      

    int theBin8TeV = gluinoxsec8TeV->FindBin( mGl ) ;					      
    if ( theBin8TeV <=0 || theBin8TeV > gluinoxsec8TeV->GetNbinsX() ) {			      
       printf("\n\n *** can't find bin for mgl=%d.  Returned %d\n\n", mGl, theBin ) ; 
       return ; 								      
    }										      
    xsec8TeV = gluinoxsec8TeV->GetBinContent( theBin8TeV ) ;				      

    printf("\n\n  SUSY Xsecs:  7 TeV = %f,  8 TeV = %f\n\n", xsec, xsec8TeV ) ;

    ////// for ( int mLsp = 50 ; mLsp < ( mGl - 25 ) ; mLsp = mLsp + 25 ) {
    for ( int mLsp = 300 ; mLsp < 710 ; mLsp = mLsp + 400 ) {

      inFile << mGl << " " << mLsp << " " << dummyEvts << " " ;
      printf(" mGl=%4d, mLsp=%4d\n", mGl, mLsp ) ; cout << flush ;


      printf("\n\n") ;
      for (int k = 0 ; k < nBinsBjets ; k++) {

         TString cutSMS = "mgluino>";
         cutSMS += mGl-1;
         cutSMS += "&&mgluino<";
         cutSMS += mGl+1;
         cutSMS += "&&mlsp>";
         cutSMS += mLsp-1;
         cutSMS += "&&mlsp<";
         cutSMS += mLsp+1;
         cutSMS += "&&";

         TString cut = cBbins[k] ;

         TString allSigCuts = cutSMS+cutsSig+cut+cutsNjets ;
         TString allSLCuts  = cutSMS+cutsSL+cut+cutsNjets ;
         TString allLDPCuts = cutSMS+cutsLDP+cut+cutsNjets ;

         char hname[1000] ;

         sprintf( hname, "h_susy_sig_%db", k+1 ) ;
         chainT1bbbb.Project( hname,"HT:MET",allSigCuts);
         printf("   mGl=%d, mLsp=%d, nBjets = %d,  SIG selection %9.1f events.\n", mGl, mLsp, k+1, h_susy_sig[k]->Integral() ) ; cout << flush ;

         sprintf( hname, "h_susy_sl_%db", k+1 ) ;
         chainT1bbbb.Project( hname,"HT:MET",allSLCuts);
         printf("   mGl=%d, mLsp=%d, nBjets = %d,  SL  selection %9.1f events.\n", mGl, mLsp, k+1, h_susy_sl[k]->Integral() ) ; cout << flush ;

         sprintf( hname, "h_susy_ldp_%db", k+1 ) ;
         chainT1bbbb.Project( hname,"HT:MET",allLDPCuts);
         printf("   mGl=%d, mLsp=%d, nBjets = %d,  LDP selection %9.1f events.\n", mGl, mLsp, k+1, h_susy_ldp[k]->Integral() ) ; cout << flush ;

      } // k (nBjets)
      printf("\n\n") ;

      printf("----------------\n") ;
      for (int i = 0 ; i < nBinsMET ; i++) {
        for (int j = 0 ; j < nBinsHT ; j++) {
          for (int k = 0 ; k < nBinsBjets ; k++) {

             printf ( " Raw MC counts: mGl=%d, mLsp=%d: MET,HT (%d,%d) nb=%d   SIG = %9.0f, SL=%9.0f, LDP=%9.0f\n",
                 mGl, mLsp, i+1, j+1, k+1,
                 h_susy_sig[k] -> GetBinContent( i+1, j+1 ),
                 h_susy_sl[k]  -> GetBinContent( i+1, j+1 ),
                 h_susy_ldp[k] -> GetBinContent( i+1, j+1 )  ) ;

          } // k
          printf("----------------\n") ;
        } // j
      } // i
      printf("\n\n") ;


      float totalSUSYyield = 0;
      printf("----------------\n") ;
      for (int i = 0 ; i < nBinsMET ; i++) {
        for (int j = 0 ; j < nBinsHT ; j++) {
          for (int k = 0 ; k < nBinsBjets ; k++) {

         //-- Aug 31, 2012: This is for using the 7TeV T1bbbb to get 8TeV 15 fb normalization.
         //
         // each point has 10k events generated. The sigma is in pb and I want to normalized to 15 fb-1. 
         // so multiple cross section by 1.5 to get events in 15 fb-1

             inFile << 1.5*xsec8TeV*(h_susy_sig[k] -> GetBinContent( i+1, j+1 )) << " " ;
             inFile << 1.5*xsec8TeV*(h_susy_sl[k]  -> GetBinContent( i+1, j+1 )) << " " ;
             inFile << 1.5*xsec8TeV*(h_susy_ldp[k] -> GetBinContent( i+1, j+1 )) << " " ;

             totalSUSYyield += (h_susy_sig[k] -> GetBinContent( i+1, j+1 )*1.5*xsec8TeV);

                double nsel_sig = h_susy_sig[k] -> GetBinContent( i+1, j+1 ) ;
                double nsel_sl  = h_susy_sl[k]  -> GetBinContent( i+1, j+1 ) ;
                double nsel_ldp = h_susy_ldp[k] -> GetBinContent( i+1, j+1 ) ;
                double nevt_err_sig = 1 ;
                double nevt_err_sl  = 1 ;
                double nevt_err_ldp = 1 ;
                if ( nsel_sig > 0. ) { nevt_err_sig = 1.5*xsec8TeV*sqrt(nsel_sig) ; }
                if ( nsel_sl  > 0. ) { nevt_err_sl  = 1.5*xsec8TeV*sqrt(nsel_sl ) ; }
                if ( nsel_ldp > 0. ) { nevt_err_ldp = 1.5*xsec8TeV*sqrt(nsel_ldp) ; }

             printf ( " xsec8TeV weighted events: mGl=%d, mLsp=%d: MET,HT (%d,%d) nb=%d   SIG = %6.1f +/- %4.1f,   SL=%6.1f +/- %4.1f,   LDP=%6.1f +/- %4.1f\n",
                 mGl, mLsp, i+1, j+1, k+1,
                 1.5*xsec8TeV*(h_susy_sig[k] -> GetBinContent( i+1, j+1 )), nevt_err_sig,
                 1.5*xsec8TeV*(h_susy_sl[k]  -> GetBinContent( i+1, j+1 )), nevt_err_sl,
                 1.5*xsec8TeV*(h_susy_ldp[k] -> GetBinContent( i+1, j+1 )), nevt_err_ldp  ) ;

         //-- Aug 31, 2012: This is for 7TeV T1bbbb with 5 fb normalization.
         //
         // each point has 10k events generated. The sigma is in pb and I want to normalized to 5 fb-1. 
         // so multiple cross section by 0.5 to get events in 5 fb-1

      ////   inFile << 0.5*xsec*(h_susy_sig[k] -> GetBinContent( i+1, j+1 )) << " " ;
      ////   inFile << 0.5*xsec*(h_susy_sl[k]  -> GetBinContent( i+1, j+1 )) << " " ;
      ////   inFile << 0.5*xsec*(h_susy_ldp[k] -> GetBinContent( i+1, j+1 )) << " " ;

      ////   totalSUSYyield += (h_susy_sig[k] -> GetBinContent( i+1, j+1 )*0.5*xsec);

      ////      double nsel_sig = h_susy_sig[k] -> GetBinContent( i+1, j+1 ) ;
      ////      double nsel_sl  = h_susy_sl[k]  -> GetBinContent( i+1, j+1 ) ;
      ////      double nsel_ldp = h_susy_ldp[k] -> GetBinContent( i+1, j+1 ) ;
      ////      double nevt_err_sig = 1 ;
      ////      double nevt_err_sl  = 1 ;
      ////      double nevt_err_ldp = 1 ;
      ////      if ( nsel_sig > 0. ) { nevt_err_sig = 0.5*xsec*sqrt(nsel_sig) ; }
      ////      if ( nsel_sl  > 0. ) { nevt_err_sl  = 0.5*xsec*sqrt(nsel_sl ) ; }
      ////      if ( nsel_ldp > 0. ) { nevt_err_ldp = 0.5*xsec*sqrt(nsel_ldp) ; }

      ////   printf ( " Xsec weighted events: mGl=%d, mLsp=%d: MET,HT (%d,%d) nb=%d   SIG = %6.1f +/- %4.1f,   SL=%6.1f +/- %4.1f,   LDP=%6.1f +/- %4.1f\n",
      ////       mGl, mLsp, i+1, j+1, k+1,
      ////       0.5*xsec*(h_susy_sig[k] -> GetBinContent( i+1, j+1 )), nevt_err_sig,
      ////       0.5*xsec*(h_susy_sl[k]  -> GetBinContent( i+1, j+1 )), nevt_err_sl,
      ////       0.5*xsec*(h_susy_ldp[k] -> GetBinContent( i+1, j+1 )), nevt_err_ldp  ) ;

          } // k
          printf("----------------\n") ;
        } // j
      } // i
      printf("Total SUSY yield within current binning = %9.1f", totalSUSYyield);
      printf("\n\n") ;



  //----------------------------------------------------------------------------

      for (int i = 0 ; i < nBinsMET ; i++) {
        for (int j = 0 ; j < nBinsHT ; j++) {
          for (int k = 0 ; k < nBinsBjets ; k++) {
            inFile << dummyCorr << " " << dummyCorr << " " << dummyCorr << " " ;
          }
        }
      }

      printf("----------------\n") ;
      for (int i = 0 ; i < nBinsMET ; i++) {
        for (int j = 0 ; j < nBinsHT ; j++) {
          for (int k = 0 ; k < nBinsBjets ; k++) {
             if ( flatDummyErr >= 0 ) {

                inFile << flatDummyErr << " " << flatDummyErr << " " << flatDummyErr << " " ;

             } else {

                //-- compute approximate stat err.
                //-- This is 100* sig_eff / eff = 100 * [sqrt(sel)/N]/[sel/N] = 100/sqrt(sel).
                double nsel_sig = h_susy_sig[k] -> GetBinContent( i+1, j+1 ) ;
                double nsel_sl  = h_susy_sl[k]  -> GetBinContent( i+1, j+1 ) ;
                double nsel_ldp = h_susy_ldp[k] -> GetBinContent( i+1, j+1 ) ;
                double frerr_sig = 100 ;
                double frerr_sl  = 100 ;
                double frerr_ldp = 100 ;
                if ( nsel_sig > 0. ) { frerr_sig = 100./sqrt(nsel_sig) ; }
                if ( nsel_sl  > 0. ) { frerr_sl  = 100./sqrt(nsel_sl ) ; }
                if ( nsel_ldp > 0. ) { frerr_ldp = 100./sqrt(nsel_ldp) ; }

                inFile << frerr_sig << " " << frerr_sl << " " << frerr_ldp << " " ;

                printf ( " MC sig_eff/eff (%%): mGl=%d, mLsp=%d: MET,HT (%d,%d) nb=%d   SIG = %5.1f,   SL=%5.1f,   LDP=%5.1f\n",
                    mGl, mLsp, i+1, j+1, k+1,
                    frerr_sig, frerr_sl, frerr_ldp ) ;
             }
          }
          printf("----------------\n") ;
        }
      }
      printf("\n\n") ;

      inFile << endl ;

    } // mLsp
  } // mGl


  // print out header line:
  inFile << "Using HT bins:  " ;
  for (int j = 0 ; j <= nBinsHT ; j++ ) {
    inFile << Hbins[j] ;
    if ( j < nBinsHT ) inFile << "-" ;
  }

  inFile << "\t Using MET bins: " ;
  for (int i = 0 ; i <= nBinsMET ; i++ ) {
    inFile << Mbins[i] ;
    if ( i < nBinsMET ) inFile << "-" ;
  }
  inFile << endl ;


  return;

}
コード例 #2
0
void 
//HTT_TT_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., string inputfile="root/$HISTFILE", const char* directory="tauTau_$CATEGORY")
HHH_TT_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., string inputfile="root/$HISTFILE", const char* directory="tauTau_$CATEGORY")
{
  // defining the common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  // determine category tag
  const char* category = ""; const char* category_extra = ""; const char* category_extra2 = "";
  if(std::string(directory) == std::string("tauTau_2jet0tag")){ category = "#tau_{h}#tau_{h}";           }
  if(std::string(directory) == std::string("tauTau_2jet0tag")){ category_extra= "2-jet 0 b-tag";           }
  if(std::string(directory) == std::string("tauTau_2jet1tag"  )){ category = "#tau_{h}#tau_{h}";           }
  if(std::string(directory) == std::string("tauTau_2jet1tag"  )){ category_extra= "2-jet 1 b-tag";     }
  if(std::string(directory) == std::string("tauTau_2jet2tag"  )){ category = "#tau_{h}#tau_{h}";           }
  if(std::string(directory) == std::string("tauTau_2jet2tag"  )){ category_extra = "2-jet 2 b-tag";              }

  const char* dataset;
#ifdef MSSM
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "#scale[1.5]{CMS}  h,H,A#rightarrow#tau#tau                                 4.9 fb^{-1} (7 TeV)";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){
    if(std::string(directory).find("btag")!=std::string::npos){
      dataset = "#scale[1.5]{CMS}  h,H,A#rightarrow#tau#tau                                18.3 fb^{-1} (8 TeV)";
    }
    else{
      dataset = "#scale[1.5]{CMS}  h,H,A#rightarrow#tau#tau                                19.7 fb^{-1} (8 TeV)";
    }
  }
#else
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS, 19.7 fb^{-1} at 8 TeV";}
#endif
  
  // open example histogram file
  TFile* input = new TFile(inputfile.c_str());
#ifdef MSSM
  TFile* input2 = new TFile((inputfile+"_$MA_$TANB").c_str());
#endif
  TH1F* Fakes  = refill((TH1F*)input->Get(TString::Format("%s/QCD"     , directory)), "QCD"); InitHist(Fakes, "", "", TColor::GetColor(250,202,255), 1001);
  TH1F* EWK1   = refill((TH1F*)input->Get(TString::Format("%s/W"       , directory)), "W"  ); InitHist(EWK1 , "", "", TColor::GetColor(222,90,106), 1001);
  TH1F* EWK2   = refill((TH1F*)input->Get(TString::Format("%s/ZJ"      , directory)), "ZJ" ); InitHist(EWK2 , "", "", TColor::GetColor(222,90,106), 1001);
//TH1F* EWK3   = refill((TH1F*)input->Get(TString::Format("%s/ZL"      , directory)), "ZL" ); InitHist(EWK3 , "", "", TColor::GetColor(222,90,106), 1001);
  TH1F* EWK    = refill((TH1F*)input->Get(TString::Format("%s/VV"      , directory)), "VV" ); InitHist(EWK  , "", "", TColor::GetColor(222,90,106), 1001);
  TH1F* ttbar  = refill((TH1F*)input->Get(TString::Format("%s/TT"      , directory)), "TT" ); InitHist(ttbar, "", "", TColor::GetColor(155,152,204), 1001);
  TH1F* Ztt    = refill((TH1F*)input->Get(TString::Format("%s/ZTT"     , directory)), "ZTT"); InitHist(Ztt  , "", "", TColor::GetColor(248,206,104), 1001);
#ifdef MSSM
  TH1F* ggHTohhTo2Tau2B    = refill((TH1F*)input2->Get(TString::Format("%s/ggHTohhTo2Tau2B$MA" , directory)), "ggHTohhTo2Tau2B"); InitSignal(ggHTohhTo2Tau2B); ggHTohhTo2Tau2B->Scale(SIGNAL_SCALE);
  TH1F* ggAToZhToLLTauTau = refill((TH1F*)input2->Get(TString::Format("%s/ggAToZhToLLTauTau$MA",directory)),"ggAToZhToLLTauTau"); InitSignal(ggAToZhToLLTauTau);
  TH1F* ggAToZhToLLBB = refill((TH1F*)input2->Get(TString::Format("%s/ggAToZhToLLBB$MA",directory)),"ggAToZhToLLBB"); InitSignal(ggAToZhToLLBB);
  TH1F* bbH    = refill((TH1F*)input2->Get(TString::Format("%s/bbH$MA" , directory)), "bbH"); InitSignal(bbH);
#endif
#ifdef ASIMOV
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs_asimov", directory)), "data", true);
#else
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data",true);
#endif
  InitHist(data, "#bf{m_{H} [GeV]}", "#bf{dN/dm_{H} [1/GeV]}"); InitData(data);

  TH1F* ref=(TH1F*)Fakes->Clone("ref");
  ref->Add(EWK1 );
  ref->Add(EWK2 );
//ref->Add(EWK3 );
  ref->Add(EWK );
  ref->Add(ttbar);
  ref->Add(Ztt  );

  double unscaled[8];
  unscaled[0] = Fakes->Integral();
  unscaled[1] = EWK  ->Integral();
  unscaled[1]+= EWK1 ->Integral();
  unscaled[1]+= EWK2 ->Integral();
//unscaled[1]+= EWK3 ->Integral();
  unscaled[2] = ttbar->Integral();
  unscaled[3] = Ztt  ->Integral();
#ifdef MSSM
  unscaled[4] = ggHTohhTo2Tau2B  ->Integral();
  unscaled[5] = ggAToZhToLLTauTau->Integral();
  unscaled[6] = ggAToZhToLLBB->Integral();
  unscaled[7] = bbH  ->Integral();
#endif

  if(scaled){

/*    Fakes = refill(shape_histos(Fakes, datacard, "QCD"), "QCD");
    EWK1  = refill(shape_histos(EWK1, datacard, "W"), "W");
    EWK2  = refill(shape_histos(EWK2, datacard, "ZJ"), "ZJ");
    EWK   = refill(shape_histos(EWK, datacard, "VV"), "VV");
    ttbar = refill(shape_histos(ttbar, datacard, "TT"), "TT"); 
    Ztt   = refill(shape_histos(Ztt, datacard, "ZTT"), "ZTT"); 
#ifdef MSSM
    ggH = refill(shape_histos(ggH, datacard, "ggH$MA"), "ggH$MA"); 
    bbH = refill(shape_histos(bbH, datacard, "bbH$MA"), "bbH$MA"); 
#else
    ggH = refill(shape_histos(ggH, datacard, "ggH"), "ggH");
    qqH = refill(shape_histos(qqH, datacard, "qqH"), "qqH");
    VH  = refill(shape_histos(VH, datacard, "VH"), "VH"); 
#endif
*/
    rescale(Fakes, 7); 
    rescale(EWK1 , 3); 
    rescale(EWK2 , 4); 
  //rescale(EWK3 , 5);
    rescale(EWK  , 6); 
    rescale(ttbar, 2); 
    rescale(Ztt  , 1);
#ifdef MSSM
    rescale(ggHTohhTo2Tau2B  , 8); 
    rescale(ggAToZhToLLTauTau,9);
    rescale(ggAToZhToLLBB,10);
    rescale(bbH  , 11);  
#endif
  }

  TH1F* scales[8];
  scales[0] = new TH1F("scales-Fakes", "", 8, 0, 8);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (Fakes->Integral()/unscaled[0]-1.) : 0.);
  scales[1] = new TH1F("scales-EWK"  , "", 8, 0, 8);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? ((EWK  ->Integral()
					       +EWK1 ->Integral()
					       +EWK2 ->Integral()
					      //+EWK3 ->Integral()
						)/unscaled[1]-1.) : 0.);
  scales[2] = new TH1F("scales-ttbar", "", 8, 0, 8);
  scales[2]->SetBinContent(3, unscaled[2]>0 ? (ttbar->Integral()/unscaled[2]-1.) : 0.);
  scales[3] = new TH1F("scales-Ztt"  , "", 8, 0, 8);
  scales[3]->SetBinContent(4, unscaled[3]>0 ? (Ztt  ->Integral()/unscaled[3]-1.) : 0.);
#ifdef MSSM
  scales[4] = new TH1F("scales-ggHTohhTo2Tau2B"  , "", 8, 0, 8);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggHTohhTo2Tau2B  ->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-ggAToZhToLLTauTau"  , "", 8, 0, 8);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (ggAToZhToLLTauTau  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-ggAToZhToLLBB"  , "", 8, 0, 8);
  scales[6]->SetBinContent(7, unscaled[6]>0 ? (ggAToZhToLLBB  ->Integral()/unscaled[6]-1.) : 0.);
  scales[7] = new TH1F("scales-bbH"  , "", 8, 0, 8);
  scales[7]->SetBinContent(8, unscaled[7]>0 ? (bbH  ->Integral()/unscaled[7]-1.) : 0.);
#endif

//#ifdef MSSM
//  qqH_SM125->Add(ggH_SM125);
 // VH_SM125->Add(qqH_SM125);
 // Fakes->Add(VH_SM125);
//#endif
  Fakes->Add(ttbar);
  EWK1 ->Add(Fakes);
  EWK2 ->Add(EWK1 );
//EWK3 ->Add(EWK2 );
//EWK  ->Add(EWK3 );
  EWK  ->Add(EWK2 );
//  ttbar->Add(EWK  );
  Ztt  ->Add(EWK);
  //if(log){
//#ifdef MSSM
 //   ggH->Add(bbH);
//#else
 //   qqH->Add(VH );
  //  ggH->Add(qqH);
//#endif
 // }
  //else{
//#ifdef MSSM    
 //   bbH->Add(Ztt);
  //  ggH->Add(bbH);
//#else
 //   VH ->Add(Ztt);
  //  qqH->Add(VH );
   // ggH->Add(qqH);
//#endif
 // }

  /*
    Mass plot before and after fit
  */
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);

  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(200, data->FindBin(UPPER_EDGE)); } else{ data->GetXaxis()->SetRange(200, data->FindBin(UPPER_EDGE)); };
#else
  data->GetXaxis()->SetRange(200, data->FindBin(UPPER_EDGE));
#endif
  data->SetNdivisions(505);
  data->SetMinimum(min);
  data->SetMaximum(max>0 ? max : std::max(std::max(maximum(data, log), maximum(Ztt, log)), maximum(ggHTohhTo2Tau2B, log)));
  data->Draw("e");

  TH1F* errorBand = (TH1F*)Ztt ->Clone();
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(13);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
    if(errorBand->GetBinContent(idx)>0){
      std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
      break;
    }
  }
  if(log){
    Ztt  ->Draw("histsame");
//    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    Fakes->Draw("histsame");
    ttbar->Draw("histsame");
//#ifdef MSSM
//    VH_SM125->Draw("histsame");
//#endif
    $DRAW_ERROR
    ggHTohhTo2Tau2B  ->Draw("histsame");
  }
  else{
    ggHTohhTo2Tau2B  ->Draw("histsame");
    Ztt  ->Draw("histsame");
//    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    Fakes->Draw("histsame");
    ttbar->Draw("histsame");
#ifdef MSSM
    //VH_SM125->Draw("histsame");
#endif
    $DRAW_ERROR
  }
  data->Draw("esame");
  canv->RedrawAxis();

  //CMSPrelim(dataset, "#tau_{h}#tau_{h}", 0.17, 0.835);
  CMSPrelim(dataset, "", 0.16, 0.835);  
#if defined MSSM
  TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "tlbrNDC");
  if (strcmp(category_extra2,"")!=0) chan     = new TPaveText(0.20, 0.69+0.061, 0.32, 0.74+0.161, "tlbrNDC");
#else
  TPaveText* chan     = new TPaveText(0.52, 0.35, 0.91, 0.55, "tlbrNDC");
#endif
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText(category);
  chan->AddText(category_extra);
#if defined MSSM
  if (strcmp(category_extra2,"")!=0) chan->AddText(category_extra2);
#else
  chan->AddText(category_extra2);
#endif
  chan->Draw();
/*
  TPaveText* cat      = new TPaveText(0.20, 0.71+0.061, 0.32, 0.71+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();

  TPaveText* cat2      = new TPaveText(0.20, 0.66+0.061, 0.32, 0.66+0.161, "NDC");
  cat2->SetBorderSize(   0 );
  cat2->SetFillStyle(    0 );
  cat2->SetTextAlign(   12 );
  cat2->SetTextSize ( 0.05 );
  cat2->SetTextColor(    1 );
  cat2->SetTextFont (   62 );
  cat2->AddText(category_extra2);
  cat2->Draw();
*/  
#ifdef MSSM
  TPaveText* massA      = new TPaveText(0.53, 0.44+0.061, 0.95, 0.44+0.151, "NDC");
  massA->SetBorderSize(   0 );
  massA->SetFillStyle(    0 );
  massA->SetTextAlign(   12 );
  massA->SetTextSize ( 0.03 );
  massA->SetTextColor(    1 );
  massA->SetTextFont (   62 );
  massA->AddText("MSSM m^{h}_{mod+} scenario");
  massA->AddText("m_{A}=$MA GeV, tan#beta=$TANB");
  massA->Draw();
#endif
  
#ifdef MSSM
  TLegend* leg = new TLegend(0.53, 0.60, 0.95, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(ggHTohhTo2Tau2B  , TString::Format("%0.f #times H#rightarrowhh#rightarrow#tau#taubb", SIGNAL_SCALE) , "L" );
#endif
#ifdef ASIMOV
  leg->AddEntry(data , "sum(bkg) + H(125)"              , "LP");
#else
  leg->AddEntry(data , "Observed"                       , "LP");
#endif
  leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
  leg->AddEntry(EWK  , "Electroweak"                    , "F" );
  leg->AddEntry(Fakes, "QCD"                            , "F" );
  leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
/*#ifdef MSSM
  leg->AddEntry(VH_SM125, "SM H(125 GeV) #rightarrow #tau#tau", "F" );
#endif
*/
  $ERROR_LEGEND
  leg->Draw();

  /*
    Ratio Data over MC
  */
  TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
  canv0->SetGridx();
  canv0->SetGridy();
  canv0->cd();

  TH1F* model = (TH1F*)Ztt ->Clone("model");
  TH1F* test1 = (TH1F*)data->Clone("test1"); 
  for(int ibin=0; ibin<test1->GetNbinsX(); ++ibin){
    //the small value in case of 0 entries in the model is added to prevent the chis2 test from failing
    model->SetBinContent(ibin+1, model->GetBinContent(ibin+1)>0 ? model->GetBinContent(ibin+1)*model->GetBinWidth(ibin+1) : 0.01);
    model->SetBinError  (ibin+1, CONSERVATIVE_CHI2 ? 0. : model->GetBinError  (ibin+1)*model->GetBinWidth(ibin+1));
    test1->SetBinContent(ibin+1, test1->GetBinContent(ibin+1)*test1->GetBinWidth(ibin+1));
    test1->SetBinError  (ibin+1, test1->GetBinError  (ibin+1)*test1->GetBinWidth(ibin+1));
  }
  double chi2prob = test1->Chi2Test      (model,"PUW");        std::cout << "chi2prob:" << chi2prob << std::endl;
  double chi2ndof = test1->Chi2Test      (model,"CHI2/NDFUW"); std::cout << "chi2ndf :" << chi2ndof << std::endl;
  double ksprob   = test1->KolmogorovTest(model);              std::cout << "ksprob  :" << ksprob   << std::endl;
  double ksprobpe = test1->KolmogorovTest(model,"DX");         std::cout << "ksprobpe:" << ksprobpe << std::endl;  

  std::vector<double> edges;
  TH1F* zero = (TH1F*)ref->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)data->Clone("rat1"); 
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    rat1->SetBinContent(ibin+1, Ztt->GetBinContent(ibin+1)>0 ? data->GetBinContent(ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
    rat1->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? data->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
    zero->SetBinContent(ibin+1, 0.);
    zero->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? Ztt ->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat1->GetBinContent(ibin+1)-1.)+TMath::Abs(rat1->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
  }
  float range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+range);
  rat1->SetMinimum(-range);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
  rat1->GetXaxis()->SetTitle("#bf{m_{H} [GeV]}");
  rat1->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->SetMarkerSize(0.1);
  zero->Draw("e2histsame");
  canv0->RedrawAxis();

  TPaveText* stat1 = new TPaveText(0.20, 0.76+0.061, 0.32, 0.76+0.161, "NDC");
  stat1->SetBorderSize(   0 );
  stat1->SetFillStyle(    0 );
  stat1->SetTextAlign(   12 );
  stat1->SetTextSize ( 0.05 );
  stat1->SetTextColor(    1 );
  stat1->SetTextFont (   62 );
  stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f", chi2ndof, chi2prob));
  //stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f, P(KS)=%.3f", chi2ndof, chi2prob, ksprob));
  stat1->Draw();

  /*
    Ratio After fit over Prefit
  */
  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  edges.clear();
  TH1F* rat2 = (TH1F*) Ztt->Clone("rat2");
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    rat2->SetBinContent(ibin+1, ref->GetBinContent(ibin+1)>0 ? Ztt->GetBinContent(ibin+1)/ref->GetBinContent(ibin+1) : 0);
    rat2->SetBinError  (ibin+1, ref->GetBinContent(ibin+1)>0 ? Ztt->GetBinError  (ibin+1)/ref->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    if(rat2->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat2->GetBinContent(ibin+1)-1.)+TMath::Abs(rat2->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
    }
  }
  range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
#if defined MSSM
  if(!log){ rat2->GetXaxis()->SetRange(200, rat2->FindBin(UPPER_EDGE)); } else{ rat2->GetXaxis()->SetRange(200, rat2->FindBin(UPPER_EDGE)); };
#else
  rat2->GetXaxis()->SetRange(200, rat2->FindBin(UPPER_EDGE));
#endif
  rat2->SetNdivisions(505);
  rat2->SetLineColor(kRed+ 3);
  rat2->SetMarkerColor(kRed+3);
  rat2->SetMarkerSize(1.1);
  rat2->SetMaximum(+range);
  rat2->SetMinimum(-range);
  rat2->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  rat2->GetYaxis()->CenterTitle();
  rat2->GetXaxis()->SetTitle("#bf{m_{H} [GeV]}");
  rat2->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->Draw("e2histsame");
  canv1->RedrawAxis();

  /*
    Relative shift per sample
  */
  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
  canv2->SetGridx();
  canv2->SetGridy();
  canv2->cd();

  InitHist  (scales[0], "", "", TColor::GetColor(250,202,255), 1001);
  InitHist  (scales[1], "", "", TColor::GetColor(222,90,106), 1001);
  InitHist  (scales[2], "", "", TColor::GetColor(155,152,204), 1001);
  InitHist  (scales[3], "", "", TColor::GetColor(248,206,104), 1001);
  InitHist(scales[4],"","",kGreen+2,1001);
  InitHist(scales[5],"","",kGreen+2,1001);
  InitHist(scales[6],"","",kGreen+2,1001);
  InitHist(scales[7],"","",kGreen+2,1001);

  scales[0]->Draw();
  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{Fakes}");
  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{EWK}"  );
  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{ttbar}");
  scales[0]->GetXaxis()->SetBinLabel(4, "#bf{Ztt}"  );
#ifdef MSSM
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggHTohhTo2tau2B}"  );
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{ggAToZhToLLTauTau}");
  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{ggAToZhToLLBB}");
  scales[0]->GetXaxis()->SetBinLabel(8, "#bf{bbH}"  );
#endif
  scales[0]->SetMaximum(+0.5);
  scales[0]->SetMinimum(-0.5);
  scales[0]->GetYaxis()->CenterTitle();
  scales[0]->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  scales[1]->Draw("same");
  scales[2]->Draw("same");
  scales[3]->Draw("same");
  scales[4]->Draw("same");
  scales[5]->Draw("same");
  scales[6]->Draw("same");
  TH1F* zero_samples = (TH1F*)scales[0]->Clone("zero_samples"); zero_samples->Clear();
  zero_samples->SetBinContent(1,0.);
  zero_samples->Draw("same"); 
  canv2->RedrawAxis();

  /*
    prepare output
  */
  bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.png"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.pdf"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.eps"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  if(!log || FULLPLOTS)
  {
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }
  if((!log && scaled) || FULLPLOTS)
  {
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }

  TFile* output = new TFile(TString::Format("%s_%sfit_%s_%s.root", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"), "update");
  output->cd(); 
  data ->Write("data_obs");
  Fakes->Write("Fakes"   );
  EWK  ->Write("EWK"     );
  ttbar->Write("ttbar"   );
  Ztt  ->Write("Ztt"     );
#ifdef MSSM
  ggHTohhTo2Tau2B  ->Write("ggHTohhTo2Tau2B"     );
  ggAToZhToLLTauTau->Write("ggAToZhToLLTauTau");
  ggAToZhToLLBB->Write("ggAToZhToLLBB");
  bbH  ->Write("bbH"     );
#endif
  output->Close();
 
  delete errorBand;
  delete model;
  delete test1;
  delete zero;
  delete rat1;
  delete rat2;
  delete zero_samples;
  delete ref;
}
コード例 #3
0
void AlignTopAndBottomTOFs(string ArrayPart="NV",Float_t Start=-5,Float_t End=25){
  
  for (int bar=1;bar<13;bar++){
    stringstream nameTop;
    stringstream nameBottom;

    nameTop<<ArrayPart<<setfill('0')<<setw(2)<<bar<<"_TopCutTOFPr";
    TH1F * CurrentTop = (TH1F*)gDirectory->Get(nameTop.str().c_str());


    nameBottom<<ArrayPart<<setfill('0')<<setw(2)<<bar<<"_BottomCutTOFPr";
    TH1F * CurrentBottom = (TH1F*)gDirectory->Get(nameBottom.str().c_str());
  
    // TCanvas *c=new TCanvas("c");
    // c->cd(1);
    // CurrentTop->Draw();
    // CurrentBottom->Draw("same");

    int binsTop = CurrentTop->GetNbinsX();

    int binsBottom= CurrentBottom->GetNbinsX();
  
    if ( binsTop !=binsBottom){
      cout<<"Nubmer of bins for the top channel not the same as for the bottom channel"<<endl;
      cout<<"This was for "<<CurrentTop->GetName()<<" and "<<CurrentBottom->GetName()<<endl;
      return;
    }
  
    int bins=binsTop;
  
    double topLow = CurrentTop->GetBinLowEdge(1);//ROOT histograms start at bin 1. bin 0 is underflow
    double topHigh= CurrentBottom->GetBinLowEdge(binsTop) +CurrentBottom->GetBinWidth(binsTop);//ROOT histograms end at bin N. N+1 is overflow bin.

    double NanoSecsPerBin = ((topHigh-topLow)*4)/binsTop;
  
    //    cout<<topLow<<" "<<topHigh<<endl;
    //    cout<<"NanoSecsPerBin "<<NanoSecsPerBin<<endl;
  
 
    int ForthOfBins = TMath::Floor(0.25* bins);
    int EighthOfBins = TMath::Floor( (1.0/8)* bins);

    int NumberOfShifts = 2*EighthOfBins; // 1/8 of the number of bins *2 for left/right shifts
  
    int TopZeroBin = CurrentTop->GetMaximumBin();
  
    int StartBin = CurrentTop->FindBin(Start);
    int EndBin = CurrentTop->FindBin(End);

    //Find shift That moves Bottom -> Top
    vector <double> TheChi2s;
    vector <int> TheShifts;
    for (int i=0;i<NumberOfShifts;i++){
      double binShift = (i - NumberOfShifts/2);

      double chi2=0;
      // cout<<"Looking in bin range "<<TopZeroBin-EighthOfBins<<" "<<TopZeroBin+EighthOfBins<<endl;
      // cout<<"That is from "<<CurrentTop->GetBinCenter(TopZeroBin-EighthOfBins)<<" "<<CurrentTop->GetBinCenter(TopZeroBin+EighthOfBins)<<endl;

      for (int bin=StartBin ;bin<EndBin;bin++){
	double b = CurrentBottom->GetBinContent(bin + binShift);
	double t = CurrentTop->GetBinContent(bin);
	if (b !=0 && t!=0){
	  double temp =((b-t)*(b-t))/( TMath::Sqrt(t) );
	  chi2+=temp;
	}
      }
    
      TheChi2s.push_back(chi2);
      TheShifts.push_back(binShift);

    }
  
    ///Find miminum by linear search 
    double min = 9999999999.0;
    int MinSpot=-1;
    for (int i=0;i<NumberOfShifts;i++){
      if ( TheChi2s[i] < min){
	min=TheChi2s[i];
	MinSpot=i;
      }
    }

    cout<<ArrayPart<<setfill('0')<<setw(2)<<bar<<"B  "<<"1  0  "<<fixed<<setw(6)<<setprecision(4)<<TheShifts[MinSpot]/4.0*NanoSecsPerBin<<endl;
    cout<<ArrayPart<<setfill('0')<<setw(2)<<bar<<"T  "<<"1  0  0"<<endl;

  }


  cout<<"There were "<<NanoSecsPerBin<<" nano secs per bin"<<endl;
  // TGraph * graph = new TGraph();
  
  // cout<<"Size of Chi2s "<<TheChi2s.size()<<endl;
  // cout<<"Num "<<NumberOfShifts<<endl;

  // for (int i=0;i<NumberOfShifts;i++){
  //   graph->SetPoint(i,TheShifts[i],TheChi2s[i]);
  // }

  // TCanvas *c2 = new TCanvas("c2");
  // c2->cd(1);
  // graph->Draw("A*");


}
コード例 #4
0
ファイル: MakeTrendingITSQA.C プロジェクト: ktf/AliPhysics
Int_t MakeTrendingITSQA(TString qafilename ="QAresults.root",       //full path of the QA output; set IsOnGrid to prepend "alien://"
                        Int_t runNumber= 133005,          // run number
                        Bool_t isMC=kFALSE,       //MC flag, to disable meaningless checks
                        Bool_t canvasE = kFALSE,  //enable display plots on canvas and save png
                        Bool_t IsOnGrid = kFALSE, //set to kTRUE to access files on the grid
                        TString ocdbStorage = "raw://") //set the default ocdb storage
{
    // macro to generate tree with ITS QA trending variables
    // access qa PWGPP output files
    if (!qafilename) {
        Printf("Error - Invalid input file");
        return 1;
    }



    char defaultQAoutput[30]="QAresults.root";
    char * treePostFileName="trending.root";

    if (IsOnGrid) TGrid::Connect("alien://");
    TFile * fin = TFile::Open(qafilename,"r");
    if (!fin) {
        Printf("ERROR: QA output not found. Exiting...\n");
        return -1;
    } else {
        Printf("INFO: QA output file %s open. \n",fin->GetName());
    }

    TFile * trendFile = new TFile(treePostFileName,"recreate");


    ///// SDD Variables
    
    Int_t nrun,nEvents, nEventsTriggered;
    Float_t minDrTime,errminDrTime,meanDrTime,errmeanDrTime;
    Float_t fracTrackWithClu1,fracTrackWithClu2,errfracTrackWithClu1,errfracTrackWithClu2;
    Float_t fracTrackWithClu3,fracTrackWithClu4,errfracTrackWithClu3,errfracTrackWithClu4;
    Float_t fracTrackWithClu5,fracTrackWithClu6,errfracTrackWithClu5,errfracTrackWithClu6;
    Float_t fracExtra,errfracExtra;
    Float_t fracT[6]={0.,0.,0.,0.,0.,0.};
    Float_t efracT[6]={0.,0.,0.,0.,0.,0.};
    Int_t nTotEvents;
    Int_t nTrigEvents;
    Double_t averPoints=0.;
    Double_t cntBins=0.;
    Float_t minTime=-999.;
    Float_t errMinTime=0.;
    Float_t MPVdEdxLay3,errMPVdEdxLay3,MPVdEdxLay4,errMPVdEdxLay4;
    Float_t MPVdEdxTB0,errMPVdEdxTB0,MPVdEdxTB5,errMPVdEdxTB5;

    
    //// Vertex Variables
    
    Float_t meanVtxTRKx,meanVtxTRKy,meanVtxTRKz;
    Float_t meanVtxSPDx,meanVtxSPDy,meanVtxSPDz;
    Float_t sigmaVtxTRKx,sigmaVtxTRKy,sigmaVtxTRKz;
    Float_t sigmaVtxSPDx,sigmaVtxSPDy,sigmaVtxSPDz;
    Float_t meanVtxTRKxErr,meanVtxTRKyErr,meanVtxTRKzErr;
    Float_t meanVtxSPDxErr,meanVtxSPDyErr,meanVtxSPDzErr;
    Float_t sigmaVtxTRKxErr,sigmaVtxTRKyErr,sigmaVtxTRKzErr;
    Float_t sigmaVtxSPDxErr,sigmaVtxSPDyErr,sigmaVtxSPDzErr;
    
    
    ///// SSD Variables
    
    
    Float_t MPVL5,MPVErrL5;
    Float_t MPVL6,MPVErrL6;
    Float_t ChargeRatioL5,ChargeRatioErrL5;
    Float_t ChargeRatioL6,ChargeRatioErrL6;
    Float_t EmptyModulesSDD;


    ///// Matching Variables
    


    Float_t FracSPD1;
    Float_t errFracSPD1;
    Float_t FracSPD2;
    Float_t errFracSPD2;
    Float_t Eff6Pt02;
    Float_t errEff6Pt02;
    Float_t Eff6Pt1;
    Float_t errEff6Pt1;
    Float_t Eff6Pt10;
    Float_t errEff6Pt10;
    Float_t Eff5Pt02;
    Float_t errEff5Pt02;
    Float_t Eff5Pt1;
    Float_t errEff5Pt1;
    Float_t Eff5Pt10;
    Float_t errEff5Pt10;
    Float_t Eff4Pt02;
    Float_t errEff4Pt02;
    Float_t Eff4Pt1;
    Float_t errEff4Pt1;
    Float_t Eff4Pt10;
    Float_t errEff4Pt10;
    Float_t Eff3Pt02;
    Float_t errEff3Pt02;
    Float_t Eff3Pt1;
    Float_t errEff3Pt1;
    Float_t Eff3Pt10;
    Float_t errEff3Pt10;
    Float_t Eff2Pt02;
    Float_t errEff2Pt02;
    Float_t Eff2Pt1;
    Float_t errEff2Pt1;
    Float_t Eff2Pt10;
    Float_t errEff2Pt10;
    Float_t EffSPDPt02;
    Float_t errEffSPDPt02;
    Float_t EffSPDPt1;
    Float_t errEffSPDPt1;
    Float_t EffSPDPt10;
    Float_t errEffSPDPt10;
    Float_t EffoneSPDPt02;
    Float_t errEffoneSPDPt02;
    Float_t EffoneSPDPt1;
    Float_t errEffoneSPDPt1;
    Float_t EffoneSPDPt10;
    Float_t errEffoneSPDPt10;
    Float_t EffTOTPt02;
    Float_t errEffTOTPt02;
    Float_t EffTOTPt1;
    Float_t errEffTOTPt1;
    Float_t EffTOTPt10;
    Float_t errEffTOTPt10;
    
    

    
    
    TTree * ttree=new TTree("trending","tree of trending variables");
    ttree->Branch("nrun",&nrun,"nrun/I");
    ttree->Branch("nEvents",&nEvents,"nEvents/I");
    ttree->Branch("nEventsTriggered",&nEventsTriggered,"nEventsTriggered/I");
    ttree->Branch("minDrTime",&minDrTime,"minDrTime/F");
    ttree->Branch("errminDrTime",&errminDrTime,"errminDrTime/F");
    ttree->Branch("meanDrTime",&meanDrTime,"meanDrTime/F");
    ttree->Branch("errmeanDrTime",&errmeanDrTime,"errmeanDrTime/F"); //mean time
    ttree->Branch("fracTrackWithClu1",&fracTrackWithClu1,"fracTrackWithClu1/F"); //fraction of tracks with cluster in layer 1

    ttree->Branch("errfracTrackWithClu1",&errfracTrackWithClu1,"errfracTrackWithClu1/F"); //error fraction of tracks with cluster in layer 1
    ttree->Branch("fracTrackWithClu2",&fracTrackWithClu2,"fracTrackWithClu2/F"); //
    ttree->Branch("errfracTrackWithClu2",&errfracTrackWithClu2,"errfracTrackWithClu2/F"); //
    ttree->Branch("fracTrackWithClu3",&fracTrackWithClu3,"fracTrackWithClu3/F");
    ttree->Branch("errfracTrackWithClu3",&errfracTrackWithClu3,"errfracTrackWithClu3/F");
    ttree->Branch("fracTrackWithClu4",&fracTrackWithClu4,"fracTrackWithClu4/F");
    ttree->Branch("errfracTrackWithClu4",&errfracTrackWithClu4,"errfracTrackWithClu4/F");
    ttree->Branch("fracTrackWithClu5",&fracTrackWithClu5,"fracTrackWithClu5/F");
    ttree->Branch("errfracTrackWithClu5",&errfracTrackWithClu5,"errfracTrackWithClu5/F");
    ttree->Branch("fracTrackWithClu6",&fracTrackWithClu6,"fracTrackWithClu6/F");
    ttree->Branch("errfracTrackWithClu6",&errfracTrackWithClu6,"errfracTrackWithClu6/F");


    
    ttree->Branch("meanVtxTRKx",&meanVtxTRKx,"meanVtxTRKx/F"); // mean of tracks vertex position - x
    ttree->Branch("meanVtxTRKy",&meanVtxTRKy,"meanVtxTRKy/F"); // mean of tracks vertex position - y
    ttree->Branch("meanVtxTRKz",&meanVtxTRKz,"meanVtxTRKz/F"); // mean of tracks vertex position - z
    ttree->Branch("meanVtxTRKxErr",&meanVtxTRKxErr,"meanVtxTRKxErr/F"); // error mean of tracks vertex position - x
    ttree->Branch("meanVtxTRKyErr",&meanVtxTRKyErr,"meanVtxTRKyErr/F"); // error mean of tracks vertex position - y
    ttree->Branch("meanVtxTRKzErr",&meanVtxTRKzErr,"meanVtxTRKzErr/F"); // error mean of tracks vertex position - z

    ttree->Branch("meanVtxSPDx",&meanVtxSPDx,"meanVtxSPDx/F"); // mean of SPD vertex position - x
    ttree->Branch("meanVtxSPDy",&meanVtxSPDy,"meanVtxSPDy/F"); // mean of SPD vertex position - y
    ttree->Branch("meanVtxSPDz",&meanVtxSPDz,"meanVtxSPDz/F"); // mean of SPD vertex position - z
    ttree->Branch("meanVtxSPDxErr",&meanVtxSPDxErr,"meanVtxSPDxErr/F"); // error mean of SPD vertex position - x
    ttree->Branch("meanVtxSPDyErr",&meanVtxSPDyErr,"meanVtxSPDyErr/F"); // error mean of SPD vertex position - y
    ttree->Branch("meanVtxSPDzErr",&meanVtxSPDzErr,"meanVtxSPDzErr/F"); // error mean of SPD vertex position - z

    ttree->Branch("sigmaVtxTRKx",&sigmaVtxTRKx,"sigmaVtxTRKx/F"); // sigma of tracks vertex position - x
    ttree->Branch("sigmaVtxTRKy",&sigmaVtxTRKy,"sigmaVtxTRKy/F"); // sigma of tracks vertex position - y
    ttree->Branch("sigmaVtxTRKz",&sigmaVtxTRKz,"sigmaVtxTRKz/F"); // sigma of tracks vertex position - z
    ttree->Branch("sigmaVtxTRKxErr",&sigmaVtxTRKxErr,"sigmaVtxTRKxErr/F"); // error sigma of tracks vertex position - x
    ttree->Branch("sigmaVtxTRKyErr",&sigmaVtxTRKyErr,"sigmaVtxTRKyErr/F"); // error sigma of tracks vertex position - y
    ttree->Branch("sigmaVtxTRKzErr",&sigmaVtxTRKzErr,"sigmaVtxTRKzErr/F"); // error sigma of tracks vertex position - z

    ttree->Branch("sigmaVtxSPDx",&sigmaVtxSPDx,"sigmaVtxSPDx/F"); // sigma of tracks vertex position - x
    ttree->Branch("sigmaVtxSPDy",&sigmaVtxSPDy,"sigmaVtxSPDy/F"); // sigma of tracks vertex position - y
    ttree->Branch("sigmaVtxSPDz",&sigmaVtxSPDz,"sigmaVtxSPDz/F"); // sigma of tracks vertex position - z
    ttree->Branch("sigmaVtxSPDxErr",&sigmaVtxSPDxErr,"sigmaVtxSPDxErr/F"); // error sigma of tracks vertex position - x
    ttree->Branch("sigmaVtxSPDyErr",&sigmaVtxSPDyErr,"sigmaVtxSPDyErr/F"); // error sigma of tracks vertex position - y
    ttree->Branch("sigmaVtxSPDzErr",&sigmaVtxSPDzErr,"sigmaVtxSPDzErr/F"); // error sigma of tracks vertex position - z
    
    
    
    ttree->Branch("MPVL5",&MPVL5,"MPVL5/F"); // Most Probable Value dEdx Layer 5
    ttree->Branch("MPVErrL5",&MPVErrL5,"MPVErrL5/F"); // Most Probable Value error dEdx Layer 5

    ttree->Branch("MPVL6",&MPVL6,"MPVL6/F"); // Most Probable Value dEdx Layer 6
    ttree->Branch("MPVErrL6",&MPVErrL6,"MPVErrL6/F"); // Most Probable Value error dEdx Layer 6

    ttree->Branch("ChargeRatioL5",&ChargeRatioL5,"ChargeRatioL5/F"); // Charge ratio (2 sides of SSD) Layer 5
    ttree->Branch("ChargeRatioErrL5",&ChargeRatioErrL5,"ChargeRatioErrL5/F"); // Charge ratio error (2 sides of SSD) Layer 5

    ttree->Branch("ChargeRatioL6",&ChargeRatioL6,"ChargeRatioL6/F"); // Charge ratio (2 sides of SSD) Layer 6
    ttree->Branch("ChargeRatioErrL6",&ChargeRatioErrL6,"ChargeRatioErrL6/F"); // Charge ratio error(2 sides of SSD) Layer 6

    ttree->Branch("EmptyModulesSDD",&EmptyModulesSDD,"EmptyModulesSDD/F"); // Number of empty SSD  modules


    
    ttree->Branch("fracExtra",&fracExtra,"fracExtra/F"); // fraction of extra clusters in SDD
    ttree->Branch("errfracExtra",&errfracExtra,"errfracExtra/F"); // fraction of extra clusters in SDD
    
    ttree->Branch("minTime",&minTime,"minTime/F"); // minimum drift time SDD
    ttree->Branch("errMinTime",&errMinTime,"errMinTime/F"); //  error on minimum drift time SDD
    
    ttree->Branch("MPVdEdxLay3",&MPVdEdxLay3,"MPVdEdxLay3/F"); // most probable value of dE/Fx distribution of SDD Layer 3
    ttree->Branch("errMPVdEdxLay3",&errMPVdEdxLay3,"errMPVdEdxLay3/F"); // error  most probable value of dE/Fx distribution of SDD Layer 3

    ttree->Branch("MPVdEdxLay4",&MPVdEdxLay4,"MPVdEdxLay4/F"); // most probable value of dE/Fx distribution of SDD Layer 4
    ttree->Branch("errMPVdEdxLay4",&errMPVdEdxLay4,"errMPVdEdxLay4/F"); // error  most probable value of dE/Fx distribution of SDD Layer 4

    ttree->Branch("MPVdEdxTB0",&MPVdEdxTB0,"MPVdEdxTB0/F"); // most probable value of dE/Fx distribution of SDD - small drift time
    ttree->Branch("errMPVdEdxTB0",&errMPVdEdxTB0,"errMPVdEdxTB0/F"); // most probable value of dE/Fx distribution of SDD - small drift time

    ttree->Branch("MPVdEdxTB5",&MPVdEdxTB5,"MPVdEdxTB5/F"); // most probable value of dE/Fx distribution of SDD - large drift time
    ttree->Branch("errMPVdEdxTB5",&errMPVdEdxTB5,"errMPVdEdxTB5/F"); // most probable value of dE/Fx distribution of SDD - large drift time


    
    
    ttree->Branch("Eff6Pt02",&Eff6Pt02,"Eff6Pt02/F"); // matching efficiency low pt 6 clusters
    ttree->Branch("errEff6Pt02",&errEff6Pt02,"errEff6Pt02/F"); // error matching efficiency low pt 6 clusters
    ttree->Branch("Eff5Pt02",&Eff5Pt02,"Eff5Pt02/F"); // matching efficiency low pt 5 clusters
    ttree->Branch("errEff5Pt02",&errEff5Pt02,"errEff5Pt02/F"); // error matching efficiency low pt 5 clusters
    ttree->Branch("Eff4Pt02",&Eff4Pt02,"Eff4Pt02/F"); // matching efficiency low pt 4 clusters
    ttree->Branch("errEff4Pt02",&errEff4Pt02,"errEff4Pt02/F"); // error matching efficiency low pt 4 clusters
    ttree->Branch("Eff3Pt02",&Eff3Pt02,"Eff3Pt02/F"); // matching efficiency low pt 3 clusters
    ttree->Branch("errEff3Pt02",&errEff3Pt02,"errEff3Pt02/F"); // error matching efficiency low pt 3 clusters
    ttree->Branch("Eff2Pt02",&Eff2Pt02,"Eff2Pt02/F"); // matching efficiency low pt 2 clusters
    ttree->Branch("errEff2Pt02",&errEff2Pt02,"errEff2Pt02/F"); // error matching efficiency low pt 2 clusters
    ttree->Branch("EffSPDPt02",&EffSPDPt02,"EffSPDPt02/F"); // matching efficiency low pt 2 SPD
    ttree->Branch("errEffSPDPt02",&errEffSPDPt02,"errEffSPDPt02/F"); // error matching efficiency low pt 2 SPD
    ttree->Branch("EffoneSPDPt02",&EffoneSPDPt02,"EffoneSPDPt02/F"); // matching efficiency low pt 6 one SPD
    ttree->Branch("errEffoneSPDPt02",&errEffoneSPDPt02,"errEffoneSPDPt02/F"); // error matching efficiency low pt one SPD
    ttree->Branch("EffTOTPt02",&EffTOTPt02,"EffTOTPt02/F"); // matching efficiency low pt
    ttree->Branch("errEffTOTPt02",&errEffTOTPt02,"errEffTOTPt02/F"); // error matching efficiency low pt
    
    

    
    
    ttree->Branch("Eff6Pt1",&Eff6Pt1,"Eff6Pt1/F"); // matching efficiency mid pt 6 clusters
    ttree->Branch("errEff6Pt1",&errEff6Pt1,"errEff6Pt1/F"); // error matching efficiency mid pt 6 clusters
    ttree->Branch("Eff5Pt1",&Eff5Pt1,"Eff5Pt1/F"); // matching efficiency mid pt 5 clusters
    ttree->Branch("errEff5Pt1",&errEff5Pt1,"errEff5Pt1/F"); // error matching efficiency mid pt 5 clusters
    ttree->Branch("Eff4Pt1",&Eff4Pt1,"Eff4Pt1/F"); // matching efficiency mid pt 4 clusters
    ttree->Branch("errEff4Pt1",&errEff4Pt1,"errEff4Pt1/F"); // error matching efficiency mid pt 4 clusters
    ttree->Branch("Eff3Pt1",&Eff3Pt1,"Eff3Pt1/F"); // matching efficiency mid pt 3 clusters
    ttree->Branch("errEff3Pt1",&errEff3Pt1,"errEff3Pt1/F"); // error matching efficiency mid pt 3 clusters
    ttree->Branch("Eff2Pt1",&Eff2Pt1,"Eff2Pt1/F"); // matching efficiency mid pt 2 clusters
    ttree->Branch("errEff2Pt1",&errEff2Pt1,"errEff2Pt1/F"); // error matching efficiency mid pt 2 clusters
    ttree->Branch("EffSPDPt1",&EffSPDPt1,"EffSPDPt1/F"); // matching efficiency mid pt 2 SPD
    ttree->Branch("errEffSPDPt1",&errEffSPDPt1,"errEffSPDPt1/F"); // error matching efficiency mid pt 2 SPD
    ttree->Branch("EffoneSPDPt1",&EffoneSPDPt1,"EffoneSPDPt1/F"); // matching efficiency mid pt 6 one SPD
    ttree->Branch("errEffoneSPDPt1",&errEffoneSPDPt1,"errEffoneSPDPt1/F"); // error matching efficiency mid pt one SPD
    ttree->Branch("EffTOTPt1",&EffTOTPt1,"EffTOTPt1/F"); // matching efficiency mid pt
    ttree->Branch("errEffTOTPt1",&errEffTOTPt1,"errEffTOTPt1/F"); // error matching efficiency mid pt




    ttree->Branch("Eff6Pt10",&Eff6Pt10,"Eff6Pt10/F"); // matching efficiency high pt 6 clusters
    ttree->Branch("errEff6Pt10",&errEff6Pt10,"errEff6Pt10/F"); // error matching efficiency high pt 6 clusters
    ttree->Branch("Eff5Pt10",&Eff5Pt10,"Eff5Pt10/F"); // matching efficiency high pt 5 clusters
    ttree->Branch("errEff5Pt10",&errEff5Pt10,"errEff5Pt10/F"); // error matching efficiency high pt 5 clusters
    ttree->Branch("Eff4Pt10",&Eff4Pt10,"Eff4Pt10/F"); // matching efficiency high pt 4 clusters
    ttree->Branch("errEff4Pt10",&errEff4Pt10,"errEff4Pt10/F"); // error matching efficiency high pt 4 clusters
    ttree->Branch("Eff3Pt10",&Eff3Pt10,"Eff3Pt10/F"); // matching efficiency high pt 3 clusters
    ttree->Branch("errEff3Pt10",&errEff3Pt10,"errEff3Pt10/F"); // error matching efficiency high pt 3 clusters
    ttree->Branch("Eff2Pt10",&Eff2Pt10,"Eff2Pt10/F"); // matching efficiency high pt 2 clusters
    ttree->Branch("errEff2Pt10",&errEff2Pt10,"errEff2Pt10/F"); // error matching efficiency high pt 2 clusters
    ttree->Branch("EffSPDPt10",&EffSPDPt10,"EffSPDPt10/F"); // matching efficiency high pt 2 SPD
    ttree->Branch("errEffSPDPt10",&errEffSPDPt10,"errEffSPDPt10/F"); // error matching efficiency high pt 2 SPD
    ttree->Branch("EffoneSPDPt10",&EffoneSPDPt10,"EffoneSPDPt10/F"); // matching efficiency high pt 6 one SPD
    ttree->Branch("errEffoneSPDPt10",&errEffoneSPDPt10,"errEffoneSPDPt10/F"); // error matching efficiency high pt one SPD
    ttree->Branch("EffTOTPt10",&EffTOTPt10,"EffTOTPt10/F"); // matching efficiency high pt
    ttree->Branch("errEffTOTPt10",&errEffTOTPt10,"errEffTOTPt10/F"); // error matching efficiency high pt

    
    
    ttree->Branch("FracSPD1",&FracSPD1,"FracSPD1/F"); // fraction SPD layers active on 1 layer
    ttree->Branch("errFracSPD1",&errFracSPD1,"errFracSPD1/F");

    ttree->Branch("FracSPD2",&FracSPD2,"FracSPD2/F"); // fraction SPD layers active on 1 layer
    ttree->Branch("errFracSPD2",&errFracSPD2,"errFracSPD2/F");
    
    
    ///////////////   Vertex part
    nrun=runNumber;
    
    
    char VertexDirName[25]="Vertex_Performance";
    
    char VertexListName[25]="cOutputVtxESD";
    
    TDirectoryFile * VertexQAdir=(TDirectoryFile*)fin->Get(VertexDirName);
    if (!VertexQAdir) {
        Printf("ERROR: Vertex QA directory not present in input file.\n");
        return -1;
    }
    TList * VertxList=(TList*)VertexQAdir->Get(VertexListName);
    
    
    if (!VertxList) Printf("WARNING: Vertex QA histograms absent or not accessible\n");
    
    
    
    
    Printf("Vertex - QA");
    
    
    Int_t iRun=runNumber;

    TH1F *xVtxTRK = (TH1F*)VertxList->FindObject("fhTRKVertexX");
    
    
    TH1F *yVtxTRK = (TH1F*)VertxList->FindObject("fhTRKVertexY");
    

    
    TH1F *zVtxTRK = (TH1F*)VertxList->FindObject("fhTRKVertexZ");
    
    
    TH1F *xVtxSPD = (TH1F*)VertxList->FindObject("fhSPDVertexX");
    
    if(xVtxSPD->GetEntries()==0){
        printf("Run %d xVtxSOD EMPTY -> Return\n",iRun);
        

    }
    
    TH1F *yVtxSPD = (TH1F*)VertxList->FindObject("fhSPDVertexY");
    
    if(yVtxSPD->GetEntries()==0){
        printf("Run %d yVtxSPD EMPTY -> Return\n",iRun);
        

    }
    
    TH1F *zVtxSPD = (TH1F*)VertxList->FindObject("fhSPDVertexZ");
    
    if(zVtxSPD->GetEntries()==0){
        printf("Run %d zVtxSPD EMPTY -> Return\n",iRun);
        

    }
    
    TF1 *fxTRK = new TF1("gausx", "gaus", -1, 1);
    xVtxTRK->Fit("gausx", "NQRL");
    
    TF1 *fyTRK = new TF1("gausy", "gaus", -1, 1);
    yVtxTRK->Fit("gausy","NQLR");
    
    TF1 *fzTRK = new TF1("gausz", "gaus", -1, 1);
    zVtxTRK->Fit("gausz","NQRL");
    TF1 *fxSPD = new TF1("gausxSPD", "gaus", -1, 1);
    xVtxSPD->Fit("gausxSPD", "NQRL");
    
    TF1 *fySPD = new TF1("gausySPD", "gaus", -1, 1);
    yVtxSPD->Fit("gausySPD","NQLR");
    
    TF1 *fzSPD = new TF1("gauszSPD", "gaus", -1, 1);
    zVtxSPD->Fit("gauszSPD","NQRL");


    meanVtxTRKx=(Float_t)fxTRK->GetParameter(1);
    meanVtxTRKxErr=(Float_t)fxTRK->GetParError(1);
    sigmaVtxTRKx=(Float_t)fxTRK->GetParameter(2);
    sigmaVtxTRKxErr=(Float_t)fxTRK->GetParError(2);
    meanVtxTRKy=(Float_t)fyTRK->GetParameter(1);
    meanVtxTRKyErr=(Float_t)fyTRK->GetParError(1);
    sigmaVtxTRKy=(Float_t)fyTRK->GetParameter(2);
    sigmaVtxTRKyErr=(Float_t)fyTRK->GetParError(2);
    meanVtxTRKz=(Float_t)fzTRK->GetParameter(1);
    meanVtxTRKzErr=(Float_t)fzTRK->GetParError(1);
    sigmaVtxTRKz=(Float_t)fzTRK->GetParameter(2);
    sigmaVtxTRKzErr=(Float_t)fzTRK->GetParError(2);
    meanVtxSPDx=(Float_t)fxSPD->GetParameter(1);
    meanVtxSPDxErr=(Float_t)fxSPD->GetParError(1);
    sigmaVtxSPDx=(Float_t)fxSPD->GetParameter(2);
    sigmaVtxSPDxErr=(Float_t)fxSPD->GetParError(2);
    meanVtxSPDy=(Float_t)fySPD->GetParameter(1);
    meanVtxSPDyErr=(Float_t)fySPD->GetParError(1);
    sigmaVtxSPDy=(Float_t)fySPD->GetParameter(2);
    sigmaVtxSPDyErr=(Float_t)fySPD->GetParError(2);
    meanVtxSPDz=(Float_t)fzSPD->GetParameter(1);
    sigmaVtxSPDzErr=(Float_t)fzSPD->GetParError(1);
    sigmaVtxSPDz=(Float_t)fzSPD->GetParameter(2);
    sigmaVtxSPDzErr=(Float_t)fzSPD->GetParError(2);
    
    
    /////////// end of vertex part
    
    
    ///////////////////////  SSD Part
    char SSDDirName[25]="PWGPPdEdxSSDQA";
    
    char SSDListName[25]="SSDdEdxQA";
    
    TDirectoryFile * SSDQAdir=(TDirectoryFile*)fin->Get(SSDDirName);
    if (!SSDQAdir) {
        Printf("ERROR: SSD QA directory not present in input file.\n");
        return -1;
    }
    TList * SSDList=(TList*)SSDQAdir->Get(SSDListName);
    
    
    if (!SSDList) Printf("WARNING: SSD QA histograms absent or not accessible\n");
    
    
    
    
    Printf("SSD - QA");
    

    MPVL5=0;
    MPVErrL5=0;
    MPVL6=0;
    MPVErrL6=0;
    ChargeRatioL5=0;
    ChargeRatioErrL5=0;
    ChargeRatioL6=0;
    ChargeRatioErrL6=0;
    EmptyModulesSDD=0;
    
    
    TH2F* QAchargeRatio=(TH2F*)SSDList->FindObject("QAChargeRatio");
    
    if(QAchargeRatio->GetEntries()==0){
        printf("Run %d QAchargeRatio EMPTY -> Return\n",iRun);
    }
    
    TH2F* QAcharge=(TH2F*)SSDList->FindObject("QACharge");
    
    if(QAcharge->GetEntries()==0){
        printf("Run %d QAcharge EMPTY -> Return\n",iRun);
        
    }
    
    if((QAcharge)&&(QAchargeRatio)&&(QAcharge->GetEntries()>10)&&(QAchargeRatio->GetEntries()>10)){

        Int_t biny = QAcharge->GetXaxis()->FindBin(747);
        Int_t maxy = QAcharge->GetXaxis()->GetXmax();

        Int_t  contEmpty=0;
        Int_t  contFull=0;

        TH1D *hChargeL5=QAcharge->ProjectionY("hChargeL5",0,biny);
        TH1D *hChargeL6=QAcharge->ProjectionY("hChargeL6",biny,maxy);



        TH1D *hChargeRatioL5=QAchargeRatio->ProjectionY("hChargeRatioL5",0,biny);
        TH1D *hChargeRatioL6=QAchargeRatio->ProjectionY("hChargeRatioL6",biny,maxy);


        if(QAcharge->GetEntries()< 45000)
            contEmpty=1;

        else{
            for(Int_t i =0;i<1698;i++){

                TString tmpQ("Q");
                tmpQ+=i;

                TH1D* fHist1DQ= QAcharge->ProjectionY(tmpQ,i+1,i+1);
                Double_t mean=fHist1DQ->GetMean();

                if(TMath::Abs(mean)<1.0 ||fHist1DQ->GetEntries()<10)
                    contEmpty++;

                else
                    contFull++;

            }
        }
        
        TF1 *lfunLay5 = new TF1("LangausFunLay5",LangausFun,50.,300.,4);
        lfunLay5->SetParameter(0,5.);
        lfunLay5->SetParameter(1,80.);
        lfunLay5->SetParameter(2,hChargeL5->GetEntries()/10.);
        lfunLay5->SetParameter(3,10.);
        lfunLay5->SetParLimits(3,0.,20);
        hChargeL5->Fit(lfunLay5,"NQLR");
        TF1 *lfunLay6 = new TF1("LangausFunLay6",LangausFun,50.,300.,4);
        lfunLay6->SetParameter(0,5.);
        lfunLay6->SetParameter(1,80.);
        lfunLay6->SetParameter(2,hChargeL6->GetEntries()/10.);
        lfunLay6->SetParameter(3,10.);
        lfunLay6->SetParLimits(3,0.,20);
        hChargeL6->Fit(lfunLay6,"NQLR");
        





        MPVL5=(Float_t)lfunLay5->GetParameter(1);
        MPVErrL5=(Float_t)lfunLay5->GetParError(1);
        MPVL6=(Float_t)lfunLay6->GetParameter(1);
        MPVErrL6=(Float_t)lfunLay6->GetParError(1);
        ChargeRatioL5=(Float_t)hChargeRatioL5->GetMean();
        ChargeRatioErrL5=(Float_t)hChargeRatioL5->GetMeanError();
        ChargeRatioL6=(Float_t)hChargeRatioL6->GetMean();
        ChargeRatioErrL6=(Float_t)hChargeRatioL6->GetMeanError();
        EmptyModulesSDD=(Float_t)contEmpty;

    }

    /////////// end of SSD part
    
    
    
    
    
    
    
    
    
    
    
    
    
    ///////////////////////  SDD Part
    char SDDDirName[25]="SDD_Performance";
    
    char SDDListName[15]="coutputRP";
    
    TDirectoryFile * SDDQAdir=(TDirectoryFile*)fin->Get(SDDDirName);
    if (!SDDQAdir) {
        Printf("ERROR: SDD QA directory not present in input file.\n");
        return -1;
    }
    TList * SDDList=(TList*)SDDQAdir->Get(SDDListName);
    
    
    if (!SDDList) Printf("WARNING: SDD QA histograms absent or not accessible\n");
    
    
    
    
    Printf("SDD - QA");
    
    
    TH1F* hcllay=(TH1F*)SDDList->FindObject("hCluInLay");
    
    


    if(hcllay->GetBinContent(1)>0){
        for(Int_t iLay=0; iLay<6; iLay++){
            fracT[iLay]=hcllay->GetBinContent(iLay+2)/hcllay->GetBinContent(1);
            efracT[iLay]=TMath::Sqrt(fracT[iLay]*(1-fracT[iLay])/hcllay->GetBinContent(1));
        }
    }

    fracTrackWithClu1=fracT[0];
    errfracTrackWithClu1=efracT[0];
    fracTrackWithClu2=fracT[1];
    errfracTrackWithClu2=efracT[1];
    fracTrackWithClu3=fracT[2];
    errfracTrackWithClu3=efracT[2];
    fracTrackWithClu4=fracT[3];
    errfracTrackWithClu4=efracT[3];
    fracTrackWithClu5=fracT[4];
    errfracTrackWithClu5=efracT[4];
    fracTrackWithClu6=fracT[5];
    errfracTrackWithClu6=efracT[5];
    
    cout<<endl<<errfracTrackWithClu6<<endl;

    TH1F* hmodT=(TH1F*)SDDList->FindObject("hTPMod");

    
    TH1F* hgamod=(TH1F*)SDDList->FindObject("hGAMod");
    


    
    TH1F* hev=(TH1F*)SDDList->FindObject("hNEvents");

    nTotEvents=hev->GetBinContent(2);
    nTrigEvents=hev->GetBinContent(3);
    nEvents=nTotEvents;


    
    TH1F* htimT=(TH1F*)SDDList->FindObject("hDrTimTPAll");

    
    TH1F* htimTe=(TH1F*)SDDList->FindObject("hDrTimTPExtra");
    

    if(htimT->GetEntries()>0){
        fracExtra=htimTe->GetEntries()/htimT->GetEntries();
        errfracExtra=TMath::Sqrt(htimTe->GetEntries())/htimT->GetEntries();
    }

    for(Int_t iBin=1; iBin<=htimT->GetNbinsX(); iBin++){
        Float_t tim=htimT->GetBinCenter(iBin);
        if(tim>2000. && tim<4000.){
            averPoints+=htimT->GetBinContent(iBin);
            cntBins+=1;
        }
    }

    if(cntBins>0){
        averPoints/=cntBins;
        for(Int_t iBin=1; iBin<=htimT->GetNbinsX(); iBin++){
            if(htimT->GetBinContent(iBin)>0.5*averPoints){
                minDrTime=htimT->GetBinCenter(iBin);
                errminDrTime=0.5*htimT->GetBinWidth(iBin);
                break;
            }
        }
    }
    meanDrTime=htimT->GetMean();
    errmeanDrTime=htimT->GetMeanError();
    TH2F* hdedxmod=(TH2F*)SDDList->FindObject("hdEdxVsMod");
    
    
    TH1D* hdedxLay3=hdedxmod->ProjectionY("hdedxLay3",1,84);
    TH1D* hdedxLay4=hdedxmod->ProjectionY("hdedxLay4",85,260);
    
    TH1F* hSigTim0=(TH1F*)SDDList->FindObject("hSigTimeInt0");

    
    TH1F* hSigTim5=(TH1F*)SDDList->FindObject("hSigTimeInt5");

    //Fitting the same distributions in order to have the MPV
    TF1 *lfunLay3 = new TF1("LangausFunLay3",LangausFun,50.,300.,4);
    lfunLay3->SetParameter(0,5.);
    lfunLay3->SetParameter(1,80.);
    lfunLay3->SetParameter(2,hdedxLay3->GetEntries()/10.);
    lfunLay3->SetParameter(3,10.);
    lfunLay3->SetParLimits(3,0.,20);
    hdedxLay3->Fit(lfunLay3,"NQLR");
    TF1 *lfunLay4 = new TF1("LangausFunLay4",LangausFun,50.,300.,4);
    lfunLay4->SetParameter(0,5.);
    lfunLay4->SetParameter(1,80.);
    lfunLay4->SetParameter(2,hdedxLay4->GetEntries()/10.);
    lfunLay4->SetParameter(3,10.);
    lfunLay4->SetParLimits(3,0.,20);
    hdedxLay4->Fit(lfunLay4,"NQLR");
    TF1 *lfunTim0 = new TF1("LangausFunTim0",LangausFun,50.,300.,4);
    lfunTim0->SetParameter(0,5.);
    lfunTim0->SetParameter(1,80.);
    lfunTim0->SetParameter(2,hSigTim0->GetEntries()/10.);
    lfunTim0->SetParameter(3,10.);
    lfunTim0->SetParLimits(3,0.,20);
    hSigTim0->Fit(lfunTim0,"NQLR");
    TF1 *lfunTim5 = new TF1("LangausFunTim5",LangausFun,50.,300.,4);
    lfunTim5->SetParameter(0,5.);
    lfunTim5->SetParameter(1,80.);
    lfunTim5->SetParameter(2,hSigTim5->GetEntries()/10.);
    lfunTim5->SetParameter(3,10.);
    lfunTim5->SetParLimits(3,0.,20);
    hSigTim5->Fit(lfunTim5,"NQLR");
    
    




    MPVdEdxLay3=lfunLay3->GetParameter(1);
    errMPVdEdxLay3=lfunLay3->GetParError(1);
    MPVdEdxLay4=lfunLay4->GetParameter(1);
    errMPVdEdxLay4=lfunLay4->GetParError(1);
    MPVdEdxTB0=lfunTim0->GetParameter(1);
    errMPVdEdxTB0=lfunTim0->GetParError(1);
    MPVdEdxTB5=lfunTim5->GetParameter(1);
    errMPVdEdxTB5=lfunTim5->GetParError(1);
    
    

    
    /////////// end of SDD part
    
    
    // Matching Part
    
    cout<<"Tracking"<<endl;
    
    TDirectoryFile *dirMatch=(TDirectoryFile*)fin->GetDirectory("ITS_Performance");
    TList *list=NULL;
    TList *listSPD=NULL;
    
    if(dirMatch) {

        list = (TList*)dirMatch->Get("cOutputITS"); // LHC12e
    }
    dirMatch=(TDirectoryFile*)fin->GetDirectory("SPD_Performance");
    if(dirMatch) listSPD = (TList*)dirMatch->Get("coutput1");
    
    // if(!list) return kFALSE;
    
    Float_t ioValues[30];
    Float_t ioErrors[30];
    for(Int_t jj=0;jj<30;jj++){
        ioValues[jj]=0.;
        ioErrors[jj]=0.;
    }
    
    Float_t ptbin=0;
    
    TH1F *hFiredChip = (TH1F*)listSPD->FindObject("hFiredChip");
    
    if(hFiredChip->GetEntries()==0){
        printf("Run %d hFiredChip EMPTY -> Return\n",iRun);
        
    }
    
    Int_t nHSsInner=0,nHSsOuter=0;
    for(Int_t i=0;i<400;i++) if(hFiredChip->GetBinContent(i)>0) nHSsInner++;
    for(Int_t i=400;i<1200;i++) if(hFiredChip->GetBinContent(i)>0) nHSsOuter++;
    nHSsInner = (Int_t)(nHSsInner/10);
    nHSsOuter = (Int_t)(nHSsOuter/10);
    
    ioValues[0]=(Float_t)nHSsInner/40.;
    ioValues[1]=(Float_t)nHSsOuter/80.;
    
    TH1F *fHistPtTPCInAcc = (TH1F*)list->FindObject("fHistPtTPCInAcc");
    Int_t check1=0;
    
    if(fHistPtTPCInAcc->GetEntries()==0){
        check1=1;
        printf("Run %dfHistPtTPCInAcc  EMPTY -> Return\n",iRun);
    }
    
    TH1F *fHistPtITSMI6InAcc = (TH1F*)list->FindObject("fHistPtITSMI6InAcc");

    
    TH1F *fHistPtITSMI5InAcc = (TH1F*)list->FindObject("fHistPtITSMI5InAcc");
    
    TH1F *fHistPtITSMI4InAcc = (TH1F*)list->FindObject("fHistPtITSMI4InAcc");
    
    TH1F *fHistPtITSMI3InAcc = (TH1F*)list->FindObject("fHistPtITSMI3InAcc");

    TH1F *fHistPtITSMI2InAcc = (TH1F*)list->FindObject("fHistPtITSMI2InAcc");
    
    TH1F *fHistPtITSMISPDInAcc = (TH1F*)list->FindObject("fHistPtITSMISPDInAcc");
    
    TH1F *fHistPtITSMIoneSPDInAcc = (TH1F*)list->FindObject("fHistPtITSMIoneSPDInAcc");
    
    
    
    TH1F *fHistPtITSMIge2InAcc = (TH1F*)fHistPtITSMI6InAcc->Clone("fHistPtITSMIge2InAcc");
    fHistPtITSMIge2InAcc->Add(fHistPtITSMI5InAcc);
    fHistPtITSMIge2InAcc->Add(fHistPtITSMI4InAcc);
    fHistPtITSMIge2InAcc->Add(fHistPtITSMI3InAcc);
    fHistPtITSMIge2InAcc->Add(fHistPtITSMI2InAcc);
    
    
    
    fHistPtITSMI6InAcc->Divide(fHistPtITSMI6InAcc,fHistPtTPCInAcc,1,1,"B");
    ptbin=fHistPtITSMI6InAcc->FindBin(0.201);
    ioValues[2]=fHistPtITSMI6InAcc->GetBinContent(ptbin);
    ioErrors[2]=fHistPtITSMI6InAcc->GetBinError(ptbin);
    ptbin=fHistPtITSMI6InAcc->FindBin(1.001);
    ioValues[3]=fHistPtITSMI6InAcc->GetBinContent(ptbin);
    ioErrors[3]=fHistPtITSMI6InAcc->GetBinError(ptbin);
    ptbin=fHistPtITSMI6InAcc->FindBin(10.001);
    ioValues[4]=fHistPtITSMI6InAcc->GetBinContent(ptbin);
    ioErrors[4]=fHistPtITSMI6InAcc->GetBinError(ptbin);
    
    fHistPtITSMI5InAcc->Divide(fHistPtITSMI5InAcc,fHistPtTPCInAcc,1,1,"B");
    
    ptbin=fHistPtITSMI5InAcc->FindBin(0.201);
    ioValues[5]=fHistPtITSMI5InAcc->GetBinContent(ptbin);
    ioErrors[5]=fHistPtITSMI5InAcc->GetBinError(ptbin);
    ptbin=fHistPtITSMI5InAcc->FindBin(1.001);
    ioValues[6]=fHistPtITSMI5InAcc->GetBinContent(ptbin);
    ioErrors[6]=fHistPtITSMI5InAcc->GetBinError(ptbin);
    ptbin=fHistPtITSMI5InAcc->FindBin(10.001);
    ioValues[7]=fHistPtITSMI5InAcc->GetBinContent(ptbin);
    ioErrors[7]=fHistPtITSMI5InAcc->GetBinError(ptbin);
    
    fHistPtITSMI4InAcc->Divide(fHistPtITSMI4InAcc,fHistPtTPCInAcc,1,1,"B");
    
    ptbin=fHistPtITSMI4InAcc->FindBin(0.201);
    ioValues[9]=fHistPtITSMI4InAcc->GetBinContent(ptbin);
    ioErrors[9]=fHistPtITSMI4InAcc->GetBinError(ptbin);
    ptbin=fHistPtITSMI4InAcc->FindBin(1.001);
    ioValues[10]=fHistPtITSMI4InAcc->GetBinContent(ptbin);
    ioErrors[10]=fHistPtITSMI4InAcc->GetBinError(ptbin);
    ptbin=fHistPtITSMI4InAcc->FindBin(10.001);
    ioValues[11]=fHistPtITSMI4InAcc->GetBinContent(ptbin);
    ioErrors[11]=fHistPtITSMI4InAcc->GetBinError(ptbin);
    
    fHistPtITSMI3InAcc->Divide(fHistPtITSMI3InAcc,fHistPtTPCInAcc,1,1,"B");
    
    ptbin=fHistPtITSMI3InAcc->FindBin(0.201);
    ioValues[12]=fHistPtITSMI3InAcc->GetBinContent(ptbin);
    ioErrors[12]=fHistPtITSMI3InAcc->GetBinError(ptbin);
    ptbin=fHistPtITSMI3InAcc->FindBin(1.001);
    ioValues[13]=fHistPtITSMI3InAcc->GetBinContent(ptbin);
    ioErrors[13]=fHistPtITSMI3InAcc->GetBinError(ptbin);
    ptbin=fHistPtITSMI3InAcc->FindBin(10.001);
    ioValues[14]=fHistPtITSMI3InAcc->GetBinContent(ptbin);
    ioErrors[14]=fHistPtITSMI3InAcc->GetBinError(ptbin);
    
    fHistPtITSMI2InAcc->Divide(fHistPtITSMI2InAcc,fHistPtTPCInAcc,1,1,"B");
    
    ptbin=fHistPtITSMI2InAcc->FindBin(0.201);
    ioValues[15]=fHistPtITSMI2InAcc->GetBinContent(ptbin);
    ioErrors[15]=fHistPtITSMI2InAcc->GetBinError(ptbin);
    ptbin=fHistPtITSMI2InAcc->FindBin(1.001);
    ioValues[16]=fHistPtITSMI2InAcc->GetBinContent(ptbin);
    ioErrors[16]=fHistPtITSMI2InAcc->GetBinError(ptbin);
    ptbin=fHistPtITSMI2InAcc->FindBin(10.001);
    ioValues[17]=fHistPtITSMI2InAcc->GetBinContent(ptbin);
    ioErrors[17]=fHistPtITSMI2InAcc->GetBinError(ptbin);
    
    fHistPtITSMISPDInAcc->Divide(fHistPtITSMISPDInAcc,fHistPtTPCInAcc,1,1,"B");
    ptbin=fHistPtITSMISPDInAcc->FindBin(0.201);
    ioValues[18]=fHistPtITSMISPDInAcc->GetBinContent(ptbin);
    ioErrors[18]=fHistPtITSMISPDInAcc->GetBinError(ptbin);
    ptbin=fHistPtITSMISPDInAcc->FindBin(1.001);
    ioValues[19]=fHistPtITSMISPDInAcc->GetBinContent(ptbin);
    ioErrors[19]=fHistPtITSMISPDInAcc->GetBinError(ptbin);
    ptbin=fHistPtITSMISPDInAcc->FindBin(10.001);
    ioValues[20]=fHistPtITSMISPDInAcc->GetBinContent(ptbin);
    ioErrors[20]=fHistPtITSMISPDInAcc->GetBinError(ptbin);
    
    fHistPtITSMIoneSPDInAcc->Divide(fHistPtITSMIoneSPDInAcc,fHistPtTPCInAcc,1,1,"B");
    
    ptbin=fHistPtITSMIoneSPDInAcc->FindBin(0.201);
    ioValues[21]=fHistPtITSMIoneSPDInAcc->GetBinContent(ptbin);
    ioErrors[21]=fHistPtITSMIoneSPDInAcc->GetBinError(ptbin);
    ptbin=fHistPtITSMIoneSPDInAcc->FindBin(1.001);
    ioValues[22]=fHistPtITSMIoneSPDInAcc->GetBinContent(ptbin);
    ioErrors[22]=fHistPtITSMIoneSPDInAcc->GetBinError(ptbin);
    ptbin=fHistPtITSMIoneSPDInAcc->FindBin(10.001);
    ioValues[23]=fHistPtITSMIoneSPDInAcc->GetBinContent(ptbin);
    ioErrors[23]=fHistPtITSMIoneSPDInAcc->GetBinError(ptbin);
    
    
    fHistPtITSMIge2InAcc->Divide(fHistPtITSMIge2InAcc,fHistPtTPCInAcc,1,1,"B");
    ptbin=fHistPtITSMIge2InAcc->FindBin(0.201);
    ioValues[24]=fHistPtITSMIge2InAcc->GetBinContent(ptbin);
    ioErrors[24]=fHistPtITSMIge2InAcc->GetBinError(ptbin);
    ptbin=fHistPtITSMIge2InAcc->FindBin(1.001);
    ioValues[25]=fHistPtITSMIge2InAcc->GetBinContent(ptbin);
    ioErrors[25]=fHistPtITSMIge2InAcc->GetBinError(ptbin);
    ptbin=fHistPtITSMIge2InAcc->FindBin(10.001);
    ioValues[26]=fHistPtITSMIge2InAcc->GetBinContent(ptbin);
    ioErrors[26]=fHistPtITSMIge2InAcc->GetBinError(ptbin);
    
    FracSPD1=ioValues[0];
    errFracSPD1=ioErrors[0];
    FracSPD2=ioValues[1];
    errFracSPD2=ioErrors[1];
    Eff6Pt02=ioValues[2];
    errEff6Pt02=ioErrors[2];
    Eff6Pt1=ioValues[3];
    errEff6Pt1=ioErrors[3];
    Eff6Pt10=ioValues[4];
    errEff6Pt10=ioErrors[4];
    Eff5Pt02=ioValues[5];
    errEff5Pt02=ioErrors[5];
    Eff5Pt1=ioValues[6];
    errEff5Pt1=ioErrors[6];
    Eff5Pt10=ioValues[7];
    errEff5Pt10=ioErrors[7];
    Eff4Pt02=ioValues[8];
    errEff4Pt02=ioErrors[8];
    Eff4Pt1=ioValues[9];
    errEff4Pt1=ioErrors[9];
    Eff4Pt10=ioValues[10];
    errEff4Pt10=ioErrors[10];
    Eff3Pt02=ioValues[11];
    errEff3Pt02=ioErrors[11];
    Eff3Pt1=ioValues[12];
    errEff3Pt1=ioErrors[12];
    Eff3Pt10=ioValues[13];
    errEff3Pt10=ioErrors[13];
    Eff2Pt02=ioValues[14];
    errEff2Pt02=ioErrors[14];
    Eff2Pt1=ioValues[15];
    errEff2Pt1=ioErrors[15];
    Eff2Pt10=ioValues[16];
    errEff2Pt10=ioErrors[16];
    EffSPDPt02=ioValues[17];
    errEffSPDPt02=ioErrors[17];
    EffSPDPt1=ioValues[18];
    errEffSPDPt1=ioErrors[18];
    EffSPDPt10=ioValues[19];
    errEffSPDPt10=ioErrors[19];
    EffoneSPDPt02=ioValues[20];
    errEffoneSPDPt02=ioErrors[20];
    EffoneSPDPt1=ioValues[21];
    errEffoneSPDPt1=ioErrors[21];
    EffoneSPDPt10=ioValues[22];
    errEffoneSPDPt10=ioErrors[22];
    EffTOTPt02=ioValues[23];
    errEffTOTPt02=ioErrors[23];
    EffTOTPt1=ioValues[24];
    errEffTOTPt1=ioErrors[24];
    EffTOTPt10=ioValues[25];
    errEffTOTPt10=ioErrors[25];
    
    
    
    
    
    
    
    


    ttree->Fill();
    printf("==============  Saving trending quantities in tree for run %i ===============\n",runNumber);
    trendFile->cd();
    ttree->Write();
    trendFile->Close();


    return  1;
}
コード例 #5
0
void plot_ljpsi(const char* fdata, const char* fmc) {
   TFile *tfd = TFile::Open(fdata);
   TFile *tfm = TFile::Open(fmc);

   TCanvas *c1 = new TCanvas();
   c1->cd();
   TPad *p1 = new TPad("p1","",0,0,1,0.33);
   p1->SetBottomMargin(2.*gStyle->GetPadBottomMargin());
   p1->SetTopMargin(0);
   p1->SetFrameBorderMode(0);
   p1->SetBorderMode(0);
   p1->SetBorderSize(0);
   p1->SetGridy();
   if (datamc) p1->Draw();
   TPad *p2 = new TPad("p2","",0,0.33,1,1);
   // p2->SetTopMargin(gStyle->GetPadTopMargin()/(1.-0.2));
   p2->SetBottomMargin(0);
   p2->SetFrameBorderMode(0);
   p2->SetBorderMode(0);
   p2->SetBorderSize(0);
   // p2->SetLogy();
   if (datamc) p2->Draw();
   p1->cd();
   if (!datamc) c1->cd();

   TF1 *dg = new TF1("f1","[0]*([1]*TMath::Gaus(x,[2],[3])+(1-[1])*TMath::Gaus(x,[4],[3]*[5]))",-0.2,0.04);
   dg->SetParLimits(0,0,1e15);
   dg->SetParLimits(1,0.5,1);
   dg->SetParLimits(2,-0.05,0.05);
   dg->SetParLimits(3,0,0.1);
   dg->SetParLimits(4,-0.05,0.05);
   dg->SetParLimits(5,0,100);
   dg->SetParameters(1000,0.8,1e-3,0.03,1e-4,2.);

   TIter next(tfd->GetListOfKeys()); TObject *obj;
   while ((obj = next())) {
      obj = ((TKey*) obj)->ReadObj();
      if (TString(obj->ClassName()) == "TH1F") {
         TH1F *hdata = (TH1F*) tfd->Get(obj->GetName());
         TH1F *hmc = (TH1F*) tfm->Get(obj->GetName());
         // hdata->Rebin(6);
         // hmc->Rebin(6);

         if (!integrate) {
            double int_data = hdata->Integral(hdata->FindBin(-0.015), hdata->FindBin(0.015));
            double int_mc = hmc->Integral(hmc->FindBin(-0.015), hmc->FindBin(0.015));
            hmc->Scale(int_data/int_mc);
         } else {
            double int_mc_all = hmc->Integral(0, hmc->GetNbinsX()+1);
            double int_data_all = hdata->Integral(0, hdata->GetNbinsX()+1);
            hmc->Scale(1./int_mc_all);
            hdata->Scale(1./int_data_all);
            double int_data = hdata->Integral(0, hdata->FindBin(0.));
            double int_mc = hmc->Integral(0, hmc->FindBin(0.));
            hdata->Scale(int_mc/int_data); 
            integrateHist(hdata);
            integrateHist(hmc);
         }
         hdata->GetXaxis()->SetTitle("#font[12]{l}_{J/#psi} [mm]");
         hdata->GetYaxis()->SetTitle("Entries");
         if (integrate) hdata->GetYaxis()->SetTitle("c.d.f.");

         // read the bin from the name
         TString thname(hdata->GetName());
         bool isfwd = (thname.Index("fwd") != kNPOS);
         int pos1 = thname.Index("pt")+2;
         int pos2 = thname.Index("-")-pos1;
         TString tsubstr(thname(pos1,pos2));
         float ptmin = atof(tsubstr.Data());
         pos1 = thname.Index("-")+1;
         pos2 = thname.Length();
         tsubstr = TString(thname(pos1,pos2));
         float ptmax = atof(tsubstr.Data());

         if (datamc) p2->cd();
         hdata->Draw();
         hmc->SetLineColor(kRed);
         hmc->SetMarkerColor(kRed);
         hmc->Draw("same");
         gPad->Update();

         // display the position of the ctau cut
         double a=1,b=1;
         if (!isfwd){a=ctaucut_a_mid_pp; b=ctaucut_b_mid_pp;} 
         else {a=ctaucut_a_fwd_pp; b=ctaucut_b_fwd_pp;}
         double cutmin = a + b / ptmin;
         double cutmax = a + b / ptmax;
         double xmin, xmax, ymin, ymax;
         TBox *tb = new TBox(cutmin,gPad->GetUymin(),cutmax,gPad->GetUymax());
         tb->SetFillColor(kBlack);
         tb->SetFillStyle(3003);
         tb->Draw();

         if (integrate) {
            TLine *tl = new TLine(hdata->GetXaxis()->GetXmin(),0.9,hdata->GetXaxis()->GetXmax(),0.9);
            tl->SetLineStyle(3);
            tl->SetLineColor(kBlack);
            tl->SetLineWidth(5);
            tl->Draw();
         }

         if (datamc) {
            p1->cd();
            TH1F *hratio = (TH1F*) hdata->Clone("hratio");
            hratio->Divide(hmc);
            hratio->GetYaxis()->SetTitle("data/MC");
            hratio->GetYaxis()->SetRangeUser(0.5,1.5);
            hratio->GetXaxis()->SetLabelSize(2.*hratio->GetXaxis()->GetLabelSize());
            hratio->GetXaxis()->SetTitleSize(2.*hratio->GetXaxis()->GetTitleSize());
            hratio->GetYaxis()->SetLabelSize(2.*hratio->GetYaxis()->GetLabelSize());
            hratio->GetYaxis()->SetTitleSize(2.*hratio->GetYaxis()->GetTitleSize());
            hratio->Draw();

            p2->cd();
         }

         // dg->SetParameters(1000,0.8,1e-3,0.03,1e-4,2.);
         // dg->SetParameter(0,int_data);
         // dg->SetParLimits(0,0,int_data*100.);
         // hdata->Fit(dg, "LERQ");
         // double sigma_data = dg->GetParameter(3);
         // double dsigma_data = dg->GetParError(3);
         // dg->SetRange(-5.*sigma_data,1.5*sigma_data);
         // hdata->Fit(dg, "LERQ");
         // sigma_data = dg->GetParameter(3);
         // dsigma_data = dg->GetParError(3);
         // dg->SetRange(-5.*sigma_data,1.5*sigma_data);
         // hdata->Fit(dg, "LERQ");
         // sigma_data = dg->GetParameter(3);
         // dsigma_data = dg->GetParError(3);
         // hmc->Fit(dg, "LERQ");
         // double sigma_mc = dg->GetParameter(3);
         // double dsigma_mc = dg->GetParError(3);

         double lx1=0.61, lx2=0.9, ly1=0.6, ly2=0.88;
         if (integrate) {ly1-=0.4; ly2-=0.4;}
         TLegend *tleg = new TLegend(lx1,ly1,lx2,ly2);
         tleg->SetBorderSize(0);
         TString header("#splitline{");
         header += isfwd ? "1.6<|y|<2.4" : "|y|<1.6";
         header += Form("}{%.1f<pt<%.1f GeV/c}",ptmin,ptmax);
         tleg->SetHeader(header);
         // tleg->AddEntry(hdata,Form("pp data (#sigma = %.3f +/- %.3f)",sigma_data,dsigma_data),"lp");
         // tleg->AddEntry(hmc,Form("pp prompt J/#psi mc (#sigma = %.3f +/- %.3f)",sigma_mc,dsigma_mc),"lp");
         tleg->AddEntry(hdata,"data","lp");
         tleg->AddEntry(hmc,"prompt J/#psi mc","lp");
         tleg->Draw();
         c1->SaveAs(Form("%s.pdf",hdata->GetName()));
         c1->SaveAs(Form("%s.png",hdata->GetName()));
      }
   }
}
コード例 #6
0
void yj_forest2yskim_jetSkim_forestV3(TString inputFile_="forestFiles/pA/pA_photonSkimForest_v85_skimPhotonPt50_eta1.5.root",
				   std::string MinbiasFname = "skim_trackJet_minbiasTrackJet_mc.root",
				   float cutphotonPt  = 35,  // default value dropped to 35GeV  for later photon energy smearing/scaling
				   std::string outname = "testPhotonSkim.root",
				   sampleType colli=kPADATA,
				   bool doMix = false,
				   bool doJetResCorrection = 1,  // = L2L3 * MC nonclosure correction  jet energy correction is done by default from Oct 19th (YS)
				   int smearingCentBin = -1, //0=0-10%, 1=10-30%, 2=30-50%, 3=50-100%, 4=0-30%, 5=30-100%  : Jet pT and phi smearing!
				   bool useGenJetColl = 0
  )
{
  bool isMC=true;
  if ((colli==kPPDATA)||(colli==kPADATA)||(colli==kHIDATA))
    isMC=false;

  int seconds = time(NULL);         cout << " time = " <<seconds%10000<< endl;
  TRandom3 rand(seconds%10000);
  TString datafname  = "";
  float cutphotonEta = 1.44;
  float preCutPhotonEt = 30;

  const int nMaxPho = 100;


  HiForest *c;
  if((colli==kPADATA)||(colli==kPAMC)) {
    c = new HiForest(inputFile_.Data(), "forest", cPPb, isMC );
  }
  else if  ((colli==kPPDATA)||(colli==kPPMC)) {
    c = new HiForest(inputFile_.Data(), "forest", cPP, isMC );
  }
  else if  ((colli==kHIDATA)||(colli==kHIMC)) {
    c = new HiForest(inputFile_.Data(), "forest", cPbPb, isMC );
    c->GetEnergyScaleTable("../photonEnergyScaleTable_lowPt_v6.root");
  }
  else {
    cout << " Error!  No such collision type" << endl;
    return;
  }

  c->InitTree();


  // vertex and centrality vtxCentWeighting
  TFile* fWeight = new TFile("../vertexReweightingHistogram_pthatweighted.root");

  TH1D* hWeight_vtx_data_pp = (TH1D*)fWeight->Get("vertexHistoData_pp");
  TH1D* hWeight_vtx_mc_pp = (TH1D*)fWeight->Get("vertexHistoMC_pp");

  TH1D* hWeight_vtx_data_ppb = (TH1D*)fWeight->Get("vertexHistoData_ppb");
  TH1D* hWeight_vtx_mc_ppb = (TH1D*)fWeight->Get("vertexHistoMC_ppb");

  TH1D* hWeight_vtx_data_pbpb = (TH1D*)fWeight->Get("vertexHistoData_pbpb");
  TH1D* hWeight_vtx_mc_pbpb = (TH1D*)fWeight->Get("vertexHistoMC_pbpb");
  TH1D* hWeight_cent_data_pbpb = (TH1D*)fWeight->Get("centBinHistoData_pbpb");
  TH1D* hWeight_cent_mc_pbpb = (TH1D*)fWeight->Get("centBinHistoMC_pbpb");




  // L2L3 correction
  TFile* fL2L3pp = new TFile("../corrL2L3/Casym_pp_double_hcalbins_algo_ak3PF_pt100_140_jet80_alphahigh_20_phicut250.root");
  TH1D * c_etapp=(TH1D*)fL2L3pp->Get("C_asym");
  TF1* fptpp = new TF1("fptpp","1-[0]/pow(x,[1])",20,300);
  fptpp->SetParameters(0.06971,0.8167);

  TFile* fL2L3pA = new TFile("../corrL2L3/Casym_pPb_double_hcalbins_algo_akPu3PF_pt100_140_jet80_alphahigh_20_phicut250.root");
  TH1D * c_etapA=(TH1D*)fL2L3pA->Get("C_asym");
  TF1* fptpA = new TF1("fptpA","1-[0]/pow(x,[1])",20,300);
  fptpA->SetParameters(0.3015, 0.8913);

  TFile* fL2L3Ap = new TFile("../corrL2L3/Casym_Pbp_double_hcalbins_algo_akPu3PF_pt100_140_jet80_alphahigh_20_phicut250.root");
  TH1D * c_etaAp=(TH1D*)fL2L3Ap->Get("C_asym");
  TF1* fptAp = new TF1("fptAp","1-[0]/pow(x,[1])",20,300);
  fptAp->SetParameters(0.3015, 0.8913);

  // pA MC
  TF1 * fgaus=new TF1("fgaus_pA","gaus(0)",-20,20);
  fgaus->SetParameters(1,0,1);
  TF1 * fsmear_pA = new TF1("fsmear_pA","[0]/pow(x,[1])",50,300);
  fsmear_pA->SetParameters(1.052,0.5261);


  TCanvas* c11 = new TCanvas("c11","",1200,400);
  c11->Divide(3,1);
  c11->cd(1);
  c_etapp->Draw();
  c11->cd(2);
  c_etaAp->Draw();
  c11->cd(3);
  c_etapA->Draw();
  //c11->SaveAs("f1.gif");



  // now open new root file
  TFile* newfile_data = new TFile(outname.data(),"recreate");

  TTree* newtreePhoton;
  float newPt[nMaxPho];  // <<= temporary space
  int order[nMaxPho];
  float corrPt[nMaxPho];
  newtreePhoton = c->photonTree->CloneTree(0);
  newtreePhoton->SetName("yPhotonTree");
  newtreePhoton->SetMaxTreeSize(MAXTREESIZE);
  newtreePhoton->Branch("order",  order, "order[nPhotons]/I");
  newtreePhoton->Branch("corrPt", corrPt,"corrPt[nPhotons]/F");

  TTree* treeFullJet;
  if (   (colli==kPPDATA) || (colli==kPPMC) ) {
    treeFullJet = c->ak3jetTree->CloneTree(0);
    cout << "pp collision.  Using ak3PF Jet Algo" << endl<<endl;
  }
  else {
    treeFullJet = c->akPu3jetTree->CloneTree(0);
    cout << "pPb or PbPb collision. Using akPu3PF Jet Algo" << endl<<endl;
  }
  treeFullJet->SetName("fullJet");
  treeFullJet->SetMaxTreeSize(MAXTREESIZE);

  // genpana 131217 yeonju
  TTree* genpana;

  if(isMC){ 
      genpana = c->genpTree->CloneTree(0);
      genpana->SetName("genTree");
      genpana->SetMaxTreeSize(MAXTREESIZE);
  }

  // jet tree!
  int nJet;
  const int MAXJET = 50000; // to accomodate 100 smeared jets, need to be careful with ram
  float jetPt[MAXJET];
  float jetEta[MAXJET];
  float jetPhi[MAXJET];
  float jetDphi[MAXJET];
  int jetSubid[MAXJET];
  float jetRefPt[MAXJET];
  float jetRefEta[MAXJET];
  float jetRefPhi[MAXJET];
  float jetRefDphi[MAXJET];
  float jetRefPartonPt[MAXJET];
  int  jetRefPartonFlv[MAXJET];

  TTree *newtreeJet = new TTree("yJet","jets");
  newtreeJet->SetMaxTreeSize(MAXTREESIZE);
  newtreeJet->Branch("nJet",&nJet,"nJet/I");
  newtreeJet->Branch("pt",jetPt,"pt[nJet]/F");
  newtreeJet->Branch("eta",jetEta,"eta[nJet]/F");
  newtreeJet->Branch("phi",jetPhi,"phi[nJet]/F");
  newtreeJet->Branch("dphi",jetDphi,"dphi[nJet]/F");
  if ( isMC )  {
    newtreeJet->Branch("subid",jetSubid,"subid[nJet]/I");
    newtreeJet->Branch("refPt",jetRefPt,"refPt[nJet]/F");
    newtreeJet->Branch("refEta",jetRefEta,"refEta[nJet]/F");
    newtreeJet->Branch("refPhi",jetRefPhi,"refPhi[nJet]/F");
    newtreeJet->Branch("refDphi",jetRefDphi,"refDphi[nJet]/F");
    newtreeJet->Branch("refPartonPt",jetRefPartonPt,"refPartonPt[nJet]/F");
    newtreeJet->Branch("refPartonFlv",jetRefPartonFlv,"refPartonFlv[nJet]/I");
  }



  int nMjet;
  float mJetPt[MAXMJET];
  float mJetEta[MAXMJET];
  float mJetPhi[MAXMJET];
  float mJetDphi[MAXMJET];

  TTree * tmixJet = new TTree("mJet","Jet from minbias events");
  tmixJet->SetMaxTreeSize(MAXTREESIZE);
  tmixJet->Branch("nJet",&nMjet,"nJet/I");
  tmixJet->Branch("pt",mJetPt,"pt[nJet]/F");
  tmixJet->Branch("eta",mJetEta,"eta[nJet]/F");
  tmixJet->Branch("phi",mJetPhi,"phi[nJet]/F");
  tmixJet->Branch("dphi", mJetDphi, "dphi[nJet]/F");



  // Imb = Input MinBias events
  EvtSel          evtImb;
  Int_t           nJetImb;
  Float_t         jetPtImb[100];
  Float_t         jetEtaImb[100];
  Float_t         jetPhiImb[100];
  TBranch        *b_evt;
  TBranch        *b_nJetImb;
  TBranch        *b_jetPtImb;
  TBranch        *b_jetEtaImb;
  TBranch        *b_jetPhiImb;


  int nCentBins =  nCentBinSkim;
  if ((colli==kPADATA)||(colli==kPAMC)) {
    nCentBins = nCentBinSkimPA;
  }

  TChain   *tjmb[100][nVtxBin+1];
  int nMB[100][nVtxBin+1] ; //= 199109;
  int mbItr[100][nVtxBin+1];
  if ( doMix ) {
    cout <<"  Tree initialization for MinBias mixing" << endl;
    for( int icent = 0 ; icent< nCentBins ; icent++) {
      for( int ivz = 1 ; ivz<=nVtxBin ; ivz++) {

	tjmb[icent][ivz] = new TChain(Form("trkAndJets_first_cBin2icent%d_ivz%d",icent,ivz));
	tjmb[icent][ivz]->Add(MinbiasFname.data());
	tjmb[icent][ivz]->SetBranchAddress("evt", &evtImb,&b_evt);
	tjmb[icent][ivz]->SetBranchAddress("nJet",   &nJetImb,   &b_nJetImb);
	tjmb[icent][ivz]->SetBranchAddress("jetPt",  &jetPtImb,  &b_jetPtImb);
	tjmb[icent][ivz]->SetBranchAddress("jetEta", &jetEtaImb, &b_jetEtaImb);
	tjmb[icent][ivz]->SetBranchAddress("jetPhi", &jetPhiImb, &b_jetPhiImb);


	nMB[icent][ivz] = tjmb[icent][ivz]->GetEntries();
	cout << "number of evetns in (icent = " << icent << ", ivtxZ = "<< ivz << ")  = " << nMB[icent][ivz] << endl;
	int primeSeed = rand.Integer(37324);
	mbItr[icent][ivz] = primeSeed%(nMB[icent][ivz]);
	cout <<" initial itr = " << mbItr[icent][ivz] << endl;
      }
    }
  }
  else
    cout << endl << endl << "  Mixing process is skipped" << endl << endl << endl ;


  // reweighting factor should go here
  int eTot(0), eSel(0);
  EvtSel evt;
  GammaJet gj;
  Isolation isol;
  TTree *tgj;
  tgj = new TTree("tgj","gamma jet tree");
  tgj->SetMaxTreeSize(MAXTREESIZE);
  tgj->Branch("evt",&evt.run,"run/I:evt:cBin:pBin:trig/O:offlSel:noiseFilt:anaEvtSel:vz/F:vtxCentWeight/F:hf4Pos:hf4Neg:hf4Sum:ptHat:ptHatWeight");
  tgj->Branch("lpho",&gj.photonEt,"photonEt/F:photonRawEt:photonEta:photonPhi:hovere:r9:sigmaIetaIeta:sumIso:genIso:genPhotonEt:genMomId/I:lJetPt/F:lJetEta:lJetPhi:lJetDphi:lJetSubid/I");
  tgj->Branch("isolation",&isol.cc1,"cc1:cc2:cc3:cc4:cc5:cr1:cr2:cr3:cr4:cr5:ct1PtCut20:ct2PtCut20:ct3PtCut20:ct4PtCut20:ct5PtCut20:ecalIso:hcalIso:trackIso");  // ecalIso,hcalIso,trackIso are the pp style isolation


  float vzCut = vtxCutPhotonAna;
  TH1F* hvz = new TH1F("hvz","",nVtxBin,-vzCut,vzCut);
  // event plane hitogram
  TH1F* hEvtPlnBin = new TH1F("hEvtPlnBin", "", nPlnBin, -PI/2., PI/2.);
  // jet algos
  Jets* theJet;
  if (   (colli==kPPDATA) || (colli==kPPMC) ) {
    theJet = &(c->ak3PF) ;
    cout << "pp collision.  Using ak3PF Jet Algo" << endl<<endl;
  }
  else {
    theJet = &(c->akPu3PF) ;
    cout << "pa, aa collision. Using akPu3PF Jet Algo" << endl<<endl;
  }

  // Loop starts.
  int nentries = c->GetEntries();
  cout << "number of entries = " << nentries << endl;
  for (Long64_t jentry = 0 ; jentry < nentries; jentry++) {
    eTot++;
    if (jentry% 2000 == 0)  {
      cout <<jentry<<" / "<<nentries<<" "<<setprecision(2)<<(double)jentry/nentries*100<<endl;
    }
    
    // Select events with a generated photon in mid-rapidity
    bool genPhotonFlag=false;
    if ( isMC )  
      genPhotonFlag = true;
    else {
      for ( int g=0 ; g< c->genp.nPar ; g++) {
	if ( c->genp.id[g] != 22 )
	  continue;
	if ( fabs( c->genp.momId[g] ) > 22 )
	  continue;
	if ( fabs( c->genp.status[g] ) != 1 )
	  continue;
	if ( fabs( c->genp.eta[g] ) > 1.44 ) 
	  continue;
	if ( c->genp.et[g] < 35 )
	  continue;
	genPhotonFlag = true;
      }
    }
    if ( !genPhotonFlag) 
      continue;
    
    c->GetEntry(jentry);
    evt.clear();
    evt.run   = c->evt.run;
    evt.evt = c->evt.evt;
    evt.hf4Pos = c->evt.hiHFplusEta4;
    evt.hf4Neg = c->evt.hiHFminusEta4;
    evt.hf4Sum = evt.hf4Pos + evt.hf4Neg;
    evt.cBin = -99;
    evt.pBin   = -99 ;
    if ((colli==kHIDATA)||(colli==kHIMC))   {
      evt.cBin = c->evt.hiBin;
      evt.pBin   = hEvtPlnBin->FindBin( c->evt.hiEvtPlanes[theEvtPlNumber] ) ;
    }
    else if ((colli==kPADATA)||(colli==kPAMC))   {
      evt.cBin =  getHfBin(evt.hf4Sum);
      if (  ((evt.cBin) < 0) || (evt.cBin) > 18 )
        cout << " Check the pA centrality..  cbin = " << evt.cBin << endl;
    }

    evt.trig = 0;
    evt.offlSel = (c->skim.pcollisionEventSelection > 0);
    evt.noiseFilt = (c->skim.pHBHENoiseFilter > 0);
    evt.anaEvtSel = c->selectEvent() && evt.trig;
    evt.vz = c->evt.vz;


    if ( ( (colli==kHIDATA)||(colli==kHIMC)||(colli==kPADATA)||(colli==kPAMC) ) && ( c->selectEvent() == 0 ))
      continue;
    if ( ( (colli==kPADATA)||(colli==kPPDATA) ) && ( c->skim.pVertexFilterCutGplus ==0 ) ) // No Pile up events
      continue;

    eSel++;      // OK.  This event is a collisional and no-noise event.

    int cBin = evt.cBin;
    int vzBin = hvz->FindBin(evt.vz)  ;
    hvz->Fill(evt.vz) ;
    if ( (vzBin<1) || ( vzBin > nVtxBin) )
      continue;

 
    // Reweight for vertex and centrality of MC 
    evt.vtxCentWeight = 1;
    double wVtx=1;
    double wCent=1;
    if (colli ==kHIMC) {
      int vBin =  hWeight_vtx_data_pbpb->FindBin(evt.vz);
      wVtx =   hWeight_vtx_data_pbpb->GetBinContent(vBin) / hWeight_vtx_mc_pbpb->GetBinContent(vBin) ;
      wCent =  hWeight_cent_data_pbpb->GetBinContent(evt.cBin+1) / hWeight_cent_mc_pbpb->GetBinContent(evt.cBin+1) ;
    }
    else if ( colli ==kPPMC) {
      int vBin =  hWeight_vtx_data_pp->FindBin(evt.vz);
      wVtx =   hWeight_vtx_data_pp->GetBinContent(vBin) / hWeight_vtx_mc_pp->GetBinContent(vBin) ;
    }
    else if ( colli ==kPAMC) {
      int vBin =  hWeight_vtx_data_ppb->FindBin(evt.vz);
      wVtx =   hWeight_vtx_data_ppb->GetBinContent(vBin) / hWeight_vtx_mc_ppb->GetBinContent(vBin) ;
    }
    evt.vtxCentWeight = wVtx * wCent;
    //    cout << " vz = " << evt.vz << "     centrality = " << evt.cBin << endl;
    //   cout <<" reweight = " << evt.reweight << endl;
    
    /// correct the photon energy and make order
      
    evt.ptHat = -1;
    evt.ptHatWeight = 1;
    evt.ptHat = c->photon.ptHat; 

    if (colli ==kHIMC) {
      if ( evt.ptHat < 50  )       evt.ptHatWeight = 0.655032/16237. ;
      else if ( evt.ptHat < 80  )       evt.ptHatWeight = 0.267898/85438. ;
      else   evt.ptHatWeight =  0.0770698/140432. ;
    }
    else if ( colli == kPPMC) { // pp has only 4 pthat samples 
      if ( evt.ptHat < 50  )       evt.ptHatWeight = 0.631803/9008. ;
      else if ( evt.ptHat < 80  )       evt.ptHatWeight = 0.272383/40109. ;
      else   evt.ptHatWeight = 0.0958137/66934. ;
    }
    
    for (int j=0;j< c->photon.nPhotons;j++) {
      
      if (  ( c->photon.pt[j] > preCutPhotonEt ) && ( fabs( c->photon.eta[j] ) < cutphotonEta ) ) {
	newPt[j] = c->getCorrEt(j);
      }
      else
	newPt[j] = c->photon.pt[j] - 10000;

      if ( (c->isSpike(j)) || (c->photon.hadronicOverEm[j]>0.2) ||  (c->photon.isEle[j]) )
	newPt[j] = newPt[j] - 20000;
      if (c->photon.seedTime[j] ==0 )   // clustering bug
	newPt[j] = newPt[j] - 30000;

      corrPt[j] = newPt[j];
    }

    TMath::Sort(c->photon.nPhotons, newPt, order);


    // Select the leading photon
    gj.clear();
    int leadingIndex=-1;
    for (int j=0;j<c->photon.nPhotons;j++) {
      if ( c->photon.pt[j]  < preCutPhotonEt ) continue;
      if ( fabs(c->photon.eta[j]) > cutphotonEta ) continue;
      if (c->isSpike(j)) continue;
      if (!(c->isLoosePhoton(j))) continue;

      // sort using corrected photon pt
      float theCorrPt= corrPt[j];
      if ( theCorrPt > gj.photonEt) {
	gj.photonEt = theCorrPt;
	leadingIndex = j;
      }
    }
    if ( (gj.photonEt < cutphotonPt) )
      continue;


    /// Save leading photons
    if (leadingIndex!=-1) {
      gj.photonRawEt=c->photon.pt[leadingIndex];
      gj.photonEta=c->photon.eta[leadingIndex];
      gj.photonPhi=c->photon.phi[leadingIndex];
      gj.hovere=c->photon.hadronicOverEm[leadingIndex];
      gj.r9=c->photon.r9[leadingIndex];
      gj.sigmaIetaIeta=c->photon.sigmaIetaIeta[leadingIndex];
      gj.sumIsol = (c->photon.cr4[leadingIndex]+c->photon.cc4[leadingIndex]+c->photon.ct4PtCut20[leadingIndex]) / 0.9;
      gj.genIso   = c->photon.genCalIsoDR04[leadingIndex];
      gj.genPhotonEt = c->photon.genMatchedPt[leadingIndex];
      gj.genMomId = c->photon.genMomId[leadingIndex];
      isol.Set(c,leadingIndex);
    }
    else {
      gj.clear();
    }
    if ( (colli==kPADATA) && ( evt.run > 211256 ) )  {
      gj.photonEta = - gj.photonEta;
      //      cout << " reflect eta" << endl;
    }



    ///////////////////// Skimmed Jet tree ///////////////////////////////////
    nJet = 0 ;

    int jetEntries = 0;
    if (useGenJetColl )    jetEntries = theJet->ngen;
    else                   jetEntries = theJet->nref;

    int nSmear = 1;
    if(smearingCentBin != -1)
      nSmear = 100;

    for (int ij=0; ij< jetEntries ; ij++) {
      for(int iSmear =0; iSmear < nSmear; iSmear++){
	
	if (  useGenJetColl )   {
	  jetPt[nJet] = theJet->genpt[ij];
	  jetEta[nJet] = theJet->geneta[ij];
	  jetPhi[nJet] = theJet->genphi[ij];
	}
	else  {
	  jetPt[nJet] = theJet->jtpt[ij];
	  jetEta[nJet] = theJet->jteta[ij];
	  jetPhi[nJet] = theJet->jtphi[ij];
	}

	// Smear phi
	Double_t newPhi = jetPhi[nJet] ;
	if( smearingCentBin != -1 )
	{
	  Double_t phiSmear  = TMath::Sqrt((cphi_pbpb[smearingCentBin]*cphi_pbpb[smearingCentBin] - cphi_pp*cphi_pp)
					   + (sphi_pbpb[smearingCentBin]*sphi_pbpb[smearingCentBin] - sphi_pp*sphi_pp)/jetPt[nJet]
					   + (nphi_pbpb[smearingCentBin]*nphi_pbpb[smearingCentBin] - nphi_pp*nphi_pp)/(jetPt[nJet]*jetPt[nJet]));
	  newPhi  =  jetPhi[nJet] +   rand.Gaus(0, phiSmear);
	  while ( fabs(newPhi) > PI )  {
	    if ( newPhi > PI )  newPhi = newPhi - 2*PI;
	    if ( newPhi < -PI )  newPhi = newPhi + 2*PI;
	  }
	}
	jetPhi[nJet] = newPhi;


	// smear the jet pT
	//float smeared = jetPt[nJet] * rand.Gaus(1,addJetEnergyRes/jetPt[nJet])   *  rand.Gaus(1, addFlatJetEnergyRes) ;
	Double_t smeared = jetPt[nJet];
	if( smearingCentBin != -1 )
	{
	  Double_t smearSigma = TMath::Sqrt((c_pbpb[smearingCentBin]*c_pbpb[smearingCentBin] - c_pp*c_pp)
					    + (s_pbpb[smearingCentBin]*s_pbpb[smearingCentBin] - s_pp*s_pp)/jetPt[nJet]
					    + (n_pbpb[smearingCentBin]*n_pbpb[smearingCentBin] - n_pp*n_pp)/(jetPt[nJet]*jetPt[nJet]));
	  smeared = jetPt[nJet] * rand.Gaus(1, smearSigma);
	}
	// then multiply jet energy sclae

	// resCorrection
	float resCorrection =1. ;
	float l2l3Corr =1 ;

	if  (doJetResCorrection)   {
	  if ((colli==kHIDATA)||(colli==kHIMC))  { // do the residual correction
	    if ( evt.cBin  < 12 )   // central
	      resCorrection  =  1.04503 -1.6122  /(sqrt(jetPt[nJet])) + 9.27212 / (jetPt[nJet]);  //1.04503    -1.6122    9.27212
	    else                  // peripheral
	      resCorrection  =  1.00596 -0.653191/(sqrt(jetPt[nJet])) + 4.35373 / (jetPt[nJet]);  //1.00596     -0.653191  4.35373
	  }
	  else if ((colli==kPPDATA)||(colli==kPPMC)){  // do the residual correction
	    resCorrection  = 0.993609  +0.158418/(sqrt(jetPt[nJet])) + 0.335479 / (jetPt[nJet]);//	  0.993609   0.158418   0.335479
	  }

	  // L2L3 correction!
	  if ( colli == kPPDATA)   {
	    l2l3Corr = c_etapp->GetBinContent(c_etapp->FindBin(jetEta[nJet])) * fptpp->Eval( jetPt[nJet]);
	  }
	  else if ( colli == kPADATA)   {
	    if ( evt.run > 211256 )
	      l2l3Corr = c_etapA->GetBinContent(c_etapA->FindBin(jetEta[nJet]))  * fptpA->Eval( jetPt[nJet]);
	    else
	      l2l3Corr = c_etaAp->GetBinContent(c_etaAp->FindBin(jetEta[nJet]))  * fptAp->Eval( jetPt[nJet]);
	  }
	  else if ( colli == kPAMC)
	    l2l3Corr = 1 + (fsmear_pA->Eval( jetPt[nJet] )) * fgaus->GetRandom()  ;
	}

	// reflect eta! 
	if ( (colli==kPADATA) && ( evt.run > 211256 ) )  {
	  jetEta[nJet] = -jetEta[nJet];
	}

	jetPt[nJet] = smeared * l2l3Corr /resCorrection;

      

	if ( jetPt[nJet] < cutjetPtSkim)  // double cutjetPtSkim = 15; Oct 19th
	  continue;
	if ( fabs( jetEta[nJet] ) > cutjetEtaSkim )     // double cutjetEtaSkim = 3.0; Oct 19th
	  continue;
	if ( getDR( jetEta[nJet], jetPhi[nJet], gj.photonEta, gj.photonPhi) < 0.5 )
	  continue;


	if (jetPt[nJet] >0)
	  jetDphi[nJet] = getAbsDphi( jetPhi[nJet], gj.photonPhi) ;
	else
	  jetDphi[nJet] = -1;


	if (  useGenJetColl )   {
	  jetSubid[nJet] = -9999;
	  jetRefPt[nJet] = -9999;
	  jetRefEta[nJet] = -9999;
	  jetRefPhi[nJet] = -9999;
	  jetRefPt[nJet] =  -9999;
	  jetRefPartonPt[nJet] = -9999;
	  jetRefPartonFlv[nJet] = -9999;
	}
	else {
	  jetSubid[nJet] = theJet->subid[ij];
	  jetRefPt[nJet] = theJet->refpt[ij];
	  jetRefEta[nJet] = theJet->refeta[ij];
	  jetRefPhi[nJet] = theJet->refphi[ij];
	  if (jetRefPt[nJet] >0)
	    jetRefDphi[nJet] = getAbsDphi( jetRefPhi[nJet] , gj.photonPhi) ;
	  else
	    jetRefDphi[nJet] = -1;
	  jetRefPartonPt[nJet] = theJet->refparton_pt[ij];
	  jetRefPartonFlv[nJet] = theJet->refparton_flavor[ij];
	}

	nJet++ ;
      }
    }

    //////// Leading jet kinematics in dphi>7pi/8
    float maxJpt = 0;
    int jetLeadingIndex = -1;

    for (int ij=0; ij< nJet ; ij++) {
      if ( jetDphi[ij] < awayRange )  // const float awayRange= PI * 7./8.;
	continue;
      if ( fabs( jetEta[ij] ) > cutjetEta )  // double cutjetEta = 1.6;
	continue;
      if ( jetPt[ij] > maxJpt) {
	maxJpt = jetPt[ij] ;
	jetLeadingIndex = ij;
      }
    }
    if ( jetLeadingIndex > -1 ) {
      gj.lJetPt = jetPt[jetLeadingIndex];
      gj.lJetEta = jetEta[jetLeadingIndex];
      gj.lJetPhi = jetPhi[jetLeadingIndex];
      gj.lJetDphi =  jetDphi[jetLeadingIndex];
      gj.lJetSubid=  jetSubid[jetLeadingIndex];
    }
    else {
      gj.lJetPt = -1;
      gj.lJetEta = 999;
      gj.lJetPhi = 999;
      gj.lJetDphi = 0;
      gj.lJetSubid=  -99;
    }


    int nMixing = nMixing1;
    nMjet = 0;
    bool noSuchEvent = false;
    int iMix=0;
    int loopCounter=0;

    if ( !doMix )
      iMix = nMixing+1;   // Mixing step will be skipped

    while (iMix<nMixing)  {
      loopCounter++;
      if ( loopCounter > nMB[cBin][vzBin]+1) {
	iMix = 999999 ;
	noSuchEvent = true;
	cout << " no such event!! :  icent = " << cBin << ",  vzBin = " << vzBin << ",  pBin = " << evt.pBin << endl;
	continue;
      }

      mbItr[cBin][vzBin] = mbItr[cBin][vzBin] + 1;
      if ( mbItr[cBin][vzBin] == nMB[cBin][vzBin] )
	mbItr[cBin][vzBin] =  mbItr[cBin][vzBin] - nMB[cBin][vzBin];

      /// Load the minbias tracks!!
      tjmb[cBin][vzBin]->GetEntry(mbItr[cBin][vzBin]);



      // ok found the event!! ///////////
      loopCounter =0;  // Re-initiate loopCounter
      // Jet mixing
      for (int it = 0 ; it < nJetImb ; it++) {

	// Smear phi
	Double_t newPhi = jetPhiImb[it];
	if( smearingCentBin != -1 )
	{
	  Double_t phiSmear  = TMath::Sqrt((cphi_pbpb[smearingCentBin]*cphi_pbpb[smearingCentBin] - cphi_pp*cphi_pp)
					   + (sphi_pbpb[smearingCentBin]*sphi_pbpb[smearingCentBin] - sphi_pp*sphi_pp)/jetPtImb[it]
					   + (nphi_pbpb[smearingCentBin]*nphi_pbpb[smearingCentBin] - nphi_pp*nphi_pp)/(jetPtImb[it]*jetPtImb[it]));
	  newPhi  =  jetPhiImb[it] +   rand.Gaus(0, phiSmear);
	  while ( fabs(newPhi) > PI )  {
	    if ( newPhi > PI )  newPhi = newPhi - 2*PI;
	    if ( newPhi < -PI )  newPhi = newPhi + 2*PI;
	  }
	}
	jetPhiImb[it] = newPhi;
	
	
	// smear the jet pT
	//float smeared = jetPtImb[it] * rand.Gaus(1,addJetEnergyRes/jetPtImb[it]) *  rand.Gaus(1, addFlatJetEnergyRes) ;
	Double_t smeared = jetPtImb[it];
	if( smearingCentBin != -1 )
	{
	  Double_t smearSigma = TMath::Sqrt((c_pbpb[smearingCentBin]*c_pbpb[smearingCentBin] - c_pp*c_pp)
					    + (s_pbpb[smearingCentBin]*s_pbpb[smearingCentBin] - s_pp*s_pp)/jetPtImb[it]
					    + (n_pbpb[smearingCentBin]*n_pbpb[smearingCentBin] - n_pp*n_pp)/(jetPtImb[it]*jetPtImb[it]));
	  smeared = jetPtImb[it] * rand.Gaus(1, smearSigma);
	}
	float resCorrection =1. ;
	float l2l3Corr =1 ;

	if  (doJetResCorrection)   {
	  // Correction from MC closure
	  if ((colli==kHIDATA)||(colli==kHIMC))  { // do the residual correction
	    if ( evt.cBin  < 12 )   // central
	      resCorrection  =  1.04503 -1.6122  /(sqrt(jetPtImb[it])) + 9.27212 / (jetPtImb[it]);  //1.04503    -1.6122    9.27212
	    else                  // peripheral
	      resCorrection  =  1.00596 -0.653191/(sqrt(jetPtImb[it])) + 4.35373 / (jetPtImb[it]);  //1.00596     -0.653191  4.35373
	  }
	  else if ((colli==kPPDATA)||(colli==kPPMC)){  // do the residual correction
	    resCorrection  = 0.993609  +0.158418/(sqrt(jetPtImb[it])) + 0.335479 / (jetPtImb[it]);//          0.993609   0.158418   0.335479
	  }
	  // L2L3
	  if ( colli == kPPDATA)   {
	    l2l3Corr = c_etapp->GetBinContent(c_etapp->FindBin(jetEtaImb[it])) * fptpp->Eval( jetPtImb[it]);
	  }
	  else if ( colli == kPADATA)   {
	    if ( evt.run > 211256 )
	      l2l3Corr = c_etapA->GetBinContent(c_etapA->FindBin(jetEtaImb[it]))  * fptpA->Eval( jetPtImb[it]);
	    else
	      l2l3Corr = c_etaAp->GetBinContent(c_etaAp->FindBin(jetEtaImb[it]))  * fptAp->Eval( jetPtImb[it]);
	  }
	  else if ( colli == kPAMC)
	    l2l3Corr = 1 + (fsmear_pA->Eval( jetPtImb[it] )) * fgaus->GetRandom()  ;
	}


	float smearedCorrected  = smeared *l2l3Corr / resCorrection; // residual correction

	if ( smearedCorrected < cutjetPtSkim )  // double cutjetPtSkim = 15; Oct 19th
	  continue;
	if ( fabs( jetEtaImb[it] ) > cutjetEtaSkim )   // double cutjetEtaSkim = 3.0; Oct 19th
	  continue;
	if ( getDR( jetEtaImb[it], jetPhiImb[it], gj.photonEta, gj.photonPhi) < 0.5 )  // This cut added for consistency ; Oct 19th
	  continue;

	mJetPt[nMjet]    = smearedCorrected;
	mJetEta[nMjet]   = jetEtaImb[it];
	mJetPhi[nMjet]   = jetPhiImb[it];
	if  ( mJetPt[nMjet]>0 )
	  mJetDphi[nMjet]  =   getAbsDphi(mJetPhi[nMjet], gj.photonPhi) ;
	else
	  mJetDphi[nMjet]=-1;

	nMjet++; // < == Important!
      }


      iMix++;
    }
    if ( noSuchEvent )
      continue;

    tgj->Fill();
    newtreeJet->Fill();
    tmixJet->Fill();
    newtreePhoton->Fill();
    genpana->Fill();
    //    treeFullJet->Fill();
  }



  newfile_data->Write();
  //   newfile_data->Close();   // <<=== If there is close() function. writing stucks in the middle of looping.. I don't know why!!
  cout << " Done! "<< endl;
  cout << "    " << eSel<<" out of total "<<eTot<<" events were analyzed."<<endl;
}
コード例 #7
0
void 
HTT_TT_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., string inputfile="root/$HISTFILE", const char* directory="tauTau_$CATEGORY")
{
  // defining the common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  // determine category tag
  const char* category_extra = "";
  if(std::string(directory) == std::string("tauTau_1jet"      )){ category_extra = "1 jet";             }
  if(std::string(directory) == std::string("tauTau_vbf"       )){ category_extra = "2 jet (VBF)";       }
  if(std::string(directory) == std::string("tauTau_nobtag"    )){ category_extra = "No B-Tag";          }
  if(std::string(directory) == std::string("tauTau_btag"      )){ category_extra = "B-Tag";             }

  const char* dataset;
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "CMS Preliminary,  H#rightarrow#tau#tau,  4.9 fb^{-1} at 7 TeV";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS Preliminary,  H#rightarrow#tau#tau,  19.8 fb^{-1} at 8 TeV";}
#ifdef MSSM
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS Preliminary, #sqrt{s} = 8 TeV, L = 19.8 fb^{-1}, H #rightarrow #tau #tau";}
#endif

  // open example histogram file
  TFile* input = new TFile(inputfile.c_str());
#ifdef MSSM
  TFile* input2 = new TFile((inputfile+"_$MA_$TANB").c_str());
#endif
  TH1F* Fakes  = refill((TH1F*)input->Get(TString::Format("%s/QCD"   , directory)), "QCD"); InitHist(Fakes, "", "", kMagenta-10, 1001);
  TH1F* EWK1   = refill((TH1F*)input->Get(TString::Format("%s/W"     , directory)), "W"  ); InitHist(EWK1 , "", "", kRed    + 2, 1001);
  TH1F* EWK2   = refill((TH1F*)input->Get(TString::Format("%s/ZJ"    , directory)), "ZJ" ); InitHist(EWK2 , "", "", kRed    + 2, 1001);
//TH1F* EWK3   = refill((TH1F*)input->Get(TString::Format("%s/ZL"    , directory)), "ZL" ); InitHist(EWK3 , "", "", kRed    + 2, 1001);
  TH1F* EWK    = refill((TH1F*)input->Get(TString::Format("%s/VV"    , directory)), "VV" ); InitHist(EWK  , "", "", kRed    + 2, 1001);
  TH1F* ttbar  = refill((TH1F*)input->Get(TString::Format("%s/TT"    , directory)), "TT" ); InitHist(ttbar, "", "", kBlue   - 8, 1001);
  TH1F* Ztt    = refill((TH1F*)input->Get(TString::Format("%s/ZTT"   , directory)), "ZTT"); InitHist(Ztt  , "", "", kOrange - 4, 1001);
#ifdef MSSM
  // float ggHScale = 1., bbHScale = 1.;
//   ggHScale = ($MSSM_SIGNAL_ggH_xseff_A + $MSSM_SIGNAL_ggH_xseff_hH);
//   bbHScale = ($MSSM_SIGNAL_bbH_xseff_A + $MSSM_SIGNAL_bbH_xseff_hH);
  TH1F* ggH    = refill((TH1F*)input2->Get(TString::Format("%s/ggH$MA", directory)), "ggH"); InitSignal(ggH); ggH->Scale($TANB); //ggH ->Scale(ggHScale);
  TH1F* bbH    = refill((TH1F*)input2->Get(TString::Format("%s/bbH$MA", directory)), "bbH"); InitSignal(bbH); bbH->Scale($TANB); //bbH ->Scale(bbHScale);
#else
  TH1F* ggH    = refill((TH1F*)input->Get(TString::Format("%s/ggH125", directory)), "ggH"); InitSignal(ggH); ggH ->Scale(SIGNAL_SCALE);
  TH1F* qqH    = refill((TH1F*)input->Get(TString::Format("%s/qqH125", directory)), "qqH"); InitSignal(qqH); qqH ->Scale(SIGNAL_SCALE);
  TH1F* VH     = refill((TH1F*)input->Get(TString::Format("%s/VH125" , directory)), "VH" ); InitSignal(VH ); VH  ->Scale(SIGNAL_SCALE);
#endif
#ifdef ASIMOV
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs_asimov", directory)), "data", true);
#else
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
#endif
  InitHist(data, "#bf{m_{#tau#tau} [GeV]}", "#bf{dN/dm_{#tau#tau} [1/GeV]}"); InitData(data);

  TH1F* ref=(TH1F*)Fakes->Clone("ref");
  ref->Add(EWK1 );
  ref->Add(EWK2 );
//ref->Add(EWK3 );
  ref->Add(ttbar);
  ref->Add(Ztt  );

  double unscaled[7];
  unscaled[0] = Fakes->Integral();
  unscaled[1] = EWK  ->Integral();
  unscaled[1]+= EWK1 ->Integral();
  unscaled[1]+= EWK2 ->Integral();
//unscaled[1]+= EWK3 ->Integral();
  unscaled[2] = ttbar->Integral();
  unscaled[3] = Ztt  ->Integral();
#ifdef MSSM
  unscaled[4] = ggH  ->Integral();
  unscaled[5] = bbH  ->Integral();
  unscaled[6] = 0;
#else
  unscaled[4] = ggH  ->Integral();
  unscaled[5] = qqH  ->Integral();
  unscaled[6] = VH   ->Integral();
#endif

  if(scaled){
    rescale(Fakes, 7); 
    rescale(EWK1 , 3); 
    rescale(EWK2 , 4); 
  //rescale(EWK3 , 5);
    rescale(EWK  , 6); 
    rescale(ttbar, 2); 
    rescale(Ztt  , 1);
#ifdef MSSM
    rescale(ggH  , 8); 
    rescale(bbH  , 9);  
#else
    rescale(ggH  , 8); 
    rescale(qqH  , 9);  
    rescale(VH   ,10);  
#endif
  }

  TH1F* scales[7];
  scales[0] = new TH1F("scales-Fakes", "", 7, 0, 7);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (Fakes->Integral()/unscaled[0]-1.) : 0.);
  scales[1] = new TH1F("scales-EWK"  , "", 7, 0, 7);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? ((EWK  ->Integral()
					       +EWK1 ->Integral()
					       +EWK2 ->Integral()
					      //+EWK3 ->Integral()
						)/unscaled[1]-1.) : 0.);
  scales[2] = new TH1F("scales-ttbar", "", 7, 0, 7);
  scales[2]->SetBinContent(3, unscaled[2]>0 ? (ttbar->Integral()/unscaled[2]-1.) : 0.);
  scales[3] = new TH1F("scales-Ztt"  , "", 7, 0, 7);
  scales[3]->SetBinContent(4, unscaled[3]>0 ? (Ztt  ->Integral()/unscaled[3]-1.) : 0.);
#ifdef MSSM
  scales[4] = new TH1F("scales-ggH"  , "", 7, 0, 7);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggH  ->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-bbH"  , "", 7, 0, 7);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (bbH  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-NONE" , "", 7, 0, 7);
  scales[6]->SetBinContent(7, 0.);
#else
  scales[4] = new TH1F("scales-ggH"  , "", 7, 0, 7);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggH  ->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-qqH"  , "", 7, 0, 7);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (qqH  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-VH"   , "", 7, 0, 7);
  scales[6]->SetBinContent(7, unscaled[6]>0 ? (VH   ->Integral()/unscaled[6]-1.) : 0.);
#endif

  EWK1 ->Add(Fakes);
  EWK2 ->Add(EWK1 );
//EWK3 ->Add(EWK2 );
//EWK  ->Add(EWK3 );
  EWK  ->Add(EWK2 );
  ttbar->Add(EWK  );
  Ztt  ->Add(ttbar);
  if(log){
#ifdef MSSM
    ggH  ->Add(bbH);
#else
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
  }
  else{
#ifdef MSSM    
    bbH  ->Add(Ztt);
    ggH  ->Add(bbH);
#else
    VH   ->Add(Ztt);
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
  }

  /*
    Mass plot before and after fit
  */
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);

  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(0, data->FindBin(500)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(1000)); };
#else
  data->GetXaxis()->SetRange(0, data->FindBin(350));
#endif
  data->SetNdivisions(505);
  data->SetMinimum(min);
  data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Ztt, log)));
  data->Draw("e");

  TH1F* errorBand = (TH1F*)Ztt ->Clone();
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(1);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
    if(errorBand->GetBinContent(idx)>0){
      std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
      break;
    }
  }
  if(log){
    Ztt  ->Draw("histsame");
    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    Fakes->Draw("histsame");
    $DRAW_ERROR
    ggH  ->Draw("histsame");
  }
  else{
    ggH  ->Draw("histsame");
    Ztt  ->Draw("histsame");
    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    Fakes->Draw("histsame");
    $DRAW_ERROR
  }
  data->Draw("esame");
  canv->RedrawAxis();

  //CMSPrelim(dataset, "#tau_{h}#tau_{h}", 0.17, 0.835);
  CMSPrelim(dataset, "", 0.18, 0.835);  
  TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "NDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText("#tau_{h}#tau_{h}");
  chan->Draw();

  TPaveText* cat      = new TPaveText(0.20, 0.68+0.061, 0.32, 0.68+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();

#ifdef MSSM
  TPaveText* massA      = new TPaveText(0.75, 0.48+0.061, 0.85, 0.48+0.161, "NDC");
  massA->SetBorderSize(   0 );
  massA->SetFillStyle(    0 );
  massA->SetTextAlign(   12 );
  massA->SetTextSize ( 0.03 );
  massA->SetTextColor(    1 );
  massA->SetTextFont (   62 );
  massA->AddText("m_{A}=$MA GeV");
  massA->Draw();

  TPaveText* tanb      = new TPaveText(0.75, 0.44+0.061, 0.85, 0.44+0.161, "NDC");
  tanb->SetBorderSize(   0 );
  tanb->SetFillStyle(    0 );
  tanb->SetTextAlign(   12 );
  tanb->SetTextSize ( 0.03 );
  tanb->SetTextColor(    1 );
  tanb->SetTextFont (   62 );
  tanb->AddText("tan#beta=$TANB");
  tanb->Draw();

  TPaveText* scen      = new TPaveText(0.75, 0.40+0.061, 0.85, 0.40+0.161, "NDC");
  scen->SetBorderSize(   0 );
  scen->SetFillStyle(    0 );
  scen->SetTextAlign(   12 );
  scen->SetTextSize ( 0.03 );
  scen->SetTextColor(    1 );
  scen->SetTextFont (   62 );
  scen->AddText("m^{h}_{max}");
  scen->Draw();
#endif
  
#ifdef MSSM
  TLegend* leg = new TLegend(0.45, 0.65, 0.95, 0.88);
  SetLegendStyle(leg);
  leg->AddEntry(ggH  , "#phi#rightarrow#tau#tau" , "L" );
#else
  TLegend* leg = new TLegend(0.50, 0.65, 0.95, 0.88);
  SetLegendStyle(leg);
  if(SIGNAL_SCALE!=1){
    leg->AddEntry(ggH  , TString::Format("%.0f#timesH(125 GeV)#rightarrow#tau#tau", SIGNAL_SCALE) , "L" );
  }
  else{
    leg->AddEntry(ggH  , "H(125 GeV)#rightarrow#tau#tau" , "L" );
  }
#endif
#ifdef ASIMOV
  leg->AddEntry(data , "sum(bkg) + SM125 GeV signal"    , "LP");
#else
  leg->AddEntry(data , "observed"                       , "LP");
#endif
  leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
  leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
  leg->AddEntry(EWK  , "electroweak"                    , "F" );
  leg->AddEntry(Fakes, "QCD"                            , "F" );
  $ERROR_LEGEND
  leg->Draw();

//#ifdef MSSM
//  TPaveText* mssm  = new TPaveText(0.69, 0.85, 0.90, 0.90, "NDC");
//  mssm->SetBorderSize(   0 );
//  mssm->SetFillStyle(    0 );
//  mssm->SetTextAlign(   12 );
//  mssm->SetTextSize ( 0.03 );
//  mssm->SetTextColor(    1 );
//  mssm->SetTextFont (   62 );
//  mssm->AddText("(m_{A}=120, tan#beta=10)");
//  mssm->Draw();
//#else
//  TPaveText* mssm  = new TPaveText(0.83, 0.85, 0.95, 0.90, "NDC");
//  mssm->SetBorderSize(   0 );
//  mssm->SetFillStyle(    0 );
//  mssm->SetTextAlign(   12 );
//  mssm->SetTextSize ( 0.03 );
//  mssm->SetTextColor(    1 );
//  mssm->SetTextFont (   62 );
//  mssm->AddText("m_{H}=125");
//  mssm->Draw();
//#endif

  /*
    Ratio Data over MC
  */
  TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
  canv0->SetGridx();
  canv0->SetGridy();
  canv0->cd();

  TH1F* zero = (TH1F*)ref->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)data->Clone("rat"); 
  rat1->Divide(Ztt);
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
    zero->SetBinContent(ibin+1, 0.);
  }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+0.5);
  rat1->SetMinimum(-0.5);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
  rat1->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  rat1->Draw();
  zero->SetLineColor(kBlack);
  zero->Draw("same");
  canv0->RedrawAxis();

  /*
    Ratio After fit over Prefit
  */
  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  TH1F* rat2 = (TH1F*) Ztt->Clone("rat2");
  rat2->Divide(ref);
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    if(rat2->GetBinContent(ibin+1)>0){
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
    }
  }
  rat2->SetLineColor(kRed+ 3);
  rat2->SetFillColor(kRed-10);
  rat2->SetMaximum(+0.3);
  rat2->SetMinimum(-0.3);
  rat2->GetYaxis()->SetTitle("#bf{Fit/Prefit-1}");
  rat2->GetYaxis()->CenterTitle();
  rat2->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  rat2->Draw();
  zero->SetLineColor(kBlack);
  zero->Draw("same");
  canv1->RedrawAxis();

  /*
    Relative shift per sample
  */
  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
  canv2->SetGridx();
  canv2->SetGridy();
  canv2->cd();

  InitHist  (scales[0], "", "", kMagenta-10, 1001);
  InitHist  (scales[1], "", "", kRed    + 2, 1001);
  InitHist  (scales[2], "", "", kBlue   - 8, 1001);
  InitHist  (scales[3], "", "", kOrange - 4, 1001);
  InitSignal(scales[4]);
  InitSignal(scales[5]);
  InitSignal(scales[6]);

  scales[0]->Draw();
  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{Fakes}");
  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{EWK}"  );
  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{ttbar}");
  scales[0]->GetXaxis()->SetBinLabel(4, "#bf{Ztt}"  );
#ifdef MSSM
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{bbH}"  );
  scales[0]->GetXaxis()->SetBinLabel(7, "NONE"      );
#else
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{qqH}"  );
  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{VH}"   );
#endif
  scales[0]->SetMaximum(+1.0);
  scales[0]->SetMinimum(-1.0);
  scales[0]->GetYaxis()->CenterTitle();
  scales[0]->GetYaxis()->SetTitle("#bf{Fit/Prefit-1}");
  scales[1]->Draw("same");
  scales[2]->Draw("same");
  scales[3]->Draw("same");
  scales[4]->Draw("same");
  scales[5]->Draw("same");
  scales[6]->Draw("same");
  zero->Draw("same");
  canv2->RedrawAxis();

  /*
    prepare output
  */
  bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv ->Print(TString::Format("%s_%sfit_%s_%s.png"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv ->Print(TString::Format("%s_%sfit_%s_%s.pdf"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv ->Print(TString::Format("%s_%sfit_%s_%s.eps"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  if(!log || FULLPLOTS)
  {
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }
  if((!log && scaled) || FULLPLOTS)
  {
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }

  TFile* output = new TFile(TString::Format("%s_%sfit_%s_%s.root", directory, scaled ? "pre" : "post", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"), "update");
  output->cd(); 
  data ->Write("data_obs");
  Fakes->Write("Fakes"   );
  EWK  ->Write("EWK"     );
  ttbar->Write("ttbar"   );
  Ztt  ->Write("Ztt"     );
#ifdef MSSM
  ggH  ->Write("ggH"     );
  bbH  ->Write("bbH"     );
#else
  ggH  ->Write("ggH"     );
  qqH  ->Write("qqH"     );
  VH   ->Write("VH"      );
#endif
  output->Close();
}
コード例 #8
0
ファイル: postfit.C プロジェクト: aashaqshah/cmssw-1
void 
postfit(const char* inputfile, const char* analysis = "SM", const char* dataset = "2011+2012", const char* extra="", const char* extra2="", float min=0.1, float max=-1., bool log=true)
{
  // defining the common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");
  // switch for MSSM/SM
  bool MSSM = std::string(analysis) == std::string("MSSM");
  // determine label
  if (std::string(dataset) == std::string("2011"     )){ dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 4.9 fb^{-1} at 7 TeV"; }
  if (std::string(dataset) == std::string("2012"     )){ 
	if (std::string(extra) == std::string("#mu#mu") ) dataset = "MS Preliminary,  H#rightarrow#tau#tau, 18.7 fb^{-1} at 8 TeV"; 
	else dataset = "MS Preliminary,  H#rightarrow#tau#tau, 19.4 fb^{-1} at 8 TeV";
  }
  if (std::string(dataset) == std::string("2011+2012")){ 
	if (std::string(extra) == std::string("#mu#mu") ) dataset = "CMS Preliminary,  H#rightarrow#tau#tau,  4.9 fb^{-1} at 7 TeV, 18.6 fb^{-1} at 8 TeV"; 
 	else dataset = "CMS Preliminary,  H#rightarrow#tau#tau,  4.9 fb^{-1} at 7 TeV, 19.4 fb^{-1} at 8 TeV";
	if (MSSM) dataset = "CMS Preliminary,  H#rightarrow#tau#tau,  4.9 fb^{-1} at 7 TeV, 12.1 fb^{-1} at 8 TeV";
  }
  // determine category tag
  const char* category_extra = "";
  if(std::string(extra2) == std::string("0jet_low"  )){ category_extra = "0 jet, low p_{T}";  }
  if(std::string(extra2) == std::string("0jet_high" )){ category_extra = "0 jet, high p_{T}"; }
  if(std::string(extra2) == std::string("0jet"      )){ category_extra = "0 jet";             }
  if(std::string(extra2) == std::string("boost_low" )){ category_extra = "1 jet, low p_{T}";  }
  if(std::string(extra2) == std::string("boost_high")){ category_extra = "1 jet, high p_{T}"; }
  if(std::string(extra2) == std::string("boost"     )){ category_extra = "1 jet";             }
  if(std::string(extra2) == std::string("vbf"       )){ category_extra = "2 jet (VBF)";       }
  if(std::string(extra2) == std::string("nobtag"    )){ category_extra = "No B-Tag";          }
  if(std::string(extra2) == std::string("btag"      )){ category_extra = "B-Tag";             }

  TFile* input = new TFile(inputfile);
  TH1F* Fakes  = refill((TH1F*)input->Get("Fakes"   ), "Fakes/QCD"); 
  TH1F* EWK    = refill((TH1F*)input->Get("EWK"     ), "EWK"      ); 
  TH1F* ttbar  = refill((TH1F*)input->Get("ttbar"   ), "ttbar"    ); 
  TH1F* Ztt    = refill((TH1F*)input->Get("Ztt"     ), "Ztt"      ); 
  TH1F* Zmm    = refill((TH1F*)input->Get("Zmm"     ), "Zmm"      ); 
  TH1F* ggH    = refill((TH1F*)input->Get("ggH"     ), "ggH"      ); 
  TH1F* data   = (TH1F*)input->Get("data_obs"); 
  // determine channel for etau Z->ee (EWK) will be shown separated from the rest (EWK1)
  TH1F* EWK1   = 0;
  if(std::string(extra) == std::string("e#tau_{h}")){
    EWK1 = refill((TH1F*)input->Get("EWK1"),  "EWK1");
  }
  TH1F* errorBand = (TH1F*)input->Get("errorBand");

  /* 
    mass plot before and after fit
  */
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);
  if(log) canv->SetLogy(1);
  // reduce the axis range if necessary for linea plots and SM
  if(MSSM && !log){ data->GetXaxis()->SetRange(0, data->FindBin(350)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(490)); };
  if(!MSSM){ data->GetXaxis()->SetRange(0, data->FindBin(350)); }

  data->SetNdivisions(505);
  data->SetMinimum(min);
  if(Zmm){
    data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(EWK, log)));
  }
  else{
    data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Ztt, log)));
  }
  data->Draw("e");

  if(log){
    if(Zmm){
      EWK  ->Draw("same");
      ttbar->Draw("same");
      Fakes->Draw("same");
      Zmm  ->Draw("same");
      Ztt  ->Draw("same");
    }
    else{
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      EWK  ->Draw("same");
      if(EWK1){
	EWK1->Draw("same");
      }
      if(Fakes){ Fakes->Draw("same"); }
    }
    if(ggH) ggH  ->Draw("histsame");
  }
  else{
    if(ggH) ggH  ->Draw("histsame");
    if(Zmm){
      EWK->Draw("same");
      Fakes->Draw("same");
      ttbar->Draw("same");
      Zmm->Draw("same");
      Ztt->Draw("same");
    }
    else{
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      EWK  ->Draw("same");
      if(EWK1){
	EWK1->Draw("same");
      }
      if(Fakes){ Fakes->Draw("same"); }
    }
  }
  if(errorBand){
    errorBand->Draw("e2same");
  }
  data->Draw("esame");
  canv->RedrawAxis();

  //CMSPrelim(dataset, extra, 0.17, 0.835);
  CMSPrelim(dataset, "", 0.18, 0.835);  
  TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "NDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText(extra);
  chan->Draw();

  TPaveText* cat      = new TPaveText(0.20, 0.68+0.061, 0.32, 0.68+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();

  if(MSSM){
    TPaveText* massA      = new TPaveText(0.75, 0.48+0.061, 0.85, 0.48+0.161, "NDC");
    massA->SetBorderSize(   0 );
    massA->SetFillStyle(    0 );
    massA->SetTextAlign(   12 );
    massA->SetTextSize ( 0.03 );
    massA->SetTextColor(    1 );
    massA->SetTextFont (   62 );
    massA->AddText("m_{A}=160GeV");
    massA->Draw();
    
    TPaveText* tanb      = new TPaveText(0.75, 0.44+0.061, 0.85, 0.44+0.161, "NDC");
    tanb->SetBorderSize(   0 );
    tanb->SetFillStyle(    0 );
    tanb->SetTextAlign(   12 );
    tanb->SetTextSize ( 0.03 );
    tanb->SetTextColor(    1 );
    tanb->SetTextFont (   62 );
    tanb->AddText("tan#beta=20");
    tanb->Draw();
    
    TPaveText* scen      = new TPaveText(0.75, 0.40+0.061, 0.85, 0.40+0.161, "NDC");
    scen->SetBorderSize(   0 );
    scen->SetFillStyle(    0 );
    scen->SetTextAlign(   12 );
    scen->SetTextSize ( 0.03 );
    scen->SetTextColor(    1 );
    scen->SetTextFont (   62 );
    scen->AddText("mhmax");
    scen->Draw();
  }
  
  
  float lower_bound = EWK1 ? 0.60 : 0.65;
  TLegend* leg = new TLegend(MSSM ? 0.45 : 0.50, lower_bound, 0.93, 0.90);
  SetLegendStyle(leg);
  if(MSSM){
    leg->AddEntry(ggH  , "#phi#rightarrow#tau#tau", "L" );
  }
  else{
    if(ggH){
      if(SIGNAL_SCALE!=1){
	leg->AddEntry(ggH  , TString::Format("%.0f#timesH(125 GeV)#rightarrow#tau#tau", SIGNAL_SCALE) , "L" );
      }
      else{
	leg->AddEntry(ggH  , "H(125 GeV)#rightarrow#tau#tau" , "L" );
      }
    }
  }
  leg->AddEntry(data , "observed"                       , "LP");
  leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
  if(Zmm){ leg->AddEntry(Zmm  , "Z#rightarrow#mu#mu"    , "F" ); }
  if(EWK1){
    leg->AddEntry(EWK  , "Z#rightarrow ee"              , "F" );
    leg->AddEntry(EWK1 , "electroweak"                  , "F" );
  }
  else{
    leg->AddEntry(EWK  , "electroweak"                  , "F" );
  }
  leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
  if(Fakes){ leg->AddEntry(Fakes, "QCD"                 , "F" ); }
  if(errorBand){
    leg->AddEntry(errorBand, "bkg. uncertainty" , "F" );
  }
  leg->Draw();

  /*
  TPaveText* ext0     = new TPaveText(0.50, lower_bound-0.08, 0.70, lower_bound-0.03, "NDC");
  ext0->SetBorderSize(   0 );
  ext0->SetFillStyle(    0 );
  ext0->SetTextAlign(   12 );
  ext0->SetTextSize ( 0.035 );
  ext0->SetTextColor(    1 );
  ext0->SetTextFont (   42 );
  ext0->AddText("CMS Preliminary");
  ext0->Draw();

  TPaveText* ext1     = new TPaveText(0.50, lower_bound-0.13, 0.70, lower_bound-0.08, "NDC");
  ext1->SetBorderSize(   0 );
  ext1->SetFillStyle(    0 );
  ext1->SetTextAlign(   12 );
  ext1->SetTextSize ( 0.035 );
  ext1->SetTextColor(    1 );
  ext1->SetTextFont (   42 );
  ext1->AddText("#sqrt{s} = 7 TeV, L = 4.9 fb^{-1}");
  ext1->Draw();

  TPaveText* ext2     = new TPaveText(0.50, lower_bound-0.18, 0.70, lower_bound-0.13, "NDC");
  ext2->SetBorderSize(   0 );
  ext2->SetFillStyle(    0 );
  ext2->SetTextAlign(   12 );
  ext2->SetTextSize ( 0.035 );
  ext2->SetTextColor(    1 );
  ext2->SetTextFont (   42 );
  ext2->AddText("#sqrt{s} = 8 TeV, L = 19.4 fb^{-1}");
  ext2->Draw();
  
  TPaveText* ext3     = new TPaveText(0.50, lower_bound-0.23, 0.70, lower_bound-0.18, "NDC");
  ext3->SetBorderSize(   0 );
  ext3->SetFillStyle(    0 );
  ext3->SetTextAlign(   12 );
  ext3->SetTextSize ( 0.035 );
  ext3->SetTextColor(    1 );
  ext3->SetTextFont (   42 );
  ext3->AddText("H#rightarrow#tau#tau");
  ext3->Draw();
  */

  /*
    prepare output
  */
  std::string newName = std::string(inputfile).substr(0, std::string(inputfile).find(".root"));
  //canv->Print(TString::Format("%s%s.png", newName.c_str(), log ? "_LOG" : "")); 
  //canv->Print(TString::Format("%s%s.pdf", newName.c_str(), log ? "_LOG" : "")); 
  //canv->Print(TString::Format("%s%s.eps", newName.c_str(), log ? "_LOG" : "")); 
  canv->Print(TString::Format("%s.png", newName.c_str())); 
  canv->Print(TString::Format("%s.pdf", newName.c_str())); 
  canv->Print(TString::Format("%s.eps", newName.c_str())); 
}
コード例 #9
0
void SPEFit(char * fname, int run, int LED_amp, double cutmax = 250.0)
{

  //set plotting styles
  gStyle->SetCanvasColor(0);
  gStyle->SetPadColor(0);
  gStyle->SetCanvasBorderMode(0);
  gStyle->SetFrameBorderMode(0);
  gStyle->SetStatColor(0);
  gStyle->SetPadTickX(1);
  gStyle->SetPadTickY(1);

    //set file names
    stringstream out_fname;
    stringstream out_fname1;
    out_fname<<"SPEconstants_Run_"<<run<<".txt";
    out_fname1<<"SPEspec_Run_"<<run<<".txt";

    ofstream  constants_file(out_fname.str().c_str(),ios_base::trunc); 
    ofstream  constants_file1(out_fname1.str().c_str(),ios_base::trunc);
    constants_file<<"Run "<<run<<endl;
    constants_file<<"type SPE"<<endl;
    constants_file<<"LED_amplitude "<<LED_amp<<endl<<endl;

    //constants_file<<endl<<"LED_amplitude HV Spigot Channel Ped_mean Ped_mean_err Ped_RMS  Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl;
    constants_file<<endl<<"LED_amplitude HV Spigot Channel Ped_mean Ped_mean_err Ped_RMS  Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag Polya_shape Polya_shape_err Polya_mode"<<endl;

    out_fname.str("");
    out_fname<<"SPEdistributions_Run_"<<run<<".txt";


    out_fname.str("");
    out_fname<<"SPEextra_Run_"<<run<<".txt";
    //ofstream  extra_file(out_fname.str().c_str(),ios_base::trunc); 

    //extra_file<<endl<<"LED_amplitude HV Spigot Channel PedSubtracted_mean Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl;


    double scale = 1.0;
    scale = 2.6; //Need to scale up HF charge
    double fC2electrons = 6240.; //convert fC to #electrons

    char spename[128], pedname[128], spehistname[128];
    bool drawflag;   
 
    TFile *tf = new TFile(fname);
    
    TCanvas *c1 = new TCanvas("c1","c1",1200,700);
    c1->Divide(6,4);
    c1->SetBorderMode(0);
    c1->SetBorderSize(0);
    TCanvas *c2 = new TCanvas("c2","c2",1200,700);
    c2->Divide(6,4);
    c2->SetBorderMode(0);
    c2->SetBorderSize(0);  
    TCanvas *c3 = new TCanvas("c3","c3",1200,700);
    c3->Divide(6,4);
    c3->SetBorderMode(0);
    c3->SetBorderSize(0);

    const int NnewBins = 106;
    double binsX[NnewBins] = {0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,180,190,200,210,220,230,240,250,266,282,298,316,336,356,378,404,430,456,482,500};	  
    TH1F* hspe = new TH1F("hspe","hspe",NnewBins-1,binsX);

    int Npoints;
    TH2D *tmp;
    for(Npoints=0;Npoints<10;Npoints++){
      sprintf(spename,"spetest/spigot_%d/bb_%d/LED_HVset_%d_sp_%d_BB_%d",0,1,Npoints,0,1);
      tmp=(TH2D *)tf->Get(spename);
      if(tmp==0) break;
    }
    TH2D *LED[3][3][20];
    TH2D *PED[3][3];
    for(int iSpig = 0; iSpig < 3; iSpig++)for(int bb = 1; bb < 4; bb++){
        for(int ii=0; ii<Npoints; ii++){
           sprintf(spename,"spetest/spigot_%d/bb_%d/LED_HVset_%d_sp_%d_BB_%d",iSpig,bb,ii,iSpig,bb);
           LED[iSpig][bb-1][ii]=(TH2D *)tf->Get(spename);
        }
        sprintf(spename,"spetest/spigot_%d/bb_%d/PED_sp_%d_BB_%d",iSpig,bb,iSpig,bb);
        PED[iSpig][bb-1]=(TH2D *)tf->Get(spename);
    }


    for(int ii=0; ii<Npoints; ii++) {
      drawflag=false;
      int HV=0;
      for (int iSpig = 0; iSpig < 3; iSpig++) {
	for(int i = 0; i < 24; i++) {
            int bb=BB_MAP[i];
            int pmt=PMT_MAP[i];
            sprintf(spehistname,"led %d %d %d",ii,iSpig,i);
            TH1D *hspe_temp = (TH1D *)LED[iSpig][bb-1][ii]->ProjectionX(spehistname,pmt,pmt,"")->Clone();
            sprintf(spehistname,"ped %d %d %d",ii,iSpig,i);
            TH1D *hped = (TH1D *)PED[iSpig][bb-1]->ProjectionX(spehistname,pmt,pmt,"")->Clone();
            sscanf(&hspe_temp->GetTitle()[7],"%d",&HV);
	    hspe->Reset();
            sprintf (spehistname, "SumLED%d_sp_%d_ch_%d", HV, iSpig, i);
	    hspe->SetTitle(spehistname);

	    //combine bins of original SPE histogram
	    for(int ib=1; ib<=hspe_temp->GetNbinsX(); ib++) {
	      double bin_center = hspe_temp->GetBinCenter(ib);
	      if(bin_center>hspe->GetXaxis()->GetXmax()) continue;
	      int newbin = hspe->FindBin(bin_center);
	      double new_content = hspe->GetBinContent(newbin) + hspe_temp->GetBinContent(ib);
	      double new_error = sqrt(pow(hspe->GetBinError(newbin),2)+pow(hspe_temp->GetBinError(ib),2));
	      hspe->SetBinContent(newbin,new_content);
	      hspe->SetBinError(newbin,new_error);
	    }
	    TH1F* hspe_unscaled = (TH1F*)hspe->Clone("hspe_unscaled");

	    //renormalize bins of new SPE histogram
	    for(int ib=1; ib<=hspe->GetNbinsX(); ib++) {
	      double new_content = hspe->GetBinContent(ib)/hspe->GetXaxis()->GetBinWidth(ib)*hspe_temp->GetXaxis()->GetBinWidth(1);
	      double new_error = hspe->GetBinError(ib)/hspe->GetXaxis()->GetBinWidth(ib)*hspe_temp->GetXaxis()->GetBinWidth(1);
	      hspe->SetBinContent(ib,new_content);
	      hspe->SetBinError(ib,new_error);
	    }
	    
	    if(hspe_temp->Integral()==0) continue;
	    else drawflag=true;	  
    
            Nev = hspe_temp->Integral()*hspe_temp->GetXaxis()->GetBinWidth(1); 
	    
	    TF1 *fped = new TF1("fped","gaus",0, 80);
	    hped->Fit(fped,"NQR");
	    double pploc = fped->GetParameter(1), ppwidth = fped->GetParameter(2);
	    //cout<<"Ped only: ped mean "<<fped->GetParameter(1)<<", ped width "<<fped->GetParameter(2)<<" normalization "<<fped->GetParameter(0)<<endl;
	    hspe->Fit(fped, "NQ", "", pploc - 3*ppwidth, pploc + ppwidth);
	    //cout<<"SPE distribution: ped mean "<<fped->GetParameter(1)<<", ped width "<<fped->GetParameter(2)<<" normalization "<<fped->GetParameter(0)<<endl;
	    
	    
	    //estimate SPE peak location
	    int max_SPE_bin, maxbin, Nbins;
	    double max_SPE_height=0, minheight, max_SPE_location;
	    bool minflag = false;
	    maxbin=hspe->FindBin(fped->GetParameter(1)); //location of pedestal peak
	    minheight=hspe->GetBinContent(maxbin); //initialize minheight
	    /*
	    int maxped_bin = hspe->GetMaximumBin();
	    int maxped_binheight = hspe->GetBinContent(maxped_bin);
	    minheight = maxped_binheight;
	    */
	    Nbins = hspe->GetNbinsX();
	    for(int j=/*maxped_bin*/maxbin+1; j<Nbins-1; j++) { //start from pedestal peak and loop through bins
	      if(hspe->GetBinContent(j) > minheight && !minflag) minflag=true; //only look for SPE peak when minflag=true
	      if(hspe->GetBinContent(j) < minheight )  minheight = hspe->GetBinContent(j);
	      if(minflag && hspe->GetBinContent(j) > max_SPE_height){
		max_SPE_bin = j;
		max_SPE_location = hspe->GetBinCenter(max_SPE_bin);
		max_SPE_height = hspe->GetBinContent(j);
	      }
	    } //start from pedestal peak and loop through bins
	    //find minimum bin between pedestal and SPE peaks
	    hspe->GetXaxis()->SetRange(maxbin,max_SPE_bin);
	    int minbin = hspe->GetMinimumBin(); 
	    double minbin_location = hspe->GetBinCenter(minbin);
	    hspe->GetXaxis()->SetRange(1,Nbins);
	    
	    
	    TF1 *fit = new TF1("fit", FitFun, 0, 500, 5);
	    
	    double mu = - log(fped->Integral(0,100)/Nev);
	    if(mu<0) mu=0.01;
	    double gain_est = max_SPE_location-1.0*fped->GetParameter(1);
	    if(max_SPE_bin > (minbin+1)) fit->SetParameters(mu, 20, 1, gain_est, 3.0);
	    else fit->SetParameters(mu, 20, 1, 2.1*fped->GetParameter(2), 3.0); //case of no clear minimum; start looking for SPE peak at 2sigma away from pedestal peak
	    fit->SetParLimits(0, 0, 10);
	    fit->FixParameter(1, fped->GetParameter(1));
	    fit->FixParameter(2, fped->GetParameter(2));
	    fit->SetParLimits(3, fped->GetParameter(2)*2, 350);
	    fit->SetParLimits(4, 1.01, 100.);


	    double maxfitrange = 500.;    
	    double minfitrange = 0.;
	    hspe->Fit(fit, "MNQL", "", minfitrange, maxfitrange);
	    double rms_estimate = fit->GetParameter(3)/sqrt(fit->GetParameter(4));
            maxfitrange = fped->GetParameter(1)+4*fit->GetParameter(3)+rms_estimate;

 //  cout<<"estimate of gain "<<gain_est<<", fit "<<fit->GetParameter(3)<<endl;
 //  cout<<"Shape Parameter "<<fit->GetParameter(4)<<endl;
 //  cout<<"SPE width "<<rms_estimate<<endl;
 //  cout<<"maxfitrange "<<maxfitrange<<endl;

            if(500<maxfitrange) maxfitrange = 500;
	    hspe->Fit(fit, "MNQL", "", minfitrange, maxfitrange);

	    //calculate NDOF of fit excluding bins with 0 entries
	    int myNDOF=-3; //three free parameters
	    for(int j=hspe->FindBin(minfitrange); j<=hspe->FindBin(maxfitrange); j++) { //loop through fitted spe bins
	      if(hspe->GetBinContent(j)) myNDOF++;
            } //loop through fitted spe bins


//	    cout<<"estimate of gain "<<gain_est<<", fit "<<fit->GetParameter(3)<<endl;
//	    cout<<"Shape Parameter "<<fit->GetParameter(4)<<endl;
//	    double SPE_rms = fit->GetParameter(3)/sqrt(fit->GetParameter(4));
//	    cout<<"SPE width "<<SPE_rms<<endl;

	    //cout<<"SPE width "<<fit->GetParameter(4)<<endl;
	    //cout<<"Fit normalization constant: estimate "<<mu<<" fit "<<fit->GetParameter(0)<<endl;
	    //cout<<spename<<endl;


	    //calculate means and integrals of the fit and data
	    double fint, fint_error, hint, favg, havg;
	    int temp_lowbin, temp_highbin;
	    temp_lowbin = hspe->FindBin(minfitrange);
	    temp_highbin = hspe->FindBin(maxfitrange);
	    hspe_unscaled->GetXaxis()->SetRangeUser(minfitrange, maxfitrange);
	    havg = hspe_unscaled->GetMean();
	    hint = hspe->Integral(temp_lowbin,temp_highbin,"width");
	    double min_frange = hspe->GetBinLowEdge(temp_lowbin);
	    favg = fit->Mean(min_frange, maxfitrange);
	    fint = fit->Integral(min_frange, maxfitrange);
	    //fint_error = fit->IntegralError(min_frange, maxfitrange);
	    
	    double PE5int = 0; //integral of events with >=5 PE
	    double PE5loc =  fped->GetParameter(1)+ 5*fit->GetParameter(3);
	    if(PE5loc>500) PE5int = 0;
	    else {
	      int PE5bin =  hspe_temp->FindBin(PE5loc);
	      temp_highbin = hspe_temp->FindBin(maxfitrange)-1;
	      PE5int =  hspe_temp->Integral(PE5bin,temp_highbin,"width");
	    }
	    int PE5flag = 0;
	    if(PE5int/hint>0.05) PE5flag = 1; //set flag if more than 5% of events in the fit correspond to >=5PE
        //=========================================    
            for(int i1=1;i1<hspe->GetNbinsX();i1++){
constants_file1<<HV<<"\t"<<iSpig<<"\t"<<i<<"\t"<<2.6*hspe->GetBinCenter(i1)<<"\t"<<hspe->GetBinContent(i1)<<"\t"<<fit->Eval(hspe->GetBinCenter(i1))<<"\n";
            }
        //=========================================    


	    //output calibrations constants
	    //constants_file<<endl<<"LED_amplitude HV Spigot Channel Ped_mean Ped_mean_err Ped_RMS  Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag Polya_shape Polya_shape_err Polya_mode"<<endl;
	    constants_file<<LED_amp<<" "<<HV<<" "<<iSpig<<" "<<(bb-1)*8+pmt<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParError(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fped->GetParError(2)<<" "<<scale*fit->GetParameter(3)/sqrt(fit->GetParameter(4))<<" "<<0<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<scale*fit->GetParError(3)*fC2electrons<<" "<<fit->GetChisquare()/myNDOF/*fit->GetNDF()*/<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<" "<<fit->GetParameter(4)<<" "<<fit->GetParError(4)<<" "<<scale*(fit->GetParameter(4)-1.0)/fit->GetParameter(4)*fit->GetParameter(3)*fC2electrons<<endl;



//	    cout<<LED_amp<<" "<<HV<<" "<<iSpig<<" "<<QIECh[i]<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParError(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fped->GetParError(2)<<" "<<scale*fit->GetParameter(4)<<" "<<scale*fit->GetParError(4)<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<scale*fit->GetParError(3)*fC2electrons<<" "<<fit->GetChisquare()/fit->GetNDF()<<" "<<fit->GetChisquare()<<" "<<fit->GetNDF()<<" "<<myNDOF<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<endl;
	   
	    //extra_file<<endl<<"LED_amplitude HV Spigot Channel SignalAvg_inFitRange FitAvg_inFitRange SignalInt_inFitRange FitInt_inFitRange PEge5Int Gain(fC) Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl;
	    //extra_file<<LED_amp<<" "<<HV<<" "<<iSpig<<" "<<QIECh[i]<<" "<<scale*havg<<" "<<scale*favg<<" "<<hint<<" "<<fint<<" "<<PE5int<<" "<<scale*fit->GetParameter(3)<<" "<<scale*fit->GetParError(3)<<" "<<fit->GetChisquare()/myNDOF<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<endl;


	    //cout<<"# Spigot Channel Ped_mean Ped_RMS SPE_PeakRMS Gain Normalized_Chi2 Avg_PE"<<endl;
	    //cout<<iSpig<<" "<<i<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fit->GetParameter(4)<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<fit->GetChisquare()/fit->GetNDF()<<" "<<fit->GetParameter(0)<<endl<<endl;
	    
	    
	  
	    if(iSpig==0) c1->cd(i+1);
	    else if(iSpig==1) c2->cd(i+1);
            else if(iSpig==2) c3->cd(i+1);
	    gPad->SetBorderMode(0);
	    gPad->SetBorderSize(0);
	    gPad->SetRightMargin(0.01);
	    gPad->SetBottomMargin(0.1);
	    gPad->SetLogy(true);
	    hspe->GetXaxis()->SetRangeUser(0, /*300*/508);
	    hspe->SetLineColor(kBlue);
	    hspe->DrawClone("hist");
	    fit->SetLineWidth(2);
	    fit->Draw("same");
	   
	  }
      }

      if(drawflag) { //draw plots of fit if data for the HV is present
        stringstream plot_name;
        //plot_name<<"Plots/SPEFits_Spigot0_Run_"<<run<<"_HV"<<HV<<".pdf";
        plot_name<<"Plots/SPEFits_Spigot0_Run_"<<run<<"_HV"<<HV<<"_config"<<ii<<".pdf";
        c1->SaveAs(plot_name.str().c_str());
        plot_name.str( std::string() );
        //plot_name<<"Plots/SPEFits_Spigot1_Run_"<<run<<"_HV"<<HV<<".pdf";
        plot_name<<"Plots/SPEFits_Spigot1_Run_"<<run<<"_HV"<<HV<<"_config"<<ii<<".pdf";
        c2->SaveAs(plot_name.str().c_str());
        plot_name.str( std::string() );
        //plot_name<<"Plots/SPEFits_Spigot2_Run_"<<run<<"_HV"<<HV<<".pdf";
        plot_name<<"Plots/SPEFits_Spigot2_Run_"<<run<<"_HV"<<HV<<"_config"<<ii<<".pdf";
        c3->SaveAs(plot_name.str().c_str());
      }

    } //HV loop

    constants_file.close();
    constants_file1.close();
}
コード例 #10
0
ファイル: treeSkimmer.C プロジェクト: bianchini/usercode
void makeTrees_MuTau( int index = 0 ){
 
  cout <<  "Now analyzing sample with index " << index << endl;

  TFile corrections("../data/corrections.root");
  TF1 *ratioMuIDIsoBL     = (TF1*)corrections.Get("ratioMuIDIsoBL");
  TF1 *ratioMuIDIsoEC     = (TF1*)corrections.Get("ratioMuIDIsoEC");
  TF1 *ratioMuHLTBL       = (TF1*)corrections.Get("ratioMuHLTBL");
  TF1 *ratioMuHLTEC       = (TF1*)corrections.Get("ratioMuHLTEC");
  TF1 *ratioTauHLTBL      = (TF1*)corrections.Get("ratioTauHLTBL");  
  TF1 *ratioTauHLTEC      = (TF1*)corrections.Get("ratioTauHLTEC");  

  typedef ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> > LV;

  std::vector<std::string> samples;
  std::vector<float> crossSec;

  // samples & x-sections & skim1 
  samples.push_back("Data");        crossSec.push_back(     0  );                          
  samples.push_back("DYJets");      crossSec.push_back(  3048.0     * 0.00963); 
  samples.push_back("TTJets");      crossSec.push_back(   157.5     * 0.0210);  
  samples.push_back("WJets");       crossSec.push_back( 31314.0     * 0.00126);   
  samples.push_back("VBFH130");     crossSec.push_back(     0.0632  * 0.066);   
  samples.push_back("GGFH130");     crossSec.push_back(     0.774   * 0.055);  
  samples.push_back("QCD");         crossSec.push_back(   641              );
 
  // normalization Lumi
  Float_t Lumi= 100;

  string currentSample = samples[index];
  TString sample(currentSample.c_str());

  TString outName = "treeSkimmedMuTau_"+sample+".root";
  TFile *outFile = new TFile(outName,"UPDATE");

  TTree* outTreePtOrd     = new TTree("outTreePtOrd","tree");

  // kinematical variables of leading and trailing jet (ordered by pt)
  // pt, eta, |eta1-eta2|, mass of the di-jet system, azimuthal angle, phi1-phi2  
  float pt1,pt2,eta1,eta2,Deta,Mjj,Dphi,phi1,phi2;
  // number of jets above 30 or 20 GeV
  int nJets30, nJets20;

  // pt, eta and phi of the third veto
  float ptVeto, etaVeto, phiVeto; 
  // bool saying if the third jet lies within the leading and trailing jets
  int isVetoInJets;

  // diTau related variables
  // full mass of the di-tau
  float diTauSVFitMass;
  // visible mass, pt , eta and phi of the di-tau
  float diTauVisMass,diTauVisPt,diTauVisEta,diTauVisPhi;

  // taus/MET related variables
  // pt and eta of the muon (1) and tau (2)
  float ptL1,ptL2,etaL1,etaL2,phiL1,phiL2,dPhiL1L2;
  //  As in the input TTree..
  float diTauCharge_;
  //  As in the input TTree..
  float MtLeg1_;
  // MET pt
  float MEt;
  // relative isolation variable: w/o and w/ pile-up correction
  float combRelIsoLeg1DBeta;
  //  As in the input TTree..
  int tightestHPSDBWP_, decayMode_;
  float visibleTauMass_;

  // event-related variables
  // numnber of reconstructed vertices
  float numPV_ ;
  // weight to normalize the sample to 100pb-1
  float sampleWeight;
  // pile-up reweighting 
  float puWeight;
  // Higgs boson pt spectrum reweighting
  float HqTWeight;

  // object-related weights and triggers
  // trigger bit: 1=FIRED ; 0=NOT FIRED
  float HLTx;
  // trigger matching: 1=MATCHED; 0=UNMATCHED
  float HLTmatch;
  // Trigger turn-on correction
  float HLTweightTau, HLTweightMu;
  // Muon and tau isolation(X)identification data/MC scale factor
  float SFMu, SFTau;
  // As in the input TTree..
  int muFlag_;
  // As in the input TTree..
  int genDecay_;

  // As in the input TTree..
  ULong64_t event_,run_,lumi_;

  outTreePtOrd->Branch("pt1",  &pt1,"pt1/F");
  outTreePtOrd->Branch("pt2",  &pt2,"pt2/F");
  outTreePtOrd->Branch("eta1", &eta1,"eta1/F");
  outTreePtOrd->Branch("eta2", &eta2,"eta2/F");
  outTreePtOrd->Branch("phi1", &phi1,"phi1/F");
  outTreePtOrd->Branch("phi2", &phi2,"phi2/F");
  outTreePtOrd->Branch("Deta", &Deta,"Deta/F");
  outTreePtOrd->Branch("Dphi", &Dphi,"Dphi/F");
  outTreePtOrd->Branch("Mjj",  &Mjj,"Mjj/F");

  outTreePtOrd->Branch("nJets30",       &nJets30,  "nJets30/I");  
  outTreePtOrd->Branch("nJets20",       &nJets20,  "nJets20/I");  

  outTreePtOrd->Branch("ptVeto",  &ptVeto, "ptVeto/F");
  outTreePtOrd->Branch("phiVeto", &phiVeto,"phiVeto/F");
  outTreePtOrd->Branch("etaVeto", &etaVeto,"etaVeto/F");
  outTreePtOrd->Branch("isVetoInJets", &isVetoInJets,"isVetoInJets/I");
 
  outTreePtOrd->Branch("diTauSVFitMass",&diTauSVFitMass,"diTauSVFitMass/F");
  
  outTreePtOrd->Branch("diTauVisMass",&diTauVisMass,"diTauVisMass/F");
  outTreePtOrd->Branch("diTauVisPt",  &diTauVisPt,"diTauVisPt/F");
  outTreePtOrd->Branch("diTauVisEta", &diTauVisEta,"diTauVisEta/F");
  outTreePtOrd->Branch("diTauVisPhi", &diTauVisPhi,"diTauVisPhi/F");

  outTreePtOrd->Branch("etaL1",   &etaL1,"etaL1/F");
  outTreePtOrd->Branch("etaL2",   &etaL2,"etaL2/F");
  outTreePtOrd->Branch("ptL1",    &ptL1,"ptL1/F");
  outTreePtOrd->Branch("ptL2",    &ptL2,"ptL2/F");
  outTreePtOrd->Branch("phiL1",   &phiL1,"phiL1/F");
  outTreePtOrd->Branch("phiL2",   &phiL2,"phiL2/F");
  outTreePtOrd->Branch("dPhiL1L2",&dPhiL1L2,"dPhiL1L2/F");

  outTreePtOrd->Branch("diTauCharge", &diTauCharge_,"diTauCharge/F");
  outTreePtOrd->Branch("MtLeg1",      &MtLeg1_,"MtLeg1/F");
  outTreePtOrd->Branch("MEt",         &MEt,"MEt/F");

  outTreePtOrd->Branch("combRelIsoLeg1DBeta",&combRelIsoLeg1DBeta,"combRelIsoLeg1DBeta/F");

  outTreePtOrd->Branch("tightestHPSDBWP",  &tightestHPSDBWP_,"tightestHPSDBWP/I");
  outTreePtOrd->Branch("decayMode",        &decayMode_,"decayMode/I");
  outTreePtOrd->Branch("visibleTauMass",&visibleTauMass_,"visibleTauMass/F");

  outTreePtOrd->Branch("numPV",              &numPV_,"numPV/F");
  outTreePtOrd->Branch("sampleWeight",       &sampleWeight,"sampleWeight/F"); 
  outTreePtOrd->Branch("puWeight",           &puWeight,"puWeight/F");
  outTreePtOrd->Branch("HqTWeight",          &HqTWeight,"HqTWeight/F");

  outTreePtOrd->Branch("HLTx",         &HLTx, "HLTx/F");
  outTreePtOrd->Branch("HLTmatch",     &HLTmatch,"HLTmatch/F");
  outTreePtOrd->Branch("HLTweightMu",  &HLTweightMu,"HLTweightMu/F");
  outTreePtOrd->Branch("HLTweightTau", &HLTweightTau,"HLTweightTau/F");
  outTreePtOrd->Branch("SFTau",        &SFTau,"SFTau/F");
  outTreePtOrd->Branch("SFMu",         &SFMu,"SFMu/F");

  outTreePtOrd->Branch("muFlag",          &muFlag_,"muFlag/I"); 
  outTreePtOrd->Branch("genDecay",        &genDecay_,"genDecay/I");

  outTreePtOrd->Branch("event",&event_,"event/l");
  outTreePtOrd->Branch("run",  &run_,  "run/l");
  outTreePtOrd->Branch("lumi", &lumi_, "lumi/l");
 
  string currentInName = "./treeMuTau_"+samples[index]+".root" ;

  TString inName(currentInName.c_str());
  TFile* file   = new TFile(inName,"READ");
  if(file->IsZombie()){
    cout << "No such file!" << endl;
    return;
  }

  TString treeName("muTauAnalyzer/tree");

  TTree* currentTree = (TTree*)file->Get(treeName);
  int nEntries    = currentTree->GetEntries() ;
  int nEventsRead = ((TH1F*)file->Get("allEventsFilter/totalEvents"))->GetBinContent(1) ;
  float crossSection = crossSec[index] ; 
  float scaleFactor = (crossSection != 0) ? Lumi / (  float(nEventsRead)/crossSection )  : 1.0;

  cout << "Processing sample " << sample.Data() << endl;
  cout<< "nEventsRead = " << nEventsRead << endl;
  cout<< "nEntries    = " << nEntries << endl;
  cout<< "crossSection " << crossSection << " pb ==> scaleFactor " << scaleFactor << endl;

  // jets
  currentTree->SetBranchStatus("jetsIDP4"              ,1);
  currentTree->SetBranchStatus("genJetsIDP4"           ,0);

  // diTaus
  currentTree->SetBranchStatus("diTauVisP4"            ,1);
  currentTree->SetBranchStatus("diTauSVfitP4"          ,1);
  currentTree->SetBranchStatus("diTauCharge"           ,1);

  // taus
  currentTree->SetBranchStatus("diTauLegsP4"           ,1);
  currentTree->SetBranchStatus("genDiTauLegsP4"        ,1);
  currentTree->SetBranchStatus("chIsoLeg1v2"           ,1);
  currentTree->SetBranchStatus("nhIsoLeg1v2"           ,1);
  currentTree->SetBranchStatus("phIsoLeg1v2"           ,1);
  currentTree->SetBranchStatus("nhIsoPULeg1v2"         ,1);
  currentTree->SetBranchStatus("decayMode"             ,1);
  currentTree->SetBranchStatus("tightestHPSDBWP"       ,1);
  currentTree->SetBranchStatus("visibleTauMass"        ,1);
  currentTree->SetBranchStatus("isTauLegMatched"       ,0);
  currentTree->SetBranchStatus("isMuLegMatched"        ,0);
  currentTree->SetBranchStatus("signalPFChargedHadrCands"    ,1);
  currentTree->SetBranchStatus("signalPFGammaCands"    ,1);

  // MET
  currentTree->SetBranchStatus("METP4"                 ,1);
  currentTree->SetBranchStatus("genMETP4"              ,1);
  currentTree->SetBranchStatus("MtLeg1"                ,1);

  // generator-level boson
  currentTree->SetBranchStatus("genVP4"                ,1);
  currentTree->SetBranchStatus("genDecay"              ,1);

  // extra-muons
  currentTree->SetBranchStatus("muFlag"                ,1);

  // event-dependent variables
  currentTree->SetBranchStatus("numPV"                 ,1);
  currentTree->SetBranchStatus("nPUVertices"           ,1);
  currentTree->SetBranchStatus("numOfLooseIsoDiTaus"   ,0);
  currentTree->SetBranchStatus("run"                   ,1);
  currentTree->SetBranchStatus("event"                 ,1);
  currentTree->SetBranchStatus("lumi"                  ,1);

  // triggers
  currentTree->SetBranchStatus("tauXTriggers"          ,1);
  currentTree->SetBranchStatus("triggerBits"           ,1);

  ////////////////////////////////////////////////////////////////////

  std::vector< LV >* jets           = new std::vector< LV >();
  currentTree->SetBranchAddress("jetsIDP4",          &jets);

  std::vector< LV >* diTauLegsP4    = new std::vector< LV >();
  currentTree->SetBranchAddress("diTauLegsP4",     &diTauLegsP4);

  std::vector< LV >* diTauVisP4     = new std::vector< LV >();
  currentTree->SetBranchAddress("diTauVisP4",      &diTauVisP4);

  std::vector< LV >* diTauSVfitP4     = new std::vector< LV >();
  currentTree->SetBranchAddress("diTauSVfitP4",    &diTauSVfitP4);

  std::vector< LV >* genDiTauLegsP4 = new std::vector< LV >();
  currentTree->SetBranchAddress("genDiTauLegsP4",    &genDiTauLegsP4);

  std::vector< LV >* genVP4         = new std::vector< LV >();
  currentTree->SetBranchAddress("genVP4",          &genVP4);

  std::vector< LV >* METP4          = new std::vector< LV >();
  currentTree->SetBranchAddress("METP4",           &METP4);

  std::vector< LV >* genMETP4          = new std::vector< LV >();
  currentTree->SetBranchAddress("genMETP4",        &genMETP4);

  std::vector< int >* tauXTriggers  = new std::vector< int >();
  currentTree->SetBranchAddress("tauXTriggers",    &tauXTriggers);
  std::vector< int >* triggerBits   = new std::vector< int >();
  currentTree->SetBranchAddress("triggerBits",     &triggerBits);

  // auxiliary float to store branch values
  float diTauCharge;
  int tightestHPSDBWP, decayMode;
  float numPV;
  int signalPFChargedHadrCands, signalPFGammaCands;
  int muFlag,genDecay, nPUVertices;
  float visibleTauMass;
  float chIsoLeg1,nhIsoLeg1,phIsoLeg1; 
  float nhIsoPULeg1; 
  ULong64_t event,run,lumi;

  currentTree->SetBranchAddress("chIsoLeg1v2",          &chIsoLeg1);
  currentTree->SetBranchAddress("nhIsoLeg1v2",          &nhIsoLeg1);
  currentTree->SetBranchAddress("phIsoLeg1v2",          &phIsoLeg1);
  currentTree->SetBranchAddress("nhIsoPULeg1v2",        &nhIsoPULeg1);
  currentTree->SetBranchAddress("tightestHPSDBWP",      &tightestHPSDBWP);
  currentTree->SetBranchAddress("diTauCharge",          &diTauCharge);
  currentTree->SetBranchAddress("numPV",                &numPV);
  currentTree->SetBranchAddress("event",                &event);
  currentTree->SetBranchAddress("run",                  &run);
  currentTree->SetBranchAddress("lumi",                 &lumi);
  currentTree->SetBranchAddress("nPUVertices",          &nPUVertices);
  currentTree->SetBranchAddress("genDecay",             &genDecay);
  currentTree->SetBranchAddress("decayMode",            &decayMode);
  currentTree->SetBranchAddress("muFlag",               &muFlag);
  currentTree->SetBranchAddress("visibleTauMass",       &visibleTauMass);
  currentTree->SetBranchAddress("signalPFChargedHadrCands"    ,&signalPFChargedHadrCands);
  currentTree->SetBranchAddress("signalPFGammaCands"   ,&signalPFGammaCands);

  TFile* HqT      = 0;
  int mH          = 130;
  TH1F* histo     = 0;
  if(samples[index].find("GGFH130")!=string::npos){
    mH = 130;
    cout << "Reweighting powheg with HqT mH=" << mH << endl;
    HqT = new TFile(Form("../data/weight_ptH_%d.root", mH));
    if(!HqT) cout << "Cannot find HqT file..." << endl;
    else{
      histo = (TH1F*)(HqT->Get(Form("powheg_weight/weight_hqt_fehipro_fit_%d",mH)));
    }
  }


  for (int n = 0; n < nEntries ; n++) {
    
    currentTree->GetEntry(n);
    if(n%500==0) cout << n << endl;
    
    // initialize variables filled only in the two jet case
    pt1=-99;pt2=-99;eta1=-99,eta2=-99;Deta=-99;Dphi=-99;Mjj=-99;phi1=-99;phi2=-99;
    ptVeto = -99; phiVeto= -99; etaVeto= -99;isVetoInJets=-99;

    // define the relevant jet collection 
    nJets30        = 0;
    int lead  = -99;
    int trail = -99;
    int veto  = -99;
    vector<int> indexes;
    for(int l = 0 ; l < jets->size() ; l++){
      if((*jets)[l].Pt()>MINPt1 && TMath::Abs((*jets)[l].Eta())<MAXEta)
	indexes.push_back(l);
    }
    nJets20 = indexes.size();
    if(indexes.size()>0) lead  = indexes[0];  
    if(indexes.size()>1) trail = indexes[1];  
    if(indexes.size()>2) veto  = indexes[2];  

    for(int v = 0 ; v < indexes.size() ; v++){
      if( (*jets)[indexes[v]].Pt() > 30 ) nJets30++;
    }

    // first jet
    if(lead>=0){

      pt1  = (*jets)[lead].Pt();
      eta1 = (*jets)[lead].Eta();
      phi1 = (*jets)[lead].Phi();

      // second jet
      if(trail>=0){
	pt2  = (*jets)[trail].Pt();
	eta2 = (*jets)[trail].Eta();
	phi2 = (*jets)[trail].Phi();
	Deta = abs(eta1-eta2);
	Dphi = abs((*jets)[lead].Phi()-(*jets)[trail].Phi()) > TMath::Pi() ? 
	  -abs( (*jets)[lead].Phi()-(*jets)[trail].Phi() ) + 2*TMath::Pi()  :
	  abs( (*jets)[lead].Phi()-(*jets)[trail].Phi() ) ;
	Mjj  = ((*jets)[lead]+(*jets)[trail]).M();
      }
    }

    

    ptVeto  = (veto>=0) ? (*jets)[veto].Pt() : -99;
    etaVeto = (veto>=0) ? (*jets)[veto].Eta(): -99;
    phiVeto = (veto>=0) ? (*jets)[veto].Phi(): -99;
 
    isVetoInJets = 0;
    for(int l = 0 ; l < indexes.size() ; l++){
      if(lead>=0 && trail>=0 && (l!= lead && l!= trail) &&
	 (*jets)[indexes[l]].Pt()>PtVETO && ((*jets)[indexes[l]].Eta() - eta1)*((*jets)[indexes[l]].Eta() - eta2)<=0 )
	isVetoInJets = 1;
    }

    diTauSVFitMass = (*diTauSVfitP4)[0].M();
    diTauVisMass   = (*diTauVisP4)[0].M();
    diTauVisPt     = (*diTauVisP4)[0].Pt();
    diTauVisEta    = (*diTauVisP4)[0].Eta();
    diTauVisPhi    = (*diTauVisP4)[0].Phi();
    
    ptL1     = (*diTauLegsP4)[0].Pt();
    ptL2     = (*diTauLegsP4)[1].Pt();
    etaL1    = (*diTauLegsP4)[0].Eta();
    etaL2    = (*diTauLegsP4)[1].Eta();
    phiL1    = (*diTauLegsP4)[0].Phi();
    phiL2    = (*diTauLegsP4)[1].Phi();
    dPhiL1L2 =  abs((*diTauLegsP4)[0].Phi()-(*diTauLegsP4)[1].Phi()) > TMath::Pi() ? 
      -abs( (*diTauLegsP4)[0].Phi()-(*diTauLegsP4)[1].Phi() ) + 2*TMath::Pi()  :
      abs( (*diTauLegsP4)[0].Phi()-(*diTauLegsP4)[1].Phi() ) ;

    diTauCharge_    = diTauCharge;
    
    

    ////////////////////////////////////////////////////////////////////

    float scalarSumPt     = ( *diTauLegsP4)[0].Pt() + (*METP4)[0].Pt();
    float vectorSumPt     = ((*diTauLegsP4)[0] +      (*METP4)[0]).Pt() ;

    MtLeg1_     = TMath::Sqrt( scalarSumPt*scalarSumPt - vectorSumPt*vectorSumPt ) ;
    MEt     = (*METP4)[0].Et();
    combRelIsoLeg1DBeta    = (chIsoLeg1+ std::max( nhIsoLeg1+phIsoLeg1-0.5*(nhIsoPULeg1),double(0.0)))/(*diTauLegsP4)[0].Pt();

    tightestHPSDBWP_ = tightestHPSDBWP;
    visibleTauMass_  = visibleTauMass;
    decayMode_       = decayMode;
    numPV_           = numPV;
    sampleWeight     = scaleFactor; 
    puWeight         = (std::string(sample.Data())).find("Data")!=string::npos ? 1.0 : pileupWeight(nPUVertices);   

    HqTWeight = histo!=0 ? histo->GetBinContent( histo->FindBin( (*genVP4)[0].Pt() ) ) : 1.0;

    if((std::string(sample.Data())).find("Data")!=string::npos){
      
      HLTx =  float((*triggerBits)[0]);  //HLT_IsoMu15_LooseIsoPFTau15_v8
      bool isTriggMatched = (*tauXTriggers)[0] && (*tauXTriggers)[1] ; //hltSingleMuIsoL3IsoFiltered15 && hltOverlapFilterIsoMu15IsoPFTau15
      HLTmatch = isTriggMatched ? 1.0 : 0.0;
      HLTweightTau = 1.0;
      HLTweightMu  = 1.0;
      SFTau        = 1.0;
      SFMu         = 1.0;
      
    } 
    else{

      HLTx  =  float((*triggerBits)[0]); //HLT_IsoMu15_LooseIsoPFTau15_v9
      bool isTriggMatched = (*tauXTriggers)[0] && (*tauXTriggers)[1] ; //hltSingleMuIsoL3IsoFiltered15 && hltOverlapFilterIsoMu15IsoPFTau15
      HLTmatch = isTriggMatched ? 1.0 : 0.0;

      HLTweightTau  = TMath::Abs((*diTauLegsP4)[1].Eta())<1.5 ?  
	ratioTauHLTBL->Eval( (*diTauLegsP4)[1].Pt() ) : ratioTauHLTEC->Eval( (*diTauLegsP4)[1].Pt() );
      HLTweightMu  = TMath::Abs((*diTauLegsP4)[0].Eta())<1.5 ?  
	ratioMuHLTBL->Eval( (*diTauLegsP4)[0].Pt() ) : ratioMuHLTEC->Eval( (*diTauLegsP4)[0].Pt() );
      SFTau  = 1.0;
      SFMu   =  TMath::Abs((*diTauLegsP4)[0].Eta())<1.5 ?
	ratioMuIDIsoBL->Eval( (*diTauLegsP4)[0].Pt() ): 
	ratioMuIDIsoEC->Eval( (*diTauLegsP4)[0].Pt() );
      
    }
   
    muFlag_          = muFlag;
    genDecay_        = genDecay ;
    event_           = event;
    run_             = run;
    lumi_            = lumi;
    
    outTreePtOrd->Fill();
  }


  file->Close();
  
  if(SAVE) outFile->Write();
  outFile->Close();

  delete jets; delete diTauLegsP4; delete diTauVisP4; delete diTauSVfitP4; delete genDiTauLegsP4;
  delete tauXTriggers; delete triggerBits;
  delete METP4; delete genVP4; delete genMETP4;
  delete HqT;
  
  return;

}
コード例 #11
0
void 
HTT_MM_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., const char* inputfile="root/$HISTFILE", const char* directory="mumu_$CATEGORY")
{
  // define common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  // determine category tag
  const char* category_extra = "";
  if(std::string(directory) == std::string("mumu_0jet_low"  )){ category_extra = "0 jet, low p_{T}";  }
  if(std::string(directory) == std::string("mumu_0jet_high" )){ category_extra = "0 jet, high p_{T}"; }
  if(std::string(directory) == std::string("mumu_boost_low" )){ category_extra = "1 jet, low p_{T}";  }
  if(std::string(directory) == std::string("mumu_boost_high")){ category_extra = "1 jet, high p_{T}"; }
  if(std::string(directory) == std::string("mumu_vbf"       )){ category_extra = "2 jet (VBF)";       }
  if(std::string(directory) == std::string("mumu_nobtag"    )){ category_extra = "No B-Tag";          }
  if(std::string(directory) == std::string("mumu_btag"      )){ category_extra = "B-Tag";             }

  const char* dataset;
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 4.9 fb^{-1} at 7 TeV";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 18.7 fb^{-1} at 8 TeV";}
#ifdef MSSM
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 12.1 fb^{-1} at 8 TeV";}
#endif
 
  TFile* input = new TFile(inputfile);
  TH1F* ZTT = refill((TH1F*)input->Get(TString::Format("%s/ZTT"   , directory)), "ZTT"); InitHist(ZTT, "", "", kOrange-4, 1001);
  TH1F* ZMM    = refill((TH1F*)input->Get(TString::Format("%s/ZMM"     , directory)), "ZMM"); InitHist(ZMM  , "", "", kAzure+2, 1001);
  TH1F* TTJ  = refill((TH1F*)input->Get(TString::Format("%s/TTJ"   , directory)), "TTJ"); InitHist(TTJ, "", "", kBlue-8, 1001);
  TH1F* QCD    = refill((TH1F*)input->Get(TString::Format("%s/QCD"     , directory)), "QCD"); InitHist(QCD  , "", "", kMagenta - 10, 1001);
  TH1F* Dibosons  = refill((TH1F*)input->Get(TString::Format("%s/Dibosons"   , directory)), "Dibosons"); InitHist(Dibosons, "", "", kGreen - 4, 1001);
  TH1F* WJets    = refill((TH1F*)input->Get(TString::Format("%s/WJets"     , directory)), "WJets"); InitHist(WJets  , "", "", kRed + 2, 1001);
#ifdef MSSM
  float ggHScale = 1., bbHScale = 1.;
  ggHScale = ($MSSM_SIGNAL_ggH_xseff_A + $MSSM_SIGNAL_ggH_xseff_hH);
  bbHScale = ($MSSM_SIGNAL_bbH_xseff_A + $MSSM_SIGNAL_bbH_xseff_hH);
 //  float ggHScale = 1., bbHScale = 1.; // scenario for MSSM, mhmax, mA=160, tanb=20, A + H for the time being
//   if(std::string(inputfile).find("7TeV")!=std::string::npos){ ggHScale = (9157.49*0.119 + 10180.7*0.120)/1000.; 
//                                                               bbHScale = (23314.3*0.119 + 21999.3*0.120)/1000.; }
//   if(std::string(inputfile).find("8TeV")!=std::string::npos){ ggHScale = (11815.3*0.119 + 13124.9*0.120)/1000.; 
//                                                               bbHScale = (31087.9*0.119 + 29317.8*0.120)/1000.; }
 //  float ggHScale = 1., bbHScale = 1.; // scenario for MSSM, mhmax, mA=160, tanb=10, A + H for the time being
//   if(std::string(inputfile).find("7TeV")!=std::string::npos){ ggHScale = (2111.4*0.11 + 4022.9*0.11)/1000.;
//                                                               bbHScale = (6211.6*0.11 + 5147.0*0.11)/1000.; }
//   if(std::string(inputfile).find("8TeV")!=std::string::npos){ ggHScale = (2729.9*0.11 + 5193.2*0.11)/1000.;
//                                                               bbHScale = (8282.7*0.11 + 6867.8*0.11)/1000.; }
  TH1F* ggH    = refill((TH1F*)input->Get(TString::Format("%s/ggH160"  , directory)), "ggH"  ); InitSignal(ggH); ggH->Scale(ggHScale);
  TH1F* bbH    = refill((TH1F*)input->Get(TString::Format("%s/bbH160"  , directory)), "bbH"  ); InitSignal(bbH); bbH->Scale(bbHScale);
#else
#ifndef DROP_SIGNAL
  TH1F* ggH    = refill((TH1F*)input->Get(TString::Format("%s/ggH125"  , directory)), "ggH"  ); InitSignal(ggH); ggH->Scale(SIGNAL_SCALE);
  TH1F* qqH    = refill((TH1F*)input->Get(TString::Format("%s/qqH125"  , directory)), "qqH"  ); InitSignal(qqH); qqH->Scale(SIGNAL_SCALE);
  TH1F* VH     = refill((TH1F*)input->Get(TString::Format("%s/VH125"   , directory)), "VH"   ); InitSignal(VH ); VH ->Scale(SIGNAL_SCALE);
#endif
#endif
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
  InitHist(data, "#bf{m_{#tau#tau} [GeV]}", "#bf{dN/dm_{#tau#tau} [1/GeV]}"); InitData(data);

  TH1F* ref=(TH1F*)ZTT->Clone("ref");
  ref->Add(ZMM  );
  ref->Add(TTJ);
  ref->Add(QCD  );
  ref->Add(Dibosons);
  ref->Add(WJets  );

  double unscaled[9];
  unscaled[0] = ZTT->Integral();
  unscaled[1] = ZMM  ->Integral();
  unscaled[2] = TTJ->Integral();
  unscaled[3] = QCD  ->Integral();
  unscaled[4] = Dibosons  ->Integral();
  unscaled[5] = WJets  ->Integral();
#ifdef MSSM
  unscaled[6] = ggH  ->Integral();
  unscaled[7] = bbH  ->Integral();
  unscaled[8] = 0;
#else
#ifndef DROP_SIGNAL
  unscaled[6] = ggH  ->Integral();
  unscaled[7] = qqH  ->Integral();
  unscaled[8] = VH   ->Integral();
#endif
#endif
  
  if(scaled){
    rescale(ZTT, 1); 
    rescale(ZMM,   2); 
    rescale(TTJ, 3); 
    rescale(QCD,   4); 
    rescale(Dibosons, 5); 
    rescale(WJets,   6);
#ifdef MSSM 
    rescale(ggH,   7);
    rescale(bbH,   8);
#else
#ifndef DROP_SIGNAL
    rescale(ggH,   7);
    rescale(qqH,   8);
    rescale(VH,   9);
#endif
#endif
  }

  TH1F* scales[9];
  scales[0] = new TH1F("scales-ZTT", "", 9, 0, 9);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (ZTT->Integral()/unscaled[0]-1.) : 0.);
  scales[1] = new TH1F("scales-ZMM"  , "", 9, 0, 9);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? (ZMM  ->Integral()/unscaled[1]-1.) : 0.);
  scales[2] = new TH1F("scales-TTJ", "", 9, 0, 9);
  scales[2]->SetBinContent(3, unscaled[2]>0 ? (TTJ->Integral()/unscaled[2]-1.) : 0.);
  scales[3] = new TH1F("scales-QCD"  , "", 9, 0, 9);
  scales[3]->SetBinContent(4, unscaled[3]>0 ? (QCD  ->Integral()/unscaled[3]-1.) : 0.);
  scales[4] = new TH1F("scales-Dibosons", "", 9, 0, 9);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (Dibosons->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-WJets"  , "", 9, 0, 9);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (WJets  ->Integral()/unscaled[5]-1.) : 0.);
#ifdef MSSM
  scales[6] = new TH1F("scales-ggH"  , "", 9, 0, 9);
  scales[6]->SetBinContent(7, unscaled[6]>0 ? (ggH  ->Integral()/unscaled[4]-1.) : 0.);
  scales[7] = new TH1F("scales-bbH"  , "", 9, 0, 9);
  scales[7]->SetBinContent(8, unscaled[7]>0 ? (bbH  ->Integral()/unscaled[5]-1.) : 0.);
  scales[8] = new TH1F("scales-NONE" , "", 9, 0, 9);
  scales[8]->SetBinContent(9, 0.);
#else
#ifndef DROP_SIGNAL
  scales[6] = new TH1F("scales-ggH"  , "", 9, 0, 9);
  scales[6]->SetBinContent(7, unscaled[6]>0 ? (ggH  ->Integral()/unscaled[4]-1.) : 0.);
  scales[7] = new TH1F("scales-qqH"  , "", 9, 0, 9);
  scales[7]->SetBinContent(8, unscaled[7]>0 ? (qqH  ->Integral()/unscaled[5]-1.) : 0.);
  scales[8] = new TH1F("scales-VH"   , "", 9, 0, 9);
  scales[8]->SetBinContent(9, unscaled[8]>0 ? (VH   ->Integral()/unscaled[6]-1.) : 0.);
#endif
#endif

  ZMM->Add(ZTT);
  QCD->Add(ZMM);
  TTJ->Add(QCD);
  Dibosons->Add(TTJ);
  WJets->Add(Dibosons);
  if(log){
#ifdef MSSM
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }
  else{
#ifdef MSSM
    bbH  ->Add(WJets);
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
    VH   ->Add(WJets);
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }


  /*
    mass plot before and after fit
  */
  TCanvas* canv = MakeCanvas("canv", "histograms", 600, 600);
  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(0, data->FindBin(350)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(1000)); };
#else
  data->GetXaxis()->SetRange(0, data->FindBin(350));
#endif
  data->SetNdivisions(505);
  data->SetMinimum(min);
  data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(WJets, log)));
  data->Draw("e");

  TH1F* errorBand = (TH1F*)WJets ->Clone();
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(1);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
    if(errorBand->GetBinContent(idx)>0){
      std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
      break;
    }
  }
  if(log){
    WJets->Draw("histsame");
    //Dibosons->Draw("histsame");
    TTJ->Draw("histsame");
    QCD->Draw("histsame");
    ZMM->Draw("histsame");
    ZTT->Draw("histsame");
    $DRAW_ERROR
#ifndef DROP_SIGNAL
    ggH->Draw("histsame");
#endif

  }
  else{
#ifndef DROP_SIGNAL
    ggH  ->Draw("histsame");
#endif
    WJets->Draw("histsame");
    //Dibosons->Draw("histsame");
    TTJ->Draw("histsame");
    QCD->Draw("histsame");
    ZMM->Draw("histsame");
    ZTT->Draw("histsame");
    $DRAW_ERROR
  }
  data->Draw("esame");
  canv->RedrawAxis();

  //CMSPrelim(dataset, "#tau_{#mu}#tau_{#mu}", 0.17, 0.835);
  CMSPrelim(dataset, "", 0.16, 0.835);  
  TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "NDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText("#mu#mu");
  chan->Draw();

  TPaveText* cat      = new TPaveText(0.20, 0.68+0.061, 0.32, 0.68+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();

#ifdef MSSM
  TPaveText* massA      = new TPaveText(0.75, 0.48+0.061, 0.85, 0.48+0.161, "NDC");
  massA->SetBorderSize(   0 );
  massA->SetFillStyle(    0 );
  massA->SetTextAlign(   12 );
  massA->SetTextSize ( 0.03 );
  massA->SetTextColor(    1 );
  massA->SetTextFont (   62 );
  massA->AddText("m_{A}=160GeV");
  massA->Draw();

  TPaveText* tanb      = new TPaveText(0.75, 0.44+0.061, 0.85, 0.44+0.161, "NDC");
  tanb->SetBorderSize(   0 );
  tanb->SetFillStyle(    0 );
  tanb->SetTextAlign(   12 );
  tanb->SetTextSize ( 0.03 );
  tanb->SetTextColor(    1 );
  tanb->SetTextFont (   62 );
  tanb->AddText("tan#beta=20");
  tanb->Draw();

  TPaveText* scen      = new TPaveText(0.75, 0.40+0.061, 0.85, 0.40+0.161, "NDC");
  scen->SetBorderSize(   0 );
  scen->SetFillStyle(    0 );
  scen->SetTextAlign(   12 );
  scen->SetTextSize ( 0.03 );
  scen->SetTextColor(    1 );
  scen->SetTextFont (   62 );
  scen->AddText("mhmax");
  scen->Draw();
#endif

#ifdef MSSM  
  TLegend* leg = new TLegend(0.45, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(ggH  , "#phi#rightarrow#tau#tau" , "L" );
#else
  TLegend* leg = new TLegend(0.50, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
#ifndef DROP_SIGNAL
  if(SIGNAL_SCALE!=1){
    leg->AddEntry(ggH  , TString::Format("%.0f#timesH(125 GeV)#rightarrow#tau#tau", SIGNAL_SCALE) , "L" );
  }
  else{
    leg->AddEntry(ggH  , "H(125 GeV)#rightarrow#tau#tau" , "L" );
  }
#endif
#endif
  leg->AddEntry(data , "observed"                    , "LP");
  leg->AddEntry(ZTT  , "Z#rightarrow#tau#tau"        , "F" );
  leg->AddEntry(ZMM  , "Z#rightarrow#mu#mu"          , "F" );
  leg->AddEntry(TTJ  , "t#bar{t}"                    , "F" );
  leg->AddEntry(QCD  , "QCD"                         , "F" );
  //leg->AddEntry(Dibosons  , "Dibosons"             , "F" );
  leg->AddEntry(WJets, "electroweak"                 , "F" );
  $ERROR_LEGEND
  leg->Draw();

//#ifdef MSSM
//  TPaveText* mssm  = new TPaveText(0.69, 0.85, 0.90, 0.90, "NDC");
//  mssm->SetBorderSize(   0 );
//  mssm->SetFillStyle(    0 );
//  mssm->SetTextAlign(   12 );
//  mssm->SetTextSize ( 0.03 );
//  mssm->SetTextColor(    1 );
//  mssm->SetTextFont (   62 );
//  mssm->AddText("(m_{A}=120, tan#beta=10)");
//  mssm->Draw();
//#else
//  TPaveText* mssm  = new TPaveText(0.83, 0.85, 0.95, 0.90, "NDC");
//  mssm->SetBorderSize(   0 );
//  mssm->SetFillStyle(    0 );
//  mssm->SetTextAlign(   12 );
//  mssm->SetTextSize ( 0.03 );
//  mssm->SetTextColor(    1 );
//  mssm->SetTextFont (   62 );
//  mssm->AddText("m_{H}=125");
//  mssm->Draw();
//#endif

  /*
    Ratio Data over MC
  */
  TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
  canv0->SetGridx();
  canv0->SetGridy();
  canv0->cd();

  TH1F* zero = (TH1F*)ref ->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)data->Clone("rat"); 
  rat1->Divide(WJets);
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
    zero->SetBinContent(ibin+1, 0.);
  }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+0.5);
  rat1->SetMinimum(-0.5);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
  rat1->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}"); 
  rat1->Draw();
  zero->SetLineColor(kBlack);
  zero->Draw("same");
  canv0->RedrawAxis();

  /*
    Ratio After fit over Prefit
  */
  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  TH1F* rat2 = (TH1F*) WJets->Clone("rat2");
  rat2->Divide(ref);
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    if(rat2->GetBinContent(ibin+1)>0){
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
    }
  }
  rat2->SetLineColor(kRed+ 3);
  rat2->SetFillColor(kRed-10);
  rat2->SetMaximum(+0.3);
  rat2->SetMinimum(-0.3);
  rat2->GetYaxis()->SetTitle("#bf{Fit/Prefit-1}");
  rat2->GetYaxis()->CenterTitle();
  rat2->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  rat2->GetXaxis()->SetRange(0, 28);
  rat2->Draw();
  zero->SetLineColor(kBlack);
  zero->Draw("same");
  canv1->RedrawAxis();
  /*
    Relative shift per sample
  */
  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
  canv2->SetGridx();
  canv2->SetGridy();
  canv2->cd();

  InitHist  (scales[0], "", "", kGreen  - 4, 1001);
  InitHist  (scales[1], "", "", kYellow - 4, 1001);
  InitHist  (scales[2], "", "", kMagenta-10, 1001);
  InitHist  (scales[3], "", "", kRed    + 2, 1001);
  InitHist  (scales[4], "", "", kBlue   - 8, 1001);
  InitHist  (scales[5], "", "", kOrange - 4, 1001);  
#ifndef DROP_SIGNAL
  InitSignal(scales[6]);
  InitSignal(scales[7]);
  InitSignal(scales[8]);
#endif
  scales[0]->Draw();
  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{ZTT}");
  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{ZMM}"  );
  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{TTJ}");
  scales[0]->GetXaxis()->SetBinLabel(4, "#bf{QCD}"  );
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{Dibosons}");
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{WJets}"  );
#ifdef MSSM
  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(8, "#bf{bbH}"  );
  scales[0]->GetXaxis()->SetBinLabel(9, "#bf{NONE}" );
#else
  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(8, "#bf{qqH}"  );
  scales[0]->GetXaxis()->SetBinLabel(9, "#bf{VH}"   );
#endif
  scales[0]->SetMaximum(+1.5);
  scales[0]->SetMinimum(-1.5);
  scales[0]->GetYaxis()->CenterTitle();
  scales[0]->GetYaxis()->SetTitle("#bf{Fit/Prefit-1}");
  scales[1]->Draw("same");
  scales[2]->Draw("same");
  scales[3]->Draw("same");
  scales[4]->Draw("same");
  scales[5]->Draw("same");
#ifndef DROP_SIGNAL
  scales[6]->Draw("same");
  scales[7]->Draw("same");
  scales[8]->Draw("same");
#endif
  zero->Draw("same");
  canv2->RedrawAxis();

  /*
    prepare output
  */
 bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.png"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.pdf"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.eps"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));

  TFile* output = new TFile(TString::Format("%s_%sscaled_%s_%s.root", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""), "update");
  output->cd();
  data ->Write("data_obs");
  ZTT->Write("Ztt"   );
  ZMM->Write("Zmm"     );
  TTJ->Write("ttbar"   );
  QCD->Write("Fakes"     );
  Dibosons->Write("Dibosons"   );
  WJets->Write("EWK"     );
#ifdef MSSM
  ggH  ->Write("ggH"     );
  bbH  ->Write("bbH"     );
#else
#ifndef DROP_SIGNAL
  ggH  ->Write("ggH"     );
  qqH  ->Write("qqH"     );
  VH   ->Write("VH"      );
#endif
#endif
  if(errorBand){
    errorBand->Write("errorBand");
  }
  output->Close();
}
コード例 #12
0
ファイル: SMS.C プロジェクト: cmstas/ZMet2012
void SMS(char* sample = "wzsms" , bool print = false){

  //--------------------------------------------------
  // input parameters
  //--------------------------------------------------
  
  const float denom    = 100000;
  const float lumi     =   9200;
  const char* filename = Form("../../output/V00-01-05/%s_baby_oldIso.root",sample);

  cout << "Using file        " << filename << endl;
  cout << "Using denominator " << denom    << " events" << endl;
  cout << "Using lumi        " << lumi     << " pb-1" << endl;

  //--------------------------------------------------
  // set text stuff
  //--------------------------------------------------

  char* xtitle  = "m_{#chi_{2}^{0}} = m_{#chi_{1}^{#pm}} [GeV]";
  char* ytitle  = "m_{#chi_{1}^{0}} [GeV]";
  char* label   = "CMS Preliminary   #sqrt{s} = 8 TeV, #scale[0.6]{#int}Ldt = 9.2 fb^{-1}";
  char* process = "pp #rightarrow#chi_{2}^{0} #chi_{1}^{#pm} #rightarrow WZ+E_{T}^{miss}";

  //--------------------------------------------------
  // read in TChain
  //--------------------------------------------------

  TChain *ch = new TChain("T1");
  ch->Add(filename);

  //--------------------------------------------------
  // read in reference cross section
  //--------------------------------------------------

  TFile *xsecfile = TFile::Open("C1N2_8TeV_finer.root");
  TH1F* refxsec   = (TH1F*) xsecfile->Get("C1N2_8TeV_NLO");

  //--------------------------------------------------
  // preselection
  //--------------------------------------------------

  TCut pt2020("lep1.pt()>20.0 && lep2.pt()>20.0");
  TCut Zmass("dilmass>81 && dilmass<101");
  TCut sf = "leptype<2";
  TCut njets2("njets>=2");
  TCut bveto("nbcsvm==0");
  TCut nlep2("nlep==2");
  TCut mjj("mjj>70.0 && mjj<110.0");

  TCut presel;
  presel += pt2020;
  presel += Zmass;
  presel += sf;
  presel += njets2;
  presel += bveto;
  presel += mjj;
  presel += nlep2;

  TCut weight("vtxweight * trgeff");

  cout << "Using selection   " << presel.GetTitle() << endl;
  cout << "Using weight      " << weight.GetTitle() << endl;

  //--------------------------------------------------
  // signal regions
  //--------------------------------------------------

  vector<TCut>    sigcuts;
  vector<string>  signames;
  vector<string>  labels;
  vector<int>     cuts;

  TCut met60 ("pfmet > 60.0");
  TCut met80 ("pfmet > 80.0");
  TCut met100("pfmet > 100.0");
  TCut met120("pfmet > 120.0");
  TCut met140("pfmet > 140.0");
  TCut met160("pfmet > 160.0");
  TCut met180("pfmet > 180.0");
  TCut met200("pfmet > 200.0");

  // sigcuts.push_back(TCut(presel+met60));      signames.push_back("E_{T}^{miss} > 60 GeV");      labels.push_back("met60");  cuts.push_back(60);
  // sigcuts.push_back(TCut(presel+met80));      signames.push_back("E_{T}^{miss} > 80 GeV");      labels.push_back("met80");  cuts.push_back(80);
  // sigcuts.push_back(TCut(presel+met100));     signames.push_back("E_{T}^{miss} > 100 GeV");     labels.push_back("met100"); cuts.push_back(100);
  sigcuts.push_back(TCut(presel+met120));     signames.push_back("E_{T}^{miss} > 120 GeV");     labels.push_back("met120"); cuts.push_back(120);
  // sigcuts.push_back(TCut(presel+met140));     signames.push_back("E_{T}^{miss} > 140 GeV");     labels.push_back("met140"); cuts.push_back(140);
  // sigcuts.push_back(TCut(presel+met160));     signames.push_back("E_{T}^{miss} > 160 GeV");     labels.push_back("met160"); cuts.push_back(160);
  // sigcuts.push_back(TCut(presel+met180));     signames.push_back("E_{T}^{miss} > 180 GeV");     labels.push_back("met180"); cuts.push_back(180);
  // sigcuts.push_back(TCut(presel+met200));     signames.push_back("E_{T}^{miss} > 200 GeV");     labels.push_back("met200"); cuts.push_back(200);

  const unsigned int nsig = sigcuts.size();

  //--------------------------------------------------
  // make efficiency and xsec TH2's
  //--------------------------------------------------
  
  TH2F* heff[nsig];
  TH2F* heffup[nsig];
  TH2F* heffdn[nsig];
  TH2F* hxsec[nsig];
  TH2F* hxsec_exp[nsig];
  TH2F* hexcl[nsig];
  TH2F* hjes[nsig];
  
  TCanvas *ctemp = new TCanvas();
  ctemp->cd();

  for( unsigned int i = 0 ; i < nsig ; ++i ){

    TString jesup(sigcuts.at(i));
    jesup.ReplaceAll("njets","njetsup");
    jesup.ReplaceAll("pfmet","pfmetup");

    TString jesdn(sigcuts.at(i));
    jesdn.ReplaceAll("njets","njetsdn");
    jesdn.ReplaceAll("pfmet","pfmetdn");

    TCut jesupcut(jesup);
    TCut jesdncut(jesdn);

    cout << endl << endl;
    cout << "Signal region : " << labels.at(i)  << endl;
    cout << "Selection     : " << sigcuts.at(i) << endl;
    cout << "Selection up  : " << jesupcut      << endl;
    cout << "Selection dn  : " << jesdncut      << endl;

    int   nx   =  26;
    float xmin =  95;
    float xmax = 355;

    int   ny   =  36;
    float ymin =  -5;
    float ymax = 355;
    
    heff[i]      = new TH2F(Form("heff_%i",i)        , Form("heff_%i",i)       ,  nx , xmin , xmax , ny , ymin , ymax );
    heffup[i]    = new TH2F(Form("heffup_%i",i)      , Form("heffup_%i",i)     ,  nx , xmin , xmax , ny , ymin , ymax );
    heffdn[i]    = new TH2F(Form("heffdn_%i",i)      , Form("heffdn_%i",i)     ,  nx , xmin , xmax , ny , ymin , ymax );
    hxsec[i]     = new TH2F(Form("hxsec_%i",i)       , Form("hxsec_%i",i)      ,  nx , xmin , xmax , ny , ymin , ymax );
    hxsec_exp[i] = new TH2F(Form("hxsec_exp_%i",i)   , Form("hxsec_exp_%i",i)  ,  nx , xmin , xmax , ny , ymin , ymax );
    hexcl[i]     = new TH2F(Form("hexcl_%i",i)       , Form("hexcl_%i",i)      ,  nx , xmin , xmax , ny , ymin , ymax );
    hjes[i]      = new TH2F(Form("hjes_%i",i)        , Form("hjes_%i",i)       ,  nx , xmin , xmax , ny , ymin , ymax );

    ch->Draw(Form("ml:mg>>heff_%i",i),sigcuts.at(i)*weight);
    heff[i]->Scale(1.0/denom);

    // ch->Draw(Form("ml:mg>>heffup_%i",i),jesupcut*weight);
    // heffup[i]->Scale(1.0/denom);

    // ch->Draw(Form("ml:mg>>heffdn_%i",i),jesdncut*weight);
    // heffdn[i]->Scale(1.0/denom);

    for( unsigned int ibin = 1 ; ibin <= nx ; ibin++ ){
      for( unsigned int jbin = 1 ; jbin <= ny ; jbin++ ){

	float mg = heff[i]->GetXaxis()->GetBinCenter(ibin);
	float ml = heff[i]->GetYaxis()->GetBinCenter(jbin);

	float eff    = heff[i]->GetBinContent(ibin,jbin);
	// float effup  = heffup[i]->GetBinContent(ibin,jbin);
	// float effdn  = heffdn[i]->GetBinContent(ibin,jbin);

	if( eff   < 1e-20 ) continue;

	// float dup    = effup/eff-1;
	// float ddn    = 1-effdn/eff;
	// float djes   = 0.5 * (dup+ddn);
	// hjes[i]->SetBinContent(ibin,jbin,djes);

	// float toterr = sqrt( 0.04*0.04 + 0.05*0.05 + 0.05*0.05 + djes*djes );

	//float this_ul = getObservedLimit( cuts.at(i) , toterr );
	float this_ul = getObservedUpperLimit( cuts.at(i) );
	float xsecul  = this_ul / ( lumi * eff );

	//float this_ul_exp = getExpectedLimit( cuts.at(i) , toterr );
	float this_ul_exp = getExpectedUpperLimit( cuts.at(i) );
	float xsecul_exp  = this_ul_exp / ( lumi * eff );

	if( eff > 0 ){
	  hxsec[i]->SetBinContent(ibin,jbin, xsecul );
	  hxsec_exp[i]->SetBinContent(ibin,jbin, xsecul_exp );
	}

	int   bin = refxsec->FindBin(mg);
	float xsec = refxsec->GetBinContent(bin);

	hexcl[i]->SetBinContent(ibin,jbin,0);
	if( xsec > xsecul )   hexcl[i]->SetBinContent(ibin,jbin,1);
	//cout << "ibin jbin mg xsec " << ibin << " " << jbin << " " << mg << " " << xsec << endl;
      }
    }
  }

  delete ctemp;

  cout << endl << endl;

  //--------------------------------------------------
  // make pretty pictures
  //--------------------------------------------------
  
  TLatex *t = new TLatex();
  t->SetNDC();
  t->SetTextSize(0.04);

  TCanvas* can[nsig];

  for( unsigned int i = 0 ; i < nsig ; ++i ){
  
    //can[i] = new TCanvas(Form("can_%i",i),Form("can_%i",i),1200,600);
    //can[i]->Divide(2,1);
    //can[i] = new TCanvas(Form("can_%i",i),Form("can_%i",i),1800,600);
    //can[i]->Divide(3,1);
    can[i] = new TCanvas(Form("can_%i",i),Form("can_%i",i),1000,1000);
    can[i]->Divide(2,2);

    //-------------------------------
    // efficiency
    //-------------------------------

    can[i]->cd(1);
    gPad->SetTopMargin(0.1);
    gPad->SetRightMargin(0.2);
    heff[i]->GetXaxis()->SetLabelSize(0.035);
    heff[i]->Scale(1000);
    heff[i]->GetYaxis()->SetTitle(ytitle);
    heff[i]->GetXaxis()->SetTitle(xtitle);
    heff[i]->GetZaxis()->SetTitle("efficiency (10^{-3})");
    heff[i]->Draw("colz");

    
    t->DrawLatex(0.2 ,0.83,process);
    t->DrawLatex(0.2 ,0.71,signames.at(i).c_str());
    t->DrawLatex(0.18,0.92,label);

    //-------------------------------
    // cross section
    //-------------------------------
  
    can[i]->cd(2);
    gPad->SetTopMargin(0.1);
    gPad->SetRightMargin(0.2);
    gPad->SetLogz();
    hxsec[i]->GetXaxis()->SetLabelSize(0.035);
    hxsec[i]->GetYaxis()->SetTitle(ytitle);
    hxsec[i]->GetXaxis()->SetTitle(xtitle);
    hxsec[i]->GetXaxis()->SetRangeUser(95,305);
    hxsec[i]->GetYaxis()->SetRangeUser(-5,305);
    hxsec[i]->GetZaxis()->SetTitle("#sigma upper limit [pb]");
    hxsec[i]->Draw("colz");
    hxsec[i]->SetMinimum(0.01);
    hxsec[i]->SetMaximum(100);

    TGraph* gr2011 = getGraph_2011();
    TGraph* gr2012 = getGraph_2012();

    gr2011->Draw("same");
    gr2012->Draw("same");

    // TGraph* gr_excl      = getRefXsecGraph(hxsec[i], "T5zz", 1.0);
    // TGraph* gr_excl_down = getRefXsecGraph(hxsec[i], "T5zz", 1./3.);
    // TGraph* gr_excl_up   = getRefXsecGraph(hxsec[i], "T5zz", 3.);

    // gr_excl->SetLineWidth(2);
    // gr_excl_up->SetLineWidth(2);
    // gr_excl_down->SetLineWidth(2);
    // gr_excl_up->SetLineStyle(2);
    // gr_excl_down->SetLineStyle(3);
    // gr_excl->Draw("same");
    // gr_excl_up->Draw("same");
    // gr_excl_down->Draw("same");

    TLegend *leg = new TLegend(0.2,0.53,0.53,0.67);
    // leg->AddEntry(gr_excl,"#sigma^{prod} = #sigma^{NLO-QCD}","l");
    // leg->AddEntry(gr_excl_up,"#sigma^{prod} = 3 #times #sigma^{NLO-QCD}","l");
    // leg->AddEntry(gr_excl_down,"#sigma^{prod} = 1/3 #times #sigma^{NLO-QCD}","l");
    leg->AddEntry(gr2011,"2011 observed","l");
    leg->AddEntry(gr2012,"2012 expected","l");
    leg->SetFillColor(0);
    leg->SetBorderSize(0);
    leg->Draw();

    // t->DrawLatex(0.2,0.83,"pp #rightarrow #tilde{g}#tilde{g}, #tilde{g} #rightarrow 2j+#chi_{2}^{0}, #chi_{2}^{0} #rightarrow Z #chi_{1}^{0}");
    // t->DrawLatex(0.2,0.77,"m(#tilde{q}) >> m(#tilde{g})");
    // t->DrawLatex(0.2,0.71,signames.at(i).c_str());
    // t->DrawLatex(0.18,0.92,"CMS Preliminary            #sqrt{s} = 7 TeV, #scale[0.6]{#int}Ldt = 4.7 fb^{-1}");

    t->DrawLatex(0.2 ,0.83,process);
    t->DrawLatex(0.2 ,0.71,signames.at(i).c_str());
    t->DrawLatex(0.18,0.92,label);

    //-------------------------------
    // excluded points
    //-------------------------------

    can[i]->cd(3);
    gPad->SetGridx();
    gPad->SetGridy();
    gPad->SetRightMargin(0.2);
    gPad->SetTopMargin(0.1);
    hexcl[i]->GetXaxis()->SetRangeUser(150,250);
    hexcl[i]->GetYaxis()->SetRangeUser(-10,100);
    hexcl[i]->GetYaxis()->SetTitle("#chi^{0}_{1} mass (GeV)");
    hexcl[i]->GetXaxis()->SetTitle("gluino mass (GeV)");
    hexcl[i]->GetZaxis()->SetTitle("excluded points");
    hexcl[i]->Draw("colz");

    gr2012->Draw("same");
    gr2012->Draw("samep");

    //gr_excl->Draw("same");

    // t->DrawLatex(0.2,0.83,"pp #rightarrow #tilde{g}#tilde{g}, #tilde{g} #rightarrow 2j+#chi_{2}^{0}, #chi_{2}^{0} #rightarrow Z #chi_{1}^{0}");
    // t->DrawLatex(0.2,0.77,"m(#tilde{q}) >> m(#tilde{g})");
    // t->DrawLatex(0.2,0.71,signames.at(i).c_str());
    // t->DrawLatex(0.18,0.92,"CMS Preliminary            #sqrt{s} = 7 TeV, #scale[0.6]{#int}Ldt = 4.7 fb^{-1}");

    t->DrawLatex(0.2 ,0.83,process);
    t->DrawLatex(0.2 ,0.71,signames.at(i).c_str());
    t->DrawLatex(0.18,0.92,label);

    //-------------------------------
    // JES uncertainty
    //-------------------------------

    can[i]->cd(4);
    gPad->SetRightMargin(0.2);
    gPad->SetTopMargin(0.1);
    hjes[i]->GetYaxis()->SetTitle("#chi^{0}_{1} mass (GeV)");
    hjes[i]->GetXaxis()->SetTitle("gluino mass (GeV)");
    hjes[i]->GetZaxis()->SetTitle("JES uncertainty");
    hjes[i]->Draw("colz");

    t->DrawLatex(0.2 ,0.83,process);
    t->DrawLatex(0.2 ,0.71,signames.at(i).c_str());
    t->DrawLatex(0.18,0.92,label);

    // t->DrawLatex(0.2,0.83,"pp #rightarrow #tilde{g}#tilde{g}, #tilde{g} #rightarrow 2j+#chi_{2}^{0}, #chi_{2}^{0} #rightarrow Z #chi_{1}^{0}");
    // t->DrawLatex(0.2,0.77,"m(#tilde{q}) >> m(#tilde{g})");
    // t->DrawLatex(0.2,0.71,signames.at(i).c_str());
    // t->DrawLatex(0.18,0.92,"CMS Preliminary            #sqrt{s} = 7 TeV, #scale[0.6]{#int}Ldt = 4.7 fb^{-1}");

    if( print ){
      can[i]->Print(Form("../../plots/%s.pdf",labels.at(i).c_str()));
      //can[i]->Print(Form("../plots/%s.eps",labels.at(i).c_str()));
      //gROOT->ProcessLine(Form(".! ps2pdf ../plots/%s.eps  ../plots/%s.pdf",labels.at(i).c_str(),labels.at(i).c_str()));
    }

    int bin = heff[i]->FindBin(250,50);
    cout << "efficiency (250,50)  " << heff[i]->GetBinContent(bin) << endl;
    cout << "xsec UL              " << hxsec[i]->GetBinContent(bin) << endl;
    cout << "xsec UL exp          " << hxsec_exp[i]->GetBinContent(bin) << endl;
    cout << "JES                  " << hjes[i]->GetBinContent(bin) << endl;
    cout << "tot err              " << sqrt(pow(hjes[i]->GetBinContent(bin),2)+0.06*0.06+0.05*0.05) << endl;
    cout << endl << endl;
  }
  
  TFile *outfile = TFile::Open(Form("%s_histos.root",sample),"RECREATE");
  outfile->cd();
  for( unsigned int i = 0 ; i < nsig ; ++i ){
    hxsec[i]->Write();
    heff[i]->Write();
    hxsec_exp[i]->Write();
  }
  outfile->Close();

}
コード例 #13
0
// flags: [apply fake rate | pass Trigger | lumi | MC weight | trigger Eff | trigger MC to data SF | lumi SF | ele SF | mu SF | PU reweight]
TH1F *
MakeHistoFromBranch(TFile *input, const char *treeName, const char *brName, int signs, int &region, const char *cutVariable, float cutLow, float cutHigh, vector<float> &binning, unsigned int flags, bool normToBinWidth, float userScale)
{
  input->cd();
  // prepare the histogram
  TH1F *histo = new TH1F("dummy", "dummy", 150, 0., 1500.);
  histo->Sumw2();
  histo->SetName(brName);
  histo->SetTitle(brName);
  float *bins = &binning[0];
  histo->GetXaxis()->Set(binning.size() - 1, bins);

  if (flags & 1<<7) userScale *= ((TParameter<float> *)input->Get("lumi"))->GetVal();
  if (flags & 1<<6) {
    THashList *mcWeights = (THashList *)input->Get("mcWeights");
    unsigned int charOffset = 8;
    if (flags & 1<<9) charOffset += 2;
    userScale *= ((TParameter<float> *)mcWeights->FindObject(treeName + charOffset))->GetVal();
  }
  if (flags & 1<<5) userScale *= ((TParameter<float> *)input->Get("trgEff"))->GetVal();
  if (flags & 1<<4) userScale *= ((TParameter<float> *)input->Get("trgDataMcScaleFactor"))->GetVal();
  if (flags & 1<<1) userScale *= ((TParameter<float> *)input->Get("muScaleFactor"))->GetVal();
  float eleScaleFactorEB = ((TParameter<float> *)input->Get("eleScaleFactorEB"))->GetVal();
  float eleScaleFactorEE = ((TParameter<float> *)input->Get("eleScaleFactorEE"))->GetVal();
  float lumiScaleFactorEB = ((TParameter<float> *)input->Get("lumiScaleFactorEB"))->GetVal();
  float lumiScaleFactorEE = ((TParameter<float> *)input->Get("lumiScaleFactorEE"))->GetVal();

  //cout << "Scalefactor = " << userScale << endl;

  // get the tree
  TTree *tree;
  tree = (TTree *)input->Get(treeName);

  // get branches
  float var;
  bool passTrg;
  bool passHeep;
  float puWeight = 1.;
  int eCharge;
  int muCharge;
  int evtRegion;
  float cutVar = 0.;
  float fakeRate = 0.;
  tree->SetBranchStatus("*",0); //disable all branches
  tree->SetBranchStatus(brName,1);
  tree->SetBranchAddress(brName, &var);
  if (flags & 1<<8) {
    tree->SetBranchStatus("passTrg",1);
    tree->SetBranchAddress("passTrg", &passTrg);
  }
  if (signs != 0) {
    tree->SetBranchStatus("eCharge",1);
    tree->SetBranchStatus("muCharge",1);
    tree->SetBranchAddress("eCharge", &eCharge);
    tree->SetBranchAddress("muCharge", &muCharge);
  }
  if (region < 2) {
    tree->SetBranchStatus("evtRegion",1);
    tree->SetBranchAddress("evtRegion", &evtRegion);
  }
  if (flags & 1) {
    tree->SetBranchStatus("puWeight",1);
    tree->SetBranchAddress("puWeight", &puWeight);
  }
  if (cutVariable[0] != '\0') {
    tree->SetBranchStatus(cutVariable,1);
    tree->SetBranchAddress(cutVariable, &cutVar);
  }
  if (flags & 1<<9) {
    tree->SetBranchStatus("passHeep",1);
    tree->SetBranchStatus("fakeRate",1);
    tree->SetBranchAddress("passHeep", &passHeep);
    tree->SetBranchAddress("fakeRate", &fakeRate);
  }

  Long64_t nEntries = (*tree).GetEntries();
  for (unsigned int i = 0; i < nEntries; ++i) {
    tree->GetEntry(i);

    // trigger fired?
    if ((flags & 1<<8) && passTrg == false) continue;

    // select electron region
    if (evtRegion == 0 && region == 1) continue;
    if (evtRegion == 1 && region == 0) continue;

    float scaleFactor = userScale;
    // set lumi and electron scalefactor according to detector region
    if (evtRegion == 0 && flags & 1<<2) scaleFactor *= eleScaleFactorEB;
    if (evtRegion == 1 && flags & 1<<2) scaleFactor *= eleScaleFactorEE;
    if (evtRegion == 0 && flags & 1<<3) scaleFactor *= lumiScaleFactorEB;
    if (evtRegion == 1 && flags & 1<<3) scaleFactor *= lumiScaleFactorEE;

    // PU reweight
    if (flags & 1) scaleFactor *= puWeight;

    // get only the desired charge combination. Scheme emu -3 to +3: -+, +-, OS, ALL, SS, ++, --
    if (signs < 0 && (eCharge * muCharge) > 0) continue; // OS
    if (signs > 0 && (eCharge * muCharge) < 0) continue; // SS
    if (abs(signs) == 3 && eCharge > 0) continue; // e-mu+ or e-mu-
    if (abs(signs) == 2 && eCharge < 0) continue; // e+mu- or e+mu+

    // user defined cut
    if (cutVariable[0] != '\0')
      if (cutVar < cutLow || cutVar >= cutHigh) continue;
    
    if (flags & 1<<9) {
      if (!passHeep) scaleFactor *= fakeRate / (1 - fakeRate);
      else continue;
    }

    if (normToBinWidth) scaleFactor /= histo->GetBinWidth(histo->FindBin(var));
    histo->Fill(var, scaleFactor);
  }

  //cout << "integral: " << histo->Integral() << "       overflow: " << histo->GetBinContent(histo->GetNbinsX() + 1) << endl;
  return histo;
}
コード例 #14
0
ファイル: fitPtOverMCJLST.C プロジェクト: HZZ4l/CombinationPy
void fitPtOverMCJLST(int mass = 125, int LHCsqrts = 7, int whichtype = 1, 
		     bool correctErrors = false, /* string changeParName = "", */
		     bool showErrorPDFs = false, string systString = "Default")

// whichtype
// 0 - gg Signal
// 1 - VBF Signal
// 2 - ZZ
// 3 - ZX
// 4 - ggZZ
// 5 - WH
// 6 - ZH
// 7 - ttH

{

  string changeParName = "";
  if (systString == "Default") changeParName = "up";

  string nameSample[8] = {"gg","vbf","zz","zx","ggzz","wh","zh","tth"};
  float maxType[8] = {2.4,3.2,1.6,1.6,1.6,3.2,3.2,3.2};   
  float rebinType[8] = {1,2,1,1,4,10,10,40};
  
  for (int t = 0; t < 8; t++) {
    if (mass > 150) maxType[t] = int(117.90*maxType[t]/sqrt(mass-10.91))/10.;
  }

  char fileToOpen[200];
  sprintf(fileToOpen,"selRootFiles/PToverM_%s%d_SEL_%dTeV.root",nameSample[whichtype].c_str(),mass,LHCsqrts);
  // if (whichtype == 3) sprintf(fileToOpen,"PTOVERM_%s_SEL_allTeV.root",nameSample[whichtype].c_str());

  RooRealVar* ptoverm = new RooRealVar("ptoverm","p_{T}/M^{4l}",0.,maxType[whichtype],"GeV/c");
 
  TFile input(fileToOpen);
  // if (systString == "Mass" || systString == "Mela") {
  //  sprintf(fileToOpen,"ptovermH_%sUp",systString.c_str());
  // } else {
  sprintf(fileToOpen,"ptovermH_%s",systString.c_str());
  //}
  TH1F* ptovermH = (TH1F*)input.Get(fileToOpen);
  
  if (rebinType[whichtype] > 1) ptovermH->Rebin(rebinType[whichtype]);
  if (maxType[whichtype] < ptovermH->GetBinLowEdge(ptovermH->GetNbinsX() + 1) - ptovermH->GetBinWidth(1)) {
    int theBin = ptovermH->FindBin(maxType[whichtype]);
    ptovermH->GetXaxis()->SetRange(1,theBin-1);
  }

  gROOT->ProcessLine(".L mytdrstyle.C");
  gROOT->ProcessLine("setTDRStyle()");
  
  // cout << endl << "Signal " << endl;   
  ptoverm->setBins(ptovermH->GetNbinsX());

  RooDataHist* rdh = new RooDataHist("rdh","Some dataset",RooArgList(*ptoverm),Import(*ptovermH,kFALSE));
 
  // fit definitions
  // RooWorkspace *ws = new RooWorkspace("ws");

  RooRealVar m("m","emme", 1.,0.01, 40.);
  RooRealVar n("n","enne", 0.93, 0.05, 15.);
  RooRealVar n2("n2","enne2", 0.75, 0.5, 15.);
  RooRealVar bb("bb","bibi",0.02, 0.000005, 20.0);
  RooRealVar T("T","tti",0.2,0.00000005,1.);
  RooRealVar bb2("bb2","bibi2",0.02, 0.0005, 10.0);
  RooRealVar fexp("fexp","f_exp",0.02, 0.0, 1.0);
  if (whichtype == 0) {
    if (LHCsqrts == 8) {
      m.setVal(3.319);   // m.setConstant(kTRUE);
      n.setVal(0.7606);    if (systString != "Default" || mass != 125) n.setConstant(kTRUE); 
      n2.setVal(0.8061);   n2.setConstant(kTRUE);
      bb.setVal(3.728);   // bb.setConstant(kTRUE);
      T.setVal(0.00333);   // T.setConstant(kTRUE);
      bb2.setVal(1.7172);    // bb2.setConstant(kTRUE);
      fexp.setVal(0.002144);   if (systString != "Default" || mass != 125) fexp.setConstant(kTRUE);
    } else {
      m.setVal(0.061);   // m.setConstant(kTRUE);
      n.setVal(1.6141);   if (systString == "Resummation" || systString == "TopMass")  n.setConstant(kTRUE);
      n2.setVal(1.3294);   n2.setConstant(kTRUE);
      bb.setVal(4.2761);   // bb.setConstant(kTRUE);
      T.setVal(0.0361);   // T.setConstant(kTRUE);
      bb2.setVal(1.6643);   bb2.setConstant(kTRUE);
      fexp.setVal(0.0004);   // fexp.setConstant(kTRUE);
    }
  } else if (whichtype == 1) {
    m.setVal(1.006);   // m.setConstant(kTRUE);
    n.setVal(10.939);   n.setConstant(kTRUE);
    n2.setVal(1.1448);   n2.setConstant(kTRUE);
    bb.setVal(0.02048);   bb.setConstant(kTRUE);
    T.setVal(0.16115);   if (systString.find("Mela") != string::npos) T.setConstant(kTRUE); // T.setConstant(kTRUE);
    bb2.setVal(1.0024);   bb2.setConstant(kTRUE);
    fexp.setVal(0.005);   fexp.setConstant(kTRUE);
    if (mass > 300) {
      fexp.setVal(0.0);   fexp.setConstant(kFALSE);
    }
    if (mass > 500) {
      bb2.setVal(5.0);  //  bb2.setConstant(kFALSE);
    }
    if (mass > 500) {
      bb.setVal(15.0);  //  bb.setConstant(kFALSE);
    }
  } else if (whichtype == 2) {
    if (LHCsqrts == 8) {
      m.setVal(1.0476);   // m.setConstant(kTRUE);    
      bb.setVal(3.3088);  // if (mass != 140) bb.setConstant(kTRUE);
      n2.setVal(0.7146);   n2.setConstant(kTRUE);
      n.setVal(0.9518);      n.setConstant(kTRUE);
      bb2.setVal(100000.);  bb2.setConstant(kTRUE);
      T.setVal(0.0021889);    if (systString.find("Mela") != string::npos || mass != 140) T.setConstant(kTRUE);
      fexp.setVal(0.0);    fexp.setConstant(kTRUE);
    } else {
      m.setVal(1.028);   // m.setConstant(kTRUE);    
      bb.setVal(2.91); // bb.setConstant(kTRUE);
      n2.setVal(0.7146);  n2.setConstant(kTRUE);
      n.setVal(0.9518);     n.setConstant(kTRUE);
      bb2.setVal(100000.);  bb2.setConstant(kTRUE);
      T.setVal(0.002248);   if (systString.find("Mela") != string::npos) T.setConstant(kTRUE);
      fexp.setVal(0.0);    fexp.setConstant(kTRUE);
    }
  } else if (whichtype == 3) {
    m.setVal(1.411);   // m.setConstant(kTRUE);
    n.setVal(3.4523);     n.setConstant(kTRUE);
    n2.setVal(0.6910);    n2.setConstant(kTRUE);
    bb.setVal(0.00039);  // bb.setConstant(kTRUE);
    T.setVal(0.118);   // T.setConstant(kTRUE);
    bb2.setVal(0.0224);   bb2.setConstant(kTRUE);
    fexp.setVal(0.0);   fexp.setConstant(kTRUE);
  } else if (whichtype == 4) {
    m.setVal(1.411);   // m.setConstant(kTRUE);
    n.setVal(5.756);    // n.setConstant(kTRUE);
    n2.setVal(0.8738);   // n2.setConstant(kTRUE);
    bb.setVal(0.00039);  // bb.setConstant(kTRUE);
    T.setVal(0.118);   // T.setConstant(kTRUE);
    bb2.setVal(0.0224);   bb2.setConstant(kTRUE);
    fexp.setVal(0.0);   fexp.setConstant(kTRUE);
  } else if (whichtype == 5 && LHCsqrts == 8) {
    m.setVal(1.006);   // m.setConstant(kTRUE);
    n.setVal(10.939);    n.setConstant(kTRUE);
    n2.setVal(1.1448);   n2.setConstant(kTRUE);
    bb.setVal(3.897);   bb.setConstant(kTRUE);
    T.setVal(0.1009);  // T.setConstant(kTRUE);
    bb2.setVal(1.0224);   bb2.setConstant(kTRUE);
    fexp.setVal(0.01);   fexp.setConstant(kTRUE);
  } else {
    // cout << "Entro qui" << endl;
    m.setVal(1.006);   // m.setConstant(kTRUE);
    n.setVal(10.939);    n.setConstant(kTRUE);
    n2.setVal(1.1448);   n2.setConstant(kTRUE);
    bb.setVal(0.0129);  bb.setConstant(kTRUE);
    T.setVal(0.1009);    // T.setConstant(kTRUE);
    bb2.setVal(1.0224);   bb2.setConstant(kTRUE);
    fexp.setVal(0.01);   fexp.setConstant(kTRUE);
  }
 
  
  RooModifTsallis* rt3 = new RooModifTsallis("rt3","rt3",*ptoverm,m,n,n2,bb,bb2,T,fexp);
  // ws->import(*rt3);

  // fit
  RooFitResult* fit = rt3->fitTo(*rdh,Minos(0),Save(1),SumW2Error(kTRUE),NumCPU(1));  

  float mVal = m.getVal();   
  float nVal = n.getVal();
  float n2Val = n2.getVal();
  float bbVal = bb.getVal();
  float bb2Val = bb2.getVal();
  float fexpVal = fexp.getVal();
  float TVal = T.getVal();

  if (correctErrors) {
    // Tsallis errors not reliable, use toy MC

    TH1F* mHist = new TH1F("mHist","m",21,-0.5*mVal,0.5*mVal);
    TH1F* nHist = new TH1F("nHist","n",21,-0.2*nVal,0.2*nVal);
    TH1F* n2Hist = new TH1F("n2Hist","n2",21,-0.2*n2Val,0.2*n2Val);
    TH1F* bbHist = new TH1F("bbHist","bb",21,-0.2*bbVal,0.2*bbVal);
    TH1F* bb2Hist = new TH1F("bb2Hist","bb2",21,-0.2*bb2Val,0.2*bb2Val);
    TH1F* fexpHist = new TH1F("fexpHist","fexp",21,-0.2*fexpVal-0.000001,0.2*fexpVal+0.000001);
    TH1F* THist = new TH1F("THist","T",21,-0.5*TVal,0.5*TVal);
    mHist->GetXaxis()->SetTitle("m-m_{gen}");
    nHist->GetXaxis()->SetTitle("n-n_{gen}");
    n2Hist->GetXaxis()->SetTitle("n2-n2_{gen}");
    bbHist->GetXaxis()->SetTitle("bb-bb_{gen}");
    bb2Hist->GetXaxis()->SetTitle("bb2-bb2_{gen}");
    THist->GetXaxis()->SetTitle("T-T_{gen}");
    fexpHist->GetXaxis()->SetTitle("fexp-fexp_{gen}");

    for (unsigned int iToy = 0; iToy < 200; iToy++) {

      cout << endl << "####" << endl;
      cout << "Generating toy experiment n. " << iToy+1 << endl;

      m.setVal(mVal);
      n.setVal(nVal);
      n2.setVal(n2Val);
      bb.setVal(bbVal);
      bb2.setVal(bb2Val);
      fexp.setVal(fexpVal);
      T.setVal(TVal);

      TDatime *now = new TDatime();
      Int_t seed = now->GetDate() + now->GetTime();
      cout << "RooFit Generation Seed = " << seed+iToy << endl;
      RooRandom::randomGenerator()->SetSeed(seed+iToy);
      cout << "####" << endl << endl;

      RooDataSet *dataToy = rt3->generate(RooArgSet(*ptoverm),ptovermH->GetEntries());
      RooDataHist *dataToyH = new RooDataHist("dataToyH","toy",RooArgSet(*ptoverm),*dataToy);
      
      rt3->fitTo(*dataToyH,Minos(0),SumW2Error(kTRUE),NumCPU(1));  
  
      if (fit->floatParsFinal().find("m")) mHist->Fill(m.getVal()-mVal);
      if (fit->floatParsFinal().find("n")) nHist->Fill(n.getVal()-nVal);
      if (fit->floatParsFinal().find("n2")) n2Hist->Fill(n2.getVal()-n2Val);
      if (fit->floatParsFinal().find("bb")) bbHist->Fill(bb.getVal()-bbVal);
      if (fit->floatParsFinal().find("bb2")) bb2Hist->Fill(bb2.getVal()-bb2Val);
      if (fit->floatParsFinal().find("fexp")) fexpHist->Fill(fexp.getVal()-fexpVal);
      if (fit->floatParsFinal().find("T")) THist->Fill(T.getVal()-TVal);
    }

    TCanvas cant("cant","Test canvas",5.,5.,900.,500.);
    cant.Divide(4,2);
    cant.cd(1);   mHist->Draw();
    cant.cd(2);   nHist->Draw();
    cant.cd(3);   n2Hist->Draw();
    cant.cd(4);   bbHist->Draw();
    cant.cd(5);   bb2Hist->Draw();
    cant.cd(6);   fexpHist->Draw();
    cant.cd(7);   THist->Draw();
    // cant.SaveAs("figs/testToys.pdf");
    cant.SaveAs("newfigs/testToys.pdf");

    if (fit->floatParsFinal().find("m")) m.setError(mHist->GetRMS());
    if (fit->floatParsFinal().find("n")) n.setError(nHist->GetRMS());
    if (fit->floatParsFinal().find("n2")) n2.setError(n2Hist->GetRMS());
    if (fit->floatParsFinal().find("bb")) bb.setError(bbHist->GetRMS());
    if (fit->floatParsFinal().find("bb2")) bb2.setError(bb2Hist->GetRMS());
    if (fit->floatParsFinal().find("fexp")) fexp.setError(fexpHist->GetRMS());
    if (fit->floatParsFinal().find("T")) T.setError(THist->GetRMS());
  }

  m.setVal(mVal);
  n.setVal(nVal);
  n2.setVal(n2Val);
  bb.setVal(bbVal);
  bb2.setVal(bb2Val);
  fexp.setVal(fexpVal);
  T.setVal(TVal);

  char fileToSave[200];
  // if (changeParName != "") 
  //  sprintf(fileToSave,"text/paramsPTOverMCJLST_%s_%dTeV_%s_%s.txt",nameSample[whichtype].c_str(),LHCsqrts,systString.c_str(),changeParName.c_str()); 
  // else 
  sprintf(fileToSave,"text/paramsPTOverMCJLST_%s%d_%dTeV_%s.txt",nameSample[whichtype].c_str(),mass,LHCsqrts,systString.c_str());
  ofstream os1(fileToSave);
  if (changeParName != "") {
    sprintf(fileToSave,"m%s",changeParName.c_str());  m.SetName(fileToSave);
    sprintf(fileToSave,"n%s",changeParName.c_str());  n.SetName(fileToSave);
    sprintf(fileToSave,"n2%s",changeParName.c_str());  n2.SetName(fileToSave);
    sprintf(fileToSave,"bb%s",changeParName.c_str());  bb.SetName(fileToSave);
    sprintf(fileToSave,"bb2%s",changeParName.c_str());  bb2.SetName(fileToSave);
    sprintf(fileToSave,"fexp%s",changeParName.c_str());  fexp.SetName(fileToSave);
    sprintf(fileToSave,"T%s",changeParName.c_str());  T.SetName(fileToSave);
  }
  (RooArgSet(m,n,n2,bb,bb2,fexp,T)).writeToStream(os1,false);
  os1.close();

  RooRealVar mup("mup","emme", 1.,0.01, 30.);
  RooRealVar nup("nup","enne", 0.93, 0.5, 15.);
  RooRealVar n2up("n2up","enne2", 0.75, 0.5, 15.);
  RooRealVar bbup("bbup","bibi",0.02, 0.00005, 20.0);
  RooRealVar Tup("Tup","tti",0.2,0.00000005,1.);
  RooRealVar bb2up("bb2up","bibi2",0.02, 0.0005, 10.0);
  RooRealVar fexpup("fexpup","f_exp",0.02, 0.0, 1.0);
 
  RooModifTsallis* rt3up = new RooModifTsallis("rt3up","rt3up",*ptoverm,mup,nup,n2up,bbup,bb2up,Tup,fexpup);
  // ws->import(*rt3up);
 
  RooRealVar mdown("mdown","emme", 1.,0.01, 30.);
  RooRealVar ndown("ndown","enne", 0.93, 0.5, 15.);
  RooRealVar n2down("n2down","enne2", 0.75, 0.5, 15.);
  RooRealVar bbdown("bbdown","bibi",0.02, 0.00005, 20.0);
  RooRealVar Tdown("Tdown","tti",0.2,0.00000005,1.);
  RooRealVar bb2down("bb2down","bibi2",0.02, 0.0005, 10.0);
  RooRealVar fexpdown("fexpdown","f_exp",0.02, 0.0, 1.0);

  RooModifTsallis* rt3down = new RooModifTsallis("rt3down","rt3down",*ptoverm,mdown,ndown,n2down,bbdown,bb2down,Tdown,fexpdown);
  // ws->import(*rt3down);

  RooPlot *frame = ptoverm->frame();

  char reducestr[300];
  sprintf(reducestr,"ptoverm > %f && ptoverm < %f",ptoverm->getMin(),ptoverm->getMax());
  
  rdh->plotOn(frame,DataError(RooAbsData::SumW2),Cut(reducestr));
  static RooHist *hpull;
  float chi2 = 0.;

  if (changeParName == "") {
    sprintf(fileToSave,"text/paramsPTOverMCJLST_%s%d_%dTeV_Default.txt",nameSample[whichtype].c_str(),mass,LHCsqrts);
    ifstream is1(fileToSave);
    (RooArgSet(mup,nup,n2up,bbup,bb2up,fexpup,Tup)).readFromStream(is1,false);

    mdown.setVal(fabs(3*mup.getVal() - 2*m.getVal()));
    ndown.setVal(fabs(3*nup.getVal() - 2*n.getVal()));
    n2down.setVal(fabs(3*n2up.getVal() - 2*n2.getVal()));
    bbdown.setVal(fabs(3*bbup.getVal() - 2*bb.getVal()));
    Tdown.setVal(fabs(3*Tup.getVal() - 2*T.getVal()));
    bb2down.setVal(fabs(3*bb2up.getVal() - 2*bb2.getVal()));
    fexpdown.setVal(fabs(3*fexpup.getVal() - 2*fexp.getVal()));

    if (showErrorPDFs) {
      rt3->plotOn(frame,LineColor(kRed),LineStyle(kDashed),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent));
      hpull = frame->pullHist();
      rt3up->plotOn(frame,LineColor(kBlue),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent));
      if (systString.find("Mela") == string::npos) rt3down->plotOn(frame,LineColor(kRed),LineStyle(kDashed),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent));
    } else {
      rt3->plotOn(frame,LineColor(kBlue),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent));
      hpull = frame->pullHist();
    }
  } else {
    mup.setVal(m.getVal() + m.getError());   cout << "mup = " << mup.getVal() << endl;
    nup.setVal(n.getVal() + n.getError());
    n2up.setVal(n2.getVal() + n2.getError());
    bbup.setVal(bb.getVal() + bb.getError());
    Tup.setVal(T.getVal() + T.getError());
    bb2up.setVal(bb2.getVal() + bb2.getError());
    fexpup.setVal(fexp.getVal() + fexp.getError());

    mdown.setVal(m.getVal() - m.getError());  cout << "mdown = " << mdown.getVal() << endl;
    ndown.setVal(n.getVal() - n.getError());
    n2down.setVal(n2.getVal() - n2.getError());
    bbdown.setVal(bb.getVal() - bb.getError());
    Tdown.setVal(T.getVal() - T.getError());
    bb2down.setVal(bb2.getVal() - bb2.getError());
    fexpdown.setVal(fexp.getVal() - fexp.getError());

    rt3->plotOn(frame,LineColor(kBlue),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent));
    hpull = frame->pullHist();
    if (showErrorPDFs) {
      rt3up->plotOn(frame,LineColor(kRed),LineStyle(kDashed),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent));
      rt3down->plotOn(frame,LineColor(kRed),LineStyle(kDashed),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent));
    }
  }

  double *ypulls = hpull->GetY();
  unsigned int nBins = rdh->numEntries();
  unsigned int nFullBins = 0;
  for (unsigned int i = 0; i < nBins; i++) {
    cout << "Pull of bin " << i << " = " << ypulls[i] << endl;
    if (fabs(ypulls[i]) < 5.0) chi2 += ypulls[i]*ypulls[i]; 
    cout << "Partial chi2 = " << chi2 << endl;
    if (fabs(ypulls[i]) > 0.0001 && fabs(ypulls[i]) < 5.0) nFullBins++;
  }
  for (unsigned int i = 0; i < nBins; i++) {
    if (fabs(ypulls[i]) < 0.0001) ypulls[i] = 999.; 
    hpull->SetPointError(i,0.,0.,0.,0.);
  } 
  int nFitPar = fit->floatParsFinal().getSize() - 1;

  TCanvas can("can","The canvas",5.,5.,500.,900.); 
  can.Divide(1,3);

  TLatex *t = new TLatex();
  t->SetNDC();
  t->SetTextAlign(22);
  t->SetTextSize(0.06);

  can.cd(1);
  gPad->SetBottomMargin(0.0);
  frame->Draw();
  // gPad->SetLogy(); 
  // Htest->Draw();
  sprintf(fileToSave,"%s %d GeV at %d TeV",nameSample[whichtype].c_str(),mass,LHCsqrts);
  t->DrawLatex(0.6,0.8,fileToSave); 

  can.cd(2);
  gPad->SetLogy(); 
  gPad->SetTopMargin(0.0);
  frame->Draw();
 
  RooPlot* pull = ptoverm->frame(Title("Pull Distribution")) ;
  pull->GetYaxis()->SetTitle("Pull");
  /* pull->SetLabelSize(0.08,"XYZ");
  pull->SetTitleSize(0.08,"XYZ");
  pull->SetTitleOffset(0.6,"Y");
  pull->SetTitleOffset(1.0,"X"); */
  pull->addPlotable(hpull,"P") ; 
  pull->SetMinimum(-6.); 
  pull->SetMaximum(6.); 

  can.cd(3);
  gPad->SetGridy();
  pull->Draw();
  sprintf(fileToSave,"#chi^{2}/n_{DoF} = %4.1f/%d",chi2,nFullBins - nFitPar);
  if (chi2 < 1000.) t->DrawLatex(0.80,0.86,fileToSave);

  // sprintf(fileToSave,"figs/fitPTOverMCJLST_%s%d_%dTeV_%s.pdf",nameSample[whichtype].c_str(),mass,LHCsqrts,systString.c_str());
  sprintf(fileToSave,"newfigs/fitPTOverMCJLST_%s%d_%dTeV_%s.pdf",nameSample[whichtype].c_str(),mass,LHCsqrts,systString.c_str());
  can.SaveAs(fileToSave);

}
コード例 #15
0
// This is the Efrac plot for a CALSum range
void Efrac_all_energies::Loop2()
{
  
  if (fChain == 0) return;
  
  TH1F * hPi = new TH1F("hPi","",500,-0.2,3);
  TH1F * hE = new TH1F("hE","",500,-0.2,3);
  
  Int_t NE75 = 0;
  Int_t NE100 = 0;
  Int_t NE125 = 0;
  Int_t NE150 = 0;
  Int_t NE175 = 0;

  Int_t NPi250 = 0;
  Int_t NPi300 = 0;
  Int_t NPi350 = 0;    
    
  Double_t gainA[12] = {4.23,4.23,3.92,3.09,5.81,5.03,3.17,5.30,4.31,3.90,4.04,3.68};
  Double_t myfCHA[12];
  Double_t myBSDLatePE = 0;

  fChain->SetBranchStatus("*",1);
  
  Long64_t nentries = fChain->GetEntriesFast();
  
  Long64_t nbytes = 0, nb = 0;
  for (Long64_t jentry=0; jentry<nentries;jentry++) 
    {
      Long64_t ientry = LoadTree(jentry);
      if (ientry < 0) break;
      nb = fChain->GetEntry(jentry);   nbytes += nb;

      /////////////////////////////////////////////////////////////////////////
      // These are just cuts for valid BSD/CAL data values
      // Need a BSD event which also includes the CAL
      ////////////////////////////////////////////////////////////////////////
      if( !IsWithCal ) continue;

      myBSDLatePE = 0;
      for( int i = 0; i < 12; i++ )
	myfCHA[i] = -1;
            
      for( int i = 1; i <= 10; i++ )
	{
	  if( fCHA[i] <= 0 )
	    {
	      myfCHA[i] = 2048;
	    }
	  else
	    {
	      myfCHA[i] = fCHA[i];
	    }
	}
      
      // Simulate CAL trigger by requiring 6 consecutive layers with > 40 MeV
      Int_t Ntrig_layers = 0;
      for( int i = 0; i < 20; i++ )
	{
	  if( CALProfile[i]/9 > 40 )
	    Ntrig_layers++;
	  else
	    Ntrig_layers = 0;
	  if( Ntrig_layers >= 6 )
	    break;
	}
      if( Ntrig_layers < 6 ) continue;

      // New cut to look at a range of CALSum
      // if( CALSum < 6000 || CALSum > 7500 ) continue;
      if( CALSum < 6000 || CALSum > 9000 ) continue;

      for( int i = 1; i <= 10; i++ )
	myBSDLatePE += myfCHA[i]*0.25E-12/(gainA[i]*1.E6*1.6E-19);
            
      // Check if we've got enough of that particular flavor, i.e. all electrons 
      // need to be weighted equally relative to pions
      if( ptype == 2 && penergy == 250 && NPi250 > 6617) continue; 
      if( ptype == 2 && penergy == 300 && NPi300 > 6617) continue; 
      if( ptype == 2 && penergy == 350 && NPi350 > 6617) continue; 
      
      if( ptype == 1 && penergy == 75 && NE75 > 2442 ) continue;
      if( ptype == 1 && penergy == 100 && NE100 > 2442 ) continue;
      if( ptype == 1 && penergy == 125 && NE125 > 2442 ) continue;
      if( ptype == 1 && penergy == 150 && NE150 > 2442 ) continue;
      if( ptype == 1 && penergy == 175 && NE175 > 2442 ) continue;

      // Fill Efrac for electrons
      if( ptype == 1 && (penergy >=75 || penergy <= 175) )
	hE->Fill(myBSDLatePE/CALSum);
      
      // Fill Efrac for pions
      if( ptype == 2 && (penergy >= 250 || penergy <= 350) )
	hPi->Fill(myBSDLatePE/CALSum);
      // Increment counts, since everything has to be equally weighted
      if( ptype == 2 && penergy == 250 ) NPi250++;
      if( ptype == 2 && penergy == 300 ) NPi300++;
      if( ptype == 2 && penergy == 350 ) NPi350++;
      
      if( ptype == 1 && penergy == 75 ) NE75++;
      if( ptype == 1 && penergy == 100 ) NE100++;
      if( ptype == 1 && penergy == 125 ) NE125++;
      if( ptype == 1 && penergy == 150 ) NE150++;
      if( ptype == 1 && penergy == 175 ) NE175++;
    }
  
  hE->SetLineColor(kRed);
  hE->SetTitle("Efrac for 250-350 GeV Pions (Blue) and 75-175 GeV Electrons (Red) and CALSum Between 6000 and 9000");
  hE->GetXaxis()->SetTitle("Efrac (\"detector\" units)");
  hE->GetXaxis()->CenterTitle();
  hE->Scale(1./hE->GetEntries());
  hE->Draw();
  hPi->Scale(1./hPi->GetEntries());
  hPi->Draw("sames");

  Double_t reg_power[1000];
  Double_t e_accept[1000];
  Double_t pi_accept[1000];
  Double_t endbin[1000];
  Int_t Npts = 0;
  Int_t Nskip = 0;

  Int_t start = hE->FindBin(0);
  Int_t nbins = 40;
  // ToDo: Add error bars
  cout << "Start = " << start << endl;

  Double_t x_err[1000];
  Double_t y_err[1000];

  Double_t num = 0;
  Double_t den = 0;
  Double_t num_err = 0;
  Double_t den_err = 0;
  Double_t Ne = 0;
  Double_t Ne_total = 0;
  Double_t Npi = 0;
  Double_t Npi_total = 0;
  Double_t Ne_entries = hE->GetEntries();
  Double_t Npi_entries = hPi->GetEntries();
  for( int i = 0; i < nbins; i++ )
    {
      cout << "Efrac = " << hE->GetBinLowEdge(start+i) << endl;
      if( hPi->Integral(start,start+i) > 10./Ne_entries && 
	  hE->Integral(start,start+i) > 10./Npi_entries )
	{
	  num_err = 0;
	  den_err = 0;
	  Ne = 0;
	  Npi = 0;
	  num = 0;
	  den = 0;
	  Npi_total = 0;
	  Ne_total = 0;
	  
	  Ne = hE->Integral(start,start+i);
	  Ne_total = hE->Integral();
	  Npi = hPi->Integral(start,start+i);
	  Npi_total = hPi->Integral();
	  
	  num = (Ne/Ne_total);
	  den = (Npi/Npi_total);

	  reg_power[i-Nskip] = num/den;
	  e_accept[i-Nskip] = num;
	  pi_accept[i-Nskip] = den;
	  endbin[i-Nskip] = start+i;
	  
	  num = (Ne/Ne_total);
	  den = (Npi/Npi_total);
	  num_err = (num) * sqrt(1/(Ne*Ne_entries) + 1/(Ne_total*Ne_entries));
	  den_err = (den) * sqrt(1/(Npi*Npi_entries) + 1/(Npi_total*Npi_entries));
	  y_err[i-Nskip] = (num/den) * sqrt( (num_err*num_err)/(num*num) + (den_err*den_err)/(den*den) );
	  x_err[i-Nskip] = num_err;
	
	  cout << i-Nskip 
	       << " " << e_accept[i-Nskip]
	       << " " << pi_accept[i-Nskip]
	       << " " << reg_power[i-Nskip] 
	       << " " << hPi->Integral(start,start+i)
	       << " " << hE->Integral(start,start+i)
	       << " " << num_err
	       << " " << den_err
	       << endl;
	  Npts++;
	}
      else
	Nskip++;
    }
  
  /*  
  // For quick and easy copy/paste graphing
  cout << "rej[" << Npts << "] = {";
  for(int i = 0; i < Npts; i++ )
    cout << reg_power[i] << ", " << endl;
  cout << endl;
  
  // For quick and easy copy/paste graphing
  cout << "e_accept[" << Npts << "] = {";
  for(int i = 0; i < Npts; i++ )
    cout << e_accept[i] << ", " << endl;
  cout << endl;
  
  cout << "x_err[" << Npts << "] = {";
  for( int i = 0; i < Npts; i++ )
    cout << x_err[i] << endl;
  cout << endl;

  cout << "y_err[" << Npts << "] = {";
  for( int i = 0; i < Npts; i++ )
    cout << y_err[i] << endl;
  cout << endl;
  */
  TCanvas * cv2 = new TCanvas("cv2");
  TGraphErrors * gr = new TGraphErrors(Npts,e_accept,reg_power,x_err,y_err);
  gr->SetTitle("");
  gr->GetXaxis()->SetTitle("Electron acceptance");
  gr->GetXaxis()->CenterTitle();
  gr->GetYaxis()->SetTitle("Rejection Power");
  gr->GetYaxis()->CenterTitle();
  gr->SetMarkerStyle(20);
  gr->Draw("APL");
}
コード例 #16
0
ファイル: createNNLOplot.C プロジェクト: eschliec/TopAnalysis
void createNNLOplot(TString theory="ahrens")
{
  // theory="ahrens", "kidonakis"
  TString outputRootFile="test.root";
  // NB: add new datset name here
  if(theory.Contains("ahrens")   ){
    outputRootFile="AhrensNLONNLL";
    //if(theory.Contains("mtt")    ) outputRootFile+="mttbar" ;
    //else if(theory.Contains("pt")) outputRootFile+="pTttbar";
    outputRootFile+=".root";
  }
  else if(theory=="kidonakis") outputRootFile="KidonakisAproxNNLO.root";
  // general options
  gStyle->SetOptStat(0);
  bool usequad=true;
  bool divideByBinwidth=true;
  // list of variables
  std::vector<TString> xSecVariables_, xSecLabel_;
  // NB: add variables for new datset name here
  TString xSecVariablesUsedAhrens[]    ={"ttbarMass", "ttbarPt"};
  TString xSecVariablesUsedKidonakis[] ={"topPt"    , "topY"   };
  if(     theory.Contains("ahrens")   ) xSecVariables_ .insert( xSecVariables_.begin(), xSecVariablesUsedAhrens   , xSecVariablesUsedAhrens    + sizeof(xSecVariablesUsedAhrens   )/sizeof(TString) );
  else if(theory=="kidonakis") xSecVariables_ .insert( xSecVariables_.begin(), xSecVariablesUsedKidonakis, xSecVariablesUsedKidonakis + sizeof(xSecVariablesUsedKidonakis)/sizeof(TString) );
  // get variable binning used for final cross sections 
  std::map<TString, std::vector<double> > bins_=makeVariableBinning();
  //std::vector<double> tempbins_;
  //double ttbarMassBins[]={345,445,545,745, 1045};
  //tempbins_.insert( tempbins_.begin(), ttbarMassBins, ttbarMassBins + sizeof(ttbarMassBins)/sizeof(double) );
  //bins_["ttbarMass"]=tempbins_;

  // loop all variables
  for(unsigned var=0; var<xSecVariables_.size(); ++var){
    TString variable=xSecVariables_[var];
    std::cout << "----------" << std::endl;
    std::cout << theory << ": " << variable << std::endl;
    // get bin boundaries
    double low =bins_[variable][0];
    double high=bins_[variable][bins_[variable].size()-1];
    // --------------------------
    // get raw nnlo theory points
    // --------------------------
    // NB: add new datset file names here
    TGraph * rawHist;
    TString predictionfolder="/afs/naf.desy.de/group/cms/scratch/tophh/CommonFiles/";
    if(theory=="ahrens"   ){
      if(variable.Contains("ttbarMass")) rawHist= new TGraph(predictionfolder+"AhrensTheory_Mttbar_8000_172.5_NLONNLL_norm.dat");//AhrensTheory_Mtt_7000_172.5_Mtt_fin.dat
      if(variable.Contains("ttbarPt"  )) rawHist= new TGraph(predictionfolder+"AhrensTheory_pTttbar_8000_172.5_NLONNLL_abs.dat");//AhrensTheory_pTttbar_7000_172.5_NLONNLL_abs.dat
    }
    else if(theory=="kidonakis"){
      if(variable.Contains("topPt")) rawHist= new TGraph(predictionfolder+"pttopnnloapprox8lhc173m.dat");//"ptnormalNNLO7lhc173m.dat" //"pttopnnloapprox8lhc173m.dat"
      if(variable.Contains("topY" )) rawHist= new TGraph(predictionfolder+"ytopnnloapprox8lhc173m.dat" );//"ynormalNNLO7lhc173m.dat"  //"ytopnnloapprox8lhc173m.dat"
    }
    // NB: say if points should be interpreted as single points with 
    //     nothing in between or as integrated value over the range
    bool points=true;
    if(theory.Contains("ahrens")) points=false;
    else if(theory=="kidonakis")  points=true;
    std::cout << "input: " << rawHist->GetTitle() << std::endl;
    std::cout << "interprete values as points?: " << points << std::endl;

    // --------------------
    // convertion to TH1F*
    // --------------------
    double *Xvalues = rawHist->GetX();
    int Nbins=rawHist->GetN();
    //double *Yvalues = rawHist->GetY(); // not working
    double xmax=-1;
    double xmin=-1;
    double binwidth=-1;
    //
    TH1F* hist;
    // NB: add additional binning for new theory here
    // NB: if loaded data should be interpreted as points with 
    //     nothing in between (like kidonakis), make suree you 
    //     choose a binning that is fine enough for the 
    //     data points loaded
    if(theory=="ahrens"){
      if(variable.Contains("ttbarMass")){
	xmin= 345.;
	xmax=2720.;
	binwidth=25.;// 5 for 8TeV, 25 for 7TeV
	if(TString(rawHist->GetTitle()).Contains("8000")) binwidth=5.;
      }
      else if(variable.Contains("ttbarPt")){
	xmin= 0.;
	xmax=1300.;
	binwidth=5.;
      }
    }
    else if(theory=="kidonakis"){ 
      if(variable.Contains("topPt")){
	xmin=   0.;
	xmax=1500.;
	binwidth=1.;
      }
      else if(variable.Contains("topY")){
	xmin=-3.8;
	xmax= 3.8;
	binwidth=0.01;
      }
    }
    // fill data in binned TH1F
    hist= new TH1F ( variable, variable, (int)((xmax-xmin)/binwidth), xmin, xmax);
    TH1F* ori=(TH1F*)hist->Clone("original points");
    std::cout << "fine binned theory prediction has " << hist->GetNbinsX() << " bins" << std::endl;
    std::cout << "loaded values from .dat file: " << std::endl;
    // list all data values loaded and the corresponding bin
    for(int bin=1; bin<=Nbins; ++bin){
      double x=-999;
      double y=-999;
      // NB: choose if loaded data is interpreted as points with nothing 
      //     between (like kidonakis) or as integrated over the bin range (like ahrens)
      if(points){
	// check if you are still inside the array
	//std::cout << "data point " << bin-1 << "/" << sizeof(Xvalues)/sizeof(double) << std::endl;
	if(rawHist->GetPoint(bin-1, x, y)!=-1){
	  //x=Xvalues[bin-1]; // get value from data points
	  x+=0.5*binwidth;  // add half the binwidth to get the center of the bin
	}
      }
      else{
	x=hist->GetBinCenter(bin);  // get bin center
	y=rawHist->GetY()[bin-1];
      }
      if(x!=-999){
	std::cout << "data point: " << bin;
	std::cout << "(<x>=" << x << ")-> bin";
	// get bin in target (fine binned) plot
	int bin2=bin;
	if(points) bin2=hist->FindBin(x);
	//double y=Yvalues[bin2-1];
	std::cout << bin2 << " (";
	std::cout << hist->GetBinLowEdge(bin2) << ".." << hist->GetBinLowEdge(bin2+1);
	std::cout << "): " << y << std::endl;
	// fill target (fine binned) plot
	if(!points) hist->SetBinContent(bin2, y);
	// mark bins coming from the original prediction
	ori->SetBinContent(bin2, 1.);
	// -------------------------------
	// fit range without data entries
	// -------------------------------
	// NB: needed if loaded data is interpreted as points with nothing 
	//     between (like kidonakis)
	if(points){
	  // perform a linear fit wrt previous point
	  // get the two points (this bin and the previous one)
	  int binPrev= (bin==1&&variable=="topPt") ? 0 : hist->FindBin(Xvalues[bin-2]+0.5*binwidth);
	  double x2=-1;
	  double x1= 0;
	  double y2=-1;
	  double y1= 0.;
	  rawHist->GetPoint(bin-1, x2, y2);
	  x2+=0.5*binwidth;
	  if(bin==1&&variable=="topPt"){
	    y1=0;
	    x1=0;
	  }
	  else{
	    rawHist->GetPoint(bin-2, x1, y1);
	    x1+=0.5*binwidth;
	  }
	  // calculate linear funtion
	  double a=(y2-y1)/(x2-x1);
	  double b=y1-a*x1;
	  TF1* linInterpol=new TF1("linInterpol"+getTStringFromInt(bin), "[0]*x+[1]", x1, x2);
	  linInterpol->SetParameter(0,a);
	  linInterpol->SetParameter(1,b);
	  double xlow  = (bin==1&&variable=="topPt") ? 0. : hist->GetBinLowEdge(binPrev+1);
	  double xhigh = hist->GetBinLowEdge(bin2+1);
	  std::cout << " lin. interpolation [ (" << x1 << "," << y1 << ") .. (" << x2 << "," << y2 << ") ]: " << a << "*x+" << b << std::endl;
	  linInterpol->SetRange(xlow, xhigh);
	  hist->Add(linInterpol);
	}
      }
    }
    // check theory curve
    std::cout << std::endl << "analyze theory curve:" << std::endl;
    double integralRawTheory=hist->Integral(0.,hist->GetNbinsX()+1);
    std::cout << "Integral: " << integralRawTheory << std::endl;
    if(integralRawTheory==0.){
      std::cout << "ERROR: Integral can not be 0!" << std::endl;
      exit(0);
    }
    std::cout << "binwidth: " << binwidth << std::endl;
    std::cout << "Integral*binwidth: " << integralRawTheory*binwidth << std::endl;
    std::cout << "binRange: " << xmin << ".." << xmax << std::endl;
    std::cout << "   -> reco range: " << low << ".." << high << std::endl;
    std::vector<double> recoBins_=bins_[variable];
    for(unsigned int i=0; i<recoBins_.size(); ++i){
      i==0 ? std::cout << "(" : std::cout << ", ";
      std::cout << recoBins_[i];
      if(i==recoBins_.size()-1) std::cout << ")" << std::endl;
    }
    // check if you need to divide by binwidth
    if(std::abs(1.-integralRawTheory)<0.03){
      std::cout << "Integral is approx. 1 -> need to divide by binwidth!" << std::endl;
      hist->Scale(1./binwidth);
    }
    else if(std::abs(1-integralRawTheory*binwidth)<0.03){
      std::cout << "Integral*binwidth is approx. 1 -> no scaling needed!" << std::endl;
    }
    else{
      std::cout << "need to normalize and divide by binwidth";
      hist->Scale(1./(binwidth*integralRawTheory));
    }
    // styling
    hist->GetXaxis()->SetRangeUser(low,high);
    hist->SetMarkerColor(kMagenta);
    hist->SetLineColor(  kMagenta);
    hist->SetMarkerStyle(24);
    // create canvas
    std::cout << std::endl << "create canvas " << std::endl;
    TCanvas *canv = new TCanvas(variable,variable,800,600);
    canv->cd();
    std::cout << "draw original theory curve " << std::endl;
    //temp->Draw("axis");
    hist->Draw("p");
    //hist->Draw("hist same");
    // draw original points
    if(points){
      for(int bin=1; bin<ori->GetNbinsX(); ++bin){
	// create copy of original data points with the normalized values
	if(ori->GetBinContent(bin)!=0) ori->SetBinContent(bin, hist->GetBinContent(bin));
	ori->SetMarkerColor(kBlack);
	ori->SetMarkerStyle(29);
	ori->SetMarkerSize(1);
	ori->Draw("p same");
      }
    }
    // --------------------
    // create rebinned plot
    // --------------------
    std::cout << std::endl << "create rebinned curve:" << std::endl;
    TString name="";
    // NB: add name for dataset here
    name=variable;
    if(    theory=="kidonakis") name+="approxnnlo";
    else if(theory=="ahrens"  ) name+="nlonnll"   ;
    TH1F* binnedPlot=new TH1F(name, name, bins_[variable].size()-1, &bins_[variable][0]);
    for(int bin=1; bin<=hist->GetNbinsX(); ++bin){
      double y=hist->GetBinContent(bin)*hist->GetBinWidth(bin);
      double xlow =hist->GetBinLowEdge(bin);
      double xhigh=hist->GetBinLowEdge(bin+1);
      // search corresponding bin in rebinned curve
      bool found=false;
      //std::cout << "xlow: " << xlow << ", xhigh: " << xhigh << std::endl; // FIXME
      for(int binRebinned=0; binRebinned<=binnedPlot->GetNbinsX()+1; ++binRebinned){
	if(binnedPlot->GetBinLowEdge(binRebinned)<=xlow&&binnedPlot->GetBinLowEdge(binRebinned+1)>=xhigh){
	  found=true;
	  binnedPlot->SetBinContent(binRebinned, binnedPlot->GetBinContent(binRebinned)+y);
	  break;
	}
	//else{
	//  std::cout << "not in: " << binnedPlot->GetBinLowEdge(binRebinned) << ".." << binnedPlot->GetBinLowEdge(binRebinned+1)<< std::endl;
	//}
      }
      // --------------------
      // use linear interpolation for edge bins
      // --------------------
      if(hist->GetBinCenter(bin)<high&&!found){
	std::cout << "need interpolation for bin" << bin << "(<x>=" << hist->GetBinCenter(bin) << ")!"<< std::endl;
	// search for the two bins involved
	double binLow=0;
	double binHigh=0;
	for(int binRebinned=1; binRebinned<=binnedPlot->GetNbinsX(); ++binRebinned){
	  // search for bin in binned histo where upper border of is close to lower border of unbinned histo
	  if(std::abs(binnedPlot->GetBinLowEdge(binRebinned+1)-xlow)<binwidth){
	    binLow =binRebinned; 
	    binHigh=binRebinned+1;
	    break;
	  }
	}
	std::cout << "theory bin " << xlow << ".." << xhigh << "-> reco bins ";
	std::cout << binnedPlot->GetBinLowEdge(binLow) << ".." << binnedPlot->GetBinLowEdge(binLow+1) << " & ";
	std::cout << binnedPlot->GetBinLowEdge(binHigh) << ".." << binnedPlot->GetBinLowEdge(binHigh+1) << std::endl;
	// get the two points (this bin and the previous one)
	double x2=hist->GetBinCenter (bin  );
	double x1=hist->GetBinCenter (bin-1);
	double x3=hist->GetBinCenter (bin+1);
	double y2=hist->GetBinContent(bin  );
	double y1=hist->GetBinContent(bin-1);
	double y3=hist->GetBinContent(bin+1);	
	// calculate linear funtion
	double a=(y2-y1)/(x2-x1);
	double b=y1-a*x1;
	TF1* linInterpol=new TF1("linInterpol"+getTStringFromInt(bin), "[0]*x+[1]", x1, x2);
	linInterpol->SetParameter(0,a);
	linInterpol->SetParameter(1,b);
	// calculate the corresponding area of linear function to binned curve
	double contributionLowerBin=linInterpol->Integral(xlow,binnedPlot->GetBinLowEdge(binHigh));
	double contributionUpperBin=linInterpol->Integral(binnedPlot->GetBinLowEdge(binHigh),xhigh);
	// draw interpolation function for checking
	linInterpol->SetRange(xlow,xhigh);
	linInterpol->SetLineColor(kMagenta);
	linInterpol->DrawClone("same");
	// eventually use quadratic interpolation for the first harens m(ttbar) bin
	if(theory=="ahrens"&&variable.Contains("ttbarMass")&&usequad&&x2<450){
	  // calculate quadratic funtion
	  double a2=(y2-((y3-y1))*(x2-x1)/(x3-x1))/(x2*x2-x1*x1-(x2-x1)*(x3*x3+x1*x1)/(x3-x1));
	  double b2=((y3-y1)-a2*(x3*x3-x1*x1))/(x3-x1);
	  double c2=y1-a2*x1*x1-b*x1;
	  TF1* quadInterpol=new TF1("quadInterpol"+getTStringFromInt(bin), "[0]*x*x+[1]*x+[2]", x1, x2);
	  quadInterpol->SetParameter(0,a2);
	  quadInterpol->SetParameter(1,b2);
	  quadInterpol->SetParameter(2,c2);
	  // draw quad interpolation function for checking
	  quadInterpol->SetRange(xlow,xhigh);
	  quadInterpol->SetLineColor(kGreen);
	  quadInterpol->SetLineStyle(2);
	  hist->Fit(quadInterpol, "", "same", x1, x3);
	  // calculate the corresponding area of linear function to binned curve
	  quadInterpol->DrawClone("same");
	  double areaLow =quadInterpol->Integral(xlow,binnedPlot->GetBinLowEdge(binHigh) );
	  double areaHigh=quadInterpol->Integral(binnedPlot->GetBinLowEdge(binHigh),xhigh);
	  std::cout << "ratio(high/low) linear/quadratic: " << contributionUpperBin/contributionLowerBin << "/"<< areaHigh/areaLow << std::endl;
	  contributionLowerBin=y2*binwidth*areaLow /(areaLow+areaHigh);
	  contributionUpperBin=y2*binwidth*areaHigh/(areaLow+areaHigh);
	}
	// add fitted result
	binnedPlot->SetBinContent(binLow , binnedPlot->GetBinContent(binLow )+contributionLowerBin);
	binnedPlot->SetBinContent(binHigh, binnedPlot->GetBinContent(binHigh)+contributionUpperBin);
      }
    }
    // ensure over/underflow is 0
    binnedPlot->SetBinContent(0, 0.);
    binnedPlot->SetBinContent(binnedPlot->GetNbinsX()+1, 0.);
    // ensure normalization
    binnedPlot->Scale(1./(binnedPlot->Integral(0.,binnedPlot->GetNbinsX()+1)));
    // divide by binwidth
    if(divideByBinwidth){
      for(int bin=1; bin<=binnedPlot->GetNbinsX(); ++bin){
	binnedPlot->SetBinContent(bin, binnedPlot->GetBinContent(bin)/binnedPlot->GetBinWidth(bin));
      }
    }
    std::cout << "-------------------------------------------" << std::endl;
    std::cout << "result: binned output histo" << std::endl;
    for(int bin=1; bin<=binnedPlot->GetNbinsX(); ++bin){
      std::cout << "content bin " << bin << " (" << binnedPlot->GetBinLowEdge(bin) << ".." << binnedPlot->GetBinLowEdge(bin+1) << ")= " << binnedPlot->GetBinContent(bin) << std::endl;
    }

    // styling
    binnedPlot->SetLineColor(kBlue);
    binnedPlot->SetLineWidth(2);
    std::cout << "draw rebinned theory curve " << std::endl;
    binnedPlot->Draw("hist same");
    // draw bin boundaries
    std::cout << "draw bin boundaries " << std::endl;
    int binColor=kRed;
    int binWidth=2;
    int binStyle=6;
    for(int bin=0; bin<(int)bins_.size(); ++bin){
      if(!variable.Contains("ttbarMass")||bins_[variable][bin]>=345.) drawLine(bins_[variable][bin], 0, bins_[variable][bin], hist->GetMaximum(), binColor, binWidth, binStyle);
    }
    TH1F* line=(TH1F*)hist->Clone("line");
    line->SetLineColor(binColor);
    line->SetLineWidth(binWidth);
    line->SetLineStyle(binStyle);
    // legend
    TLegend *leg = new TLegend(0.7, 0.6, 0.95, 0.9);
    legendStyle(*leg,theory);
    if(points) leg ->AddEntry(ori, "original data points","P");
    leg ->AddEntry(hist      , "theory prediction" ,"P");
    leg ->AddEntry(line      , "reco binning"      ,"L");
    leg ->AddEntry(hist      , "linear interpolation" ,"L");
    leg ->AddEntry(binnedPlot, "rebinned curve"    ,"L");
    leg->Draw("same");
    std::cout << "done" << std::endl;
    // save in png and rootfile
    std::cout << std::endl << "do saving..." << std::endl;
    canv->SaveAs(variable+"Norm_Theory.png");
    TH1F* out=(TH1F*)binnedPlot->Clone();
    out->SetTitle(variable);
    out->SetName (variable);
    out->GetXaxis()->SetTitle(xSecLabelName(variable));
    TString yTile="#frac{1}{#sigma} #frac{d#sigma}{d";
    if(variable=="ttbarMass") yTile+="m^{t#bar{t}}} [GeV^{-1}]";
    if(variable=="ttbarPt") yTile+="p_{T}^{t#bar{t}}} [GeV^{-1}]";
    if(variable=="topPt") yTile+="p_{T}^{t}} [GeV^{-1}]";
    if(variable=="topY" ) yTile+="y^{t}}";
    out->GetYaxis()->SetTitle(yTile);
    out->SetLineColor(kOrange+2);
    out->SetLineStyle(2);
    std::cout << std::endl << "draw final result " << std::endl;
    TCanvas *canv2 = new TCanvas(variable+"Rebinned",variable+"Rebinned",800,600);
    canv2->cd();
    out->Draw();
    saveToRootFile(outputRootFile, out    , true, 0,""      );
    saveToRootFile(outputRootFile, rawHist, true, 0,"graph" );
    saveToRootFile(outputRootFile, canv   , true, 0,"detail");
    std::cout << "done!" << std::endl;
  }
}
コード例 #17
0
void GenerateInputFile_ge4b( double mgl=-1., double mlsp=-1., double target_susy_all0lep=-1. ) {

  TChain* dyTree = new TChain("treeZ") ;
  int nAdded = dyTree->Add("files15fb_8TeV_old1/DY.root") ;
  if ( nAdded <= 0 ) {
     printf("\n\n\n *** No treeZ in files15fb_8TeV_old1/DY.root\n\n\n") ;
     return ;
  }

  double t1bbbbWeight(0.) ;
  TChain chainT1bbbb("tree") ;
  char susycutstring[1000] ;
  sprintf( susycutstring, "&&mgluino==%.0f&&mlsp==%.0f", mgl, mlsp ) ;
  TString susycut( susycutstring ) ;
  if ( mgl>0. && mlsp>0. ) {
     nAdded = chainT1bbbb.Add("files5fb_MT/T1bbbb.root") ;
     if ( nAdded <= 0 ) {
        printf("\n\n\n *** No tree in files5fb_MT/T1bbbb.root\n\n\n") ;
        return ;
     }
     TFile f("referenceXSecs.root") ;
     TH1F* xsechist = (TH1F*) f.Get("gluino8TeV_NLONLL") ;
     if ( xsechist==0x0 ) { printf("\n\n *** can't find reference Xsec histogram in referenceXSecs.root.\n\n") ; return ; }
     int theBin = xsechist->FindBin( mgl ) ;
     if ( theBin <=0 || theBin > xsechist->GetNbinsX() ) {
        printf("\n\n *** can't find bin for mgl=%g.  Returned %d\n\n", mgl, theBin ) ;
        return ;
     }
     double xsec = xsechist->GetBinContent( theBin ) ;
     printf("\n\n T1bbbb xsec for mgl=%g is %g\n\n", mgl, xsec ) ;
     t1bbbbWeight = 1.5*xsec ;  //in pb. scan has 10k events, so nScan*1.5*xsec = events in 15fb-1
     //////  t1bbbbWeight = 0.1*xsec ;  //in pb. T1tttt scan has 50k events, so nScan*0.1*xsec = events in 5fb-1
     printf("\n\n Susy ttree cut: %s\n\n", susycutstring ) ;
  }


  TChain chainQCD("tree") ;
   //--- these have high weight
//chainQCD.Add("files15fb_8TeV/QCD-50to80.root");
//chainQCD.Add("files15fb_8TeV/QCD-80to120.root");
  chainQCD.Add("files15fb_8TeV/QCD-120to170.root");
  chainQCD.Add("files15fb_8TeV/QCD-170to300.root");
   //--- below here, these have weight less than one.
  chainQCD.Add("files15fb_8TeV/QCD-300to470.root");
  chainQCD.Add("files15fb_8TeV/QCD-470to600.root");
  chainQCD.Add("files15fb_8TeV/QCD-600to800.root");
  chainQCD.Add("files15fb_8TeV/QCD-800to1000.root");
  chainQCD.Add("files15fb_8TeV/QCD-1000to1400.root");
  chainQCD.Add("files15fb_8TeV/QCD-1400to1800.root");
  chainQCD.Add("files15fb_8TeV/QCD-1800.root");

  TChain chainTT("tree") ;
  chainTT.Add("files15fb_8TeV/TT.root") ;

  TChain chainZnn("tree") ;
  chainZnn.Add("files15fb_8TeV/Zinv-100to200.root") ;
  chainZnn.Add("files15fb_8TeV/Zinv-200to400.root") ;
  chainZnn.Add("files15fb_8TeV/Zinv-400.root") ;

  TChain chainWJets("tree") ;
  chainWJets.Add("files15fb_8TeV/WJets-250to300.root") ;
  chainWJets.Add("files15fb_8TeV/WJets-300to400.root") ;
  chainWJets.Add("files15fb_8TeV/WJets-400.root") ;
  chainWJets.Add("files15fb_8TeV/T-s.root") ;
  chainWJets.Add("files15fb_8TeV/T-t.root") ;
  chainWJets.Add("files15fb_8TeV/T-tW.root") ;
  chainWJets.Add("files15fb_8TeV/Tbar-s.root") ;
  chainWJets.Add("files15fb_8TeV/Tbar-t.root") ;
  chainWJets.Add("files15fb_8TeV/Tbar-tW.root") ;



      char qcdinputfile[9][1000] = {
        "files15fb_8TeV/QCD-120to170.root"
       ,"files15fb_8TeV/QCD-170to300.root"
       ,"files15fb_8TeV/QCD-300to470.root"
       ,"files15fb_8TeV/QCD-470to600.root"
       ,"files15fb_8TeV/QCD-600to800.root"
       ,"files15fb_8TeV/QCD-800to1000.root"
       ,"files15fb_8TeV/QCD-1000to1400.root"
       ,"files15fb_8TeV/QCD-1400to1800.root"
       ,"files15fb_8TeV/QCD-1800.root"
      } ;

      char qcdsamplename[9][100] = {
        "qcd_0120_to_0170"
       ,"qcd_0170_to_0300"
       ,"qcd_0300_to_0470"
       ,"qcd_0470_to_0600"
       ,"qcd_0600_to_0800"
       ,"qcd_0800_to_1000"
       ,"qcd_1000_to_1400"
       ,"qcd_1400_to_1800"
       ,"qcd_1800_to_9999"
      } ;



  gROOT->Reset();

  const int nBinsBjets = 4 ;
  const int nJetsCut = 3 ;     // #jets >= nJetsCut

//be careful because this is hard coded now in SmallTree::Loop
  double minLeadJetPt = 70. ;
  double min3rdJetPt = 50. ;
  
  bool doPUreweighting = false;

  //-- met2-ht1-v1
//const int nBinsMET   = 2 ;
//const int nBinsHT    = 1 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,250.,99999.};
//float Hbins[nBinsHT+1] = {400.,99999.};

//-- met2-ht2-v1
//const int nBinsMET   = 2 ;
//const int nBinsHT    = 2 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,250.,99999.};
//float Hbins[nBinsHT+1] = {400.,600.,99999.};

////-- met2-ht8-v1
//const int nBinsMET   = 2 ;
//const int nBinsHT    = 8 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,250.,99999.};
//float Hbins[nBinsHT+1] = {400.,500.,600.,700.,800.,900.,1000.,1200.,99999.};

  //-- met3-ht2-v1
//const int nBinsMET   = 3 ;
//const int nBinsHT    = 2 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,250.,350.,99999.};
//float Hbins[nBinsHT+1] = {400.,800.,99999.};

////-- met3-ht3-v1
//const int nBinsMET   = 3 ;
//const int nBinsHT    = 3 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,250.,350.,99999.};
//float Hbins[nBinsHT+1] = {400.,600.,1000.,99999.};

////-- met3-ht3-v5
//    const int nBinsMET = 3 ;
//    const int nBinsHT  = 3 ;
//    const int version = 5;
//    float Mbins[nBinsMET+1] = { 125, 200,  350, 99999. } ;
//    float Hbins[nBinsHT+1]  = { 400, 600, 1000, 99999. } ;

////-- met3-ht3-v2
//const int nBinsMET   = 3 ;
//const int nBinsHT    = 3 ;
//    const int version = 2;
//float Mbins[nBinsMET+1] = {150.,250.,350.,99999.};
//float Hbins[nBinsHT+1] = {300.,500.,1000.,99999.};

////-- met3-ht4-v1
//const int nBinsMET   = 3 ;
//const int nBinsHT    = 4 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,250.,350.,99999.};
//float Hbins[nBinsHT+1] = {200, 300.,500.,1000.,99999.};

////-- met3-ht5-v1
//const int nBinsMET   = 3 ;
//const int nBinsHT    = 5 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,250.,350.,99999.};
//float Hbins[nBinsHT+1] = {400.,500.,600.,800.,1000.,99999.};

////-- met4-ht3-v1
//const int nBinsMET   = 4 ;
//const int nBinsHT    = 3 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,250.,350.,500.,99999.};
//float Hbins[nBinsHT+1] = {400.,600.,1000.,99999.};

////-- met4-ht3-v2
//const int nBinsMET   = 4 ;
//const int nBinsHT    = 3 ;
//    const int version = 2;
//float Mbins[nBinsMET+1] = {125, 150.,250.,350.,99999.};
//float Hbins[nBinsHT+1] = {300.,500.,1000.,99999.};

  //-- met5-ht4-v1
//const int nBinsMET   = 5 ;
//const int nBinsHT    = 4 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,200.,250.,300.,350.,99999.};
//float Hbins[nBinsHT+1] = {400.,600.,800.,1000.,99999.};

////-- met4-ht4-v1
//    const int nBinsMET   = 4 ;
//    const int nBinsHT    = 4 ;
//    const int version = 1;
//    float Mbins[nBinsMET+1] = {150.,200.,250.,300.,99999.};
//    float Hbins[nBinsHT+1] = {400.,500.,600.,800.,99999.};

  //-- met4-ht4-v2
//    const int nBinsMET   = 4 ;
//    const int nBinsHT    = 4 ;
//    const int version = 2;
//    float Mbins[nBinsMET+1] = {150.,250.,350.,450.,99999.};
//    float Hbins[nBinsHT+1] = {400.,500.,600.,800.,99999.};

  //-- met4-ht4-v3
//    const int nBinsMET   = 4 ;
//    const int nBinsHT    = 4 ;
//    const int version = 3;
//    float Mbins[nBinsMET+1] = {150.,200.,250.,300.,99999.};
//    float Hbins[nBinsHT+1] = {400.,600.,800.,1000.,99999.};

  //-- met4-ht4-v4
//    const int nBinsMET   = 4 ;
//    const int nBinsHT    = 4 ;
//    const int version = 4;
//    float Mbins[nBinsMET+1] = {150.,250.,350.,450.,99999.};
//    float Hbins[nBinsHT+1] = {400.,600.,800.,1000.,99999.};

  //-- met4-ht4-v5
//    const int nBinsMET   = 4 ;
//    const int nBinsHT    = 4 ;
//    const int version = 5;
//    float Mbins[nBinsMET+1] = {150.,175.,200.,400.,99999.};
//    float Hbins[nBinsHT+1] = {400.,450.,550.,850.,99999.};

  //-- met4-ht4-v6
//    const int nBinsMET   = 4 ;
//    const int nBinsHT    = 4 ;
//    const int version = 6;
//    float Mbins[nBinsMET+1] = {150.,200.,350.,450.,99999.};
//    float Hbins[nBinsHT+1] = {400.,550.,800.,950.,99999.};

////-- met4-ht4-v7
//const int nBinsMET   = 4 ;
//const int nBinsHT    = 4 ;
//    const int version = 7;
//float Mbins[nBinsMET+1] = {125, 150.,250.,350.,99999.};
//float Hbins[nBinsHT+1] = {200, 300.,500.,1000.,99999.};

  //-- met4-ht4-v15
      const int nBinsMET   = 4 ;
      const int nBinsHT    = 4 ;
      const int version = 15;
      float Mbins[nBinsMET+1] = {125.,150.,250.,350.,99999.};
      float Hbins[nBinsHT+1] = {400.,500.,800.,1000.,99999.};

////-- met4-ht5-v1
//const int nBinsMET   = 4 ;
//const int nBinsHT    = 5 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,200.,300.,400.,99999.};
//float Hbins[nBinsHT+1] = {400.,600.,800.,1000.,1200.,99999.};

////-- met5-ht5-v1
//const int nBinsMET   = 5 ;
//const int nBinsHT    = 5 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,200.,250.,300.,350.,99999.};
//float Hbins[nBinsHT+1] = {400.,500.,600.,800.,1000.,99999.};

////-- met5-ht3-v1
//const int nBinsMET   = 5 ;
//const int nBinsHT    = 3 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,200.,250.,300.,350.,99999.};
//float Hbins[nBinsHT+1] = {400.,600.,1000.,99999.};

////-- met5-ht3-v2
//const int nBinsMET   = 5 ;
//const int nBinsHT    = 3 ;
//    const int version = 2;
//float Mbins[nBinsMET+1] = {150.,175.,200.,350.,450.,99999.};
//float Hbins[nBinsHT+1] = {400.,550.,800.,99999.};

  //-- met6-ht6-v1
//const int nBinsMET   = 6 ;
//const int nBinsHT    = 6 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,200.,250.,300.,350.,400.,99999.};
//float Hbins[nBinsHT+1] = {400.,500.,600.,700.,800.,900.,99999.};

  //-- met7-ht7-v1
//const int nBinsMET   = 7 ;
//const int nBinsHT    = 7 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,200.,250.,300.,350.,400.,500.,99999.};
//float Hbins[nBinsHT+1] = {400.,500.,600.,700.,800.,900.,1000.,99999.};

////-- met8-ht8-v1
//const int nBinsMET   = 8 ;
//const int nBinsHT    = 8 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,200.,250.,300.,350.,400.,450.,600.,99999.};
//float Hbins[nBinsHT+1] = {400.,500.,600.,700.,800.,900.,1000.,1200.,99999.};

////-- met8-ht2-v1
//const int nBinsMET   = 8 ;
//const int nBinsHT    = 2 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,200.,250.,300.,350.,400.,450.,600.,99999.};
//float Hbins[nBinsHT+1] = {400.,600.,99999.};



  TString sMbins[nBinsMET];
  TString sHbins[nBinsHT];
  TString sBbins[nBinsBjets] = {"_1b","_2b","_3b","_4b"};

  TString cMbins[nBinsMET];
  TString cHbins[nBinsHT];

  for (int i = 0 ; i < nBinsMET ; i++) {
    TString base = "_M";
    stringstream sbin;
    sbin << i+1;
    base += sbin.str();
    sMbins[i] = base;
    base = "&&MET>";
    stringstream cbin;
    cbin << Mbins[i] << "&&MET<" << Mbins[i+1];
    base += cbin.str();
    cMbins[i] = base;
  }

  for (int j = 0 ; j < nBinsHT ; j++) {
    TString base = "_H";
    stringstream sbin;
    sbin << j+1;
    base += sbin.str();
    sHbins[j] = base;
    base = "&&HT>";
    stringstream cbin;
    cbin << Hbins[j] << "&&HT<" << Hbins[j+1];
    base += cbin.str();
    cHbins[j] = base;
  }

  TString leadJetPtCutString ;
  {
     leadJetPtCutString = "(pt_1st_leadJet>" ;
     stringstream number ;
     number << minLeadJetPt ;
     stringstream number2 ;
     number2 << min3rdJetPt ;
     leadJetPtCutString += number.str() ;
     leadJetPtCutString += "&&pt_2nd_leadJet>" ;
     leadJetPtCutString += number.str() ;
     leadJetPtCutString += "&&pt_3rd_leadJet>" ;
     leadJetPtCutString += number2.str() ;
     leadJetPtCutString += ")" ;
  }

//int dummyInt = 99;
//float dummyFloat = 9.999;
  float dummyZero = 0.;
  float dummyOne = 1.0;
  float dummyPoint999 = 0.999 ;
  float dummyErr = 0.1;

  float sl_frac2b_val[nBinsMET][nBinsHT];
  float sl_frac2b_err[nBinsMET][nBinsHT];
  float sl_frac3b_val[nBinsMET][nBinsHT];
  float sl_frac3b_err[nBinsMET][nBinsHT];
  float sl_frac4b_val[nBinsMET][nBinsHT];
  float sl_frac4b_err[nBinsMET][nBinsHT];


  ofstream inFile;
  char outfile[10000] ;
  if ( mgl > 0. && mlsp > 0. ) {
     if ( target_susy_all0lep > 0. ) {
        sprintf( outfile, "InputWT1bbbb-nb4-mgl%.0f-mlsp%.0f-%.0fevts-met%d-ht%d-v%d.dat", mgl, mlsp, target_susy_all0lep, nBinsMET, nBinsHT, version  ) ;
     } else {
        sprintf( outfile, "InputWT1bbbb-nb4-mgl%.0f-mlsp%.0f-met%d-ht%d-v%d.dat", mgl, mlsp, nBinsMET, nBinsHT, version  ) ;
     }
  } else {
     sprintf( outfile, "Input-nb4-met%d-ht%d-v%d.dat", nBinsMET, nBinsHT, version  ) ;
  }
  inFile.open( outfile );

  // print out header line:

  inFile << "Using HT bins:  " ;
  for (int j = 0 ; j <= nBinsHT ; j++ ) {
    inFile << Hbins[j] ;
    if ( j < nBinsHT ) inFile << "-" ;
  }

  inFile << "\t Using MET bins: " ;
  for (int i = 0 ; i <= nBinsMET ; i++ ) {
    inFile << Mbins[i] ;
    if ( i < nBinsMET ) inFile << "-" ;
  }
  
  inFile << endl ;


   int nSel(3) ;
   char selname[3][100] = { "0lep", "1lep", "ldp" } ;

   char selcuts[3][10000] = {
        "minDelPhiN>4&&nMu==0&&nEl==0&&",
        "minDelPhiN>4&&( (nMu==1&&nEl==0) || (nMu==0&&nEl==1) )&&",
        "minDelPhiN<4&&nMu==0&&nEl==0&&" } ;


  //--- Output histograms.

   TH1F* hmctruth_susy [3][4] ;
   TH1F* hmctruth_ttwj [3][4] ;
   TH1F* hmctruth_ttbar[3][4] ;
   TH1F* hmctruth_wjets[3][4] ;
   TH1F* hmctruth_qcd  [3][4] ;
   TH1F* hmctruth_znn  [3][4] ;
   TH1F* hmctruth_allsm[3][4] ;
   TH1F* hmctruth_all  [3][4] ;

   for ( int si=0; si<nSel; si++ ) {
      for ( int bbi=0; bbi<nBinsBjets; bbi++ ) {

         char hname[1000] ;
         char htitle[1000] ;
         sprintf( htitle, "%s, %d btag", selname[si], bbi+1 ) ;

         sprintf( hname, "hmctruth_susy_%s_%db", selname[si], bbi+1 ) ;
         hmctruth_susy[si][bbi] = bookHist( hname, htitle, selname[si], bbi+1, nBinsMET, nBinsHT ) ;

         sprintf( hname, "hmctruth_ttwj_%s_%db", selname[si], bbi+1 ) ;
         hmctruth_ttwj[si][bbi] = bookHist( hname, htitle, selname[si], bbi+1, nBinsMET, nBinsHT ) ;

         sprintf( hname, "hmctruth_ttbar_%s_%db", selname[si], bbi+1 ) ;
         hmctruth_ttbar[si][bbi] = bookHist( hname, htitle, selname[si], bbi+1, nBinsMET, nBinsHT ) ;

         sprintf( hname, "hmctruth_wjets_%s_%db", selname[si], bbi+1 ) ;
         hmctruth_wjets[si][bbi] = bookHist( hname, htitle, selname[si], bbi+1, nBinsMET, nBinsHT ) ;

         sprintf( hname, "hmctruth_qcd_%s_%db", selname[si], bbi+1 ) ;
         hmctruth_qcd[si][bbi] = bookHist( hname, htitle, selname[si], bbi+1, nBinsMET, nBinsHT ) ;

         sprintf( hname, "hmctruth_znn_%s_%db", selname[si], bbi+1 ) ;
         hmctruth_znn[si][bbi] = bookHist( hname, htitle, selname[si], bbi+1, nBinsMET, nBinsHT ) ;

         sprintf( hname, "hmctruth_allsm_%s_%db", selname[si], bbi+1 ) ;
         hmctruth_allsm[si][bbi] = bookHist( hname, htitle, selname[si], bbi+1, nBinsMET, nBinsHT ) ;

         sprintf( hname, "hmctruth_all_%s_%db", selname[si], bbi+1 ) ;
         hmctruth_all[si][bbi] = bookHist( hname, htitle, selname[si], bbi+1, nBinsMET, nBinsHT ) ;


      } // bbi.
   } // si.




     TH1F* hmctruth_fit_zee_1b  = bookHist("hmctruth_fit_zee_1b" , "Zee" , "Zee", 1, nBinsMET, nBinsHT ) ;
     TH1F* hmctruth_fit_zmm_1b  = bookHist("hmctruth_fit_zmm_1b" , "Zmm" , "Zmm", 1, nBinsMET, nBinsHT ) ;






  //--- histograms used in getting the observables.

    TH2F* h_tt[10] ;
    TH2F* h_wjets[10] ;
    TH2F* h_qcd[10] ;
    TH2F* h_znn[10] ;
    TH2F* h_susy[10] ;
    TH2F* h_mc[10] ;

    for ( int bi=0; bi<nBinsBjets; bi++ ) {

       char hname[100] ;

       sprintf( hname, "h_tt_%db", bi+1 ) ;
       h_tt[bi]   = new TH2F( hname, hname , nBinsMET, Mbins, nBinsHT, Hbins ) ;
       h_tt[bi] -> Sumw2() ;

       sprintf( hname, "h_wjets_%db", bi+1 ) ;
       h_wjets[bi]   = new TH2F( hname, hname , nBinsMET, Mbins, nBinsHT, Hbins ) ;
       h_wjets[bi] -> Sumw2() ;

       sprintf( hname, "h_qcd_%db", bi+1 ) ;
       h_qcd[bi]  = new TH2F( hname, hname , nBinsMET, Mbins, nBinsHT, Hbins ) ;
       h_qcd[bi] -> Sumw2() ;

       sprintf( hname, "h_znn_%db", bi+1 ) ;
       h_znn[bi]  = new TH2F( hname, hname , nBinsMET, Mbins, nBinsHT, Hbins ) ;
       h_znn[bi] -> Sumw2() ;

       sprintf( hname, "h_susy_%db", bi+1 ) ;
       h_susy[bi] = new TH2F( hname, hname , nBinsMET, Mbins, nBinsHT, Hbins ) ;
       h_susy[bi] -> Sumw2() ;

       sprintf( hname, "h_mc_%db", bi+1 ) ;
       h_mc[bi]   = new TH2F( hname, hname , nBinsMET, Mbins, nBinsHT, Hbins ) ;
       h_mc[bi] -> Sumw2() ;

    }

  float nSusyTotal = 0;

  for ( int si=0 ; si<nSel ; si++ ) {


  printf("\n\n-----------------------------------------------------------------\n\n") ;

      for (int k = 0 ; k < nBinsBjets ; k++) {

        char allcuts[10000] ;
        char allsusycuts[10000] ;

        if ( k < (nBinsBjets-1) ) {
          sprintf( allcuts, "%snB==%d&&nJets>=%d&&(pt_1st_leadJet>%.0f&&pt_2nd_leadJet>%.0f&&pt_3rd_leadJet>%.0f)", selcuts[si], k+1, nJetsCut, minLeadJetPt, minLeadJetPt, min3rdJetPt ) ;
          sprintf( allsusycuts, "%snB==%d&&nJets>=%d&&(pt_1st_leadJet>%.0f&&pt_2nd_leadJet>%.0f&&pt_3rd_leadJet>%.0f)%s", selcuts[si], k+1, nJetsCut, minLeadJetPt, minLeadJetPt, min3rdJetPt, susycut.Data() ) ;
        } else {
          sprintf( allcuts, "%snB>=%d&&nJets>=%d&&(pt_1st_leadJet>%.0f&&pt_2nd_leadJet>%.0f&&pt_3rd_leadJet>%.0f)", selcuts[si], k+1, nJetsCut, minLeadJetPt, minLeadJetPt, min3rdJetPt ) ;
          sprintf( allsusycuts, "%snB>=%d&&nJets>=%d&&(pt_1st_leadJet>%.0f&&pt_2nd_leadJet>%.0f&&pt_3rd_leadJet>%.0f)%s", selcuts[si], k+1, nJetsCut, minLeadJetPt, minLeadJetPt, min3rdJetPt, susycut.Data() ) ;
        }


        printf("\n\n N_%s -- nbjet bin (%d): cuts=%s\n\n", selname[si], k, allcuts) ; cout << flush ;

        char hname[100] ;
        sprintf( hname, "h_tt_%db", k+1 ) ;
        if(doPUreweighting) FillHTMET(&chainTT, h_tt[k], si, k);
	else chainTT.Project (hname,"HT:MET",allcuts);
	printf("    %12s %9.1f events\n", hname, h_tt[k]->Integral() ) ; cout << flush ;

        sprintf( hname, "h_wjets_%db", k+1 ) ;
        if(doPUreweighting) FillHTMET(&chainWJets, h_wjets[k], si, k);
	else chainWJets.Project(hname,"HT:MET",allcuts);
	printf("    %12s %9.1f events\n", hname, h_wjets[k]->Integral() ) ; cout << flush ;

        sprintf( hname, "h_qcd_%db", k+1 ) ;
        if (doPUreweighting) FillHTMET(&chainQCD, h_qcd[k], si, k);
	else chainQCD.Project(hname,"HT:MET",allcuts);
	printf("    %12s %9.1f events\n", hname, h_qcd[k]->Integral() ) ; cout << flush ;

        sprintf( hname, "h_znn_%db", k+1 ) ;
        if (doPUreweighting) FillHTMET(&chainZnn, h_znn[k], si, k);
	else chainZnn.Project(hname,"HT:MET",allcuts);
	printf("    %12s %9.1f events\n", hname, h_znn[k]->Integral() ) ; cout << flush ;
        if ( mgl > 0. ) {
           sprintf( hname, "h_susy_%db", k+1 ) ;
           chainT1bbbb.Project(hname,"HT:MET",allsusycuts);
           h_susy[k]->Scale( t1bbbbWeight ) ;
           printf("    %12s %9.1f events\n", hname, h_susy[k]->Integral() ) ; cout << flush ;
	   if (si==0) nSusyTotal += h_susy[k]->Integral();
        }
      } // k
      if (si==0) printf("N_Susy_Total = %9.1f events", nSusyTotal); cout << flush;
      printf("\n\n") ;


      for (int i = 0 ; i < nBinsMET ; i++) {
        for (int j = 0 ; j < nBinsHT ; j++) {
          for (int k = 0 ; k < nBinsBjets ; k++) {


             char obsname[1000] ;
             sprintf( obsname, "N_%s_M%d_H%d_%db", selname[si], i+1, j+1, k+1 ) ;


             double ttval = h_tt[k] -> GetBinContent( i+1, j+1 ) ;
             double tterr = h_tt[k] -> GetBinError(   i+1, j+1 ) ;

             double wjetsval = h_wjets[k] -> GetBinContent( i+1, j+1 ) ;
             double wjetserr = h_wjets[k] -> GetBinError(   i+1, j+1 ) ;

             double qcdval = h_qcd[k] -> GetBinContent( i+1, j+1 ) ;
             double qcderr = h_qcd[k] -> GetBinError(   i+1, j+1 ) ;

             double znnval = h_znn[k] -> GetBinContent( i+1, j+1 ) ;
             double znnerr = h_znn[k] -> GetBinError(   i+1, j+1 ) ;

             double susyval = h_susy[k] -> GetBinContent( i+1, j+1 ) ;
             double susyerr = h_susy[k] -> GetBinError(   i+1, j+1 ) ;

             printf(" N_%s, tt     met,ht,nbjet bin (%d,%d,%d)  --  npass=%7.1f +/- %6.1f\n", selname[si], i,j,k, ttval,tterr) ; cout << flush ;
             printf(" N_%s, wjets  met,ht,nbjet bin (%d,%d,%d)  --  npass=%7.1f +/- %6.1f\n", selname[si], i,j,k, wjetsval,wjetserr) ; cout << flush ;
             printf(" N_%s, qcd    met,ht,nbjet bin (%d,%d,%d)  --  npass=%7.1f +/- %6.1f\n", selname[si], i,j,k, qcdval,qcderr) ; cout << flush ;
             printf(" N_%s, znn    met,ht,nbjet bin (%d,%d,%d)  --  npass=%7.1f +/- %6.1f\n", selname[si], i,j,k, znnval,znnerr) ; cout << flush ;
             if ( mgl>0. ) {
                if ( target_susy_all0lep > 0. ) {
                   susyval = susyval * (target_susy_all0lep/nSusyTotal);
                   susyerr = susyerr * (target_susy_all0lep/nSusyTotal);
                }
                printf(" N_%s, susy   met,ht,nbjet bin (%d,%d,%d)  --  npass=%7.1f +/- %6.1f\n", selname[si], i,j,k, susyval,susyerr) ; cout << flush ;
             }
             printf("\n") ;

             double allval = ttval + wjetsval + qcdval + znnval + susyval ;

             //// inFile << obsname << "  \t" << (int)allval << endl;
             inFile << obsname << "  \t" << allval << endl;

             int histbin = 1 + (nBinsHT+1)*i + j + 1 ;

             hmctruth_ttwj[si][k]  -> SetBinContent( histbin, ttval + wjetsval  ) ;
             hmctruth_ttwj[si][k]  -> SetBinError(   histbin, sqrt( pow(tterr,2) + pow(wjetserr,2) )  ) ;
             hmctruth_ttbar[si][k] -> SetBinContent( histbin, ttval ) ;
             hmctruth_ttbar[si][k] -> SetBinError(   histbin, tterr ) ;
             hmctruth_wjets[si][k] -> SetBinContent( histbin, wjetsval  ) ;
             hmctruth_wjets[si][k] -> SetBinError(   histbin, wjetserr  ) ;
             hmctruth_qcd[si][k]   -> SetBinContent( histbin, qcdval ) ;
             hmctruth_qcd[si][k]   -> SetBinError(   histbin, qcderr ) ;
             hmctruth_znn[si][k]   -> SetBinContent( histbin, znnval ) ;
             hmctruth_znn[si][k]   -> SetBinError(   histbin, znnerr ) ;
             hmctruth_susy[si][k]  -> SetBinContent( histbin, susyval  ) ;
             hmctruth_susy[si][k]  -> SetBinError(   histbin, susyerr  ) ;
             hmctruth_allsm[si][k] -> SetBinContent( histbin, ttval+wjetsval+qcdval+znnval ) ;
             hmctruth_allsm[si][k] -> SetBinError(   histbin, sqrt( pow(tterr,2) + pow(wjetserr,2) + pow(qcderr,2) + pow(znnerr,2) ) ) ;
             hmctruth_all[si][k]   -> SetBinContent( histbin, ttval+wjetsval+qcdval+znnval+susyval ) ;
             hmctruth_all[si][k]   -> SetBinError(   histbin, sqrt( pow(tterr,2) + pow(wjetserr,2) + pow(qcderr,2) + pow(znnerr,2) + pow(susyerr,2) ) ) ;


	     // compute fractions of SL 2b/1b and 3b/1b

	     if ( si == 1 && k > 0 ) {

	       double ttval_1b = h_tt[0] -> GetBinContent( i+1, j+1 ) ;
	       double wjetsval_1b = h_wjets[0] -> GetBinContent( i+1, j+1 ) ;

	       double ttwjval = ttval + wjetsval ;
	       double ttwjval_1b = ttval_1b + wjetsval_1b ;

	       if ( k == 1 ) {
		 sl_frac2b_val[i][j] = ( ttwjval ) / ( ttwjval_1b ) ;
		 sl_frac2b_err[i][j] = 0.01 ;   // start with arbitrary errors, first
	       }

	       if ( k == 2 ) {
		 sl_frac3b_val[i][j] = ( ttwjval ) / ( ttwjval_1b ) ;
		 sl_frac3b_err[i][j] = 0.01 ;   // start with arbitrary errors, first
	       }

	       if ( k == 3 ) {
		 sl_frac4b_val[i][j] = ( ttwjval ) / ( ttwjval_1b ) ;
		 sl_frac4b_err[i][j] = 0.01 ;   // start with arbitrary errors, first
	       }

	     }

            } // k
          } // j
        } // i



          for (int k = 0 ; k < nBinsBjets ; k++) {
             h_tt[k] -> Reset() ;
             h_wjets[k] -> Reset() ;
             h_qcd[k] -> Reset() ;
             h_znn[k] -> Reset() ;
             h_susy[k] -> Reset() ;
          }


     } // si.




     //--- Insert dummy R_lsb lines for backwards compatibility.
     for ( int hbi=0; hbi<nBinsHT; hbi++ ) {
        for ( int bbi=0; bbi<nBinsBjets; bbi++ ) {
           char dummyline[1000] ;
           sprintf( dummyline, "R_lsb_H%d_%db       0.1", hbi+1, bbi+1 ) ;
           inFile << dummyline << endl ;
           sprintf( dummyline, "R_lsb_H%d_%db_err   0.01", hbi+1, bbi+1 ) ;
           inFile << dummyline << endl ;
        } // bbi.
     } // hbi.





    printf("\n\n-----------------------------------------------------------------\n\n") ; cout << flush ;

    { //--- scoping bracket for QCD chunk.

    //--- Fill histograms to be used in QCD analysis (done in mcclosure4.c).

      const int nQcdSamples(9) ;

      TCanvas* cqcd = new TCanvas("cqcd","QCD") ;

      TH2F*   h0lep[nQcdSamples][nBinsBjets] ;
      TH2F*   hldp [nQcdSamples][nBinsBjets] ;

      TChain* qcdch[nQcdSamples] ;

      char hname[1000] ;
      char htitle[1000] ;

      TH2F* hdummy = new TH2F("hdummy","",2, Mbins[0], 1500., 2, Hbins[0], 1500. ) ;

         printf("\n\n") ;
         for ( int si=0; si<nQcdSamples; si++ ) {

            qcdch[si] = new TChain("tree") ;
            printf(" %2d : connecting to %s\n", si, qcdinputfile[si] ) ;
            qcdch[si] -> Add( qcdinputfile[si] ) ;

            for ( int bbi=0; bbi<nBinsBjets; bbi++ ) {

               sprintf( hname, "h_0lep_%db_%s", bbi+1, qcdsamplename[si] ) ;
               sprintf( htitle, "QCD 0lep yield, nb=%d, %s", bbi+1, qcdsamplename[si] ) ;
               printf("         booking hist %s : %s\n", hname, htitle ) ;
               h0lep[si][bbi] = new TH2F( hname, htitle, nBinsMET, Mbins, nBinsHT, Hbins ) ;
               h0lep[si][bbi] -> Sumw2() ;
               sprintf( hname, "h_ldp_%db_%s", bbi+1, qcdsamplename[si] ) ;
               sprintf( htitle, "QCD  LDP yield, nb=%d, %s", bbi+1, qcdsamplename[si] ) ;
               printf("         booking hist %s  : %s\n", hname, htitle ) ;
               hldp [si][bbi] = new TH2F( hname, htitle, nBinsMET, Mbins, nBinsHT, Hbins ) ;
               hldp [si][bbi] -> Sumw2() ;

            } // bbi.

         } // si.
         printf("\n\n") ;


         char bcut[4][100] = { "nB==1", "nB==2", "nB==3", "nB>=4" } ;

         for ( int si=0; si<nQcdSamples; si++ ) {

            printf(" %2d : %s : 0lep\n", si, qcdsamplename[si] ) ; cout << flush ;
            for ( int bbi=0; bbi<nBinsBjets; bbi++ ) {

               char arg1[1000] ;

               char cuts0lep[10000] ;
               sprintf( cuts0lep, "%s(%s)&&nJets>=%d&&(pt_1st_leadJet>%.0f&&pt_2nd_leadJet>%.0f&&pt_3rd_leadJet>%.0f)", selcuts[0], bcut[bbi], nJetsCut, minLeadJetPt, minLeadJetPt, min3rdJetPt ) ;
               printf("     %db, 0lep cuts : %s\n", bbi+1, cuts0lep ) ;
               sprintf( arg1, "HT:MET>>h_0lep_%db_%s", bbi+1, qcdsamplename[si] ) ;
               qcdch[si] -> Draw( arg1, cuts0lep ) ;
               hdummy->Draw() ;
               h0lep[si][bbi]->Draw("samecolz") ;
               cqcd->Update() ; cqcd->Draw() ;


               char cutsldp[10000] ;
               sprintf( cutsldp, "%s(%s)&&nJets>=%d&&(pt_1st_leadJet>%.0f&&pt_2nd_leadJet>%.0f&&pt_3rd_leadJet>%.0f)", selcuts[2], bcut[bbi], nJetsCut, minLeadJetPt, minLeadJetPt, min3rdJetPt ) ;
               printf("     %db, ldp  cuts : %s\n", bbi+1, cutsldp  ) ;
               sprintf( arg1, "HT:MET>>h_ldp_%db_%s", bbi+1, qcdsamplename[si] ) ;
               qcdch[si] -> Draw( arg1, cutsldp, "colz" ) ;
               hdummy->Draw() ;
               hldp[si][bbi]->Draw("samecolz") ;
               cqcd->Update() ; cqcd->Draw() ;

            } // bbi.

         } // si.

    } //--- scoping bracket for QCD chunk.

    printf("\n\n-----------------------------------------------------------------\n\n") ; cout << flush ;
  
    // Z -> ee observables 
  
    TH1F* ht = new TH1F("ht","ht",10,0,10000);
  
    ht -> Sumw2() ;

    TString cutszee = "cat==2&&minDelPhiNee>4&&nVLB>=1&&nJets>=";
    stringstream njcut ; njcut << nJetsCut ;
    cutszee += njcut.str();
    cutszee += "&&";

    for (int i = 0 ; i < nBinsMET ; i++) {
      for (int j = 0 ; j < nBinsHT ; j++) {
  
        TString obs_Zee = "N_Zee" ;
        obs_Zee = obs_Zee+sMbins[i]+sHbins[j] ;
        
        TString cut = "HT>";  
        cut += Hbins[j];
        cut += "&&HT<";
        cut += Hbins[j+1];
        cut += "&&METee>";
        cut += Mbins[i];
        cut += "&&METee<";
        cut += Mbins[i+1];
  
        TString allcutsZ = cutszee+cut ;
        allcutsZ += "&&" ;
        allcutsZ += leadJetPtCutString ;
  
        dyTree->Project("ht","HT",allcutsZ);
        double allerr(0.) ;
        double allval = ht->IntegralAndError(1,10,allerr) ;
        printf(" N_Zee -- HT,MET bins (%d,%d): events=%7.1f +/- %6.1f, cuts=%s\n", j,i,allval,allerr,allcutsZ.Data() ) ; cout << flush ;
          ht->Reset() ;
  
        ////// inFile << obs_Zee << "  \t" << (int)allval << endl;
        inFile << obs_Zee << "  \t" << allval << endl;

        //Z->ee counts, with 1 VLb and sig selection, so so MET>250, HT>400, mindelphi>4, 2e, 0mu, nJets >= 3
  
        int histbin = 1 + (nBinsHT+1)*i + j + 1 ;
  
        hmctruth_fit_zee_1b -> SetBinContent( histbin, allval ) ;
        hmctruth_fit_zee_1b -> SetBinError(   histbin, allerr ) ;
  
      }
    }
  
    
    printf("\n\n-----------------------------------------------------------------\n\n") ; cout << flush ;
  
    // Z -> mm observables
  
    TString cutszmm = "cat==1&&minDelPhiNmm>4&&nVLB>=1&&nJets>=";
    cutszmm += njcut.str();
    cutszmm += "&&";

    for (int i = 0 ; i < nBinsMET ; i++) {
      for (int j = 0 ; j < nBinsHT ; j++) {
  
        TString obs_Zmm = "N_Zmm" ;
        obs_Zmm = obs_Zmm+sMbins[i]+sHbins[j] ;
        
        TString cut = "HT>";  
        cut += Hbins[j];
        cut += "&&HT<";
        cut += Hbins[j+1];
        cut += "&&METmm>";
        cut += Mbins[i];
        cut += "&&METmm<";
        cut += Mbins[i+1];
        
        TString allcutsZ = cutszmm+cut ;
        allcutsZ += "&&" ;
        allcutsZ += leadJetPtCutString ;
  
        dyTree->Project("ht","HT",allcutsZ);
        double allerr(0.) ;
        double allval = ht->IntegralAndError(1,10,allerr) ;
        printf(" N_Zmm -- HT,MET bins (%d,%d): events=%7.1f +/- %6.1f, cuts=%s\n", j,i,allval,allerr,allcutsZ.Data() ) ; cout << flush ;
          ht->Reset() ;
  
        ////// inFile << obs_Zmm << "  \t" << (int)allval << endl;
        inFile << obs_Zmm << "  \t" << allval << endl;

        //Z->mm counts, with 1 VLb and sig selection, so so MET>250, HT>400, mindelphi>4, 2mu, 0e, nJets >= 3
  
        int histbin = 1 + (nBinsHT+1)*i + j + 1 ;
  
        hmctruth_fit_zmm_1b -> SetBinContent( histbin, allval ) ;
        hmctruth_fit_zmm_1b -> SetBinError(   histbin, allerr ) ;
  
  
      }
    }
  
    //inFile << "Why are all three of these MC categories separate? I've just put them together (only QCD, Zinv, tt)" << endl;
    // Nttbarsingletopzjetsmc_ldp
  
  
    printf("\n\n-----------------------------------------------------------------\n\n") ; cout << flush ;

    //--- Owen : these MC inputs are no longer used.  Insert dummy values for backwards compatibility in format.

    for (int i = 0 ; i < nBinsMET ; i++) {
      for (int j = 0 ; j < nBinsHT ; j++) {
        for (int k = 0 ; k < nBinsBjets ; k++) {

           char obsname[1000] ;
           sprintf( obsname, "N_ttbarsingletopzjetsmc_ldp_M%d_H%d_%db", i+1, j+1, k+1 ) ;

           double val, err ;
           val = 0. ;
           err = 0. ;

           printf(" %s : %7.1f +/- %7.1f\n", obsname, val, err ) ;

           inFile << obsname << "  \t" << val << endl ;

        }
        printf("\n") ;
      }
      printf("\n") ;
    }

    // NWJmc_ldp
  
    for (int i = 0 ; i < nBinsMET ; i++) {
      for (int j = 0 ; j < nBinsHT ; j++) {
        for (int k = 0 ; k < nBinsBjets ; k++) {
  
  	TString obs_WJmc_ldp = "N_WJmc_ldp" ;
  	obs_WJmc_ldp = obs_WJmc_ldp+sMbins[i]+sHbins[j]+sBbins[k] ;
  	
  	inFile << obs_WJmc_ldp << "  \t" << dummyZero << endl;
  // signal selection, but ldp, so MET>250, HT>400, >=1 b, mindelphi<4, 0L, nJets >= 3
        }
      }
    }
  
  
    // NZnnmc_ldp
  
    for (int i = 0 ; i < nBinsMET ; i++) {
      for (int j = 0 ; j < nBinsHT ; j++) {
        for (int k = 0 ; k < nBinsBjets ; k++) {
  
  	TString obs_Znnmc_ldp = "N_Znnmc_ldp" ;
  	obs_Znnmc_ldp = obs_Znnmc_ldp+sMbins[i]+sHbins[j]+sBbins[k] ;
  	
  	inFile << obs_Znnmc_ldp << "  \t" << dummyZero << endl;
  // signal selection, but ldp, so MET>250, HT>400, >=1 b, mindelphi<4, 0L, nJets >= 3
        }
      }
    }
  
    printf("\n\n-----------------------------------------------------------------\n\n") ; cout << flush ;
  
    // various parameters needed for Z -> invis.
  
    // Z -> ee acceptance
  
    for (int i = 0 ; i < nBinsMET ; i++) {
  
      TString Zee_acc = "acc_Zee";
      Zee_acc = Zee_acc+sMbins[i];
  
      inFile << Zee_acc << "  \t" << dummyPoint999 << endl;
  
      Zee_acc = Zee_acc+"_err";
      inFile << Zee_acc << "  \t" << dummyErr << endl;
  
    }
  
  
    // Z -> mm acceptance
  
    for (int i = 0 ; i < nBinsMET ; i++) {
  
      TString Zmm_acc = "acc_Zmm";
      Zmm_acc = Zmm_acc+sMbins[i];
  
      inFile << Zmm_acc << "  \t" << dummyPoint999 << endl;
  
      Zmm_acc = Zmm_acc+"_err";
      inFile << Zmm_acc << "  \t" << dummyErr << endl;
  
    }
  
  
    // Z -> ll efficiencies
  
  // use 2011 values for now.
    inFile << "Z_ee_eff  \t" << 0.6774 << endl;
    inFile << "Z_ee_eff_err  \t" << 0.0580 << endl;
    inFile << "Z_mm_eff  \t" << 0.7217 << endl;
    inFile << "Z_mm_eff_err  \t" << 0.0506 << endl;
  
  
    // Z -> ee VL to nominal scale factors
  // would it make more sense to count events in only the loosest HT and/or MET bin and
  // use the scale factors to translate between the different HT and MET bins?

   //    for (int k = 0 ; k < nBinsBjets ; k++) {
   //    TString knn_ee = "knn_ee" ;
   //    knn_ee = knn_ee+sBbins[k] ;
   //    inFile << knn_ee << "  \t" << dummyOne << endl;
   //    knn_ee = knn_ee+"_err" ;
   //    inFile << knn_ee << "  \t" << dummyErr << endl;
   //  }
   //
   //
   //  // use 2011 values for now.
   //  inFile << "knn_1b     \t" << 0.401 << endl;
   //  inFile << "knn_1b_err \t" << 0.018 << endl;
   //  inFile << "knn_2b     \t" << 0.067 << endl;
   //  inFile << "knn_2b_err \t" << 0.009 << endl;
   //  inFile << "knn_3b     \t" << 0.009 << endl;
   //  inFile << "knn_3b_err \t" << 0.003 << endl;
   //

    // updated SF's to improve MC closure (the errors are the same as before)
    inFile << "knn_1b     \t" << 0.394  << endl;
    inFile << "knn_1b_err \t" << 0.018  << endl;
    inFile << "knn_2b     \t" << 0.0626 << endl;
    inFile << "knn_2b_err \t" << 0.009  << endl;
    inFile << "knn_3b     \t" << 0.0036 << endl;
    inFile << "knn_3b_err \t" << 0.003  << endl;
    inFile << "knn_4b     \t" << 0.00011 << endl;
    inFile << "knn_4b_err \t" << 0.00011  << endl;

    // Z -> ll purity
  
    // use 2011 values for now.
    inFile << "Z_ee_pur  \t" << 0.911 << endl;
    inFile << "Z_ee_pur_err  \t" << 0.079 << endl;
    inFile << "Z_mm_pur  \t" << 0.866 << endl;
    inFile << "Z_mm_pur_err  \t" << 0.079 << endl;
  
  
    // scale factors:
  
    inFile << "sf_mc  \t" << dummyOne << endl ; 
    inFile << "sf_mc_err  \t" << dummyErr << endl; 
  
  
    // sf_qcd
  
    for (int i = 0 ; i < nBinsMET ; i++) {
      for (int j = 0 ; j < nBinsHT ; j++) {
        for (int k = 0 ; k < nBinsBjets ; k++) {
  
  	TString sf_qcd = "sf_qcd" ;
  	sf_qcd = sf_qcd+sMbins[i]+sHbins[j]+sBbins[k] ;
  	
  	inFile << sf_qcd << "  \t" << dummyOne << endl;	
  
  	sf_qcd = sf_qcd+"_err" ;
  	inFile << sf_qcd << "  \t" << dummyErr << endl;	
  
        }
      }
    }
  
  
    // sf_ttwj
  
    for (int i = 0 ; i < nBinsMET ; i++) {
      for (int j = 0 ; j < nBinsHT ; j++) {
        for (int k = 0 ; k < nBinsBjets ; k++) {
  
  	TString sf_ttwj = "sf_ttwj" ;
  	sf_ttwj = sf_ttwj+sMbins[i]+sHbins[j]+sBbins[k] ;
  	
  	inFile << sf_ttwj << "  \t" << dummyOne << endl;	
  
  	sf_ttwj = sf_ttwj+"_err" ;
  	inFile << sf_ttwj << "  \t" << dummyErr << endl;	
  
        }
      }
    }
  
  
    // sf_ee
  
    for (int k = 0 ; k < nBinsBjets ; k++) {
  
      TString sf_ee = "sf_ee" ;
      sf_ee = sf_ee+sBbins[k] ;
  
      inFile << sf_ee << "  \t" << dummyOne << endl;
      
      sf_ee = sf_ee+"_err" ;
      inFile << sf_ee << "  \t" << dummyErr << endl;
  
    }
  
  
    // sf_mm
  
    for (int k = 0 ; k < nBinsBjets ; k++) {
  
      TString sf_mm = "sf_mm" ;
      sf_mm = sf_mm+sBbins[k] ;
  
      inFile << sf_mm << "  \t" << dummyOne << endl;
      
      sf_mm = sf_mm+"_err" ;
      inFile << sf_mm << "  \t" << dummyErr << endl;
  
    }


    // btag eff err (Note: this was missing until Aug 3, 2012, but it's apparently not used.)
    inFile << "btageff_err" << " \t" << dummyErr << endl ;



    //--- Addding ttwj and znn LDP/ZL MC values

    //--- ttwj MC LDP/ZL

    for (int mbi = 0 ; mbi < nBinsMET ; mbi++) {
      for (int hbi = 0 ; hbi < nBinsHT ; hbi++) {
        int hbin = 1 + (nBinsHT+1)*mbi + hbi + 1 ;
        for (int bbi = 0 ; bbi < nBinsBjets ; bbi++) {

            float ldpval = hmctruth_ttwj[2][bbi] -> GetBinContent( hbin ) ;
            float ldperr = hmctruth_ttwj[2][bbi] -> GetBinError(   hbin ) ;
            float zlval  = hmctruth_ttwj[0][bbi] -> GetBinContent( hbin ) ;
            float zlerr  = hmctruth_ttwj[0][bbi] -> GetBinError(   hbin ) ;

            float ldpoverzl = 0. ;
            float ldpoverzlerr = 0. ;

            if ( zlval > 0. && ldpval > 0. ) {
               ldpoverzl = ldpval / zlval ;
               ldpoverzlerr = ldpoverzl * sqrt( pow((zlerr/zlval),2) + pow((ldperr/ldpval),2) ) ;
            }

            char parname[1000] ;

            sprintf( parname, "ttwj_mc_ldpover0lep_ratio_M%d_H%d_%db", mbi+1, hbi+1, bbi+1 ) ;
            printf(" %s  :  %6.3f +/- %5.3f\n", parname, ldpoverzl, ldpoverzlerr ) ;
            inFile << parname << "  \t" << ldpoverzl << endl;

            sprintf( parname, "ttwj_mc_ldpover0lep_ratio_M%d_H%d_%db_err", mbi+1, hbi+1, bbi+1 ) ;
            inFile << parname << "  \t" << ldpoverzlerr << endl;

        } // bbi
      } // hbi
    } // mbi


    //--- Znn MC LDP/ZL
    //--- Note: the 2b and >=3b MC stats are too low.  Use 1b values for all 3.

    for (int mbi = 0 ; mbi < nBinsMET ; mbi++) {
      for (int hbi = 0 ; hbi < nBinsHT ; hbi++) {
        int hbin = 1 + (nBinsHT+1)*mbi + hbi + 1 ;

        float ldpval = hmctruth_znn[2][0] -> GetBinContent( hbin ) ;
        float ldperr = hmctruth_znn[2][0] -> GetBinError(   hbin ) ;
        float zlval  = hmctruth_znn[0][0] -> GetBinContent( hbin ) ;
        float zlerr  = hmctruth_znn[0][0] -> GetBinError(   hbin ) ;

        float ldpoverzl = 0. ;
        float ldpoverzlerr = 0. ;

        if ( zlval > 0. && ldpval > 0. ) {
           ldpoverzl = ldpval / zlval ;
           ldpoverzlerr = ldpoverzl * sqrt( pow((zlerr/zlval),2) + pow((ldperr/ldpval),2) ) ;
        }

        char parname[1000] ;

        for (int bbi = 0 ; bbi < nBinsBjets ; bbi++) {
            sprintf( parname, "znn_mc_ldpover0lep_ratio_M%d_H%d_%db", mbi+1, hbi+1, bbi+1 ) ;
            printf(" %s  :  %6.3f +/- %5.3f\n", parname, ldpoverzl, ldpoverzlerr ) ;
            inFile << parname << "  \t" << ldpoverzl << endl;

            sprintf( parname, "znn_mc_ldpover0lep_ratio_M%d_H%d_%db_err", mbi+1, hbi+1, bbi+1 ) ;
            inFile << parname << "  \t" << ldpoverzlerr << endl;
        } // bbi
      } // hbi
    } // mbi


    // add here the fractions (bin by bin) of 2b/1b and 3b/1b SL events (just for the MC for now)

    for (int mbi = 0 ; mbi < nBinsMET ; mbi++) {
      for (int hbi = 0 ; hbi < nBinsHT ; hbi++) {

	TString Sl2bstring     = "sl_frac_2b_val";
	TString Sl2bstring_err = "sl_frac_2b_err";
	TString Sl3bstring     = "sl_frac_3b_val";
	TString Sl3bstring_err = "sl_frac_3b_err";
	TString Sl4bstring     = "sl_frac_4b_val";
	TString Sl4bstring_err = "sl_frac_4b_err";

	Sl2bstring     += sMbins[mbi]+sHbins[hbi] ;
	Sl2bstring_err += sMbins[mbi]+sHbins[hbi] ;
	Sl3bstring     += sMbins[mbi]+sHbins[hbi] ;
	Sl3bstring_err += sMbins[mbi]+sHbins[hbi] ;
	Sl4bstring     += sMbins[mbi]+sHbins[hbi] ;
	Sl4bstring_err += sMbins[mbi]+sHbins[hbi] ;

	inFile << Sl2bstring     << "   \t" << sl_frac2b_val[mbi][hbi] << endl ;
	inFile << Sl2bstring_err << "   \t" << sl_frac2b_err[mbi][hbi] << endl ;
	inFile << Sl3bstring     << "   \t" << sl_frac3b_val[mbi][hbi] << endl ;
	inFile << Sl3bstring_err << "   \t" << sl_frac3b_err[mbi][hbi] << endl ;
	inFile << Sl4bstring     << "   \t" << sl_frac4b_val[mbi][hbi] << endl ;
	inFile << Sl4bstring_err << "   \t" << sl_frac4b_err[mbi][hbi] << endl ;

      }
    }




    gSystem->Exec("mkdir -p rootfiles") ;
    char outHistName[1000] ;
    if ( mgl>0. && mlsp>0. ) {
       if ( target_susy_all0lep > 0 ) {
          sprintf( outHistName, "rootfiles/gi-plots-nb4-wsusy-mgl%.0f-mlsp%.0f-%.0fevts-met%d-ht%d-v%d.root", mgl, mlsp, target_susy_all0lep, nBinsMET, nBinsHT, version ) ;
       } else {
          sprintf( outHistName, "rootfiles/gi-plots-nb4-wsusy-mgl%.0f-mlsp%.0f-met%d-ht%d-v%d.root", mgl, mlsp, nBinsMET, nBinsHT, version ) ;
       }
    } else {
       sprintf( outHistName, "rootfiles/gi-plots-nb4-met%d-ht%d-v%d.root", nBinsMET, nBinsHT, version ) ;
    }
    saveHist( outHistName, "h*" ) ;


    inFile.close();
    return;
  
  }
コード例 #18
0
void
HTT_MM_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., string inputfile="root/$HISTFILE", const char* directory="mumu_$CATEGORY")
{
    // define common canvas, axes pad styles
    SetStyle();
    gStyle->SetLineStyleString(11,"20 10");

    // determine category tag
    const char* category = "";
    const char* category_extra = "";
    const char* category_extra2 = "";
    if(std::string(directory) == std::string("mumu_0jet_low"             )) {
        category = "#mu#mu";
    }
    if(std::string(directory) == std::string("mumu_0jet_low"             )) {
        category_extra = "0-jet low p_{T}^{#mu}";
    }
    if(std::string(directory) == std::string("mumu_0jet_high"            )) {
        category = "#mu#mu";
    }
    if(std::string(directory) == std::string("mumu_0jet_high"            )) {
        category_extra = "0-jet high p_{T}^{#mu}";
    }
    if(std::string(directory) == std::string("mumu_1jet_low"          )) {
        category = "#mu#mu";
    }
    if(std::string(directory) == std::string("mumu_1jet_low"          )) {
        category_extra = "1-jet low p_{T}^{#mu}";
    }
    if(std::string(directory) == std::string("mumu_1jet_high"          )) {
        category = "#mu#mu";
    }
    if(std::string(directory) == std::string("mumu_1jet_high"          )) {
        category_extra = "1-jet high p_{T}^{#mu}";
    }
    if(std::string(directory) == std::string("mumu_vbf"            )) {
        category = "#mu#mu";
    }
    if(std::string(directory) == std::string("mumu_vbf"            )) {
        category_extra = "2-jet";
    }
    if(std::string(directory) == std::string("mumu_nobtag"               )) {
        category = "#mu#mu";
    }
    if(std::string(directory) == std::string("mumu_nobtag"               )) {
        category_extra = "no b-tag";
    }
    if(std::string(directory) == std::string("mumu_btag"                 )) {
        category = "#mu#mu";
    }
    if(std::string(directory) == std::string("mumu_btag"                 )) {
        category_extra = "b-tag";
    }

    const char* dataset;
#ifdef MSSM
    if(std::string(inputfile).find("7TeV")!=std::string::npos) {
        dataset = "#scale[1.5]{CMS}  h,H,A#rightarrow#tau#tau                                 4.9 fb^{-1} (7 TeV)";
    }
    if(std::string(inputfile).find("8TeV")!=std::string::npos) {
        dataset = "#scale[1.5]{CMS}  h,H,A#rightarrow#tau#tau                                19.7 fb^{-1} (8 TeV)";
    }
#else
    if(std::string(inputfile).find("7TeV")!=std::string::npos) {
        dataset = "CMS, 4.9 fb^{-1} at 7 TeV";
    }
    if(std::string(inputfile).find("8TeV")!=std::string::npos) {
        dataset = "CMS, 19.7 fb^{-1} at 8 TeV";
    }
#endif

    TFile* input = new TFile(inputfile.c_str());
#ifdef MSSM
    TFile* input2 = new TFile((inputfile+"_$MA_$TANB").c_str());
#endif
    TH1F* ZTT      = refill((TH1F*)input ->Get(TString::Format("%s/ZTT"     , directory)), "ZTT"     );
    InitHist(ZTT     , "", "", TColor::GetColor(248,206,104), 1001);
    TH1F* ZMM      = refill((TH1F*)input ->Get(TString::Format("%s/ZMM"     , directory)), "ZMM"     );
    InitHist(ZMM     , "", "", TColor::GetColor(100,182,232), 1001);
    TH1F* TTJ      = refill((TH1F*)input ->Get(TString::Format("%s/TTJ"     , directory)), "TTJ"     );
    InitHist(TTJ     , "", "", TColor::GetColor(155,152,204), 1001);
    TH1F* QCD      = refill((TH1F*)input ->Get(TString::Format("%s/QCD"     , directory)), "QCD"     );
    InitHist(QCD     , "", "", TColor::GetColor(250,202,255), 1001);
    TH1F* Dibosons = refill((TH1F*)input ->Get(TString::Format("%s/Dibosons", directory)), "Dibosons");
    InitHist(Dibosons, "", "", TColor::GetColor(222,90,106), 1001);
    TH1F* WJets    = 0;
    if(!(std::string("mumu_nobtag") == std::string(directory))) {
        // template has been removed from nobtag categories
        WJets = refill((TH1F*)input ->Get(TString::Format("%s/WJets"   , directory)), "WJets"   );
        InitHist(WJets   , "", "", kGreen -4 , 1001);
    }
#ifdef MSSM
    TH1F* ggH      = refill((TH1F*)input2->Get(TString::Format("%s/ggH$MA"  , directory)), "ggH"     );
    InitSignal(ggH);
    ggH->Scale($TANB);
    TH1F* bbH      = refill((TH1F*)input2->Get(TString::Format("%s/bbH$MA"  , directory)), "bbH"     );
    InitSignal(bbH);
    bbH->Scale($TANB);
    // TH1F* ggH_SM125= refill((TH1F*)input->Get(TString::Format("%s/ggH_SM125"  , directory)), "ggH_SM125"); InitHist(ggH_SM125, "", "", kGreen+2, 1001);
//   TH1F* qqH_SM125= refill((TH1F*)input->Get(TString::Format("%s/qqH_SM125"  , directory)), "qqH_SM125"); InitHist(qqH_SM125, "", "", kGreen+2, 1001);
//   TH1F* VH_SM125 = refill((TH1F*)input->Get(TString::Format("%s/VH_SM125"   , directory)), "VH_SM125" ); InitHist(VH_SM125, "", "", kGreen+2, 1001);
    TH1F* ggH_SM125= refill((TH1F*)input->Get(TString::Format("%s/ggH125"  , directory)), "ggH_SM125");
    InitHist(ggH_SM125, "", "", kGreen+2, 1001);
    if(std::string(inputfile).find("7TeV")!=std::string::npos) ggH_SM125->Scale((15.13+1.222+0.3351+0.08632)*0.0632);
    if(std::string(inputfile).find("8TeV")!=std::string::npos) ggH_SM125->Scale((19.27+1.578+0.7046+0.4153)*0.0632);
#else
#ifndef DROP_SIGNAL
    TH1F* ggH      = refill((TH1F*)input ->Get(TString::Format("%s/ggH125"  , directory)), "ggH"     );
    InitSignal(ggH);
    ggH->Scale(SIGNAL_SCALE);
    TH1F* qqH      = refill((TH1F*)input ->Get(TString::Format("%s/qqH125"  , directory)), "qqH"     );
    InitSignal(qqH);
    qqH->Scale(SIGNAL_SCALE);
    TH1F* VH       = refill((TH1F*)input ->Get(TString::Format("%s/VH125"   , directory)), "VH"      );
    InitSignal(VH );
    VH ->Scale(SIGNAL_SCALE);
#endif
#endif
#ifdef ASIMOV
    TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs_asimov", directory)), "data", true);
#else
    TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
#endif
#ifdef MSSM
    InitHist(data, "#bf{m_{#tau#tau} [GeV]}" , "#bf{dN/dm_{#tau#tau} [1/GeV]}");
    InitData(data);
#else
    InitHist(data, "#bf{D}", "#bf{dN/dD}"     );
    InitData(data);
#endif

    TH1F* ref=(TH1F*)ZTT->Clone("ref");
    ref->Add(ZMM);
    ref->Add(TTJ);
    ref->Add(QCD);
    ref->Add(Dibosons);
    if(WJets) {
        ref->Add(WJets);
    }
    double unscaled[9];
    unscaled[0] = ZTT->Integral();
    unscaled[1] = ZMM->Integral();
    unscaled[2] = TTJ->Integral();
    unscaled[3] = QCD->Integral();
    unscaled[4] = Dibosons->Integral();
    unscaled[5] = 0;
    if(WJets) {
        unscaled[5] = WJets->Integral();
    }
#ifdef MSSM
    unscaled[6] = ggH->Integral();
    unscaled[7] = bbH->Integral();
    unscaled[8] = 0;
#else
#ifndef DROP_SIGNAL
    unscaled[6] = ggH->Integral();
    unscaled[7] = qqH->Integral();
    unscaled[8] = VH ->Integral();
#endif
#endif

    if(scaled) {
        rescale(ZTT,  1);
        rescale(ZMM,  2);
        rescale(TTJ,  3);
        rescale(QCD,  4);
        rescale(Dibosons, 5);
        if(WJets) {
            rescale(WJets,  6);
        }
#ifdef MSSM
        rescale(ggH,  7);
        rescale(bbH,  8);
#else
#ifndef DROP_SIGNAL
        rescale(ggH,  7);
        rescale(qqH,  8);
        rescale(VH,   9);
#endif
#endif
    }

    TH1F* scales[9];
    scales[0] = new TH1F("scales-ZTT", "", 9, 0, 9);
    scales[0]->SetBinContent(1, unscaled[0]>0 ? (ZTT->Integral()/unscaled[0]-1.)      : 0.);
    scales[1] = new TH1F("scales-ZMM"  , "", 9, 0, 9);
    scales[1]->SetBinContent(2, unscaled[1]>0 ? (ZMM->Integral()/unscaled[1]-1.)      : 0.);
    scales[2] = new TH1F("scales-TTJ", "", 9, 0, 9);
    scales[2]->SetBinContent(3, unscaled[2]>0 ? (TTJ->Integral()/unscaled[2]-1.)      : 0.);
    scales[3] = new TH1F("scales-QCD"  , "", 9, 0, 9);
    scales[3]->SetBinContent(4, unscaled[3]>0 ? (QCD->Integral()/unscaled[3]-1.)      : 0.);
    scales[4] = new TH1F("scales-Dibosons", "", 9, 0, 9);
    scales[4]->SetBinContent(5, unscaled[4]>0 ? (Dibosons->Integral()/unscaled[4]-1.) : 0.);
    scales[5] = new TH1F("scales-WJets"  , "", 9, 0, 9);
    scales[5]->SetBinContent(6, 0.);
    if(WJets) {
        scales[5]->SetBinContent(6, unscaled[5]>0 ? (WJets->Integral()/unscaled[5]-1.)  : 0.);
    }
#ifdef MSSM
    scales[6] = new TH1F("scales-ggH"  , "", 9, 0, 9);
    scales[6]->SetBinContent(7, unscaled[6]>0 ? (ggH->Integral()/unscaled[6]-1.)      : 0.);
    scales[7] = new TH1F("scales-bbH"  , "", 9, 0, 9);
    scales[7]->SetBinContent(8, unscaled[7]>0 ? (bbH->Integral()/unscaled[7]-1.)      : 0.);
    scales[8] = new TH1F("scales-NONE" , "", 9, 0, 9);
    scales[8]->SetBinContent(9, 0.);
#else
#ifndef DROP_SIGNAL
    scales[6] = new TH1F("scales-ggH"  , "", 9, 0, 9);
    scales[6]->SetBinContent(7, unscaled[6]>0 ? (ggH->Integral()/unscaled[6]-1.)      : 0.);
    scales[7] = new TH1F("scales-qqH"  , "", 9, 0, 9);
    scales[7]->SetBinContent(8, unscaled[7]>0 ? (qqH->Integral()/unscaled[7]-1.)      : 0.);
    scales[8] = new TH1F("scales-VH"   , "", 9, 0, 9);
    scales[8]->SetBinContent(9, unscaled[8]>0 ? (VH ->Integral()/unscaled[8]-1.)      : 0.);
#endif
#endif

#ifdef MSSM
    // qqH_SM125->Add(ggH_SM125);
//   VH_SM125->Add(qqH_SM125);
//   Dibosons->Add(VH_SM125);
    Dibosons->Add(ggH_SM125);
#endif
    if(WJets) {
        Dibosons->Add(WJets);
    }
    QCD->Add(Dibosons);
    TTJ->Add(QCD);
    ZTT->Add(TTJ);
    ZMM->Add(ZTT);
    if(log) {
#ifdef MSSM
        ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
        qqH  ->Add(VH );
        ggH  ->Add(qqH);
#endif
#endif
    }
    else {
#ifdef MSSM
        bbH  ->Add(ZMM);
        ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
        VH   ->Add(ZMM);
        qqH  ->Add(VH );
        ggH  ->Add(qqH);
#endif
#endif
    }


    /*
      mass plot before and after fit
    */
    TCanvas* canv = MakeCanvas("canv", "histograms", 600, 600);
    canv->cd();
    if(log) {
        canv->SetLogy(1);
    }
#if defined MSSM
    if(!log) {
        data->GetXaxis()->SetRange(0, data->FindBin(345));
    }
    else {
        data->GetXaxis()->SetRange(0, data->FindBin(UPPER_EDGE));
    };
#else
    data->GetXaxis()->SetRange(0, data->FindBin(345));
#endif
    data->SetNdivisions(505);
    data->SetMinimum(min);
#ifndef DROP_SIGNAL
    data->SetMaximum(max>0 ? max : std::max(std::max(maximum(data, log), maximum(ZMM, log)), maximum(ggH, log)));
#else
    data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(ZMM, log)));
#endif
    data->Draw("e");

    TH1F* errorBand = (TH1F*)ZMM->Clone("errorBand");
    errorBand->SetMarkerSize(0);
    errorBand->SetFillColor(13);
    errorBand->SetFillStyle(3013);
    errorBand->SetLineWidth(1);
    for(int idx=0; idx<errorBand->GetNbinsX(); ++idx) {
        if(errorBand->GetBinContent(idx)>0) {
            std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
            break;
        }
    }
    if(log) {
        ZMM->Draw("histsame");
        ZTT->Draw("histsame");
        TTJ->Draw("histsame");
        QCD->Draw("histsame");
        Dibosons->Draw("histsame");
#ifdef MSSM
        //VH_SM125->Draw("histsame");
        ggH_SM125->Draw("histsame");
#endif
        $DRAW_ERROR
#ifndef DROP_SIGNAL
        ggH->Draw("histsame");
#endif

    }
    else {
#ifndef DROP_SIGNAL
        ggH  ->Draw("histsame");
#endif
        ZMM->Draw("histsame");
        ZTT->Draw("histsame");
        TTJ->Draw("histsame");
        QCD->Draw("histsame");
        Dibosons->Draw("histsame");
#ifdef MSSM
        //VH_SM125->Draw("histsame");
        ggH_SM125->Draw("histsame");
#endif
        $DRAW_ERROR
    }
    data->Draw("esame");
    canv->RedrawAxis();

    //CMSPrelim(dataset, "#tau_{#mu}#tau_{#mu}", 0.17, 0.835);
    CMSPrelim(dataset, "", 0.16, 0.835);
#if defined MSSM
    TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "tlbrNDC");
#else
    TPaveText* chan     = new TPaveText(0.22, (category_extra2 && category_extra2[0]=='\0') ? 0.65+0.061 : 0.65+0.061, 0.34, 0.75+0.161, "tlbrNDC");
#endif
    chan->SetBorderSize(   0 );
    chan->SetFillStyle(    0 );
    chan->SetTextAlign(   12 );
    chan->SetTextSize ( 0.05 );
    chan->SetTextColor(    1 );
    chan->SetTextFont (   62 );
    chan->AddText(category);
    chan->AddText(category_extra);
#if defined MSSM
#else
    chan->AddText(category_extra2);
#endif
    chan->Draw();

    /*  TPaveText* cat      = new TPaveText(0.20, 0.71+0.061, 0.32, 0.71+0.161, "NDC");
      cat->SetBorderSize(   0 );
      cat->SetFillStyle(    0 );
      cat->SetTextAlign(   12 );
      cat->SetTextSize ( 0.05 );
      cat->SetTextColor(    1 );
      cat->SetTextFont (   62 );
      cat->AddText(category_extra);
      cat->Draw();
    */
#ifdef MSSM
    TPaveText* massA      = new TPaveText(0.53, 0.44+0.061, 0.95, 0.44+0.151, "NDC");
    massA->SetBorderSize(   0 );
    massA->SetFillStyle(    0 );
    massA->SetTextAlign(   12 );
    massA->SetTextSize ( 0.03 );
    massA->SetTextColor(    1 );
    massA->SetTextFont (   62 );
    massA->AddText("MSSM m^{h}_{mod+} scenario");
    massA->AddText("m_{A}=$MA GeV, tan#beta=$TANB");
    massA->Draw();
#endif

#ifdef MSSM
    TLegend* leg = new TLegend(0.53, 0.60, 0.95, 0.90);
    SetLegendStyle(leg);
    leg->AddEntry(ggH  , "h,H,A#rightarrow#tau#tau" , "L" );
#else
    TLegend* leg = new TLegend(0.52, 0.58, 0.92, 0.89);
    SetLegendStyle(leg);
#ifndef DROP_SIGNAL
    if(SIGNAL_SCALE!=1) {
        leg->AddEntry(ggH  , TString::Format("%.0f#timesH(125 GeV)#rightarrow#tau#tau", SIGNAL_SCALE) , "L" );
    }
    else {
        leg->AddEntry(ggH  , "SM H(125 GeV)#rightarrow#tau#tau" , "L" );
    }
#endif
#endif
#ifdef ASIMOV
    leg->AddEntry(data    , "sum(bkg) + H(125)"           , "LP");
#else
    leg->AddEntry(data    , "Observed"                    , "LP");
#endif
    leg->AddEntry(ZMM     , "Z#rightarrow#mu#mu"          , "F" );
    leg->AddEntry(ZTT     , "Z#rightarrow#tau#tau"        , "F" );
    leg->AddEntry(TTJ     , "t#bar{t}"                    , "F" );
    leg->AddEntry(QCD     , "QCD"                         , "F" );
    leg->AddEntry(Dibosons, "Electroweak"                 , "F" );
#ifdef MSSM
    leg->AddEntry(ggH_SM125, "SM H(125 GeV) #rightarrow #tau#tau", "F" );
#endif
    $ERROR_LEGEND
    leg->Draw();

    /*
      Ratio Data over MC
    */
    TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
    canv0->SetGridx();
    canv0->SetGridy();
    canv0->cd();

    TH1F* model = (TH1F*)ZMM ->Clone("model");
    TH1F* test1 = (TH1F*)data->Clone("test1");
    for(int ibin=0; ibin<test1->GetNbinsX(); ++ibin) {
        //the small value in case of 0 entries in the model is added to prevent the chis2 test from failing
        model->SetBinContent(ibin+1, model->GetBinContent(ibin+1)>0 ? model->GetBinContent(ibin+1)*model->GetBinWidth(ibin+1) : 0.01);
        model->SetBinError  (ibin+1, CONVERVATIVE_CHI2 ? 0. : model->GetBinError  (ibin+1)*model->GetBinWidth(ibin+1));
        test1->SetBinContent(ibin+1, test1->GetBinContent(ibin+1)*test1->GetBinWidth(ibin+1));
        test1->SetBinError  (ibin+1, test1->GetBinError  (ibin+1)*test1->GetBinWidth(ibin+1));
    }
    double chi2prob = test1->Chi2Test      (model,"PUW");
    std::cout << "chi2prob:" << chi2prob << std::endl;
    double chi2ndof = test1->Chi2Test      (model,"CHI2/NDFUW");
    std::cout << "chi2ndf :" << chi2ndof << std::endl;
    double ksprob   = test1->KolmogorovTest(model);
    std::cout << "ksprob  :" << ksprob   << std::endl;
    double ksprobpe = test1->KolmogorovTest(model,"DX");
    std::cout << "ksprobpe:" << ksprobpe << std::endl;

    std::vector<double> edges;
    TH1F* zero = (TH1F*)ref ->Clone("zero");
    zero->Clear();
    TH1F* rat1 = (TH1F*)data->Clone("rat1");
    rat1->Reset("ICES");
    for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin) {
        if(data->GetBinContent(ibin+1) > 0) {
            rat1->SetBinContent(ibin+1, ZMM->GetBinContent(ibin+1)>0 ? data->GetBinContent(ibin+1)/ZMM->GetBinContent(ibin+1) : 0);
            rat1->SetBinError  (ibin+1, ZMM->GetBinContent(ibin+1)>0 ? data->GetBinError  (ibin+1)/ZMM->GetBinContent(ibin+1) : 0);
        }
        zero->SetBinContent(ibin+1, 0.);
        zero->SetBinError  (ibin+1, ZMM->GetBinContent(ibin+1)>0 ? ZMM ->GetBinError  (ibin+1)/ZMM->GetBinContent(ibin+1) : 0);
    }
    for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin) {
        if(rat1->GetBinContent(ibin+1)>0) {
            edges.push_back(TMath::Abs(rat1->GetBinContent(ibin+1)-1.)+TMath::Abs(rat1->GetBinError(ibin+1)));
            // catch cases of 0 bins, which would lead to 0-alpha*0-1
            rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
        }
    }
    float range = 0.1;
    std::sort(edges.begin(), edges.end());
    if (edges[edges.size()-2]>0.1) {
        range = 0.2;
    }
    if (edges[edges.size()-2]>0.2) {
        range = 0.5;
    }
    if (edges[edges.size()-2]>0.5) {
        range = 1.0;
    }
    if (edges[edges.size()-2]>1.0) {
        range = 1.5;
    }
    if (edges[edges.size()-2]>1.5) {
        range = 2.0;
    }
    rat1->SetLineColor(kBlack);
    rat1->SetFillColor(kGray );
    rat1->SetMaximum(+range);
    rat1->SetMinimum(-range);
    rat1->GetYaxis()->CenterTitle();
    rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
#ifdef MSSM
    rat1->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
#else
    rat1->GetXaxis()->SetTitle("#bf{D}");
#endif
    rat1->Draw("E0");
    zero->SetFillStyle(  3013);
    zero->SetFillColor(kBlack);
    zero->SetLineColor(kBlack);
    zero->SetMarkerSize(0.1);
    zero->Draw("e2histsame");
    canv0->RedrawAxis();

    TPaveText* stat1 = new TPaveText(0.20, 0.76+0.061, 0.32, 0.76+0.161, "NDC");
    stat1->SetBorderSize(   0 );
    stat1->SetFillStyle(    0 );
    stat1->SetTextAlign(   12 );
    stat1->SetTextSize ( 0.05 );
    stat1->SetTextColor(    1 );
    stat1->SetTextFont (   62 );
    stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f", chi2ndof, chi2prob));
    //stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f, P(KS)=%.3f", chi2ndof, chi2prob, ksprob));
    stat1->Draw();

    /*
      Ratio After fit over Prefit
    */
    TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
    canv1->SetGridx();
    canv1->SetGridy();
    canv1->cd();

    edges.clear();
    TH1F* rat2 = (TH1F*) ZMM->Clone("rat2");
    for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin) {
        rat2->SetBinContent(ibin+1, ref->GetBinContent(ibin+1)>0 ? ZMM->GetBinContent(ibin+1)/ref->GetBinContent(ibin+1) : 0);
        rat2->SetBinError  (ibin+1, ref->GetBinContent(ibin+1)>0 ? ZMM->GetBinError  (ibin+1)/ref->GetBinContent(ibin+1) : 0);
    }
    for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin) {
        if(rat2->GetBinContent(ibin+1)>0) {
            edges.push_back(TMath::Abs(rat2->GetBinContent(ibin+1)-1.)+TMath::Abs(rat2->GetBinError(ibin+1)));
            // catch cases of 0 bins, which would lead to 0-alpha*0-1
            rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
        }
    }
    range = 0.1;
    std::sort(edges.begin(), edges.end());
    if (edges[edges.size()-2]>0.1) {
        range = 0.2;
    }
    if (edges[edges.size()-2]>0.2) {
        range = 0.5;
    }
    if (edges[edges.size()-2]>0.5) {
        range = 1.0;
    }
    if (edges[edges.size()-2]>1.0) {
        range = 1.5;
    }
    if (edges[edges.size()-2]>1.5) {
        range = 2.0;
    }
#if defined MSSM
    if(!log) {
        rat2->GetXaxis()->SetRange(0, rat2->FindBin(345));
    }
    else {
        rat2->GetXaxis()->SetRange(0, rat2->FindBin(UPPER_EDGE));
    };
#else
    rat2->GetXaxis()->SetRange(0, rat2->FindBin(345));
#endif
    rat2->SetNdivisions(505);
    rat2->SetLineColor(kRed+3);
    rat2->SetMarkerColor(kRed+3);
    rat2->SetMarkerSize(1.1);
    rat2->SetMaximum(+range);
    rat2->SetMinimum(-range);
    rat2->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
    rat2->GetYaxis()->CenterTitle();
#if defined MSSM
    rat2->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
#else
    rat2->GetXaxis()->SetTitle("#bf{D}");
#endif
    rat2->Draw();
    zero->SetFillStyle(  3013);
    zero->SetFillColor(kBlack);
    zero->SetLineColor(kBlack);
    zero->Draw("e2histsame");
    canv1->RedrawAxis();

    /*
      Relative shift per sample
    */
    TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
    canv2->SetGridx();
    canv2->SetGridy();
    canv2->cd();

    InitHist  (scales[0], "", "", TColor::GetColor(248,206,104), 1001);
    InitHist  (scales[1], "", "", TColor::GetColor(100,182,232), 1001);
    InitHist  (scales[2], "", "", TColor::GetColor(155,152,204), 1001);
    InitHist  (scales[3], "", "", TColor::GetColor(250,202,255), 1001);
    InitHist  (scales[4], "", "", TColor::GetColor(222,90,106), 1001);
    InitHist  (scales[5], "", "", kGreen   -  4, 1001);
#ifndef DROP_SIGNAL
    InitSignal(scales[6]);
    InitSignal(scales[7]);
    InitSignal(scales[8]);
#endif
    scales[0]->GetXaxis()->SetBinLabel(1, "#bf{ZTT}");
    scales[0]->GetXaxis()->SetBinLabel(2, "#bf{ZMM}"  );
    scales[0]->GetXaxis()->SetBinLabel(3, "#bf{TTJ}");
    scales[0]->GetXaxis()->SetBinLabel(4, "#bf{QCD}"  );
    scales[0]->GetXaxis()->SetBinLabel(5, "#bf{Dibosons}");
    scales[0]->GetXaxis()->SetBinLabel(6, "#bf{WJets}"  );
#ifdef MSSM
    scales[0]->GetXaxis()->SetBinLabel(7, "#bf{ggH}"  );
    scales[0]->GetXaxis()->SetBinLabel(8, "#bf{bbH}"  );
    scales[0]->GetXaxis()->SetBinLabel(9, "#bf{NONE}" );
#else
    scales[0]->GetXaxis()->SetBinLabel(7, "#bf{ggH}"  );
    scales[0]->GetXaxis()->SetBinLabel(8, "#bf{qqH}"  );
    scales[0]->GetXaxis()->SetBinLabel(9, "#bf{VH}"   );
#endif
    scales[0]->SetMaximum(+0.5);
    scales[0]->SetMinimum(-0.5);
    scales[0]->GetYaxis()->CenterTitle();
    scales[0]->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
    scales[0]->Draw();
    scales[1]->Draw("same");
    scales[2]->Draw("same");
    scales[3]->Draw("same");
    scales[4]->Draw("same");
    scales[5]->Draw("same");
#ifndef DROP_SIGNAL
    scales[6]->Draw("same");
    scales[7]->Draw("same");
    scales[8]->Draw("same");
#endif
    TH1F* zero_samples = (TH1F*)scales[0]->Clone("zero_samples");
    zero_samples->Clear();
    zero_samples->SetBinContent(1,0.);
    zero_samples->Draw("same");
    canv2->RedrawAxis();

    /*
      prepare output
    */
    bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
    canv   ->Print(TString::Format("%s_%sfit_%s_%s.png"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv   ->Print(TString::Format("%s_%sfit_%s_%s.pdf"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv   ->Print(TString::Format("%s_%sfit_%s_%s.eps"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    if(log || FULLPLOTS)
    {
        canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
        canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
        canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    }
    if((log && scaled) || FULLPLOTS)
    {
        canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
        canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
        canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
        canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
        canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
        canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    }

    TFile* output = new TFile(TString::Format("%s_%sfit_%s_%s.root", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"), "update");
    output->cd();
    data ->Write("data_obs");
    ZTT->Write("Ztt"  );
    ZMM->Write("Zmm"  );
    TTJ->Write("ttbar");
    QCD->Write("Fakes");
    Dibosons->Write("EWK");
    if(WJets) {
        WJets->Write("WJets");
    }
#ifdef MSSM
    ggH  ->Write("ggH");
    bbH  ->Write("bbH");
    ggH_SM125->Write("ggH_SM125");
    //qqH_SM125->Write("qqH_SM125");
    //VH_SM125 ->Write("VH_SM125");
#else
#ifndef DROP_SIGNAL
    ggH  ->Write("ggH");
    qqH  ->Write("qqH");
    VH   ->Write("VH" );
#endif
#endif
    if(errorBand) {
        errorBand->Write("errorBand");
    }
    output->Close();

    delete errorBand;
    delete model;
    delete test1;
    delete zero;
    delete rat1;
    delete rat2;
    delete zero_samples;
    delete ref;
}
コード例 #19
0
ファイル: SPEFit_UXC.C プロジェクト: jaehyeok/HCAL
void SPEFit(char * fLEDname, char * fPEDname, int run, int LED_amp, double cutmax = 250.0)
{

  //set plotting styles
  gStyle->SetCanvasColor(0);
  gStyle->SetPadColor(0);
  gStyle->SetCanvasBorderMode(0);
  gStyle->SetFrameBorderMode(0);
  gStyle->SetStatColor(0);
  gStyle->SetPadTickX(1);
  gStyle->SetPadTickY(1);

    //set file names
    stringstream out_fname;
    stringstream out_fname1;
    out_fname<<"SPEconstants_Run_"<<run<<".txt";
    out_fname1<<"SPEspec_Run_"<<run<<".txt";

    ofstream  constants_file(out_fname.str().c_str(),ios_base::trunc); 
    //ofstream  constants_file1(out_fname1.str().c_str(),ios_base::trunc); 
    constants_file<<"Run "<<run<<endl;
    constants_file<<"type SPE"<<endl;
    constants_file<<"LED_amplitude "<<LED_amp<<endl<<endl;

    constants_file<<endl<<"LED_amplitude Depth Phi Eta Ped_mean Ped_mean_err Ped_RMS  Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl;

    out_fname.str("");
    out_fname<<"SPEdistributions_Run_"<<run<<".txt";

    out_fname.str("");
    out_fname<<"SPEextra_Run_"<<run<<".txt";
    //ofstream  extra_file(out_fname.str().c_str(),ios_base::trunc); 


    double scale = 1.0;
    scale = 2.6; //Need to scale up HF charge
    double fC2electrons = 6240.; //convert fC to #electrons

    char spename[128], pedname[128], spehistname[128];
 
    TFile *tfLED = new TFile(fLEDname);
    TFile *tfPED = new TFile(fPEDname);
    


    //const int NnewBins = 106;
    //double binsX[NnewBins] = {0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,180,190,200,210,220,230,240,250,266,282,298,316,336,356,378,404,430,456,482,500};

    const int NnewBins = 80;
    double binsX[NnewBins] = {0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,60,63,66,69,72,75,78,81,84,87,90,93,96,99,102,105,108,111,114,117,120,123,126,129,132,135,138,141,144,147,150,153,156,159,162,165,168,171,174,177,180,190,200,210,220,230,240,250,266,282,298,316,336,356,378,404,430,456,482,500};	  
    TH1F* hspe = new TH1F("hspe","hspe",NnewBins-1,binsX);


    int NDepth = 2; //number of depths
    int MinDepth = 1;
    int MaxDepth = 2;
    int MinEta = 29; 
    int MaxEta = 41;
    //int MinPhi = 41;
    //int MaxPhi = 53;
    int MinPhi = 1;
    int MaxPhi = 71;
   
 
    TCanvas *Carray[NDepth+1][MaxPhi+1];
    bool drawflag[NDepth+1][MaxPhi+1];  
    TH1F *LED[NDepth+1][MaxEta+1][MaxPhi+1];
    TH1F *PED[NDepth+1][MaxEta+1][MaxPhi+1];

    for(int iDepth = MinDepth; iDepth <= MaxDepth; iDepth++){
      for(int iPhi = MinPhi; iPhi <= MaxPhi; iPhi++){

	bool nonNull = false;

	for(int iEta = MinEta; iEta <= MaxEta; iEta++){

	  sprintf(spename,"Analyzer/CommonDir/ResPlotDir/Histo_for_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi);
	  LED[iDepth][iEta][iPhi]=(TH1F *)tfLED->Get(spename);
	  if(LED[iDepth][iEta][iPhi]) nonNull = true;
      
	  sprintf(spename,"Analyzer/CommonDir/ResPlotDir/Histo_for_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi);
	  PED[iDepth][iEta][iPhi]=(TH1F *)tfPED->Get(spename);
	}

	drawflag[iDepth][iPhi] = false;
	char canvname[16];
	sprintf(canvname, "c_%d_%d", iDepth,iPhi);
	if(nonNull){ //only create canvas if distributions exist
	  Carray[iDepth][iPhi] = new TCanvas(canvname,canvname,1200,700);
	  Carray[iDepth][iPhi]->Divide(5,3);
	}

      }
    }



    int HV=0;

    for(int iDepth = MinDepth; iDepth <= MaxDepth; iDepth++){
      for(int iPhi = MinPhi; iPhi <= MaxPhi; iPhi++){
	for(int iEta = MinEta; iEta <= MaxEta; iEta++){

	  //cout<<iDepth<<" "<<iPhi<<" "<<iEta<<endl;

	  if(!LED[iDepth][iEta][iPhi]) continue;

	  sprintf(spehistname,"led %d %d %d",iDepth,iEta,iPhi);
	  TH1F *hspe_temp = (TH1F *)LED[iDepth][iEta][iPhi]->Clone(spehistname);
	  sprintf(spehistname,"ped %d %d %d",iDepth,iEta,iPhi);
	  TH1F *hped = (TH1F *)PED[iDepth][iEta][iPhi]->Clone(spehistname);
	  hspe->Reset();
	  sprintf (spehistname, "SumLED_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi);
	  hspe->SetTitle(spehistname);

	  //combine bins of original SPE histogram
	  for(int ib=1; ib<=hspe_temp->GetNbinsX(); ib++) {
	    double bin_center = hspe_temp->GetBinCenter(ib);
	    if(bin_center>hspe->GetXaxis()->GetXmax()) continue;
	    int newbin = hspe->FindBin(bin_center);
	    double new_content = hspe->GetBinContent(newbin) + hspe_temp->GetBinContent(ib);
	    double new_error = sqrt(pow(hspe->GetBinError(newbin),2)+pow(hspe_temp->GetBinError(ib),2));
	    hspe->SetBinContent(newbin,new_content);
	    hspe->SetBinError(newbin,new_error);
	  }
	  TH1F* hspe_unscaled = (TH1F*)hspe->Clone("hspe_unscaled");
	  //renormalize bins of new SPE histogram
	  for(int ib=1; ib<=hspe->GetNbinsX(); ib++) {
	    double new_content = hspe->GetBinContent(ib)/hspe->GetXaxis()->GetBinWidth(ib)*hspe_temp->GetXaxis()->GetBinWidth(1);
	    double new_error = hspe->GetBinError(ib)/hspe->GetXaxis()->GetBinWidth(ib)*hspe_temp->GetXaxis()->GetBinWidth(1);
	    hspe->SetBinContent(ib,new_content);
	    hspe->SetBinError(ib,new_error);
	  }
	  
	  if(hspe_temp->Integral()==0) continue;
	  else drawflag[iDepth][iPhi] = true;	  

	  Nev = hspe_temp->Integral()*hspe_temp->GetXaxis()->GetBinWidth(1); 
	  //TF1 *fped = new TF1("fped","gaus",0, 80);
	  TF1 *fped = new TF1("fped","gaus",0, 20);
	  hped->Fit(fped,"NQR");
	  double pploc = fped->GetParameter(1), ppwidth = fped->GetParameter(2);
	  cout<<"depth "<<iDepth<<" ieta "<<iEta<<" iphi "<<iPhi
	      <<" pploc "<<pploc<<" ppwidth "<<ppwidth<<endl;
	  //hspe->Fit(fped, "NQ", "", pploc - 3*ppwidth, pploc + ppwidth);  
	  hspe->Fit(fped, "NQ", "", pploc - 3*ppwidth, pploc + 3*ppwidth);  
	  
	  //estimate SPE peak location
	  int max_SPE_bin, maxbin, Nbins;
	  double max_SPE_height=0, minheight, max_SPE_location;
	  bool minflag = false;
	  maxbin=hspe->FindBin(fped->GetParameter(1)); //location of pedestal peak
	  minheight=hspe->GetBinContent(maxbin); //initialize minheight
	  Nbins = hspe->GetNbinsX();
	  for(int j=maxbin+1; j<Nbins-1; j++) { //start from pedestal peak and loop through bins
	    if(hspe->GetBinContent(j) > minheight && !minflag) minflag=true; //only look for SPE peak when minflag=true
	    if(hspe->GetBinContent(j) < minheight )  minheight = hspe->GetBinContent(j);
	    if(minflag && hspe->GetBinContent(j) > max_SPE_height){
	      max_SPE_bin = j;
	      max_SPE_location = hspe->GetBinCenter(max_SPE_bin);
	      max_SPE_height = hspe->GetBinContent(j);
	    }
	  } //start from pedestal peak and loop through bins
	  //find minimum bin between pedestal and SPE peaks
	  hspe->GetXaxis()->SetRange(maxbin,max_SPE_bin);
	  int minbin = hspe->GetMinimumBin(); 
	  double minbin_location = hspe->GetBinCenter(minbin);
	  hspe->GetXaxis()->SetRange(1,Nbins);	    
	  
	  TF1 *fit = new TF1("fit", FitFun, 0, 500, 5);
	    
	  double mu = - log(fped->Integral(0,100)/Nev);
	  if(mu<0) mu=0.01;
	  double gain_est = max_SPE_location-1.0*fped->GetParameter(1);
	  if(max_SPE_bin > (minbin+1)) fit->SetParameters(mu, 20, 1, gain_est, gain_est*0.5);
	  else fit->SetParameters(mu, 20, 1, 2.1*fped->GetParameter(2), 10); //case of no clear minimum; start looking for SPE peak at 2sigma away from pedestal peak
	  fit->SetParLimits(0, 0, 10);
	  fit->FixParameter(1, fped->GetParameter(1));
	  fit->FixParameter(2, fped->GetParameter(2));
	  fit->SetParLimits(3, fped->GetParameter(2)*2, 350);
	  fit->SetParLimits(4, fped->GetParameter(2)*1.01, 250);
	  

	  double maxfitrange = 500.;    
	  double minfitrange = 0.;
	  hspe->Fit(fit, "MNQL", "", minfitrange, maxfitrange);
	  maxfitrange = fped->GetParameter(1)+4*fit->GetParameter(3)+fit->GetParameter(4);
	  if(500<maxfitrange) maxfitrange = 500;
	  hspe->Fit(fit, "MNQL", "", minfitrange, maxfitrange);

	  //calculate NDOF of fit excluding bins with 0 entries
	  int myNDOF=-3; //three free parameters
	  for(int j=hspe->FindBin(minfitrange); j<=hspe->FindBin(maxfitrange); j++) { //loop through fitted spe bins
	    if(hspe->GetBinContent(j)) myNDOF++;
	  } //loop through fitted spe bins


	  //calculate means and integrals of the fit and data
	  double fint, fint_error, hint, favg, havg;
	  int temp_lowbin, temp_highbin;
	  temp_lowbin = hspe->FindBin(minfitrange);
	  temp_highbin = hspe->FindBin(maxfitrange);
	  hspe_unscaled->GetXaxis()->SetRangeUser(minfitrange, maxfitrange);
	  havg = hspe_unscaled->GetMean();
	  hint = hspe->Integral(temp_lowbin,temp_highbin,"width");
	  double min_frange = hspe->GetBinLowEdge(temp_lowbin);
	  favg = fit->Mean(min_frange, maxfitrange);
	  fint = fit->Integral(min_frange, maxfitrange);
	  //fint_error = fit->IntegralError(min_frange, maxfitrange);
	  
	  double PE5int = 0; //integral of events with >=5 PE
	  double PE5loc =  fped->GetParameter(1)+ 5*fit->GetParameter(3);
	  if(PE5loc>500) PE5int = 0;
	  else {
	    int PE5bin =  hspe_temp->FindBin(PE5loc);
	    temp_highbin = hspe_temp->FindBin(maxfitrange)-1;
	    PE5int =  hspe_temp->Integral(PE5bin,temp_highbin,"width");
	  }
	  int PE5flag = 0;
	  if(PE5int/hint>0.05) PE5flag = 1; //set flag if more than 5% of events in the fit correspond to >=5PE
	//=========================================    
	  //for(int i1=1;i1<hspe->GetNbinsX();i1++){
	    //constants_file1<<HV<<"\t"<<iDepth<<"\t"<<iEta<<"\t"<<iPhi<<"\t"<<2.6*hspe->GetBinCenter(i1)<<"\t"<<hspe->GetBinContent(i1)<<"\t"<<fit->Eval(hspe->GetBinCenter(i1))<<"\n";
          //}
        //=========================================    

	  //printf("%d\n",myNDOF);
	  //output calibrations constants
	  //constants_file<<endl<<"LED_amplitude HV Spigot Channel Ped_mean Ped_mean_err Ped_RMS  Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl;
	  //constants_file<<LED_amp<<" "<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParError(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fped->GetParError(2)<<" "<<scale*fit->GetParameter(4)<<" "<<scale*fit->GetParError(4)<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<scale*fit->GetParError(3)*fC2electrons<<" "<<fit->GetChisquare()/myNDOF/*fit->GetNDF()*/<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<endl;
	  
	  constants_file<<LED_amp<<" "<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<fped->GetParameter(1)<<" "<<fped->GetParError(1)<<" "<<fped->GetParameter(2)<<" "<<fped->GetParError(2)<<" "<<fit->GetParameter(4)<<" "<<fit->GetParError(4)<<" "<<fit->GetParameter(3)<<" "<<fit->GetParError(3)<<" "<<fit->GetChisquare()/myNDOF/*fit->GetNDF()*/<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<endl;

	  //constants_file<<fit->GetParameter(3)<<" "<<fit->GetParError(3)<<endl;

	  /*
	  if(iDepth==2 && iPhi==53 && iEta==36){
	    cout<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<gain_est<<" "<<fit->GetParameter(3)<<endl;
	    cout<<LED_amp<<" "<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParError(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fped->GetParError(2)<<" "<<scale*fit->GetParameter(4)<<" "<<scale*fit->GetParError(4)<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<scale*fit->GetParError(3)*fC2electrons<<" "<<fit->GetChisquare()/myNDOF<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<endl;
	  }
	  */

	  Carray[iDepth][iPhi]->cd(iEta-MinEta+1);
	  gPad->SetBorderMode(0);
	  gPad->SetBorderSize(0);
	  gPad->SetRightMargin(0.01);
	  gPad->SetBottomMargin(0.1);
	  gPad->SetLogy(true);
	  hspe->GetXaxis()->SetRangeUser(0, 200 /*300*//*508*/);
	  hspe->SetLineColor(kBlue);
	  hspe->DrawClone("hist");
	  fit->SetLineWidth(2);
	  fit->Draw("same");

	}
    
	if(drawflag[iDepth][iPhi]) { //draw plots of fit if data for the HV is present
	  stringstream plot_name;
	  plot_name<<"Plots/SPEFits_Run_"<<run<<"_Depth"<<iDepth<<"_Phi"<<iPhi<<".pdf";
	  Carray[iDepth][iPhi]->SaveAs(plot_name.str().c_str());
	  plot_name.str( std::string() );
	}

      }
    }

    constants_file.close();
    //constants_file1.close();
}
コード例 #20
0
void SmallNtupleQQQ::Loop()
{
//   In a ROOT session, you can do:
//      Root > .L SmallNtupleQQQ.C
//      Root > SmallNtupleQQQ t
//      Root > t.GetEntry(12); // Fill t data members with entry number 12
//      Root > t.Show();       // Show values of entry 12
//      Root > t.Show(16);     // Read and show values of entry 16
//      Root > t.Loop();       // Loop on all entries
//

//     This is the loop skeleton where:
//    jentry is the global entry number in the chain
//    ientry is the entry number in the current Tree
//  Note that the argument to GetEntry must be:
//    jentry for TChain::GetEntry
//    ientry for TTree::GetEntry and TBranch::GetEntry
//
//       To read only selected branches, Insert statements like:
// METHOD1:
//    fChain->SetBranchStatus("*",0);  // disable all branches
//    fChain->SetBranchStatus("branchname",1);  // activate branchname
// METHOD2: replace line
//    fChain->GetEntry(jentry);       //read all branches
//by  b_branchname->GetEntry(ientry); //read only this branch
  
  
   //TFile *f1 = new TFile("WJetFile74_Pt_RRR_WWW.root", "RECREATE"); 
   //TFile *f1 = new TFile("DYJetFile74_Pt_RRR_WWW.root", "RECREATE");
   //TFile *f1 = new TFile("DYtoEEFile74_Pt_RRR_WWW.root", "RECREATE");
   //TFile *f1 = new TFile("TTJetFile74_Pt_RRR_WWW.root", "RECREATE");
   //TFile *f1 = new TFile("GJetFile1_Pt_RRR_74_WWW.root", "RECREATE");
   //TFile *f1 = new TFile("GJetFile2_Pt_RRR_74_WWW.root", "RECREATE");
  
  TFile *f1 = new TFile("FILENAME", "RECREATE");
  
   /* Defining Histograms */
   TH1::SetDefaultSumw2();
   TH1F* h_DrAll(new TH1F("h_DrAll", "DeltaR between two objects, ; DeltaR;Events", 50, 0 ,1));
   TH1F* h_Dr_MCElectron_Photon(new TH1F("h_Dr_MCElectron_Photon", "DeltaR between MCElectron and photon, ; DeltaR;Events", 50, 0 ,1));
   TH1F* h_Photon_MET(new TH1F("h_Photon_MET", "PfMet for photons, ; PfMet;Events", 100, 0 ,500));
   TH1F* h_Fake_MET(new TH1F("h_Fake_MET", "PfMet for fakes, ; PfMet;Events", 100, 0 ,500));
   TH1F* h_Fake_Photon_Pt(new TH1F("h_Fake_Photon_Pt","p_{T}for fake photons;p_{T} (GeV);Event/5 GeV", 100, 0, 500));
   TH1F* h_Electron_MET(new TH1F("h_Electron_MET", "PfMet for electrons, ; PfMet;Events", 100, 0 ,500));
   TH1F* h_SinglePhoton_MET(new TH1F("h_SinglePhoton_MET", "PfMet for single photon, ; PfMet;Events", 100, 0 ,500));
   TH1F* h_SingleFake_MET(new TH1F("h_SingleFake_MET", "PfMet for single fake, ; PfMet;Events", 100, 0 ,500));
   TH1F* h_SingleElectron_MET(new TH1F("h_SingleElectron_MET", "PfMet for single electron, ; PfMet;Events", 100, 0 ,500));
   TH1F* h_CutFlow_Electron(new TH1F("h_CutFlow_Electron", "CutFlow for electron, ;Cuts;Events",10,0,10));
   TH1F* h_CutFlow_Photon(new TH1F("h_CutFlow_Photon", "CutFlow for photon, ;Cuts;Events",10,0,10));
   TH1F* h_HoverE_Electron(new TH1F("h_HoverE_Electron", "HoverE distribution, Electron, ;H/E;Number",40,0,0.1));
   TH1F* h_HoverE_Photon(new TH1F("h_HoverE_Photon", "HoverE distribution, Photon, ;H/E;Number",40,0,0.1));
   TH1F* h_ShowerShape(new TH1F("h_ShowerShape", "Showershape distribution, ;showershape;Number",80,0,0.05));
   TH1F* h_Pt(new TH1F("h_Pt", "Pt distribution, ;p_{T};Number",100,0,100));
   TH1F* h_Dr_Electrons(new TH1F("h_Dr_Electrons", "#Delta R between mcElectron and recoElectron from PHYS14 selection, ;#Delta R;Number",100,0,3));
   TH1F* h_Dr_ElectronJets(new TH1F("h_Dr_ElectronJets", "#Delta R between recoElectron and jets from PHYS14 selection, ;#Delta R;Number",100,0,3));
   TH1F* h_Ht(new TH1F("h_Ht", "Distribtuion of Ht;Ht;Events/4 GeV",1000,0,4000));
   TH1F* h_NTrks_All(new TH1F("h_NTrks_All", "Distribtuion of All Ntrks;NTrks;Events/4 GeV",50,0,200));
   
   TH1F* h_DeltaPhi_LeadPhotonMET(new TH1F("h_DeltaPhi_LeadPhotonMET", "Distribtuion of #Delta #phi between lead photon and MET;#Delta#phi;Events",25,0,3.5));
   TH1F* h_DeltaPhi_TrailPhotonMET(new TH1F("h_DeltaPhi_TrailPhotonMET", "Distribtuion of #Delta #phi between trail photon and MET;#Delta#phi;Events",25,0,3.5));
   TH1F* h_DeltaPhi_LeadElectronMET(new TH1F("h_DeltaPhi_LeadElectronMET", "Distribtuion of #Delta #phi between lead electron and MET;#Delta#phi;Events",25,0,3.5));
   TH1F* h_DeltaPhi_TrailElectronMET(new TH1F("h_DeltaPhi_TrailElectronMET", "Distribtuion of #Delta #phi between trail electron and MET;#Delta#phi;Events",25,0,3.5));
   TH1F* h_DeltaPhi_LeadFakeMET(new TH1F("h_DeltaPhi_LeadFakeMET", "Distribtuion of #Delta #phi between lead fake and MET;#Delta#phi;Events",25,0,3.5));
   TH1F* h_DeltaPhi_TrailFakeMET(new TH1F("h_DeltaPhi_TrailFakeMET", "Distribtuion of #Delta #phi between trail fake and MET;#Delta#phi;Events",25,0,3.5));
   
   
   float xbins[] = {0,2,5,10,17,25,34,45,57,70,84,100,125,175,250,400};
   int binnum = sizeof(xbins)/sizeof(Float_t) - 1;
   float diemptbins[] = {0,3,6,9,12,15,18,22,26,30,35,40,45,50,60,70,85,100,120,145,170,200};
   int diemptbinnum = sizeof(diemptbins)/sizeof(Float_t) - 1;
   
   TH1F* h_DoublePhoton_MET(new TH1F("h_DoublePhoton_MET","MET for double photon; MET (GeV); Events",binnum,xbins));
   TH1F* h_DoubleElectron_MET(new TH1F("h_DoubleElectron_MET","MET for double electron; MET (GeV); Events",binnum,xbins));
   TH1F* h_DoubleElectron_MET_Reweighted(new TH1F("h_DoubleElectron_MET_Reweighted","MET for double electron, diEMPt reweighted; MET (GeV); Events",binnum,xbins));
   TH1F* h_DoubleFake_MET(new TH1F("h_DoubleFake_MET","MET for double fake; MET (GeV); Events",binnum,xbins));
   TH1F* h_DoubleFake_MET_Reweighted(new TH1F("h_DoubleFake_MET_Reweighted","MET for double fake, diempt reweighted; MET (GeV); Events",binnum,xbins));
   TH1F* h_ElectronPhoton_MET(new TH1F("h_ElectronPhoton_MET","MET for electron-photon; MET (GeV); Events",binnum,xbins));
   TH1F* h_ElectronPhoton_InvMass(new TH1F("h_ElectronPhoton_InvMass","Invariant Mass for electron-photon; Invariant Mass (GeV); Events/ GeV",350,0,200));
   TH1F* h_DoubleElectron_InvMass(new TH1F("h_DoubleElectron_InvMass","Invariant Mass for double electron; Invariant Mass (GeV); Events/ GeV",350,0,200));
   TH1F* h_Scaled_ElectronPhoton_MET(new TH1F("h_Scaled_ElectronPhoton_MET","MET for electron-photon, scaled with fake rate; MET (GeV); Events",binnum,xbins));
   TH1F* h_DoubleElectron_DiEMPt(new TH1F("h_DoubleElectron_DiEMPt","DiEMPt for di-electron; DiEMPt (GeV); Events/ GeV", diemptbinnum, diemptbins));
   TH1F* h_DoublePhoton_DiEMPt(new TH1F("h_DoublePhoton_DiEMPt","DiEMPt for di-photon; DiEMPt (GeV); Events/ GeV", diemptbinnum, diemptbins));
   TH1F* h_DoubleFake_DiEMPt(new TH1F("h_DoubleFake_DiEMPt","DiEMPt for di-fake; DiEMPt (GeV); Events/ GeV", diemptbinnum, diemptbins));
   TH1F* h_DoubleElectron_Rho(new TH1F("h_DoubleElectron_Rho","Rho for di-electron; Rho; Events/ GeV",10,0,40));
   TH1F* h_DoublePhoton_Rho(new TH1F("h_DoublePhoton_Rho","Rho for di-photon; Rho; Events/ GeV",10,0,40));
   TH1F* h_DoubleFake_Rho(new TH1F("h_DoubleFake_Rho","Rho for di-fake; Rho; Events/ GeV",10,0,40));
   
   TH1F *h_DoubleElectron_MET_DiEMPtReweighted_ErrorPropagatedFromDiEMPt[1000];
    
   char *histNameee        = new char[50];
   char *histtitleee       = new char[50];

   for (int d=0;d<1000; ++d) {
     sprintf(histNameee, "DiEMPtReweightedee%d",d+1);
     sprintf(histtitleee,"Reweighted ee MET with DIEMPT %d",d+1);
     h_DoubleElectron_MET_DiEMPtReweighted_ErrorPropagatedFromDiEMPt[d]=new TH1F(histNameee,histtitleee,binnum, xbins);
   }
   
   TH1F *h_DoubleFake_MET_DiEMPtReweighted_ErrorPropagatedFromDiEMPt[1000];

   for (int d=0;d<1000; ++d) {
     sprintf(histNameee, "DiEMPtReweightedff%d",d+1);
     sprintf(histtitleee,"Reweighted ff MET with DIEMPT %d",d+1);
     h_DoubleFake_MET_DiEMPtReweighted_ErrorPropagatedFromDiEMPt[d]=new TH1F(histNameee,histtitleee,binnum, xbins);
   }
   
   
   
   TFile *Fnew = new TFile("DIEMPtRatioRRR.root","READ");
   TH1F *eephotondiempt = (TH1F*)Fnew->Get("eephotondiempt");
   TH1F *ffphotondiempt = (TH1F*)Fnew->Get("ffphotondiempt");
   
   TFile *FRandom = new TFile("RandomRatioErrorPropRRR.root","READ");
   TH1F *DiEMPtRatioGaus[1000];
   TH1F *DiEMPtRatioFFGaus[1000];
   
   // getting error propagation from diEMPt ratio
   for(int g=0; g<1000; ++g){
     char *nameGraph        = new char[40];

     sprintf(nameGraph,"DiEMPtee%d",g+1);
     DiEMPtRatioGaus[g] = (TH1F*)FRandom->Get(nameGraph);
     sprintf(nameGraph,"DiEMPtff%d",g+1);
     DiEMPtRatioFFGaus[g] = (TH1F*)FRandom->Get(nameGraph);
   }
   
   //float WEIGHT = 50100*1000*0.318*5/10017930.0;
   
   float fakerate = FFF;
   
   //TH1F* h_ShowerShape_Electron(new TH1F("h_ShowerShape_Electron", "Showershape distribution, electron;showershape;Events",40,0,0.1));
   if (fChain == 0) return;

   Long64_t nentries = fChain->GetEntriesFast();

   Long64_t nbytes = 0, nb = 0;
   bool Debug = false;
   
   int PhotonNu(0), FakeNu(0), ElectronNu(0), totalphoton(0), totalmismatchphoton(0);
   int EventCutFlow[10] = {0};//NeutralCut(0), EventChargedCut(0), EventPhotonIsoCut(0), EventShowerShapeCut(0), EventHoverECut(0), EventAfterPtCut(0);
   int EventElectronDr(0), EventOnlyElectron(0), EventHEElectron(0), TotalFake(0);
   TString CutFlowLabels[9] = {"nocut", "neutral", "charged", "photoniso","showershape","Pt","PixelMatch","HoverE","DeltaR"};
   cout << "Total Events: " << nentries << endl;
   
   
   for (Long64_t jentry=0; jentry<nentries;jentry++) {
      Long64_t ientry = LoadTree(jentry);
      if (ientry < 0) break;
      nb = fChain->GetEntry(jentry);   nbytes += nb;
      
      if(jentry %10000 == 0)cout << "processed: " << jentry << endl;
      //if(jentry > 200000)break;
      if(Debug)cout << "Just in event loop " << jentry << endl; 
      //if(jentry <  8810000)continue;
      
      int realphoton(0), fake(0), electron(0);
      int NeutralCut(0), ChargedCut(0), PhotonIsoCut(0), ShowerShapeCut(0), HoverECut(0), AfterPtCut(0), HoverECutElectron(0);
      int OnlyPhoton(0), OnlyElectron(0), NoCut(0);
      vector<int> realphoton_tracker, fake_tracker, electron_tracker, showershape_tracker, pt_tracker;
      realphoton_tracker.clear(); fake_tracker.clear(); electron_tracker.clear(); showershape_tracker.clear(); pt_tracker.clear();
      //if(MCPID->size()>0)cout <<"MC: " << MCPID->size() <<endl;
      /*if(jentry==17){
        cout << "nPho: " << nPho << endl;
        cout << "phoSize: " << phoEta->size() << endl;
      }*/ 
      int fakephoton_count(0);
      vector <float> PhotonEta, ElectronEta;
      vector <float> PhotonPhi, ElectronPhi;
      vector <float> GoodMuonEta, GoodMuonPhi;
      vector <float> FakePhotonPt, ElectronMatchedPtVect, DzVect;
      vector <float> NTrksVect;
      PhotonEta.clear(); ElectronEta.clear();
      GoodMuonEta.clear(); GoodMuonPhi.clear();
      PhotonPhi.clear(); ElectronPhi.clear();
      FakePhotonPt.clear(); ElectronMatchedPtVect.clear(); DzVect.clear();
      NTrksVect.clear();
      
      h_NTrks_All->Fill(NTrks, WEIGHT);
      
      
      // photon loop starts
      for(size_t i=0;i < PhoEta->size(); ++i){
        //cout << i << endl;
        if(Debug)cout << "Just in photon loop " << jentry << endl;
        float absEta = fabs(PhoEta->at(i));
        double effA[4];
        photonEffectiveAreas(absEta, effA);
        if((absEta > 1.479) || (PhoR9->at(i) > 1.0))continue;
	// containing newest cuts fron https://twiki.cern.ch/twiki/bin/viewauth/CMS/CutBasedPhotonIdentificationRun2
	
        float pt = fabs(PhoEt->at(i)); 
        bool neutral     = (PhoPFNeuIso->at(i) - Rho * effA[1] -  exp(0.0028*pt+0.5408)) < 7.23;
        bool charged     = (PhoPFChIso->at(i) - Rho * effA[0]) < 2.67;
        bool chargedfake = (PhoPFChIso->at(i) - Rho * effA[0]) > 2.67;
        bool chargedlim  = (PhoPFChIso->at(i) - Rho * effA[0]) < 15.;
        bool photoniso   = (PhoPFPhoIso->at(i) - Rho * effA[2] - 0.0014*pt) < 2.11;
        //printf("absEta: %f and effACh: %f effPh:%f and effN:%f\n", absEta,effA[0],effA[2],effA[1]);
        bool worstiso    = (PhoPFChWorstIso->at(i) -Rho*effA[3]) < 2.6;
        bool showercut   = PhoSigmaIEtaIEta->at(i) < 0.0107 ; 
        bool shower      = PhoSigmaIEtaIEta->at(i) < 0.014 ;
        bool pixelcut    = PhohasPixelSeed->at(i) == 0;
        //cout << phohasPixelSeed->at(i) << endl;
        bool HoverE      = PhoHoverE->at(i) < 0.028;
        bool SymPtCut    = pt > RRR;
        
        if(Debug)cout << "photon selection ends " << jentry << endl;
        //if(jentry==535519)printf("yy pixelseed head:%d\n",photon_pixelseed->at(i));
        NoCut++;
        if(neutral){
          NeutralCut++;
          if(charged){
            ChargedCut++;
            if(photoniso){
              PhotonIsoCut++;
              showershape_tracker.push_back(i);
              //h_ShowerShape->Fill(phoSigmaIEtaIEta->at(i));
              if(showercut){
                ShowerShapeCut++;
                pt_tracker.push_back(i);
                if(SymPtCut){
                  AfterPtCut++;
                  if(pixelcut){
                    OnlyPhoton++;
                    h_HoverE_Photon->Fill(PhoHoverE->at(i));
                    if(HoverE){
                      HoverECut++;
                    }
                  }
                  if(!pixelcut){
                    OnlyElectron++;
                    h_HoverE_Electron->Fill(PhoHoverE->at(i));
                    if(HoverE){
                      HoverECutElectron++;
                    }
                  }
                }
              }
            } 
          }
        }
        //if(neutral && charged && photoniso && pixelcut && HoverE && SymPtCut )h_ShowerShape_Photon->Fill(phoSigmaIEtaIEta->at(i));
        //if(neutral && charged && photoniso && !pixelcut && HoverE && SymPtCut )h_ShowerShape_Electron->Fill(phoSigmaIEtaIEta->at(i));
        
        
        
        
        /////////////// photon //////////////////////////////////
        if(neutral && charged && photoniso && showercut && pixelcut && HoverE && SymPtCut ){//
          //cout << "photon inside loop: " << jentry << endl; 
	  // photon GenLevel Matching
	  if(true){
	    realphoton++;
	    totalphoton++;
	    PhotonEta.push_back(PhoEta->at(i));
	    PhotonPhi.push_back(PhoPhi->at(i));
	    realphoton_tracker.push_back(i);
	  }
	  float drmin(9999);
          if(PhohasPixelSeed->at(i) != PhoEleVeto->at(i))totalmismatchphoton++;
          if(Debug)cout << "doublephoton selection  " << jentry << endl;
        } //worstiso not used*/
        
        
        
        
        
        //////////////////// fake ////////////////////////////////
        if(neutral && !charged && chargedlim && photoniso && showercut && pixelcut  && HoverE && SymPtCut ){
          fake++;
          fake_tracker.push_back(i);
          if(Debug)cout << "doublefake selection  " << jentry << endl;
        }
        
        
        
        
        
        
        ////////////////// electron ///////////////////////////////////
        if(neutral && charged && photoniso && showercut && !pixelcut && HoverE && SymPtCut ){// 
           electron++;
	  //cout << "electron inside loop: " << jentry << endl;
	  ElectronEta.push_back(PhoEta->at(i));
	  ElectronPhi.push_back(PhoPhi->at(i));
	  electron_tracker.push_back(i);
	}
      }// photon loop ends
      
      
      
      
      
      
      //muon selection
      vector<int> GoodMuonTracker;
      GoodMuonTracker.clear();
      if(Debug)cout << "Muon selection for entry: " << jentry << endl;
      for(size_t w=0; w < MuPt->size();++w){
        if(!(MuIsGood->at(w)==1 && fabs(MuEta->at(w))<1.479 && MuPt->at(w)>5))continue;
        //cout << "max: " << MuEta->at(w) << endl;
        float combIso  = MuPFChIso->at(w) + TMath::Max(0.,MuPFNeuIso->at(w) + MuPFPhoIso->at(w) - 0.5*MuPFPUIso->at(w));
        if( combIso/MuPt->at(w) > 0.20 )continue;
        GoodMuonEta.push_back(MuEta->at(w));
        GoodMuonPhi.push_back(MuPhi->at(w));
        GoodMuonTracker.push_back(w);
      }
      
      
      
      
      //jet selection
      unsigned int jetNum(0), jetNumAll(0);
      float ht(0);
      for(size_t w=0; w < JetPt->size(); ++w){
        if(!(JetPt->at(w) > 30 && JetPFLooseId))continue;//&& ) 
        float drminpho(9999), drminele(9999), drminmu(9999);
        if(Debug)cout << "photon: " << PhotonEta.size() << " electron: " << ElectronEta.size() << " muon: " << GoodMuonEta.size() << " for entry: " << jentry << endl;
        for(size_t r=0; r < PhotonEta.size(); ++r){
          float drJetPho = dRCalc(JetEta->at(w), JetPhi->at(w), PhotonEta.at(r), PhotonPhi.at(r));
          if(!(drJetPho < drminpho))continue;
          drminpho = drJetPho;
        }
        for(size_t r=0; r < ElectronEta.size(); ++r){
          float drJetEle = dRCalc(JetEta->at(w), JetPhi->at(w), ElectronEta.at(r), ElectronPhi.at(r));
          if(!(drJetEle < drminele))continue;
          drminele = drJetEle;
        }
        for(size_t r=0; r < GoodMuonEta.size(); ++r){
          float drJetMu = dRCalc(JetEta->at(w), JetPhi->at(w), GoodMuonEta.at(r), GoodMuonPhi.at(r));
          if(!(drJetMu < drminmu))continue;
          drminmu = drJetMu;
        }
        if( PhotonEta.size() > 0 && drminpho < 0.3 )continue;
        if( ElectronEta.size() > 0 && drminele < 0.3 )continue;
        if( GoodMuonEta.size() > 0 && drminmu < 0.3 )continue;
        if(Debug)cout << "Inside jet selection loop for entry: " << jentry << endl;
        jetNumAll++;
	if(fabs(JetEta->at(w) > 2.4))continue;
	//if(MCENumber < 2)continue;
	jetNum++;
        ht += JetPt->at(w);
        //cout << "Ht: " << ht << endl;
      }
      h_Ht->Fill(ht, WEIGHT);
      
      if(Debug)cout << "total jets: " << jetNum << " for entry:" << jentry << endl;
      
      
      // if (Cut(ientry) < 0) continue;
      if(realphoton == 1)h_SinglePhoton_MET->Fill(PFMET);
      if(realphoton >=2){
        PhotonNu++;
        float DR = dRCalc(PhoEta->at(realphoton_tracker.at(0)), PhoPhi->at(realphoton_tracker.at(0)), PhoEta->at(realphoton_tracker.at(1)), PhoPhi->at(realphoton_tracker.at(1)));
	float DiEMPt = findDiEMPt(PhoE->at(realphoton_tracker.at(0)), PhoEta->at(realphoton_tracker.at(0)), PhoPhi->at(realphoton_tracker.at(0)), PhoE->at(realphoton_tracker.at(1)), PhoEta->at(realphoton_tracker.at(1)), PhoPhi->at(realphoton_tracker.at(1)));
        if(DR>0.5){
          h_DoublePhoton_DiEMPt->Fill(DiEMPt, WEIGHT);
	  h_DoublePhoton_Rho->Fill(Rho, WEIGHT);
	  h_DoublePhoton_MET->Fill(PFMET, WEIGHT);
	  if(PhoEt->at(realphoton_tracker.at(0)) > PhoEt->at(realphoton_tracker.at(1))){
	    h_DeltaPhi_LeadPhotonMET->Fill(dPhiCalc(PhoPhi->at(realphoton_tracker.at(0)), PFMETPhi));
	    h_DeltaPhi_TrailPhotonMET->Fill(dPhiCalc(PhoPhi->at(realphoton_tracker.at(1)), PFMETPhi));
	  }
	  else{
	    h_DeltaPhi_LeadPhotonMET->Fill(dPhiCalc(PhoPhi->at(realphoton_tracker.at(1)), PFMETPhi));
	    h_DeltaPhi_TrailPhotonMET->Fill(dPhiCalc(PhoPhi->at(realphoton_tracker.at(0)), PFMETPhi));
	  }
          EventCutFlow[8]++;
          if(Debug)cout << "inside doublephoton  " << jentry << endl;
          h_Photon_MET->Fill(PFMET);
        }
      }
      
      // e-gamma sample selection //
      if(electron==1 && realphoton==1){
	float DR = dRCalc(PhoEta->at(realphoton_tracker.at(0)), PhoPhi->at(realphoton_tracker.at(0)), PhoEta->at(electron_tracker.at(0)), PhoPhi->at(electron_tracker.at(0)));
	float Mass = findMass(PhoE->at(realphoton_tracker.at(0)), PhoEta->at(realphoton_tracker.at(0)), PhoPhi->at(realphoton_tracker.at(0)), PhoE->at(electron_tracker.at(0)), PhoEta->at(electron_tracker.at(0)), PhoPhi->at(electron_tracker.at(0)));
        if(DR > 0.5){
	  h_ElectronPhoton_MET->Fill(PFMET, WEIGHT);
	  h_ElectronPhoton_InvMass->Fill(Mass, WEIGHT);
	  h_Scaled_ElectronPhoton_MET->Fill(PFMET, fakerate/(1-fakerate)*WEIGHT);
	}
      }
      
      if(fake == 1)h_SingleFake_MET->Fill(PFMET);
      if(fake >=2){
        FakeNu++;
        float DR = dRCalc(PhoEta->at(fake_tracker.at(0)), PhoPhi->at(fake_tracker.at(0)), PhoEta->at(fake_tracker.at(1)), PhoPhi->at(fake_tracker.at(1)));
	float DiEMPt = findDiEMPt(PhoE->at(fake_tracker.at(0)), PhoEta->at(fake_tracker.at(0)), PhoPhi->at(fake_tracker.at(0)), PhoE->at(fake_tracker.at(1)), PhoEta->at(fake_tracker.at(1)), PhoPhi->at(fake_tracker.at(1)));
        if(DR>0.5){
	  if(PhoEt->at(fake_tracker.at(0)) > PhoEt->at(fake_tracker.at(1))){
	    h_DeltaPhi_LeadFakeMET->Fill(dPhiCalc(PhoPhi->at(fake_tracker.at(0)), PFMETPhi));
	    h_DeltaPhi_TrailFakeMET->Fill(dPhiCalc(PhoPhi->at(fake_tracker.at(1)), PFMETPhi));
	  }
	  else{
	    h_DeltaPhi_LeadFakeMET->Fill(dPhiCalc(PhoPhi->at(fake_tracker.at(1)), PFMETPhi));
	    h_DeltaPhi_TrailFakeMET->Fill(dPhiCalc(PhoPhi->at(fake_tracker.at(0)), PFMETPhi));
	  }
          
	  h_DoubleFake_MET->Fill(PFMET, WEIGHT);
	  h_DoubleFake_DiEMPt->Fill(DiEMPt, WEIGHT);
	  h_DoubleFake_Rho->Fill(Rho, WEIGHT);
	  int BinC=ffphotondiempt->FindBin(DiEMPt);
          float WeightC=ffphotondiempt->GetBinContent(BinC);
	  h_DoubleFake_MET_Reweighted->Fill(PFMET, WEIGHT*WeightC);
	  for( int s=0 ; s<1000; ++s){
            float Weightprop = DiEMPtRatioFFGaus[s]->GetBinContent(BinC);
            h_DoubleFake_MET_DiEMPtReweighted_ErrorPropagatedFromDiEMPt[s]->Fill(PFMET, Weightprop*WEIGHT);
          }
          TotalFake++;
          h_Fake_MET->Fill(PFMET);
          if(Debug)cout << "inside doublefake  " << jentry << endl;
        }
      }
      if(electron == 1)h_SingleElectron_MET->Fill(PFMET);
      if(electron >=2){
        ElectronNu++;
        float DR = dRCalc(PhoEta->at(electron_tracker.at(0)), PhoPhi->at(electron_tracker.at(0)), PhoEta->at(electron_tracker.at(1)), PhoPhi->at(electron_tracker.at(1)));
	float Mass = findMass(PhoE->at(electron_tracker.at(0)), PhoEta->at(electron_tracker.at(0)), PhoPhi->at(electron_tracker.at(0)), PhoE->at(electron_tracker.at(1)), PhoEta->at(electron_tracker.at(1)), PhoPhi->at(electron_tracker.at(1)));
	
	float DiEMPt = findDiEMPt(PhoE->at(electron_tracker.at(0)), PhoEta->at(electron_tracker.at(0)), PhoPhi->at(electron_tracker.at(0)), PhoE->at(electron_tracker.at(1)), PhoEta->at(electron_tracker.at(1)), PhoPhi->at(electron_tracker.at(1)));
        h_DrAll->Fill(DR);
	if(DR > 0.5)h_DoubleElectron_InvMass->Fill(Mass, WEIGHT);
        if(DR > 0.5 && Mass >=75 && Mass <=105){
          h_DoubleElectron_DiEMPt->Fill(DiEMPt, WEIGHT);
	  h_DoubleElectron_Rho->Fill(Rho, WEIGHT);
	  if(PhoEt->at(electron_tracker.at(0)) > PhoEt->at(electron_tracker.at(1))){
	    h_DeltaPhi_LeadElectronMET->Fill(dPhiCalc(PhoPhi->at(electron_tracker.at(0)), PFMETPhi));
	    h_DeltaPhi_TrailElectronMET->Fill(dPhiCalc(PhoPhi->at(electron_tracker.at(1)), PFMETPhi));
	  }
	  else{
	    h_DeltaPhi_LeadElectronMET->Fill(dPhiCalc(PhoPhi->at(electron_tracker.at(1)), PFMETPhi));
	    h_DeltaPhi_TrailElectronMET->Fill(dPhiCalc(PhoPhi->at(electron_tracker.at(0)), PFMETPhi));
	  }
	  int BinC=eephotondiempt->FindBin(DiEMPt);
          float WeightC=eephotondiempt->GetBinContent(BinC);
	  h_DoubleElectron_MET_Reweighted->Fill(PFMET, WEIGHT*WeightC);
	  h_DoubleElectron_MET->Fill(PFMET, WEIGHT);
	  for( int s=0 ; s<1000; ++s){
            float Weightprop = DiEMPtRatioGaus[s]->GetBinContent(BinC);
            h_DoubleElectron_MET_DiEMPtReweighted_ErrorPropagatedFromDiEMPt[s]->Fill(PFMET, Weightprop*WEIGHT);
          }
          for(int l = 0; l < electron; ++l){
            vector<float> MinDR, MinDRJet;
            MinDR.clear(); MinDRJet.clear();
            /// working with MC electron ////
            float mindr = 0;
            if(MinDR.size()!=0) mindr = *std::min_element(MinDR.begin(),MinDR.end());
            if(Debug && jentry > 8813873)cout << "MinDr: " << mindr << endl;
            if(mindr!=0)h_Dr_Electrons->Fill(mindr);
          
            /// working with Jets ////
            for(size_t m = 0; m < JetEta->size(); ++m){
              if(Debug)cout << "inside Jet " << jentry << endl;
              if(Debug){
                cout << "inside Jet  " << jentry << endl;
                cout << "JetPt(" << m << "): " << JetPt->at(m) << endl;
                cout << "JetEta(" << m << "): " << JetEta->at(m) << endl;
                cout << "JetPhi(" << m << "): " << JetPhi->at(m) << endl;
              }
              if(Debug)cout << "Jets!!!" << endl;
              float DRJet = dRCalc(PhoEta->at(electron_tracker.at(l)), PhoPhi->at(electron_tracker.at(l)), JetEta->at(m), JetPhi->at(m));
              MinDRJet.push_back(DRJet);
            }
            float mindrjet = 0;
            if(MinDRJet.size()!=0) mindrjet = *std::min_element(MinDRJet.begin(),MinDRJet.end());
            if(Debug)cout << "MinDrJet: " << mindrjet << endl;
            if(mindrjet!=0)h_Dr_ElectronJets->Fill(mindrjet);
          }
          if(Debug)cout << "inside doubleelectron  " << jentry << endl;
          EventElectronDr++;
          h_Electron_MET->Fill(PFMET);
        }
      }
            
      
      
      if(NoCut>=2)EventCutFlow[0]++;
      if(NeutralCut>=2)EventCutFlow[1]++;
      if(ChargedCut>=2)EventCutFlow[2]++;
      if(PhotonIsoCut>=2){
        EventCutFlow[3]++;
        for(int k = 0; k < PhotonIsoCut; ++k){
          h_ShowerShape->Fill(PhoSigmaIEtaIEta->at(showershape_tracker.at(k))); 
        }
      }
      if(ShowerShapeCut>=2){
        EventCutFlow[4]++;
        if(ShowerShapeCut == 2){
          for(int k = 0; k < ShowerShapeCut; ++k){
            h_Pt->Fill(PhoEt->at(pt_tracker.at(k))); 
          }
        }
      }
      if(AfterPtCut>=2)EventCutFlow[5]++;
      if(OnlyPhoton>=2)EventCutFlow[6]++;
      if(HoverECut>=2)EventCutFlow[7]++;
      if(OnlyElectron>=2)EventOnlyElectron++;
      if(HoverECutElectron>=2)EventHEElectron++;
      // if (Cut(ientry) < 0) continue;
   }// event loop ends
   
   
   
   
   
   cout << "Double Photon events: " << EventCutFlow[8] << endl;
   cout << "DOuble Fake events: " << TotalFake << endl;
   cout << "Double Electron events: " << EventElectronDr << endl;
   cout << "Number of photons: " << totalphoton << endl;
   cout << "number of photons with pixel seed and csev mismatch: " << totalmismatchphoton << endl;
   for(int i = 0; i < 9; ++i){
     h_CutFlow_Photon->SetBinContent(i+1, EventCutFlow[i]);
     h_CutFlow_Photon->GetXaxis()->SetBinLabel(i+1,CutFlowLabels[i]);
     if(i > 5)continue;
     h_CutFlow_Electron->SetBinContent(i+1, EventCutFlow[i]);
     h_CutFlow_Electron->GetXaxis()->SetBinLabel(i+1,CutFlowLabels[i]);
   }
   h_CutFlow_Electron->SetBinContent(7, EventOnlyElectron);
   h_CutFlow_Electron->GetXaxis()->SetBinLabel(7, CutFlowLabels[6]);
   h_CutFlow_Electron->SetBinContent(8, EventHEElectron);
   h_CutFlow_Electron->GetXaxis()->SetBinLabel(8, CutFlowLabels[7]);
   h_CutFlow_Electron->SetBinContent(9, EventElectronDr);
   h_CutFlow_Electron->GetXaxis()->SetBinLabel(9, CutFlowLabels[8]);
     
   gROOT->SetBatch(true);
  
   
   
   
   f1->Write();
}
コード例 #21
0
TCanvas *PlotDataMCs(TChain *data, std::vector<TChain *> mc_vec, TString branchname, TString binning, 
		     TString category,  TString selection, 
		     TString dataLabel, std::vector<TString> mcLabel_vec, TString xLabel, TString yLabelUnit, TString outputPath, TString label4Print,
		     bool logy=false, bool usePU=true, bool ratio=true,bool smear=false, bool scale=false, bool useR9Weight=false, TString pdfIndex=""){
  std::cout<<"Using macro/PlotDataMC.C:: PlotDataMCs"<<std::endl;
  TStopwatch watch;
  watch.Start();
  //gStyle->SetOptStat(11);

  int nHist= mc_vec.size();
  int colors[4]={kRed,kGreen,kBlue,kCyan};
  int fillstyle[4]={0,0,0,0}; //3003,3004,3005,3006};
  if(nHist>4) return NULL;
  TString yLabel; 
  
  TCanvas *c = new TCanvas("c","");
  TPad * pad1 = new TPad("pad1", "pad1",0.01,0.13,0.75,1.);  
  TPad * pad2 = new TPad("pad2", "pad2",0.01,0.001,0.75,0.2);  
  TPad * pad3 = new TPad("pad3", "pad3",0.68,0.001,1.,0.2);
  
  pad1->SetRightMargin(0.1);
  pad1->SetLogy();
  pad1->Draw();
  pad1->cd();
  
  pad2->SetGrid();
  pad2->SetBottomMargin(0.4);
  pad2->SetRightMargin(0.1);
  pad2->Draw();
  pad2->cd();
  
  pad3->SetGrid();    
  //pad2->SetTopMargin(0.01);
  pad3->SetBottomMargin(0.4);
  pad3->SetRightMargin(0.1);
  pad3->Draw();
  pad3->cd();
    
  pad1->cd();
  
  TString branchNameData=branchname;
  TString branchNameMC=branchname;

  ElectronCategory_class cutter;
  data->SetBranchStatus("*",0);
  std::set<TString> branchList = cutter.GetBranchNameNtuple(category);
   for(std::set<TString>::const_iterator itr = branchList.begin();
       itr != branchList.end();
       itr++){
     std::cout << "[STATUS] Enabling branch: " << *itr << std::endl;
     data->SetBranchStatus(*itr, 1);
   }
   data->SetBranchStatus(branchname, 1);
   data->SetBranchStatus("scaleEle", 1);

  if(branchNameData.Contains("energySCEle_regrCorrSemiParV5_pho")) cutter.energyBranchName="energySCEle_regrCorrSemiParV5_pho";
  else if(branchNameData.Contains("energySCEle_regrCorrSemiParV5_ele")) cutter.energyBranchName="energySCEle_regrCorrSemiParV5_ele";
  else if (branchNameData.Contains("energySCEle")) cutter.energyBranchName="energySCEle";

  TCut selection_data="";
  if(category.Sizeof()>1) selection_data = cutter.GetCut(category, false,0,scale);
  selection_data+=selection;
  TCut selection_MC="";
  if(category.Sizeof()>1) selection_MC = cutter.GetCut(category, false,0);
  selection_MC+=selection;

  if(smear){
    std::cout<<"Apply smear to the MC"<<std::endl;
    branchNameMC.ReplaceAll("invMass_SC_corr","(invMass_SC_corr*sqrt(smearEle[0]*smearEle[1]))");
    branchNameMC.ReplaceAll("invMass_SC_regrCorr_pho","(invMass_SC_regrCorr_pho*sqrt(smearEle[0]*smearEle[1]))");
    branchNameMC.ReplaceAll("invMass_SC_regrCorrSemiParV5_pho","(invMass_SC_regrCorrSemiParV5_pho*sqrt(smearEle[0]*smearEle[1]))");
    branchNameMC.ReplaceAll("energySCEle_regrCorr_pho","(energySCEle_regrCorr_pho*smearEle) ");
    branchNameMC.ReplaceAll("energySCEle_corr[0]","(energySCEle_corr[0]*smearEle[0])");
    branchNameMC.ReplaceAll("energySCEle_corr[1]","(energySCEle_corr[1]*smearEle[1])");
    branchNameMC.ReplaceAll("energySCEle_regrCorr_pho[0]","(energySCEle_regrCorr_pho[0]*smearEle[0])");
    branchNameMC.ReplaceAll("energySCEle_regrCorr_pho[1]","(energySCEle_regrCorr_pho[1]*smearEle[1])");
    branchNameMC.ReplaceAll("energySCEle_regrCorrSemiParV5_ele[0]","(energySCEle_regrCorrSemiParV5_ele[0]*smearEle[0])");
    branchNameMC.ReplaceAll("energySCEle_regrCorrSemiParV5_ele[1]","(energySCEle_regrCorrSemiParV5_ele[1]*smearEle[1])");
    if(!branchNameMC.Contains("smear")) branchNameMC.ReplaceAll("energySCEle_regrCorrSemiParV5_ele","(energySCEle_regrCorrSemiParV5_ele*smearEle)");

  }
  if(scale){
    std::cout << "Apply scale to the data" << std::endl;
    branchNameData.ReplaceAll("invMass_SC_corr","(invMass_SC_corr*sqrt(scaleEle[0]*scaleEle[1]))");
    branchNameData.ReplaceAll("invMass_SC_regrCorr_pho","(invMass_SC_regrCorr_pho*sqrt(scaleEle[0]*scaleEle[1]))");
    branchNameData.ReplaceAll("invMass_SC_regrCorrSemiParV5_pho","(invMass_SC_regrCorrSemiParV5_pho*sqrt(scaleEle[0]*scaleEle[1]))");
    branchNameData.ReplaceAll("energySCEle_regrCorrSemiParV5_pho ","(energySCEle_regrCorrSemiParV5_pho*scaleEle)");
    branchNameData.ReplaceAll("energySCEle_corr[0]","(energySCEle_corr*scaleEle[0])");
    branchNameData.ReplaceAll("energySCEle_corr[1]","(energySCEle_corr*scaleEle[1])");
    branchNameData.ReplaceAll("energySCEle_regrCorrSemiParV5_pho[0]","(energySCEle_regrCorrSemiParV5_pho[0]*scaleEle[0])");
    branchNameData.ReplaceAll("energySCEle_regrCorrSemiParV5_pho[1]","(energySCEle_regrCorrSemiParV5_pho[1]*scaleEle[1])");
    branchNameData.ReplaceAll("energySCEle_regrCorrSemiParV5_ele[0]","(energySCEle_regrCorrSemiParV5_ele[0]*scaleEle[0])");
    branchNameData.ReplaceAll("energySCEle_regrCorrSemiParV5_ele[1]","(energySCEle_regrCorrSemiParV5_ele[1]*scaleEle[1])");
    if(!branchNameData.Contains("scale"))    branchNameData.ReplaceAll("energySCEle_regrCorrSemiParV5_ele","(energySCEle_regrCorrSemiParV5_ele*scaleEle)");
  }    

  std::cout <<"For data you are plotting: "<<branchNameData <<std::endl;
  std::cout <<"For MC your are plotting:  " << branchNameMC << std::endl;
  std::cout << "Selection for data is "<<selection_data<<std::endl;
  std::cout << "binning is "<<binning<<std::endl;
  
  // Draw histograms
    data->Draw(branchNameData+">>data_hist"+binning, selection_data);
    if(nHist > 0){//for MC
      for(std::vector<TChain *>::const_iterator mc_itr = mc_vec.begin();
	  mc_itr != mc_vec.end();
	  mc_itr++){
	TChain *mc = *mc_itr;
 	mc->SetBranchStatus("*",0);
 	for(std::set<TString>::const_iterator itr = branchList.begin();
 	    itr != branchList.end();
 	    itr++){
 	  //std::cout << "[STATUS] Enabling branch: " << *itr << std::endl;
 	  mc->SetBranchStatus(*itr, 1);
 	}
	mc->SetBranchStatus(branchname, 1);
	mc->SetBranchStatus("smearEle", 1);
	mc->SetBranchStatus("puWeight",1);
	mc->SetBranchStatus("mcGenWeight", 1);
	mc->SetBranchStatus("r9Weight", 1);
 	

	TString mcHistName;  mcHistName+="hist_"; mcHistName+=mc_itr-mc_vec.begin();//better for .C generation
	//TString mcHistName; mcHistName+=mc_itr-mc_vec.begin(); mcHistName+="_hist";//better for .C generation
	
	//decide this for MC
	//TString weights="mcGenWeight";
	//if(pdfIndex!="") weights+="*(pdfWeights_cteq66["+pdfIndex+"]/pdfWeights_cteq66[0])";
	//if(usePU) weights+="*puWeight";
	//if(useR9Weight) weights+="*r9Weight";
	//std::cout<<"Complete selection for MC is "<<selection_MC *weights.Data()<<std::endl;
	//mc->Draw(branchNameMC+">>"+mcHistName+binning, selection_MC *weights.Data());
	mc->Draw(branchNameMC+">>"+mcHistName+binning, selection_MC);
      }
    }


  c->Clear();
  TLegend *leg = new TLegend(0.5,0.7,0.7,0.85);
  leg->SetBorderSize(1);
  leg->SetFillColor(0);
  leg->SetTextSize(0.04);
//   if(dataLabel !="" && mcLabel !="") leg->Draw();
//   //c->GetListOfPrimitives()->Add(leg,"");


  TH1F *d = (TH1F *) gROOT->FindObject("data_hist");
  if(dataLabel !="") leg->AddEntry(d,dataLabel,"p");
  d->SetStats(0);
  d->SetTitle("");

  d->SetMarkerStyle(20);
  d->SetMarkerSize(1);

  if(d->GetEntries()==0 || d->Integral()==0){
    //d=(TH1F *) gROOT->FindObject("0_hist");
    d=(TH1F *) gROOT->FindObject("hist_0");
    d->SetMarkerSize(0);
  }
  //d->SaveAs("tmp/d_hist.root");
  //s->SaveAs("tmp/s_hist.root");

  yLabel.Form("Events /(%.2f %s)", d->GetBinWidth(2), yLabelUnit.Data());
  
  std::cout << "nEvents data: " << d->Integral() << "\t" << d->GetEntries() << std::endl;
  std::cout << "Now normalizing data to 1: "<<std::endl;
  std::cout << "80 is in bin "<<d->FindBin(80)<<std::endl;
  std::cout << "100 is in bin "<<d->FindBin(100)<<std::endl;
  std::cout << "d integral is "<<d->Integral()<<std::endl;
  std::cout << "d integral(1,100) is "<<d->Integral(1,100)<<std::endl;
  d->Scale(1./d->Integral());
  float max = 0;
  max=1.2*d->GetMaximum();
  std::cout << "max = " << max << std::endl;  

  d->GetYaxis()->SetTitle(yLabel);
  d->GetXaxis()->SetTitle(xLabel);
  if(logy){
    max*=10;
    d->GetYaxis()->SetRangeUser(0.1,max);
    c->SetLogy();
  } else {
      d->GetYaxis()->SetRangeUser(0,max);
  }

  for(int i=0; i < nHist; i++){
    //TString mcHistName; mcHistName+=i; mcHistName+="_hist";
    TString mcHistName; mcHistName+="hist_";mcHistName+=i;
    TH1F *s = (TH1F *) gROOT->FindObject(mcHistName);
    s->SetStats(0);
    s->SetTitle("");
    if(s==NULL) continue;
    std::cout << "nEvents signal: " << s->Integral() << "\t" << s->GetEntries() << std::endl;
    if(d->Integral()==0 && s->Integral()==0){
      delete c;
      return NULL;
    }
    if(logy){
      s->GetYaxis()->SetRangeUser(0.1,max);
    } else {
      s->GetYaxis()->SetRangeUser(0,max);
    }
    s->GetYaxis()->SetTitle(yLabel);
    s->GetXaxis()->SetTitle(xLabel);

    s->SetMarkerStyle(20);
    s->SetMarkerSize(1);
    s->SetMarkerColor(colors[i]);
    s->SetFillStyle(fillstyle[i]);
    s->SetFillColor(colors[i]);
    s->SetLineColor(colors[i]);
    s->SetLineWidth(2);

    TH1F* s_norm = NULL;
    if(i==0) s_norm = (TH1F *) (s->DrawNormalized("hist", d->Integral()));
    else s_norm = (TH1F *) (s->DrawNormalized("hist same", d->Integral()));
    if(logy){
      //d_norm->GetYaxis()->SetRangeUser(0.1,max);
      s_norm->GetYaxis()->SetRangeUser(0.1,max);
    } else {
      //d_norm->GetYaxis()->SetRangeUser(0,max);  
      s_norm->GetYaxis()->SetRangeUser(0,max);  
    }

    if(mcLabel_vec[i] !="") leg->AddEntry(s,mcLabel_vec[i], "lf");

//     TH1F *sRatio = (TH1F *) s->Clone(mcHistName+"_ratio");
//     sRatio->Divide(d);
//     if(ratio){
//       pad2->cd();
//       if(i==0) sRatio->Draw();
//       else sRatio->Draw("same");
//     }
//     pad1->cd();
  }

  //TH1F* d_norm = s_norm;
  //if(d!=s) d_norm = (TH1F *) (d->DrawNormalized("p same", d->Integral()));
  std::cout<<"After normalization "<<std::endl;
  //std::cout<<"s_norm" <<s_norm->Integral()<<std::endl;
  std::cout<<"data Integral " <<d->Integral()<<std::endl;
  if(nHist>0) d->Draw("p same");
  else d->Draw("p");

//   std::cout << "Variable  & Data & Simulation \\" << std::endl;
//   std::cout << "Mean      & " << d->GetMean() << " " << d->GetMeanError() 
// 	    << " & " << s_norm->GetMean() <<  " " << s_norm->GetMeanError() << " \\" << std::endl;
//   std::cout << "Std. dev. & " << d->GetRMS() << " " << d->GetRMSError() 
// 	    << " & " << s_norm->GetRMS() << " " << s_norm->GetRMSError() << " \\" << std::endl;
//   std::cout << "\\hline" << std::endl;
//   std::cout << "$\\Chi^2$ " <<  d->Chi2Test(s_norm, "UW CHI2/NDF NORM") << std::endl;
  
  if(mcLabel_vec.size()!=0) leg->Draw();

  TPaveText *pv = new TPaveText(0.25,0.95,0.65,1,"NDC");
  pv->AddText("CMS Preliminary 2016");
  pv->SetFillColor(0);
  pv->SetBorderSize(0);
  pv->Draw();

  watch.Stop();
  watch.Print();

  c->SaveAs(outputPath+label4Print+".png","png");
  c->SaveAs(outputPath+label4Print+".pdf","pdf");
  c->SaveAs(outputPath+label4Print+".eps","eps");
  c->SaveAs(outputPath+label4Print+".C","C");

  return c;

}
コード例 #22
0
ファイル: compareMet.C プロジェクト: hooberman/UserCode
void compareMet(){

  gStyle->SetOptStat(0);

  bool isData = true;

  char* file = "output/v8/ZJets_baby.root";
  if( isData ) file = "../../metTemplate/output/v8/lepdata_skim_baby.root";
  //if( isData ) file = "../output/V00-00-00/lepdata_skim_baby.root";
  //if( isData ) file = "output/uaf/lepdata_skim_baby.root";
  //if( isData ) file = "output/v8/lepdata_skim_nov4_baby_nov4json.root";
  //if( isData ) file = "output/uaf/lepdata_skim_baby.root";
  //if( isData ) file = "lepdata_skim_Nov4_baby.root";

  cout << "Adding " << file << endl;

  TFile *f = TFile::Open( file );

  TH1F* hee = new TH1F("hee","",75,0,150);
  TH1F* hmm = new TH1F("hmm","",75,0,150);
  TH1F* hem = new TH1F("hem","",75,0,150);

  TCut sel("njets>-1");
 
  TCut ee("leptype==0&&jetptll-ptll>-5&&jetptlt-ptlt>-5&&dilmass>81&&dilmass<101");
  //TCut ee("leptype==0&&dilmass>81&&dilmass<101");
  TCut mm("leptype==1&&nmatchedpfmuons==2&&dilmasspf>81&&dilmasspf<101");
  TCut em("leptype==2&&nmatchedpfmuons==1&&dilmass>81&&dilmass<101");

  //TCut ee("leptype==0&&jetptll-ptll>-5&&jetptlt-ptlt>-5");
  //TCut mm("leptype==1&&nmatchedpfmuons==2");
  //TCut em("leptype==2&&nmatchedpfmuons==1");

  //TCut weight("weight");
  TCut weight("1");

  TCanvas *c1 = new TCanvas();
  c1->cd();

  TPad *plotpad = new TPad("plotpad","plotpad",0.0,0.0,1.0,0.8);
  plotpad->Draw();
  plotpad->cd();

  TTree* T1 = (TTree*) f->Get("T1");

  T1->Draw("TMath::Min(pfmet,149.99)>>hee",(sel+ee)*weight);
  T1->Draw("TMath::Min(pfmet,149.99)>>hmm",(sel+mm)*weight);
  T1->Draw("TMath::Min(pfmet,149.99)>>hem",(sel+em)*weight);

  hee->Sumw2();
  hmm->Sumw2();
  hem->Sumw2();

  hmm->Draw();
  hmm->GetXaxis()->SetTitle("pfmet (GeV)");
  hee->SetLineColor(2);
  hee->SetMarkerColor(2);
  hem->SetLineColor(4);
  hem->SetMarkerColor(4);
  hmm->SetMarkerStyle(20);
  hem->SetMarkerStyle(24);
  hmm->SetMarkerSize(0.7);
  hee->Draw("samehist");
  hem->Draw("same");
  gPad->SetLogy(1);

  TLegend *leg = new TLegend(0.6,0.65,0.8,0.85);
  leg->AddEntry(hee,"ee","l");
  leg->AddEntry(hmm,"#mu#mu");
  leg->AddEntry(hem,"e#mu");
  leg->SetFillColor(0);
  leg->SetBorderSize(1);
  leg->Draw();

//   TLatex *t = new TLatex();
//   t->SetNDC();
//   if( isData ){
//     t->DrawLatex(0.4,0.6,  "CMS");
//     //t->DrawLatex(0.4,0.53, "Selected Z+#geq2jet Events (DATA)");
//     t->DrawLatex(0.4,0.53, "Selected Z Events (DATA)");
//     t->DrawLatex(0.4,0.46, "34.0 pb^{-1} at #sqrt{s} = 7 TeV");
//   }else{
//     t->DrawLatex(0.4,0.6, "CMS");
//     t->DrawLatex(0.4,0.53,"Selected Z+0jet Events (Z+jets MC)");
//   }

  c1->cd();

  TPad *pullpad = new TPad("pullpad","pullpad",0.0,0.8,1.0,1.0);
  pullpad->Draw();
  pullpad->cd();

  TH1F* hratio = (TH1F*) hmm->Clone();
  hratio->Divide(hee);
  hratio->Draw();
  gPad->SetGridy();
  hratio->SetMinimum(0.8);
  hratio->SetMaximum(1.6);
  hratio->GetYaxis()->SetLabelSize(0.15);
  hratio->GetYaxis()->SetNdivisions(7);
  hratio->GetYaxis()->SetTitle("#mu#mu / ee  ");
  hratio->GetXaxis()->SetTitle("");
  hratio->GetYaxis()->SetTitleSize(0.2);
  hratio->GetYaxis()->SetTitleOffset(0.2);

  float cut1 = 30;
  float cut2 = 60;
  float cut3 = 120;

  int bin1 = hee->FindBin(cut1);
  int bin2 = hee->FindBin(cut2);
  int bin3 = hee->FindBin(cut3);
  
  cout << "ee tot         " << hee->Integral() << endl;
  cout << "ee met>30  GeV " << hee->Integral(bin1,1000) << endl;
  cout << "ee met>60  GeV " << hee->Integral(bin2,1000) << endl;
  cout << "ee met>120 GeV " << hee->Integral(bin3,1000) << endl;

  cout << "mm tot         " << hmm->Integral() << endl;
  cout << "mm met>30  GeV " << hmm->Integral(bin1,1000) << endl;
  cout << "mm met>60  GeV " << hmm->Integral(bin2,1000) << endl;
  cout << "mm met>120 GeV " << hmm->Integral(bin3,1000) << endl;

  int width1 = 15;
  int width2 =  5;

  cout << "|" << setw(width1) << ""               << setw(width2)
       << "|" << setw(width1) << Form("N(met>%.0f GeV)",cut1)  << setw(width2)
       << "|" << setw(width1) << Form("N(met>%.0f GeV)",cut2)  << setw(width2)
       << "|" << setw(width1) << Form("N(met>%.0f GeV)",cut3)  << setw(width2) 
       << "|" << endl;

  cout << "|" << setw(width1) << "ee"                       << setw(width2)
       << "|" << setw(width1) << hee->Integral(bin1,1000)  << setw(width2)
       << "|" << setw(width1) << hee->Integral(bin2,1000)  << setw(width2)
       << "|" << setw(width1) << hee->Integral(bin3,1000) << setw(width2) 
       << "|" << endl;

  cout << "|" << setw(width1) << "mm"                       << setw(width2)
       << "|" << setw(width1) << hmm->Integral(bin1,1000)  << setw(width2)
       << "|" << setw(width1) << hmm->Integral(bin2,1000)  << setw(width2)
       << "|" << setw(width1) << hmm->Integral(bin3,1000) << setw(width2) 
       << "|" << endl;

  cout << "|" << setw(width1) << "em"                       << setw(width2)
       << "|" << setw(width1) << hem->Integral(bin1,1000)  << setw(width2)
       << "|" << setw(width1) << hem->Integral(bin2,1000)  << setw(width2)
       << "|" << setw(width1) << hem->Integral(bin3,1000) << setw(width2) 
       << "|" << endl;
}
コード例 #23
0
void display(){
  
  gROOT->ProcessLine(".x lhcbStyle.C");
  gStyle->SetPalette(1);
	
  string filename = "../analysed/SET9THL914.root";
	TFile* file = new TFile(filename.c_str(),"OPEN");

	int nBinsX=32; int nBinsY=32;
	int nPixelsX=64; int nPixelsY=64;
	
  std::cout<<"Making global intercept tot map"<<std::endl;
  // Global intercept map (not per pixel)
	TH2F* hToTMap = new TH2F("hToTMap","hToTMap",nBinsX,0,nPixelsX,nBinsY,0,nPixelsY);
	for(int x=0;x<nBinsX;x++){
		for(int y=0;y<nBinsY;y++){
			int id = x + y*nBinsX;
			// Get the ToT distribution for this location
			string histoname = "/tpanal/ClicpixAnalysis/hClusterTOTAssociated1pixMap"+makestring(id);
			TH1F* totMapHisto = 0;
			totMapHisto = (TH1F*)gDirectory->Get(histoname.c_str());
			if(totMapHisto == 0) continue;
			if(totMapHisto->GetEntries() < 20) continue;
	
			// Fit the tot distribution and enter the value in the ToT map
			totMapHisto->Fit("gaus","0q");
			TF1* fit = totMapHisto->GetFunction("gaus");
			hToTMap->Fill(x*floor(nPixelsX/nBinsX),y*floor(nPixelsY/nBinsY),fit->GetParameter(1));
			
			delete fit; delete totMapHisto;
		}
	}
	// Plot the map of ToT
	TCanvas* canv = new TCanvas();
	hToTMap->GetXaxis()->SetTitle("Column");
	hToTMap->GetYaxis()->SetTitle("Row");
  hToTMap->GetZaxis()->SetTitle("Mean charge (ToT)");
	hToTMap->SetMaximum(9);
	hToTMap->SetMinimum(5);
	hToTMap->DrawCopy("colz");

  
  std::cout<<"Making per pixel tot map"<<std::endl;
  // Per pixel map
  TH2F* hToTMapPerPixel = new TH2F("hToTMapPerPixel","hToTMapPerPixel",nPixelsX,0,nPixelsX,nPixelsY,0,nPixelsY);
  for(int x=0;x<nPixelsX;x++){
    for(int y=0;y<nPixelsY;y++){
      int id = x + y*nPixelsX;
      // Get the ToT distribution for this location
      string histoname = "/tpanal/ClicpixAnalysis/hClusterTOTAssociated1pixPixel"+makestring(id);
      TH1F* totMapHisto = 0;
      totMapHisto = (TH1F*)gDirectory->Get(histoname.c_str());
      if(totMapHisto == 0) continue;
      if(totMapHisto->GetEntries() < 10) continue;
      
      // Fit the tot distribution and enter the value in the ToT map
      totMapHisto->Fit("gaus","0q");
      TF1* fit = totMapHisto->GetFunction("gaus");
      hToTMapPerPixel->Fill(x,y,fit->GetParameter(1));
      
      delete fit; delete totMapHisto;
    }
  }
  // Plot the map of ToT
  TCanvas* canv2 = new TCanvas();
  hToTMapPerPixel->GetXaxis()->SetTitle("Column");
  hToTMapPerPixel->GetYaxis()->SetTitle("Row");
  hToTMapPerPixel->GetZaxis()->SetTitle("Mean charge (ToT)");
  hToTMapPerPixel->SetMaximum(10);
  hToTMapPerPixel->SetMinimum(0);
  hToTMapPerPixel->DrawCopy("colz");

  std::cout<<"Making pixel response tot maps"<<std::endl;
  // Pixel response maps
  int responseBins=100;
  double responseWidth=0.05;
  TH2F* hToTMapPixelResponseX = new TH2F("hToTMapPixelResponseX","hToTMapPixelResponseX",responseBins+1,-responseWidth,responseWidth,15,0,15);
  for(double rID=0;rID<responseBins;rID++){
    // Get the ToT distribution for this location
    string histoname = "/tpanal/ClicpixAnalysis/hClusterTOTAssociated1pixResponseX"+makestringD(rID);
    TH1F* totMapHisto = 0;
    totMapHisto = (TH1F*)gDirectory->Get(histoname.c_str());
    if(totMapHisto == 0) continue;
    if(totMapHisto->GetEntries() < 1) continue;
 		// loop over all tot bins
    for(int i=0;i<45;i++){
      hToTMapPixelResponseX->Fill(2.*responseWidth*(rID/100.)-responseWidth,i,totMapHisto->GetBinContent(totMapHisto->FindBin(i)));
    }
    delete totMapHisto;
  }
  // Plot the map of ToT
  TCanvas* canv3 = new TCanvas();
  hToTMapPixelResponseX->GetXaxis()->SetTitle("Track distance x (mm)");
  hToTMapPixelResponseX->GetYaxis()->SetTitle("ToT");
  hToTMapPixelResponseX->DrawCopy("colz");

  TH1F* hToTProfilePixelResponseY = new TH1F("hToTProfilePixelResponseY","hToTProfilePixelResponseY",responseBins+1,-responseWidth,responseWidth);
  TH2F* hToTMapPixelResponseY = new TH2F("hToTMapPixelResponseY","hToTMapPixelResponseY",responseBins+1,-responseWidth,responseWidth,16,0,16);
  for(double rID=0;rID<responseBins;rID++){
    // Get the ToT distribution for this location
    string histoname = "/tpanal/ClicpixAnalysis/hClusterTOTAssociated1pixResponseY"+makestringD(rID);
    TH1F* totMapHisto = 0;
    totMapHisto = (TH1F*)gDirectory->Get(histoname.c_str());
    if(totMapHisto == 0) continue;
    if(totMapHisto->GetEntries() < 1) continue;
    // loop over all tot bins
    for(int i=0;i<45;i++){
      hToTMapPixelResponseY->Fill(2.*responseWidth*(rID/100.)-responseWidth,i,totMapHisto->GetBinContent(totMapHisto->FindBin(i)));
    }
    hToTProfilePixelResponseY->Fill(2.*responseWidth*(rID/100.)-responseWidth+0.001,totMapHisto->GetXaxis()->GetBinCenter(totMapHisto->GetMaximumBin()));
    delete totMapHisto;
  }
  // Plot the map of ToT
  TCanvas* canv4 = new TCanvas();
  hToTMapPixelResponseY->GetXaxis()->SetTitle("Track distance y (mm)");
  hToTMapPixelResponseY->GetYaxis()->SetTitle("ToT");
  hToTMapPixelResponseY->GetZaxis()->SetTitle("Number of events");
  hToTMapPixelResponseY->DrawCopy("colz");
//  drawline(-0.03,1,7);
//  drawline(0.03,1,7);
	
  TCanvas* canv6 = new TCanvas();
  hToTProfilePixelResponseY->GetXaxis()->SetTitle("Track distance y (mm)");
  hToTProfilePixelResponseY->GetYaxis()->SetTitle("Most probable ToT");
  hToTProfilePixelResponseY->DrawCopy("");



  
  TCanvas* canv5 = new TCanvas();
  TH1F* sidebandLow = (TH1F*)gDirectory->Get("/tpanal/ClicpixAnalysis/hClusterTOTAssociated1pixResponseY20");
  TH1F* sidebandHigh = (TH1F*)gDirectory->Get("/tpanal/ClicpixAnalysis/hClusterTOTAssociated1pixResponseY80");
  sidebandHigh->GetXaxis()->SetTitle("ToT (single pixel)");
  sidebandHigh->GetXaxis()->SetRangeUser(0,20);
  sidebandHigh->DrawCopy("");
  sidebandLow->SetLineColor(2);
  sidebandLow->DrawCopy("same");

}
コード例 #24
0
void HwwNoteFigs(TString filename = "../histo_tmva_new-ntuples-1_160_0.root",
                 int mass = 170, int ReBin = 4, int ysel = 0)
{
	TFile* infile = new TFile(filename.Data(),"READ");
	setTDRStyle(0);
	
	//BDTD dists
	TCanvas* c1 = new TCanvas("c1","c1",0,-200,500,500);
	
        TH1F* histoBg =  histo4->Clone();
        histoBg->Add(histo3);
        histoBg->Add(histo2);
        histoBg->Add(histo1);

    	TH1F* histo_4 =  histo4->Clone();
    	histo3->Add(histo_4);
    	TH1F* histo_3 =  histo3->Clone();
    	histo2->Add(histo_3);
    	TH1F* histo_2 =  histo2->Clone();
    	histo1->Add(histo_2);

        histo1->Rebin(ReBin);
        histo1->SetFillColor(kBlue);
        histo1->SetFillStyle(1001);
        histo1->SetLineStyle(0);
        histo1->SetLineWidth(0);

        histo2->Rebin(ReBin);
        histo2->SetFillColor(kMagenta);
        histo2->SetFillStyle(1001);
        histo2->SetLineStyle(0);
        histo2->SetLineWidth(0);

        histo3->Rebin(ReBin);
        histo3->SetFillColor(kGreen);
        histo3->SetFillStyle(1001);
        histo3->SetLineStyle(0);
        histo3->SetLineWidth(0);
        
        histo4->Rebin(ReBin);
        histo4->SetFillColor(kCyan);
        histo4->SetFillStyle(1001);
        histo4->SetLineStyle(0);
        histo4->SetLineWidth(0);

        char YTitle[300];
        sprintf(YTitle,"events / bin");
        char XTitle[300];
        sprintf(XTitle,"BDT Output");
    	histo0->SetYTitle(YTitle);
    	histo1->SetYTitle(YTitle);
    	histo2->SetYTitle(YTitle);
    	histo3->SetYTitle(YTitle);
    	histo4->SetYTitle(YTitle);

    	histo0->SetXTitle(XTitle);
    	histo1->SetXTitle(XTitle);
    	histo2->SetXTitle(XTitle);
    	histo3->SetXTitle(XTitle);
    	histo4->SetXTitle(XTitle);
    	histo1->SetTitleSize(0.05, "X");
    	histo1->GetXaxis()->SetTitleFont(62);
    	histo1->GetXaxis()->SetLabelFont(61);
    	histo1->GetYaxis()->SetLabelFont(61); 
    	histo1->GetYaxis()->SetTitleOffset(1.3);
    	histo1->SetLabelSize(0.04, "Y");
    	histo1->SetLabelSize(0.04, "X");

	int min = histoBg->FindBin(-1.5);
	int max = histoBg->FindBin(1.5);

	histoBg->GetXaxis()->SetRange(min,max);
	
	histoBg->SetMarkerStyle(20);
	histoBg->SetMarkerSize(1.0);
	histoBg->GetYaxis()->SetTitleOffset(1.40);
	
	histo0->SetMarkerStyle(21);
	histo0->SetMarkerSize(1.0);
	
	histoBg->Rebin(ReBin);
	histo0->Rebin(ReBin);

	histoBg->SetLineColor(4);
	histo0->SetLineColor(1);

	scaleHist(histoBg);
	scaleHist(histo0);
	cout << "bg events: " << histoBg->GetSumOfWeights() << endl;
	cout << "si events: " << histo0->GetSumOfWeights() << endl;

	histoBg->SetYTitle("Events");
    	histo1->SetMinimum(0.01);
	if(ysel == 0)  {
	  histo1->Draw("hist");
	}
	else          {
	  histo0->Draw("E");
	  histo1->Draw("hist,same");
    	}
	histo2->Draw("hist,same");
    	histo3->Draw("hist,same");
    	histo4->Draw("hist,same");
    	histo0->Draw("E, same");
	//histoBg->DrawCopy("hist");
	//histo0->DrawCopy("hist,same");

	TLegend* leg = new TLegend(0.63, 0.75, 0.92, 0.92);
	leg->SetFillColor(0);
	char theSLine[100];
	if(mass != 999)	sprintf(theSLine,"Signal, m_{H}=%d GeV",mass);
	else    	sprintf(theSLine,"WW");
        cout << theSLine << endl;
	leg ->AddEntry(histo0,theSLine);
    	leg ->AddEntry(histo4,"W+Jets, W#gamma","F"); 
    	leg ->AddEntry(histo3,"di-boson","F");  
    	leg ->AddEntry(histo2,"t#bar{t}, tW","F"); 
    	leg ->AddEntry(histo1,"Drell-Yan","F"); 
	leg->Draw("same");
	
        TString fileOutput1(filename.Data());
	TString theLine = "_";
	theLine = theLine + "plot.eps";
        fileOutput1.ReplaceAll(".root",theLine.Data());
        fileOutput1.ReplaceAll("../","");
        fileOutput1.ReplaceAll("rootfiles_fastsim/","");
        fileOutput1.ReplaceAll("rootfiles_fullsim/","");
	c1->SaveAs(fileOutput1.Data());
        //return;
	//--------------------------------
	TCanvas* c3 = new TCanvas("c3","c3",550,-200,500,500);
	c3->SetLogx();
	c3->SetLogy();
	gPad->SetGrid(1,1);
	TGraphErrors* gBDTD = makeGraphFromHists(histo0, histoBg);
	gBDTD->Draw("APXl");
	TH1* zBDTD = gBDTD->GetHistogram();
	zBDTD->SetXTitle("Signal Events");
	zBDTD->SetYTitle("Signal/Background");
	//zBDTD->SetYTitle("Background Events");
	//zBDTD->DrawCopy();

	TLegend* leg3 = new TLegend(0.7, 0.7, 0.9, 0.9);
	leg3->SetFillColor(0);
	leg3->AddEntry(gBDTD,theSLine,"lp");
	leg3->Draw("same");
        TString fileOutput2(filename.Data());
	theLine = "_";
	theLine = theLine + "counts.eps";
        fileOutput2.ReplaceAll(".root",theLine.Data());
        fileOutput2.ReplaceAll("../","");
        fileOutput2.ReplaceAll("rootfiles_fastsim/","");
        fileOutput2.ReplaceAll("rootfiles_fullsim/","");
	c3->SaveAs(fileOutput2.Data());
	
}
コード例 #25
0
int main(int argc, char * argv[]) {

  // first argument - config file 
  // second argument - filelist

  using namespace std;

  // **** configuration
  Config cfg(argv[1]);

  const bool isData = cfg.get<bool>("IsData");
  const bool applyLeptonSF = cfg.get<bool>("ApplyLeptonSF");

  const bool applyGoodRunSelection = cfg.get<bool>("ApplyGoodRunSelection");

  // pile up reweighting
  const bool applyPUreweighting_vertices = cfg.get<bool>("ApplyPUreweighting_vertices");
  const bool applyPUreweighting_official = cfg.get<bool>("ApplyPUreweighting_official");


  // kinematic cuts on muons
  const float ptMuonLowCut   = cfg.get<float>("ptMuonLowCut");
  const float ptMuonHighCut  = cfg.get<float>("ptMuonHighCut");
  const float etaMuonHighCut = cfg.get<float>("etaMuonHighCut");
  const float etaMuonLowCut = cfg.get<float>("etaMuonLowCut");
  const float dxyMuonCut     = cfg.get<float>("dxyMuonCut");
  const float dzMuonCut      = cfg.get<float>("dzMuonCut");
  const float isoMuonCut     = cfg.get<float>("isoMuonCut");
  const bool  applyTauTauSelection = cfg.get<bool>("ApplyTauTauSelection");
  const bool  selectZToTauTauMuMu = cfg.get<bool>("SelectZToTauTauMuMu");

  // topological cuts
  const float dRleptonsCut   = cfg.get<float>("dRleptonsCut");
  const float DRTrigMatch    = cfg.get<float>("DRTrigMatch"); 
  const bool oppositeSign    = cfg.get<bool>("OppositeSign");


  // vertex cuts
  const float ndofVertexCut  = cfg.get<float>("NdofVertexCut");   
  const float zVertexCut     = cfg.get<float>("ZVertexCut");
  const float dVertexCut     = cfg.get<float>("DVertexCut");

  // jet related cuts
  const float jetEtaCut      = cfg.get<float>("JetEtaCut");
  const float jetEtaTrkCut   = cfg.get<float>("JetEtaTrkCut");
  const float jetPtHighCut   = cfg.get<float>("JetPtHighCut");
  const float jetPtLowCut    = cfg.get<float>("JetPtLowCut");
  const float dRJetLeptonCut = cfg.get<float>("dRJetLeptonCut");

  // Run range
  const unsigned int RunRangeMin = cfg.get<unsigned int>("RunRangeMin");
  const unsigned int RunRangeMax = cfg.get<unsigned int>("RunRangeMax");

  const string dataBaseDir = cfg.get<string>("DataBaseDir");
  // vertex distributions filenames and histname
  const string vertDataFileName = cfg.get<string>("VertexDataFileName");
  const string vertMcFileName   = cfg.get<string>("VertexMcFileName");
  const string vertHistName     = cfg.get<string>("VertexHistName");

  const string jsonFile = cfg.get<string>("jsonFile");
  string cmsswBase = (getenv ("CMSSW_BASE"));
  string fullPathToJsonFile = cmsswBase + "/src/DesyTauAnalyses/NTupleMaker/test/json/" + jsonFile;

  // Run-lumi selector
  std::vector<Period> periods;  
  if (isData) { // read the good runs 
	  std::fstream inputFileStream(fullPathToJsonFile.c_str(), std::ios::in);
  	  if (inputFileStream.fail() ) {
            std::cout << "Error: cannot find json file " << fullPathToJsonFile << std::endl;
            std::cout << "please check" << std::endl;
            std::cout << "quitting program" << std::endl;
	    exit(-1);
	  }
  
          for(std::string s; std::getline(inputFileStream, s); ) {
           periods.push_back(Period());
           std::stringstream ss(s);
           ss >> periods.back();
          }
  }

  // **** end of configuration
/*
  // Run-lumi selector
  std::vector<Period> periods;
    
  std::fstream inputFileStream("temp", std::ios::in);
  for(std::string s; std::getline(inputFileStream, s); )
    {
      periods.push_back(Period());
      std::stringstream ss(s);
      ss >> periods.back();
    }
*/
  char ff[100];

  sprintf(ff,"%s/%s",argv[3],argv[2]);
  // file name and tree name
  std::string rootFileName(argv[2]);
  std::ifstream fileList(ff);
  std::ifstream fileList0(ff);
  std::string ntupleName("makeroottree/AC1B");
  
  TString era=argv[3];
  TString TStrName(rootFileName);
  std::cout <<TStrName <<std::endl;  

  TFile * file = new TFile(era+"/"+TStrName+TString(".root"),"update");
  file->cd("");

  TH1D * inputEventsH = new TH1D("inputEventsH","",1,-0.5,0.5);
  TH1D * histWeightsH = new TH1D("histWeightsH","",1,-0.5,0.5);


  TH1D * metAll  = new TH1D("metAll","",400,0,4000);

  TH1D * hDiJetmet = new TH1D("hDiJetmet","",400,0,4000);
  TH1D * hDiJetmass = new TH1D("hDiJetmass","",400,0,4000);
  TH1D * hDiJet1mass = new TH1D("hDiJet1mass","",400,0,4000);
  TH1D * hDiJet2mass = new TH1D("hDiJet2mass","",400,0,4000);
  TH1D * hHT_ = new TH1D("hHT_","",400,0,4000);
  TH1D * PUweightsOfficialH = new TH1D("PUweightsOfficialH","PU weights w/ official reweighting",1000, 0, -1);

 // PILE UP REWEIGHTING - OPTIONS

  if (applyPUreweighting_vertices and applyPUreweighting_official) 
	{std::cout<<"ERROR: Choose only ONE PU reweighting method (vertices or official, not both!) " <<std::endl; exit(-1);}

  // reweighting with vertices

  // reading vertex weights
  TFile * fileDataNVert = new TFile(TString(cmsswBase)+"/src/"+dataBaseDir+"/"+vertDataFileName);
  TFile * fileMcNVert   = new TFile(TString(cmsswBase)+"/src/"+dataBaseDir+"/"+vertMcFileName);

  TH1F * vertexDataH = (TH1F*)fileDataNVert->Get(TString(vertHistName));
  TH1F * vertexMcH   = (TH1F*)fileMcNVert->Get(TString(vertHistName));

  float normVertexData = vertexDataH->GetSumOfWeights();
  float normVertexMc   = vertexMcH->GetSumOfWeights();

  vertexDataH->Scale(1/normVertexData);
  vertexMcH->Scale(1/normVertexMc);


 // reweighting official recipe 
  	// initialize pile up object
  PileUp * PUofficial = new PileUp();
  

  
  if (applyPUreweighting_official) {
    TFile * filePUdistribution_data = new TFile(TString(cmsswBase)+"/src/DesyTauAnalyses/NTupleMaker/data/PileUpDistrib/Data_Pileup_2015D_Nov17.root","read"); 
    TFile * filePUdistribution_MC = new TFile (TString(cmsswBase)+"/src/DesyTauAnalyses/NTupleMaker/data/PileUpDistrib/MC_Spring15_PU25_Startup.root", "read"); 
    TH1D * PU_data = (TH1D *)filePUdistribution_data->Get("pileup");
    TH1D * PU_mc = (TH1D *)filePUdistribution_MC->Get("pileup");
    PUofficial->set_h_data(PU_data); 
    PUofficial->set_h_MC(PU_mc);
  }

  

  int nFiles = 0;
  int nEvents = 0;
  int selEventsAllMuons = 0;
  int selEventsIdMuons = 0;
  int selEventsIsoMuons = 0;



  int nTotalFiles = 0;
  std::string dummy;
  // count number of files --->
  while (fileList0 >> dummy) nTotalFiles++;

  unsigned int RunMin = 9999999;
  unsigned int RunMax = 0;

  std::vector<unsigned int> allRuns; allRuns.clear();
 vector <unsigned int> run_;
 vector <unsigned int> lumi_;
 vector <unsigned int> event_;
 run_.clear();
 lumi_.clear();
 event_.clear();
 

    std::vector<Event> EventList;
    std::string line;
    std::ifstream EventsFile;
    TString file_events=argv[4]; //eventlist_csc2015.txt
    //EventsFile.open("MET_filters/eventlist_"+file_events+".txt");
    EventsFile.open(era+"/"+file_events+".txt");
    //cout<<"  limits  int -> "<<std::numeric_limits<int>::max()<<"  long int -> "<<std::numeric_limits<long int>::max()<<"  unsigned int -> "<<std::numeric_limits<unsigned int>::max()<<endl;
    cout<<" The file that will be used will be "<<era<<"/"<<file_events<<".txt"<<endl;


    while (getline(EventsFile, line))
    {
        std::vector<std::string> columns = split(line,':');
        run_.push_back(std::stoi(columns[0]));
        lumi_.push_back(std::stoi(columns[1]));
        event_.push_back(std::stoul(columns[2]));
   	/*   Event events_;

        events_.name     = "Test";
        events_.run     = std::stoi(columns[0]);
        events_.lumi   = std::stoi(columns[1]);
        events_.eventrn = std::stof(columns[2]);

        EventList.push_back(events_);
  */
      	}

  cout<<" In total there are "<<run_.size()<< " entries for "<<file_events<<" filter "<<endl;
    EventsFile.close();

//    for (unsigned int sz=0;sz<run_.size();sz++)
//	    cout<<" run "<<run_[sz]<<"  "<<lumi_[sz]<<"  "<<event_[sz]<<endl;
    /*
         for (const Event & m: EventList) 
	{
	if (m.run == 20286)
	cout<<"  "<<m.name<<"  "<<m.run<<"  "<<m.lumi<<"  "<<m.eventrn<<endl;
	}
*/

  //----Attention----//
  //if(XSec!=1) nTotalFiles=20;
  //nTotalFiles=5;
  //
  //
 

  std::string initNtupleName("initroottree/AC1B");

  for (int iF=0; iF<nTotalFiles; ++iF) {

    std::string filen;
    fileList >> filen;

    std::cout << "file " << iF+1 << " out of " << nTotalFiles << " filename : " << filen << std::endl;
    TFile * file_ = TFile::Open(TString(filen));
    
    TH1D * histoInputEvents = NULL;
    histoInputEvents = (TH1D*)file_->Get("makeroottree/nEvents");
    if (histoInputEvents==NULL) continue;
    int NE = int(histoInputEvents->GetEntries());
    for (int iE=0;iE<NE;++iE)
      inputEventsH->Fill(0.);
    std::cout << "      number of input events         = " << NE << std::endl;

    TTree * _inittree = NULL;
    _inittree = (TTree*)file_->Get(TString(initNtupleName));
    if (_inittree==NULL) continue;
    Float_t genweight;
    if (!isData)
      _inittree->SetBranchAddress("genweight",&genweight);
    Long64_t numberOfEntriesInitTree = _inittree->GetEntries();
    std::cout << "      number of entries in Init Tree = " << numberOfEntriesInitTree << std::endl;
    for (Long64_t iEntry=0; iEntry<numberOfEntriesInitTree; iEntry++) {
      _inittree->GetEntry(iEntry);
      if (isData)
	histWeightsH->Fill(0.,1.);
      else
	histWeightsH->Fill(0.,genweight);
    }

    TTree * _tree = NULL;
    _tree = (TTree*)file_->Get(TString(ntupleName));
    if (_tree==NULL) continue;
    Long64_t numberOfEntries = _tree->GetEntries();
    std::cout << "      number of entries in Tree      = " << numberOfEntries << std::endl;
    AC1B analysisTree(_tree);


    // EVENT LOOP //
    
    
    std::cout << "      number of entries in Tree = " << numberOfEntries << std::endl;
    
    for (Long64_t iEntry=0; iEntry<numberOfEntries; iEntry++) { 
    
      analysisTree.GetEntry(iEntry);
      nEvents++;
      
      if (nEvents%10000==0) 
	cout << "      processed " << nEvents << " events" << endl; 

      float weight = 1;



      //------------------------------------------------
      // vertex cuts
      
      if (fabs(analysisTree.primvertex_z)>zVertexCut) continue;
      if (analysisTree.primvertex_ndof<ndofVertexCut) continue;
      float dVertex = (analysisTree.primvertex_x*analysisTree.primvertex_x+
		       analysisTree.primvertex_y*analysisTree.primvertex_y);
      if (dVertex>dVertexCut) continue;

      if (!isData) 
	weight *=analysisTree.genweight;

      histWeightsH->Fill(float(0),weight);


      //cout<< " We have zero counts ? "<<analysisTree.primvertex_count<<endl;

      if (!isData) {
	if (applyPUreweighting_vertices) {
	  int binNvert = vertexDataH->FindBin(analysisTree.primvertex_count);
	  float_t dataNvert = vertexDataH->GetBinContent(binNvert);
	  float_t mcNvert = vertexMcH->GetBinContent(binNvert);
	  if (mcNvert < 1e-10){mcNvert=1e-10;}
	  float_t vertWeight = dataNvert/mcNvert;
	  weight *= vertWeight;
	  //	  cout << "NVert = " << analysisTree.primvertex_count << "   weight = " << vertWeight << endl;
	}

        if (applyPUreweighting_official) {

	double Ninteractions = analysisTree.numtruepileupinteractions;
	double PUweight = PUofficial->get_PUweight(Ninteractions);
	weight *= PUweight;
	PUweightsOfficialH->Fill(PUweight);

        }
      }
      if (isData){
	
	
	bool lumi = false;
	int n=analysisTree.event_run;
	int lum = analysisTree.event_luminosityblock;
	int nr = analysisTree.event_nr;

	std::string num = std::to_string(n);
	std::string lnum = std::to_string(lum);
	for(const auto& a : periods)
	  {
	    
	    if ( num.c_str() ==  a.name ) {
	      //std::cout<< " Eureka "<<num<<"  "<<a.name<<" ";
	      //     std::cout <<"min "<< last->lower << "- max last " << last->bigger << std::endl;
	      
	      for(auto b = a.ranges.begin(); b != std::prev(a.ranges.end()); ++b) {
		
		//	cout<<b->lower<<"  "<<b->bigger<<endl;
		if (lum  >= b->lower && lum <= b->bigger ) lumi = true;
	      }
	      auto last = std::prev(a.ranges.end());
	      //    std::cout <<"min "<< last->lower << "- max last " << last->bigger << std::endl;
	      if (  (lum >=last->lower && lum <= last->bigger )) lumi=true;
	      
	      
	    }
	    
	  }
    
	//if (lumi ) cout<<"  =============  Found good run"<<"  "<<n<<"  "<<lum<<endl;
	//std::remove("myinputfile");
	if (!lumi) continue;
        bool runbool=false;
	bool lumibool=false;
	bool eventbool=false;
	runbool= std::find(run_.begin(), run_.end(), n) != run_.end();
	lumibool= std::find(lumi_.begin(), lumi_.end(), lum) != lumi_.end();
	eventbool= std::find(event_.begin(), event_.end(), nr) != event_.end();

       if (runbool && lumibool && eventbool) continue;
//	cout<<"=========================================== >>>>>>>>>>>> "<<n<<"  "<<lum<<"  "<<nr<<endl;
/*	//cout<<" Will cross-check against the list now "<<endl;
        for (const Event & m: EventList) 
	{
	if (m.run == n && m.lumi==lnum && m.eventrn == nr)
	cout<<"=========================================== >>>>>>>>>>>>  "<<m.name<<"  "<<m.run<<"  "<<m.lumi<<"  "<<m.eventrn<<endl;
	}
*/
	}


      float metall = sqrt(analysisTree.pfmet_ex*analysisTree.pfmet_ex+analysisTree.pfmet_ey*analysisTree.pfmet_ey);
                
             metAll->Fill(metall,weight);

      if (analysisTree.event_run<RunMin)
	RunMin = analysisTree.event_run;
      
      if (analysisTree.event_run>RunMax)
	RunMax = analysisTree.event_run;
      
      //std::cout << " Run : " << analysisTree.event_run << std::endl;
      
      bool isNewRun = true;
      if (allRuns.size()>0) {
	for (unsigned int iR=0; iR<allRuns.size(); ++iR) {
	  if (analysisTree.event_run==allRuns.at(iR)) {
	    isNewRun = false;
	    break;
	  }
	}
      }
	
      if (isNewRun) 
	allRuns.push_back(analysisTree.event_run);
      

	// selecting good jets --->
	if (analysisTree.pfjet_count>1) { 
			
	  for (unsigned int jet=0; jet<2; ++jet) {
	  float energy = analysisTree.pfjet_e[jet];
	  float absJetEta = fabs(analysisTree.pfjet_eta[jet]);
	  float chf = analysisTree.pfjet_chargedhadronicenergy[jet]/energy;
	  float nhf = analysisTree.pfjet_neutralhadronicenergy[jet]/energy;
	  float phf = analysisTree.pfjet_neutralemenergy[jet]/energy;
	  float elf = analysisTree.pfjet_chargedemenergy[jet]/energy;
	  float chm = analysisTree.pfjet_chargedmulti[jet];
	  float npr = analysisTree.pfjet_chargedmulti[jet] + analysisTree.pfjet_neutralmulti[jet];
	  bool isPFJetId = (npr>1 && phf<0.99 && nhf<0.99) && (absJetEta>2.4 || (elf<0.99 && chf>0 && chm>0));
	  if (!isPFJetId) continue;

	  if ( analysisTree.pfjet_pt[0] > 200. && analysisTree.pfjet_pt[1] > 200.) 
	  { 
          float metSel = sqrt(analysisTree.pfmet_ex*analysisTree.pfmet_ex+analysisTree.pfmet_ey*analysisTree.pfmet_ey);
	  hDiJetmet->Fill(metSel, weight);
	  
	  TLorentzVector jmass1; jmass1.SetPxPyPzE(analysisTree.pfjet_px[0],
					analysisTree.pfjet_py[0],
					analysisTree.pfjet_pz[0],
					analysisTree.pfjet_e[0]);

	  TLorentzVector jmass2; jmass2.SetPxPyPzE(analysisTree.pfjet_px[1],
					analysisTree.pfjet_py[1],
					analysisTree.pfjet_pz[1],
					analysisTree.pfjet_e[1]);

	  TLorentzVector dijet = jmass1 + jmass2;
	  hDiJetmass->Fill(dijet.M(),weight);
	  hDiJet1mass->Fill(jmass1.M(),weight);
	  hDiJet2mass->Fill(jmass2.M(),weight);

	  }
         }
	 }	 
     // HT variables
	float HT_=0;
	for (unsigned int jet=0; jet<analysisTree.pfjet_count; ++jet) {
	  float absJetEta = fabs(analysisTree.pfjet_eta[jet]);
	  if (absJetEta>jetEtaCut) continue;
          
	  

	  float energy = analysisTree.pfjet_e[jet];
	  float chf = analysisTree.pfjet_chargedhadronicenergy[jet]/energy;
	  float nhf = analysisTree.pfjet_neutralhadronicenergy[jet]/energy;
	  float phf = analysisTree.pfjet_neutralemenergy[jet]/energy;
	  float elf = analysisTree.pfjet_chargedemenergy[jet]/energy;
	  float chm = analysisTree.pfjet_chargedmulti[jet];
	  float npr = analysisTree.pfjet_chargedmulti[jet] + analysisTree.pfjet_neutralmulti[jet];
	  bool isPFJetId = (npr>1 && phf<0.99 && nhf<0.99) && (absJetEta>2.4 || (elf<0.99 && chf>0 && chm>0));
	  if (!isPFJetId) continue;
	  
	  HT_=HT_+analysisTree.pfjet_pt[jet];

	  }	  
        
	  hHT_->Fill(HT_,weight);



      
    } // end of file processing (loop over events in one file)
    nFiles++;
    delete _tree;
    file_->Close();
    delete file_;
  }
  std::cout << std::endl;
  int allEvents = int(inputEventsH->GetEntries());
  std::cout << "Total number of input events                     = " << allEvents << std::endl;
  std::cout << "Total number of events in Tree                   = " << nEvents << std::endl;
  std::cout << "Total number of selected events (iso muon pairs) = " << selEventsIsoMuons << std::endl;
  std::cout << std::endl;
  std::cout << "RunMin = " << RunMin << std::endl;
  std::cout << "RunMax = " << RunMax << std::endl;

  //cout << "weight used:" << weight << std::endl;

  // using object as comp
  std::sort (allRuns.begin(), allRuns.end(), myobject);
  std::cout << "Runs : ";
  for (unsigned int iR=0; iR<allRuns.size(); ++iR)
    std::cout << " " << allRuns.at(iR);
  std::cout << std::endl;
  
  file->Write();
  file->Close();
  delete file;
  
  }
コード例 #26
0
void compareSherpaMadgraph(std::string sherpafile, std::string madgraphfile,
                           std::string var,
                           float xmin=-9999.0, float xmax=-9999.0,
                           bool logScale=false,
                           std::string output="test")
{

    setTDRStyle();
    gStyle->SetOptStat(0);

    TH1F* hsherpa;
    TH1F* hmadgraph;

    char tempName[300];


    // first get the histogram files
    TFile *fsherpa = TFile::Open(sherpafile.data());
    TFile *fmadgraph   = TFile::Open(madgraphfile.data());

    hsherpa  = (TH1F*)(fsherpa->Get(var.data()));
    hmadgraph    = (TH1F*)(fmadgraph->Get(var.data()));

    TH1D* hscale =(TH1D*) hsherpa->Clone("hscale");
    hscale->SetYTitle("SHERPA/MADGRAPH");

    int nREBIN=2;
    if(var.find("pt")!= std::string::npos)
        nREBIN=4;

    hsherpa->GetXaxis()->SetNdivisions(5);
    hsherpa->GetYaxis()->SetDecimals();
    hsherpa->Rebin(nREBIN);

    hmadgraph->GetXaxis()->SetNdivisions(5);
    hmadgraph->GetYaxis()->SetDecimals();
    hmadgraph->Rebin(nREBIN);

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

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


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

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

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

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

    }

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


    //   float scale_mc = (float)hsherpa->Integral(binLo,binHi)/(float)hmadgraph->Integral(binLo,binHi);
    //   cout << "binLo = " << binLo << ", binHi = " << binHi << endl;
    //   cout << "xmin = " << xmin << "xmax = " << xmax << endl;

    //   hmadgraph->Sumw2();
    //   hmadgraph->Scale(scale_mc);

    float scale_sherpa   = 1000.0*4.890*3048.0/4.71644910071102437e+06;

    float scale_madgraph = 1000.0*4.890*3048.0/3.59644320000000000e+07;

    hsherpa->Sumw2();
    hsherpa->Scale(scale_sherpa);

    hmadgraph->Sumw2();
    hmadgraph->Scale(scale_madgraph);

    cout << "hmadgraph integral = " << hmadgraph->Integral() << endl;
    cout << "hsherpa integral = "   << hsherpa->Integral() << endl;;

    // get the ratio
    double chi2 = 0;
    int realbin = 0;
    for(int i=1; i<= nbins; i++) {

        double nmc=hmadgraph->GetBinContent(i);
        double ndata=hsherpa->GetBinContent(i);
        double nmcerr=hmadgraph->GetBinError(i);
        double ndataerr=hsherpa->GetBinError(i);

        if(nmc<0 || ndata<0)continue;

        if(nmcerr==0 && ndataerr==0)continue;

        if(nmc==0 && ndata==0)continue;

        double chi2ndef = (nmc-ndata)*(nmc-ndata)/
                          ( nmcerr*nmcerr+ ndataerr*ndataerr);
        chi2 += chi2ndef;
        realbin++;

        cout << "Bin " << i << " : " << ndata << ", " << nmc;
        cout << " " << chi2ndef << endl;


        // now calculate the ratio
        if(nmc==0 || nmcerr==0 || ndata==0 || ndataerr==0)continue;
        cout << "Bin " << i << " ratio = " << ndata/nmc << endl;
        hscale->SetBinContent(i,ndata/nmc);
        double err = 0;
        err=
            (ndata/nmc)*sqrt(pow(nmcerr/nmc,2)+pow(ndataerr/ndata,2));
        hscale->SetBinError(i,err);

    }


    hsherpa->GetXaxis()->SetRangeUser(xmin,xmax);
    hmadgraph->GetXaxis()->SetRangeUser(xmin,xmax);
    hscale->GetXaxis()->SetRangeUser(xmin,xmax);


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


    float max_data  = hsherpa->GetBinError(hsherpa->GetMaximumBin()) + hsherpa->GetMaximum();
    float max_mc    = hmadgraph->GetBinError(hmadgraph->GetMaximumBin()) + hmadgraph->GetMaximum();

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


    float x1NDC = 0.691;
    float y1NDC = 0.757;
    float x2NDC = 0.894;
    float y2NDC = 0.973;

    TLegend* leg = new TLegend(x1NDC,y1NDC,x2NDC,y2NDC);

    leg->SetFillColor(0);
    leg->SetFillStyle(0);
    leg->SetTextSize(0.04);
    leg->SetBorderSize(0);
    leg->AddEntry(hsherpa, "SHERPA");
    leg->AddEntry(hmadgraph, "MADGRAPH");
    leg->Draw("same");



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


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

    std::string filename;
    std::string psname = dirName + "/" + var;
    if(output !="test")
        psname = dirName+ "/" + output;
    else
        psname = dirName+ "/" + var;
    filename = psname + ".eps";
    c1->Print(filename.data());
    filename = psname + ".gif";
    c1->Print(filename.data());
    filename = psname + ".pdf";
    c1->Print(filename.data());
    //   c1->Close();
}
コード例 #27
0
void 
HBB_LEP_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., const char* inputfile="root/$HISTFILE", const char* directory="bb_$CATEGORY")
{
  // define common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  // determine category tag
  const char* category_extra = "";
  if(std::string(directory) == std::string("bb_had0"  )){ category_extra = "all-had_{0}";  }
  if(std::string(directory) == std::string("bb_had1"  )){ category_extra = "all-had_{1}";  }
  if(std::string(directory) == std::string("bb_had2"  )){ category_extra = "all-had_{2}";  }
  if(std::string(directory) == std::string("bb_had3"  )){ category_extra = "all-had_{3}";  }
  if(std::string(directory) == std::string("bb_had4"  )){ category_extra = "all-had_{4}";  }
  if(std::string(directory) == std::string("bb_had5"  )){ category_extra = "all-had_{5}";  }
  if(std::string(directory) == std::string("bb_lep"   )){ category_extra = "semi-lep";  }

  const char* dataset;
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "Preliminary, #sqrt{s} = 7 TeV, L = 4.8 fb^{-1}";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "Preliminary, #sqrt{s} = 8 TeV, L = 19.4 fb^{-1}";}
  
  TFile* input = new TFile(inputfile);
  TH1F* bkgBBB  = refill((TH1F*)input->Get(TString::Format("%s/bkgBBB"   , directory)), "bkgBBB"); InitHist(bkgBBB, "", "", kMagenta-10, 1001);;
#ifdef MSSM
  float bbHScale = 1.; // scenario for MSSM, mhmax, mA=160, tanb=20, A+H for the time being
  if(std::string(inputfile).find("7TeV")!=std::string::npos){ bbHScale = (23314.3*0.879 + 21999.3*0.877)/1000.; }
  if(std::string(inputfile).find("8TeV")!=std::string::npos){ bbHScale = (31087.9*0.879 + 29317.8*0.877)/1000.; }
 //  float bbHScale = 1.; // scenario for MSSM, mhmax, mA=160, tanb=10, A+H for the time being
//   if(std::string(inputfile).find("7TeV")!=std::string::npos){ bbHScale = (6211.6*0.89 + 5145.0*0.85)/1000.; }
//   if(std::string(inputfile).find("8TeV")!=std::string::npos){ bbHScale = (8282.7*0.89 + 6867.8*0.85)/1000.; }
  TH1F* bbH  = refill((TH1F*)input->Get(TString::Format("%s/bbH160"  , directory)), "bbH"  ); InitSignal(bbH); bbH->Scale(bbHScale);
#endif
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
  InitHist(data, "#bf{m_{b#bar{b}} [GeV]}", "#bf{dN/dm_{b#bar{b}} [1/GeV]}"); InitData(data);

  TH1F* ref=(TH1F*)bkgBBB->Clone("ref");

  double unscaled[7];
  unscaled[0] = bkgBBB ->Integral();
#ifdef MSSM
  unscaled[1] = bbH ->Integral();
  unscaled[2] = 0;
#endif

  if(scaled){
    rescale(bkgBBB,   1);
#ifdef MSSM 
    rescale(bbH,   2);
#endif
  }

  TH1F* scales[7];
  scales[0] = new TH1F("scales-bkgBBB", "", 3, 0, 3);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (bkgBBB  ->Integral()/unscaled[0]-1.) : 0.);
#ifdef MSSM
  scales[1] = new TH1F("scales-bbH"  , "", 3, 0, 3);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? (bbH  ->Integral()/unscaled[1]-1.) : 0.);
  scales[2] = new TH1F("scales-NONE" , "", 3, 0, 3);
  scales[2]->SetBinContent(3, 0.);
#endif

  if(!log){
#ifdef MSSM
    bbH  ->Add(bkgBBB);
#endif
  }

  /*
    mass plot before and after fit
  */
  TCanvas* canv = MakeCanvas("canv", "histograms", 600, 600);
  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(0, data->FindBin(350)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(1000)); };
#endif

  data->SetNdivisions(505);
  data->SetMinimum(min);
  data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(bkgBBB, log)));
  data->Draw("e");

  TH1F* errorBand = (TH1F*)bkgBBB ->Clone();
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(1);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);

  if(log){
    bkgBBB  ->Draw("histsame");
    $DRAW_ERROR
#ifndef DROP_SIGNAL
    bbH     ->Draw("histsame");
#endif
  }
  else{  
#ifndef DROP_SIGNAL
    bbH     ->Draw("histsame");
#endif  
    bkgBBB  ->Draw("histsame");
    $DRAW_ERROR
  }
  data->Draw("esame");
  canv->RedrawAxis();

  //CMSPrelim(dataset, "b#bar{b}", 0.17, 0.835);
  CMSPrelim(dataset, "", 0.17, 0.835);  
  TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "NDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText("b#bar{b}");
  chan->Draw();

  TPaveText* cat      = new TPaveText(0.20, 0.68+0.061, 0.32, 0.68+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();
 
#ifdef MSSM
  TPaveText* massA      = new TPaveText(0.75, 0.48+0.061, 0.85, 0.48+0.161, "NDC");
  massA->SetBorderSize(   0 );
  massA->SetFillStyle(    0 );
  massA->SetTextAlign(   12 );
  massA->SetTextSize ( 0.03 );
  massA->SetTextColor(    1 );
  massA->SetTextFont (   62 );
  massA->AddText("m_{A}=160GeV");
  massA->Draw();

  TPaveText* tanb      = new TPaveText(0.75, 0.44+0.061, 0.85, 0.44+0.161, "NDC");
  tanb->SetBorderSize(   0 );
  tanb->SetFillStyle(    0 );
  tanb->SetTextAlign(   12 );
  tanb->SetTextSize ( 0.03 );
  tanb->SetTextColor(    1 );
  tanb->SetTextFont (   62 );
  tanb->AddText("tan#beta=20");
  tanb->Draw();

  TPaveText* scen      = new TPaveText(0.75, 0.40+0.061, 0.85, 0.40+0.161, "NDC");
  scen->SetBorderSize(   0 );
  scen->SetFillStyle(    0 );
  scen->SetTextAlign(   12 );
  scen->SetTextSize ( 0.03 );
  scen->SetTextColor(    1 );
  scen->SetTextFont (   62 );
  scen->AddText("mhmax");
  scen->Draw();
#endif


#ifdef MSSM  
  TLegend* leg = new TLegend(0.55, 0.65, 0.94, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(bbH  , "#phi#rightarrowb#bar{b}" , "L" );
#endif
  leg->AddEntry(data,   "observed"                       , "LP");
  leg->AddEntry(bkgBBB, "bkgBBB"                      , "F" );
  $ERROR_LEGEND
  leg->Draw();

//#ifdef MSSM
//  TPaveText* mssm  = new TPaveText(0.69, 0.85, 0.90, 0.90, "NDC");
//  mssm->SetBorderSize(   0 );
//  mssm->SetFillStyle(    0 );
//  mssm->SetTextAlign(   12 );
//  mssm->SetTextSize ( 0.03 );
//  mssm->SetTextColor(    1 );
//  mssm->SetTextFont (   62 );
//  mssm->AddText("(m_{A}=250, tan#beta=5)");
//  mssm->Draw();
//#else
//  TPaveText* mssm  = new TPaveText(0.83, 0.85, 0.95, 0.90, "NDC");
//  mssm->SetBorderSize(   0 );
//  mssm->SetFillStyle(    0 );
//  mssm->SetTextAlign(   12 );
//  mssm->SetTextSize ( 0.03 );
//  mssm->SetTextColor(    1 );
//  mssm->SetTextFont (   62 );
//  mssm->AddText("m_{H}=125");
//  mssm->Draw();
//#endif

  /*
    Ratio Data over MC
  */
  TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
  canv0->SetGridx();
  canv0->SetGridy();
  canv0->cd();

  TH1F* zero = (TH1F*)ref ->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)data->Clone("rat"); 
  rat1->Divide(bkgBBB);
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
    zero->SetBinContent(ibin+1, 0.);
  }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+1.5);
  rat1->SetMinimum(-1.5);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
  rat1->GetXaxis()->SetTitle("#bf{m_{b#bar{b}} [GeV]}");
  rat1->Draw();
  zero->SetLineColor(kBlack);
  zero->Draw("same");
  canv0->RedrawAxis();

  /*
    Ratio After fit over Prefit
  */
  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  TH1F* rat2 = (TH1F*) bkgBBB->Clone("rat2");
  rat2->Divide(ref);
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    if(rat2->GetBinContent(ibin+1)>0){
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
    }
  }
  rat2->SetLineColor(kRed+ 3);
  rat2->SetFillColor(kRed-10);
  rat2->SetMaximum(+0.3);
  rat2->SetMinimum(-0.3);
  rat2->GetYaxis()->SetTitle("#bf{Fit/Prefit-1}");
  rat2->GetYaxis()->CenterTitle();
  rat2->GetXaxis()->SetTitle("#bf{m_{b#bar{b}} [GeV]}");
  rat2->GetXaxis()->SetRange(0, 28);
  rat2->Draw();
  zero->SetLineColor(kBlack);
  zero->Draw("same");
  canv1->RedrawAxis();

  /*
    Relative shift per sample
  */
  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
  canv2->SetGridx();
  canv2->SetGridy();
  canv2->cd();

  InitHist  (scales[0], "", "", kMagenta-10, 1001);
  scales[0]->Draw();
  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{bkgBBB}");
#ifdef MSSM
  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{bbH}"  );
  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{NONE}" );
#endif
  scales[0]->SetMaximum(+1.0);
  scales[0]->SetMinimum(-1.0);
  scales[0]->GetYaxis()->CenterTitle();
  scales[0]->GetYaxis()->SetTitle("#bf{Fit/Prefit-1}");
  zero->Draw("same");
  canv2->RedrawAxis();

  /*
    prepare output
  */
  bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.png"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.pdf"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.eps"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  TFile* output = new TFile(TString::Format("%s_%sscaled_%s_%s.root", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""), "update");
  output->cd();
  data ->Write("data_obs");
  bkgBBB  ->Write("bkgBBB"  );
#ifdef MSSM
  bbH  ->Write("bbH"     );
#endif
  if(errorBand){
    errorBand->Write("errorBand");
  }
  output->Close();
}
コード例 #28
0
void RAA_calo_pf_JetCorrelation_pp(int startfile = 10, int endfile = 11, int radius=2, int deltaR=2/*which i will divide by 10 later when using*/, Float_t CALOPTCUT = 30.0, Float_t PFPTCUT = 30.0, char *dataset = "MC", char *etaWidth = "n20_eta_p20"){

  TH1::SetDefaultSumw2();

  TStopwatch timer;
  timer.Start();

  TDatime date;
  
  bool printDebug = false;

  // Since this has to run on the HiForest files, it is best to run them as condor jobs similar to the Pp data read macro, along with the jet trees which get their branch address set. 
  
  std::string infile1;
  if(dataset == "Data")infile1 = "jetRAA_pp_data_forest.txt";
  if(dataset == "MC")infile1 = "jetRAA_pp_mc_forest.txt";

  std::ifstream instr1(infile1.c_str(),std::ifstream::in);
  std::string filename1;

  cout<<"reading from "<<startfile<<" to "<<endfile<<endl;

  if(dataset=="MC"){
    for(int ifile = 0;ifile<4*startfile;ifile++){
      instr1>>filename1;
    }
  }
  if(dataset=="Data"){
    for(int ifile = 0;ifile<startfile;ifile++){
      instr1>>filename1;
    }
  }

  
  const int N = 5;
  
  TChain *jetpp1[N][no_radius];

  string dir[N][no_radius];
  
  for(int k = 0;k<no_radius;k++){
    dir[0][k] = "hltanalysis";
    dir[1][k] = "skimanalysis";
    dir[2][k] = Form("ak%dCaloJetAnalyzer",3);
    dir[3][k] = Form("ak%dPFJetAnalyzer",radius);
    dir[4][k] = "hiEvtAnalyzer";
    //dir[5][k] = "hltobject";
    //dir[6][k] = "pfcandAnalyzer";
  }
  
  
  string trees[N] = {
    "HltTree",
    "HltTree",
    "t",
    "t",
    "HiTree"
    //"jetObjTree",
    //"pfTree"
  };
  
  //this loop is to assign the tree values before we go into the file loop. 
  for(int k = 0;k<no_radius;k++){
    for(int t = 0;t<N;t++){
      jetpp1[t][k] = new TChain(string(dir[t][k]+"/"+trees[t]).data());
    }//tree loop ends
  }// radius loop ends
  
  if(dataset == "Data"){
    for(int ifile = startfile;ifile<endfile;ifile++){
    
      instr1>>filename1;
      if(printDebug)cout<<"File: "<<filename1<<endl;
      for(int k = 0;k<no_radius;k++){

	for(int t = 0;t<N;t++){
	
	  jetpp1[t][k]->Add(filename1.c_str());
	  if(printDebug)cout << "Tree loaded  " << string(dir[t][k]+"/"+trees[t]).data() << endl;
	  if(printDebug)cout << "Entries : " << jetpp1[t][k]->GetEntries() << endl;
		
	}// tree loop ends
      
      }// radius loop ends
    
    }// file loop ends

  }

  // these different file loops for MC is necessary because of eachfile being split into 4 files except the last pthat 540 which has 5 files. 
  if(dataset == "MC" && startfile <10){
    for(int ifile = 4*startfile;ifile<4*endfile;ifile++){
    
      instr1>>filename1;
      if(printDebug)cout<<"File: "<<filename1<<endl;
      for(int k = 0;k<no_radius;k++){

	for(int t = 0;t<N;t++){
	
	  jetpp1[t][k]->Add(filename1.c_str());
	  if(printDebug)cout << "Tree loaded  " << string(dir[t][k]+"/"+trees[t]).data() << endl;
	  if(printDebug)cout << "Entries : " << jetpp1[t][k]->GetEntries() << endl;
		
	}// tree loop ends
      
      }// radius loop ends
    
    }// file loop ends

  }

  if(dataset == "MC" && startfile == 10){
    for(int ifile = 4*startfile;ifile<4*endfile+1;ifile++){
    
      instr1>>filename1;
      if(printDebug)cout<<"File: "<<filename1<<endl;
      for(int k = 0;k<no_radius;k++){

	for(int t = 0;t<N;t++){
	
	  jetpp1[t][k]->Add(filename1.c_str());
	  if(printDebug)cout << "Tree loaded  " << string(dir[t][k]+"/"+trees[t]).data() << endl;
	  if(printDebug)cout << "Entries : " << jetpp1[t][k]->GetEntries() << endl;
		
	}// tree loop ends
      
      }// radius loop ends
    
    }// file loop ends

  }
  
  for(int k = 0;k<no_radius;k++){
    jetpp1[2][k]->AddFriend(jetpp1[0][k]);
    jetpp1[2][k]->AddFriend(jetpp1[1][k]);
    jetpp1[2][k]->AddFriend(jetpp1[4][k]);
    //jetpp1[2][k]->AddFriend(jetpp1[5][k]);
    
    jetpp1[3][k]->AddFriend(jetpp1[0][k]);
    jetpp1[3][k]->AddFriend(jetpp1[1][k]);
    jetpp1[3][k]->AddFriend(jetpp1[4][k]);
    //jetpp1[3][k]->AddFriend(jetpp1[5][k]);
    
  }// radius loop ends
 
  // Ok this should now work. 

  cout<<"total no of entries in the combined forest files = "<<jetpp1[2][0]->GetEntries()<<endl;
  //  if(printDebug)cout<<"total no of entries in the Jet80 Tree     = "<<jetpp2[2][0]->GetEntries()<<endl;

  // get the centrality weight, vz weight and the scale from the cross section, pt weighting. 
  static const Int_t nbins_pthat = 11;
  Double_t xsection[nbins_pthat+1] = {2.034e-01, 1.075e-02, 1.025e-03,  9.865e-05, 1.129e-05, 1.465e-06, 2.837e-07, 5.323e-08, 5.934e-09, 8.125e-10, 1.468e-10, 0};
  Double_t boundaries_pthat[nbins_pthat+1] = {15, 30, 50, 80, 120, 170, 220, 280, 370, 460, 540, 2000};
  TH1F * hpthatBin = new TH1F("hpthatBin","",nbins_pthat, boundaries_pthat);

  // Vertex reweighting for pp
  TF1 *fVzPP = new TF1("fVzPP","[0]+[1]*x+[2]*x*x+[3]*x*x*x+[4]*x*x*x*x");
  fVzPP->SetParameters(8.41684e-01,-2.58609e-02,4.86550e-03,-3.10581e-04,2.07918e-05);
  
  
  TFile f(Form("/net/hisrv0001/home/rkunnawa/WORK/RAA/CMSSW_5_3_20/src/Output/pp_%s_closure_histogram_noJetID_deltaR_0p%d_ak%d_%d_%d.root",dataset,deltaR,radius,date.GetDate(),endfile),"RECREATE");
  f.cd();


  //set the branch addresses:
  // jet tree 1 - Calo 
  int nrefe_1;
  float pt_1[1000];
  float raw_1[1000];
  float refpt_1[1000];
  float eta_1[1000];
  float phi_1[1000];
  float chMax_1[1000];
  float trkMax_1[1000];
  float chSum_1[1000];
  float phSum_1[1000];
  float neSum_1[1000];
  float trkSum_1[1000];
  float phMax_1[1000];
  float neMax_1[1000];
  float eMax_1[1000];
  float muMax_1[1000];
  float eSum_1[1000];
  float muSum_1[1000];
  float jtpu_1[1000];
  float hcalSum_1[1000];
  float ecalSum_1[1000];
  int subid_1[1000];
  
  // jet tree 2 - PF
  int nrefe_2;
  float pt_2[1000];
  float raw_2[1000];
  float refpt_2[1000];
  float eta_2[1000];
  float eta_2_CM[1000];
  float phi_2[1000];
  float chMax_2[1000];
  float trkMax_2[1000];
  float chSum_2[1000];
  float phSum_2[1000];
  float neSum_2[1000];
  float trkSum_2[1000];
  float phMax_2[1000];
  float neMax_2[1000];
  float eMax_2[1000];
  float muMax_2[1000];
  float eSum_2[1000];
  float muSum_2[1000];
  float jtpu_2[1000];
  float hcalSum_2[1000];
  float ecalSum_2[1000];
  int subid_2[1000];
  
  // event tree
  int evt_1;
  int run_1;
  int lumi_1;
  float pthat_1;
  float vx_1;
  float vy_1;
  float vz_1;
  int hiNpix_1;
  int hiNtracks_1;
  float hiHF_1;
  float hiHFminus_1;
  float hiHFplus_1;
  float hiHFplusEta4_1;
  float hiHFminusEta4_1;
  int pPAcollisionEventSelectionPA_1;
  int pHBHENoiseFilter_1;
  int pprimaryvertexFilter_1;
  int pVertexFilterCutGplus_1;

  // trigger tree
  int jet40_1;
  int jet60_1;
  int jet80_1;
  int jet40_p_1;
  int jet60_p_1;
  int jet80_p_1;

  for(int k = 0;k<no_radius;k++){
    //set the branch addresses:  - one of the most boring parts of the code: 
    jetpp1[2][k]->SetBranchAddress("evt",&evt_1);
    jetpp1[2][k]->SetBranchAddress("run",&run_1);
    jetpp1[2][k]->SetBranchAddress("lumi",&lumi_1);
    if(dataset=="MC") jetpp1[2][k]->SetBranchAddress("pthat",&pthat_1);
    jetpp1[2][k]->SetBranchAddress("vz",&vz_1);
    jetpp1[2][k]->SetBranchAddress("vx",&vx_1);
    jetpp1[2][k]->SetBranchAddress("vy",&vy_1);
    jetpp1[2][k]->SetBranchAddress("hiNpix",&hiNpix_1);
    jetpp1[2][k]->SetBranchAddress("hiNtracks",&hiNtracks_1);
    jetpp1[2][k]->SetBranchAddress("hiHFminus",&hiHFminus_1);
    jetpp1[2][k]->SetBranchAddress("hiHF",&hiHF_1);
    jetpp1[2][k]->SetBranchAddress("hiHFplus",&hiHFplus_1);
    jetpp1[2][k]->SetBranchAddress("hiHFplusEta4",&hiHFplusEta4_1);
    jetpp1[2][k]->SetBranchAddress("hiHFminusEta4",&hiHFminusEta4_1);
    jetpp1[2][k]->SetBranchAddress("pPAcollisionEventSelectionPA",&pPAcollisionEventSelectionPA_1);
    jetpp1[2][k]->SetBranchAddress("pHBHENoiseFilter",&pHBHENoiseFilter_1);
    //jetpp1[2][k]->SetBranchAddress("pprimaryvertexFilter",&pprimaryvertexFilter_1);
    //jetpp1[2][k]->SetBranchAddress("pVertexFilterCutGplus",&pVertexFilterCutGplus_1);
  
    jetpp1[2][k]->SetBranchAddress("nref",&nrefe_1);
    jetpp1[2][k]->SetBranchAddress("jtpt",&pt_1);
    jetpp1[2][k]->SetBranchAddress("jteta",&eta_1);
    jetpp1[2][k]->SetBranchAddress("jtphi",&phi_1);
    jetpp1[2][k]->SetBranchAddress("rawpt",&raw_1);
    jetpp1[2][k]->SetBranchAddress("jtpu",&jtpu_1);
    jetpp1[2][k]->SetBranchAddress("chargedMax",&chMax_1);
    jetpp1[2][k]->SetBranchAddress("chargedSum",&chSum_1);
    jetpp1[2][k]->SetBranchAddress("trackMax",&trkMax_1);
    jetpp1[2][k]->SetBranchAddress("trackSum",&trkSum_1);
    jetpp1[2][k]->SetBranchAddress("photonMax",&phMax_1);
    jetpp1[2][k]->SetBranchAddress("photonSum",&phSum_1);
    jetpp1[2][k]->SetBranchAddress("neutralMax",&neMax_1);
    jetpp1[2][k]->SetBranchAddress("neutralSum",&neSum_1);
    jetpp1[2][k]->SetBranchAddress("eSum",&eSum_1);
    jetpp1[2][k]->SetBranchAddress("eMax",&eMax_1);
    jetpp1[2][k]->SetBranchAddress("muSum",&muSum_1);
    jetpp1[2][k]->SetBranchAddress("muMax",&muMax_1);
    jetpp1[2][k]->SetBranchAddress("ecalSum",&ecalSum_1);
    jetpp1[2][k]->SetBranchAddress("hcalSum",&hcalSum_1);
    
    jetpp1[3][k]->SetBranchAddress("nref",&nrefe_2);
    jetpp1[3][k]->SetBranchAddress("jtpt",&pt_2);
    jetpp1[3][k]->SetBranchAddress("jteta",&eta_2);
    jetpp1[3][k]->SetBranchAddress("jtphi",&phi_2);
    jetpp1[3][k]->SetBranchAddress("rawpt",&raw_2);
    jetpp1[3][k]->SetBranchAddress("jtpu",&jtpu_2);
    jetpp1[3][k]->SetBranchAddress("chargedMax",&chMax_2);
    jetpp1[3][k]->SetBranchAddress("chargedSum",&chSum_2);
    jetpp1[3][k]->SetBranchAddress("trackMax",&trkMax_2);
    jetpp1[3][k]->SetBranchAddress("trackSum",&trkSum_2);
    jetpp1[3][k]->SetBranchAddress("photonMax",&phMax_2);
    jetpp1[3][k]->SetBranchAddress("photonSum",&phSum_2);
    jetpp1[3][k]->SetBranchAddress("neutralMax",&neMax_2);
    jetpp1[3][k]->SetBranchAddress("neutralSum",&neSum_2);
    jetpp1[3][k]->SetBranchAddress("eSum",&eSum_2);
    jetpp1[3][k]->SetBranchAddress("eMax",&eMax_2);
    jetpp1[3][k]->SetBranchAddress("muSum",&muSum_2);
    jetpp1[3][k]->SetBranchAddress("muMax",&muMax_2);
    jetpp1[3][k]->SetBranchAddress("ecalSum",&ecalSum_2);
    jetpp1[3][k]->SetBranchAddress("hcalSum",&hcalSum_2);
    
    if(dataset=="MC"){

      jetpp1[2][k]->SetBranchAddress("subid",&subid_1);
      jetpp1[3][k]->SetBranchAddress("subid",&subid_2);
      jetpp1[2][k]->SetBranchAddress("refpt",&refpt_1);
      jetpp1[3][k]->SetBranchAddress("refpt",&refpt_2);

    }
    

    jetpp1[2][k]->SetBranchAddress("HLT_PAJet40_NoJetID_v1",&jet40_1);
    jetpp1[2][k]->SetBranchAddress("HLT_PAJet40_NoJetID_v1_Prescl",&jet40_p_1);
    jetpp1[2][k]->SetBranchAddress("HLT_PAJet60_NoJetID_v1",&jet60_1);
    jetpp1[2][k]->SetBranchAddress("HLT_PAJet60_NoJetID_v1_Prescl",&jet60_p_1);
    jetpp1[2][k]->SetBranchAddress("HLT_PAJet80_NoJetID_v1",&jet80_1);
    jetpp1[2][k]->SetBranchAddress("HLT_PAJet80_NoJetID_v1_Prescl",&jet80_p_1);

    // jetpp1[2][k]->SetBranchAddress("id",&trgObj_id_1);
    // jetpp1[2][k]->SetBranchAddress("pt",&trgObj_pt_1);
    // jetpp1[2][k]->SetBranchAddress("eta",&trgObj_eta_1);
    // jetpp1[2][k]->SetBranchAddress("phi",&trgObj_phi_1);
    // jetpp1[2][k]->SetBranchAddress("mass",&trgObj_mass_1);
    
    /*
    jetpp1[2][k]->SetBranchAddress("nPFpart", &nPFpart);
    jetpp1[2][k]->SetBranchAddress("pfId", pfId);
    jetpp1[2][k]->SetBranchAddress("pfPt", pfPt);
    jetpp1[2][k]->SetBranchAddress("pfVsPtInitial", pfVsPtInitial);
    jetpp1[2][k]->SetBranchAddress("pfVsPt", pfVsPt);
    jetpp1[2][k]->SetBranchAddress("pfEta", pfEta);
    jetpp1[2][k]->SetBranchAddress("pfPhi", pfPhi);
    jetpp1[2][k]->SetBranchAddress("pfArea", pfArea);
    jetpp1[2][k]->SetBranchAddress("vn",&v_n);
    jetpp1[2][k]->SetBranchAddress("psin",&psi_n);
    jetpp1[2][k]->SetBranchAddress("sumpt",&sumpT);
    */

  }// radius loop
  cout<<"after branch declaration"<<endl;

  cout<<"after histogram declaration"<<endl;

  Float_t calopt, pfpt, deltar, chMax, phMax, neMax, muMax, eMax, chSum, phSum, neSum, muSum, eSum, hcalSum, ecalSum;
  Int_t  jet80, jet80_prescl, jet60, jet60_prescl, jet40, jet40_prescl; 
  Int_t evt_value;
  Int_t run_value;
  Int_t lumi_value;
  Float_t weight;
  Float_t subid, pfrawpt, calorawpt, pfrefpt, calorefpt, pfjtpu, calojtpu, vz, pthat, caloeta, calophi, pfeta, pfphi;
  
  TTree* matchJets = new TTree("matchedJets","Ntuple containing important information about matched jets");
  matchJets->Branch("calopt",&calopt,"calopt/F");   matchJets->Branch("phSum",&phSum,"phSum/F");
  matchJets->Branch("pfpt",&pfpt,"pfpt/F");         matchJets->Branch("neSum",&neSum,"neSum/F");
  matchJets->Branch("deltar",&deltar,"deltar/F");   matchJets->Branch("muSum",&muSum,"muSum/F");
  matchJets->Branch("chMax",&chMax,"chMax/F");      matchJets->Branch("eSum",&eSum,"eSum/F");
  matchJets->Branch("phMax",&phMax,"phMax/F"); 
  matchJets->Branch("neMax",&neMax,"neMax/F");      matchJets->Branch("jet80",&jet80,"jet80/I");
  matchJets->Branch("muMax",&muMax,"muMax/F");      matchJets->Branch("jet80_prescl",&jet80_prescl,"jet80_prescl/I");
  matchJets->Branch("eMax",&eMax,"eMax/F");         matchJets->Branch("jet60",&jet60,"jet60/I");
  matchJets->Branch("chSum",&chSum,"chSum/F");      matchJets->Branch("jet60_prescl",&jet60_prescl,"jet60_prescl/I");
  matchJets->Branch("jet40",&jet40,"jet40/I");      matchJets->Branch("jet40_prescl",&jet40_prescl,"jet40_prescl/I");
  matchJets->Branch("hcalSum",&hcalSum,"hcalSum/F");matchJets->Branch("ecalSum",&ecalSum,"ecalSum/F");
  matchJets->Branch("run_value",&run_value,"run_value/I");
  matchJets->Branch("evt_value",&evt_value,"evt_value/I");
  matchJets->Branch("lumi_value",&lumi_value,"lumi_value/I");
  matchJets->Branch("caloeta", &caloeta, "caloeta/F");
  matchJets->Branch("calophi", &calophi, "calophi/F");
  matchJets->Branch("pfeta", &pfeta, "pfeta/F");
  matchJets->Branch("pfphi", &pfphi, "pfphi/F");
  if(dataset=="MC") matchJets->Branch("subid",&subid,"subid/I"); matchJets->Branch("pfrawpt",&pfrawpt,"pfrawpt/F");
  if(dataset=="MC") matchJets->Branch("pfrefpt",&pfrefpt,"pfrefpt/F"); matchJets->Branch("pfjtpu",&pfjtpu,"pfjtpu/F");
  if(dataset=="MC") matchJets->Branch("calorefpt",&calorefpt,"calorefpt/F");
  if(dataset=="MC") matchJets->Branch("pthat",&pthat,"pthat/F"); if(dataset=="MC") matchJets->Branch("vz",&vz,"vz/F");
  if(dataset=="MC") matchJets->Branch("weight",&weight,"weight/F");
  matchJets->Branch("calorawpt",&calorawpt,"calorawpt/F");
  matchJets->Branch("calojtpu",&calojtpu,"calojtpu/F");
  
  TTree* unmatchPFJets = new TTree("unmatchedPFJets","Ntuple containing important information about unmatched PF jets");
  unmatchPFJets->Branch("phSum",&phSum,"phSum/F");
  unmatchPFJets->Branch("pfpt",&pfpt,"pfpt/F");         unmatchPFJets->Branch("neSum",&neSum,"neSum/F");
  unmatchPFJets->Branch("deltar",&deltar,"deltar/F");   unmatchPFJets->Branch("muSum",&muSum,"muSum/F");
  unmatchPFJets->Branch("chMax",&chMax,"chMax/F");      unmatchPFJets->Branch("eSum",&eSum,"eSum/F");
  unmatchPFJets->Branch("phMax",&phMax,"phMax/F");
  unmatchPFJets->Branch("neMax",&neMax,"neMax/F");      unmatchPFJets->Branch("jet80",&jet80,"jet80/I");
  unmatchPFJets->Branch("muMax",&muMax,"muMax/F");      unmatchPFJets->Branch("jet80_prescl",&jet80_prescl,"jet80_prescl/I");
  unmatchPFJets->Branch("eMax",&eMax,"eMax/F");         unmatchPFJets->Branch("jet60",&jet60,"jet60/I");
  unmatchPFJets->Branch("chSum",&chSum,"chSum/F");      unmatchPFJets->Branch("jet60_prescl",&jet60_prescl,"jet60_prescl/I");
  unmatchPFJets->Branch("jet40",&jet40,"jet40/I");      unmatchPFJets->Branch("jet40_prescl",&jet40_prescl,"jet40_prescl/I");
  unmatchPFJets->Branch("hcalSum",&hcalSum,"hcalSum/F");unmatchPFJets->Branch("ecalSum",&ecalSum,"ecalSum/F");
  unmatchPFJets->Branch("run_value",&run_value,"run_value/I");
  unmatchPFJets->Branch("evt_value",&evt_value,"evt_value/I");
  unmatchPFJets->Branch("lumi_value",&lumi_value,"lumi_value/I");
  unmatchPFJets->Branch("pfeta", &pfeta, "pfeta/F");
  unmatchPFJets->Branch("pfphi", &pfphi, "pfphi/F");
  if(dataset=="MC") unmatchPFJets->Branch("subid",&subid,"subid/I"); unmatchPFJets->Branch("pfrawpt",&pfrawpt,"pfrawpt/F");
  if(dataset=="MC") unmatchPFJets->Branch("pfrefpt",&pfrefpt,"pfrefpt/F"); unmatchPFJets->Branch("pfjtpu",&pfjtpu,"pfjtpu/F");
  if(dataset=="MC") unmatchPFJets->Branch("weight",&weight,"weight/F");
  if(dataset=="MC") unmatchPFJets->Branch("pthat",&pthat,"pthat/F"); if(dataset=="MC") unmatchPFJets->Branch("vz",&vz,"vz/F");
  
  TTree* unmatchCaloJets = new TTree("unmatchedCaloJets","Ntuple containing important information about unmatched Calo jets");
  unmatchCaloJets->Branch("phSum",&phSum,"phSum/F");
  unmatchCaloJets->Branch("calopt",&calopt,"calopt/F");   unmatchCaloJets->Branch("neSum",&neSum,"neSum/F");
  unmatchCaloJets->Branch("deltar",&deltar,"deltar/F");   unmatchCaloJets->Branch("muSum",&muSum,"muSum/F");
  unmatchCaloJets->Branch("chMax",&chMax,"chMax/F");      unmatchCaloJets->Branch("eSum",&eSum,"eSum/F");
  unmatchCaloJets->Branch("phMax",&phMax,"phMax/F");     
  unmatchCaloJets->Branch("neMax",&neMax,"neMax/F");      unmatchCaloJets->Branch("jet80",&jet80,"jet80/I");
  unmatchCaloJets->Branch("muMax",&muMax,"muMax/F");      unmatchCaloJets->Branch("jet80_prescl",&jet80_prescl,"jet80_prescl/I");
  unmatchCaloJets->Branch("eMax",&eMax,"eMax/F");         unmatchCaloJets->Branch("jet60",&jet60,"jet60/I");
  unmatchCaloJets->Branch("chSum",&chSum,"chSum/F");      unmatchCaloJets->Branch("jet60_prescl",&jet60_prescl,"jet60_prescl/I");
  unmatchCaloJets->Branch("jet40",&jet40,"jet40/I");      unmatchCaloJets->Branch("jet40_prescl",&jet40_prescl,"jet40_prescl/I");
  unmatchCaloJets->Branch("hcalSum",&hcalSum,"hcalSum/F");unmatchCaloJets->Branch("ecalSum",&ecalSum,"ecalSum/F");
  unmatchCaloJets->Branch("run_value",&run_value,"run_value/I");
  unmatchCaloJets->Branch("evt_value",&evt_value,"evt_value/I");
  unmatchCaloJets->Branch("lumi_value",&lumi_value,"lumi_value/I");
  unmatchCaloJets->Branch("caloeta", &caloeta, "caloeta/F");
  unmatchCaloJets->Branch("calophi", &calophi, "calophi/F");
  if(dataset=="MC") unmatchCaloJets->Branch("subid",&subid,"subid/I"); 
  if(dataset=="MC") unmatchCaloJets->Branch("calorefpt",&calorefpt,"calorefpt/F");
  if(dataset=="MC") unmatchCaloJets->Branch("pthat",&pthat,"pthat/F"); if(dataset=="MC") unmatchCaloJets->Branch("vz",&vz,"vz/F");
  if(dataset=="MC") unmatchCaloJets->Branch("weight",&weight,"weight/F");
  unmatchCaloJets->Branch("calorawpt",&calorawpt,"calorawpt/F");
  unmatchCaloJets->Branch("calojtpu",&calojtpu,"calojtpu/F");


  TH1F * hEvents = new TH1F("hEvents","",20,0,10);

  // define the histograms 

  // define the histograms necessary for that MC closure test.
  TH2F *hpp_mcclosure_matrix_HLT;
  TH2F *hpp_mcclosure_matrix;
  //TH2F *hpp_response;
  TH1F *hpp_mcclosure_JetComb_data;
  TH1F *hpp_mcclosure_data;
  TH1F *hpp_mcclosure_Jet80_data;
  TH1F *hpp_mcclosure_Jet60_data;
  TH1F *hpp_mcclosure_Jet40_data;
  TH1F *hpp_mcclosure_gen;
  TH1F *hpp_mcclosure_JetComb_gen;
  TH1F *hpp_mcclosure_Jet80_gen;
  TH1F *hpp_mcclosure_Jet60_gen;
  TH1F *hpp_mcclosure_Jet40_gen;
  
  hpp_mcclosure_matrix_HLT = new TH2F(Form("hpp_mcclosure_matrix_HLT_R%d_%s",radius,etaWidth),Form("Matrix for mcclosure refpt jtpt from Jet triggers R%d %s ",radius,etaWidth),nbins_pt,boundaries_pt,nbins_pt,boundaries_pt);
  hpp_mcclosure_matrix = new TH2F(Form("hpp_mcclosure_matrix_R%d_%s",radius,etaWidth),Form("Matrix for mcclosure refpt jtpt from Jet triggers R%d %s ",radius,etaWidth),nbins_pt,boundaries_pt,nbins_pt,boundaries_pt);
  //cout<<"C"<<endl;
  hpp_mcclosure_data = new TH1F(Form("hpp_mcclosure_data_R%d_%s",radius,etaWidth),Form("data for unfolding mc closure test R%d %s ",radius,etaWidth),nbins_pt,boundaries_pt);
  hpp_mcclosure_JetComb_data = new TH1F(Form("hpp_mcclosure_JetComb_data_R%d_%s",radius,etaWidth),Form("data for unfolding mc closure test trigger combined  R%d %s ",radius,etaWidth),nbins_pt,boundaries_pt);
  hpp_mcclosure_Jet80_data = new TH1F(Form("hpp_mcclosure_Jet80_data_R%d_%s",radius,etaWidth),Form("data for unfolding mc closure test trigger 80  R%d %s ",radius,etaWidth),nbins_pt,boundaries_pt);
  hpp_mcclosure_Jet60_data = new TH1F(Form("hpp_mcclosure_Jet60_data_R%d_%s",radius,etaWidth),Form("data for unfolding mc closure test trigger 60  R%d %s ",radius,etaWidth),nbins_pt,boundaries_pt);
  hpp_mcclosure_Jet40_data = new TH1F(Form("hpp_mcclosure_Jet40_data_R%d_%s",radius,etaWidth),Form("data for unfolding mc closure test trigger 40  R%d %s ",radius,etaWidth),nbins_pt,boundaries_pt);

  hpp_mcclosure_gen = new TH1F(Form("hpp_mcclosure_gen_R%d_%s",radius,etaWidth),Form("gen spectra for unfolding mc closure test R%d %s ",radius,etaWidth),nbins_pt,boundaries_pt);
  hpp_mcclosure_JetComb_gen = new TH1F(Form("hpp_mcclosure_gen_JetComb_R%d_%s",radius,etaWidth),Form("gen spectra for unfolding mc closure test trigger combined R%d %s ",radius,etaWidth),nbins_pt,boundaries_pt);
  hpp_mcclosure_Jet80_gen = new TH1F(Form("hpp_mcclosure_gen_Jet80_R%d_%s",radius,etaWidth),Form("gen spectra for unfolding mc closure test trigger 80 R%d %s ",radius,etaWidth),nbins_pt,boundaries_pt);
  hpp_mcclosure_Jet60_gen = new TH1F(Form("hpp_mcclosure_gen_Jet60_R%d_%s",radius,etaWidth),Form("gen spectra for unfolding mc closure test trigger 60 R%d %s ",radius,etaWidth),nbins_pt,boundaries_pt);
  hpp_mcclosure_Jet40_gen = new TH1F(Form("hpp_mcclosure_gen_Jet40_R%d_%s",radius,etaWidth),Form("gen spectra for unfolding mc closure test trigger 40 R%d %s ",radius,etaWidth),nbins_pt,boundaries_pt);

  
  // declare the 2d calo and pf candidate vectors, deltaR_calovsPF is going to be a 3d vector like so:
  // calo jet on x axis, pf jet on y axis, and delta R, calopT, pfpT on z axis.
  // we also need to add in the trigger information here since we need to know what trigger the matching comes from. maybe i can run that later as an added check. for now just to see if the algorithm is working should try to run things. 
  //vector<vector<double> > caloJet;
  //vector<vector<double> > pfJet;

  // start the loop process

  for(int k = 0;k<no_radius;k++){

    Long64_t nentries = jetpp1[2][k]->GetEntries();
    //Long64_t nentries = 100;

    Long64_t fentries= 1;
    if(dataset=="MC"){
      TEventList *el = new TEventList("el","el");
      double pthat_upper = boundaries_pthat[startfile + 1];
      stringstream selection; selection<<"pthat<"<<pthat_upper;
      
      jetpp1[2][k]->Draw(">>el",selection.str().c_str());
      fentries = el->GetN();
      delete el;
    }
    
    for(Long64_t nentry = 0; nentry<nentries;nentry++){
      if(printDebug)cout<<"event no = "<<nentry<<endl;
      for(int t = 0;t<N;t++)  jetpp1[t][k]->GetEntry(nentry);
      
      hEvents->Fill(0);

      //int centBin = findBin(hiBin_1);
      //if(centBin==-1) continue;
      //if(pHBHENoiseFilter_1==0 || pcollisionEventSelection_1==0) continue; 
      if(pPAcollisionEventSelectionPA_1==0) continue; 
      hEvents->Fill(1);
      if(dataset=="Data") if(pHBHENoiseFilter_1==0 ) continue;
      hEvents->Fill(2);

      if(fabs(vz_1)>15) continue;
      //cout<<"passed the selection"<<endl;

      hEvents->Fill(3);

      weight = 1;

      if(dataset=="MC"){
	
	int pthatBin = hpthatBin->FindBin(pthat_1);
	
	double scale = (double)(xsection[pthatBin-1]-xsection[pthatBin])/fentries;

	Float_t weight_vz = fVzPP->Eval(vz_1);
	weight = scale*weight_vz;

      }

      // start doing the search for the match. - best thing to do would be to create a 2D match delta R matrix with each calo jet and pf jet. Once thats done - find the smallest entry in that matrix. the i,j of that smallest entry are matched. now remove the row i and column j and then we have a new distance matrix. where we need to find the smallest element again. keep doing this till we have either no rows or no columns.  

      // declare the necessary variables:
      Float_t deltaRCaloPF = 0;
      Float_t calojet_eta = 0;
      Float_t calojet_phi = 0;
      Float_t calojet_pt = 0;
      Float_t pfjet_eta = 0;
      Float_t pfjet_phi = 0;
      Float_t pfjet_pt = 0;
      
      vector<vector<double> > matchedCaloPFJet;
      vector<vector<vector<double> > > deltaR_calovsPF;
      int calosize = 0;
      Float_t deltapT = 0;
      int calomatchcounter = 0;
      
      for(int g = 0;g<nrefe_1;g++){
	
	calojet_eta = eta_1[g];
	calojet_phi = phi_1[g];
	calojet_pt = pt_1[g];
	
	if(calojet_pt < CALOPTCUT) continue;
	if(TMath::Abs(calojet_eta) > 2.0) continue;
	
	int pfmatchcounter = 0;
	deltaR_calovsPF.push_back(vector<vector<double> > ());
	
	calosize++;
	
	for(int j = 0;j<nrefe_2;j++){

	  pfjet_eta = eta_2[j];
	  pfjet_phi = phi_2[j];
	  pfjet_pt = pt_2[j];

	  if(pfjet_pt < PFPTCUT) continue;
	  if(TMath::Abs(pfjet_eta) > 2.0) continue;

	  deltaRCaloPF = Calc_deltaR(calojet_eta, calojet_phi, pfjet_eta, pfjet_phi);
	  
	  // if(deltaRCaloPF > (Float_t)deltaR/10) continue;
	  deltapT = TMath::Abs(calojet_pt - pfjet_pt);

	  deltaR_calovsPF[calomatchcounter].push_back(vector<double> ());
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(deltaRCaloPF); // 0 - delta R
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(deltapT); // 1 - delta pT	  
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(g); // 2 - calo counter 
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(calojet_pt); // 3 - calo jet pT 
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(j); // 4 - pf counter 
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(pfjet_pt); // 5 - pf jet pT
	  // this will have the candidate variables for the matched jets. 
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(chMax_2[j]); // 6 - chMax 
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(phMax_2[j]); // 7 - phMax
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(neMax_2[j]); // 8 - neMax
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(muMax_2[j]); // 9 - muMax
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(eMax_2[j]); // 10 - eMax
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(chSum_2[j]); // 11 - chSum
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(phSum_2[j]); // 12 - phSum
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(neSum_2[j]); // 13 - neSum
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(muSum_2[j]); // 14 - muSum
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(eSum_2[j]); // 15 - eSum
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(0.0); // 16 - this is the variable which will tell me if a jet is matched.
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(hcalSum_2[j]); // 17 - hcalSum 
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(ecalSum_2[j]); // 18 - hcalSum
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(raw_2[j]); // 19 - raw pt
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(jtpu_2[j]); // 20 - jtpu
	  //all the following candidate information is for the calo jets 
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(chMax_1[g]); // 21 - chMax 
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(phMax_1[g]); // 22 - phMax
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(neMax_1[g]); // 23 - neMax
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(muMax_1[g]); // 24 - muMax
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(eMax_1[g]); // 25 - eMax
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(chSum_1[g]); // 26 - chSum
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(phSum_1[g]); // 27 - phSum
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(neSum_1[g]); // 28 - neSum
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(muSum_1[g]); // 29 - muSum
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(eSum_1[g]); // 30 - eSum
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(hcalSum_1[g]); // 31 - hcalSum 
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(ecalSum_1[g]); // 32 - hcalSum
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(raw_1[g]); // 33 - raw pt
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(jtpu_1[g]); // 34 - jtpu

	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(pfjet_eta); // 35 - pf eta
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(pfjet_phi); // 36 - pf phi
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(calojet_eta); // 37 - calo eta
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(calojet_phi); // 38 - calo phi
	  
	  if(dataset=="MC") {
	    deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(refpt_1[g]); // 39 calo ref pt 
	    deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(refpt_2[j]); // 40 pf ref pt 
	    deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(subid_2[j]); // 41 - subid only for MC
	    
	  }
	  
	  
	  ++pfmatchcounter;

	}// pf jet loop
	++calomatchcounter;
	
      }// calo jet loop

      // set the event variables before proceeding to the matching. 
      jet80 = jet80_1;
      jet80_prescl = jet80_p_1;
      jet60 = jet60_1;
      jet60_prescl = jet60_p_1;
      jet40 = jet40_1;
      jet40_prescl = jet40_p_1;
      run_value = run_1;
      evt_value = evt_1;
      lumi_value = lumi_1;
      vz = vz_1;
      if(dataset=="MC")pthat = pthat_1;

      if(printDebug)cout<<deltaR_calovsPF.size()<<endl;
      if(printDebug)for(int a = 0;a<deltaR_calovsPF.size();++a) cout<<deltaR_calovsPF[a].size()<<" ";
      if(printDebug)cout<<endl<<"going to small matching"<<endl;
      
      // now that we have the 2D matrix, lets find the smallest delta R element from that and fill in the value of the 

      Float_t smallDeltaR = 10;
      Int_t small_calo = 0;
      Int_t small_pf = 0;

      for(int c = 0;c<deltaR_calovsPF.size();++c){
	// if(printDebug)cout<<"going through all rows in the  matrix "<<c<<endl;
	for(int a = 0;a<deltaR_calovsPF.size();++a){
	  // if(printDebug)cout<<"calo jet iteration "<<a<<endl;
	  for(int b = 0;b<deltaR_calovsPF[a].size();++b){
	    // if(printDebug)cout<<"pf jet iteration "<<b<<endl;
	    
	    if(deltaR_calovsPF[a][b][16]==1){ 
	      break;
	    }
	    if(smallDeltaR > deltaR_calovsPF[a][b][0]){
	      
	      smallDeltaR = deltaR_calovsPF[a][b][0];
	      small_calo = a;
	      small_pf = b;
	      
	    }
	  }
	}
	
	if(smallDeltaR > (Float_t)deltaR/10 || deltaR_calovsPF[small_calo][small_pf][16] == 1) continue;
	
	calopt = deltaR_calovsPF[small_calo][small_pf][3];
	pfpt = deltaR_calovsPF[small_calo][small_pf][5];
	if(dataset=="MC"){
	  pfrefpt = deltaR_calovsPF[small_calo][small_pf][40];
	  calorefpt = deltaR_calovsPF[small_calo][small_pf][39];
	  subid = deltaR_calovsPF[small_calo][small_pf][41]; 
	}
	pfrawpt = deltaR_calovsPF[small_calo][small_pf][19]; 
	calorawpt = deltaR_calovsPF[small_calo][small_pf][33]; 
	pfjtpu = deltaR_calovsPF[small_calo][small_pf][20]; 
	calojtpu = deltaR_calovsPF[small_calo][small_pf][34];
	deltar = deltaR_calovsPF[small_calo][small_pf][0];
	chMax = deltaR_calovsPF[small_calo][small_pf][6];
	phMax = deltaR_calovsPF[small_calo][small_pf][7];
	neMax = deltaR_calovsPF[small_calo][small_pf][8];
	muMax = deltaR_calovsPF[small_calo][small_pf][9];
	eMax = deltaR_calovsPF[small_calo][small_pf][10];
	chSum = deltaR_calovsPF[small_calo][small_pf][11];
	phSum = deltaR_calovsPF[small_calo][small_pf][12];
	neSum = deltaR_calovsPF[small_calo][small_pf][13];
	muSum = deltaR_calovsPF[small_calo][small_pf][14];
	eSum = deltaR_calovsPF[small_calo][small_pf][15];
	pfeta = deltaR_calovsPF[small_calo][small_pf][35];
	pfphi = deltaR_calovsPF[small_calo][small_pf][36];
	caloeta = deltaR_calovsPF[small_calo][small_pf][37];
	calophi = deltaR_calovsPF[small_calo][small_pf][38];
	hcalSum = deltaR_calovsPF[small_calo][small_pf][17];
	ecalSum = deltaR_calovsPF[small_calo][small_pf][18];
	
	//matchJets->Fill();
	
	if(c==0) hEvents->Fill(4);
	  
	if(dataset=="MC"){
	  // fill in the matched histograms with the Jet ID cuts:
	  if(subid!=0) continue;
	
	  Float_t Sumcand = chSum + phSum + neSum + muSum;

	  //if(calopt/pfpt > 0.5 && calopt/pfpt <= 0.85 && eMax/Sumcand < ((Float_t)18/7 *(Float_t)calopt/pfpt - (Float_t)9/7)){
	    if(nentry%2==1) {
	      hpp_mcclosure_matrix->Fill(pfrefpt, pfpt, weight);
	      hpp_mcclosure_gen->Fill(pfrefpt, weight);
	    }
	    if(nentry%2==1) {
	      hpp_mcclosure_data->Fill(pfpt, weight);
	    }
	    //}
	  
	  if(jet40 == 1 && jet60==0 && jet80 == 0){

	    //if(calopt/pfpt > 0.5 && calopt/pfpt <= 0.85 && eMax/Sumcand < ((Float_t)18/7 *(Float_t)calopt/pfpt - (Float_t)9/7)){
	      if(nentry%2==1) {
		hpp_mcclosure_matrix_HLT->Fill(pfrefpt, pfpt, weight);
		hpp_mcclosure_Jet40_gen->Fill(pfrefpt, weight);
	      }
	      if(nentry%2==1) {
		hpp_mcclosure_Jet40_data->Fill(pfpt, weight);
	      }
	      //}

	    // if(calopt/pfpt > 0.85) {
	    //   if(nentry%2==1) {
	    // 	hpp_mcclosure_matrix_HLT->Fill(pfrefpt, pfpt, weight);
	    // 	hpp_mcclosure_Jet40_gen->Fill(pfrefpt, weight);
	    //   }
	    //   if(nentry%2==1) {
	    // 	hpp_mcclosure_Jet40_data->Fill(pfpt, weight);
	    //   }
	    // }

	    // if(calopt/pfpt <= 0.5 && eMax/Sumcand < 0.05) {
	    //   if(nentry%2==1) {
	    // 	hpp_mcclosure_matrix_HLT->Fill(pfrefpt, pfpt, weight);
	    // 	hpp_mcclosure_Jet40_gen->Fill(pfrefpt, weight);
	    //   }
	    //   if(nentry%2==1) {
	    // 	hpp_mcclosure_Jet40_data->Fill(pfpt, weight);
	    //   }
	    // }
	  
	  }

	  if(jet60 == 1 && jet80 == 0){

	    //if(calopt/pfpt > 0.5 && calopt/pfpt <= 0.85 && eMax/Sumcand < ((Float_t)18/7 *(Float_t)calopt/pfpt - (Float_t)9/7)){
	      if(nentry%2==1) {
		hpp_mcclosure_matrix_HLT->Fill(pfrefpt, pfpt, weight);
		hpp_mcclosure_Jet60_gen->Fill(pfrefpt, weight);
	      }
	      if(nentry%2==1) {
		hpp_mcclosure_Jet60_data->Fill(pfpt, weight);
	      }
	      //}

	    // if(calopt/pfpt > 0.85) {
	    //   if(nentry%2==1) {
	    // 	hpp_mcclosure_matrix_HLT->Fill(pfrefpt, pfpt, weight);
	    // 	hpp_mcclosure_Jet60_gen->Fill(pfrefpt, weight);
	    //   }
	    //   if(nentry%2==1) {
	    // 	hpp_mcclosure_Jet60_data->Fill(pfpt, weight);
	    //   }
	    // }

	    // if(calopt/pfpt <= 0.5 && eMax/Sumcand < 0.05) {
	    //   if(nentry%2==1) {
	    // 	hpp_mcclosure_matrix_HLT->Fill(pfrefpt, pfpt, weight);
	    // 	hpp_mcclosure_Jet60_gen->Fill(pfrefpt, weight);
	    //   }
	    //   if(nentry%2==1) {
	    // 	hpp_mcclosure_Jet60_data->Fill(pfpt, weight);
	    //   }
	    // }
	  
	  
	  }

	  if(jet80==1){

	    //if(calopt/pfpt > 0.5 && calopt/pfpt <= 0.85 && eMax/Sumcand < ((Float_t)18/7 *(Float_t)calopt/pfpt - (Float_t)9/7)){
	      if(nentry%2==1) {
		hpp_mcclosure_matrix_HLT->Fill(pfrefpt, pfpt, weight);
		hpp_mcclosure_Jet80_gen->Fill(pfrefpt, weight);
	      }
	      if(nentry%2==1) {
		hpp_mcclosure_Jet80_data->Fill(pfpt, weight);
	      }
	      //}

	    // if(calopt/pfpt > 0.85) {
	    //   if(nentry%2==1) {
	    // 	hpp_mcclosure_matrix_HLT->Fill(pfrefpt, pfpt, weight);
	    // 	hpp_mcclosure_Jet80_gen->Fill(pfrefpt, weight);
	    //   }
	    //   if(nentry%2==1) {
	    // 	hpp_mcclosure_Jet80_data->Fill(pfpt, weight);
	    //   }
	    // }

	    // if(calopt/pfpt <= 0.5 && eMax/Sumcand < 0.05) {
	    //   if(nentry%2==1) {
	    // 	hpp_mcclosure_matrix_HLT->Fill(pfrefpt, pfpt, weight);
	    // 	hpp_mcclosure_Jet80_gen->Fill(pfrefpt, weight);
	    //   }
	    //   if(nentry%2==1) {
	    // 	hpp_mcclosure_Jet80_data->Fill(pfpt, weight);
	    //   }
	    // }
	  
	  
	  }

	}


	smallDeltaR = 10;
	for(int b = 0;b<deltaR_calovsPF[small_calo].size();++b){
	  deltaR_calovsPF[small_calo][b][16] = 1; // by setting this value you effectively remove that calo and pf jet for further matching // removes the column for getting matched. 
	}
	for(int a = 0;a<deltaR_calovsPF.size();++a){
	  deltaR_calovsPF[a][small_pf][16] = 1; // this removes the whole row from getting matched later. 
	}

      }// running it for the number of calo jets: 

      if(printDebug)cout<<"now going to find unmatched pf jets"<<endl;
      // ok Now lets find the un-matched jets and fill the necessary unmatched ntuple:

      if(deltaR_calovsPF.size() == 0) continue;
      for(int b = 0;b<deltaR_calovsPF[0].size();++b){
	if(printDebug)cout<<"pf jet iteration "<<b<<endl;

	if(deltaR_calovsPF[0][b][16] == 1) continue;

	pfpt = deltaR_calovsPF[0][b][5];
	deltar = deltaR_calovsPF[0][b][0];
	if(dataset=="MC"){
	  pfrefpt = deltaR_calovsPF[0][b][40];
	  subid = deltaR_calovsPF[0][b][41]; 
	}
	pfrawpt = deltaR_calovsPF[0][b][19]; 
	pfjtpu = deltaR_calovsPF[0][b][20]; 
	chMax = deltaR_calovsPF[0][b][6];
	phMax = deltaR_calovsPF[0][b][7];
	neMax = deltaR_calovsPF[0][b][8];
	muMax = deltaR_calovsPF[0][b][9];
	eMax = deltaR_calovsPF[0][b][10];
	chSum = deltaR_calovsPF[0][b][11];
	phSum = deltaR_calovsPF[0][b][12];
	neSum = deltaR_calovsPF[0][b][13];
	muSum = deltaR_calovsPF[0][b][14];
	eSum = deltaR_calovsPF[0][b][15];
	pfeta = deltaR_calovsPF[0][b][35];
	pfphi = deltaR_calovsPF[0][b][36];
	hcalSum = deltaR_calovsPF[0][b][17];
	ecalSum = deltaR_calovsPF[0][b][18];
	
	//unmatchPFJets->Fill();

	if(b==0) hEvents->Fill(5);

	if(dataset=="MC"){
	  // fill in the matched histograms with the Jet ID cuts:
	  if(subid!=0) continue;
	
	  Float_t Sumcand = chSum + phSum + neSum + muSum;

	  //if(eMax/Sumcand < 0.05) {
	    if(nentry%2==1) {
	      hpp_mcclosure_matrix->Fill(pfrefpt, pfpt, weight);
	      hpp_mcclosure_gen->Fill(pfrefpt, weight);
	    }
	    if(nentry%2==1) {
	      hpp_mcclosure_data->Fill(pfpt, weight);
	    }
	    //}
	  
	  
	  if(jet40 == 1 && jet60 == 0 && jet80 == 0){

	    //if(eMax/Sumcand < 0.05) {
	      if(nentry%2==1) {
		hpp_mcclosure_matrix_HLT->Fill(pfrefpt, pfpt, weight);
		hpp_mcclosure_Jet40_gen->Fill(pfrefpt, weight);
	      }
	      if(nentry%2==1) {
		hpp_mcclosure_Jet40_data->Fill(pfpt, weight);
	      }
	      //}
	  
	  }

	  if(jet60 == 1 && jet80 == 0){

	    //if(eMax/Sumcand < 0.05) {
	      if(nentry%2==1) {
		hpp_mcclosure_matrix_HLT->Fill(pfrefpt, pfpt, weight);
		hpp_mcclosure_Jet60_gen->Fill(pfrefpt, weight);
	      }
	      if(nentry%2==1) {
		hpp_mcclosure_Jet60_data->Fill(pfpt, weight);
	      }
	      //}
	  
	  
	  }

	  if(jet80==1){

	    //if(eMax/Sumcand < 0.05) {
	      if(nentry%2==1) {
		hpp_mcclosure_matrix_HLT->Fill(pfrefpt, pfpt, weight);
		hpp_mcclosure_Jet80_gen->Fill(pfrefpt, weight);
	      }
	      if(nentry%2==1) {
		hpp_mcclosure_Jet80_data->Fill(pfpt, weight);
	      }
	      //}
	  
	  
	  }
	}

	
      }// unmatched PF jets
      
      if(printDebug)cout<<"now going to find unmatched calo jets"<<endl;

      if(deltaR_calovsPF[0].size() == 0) continue;
      
      for(int a = 0;a<deltaR_calovsPF.size();++a){
	if(printDebug)cout<<"calo jet iteration "<<a<<endl;

	if(deltaR_calovsPF[a][0][16] == 1) continue;

	calopt = deltaR_calovsPF[a][0][3];
	deltar = deltaR_calovsPF[a][0][0];
	if(dataset=="MC"){
	  calorefpt = deltaR_calovsPF[a][0][39];
	  subid = deltaR_calovsPF[a][0][41]; 
	}
	calorawpt = deltaR_calovsPF[a][0][33]; 
	calojtpu = deltaR_calovsPF[a][0][34]; 
	chMax = deltaR_calovsPF[a][0][21];
	phMax = deltaR_calovsPF[a][0][22];
	neMax = deltaR_calovsPF[a][0][23];
	muMax = deltaR_calovsPF[a][0][24];
	eMax = deltaR_calovsPF[a][0][25];
	chSum = deltaR_calovsPF[a][0][26];
	phSum = deltaR_calovsPF[a][0][27];
	neSum = deltaR_calovsPF[a][0][28];
	muSum = deltaR_calovsPF[a][0][29];
	eSum = deltaR_calovsPF[a][0][30];
	caloeta = deltaR_calovsPF[a][0][37];
	calophi = deltaR_calovsPF[a][0][38];
	hcalSum = deltaR_calovsPF[a][0][31];
	ecalSum = deltaR_calovsPF[a][0][32];
	
	//unmatchCaloJets->Fill();

      }

    }// event loop 

  }// radius loop


  // matchJets->Write();
  // matchJets->Print();
  // unmatchPFJets->Write();
  // unmatchPFJets->Print();
  // unmatchCaloJets->Write();
  // unmatchCaloJets->Print();


  hpp_mcclosure_JetComb_data->Add(hpp_mcclosure_Jet80_data);
  hpp_mcclosure_JetComb_data->Add(hpp_mcclosure_Jet60_data);
  hpp_mcclosure_JetComb_data->Add(hpp_mcclosure_Jet40_data);

  hpp_mcclosure_JetComb_gen->Add(hpp_mcclosure_Jet80_gen);
  hpp_mcclosure_JetComb_gen->Add(hpp_mcclosure_Jet60_gen);
  hpp_mcclosure_JetComb_gen->Add(hpp_mcclosure_Jet40_gen);

  hpp_mcclosure_matrix_HLT->Write();
  hpp_mcclosure_matrix->Write();
  hpp_mcclosure_JetComb_data->Write();
  hpp_mcclosure_data->Write();
  hpp_mcclosure_Jet80_data->Write();
  hpp_mcclosure_Jet60_data->Write();
  hpp_mcclosure_Jet40_data->Write();
  hpp_mcclosure_JetComb_gen->Write();    
  hpp_mcclosure_gen->Write();    
  hpp_mcclosure_Jet80_gen->Write();
  hpp_mcclosure_Jet60_gen->Write();
  hpp_mcclosure_Jet40_gen->Write();
    

  hEvents->Write();

  timer.Stop();
  cout<<"Macro finished: "<<endl;
  cout<<"CPU time (min)  = "<<(Float_t)timer.CpuTime()/60<<endl;
  cout<<"Real time (min) = "<<(Float_t)timer.RealTime()/60<<endl;
  
}
コード例 #29
0
ファイル: scan2.C プロジェクト: hkaushalya/CDFPhoJets
void scan2() {

    /*  TFile f1("hist.root");
      TFile f2("SysTot.root");

      TH1D *datahist = (TH1D*)f1.Get("datahist");
      TH1D *fithist = (TH1D*)f1.Get("fithist");

      TH1D *totlow = (TH1D*)f2.Get("totlow");
      TH1D *tothigh = (TH1D*)f2.Get("tothigh");
    */

    TF1 *fun1 = new TF1("fun",fun,0,1000,3);

    TFile f("Output.root");
    TH1F *datahist = dynamic_cast<TH1F*> (f.Get("InvMass"));
    TH1F *fithist = dynamic_cast<TH1F*> (f.Get("hist_err"));
    TH1F *tothigh = dynamic_cast<TH1F*> (f.Get("SystPlus"));
    TH1F *totlow = dynamic_cast<TH1F*> (f.Get("SystMinus"));
    new TCanvas();
    datahist->DrawCopy();
    fithist->DrawCopy("same");
    gPad->SetEditable(0);

    /*	if (datahist->IsZombie()) { std::cout << "Err! datahist not found " << std::endl; return; }
    	if (fithist->IsZombie()) { std::cout << "Err! err_hist not found " << std::endl; return; }
    	if (tothigh->IsZombie()) { std::cout << "Err! syst_plus hist not found " << std::endl; return; }
    	if (totlow->IsZombie()) { std::cout << "Err! syst_minus hist not found " << std::endl; return; }
    */

    TH1D *p = new TH1D("p","Probability",100,150,900);

    for (int i = 1; i<=fithist->GetNbinsX(); i++)
    {
        double mass = fithist->GetBinCenter(i);

        if (mass>440 && mass<450)
        {
            double sigma = sqrt(2.0)*sqrt(pow(0.135*sqrt(mass/2.0),2)+
                                          pow(0.02*(mass/2.0),2));
            cout<< " ===================== mass +/- sigma = " << mass<<"+/-"<<sigma<<endl;
            int bin1 = fithist->FindBin(mass-sigma/2);
            int bin2 = fithist->FindBin(mass+sigma/2);
            cout<<mass<<" "<<bin1<<" "<<bin2<<endl;
            double data = 0;
            double bg = 0;
            double err = 0;

            for (int j = bin1; j<=bin2; j++)
            {
                data+=datahist->GetBinContent(j);
                bg+=fithist->GetBinContent(j);
                double err1 = -totlow->GetBinContent(j);
                double err2 = tothigh->GetBinContent(j);
                err+=TMath::Max(err1,err2)*bg; //why multiply by bg???
            }
            cout << "Total Data/Bg+/-err in mass window[" << mass << "] = "<< data <<"/ "<< bg << "+/-" << err <<endl;
            double prob = 0;
            fun1->SetParameter(0,bg);
            fun1->SetParameter(1,err);

            for (int j = int(data+0.001); j<100; j++) {
                fun1->SetParameter(2,j);
                //fun1->Print();
                //cout << "Evaluating Intrgral for j = " << j << " from x0= " << TMath::Max(0.0,bg-10*err) << " to x1 = " << bg+10*err << endl;
                double val = fun1->Integral(TMath::Max(0.0,bg-10*err),bg+10*err);
                //double val = fun1->Integral(TMath::Max(0.0,bg-2*err),bg+2*err);
                /*for (int z=TMath::Max(0.0,bg-2*err); z < bg+2*err; ++z)
                {
                	if (c<4)
                	{
                	std::cout << "func at [" << z << "]=" << 	fun1->Eval(z) << std::endl;
                	}
                }
                */
                prob += val;
            }
            cout<< "Prob for mass[" << mass<<"]="<< prob <<endl;
            p->SetBinContent(p->FindBin(mass),prob);
        }
    }
    /*
    delete gRandom;
    gRandom = (TRandom*) new TRandom3;
    gRandom->SetSeed(3);

    TH1D *minp = new TH1D("minp","Minimum Probability of Each PseudoExpt",100,0,0.2);

    //int nexp = 50000;
    int nexp = 10;

    TH1D *htemp = (TH1D*)datahist->Clone("htemp");

    for (int iexp = 0; iexp<nexp; iexp++){
      //if (iexp%10==0) cout<<iexp<<endl;
      //generate pseudo-experiments
      htemp->Reset();
      for (int i = 1; i<=htemp->GetNbinsX(); i++){
        double mass = htemp->GetBinCenter(i);
        if (mass>150&&mass<650){
    double bg = fithist->GetBinContent(i);
    double err1 = -totlow->GetBinContent(i);
    double err2 = tothigh->GetBinContent(i);
    double err = TMath::Max(err1,err2)*bg;
    double mean = gRandom->Gaus(bg,err);
    if (mean<0) mean = 0;
    htemp->SetBinContent(i,gRandom->Poisson(mean));
        }
      }
      double minprob = 2.;
      for (int i = 1; i<=fithist->GetNbinsX(); i++){
        double mass = fithist->GetBinCenter(i);
        if (mass>150&&mass<650){
    double sigma = sqrt(2.0)*sqrt(pow(0.135*sqrt(mass/2.0),2)+
    			      pow(0.02*(mass/2.0),2));
    //cout<<mass<<" "<<sigma<<endl;
    int bin1 = fithist->FindBin(mass-sigma/2);
    int bin2 = fithist->FindBin(mass+sigma/2);
    //cout<<mass<<" "<<bin1<<" "<<bin2<<endl;
    double data = 0;
    double bg = 0;
    double err = 0;
    for (int j = bin1; j<=bin2; j++){
      data+=htemp->GetBinContent(j);
      bg+=fithist->GetBinContent(j);
      double err1 = -totlow->GetBinContent(j);
      double err2 = tothigh->GetBinContent(j);
      err+=TMath::Max(err1,err2)*bg;
    }
    //cout<<mass<<" "<<data<<" "<<bg<<" "<<err<<endl;
    double prob = 0;
    fun1->SetParameter(0,bg);
    fun1->SetParameter(1,err);
    for (int j = int(data+0.001); j<100; j++){
      fun1->SetParameter(2,j);
      prob += fun1->Integral(TMath::Max(0.0,bg-10*err),bg+10*err);
    }
    if (prob<minprob) minprob=prob;
        }
      }
      minp->Fill(minprob);
    }
    */
    TCanvas *c1 = new TCanvas("c1","c1");
    TH2D *fr = new TH2D("fr","",100,150,900,100,1e-5,2);
    fr->SetStats(0);
    fr->SetXTitle("M(#gamma,lead jet)(GeV)");
    fr->SetYTitle("Prob of fluctuation #geq N_{obs}");
    fr->GetXaxis()->CenterTitle();
    fr->GetYaxis()->CenterTitle();
    fr->DrawCopy();
    p->SetLineWidth(2);
    p->DrawCopy("same");
    double minp=0;
    double mgg=0;
    double minc = 10;
    for (int i = 1; i<=p->GetNbinsX(); i++) {
        double bin = p->GetBinCenter(i);
        double binc = p->GetBinContent(i);
        if (binc<minc) {
            minp = binc;
            mgg = bin;
            minc = binc;
        }
    }
    cout<<mgg<<" "<<minp<<endl;
    gPad->SetLogy();
    double p1s = 0.00458319;
    double m1s = 0.0435982;
    double s3s = 0.000100319;
    TLine *l1 = new TLine(150,p1s,900,p1s);
    TLine *l2 = new TLine(150,m1s,900,m1s);
    TLine *l3 = new TLine(150,s3s,900,s3s);
    l1->SetLineColor(4);
    l2->SetLineColor(4);
    l3->SetLineColor(2);
    l1->SetLineWidth(2);
    l2->SetLineWidth(2);
    l3->SetLineWidth(2);
    l1->Draw();
    l2->Draw();
    l3->Draw();
    TLatex *t1 = new TLatex(250,m1s/4,"Expected Range for Min. Obs. Prob.");
    t1->SetTextColor(4);
    t1->SetTextSize(0.05);
    t1->Draw();
    TLatex *t2 = new TLatex(350,s3s*1.5,"3 #sigma evidence level");
    t2->SetTextColor(2);
    t2->SetTextSize(0.05);
    t2->Draw();

    TLatex *t3 = new TLatex(0.3,0.93,"CDF Run II Preliminary, 2.0 fb^{-1}");
    t3->SetNDC(true);
    t3->SetTextSize(0.06);
    t3->Draw();

//
//  TCanvas *c2 = new TCanvas("c2","c2");
//  minp->DrawCopy();
    //cout<<minp->GetMean()<<endl;
}
コード例 #30
0
void 
HTT_EM_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., TString datacard="htt_em_0_7TeV", string inputfile="root/$HISTFILE", const char* directory="emu_$CATEGORY")
{
  // define common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  // determine category tag
  const char* category = ""; const char* category_extra = ""; const char* category_extra2 = "";
  if(std::string(directory) == std::string("emu_0jet_low"             )){ category = "e#mu, 0 jet";          }    
  if(std::string(directory) == std::string("emu_0jet_low"             )){ category_extra = "p_{T}(lep1) low";          }    
  if(std::string(directory) == std::string("emu_0jet_high"            )){ category = "e#mu, 0 jet";          }    
  if(std::string(directory) == std::string("emu_0jet_high"            )){ category_extra = "p_{T}(lep1) high";         }    
  if(std::string(directory) == std::string("emu_1jet_low"          )){ category = "e#mu, 1 jet";          }    
  if(std::string(directory) == std::string("emu_1jet_low"          )){ category_extra = "p_{T}(lep1) low";       }    
  if(std::string(directory) == std::string("emu_1jet_high"          )){ category = "e#mu, 1 jet";          }    
  if(std::string(directory) == std::string("emu_1jet_high"          )){ category_extra = "p_{T}(lep1) high";       }    
  if(std::string(directory) == std::string("emu_vbf_loose"            )){ category = "e#mu, 2 jet";          }    
  if(std::string(directory) == std::string("emu_vbf_loose"            )){ category_extra = "VBF, loose";              }    
  if(std::string(directory) == std::string("emu_vbf_tight"            )){ category = "e#mu, 2 jet";          }    
  if(std::string(directory) == std::string("emu_vbf_tight"            )){ category_extra = "VBF, tight";              }    
  if(std::string(directory) == std::string("emu_nobtag"               )){ category = "e#mu";          }    
  if(std::string(directory) == std::string("emu_nobtag"               )){ category_extra = "No B-Tag";                        }    
  if(std::string(directory) == std::string("emu_btag"                 )){ category = "e#mu";          }    
  if(std::string(directory) == std::string("emu_btag"                 )){ category_extra = "B-Tag";                           }

  const char* dataset;
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 4.9 fb^{-1} at 7 TeV";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 19.7 fb^{-1} at 8 TeV";}
  
  TFile* input = new TFile(inputfile.c_str());
#ifdef MSSM
  TFile* input2 = new TFile((inputfile+"_$MA_$TANB").c_str());
#endif
  TH1F* Fakes  = refill((TH1F*)input->Get(TString::Format("%s/Fakes"     , directory)), "Fakes"  ); InitHist(Fakes, "", "", kMagenta-10, 1001);
  TH1F* EWK    = refill((TH1F*)input->Get(TString::Format("%s/EWK"       , directory)), "EWK"    ); InitHist(EWK  , "", "", kRed    + 2, 1001);
  TH1F* ttbar  = refill((TH1F*)input->Get(TString::Format("%s/ttbar"     , directory)), "ttbar"  ); InitHist(ttbar, "", "", kBlue   - 8, 1001);
  TH1F* Ztt    = refill((TH1F*)input->Get(TString::Format("%s/Ztt"       , directory)), "Ztt"    ); InitHist(Ztt  , "", "", kOrange - 4, 1001);
#ifdef MSSM
  TH1F* ggH  = refill((TH1F*)input2->Get(TString::Format("%s/ggH$MA"     , directory)), "ggH"    ); InitSignal(ggH    ); ggH    ->Scale($TANB);
  TH1F* bbH  = refill((TH1F*)input2->Get(TString::Format("%s/bbH$MA"     , directory)), "bbH"    ); InitSignal(bbH    ); bbH    ->Scale($TANB);
#else
#ifdef HWW_BG
  TH1F* ggH_hww= refill((TH1F*)input->Get(TString::Format("%s/ggH_hww125", directory)), "ggH_hww"); InitHist(ggH_hww  , "", "", kGreen + 2, 1001); ggH_hww->Scale(SIGNAL_SCALE);
  TH1F* qqH_hww= refill((TH1F*)input->Get(TString::Format("%s/qqH_hww125", directory)), "qqH_hww"); InitHist(qqH_hww  , "", "", kGreen + 2, 1001); qqH_hww->Scale(SIGNAL_SCALE);
#else
 TH1F* ggH_hww= refill((TH1F*)input->Get(TString::Format("%s/ggH_hww125", directory)), "ggH_hww"); InitSignal(ggH_hww); ggH_hww->Scale(SIGNAL_SCALE);
  TH1F* qqH_hww= refill((TH1F*)input->Get(TString::Format("%s/qqH_hww125", directory)), "qqH_hww"); InitSignal(qqH_hww); qqH_hww->Scale(SIGNAL_SCALE);
#endif
#ifndef DROP_SIGNAL
  TH1F* ggH    = refill((TH1F*)input->Get(TString::Format("%s/ggH125"    , directory)), "ggH"    ); InitSignal(ggH    ); ggH    ->Scale(SIGNAL_SCALE);
  TH1F* qqH    = refill((TH1F*)input->Get(TString::Format("%s/qqH125"    , directory)), "qqH"    ); InitSignal(qqH    ); qqH    ->Scale(SIGNAL_SCALE);
  TH1F* VH     = refill((TH1F*)input->Get(TString::Format("%s/VH125"     , directory)), "VH"     ); InitSignal(VH     ); VH     ->Scale(SIGNAL_SCALE);
#ifndef HWW_BG
  ggH->Add(ggH_hww);
  qqH->Add(qqH_hww);
#endif
#endif
#endif
#ifdef ASIMOV
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs_asimov", directory)), "data", true);
#else
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
#endif
  InitHist(data, "#bf{m_{#tau#tau} [GeV]}", "#bf{dN/dm_{#tau#tau} [1/GeV]}"); InitData(data);

  TH1F* ref=(TH1F*)Fakes->Clone("ref");
  ref->Add(EWK  );
  ref->Add(ttbar);
  ref->Add(Ztt  );
#ifdef HWW_BG
  ref->Add(qqH_hww);
  ref->Add(ggH_hww);
#endif

#ifdef HWW_BG
  const int numhistos = 9;
  const int offset = 2;
#else
  const int numhistos = 7;
  const int offset = 0;
#endif
  double unscaled[numhistos];
  unscaled[0] = Fakes->Integral();
  unscaled[1] = EWK  ->Integral();
  unscaled[2] = ttbar->Integral();
  unscaled[3] = Ztt  ->Integral();
#ifdef MSSM
  unscaled[4] = ggH  ->Integral();
  unscaled[5] = bbH  ->Integral();
  unscaled[6] = 0;
#else
#ifdef HWW_BG
  unscaled[4] = ggH_hww  ->Integral();
  unscaled[5] = qqH_hww  ->Integral();
#endif
#ifndef DROP_SIGNAL
  unscaled[4+offset] = ggH  ->Integral();
  unscaled[5+offset] = qqH  ->Integral();
  unscaled[6+offset] = VH   ->Integral();
#endif
#endif

  if(scaled){
    Fakes = refill(shape_histos(Fakes, datacard, "Fakes"), "Fakes"); 
    EWK = refill(shape_histos(EWK, datacard, "EWK"), "EWK"); 
    ttbar = refill(shape_histos(ttbar, datacard, "ttbar"), "ttbar"); 
    Ztt = refill(shape_histos(Ztt, datacard, "Ztt"), "Ztt"); 
#ifdef MSSM
    ggH = refill(shape_histos(ggH, datacard, "ggH$MA"), "ggH$MA"); 
    bbH = refill(shape_histos(bbH, datacard, "bbH$MA"), "bbH$MA"); 
#else
#ifndef DROP_SIGNAL
    ggH = refill(shape_histos(ggH, datacard, "ggH"), "ggH"); 
    qqH = refill(shape_histos(qqH, datacard, "qqH"), "qqH"); 
    VH = refill(shape_histos(VH, datacard, "VH"), "VH"); 
#endif  
#endif
#ifdef HWW_BG
    ggH_hww = refill(shape_histos(ggH_hww, datacard, "ggH_hww125"), "ggH_hww125");
    qqH_hww = refill(shape_histos(qqH_hww, datacard, "qqH_hww125"), "qqH_hww125");
#endif
    
    rescale(Fakes, 4); 
    rescale(EWK,   3); 
    rescale(ttbar, 2); 
    rescale(Ztt,   1);
#ifdef MSSM 
    rescale(ggH,   5);
    rescale(bbH,   6);
#else
#ifdef HWW_BG
    rescale(qqH_hww, 8);
    rescale(qqH_hww, 9);
#endif
#ifndef DROP_SIGNAL
    rescale(ggH,   5);
    rescale(qqH,   6);
    rescale(VH,    7);
#endif
#endif
  }

  TH1F* scales[numhistos];
  scales[0] = new TH1F("scales-Fakes", "", numhistos, 0, numhistos);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (Fakes->Integral()/unscaled[0]-1.) : 0.);
  scales[1] = new TH1F("scales-EWK"  , "", numhistos, 0, numhistos);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? (EWK  ->Integral()/unscaled[1]-1.) : 0.);
  scales[2] = new TH1F("scales-ttbar", "", numhistos, 0, numhistos);
  scales[2]->SetBinContent(3, unscaled[2]>0 ? (ttbar->Integral()/unscaled[2]-1.) : 0.);
  scales[3] = new TH1F("scales-Ztt"  , "", numhistos, 0, numhistos);
  scales[3]->SetBinContent(4, unscaled[3]>0 ? (Ztt  ->Integral()/unscaled[3]-1.) : 0.);
#ifdef MSSM
  scales[4] = new TH1F("scales-ggH"  , "", numhistos, 0, numhistos);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggH  ->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-qqH"  , "", numhistos, 0, numhistos);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (bbH  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-NONE" , "", numhistos, 0, numhistos);
  scales[6]->SetBinContent(numhistos, 0.);
#else
#ifdef HWW_BG
  scales[4] = new TH1F("scales-ggH_hww"  , "", numhistos, 0, numhistos);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggH_hww  ->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-qqH_hww"  , "", numhistos, 0, numhistos);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (qqH_hww  ->Integral()/unscaled[5]-1.) : 0.);
#endif  
#ifndef DROP_SIGNAL
  scales[4+offset] = new TH1F("scales-ggH"  , "", numhistos, 0, numhistos);
  scales[4+offset]->SetBinContent(5+offset, unscaled[4+offset]>0 ? (ggH  ->Integral()/unscaled[4+offset]-1.) : 0.);
  scales[5+offset] = new TH1F("scales-qqH"  , "", numhistos, 0, numhistos);
  scales[5+offset]->SetBinContent(6+offset, unscaled[5+offset]>0 ? (qqH  ->Integral()/unscaled[5+offset]-1.) : 0.);
  scales[6+offset] = new TH1F("scales-VH"   , "", numhistos, 0, numhistos);
  scales[6+offset]->SetBinContent(7+offset, unscaled[6+offset]>0 ? (VH   ->Integral()/unscaled[6+offset]-1.) : 0.);
#endif
#endif

  EWK  ->Add(Fakes);
  ttbar->Add(EWK  );
  Ztt  ->Add(ttbar);
#ifdef HWW_BG
  qqH_hww->Add(Ztt);
  ggH_hww->Add(qqH_hww);
#endif
  if(log){
#ifdef MSSM
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }
  else{
#ifdef MSSM
    bbH  ->Add(Ztt);
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
#ifdef HWW_BG
    VH   ->Add(qqH_hww);
#else
    VH   ->Add(Ztt);
#endif
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }

  /*
    mass plot before and after fit
  */
  TCanvas* canv = MakeCanvas("canv", "histograms", 600, 600);
  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(0, data->FindBin(345)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(UPPER_EDGE)); };
#else
  data->GetXaxis()->SetRange(0, data->FindBin(345));
#endif
  data->SetNdivisions(505);
  data->SetMinimum(min);
#ifndef DROP_SIGNAL
  data->SetMaximum(max>0 ? max : std::max(std::max(maximum(data, log), maximum(Ztt, log)), maximum(ggH, log)));
#else
  data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Ztt, log)));
#endif
  data->Draw("e");

#ifdef HWW_BG
  TH1F* errorBand = (TH1F*)ggH_hww ->Clone("errorBand");
#else
  TH1F* errorBand = (TH1F*)Ztt ->Clone("errorBand");
#endif
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(1);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
    if(errorBand->GetBinContent(idx)>0){
      std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
      break;
    }
  }
  if(log){
#ifdef HWW_BG
    ggH_hww->Draw("histsame");
#endif
    Ztt  ->Draw("histsame");
    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    Fakes->Draw("histsame");
    $DRAW_ERROR
#ifndef DROP_SIGNAL
    ggH  ->Draw("histsame");
#endif
  }
  else{
#ifndef DROP_SIGNAL
    ggH  ->Draw("histsame");
#endif
#ifdef HWW_BG
    ggH_hww->Draw("histsame");
#endif
    Ztt  ->Draw("histsame");
    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    Fakes->Draw("histsame");
    $DRAW_ERROR
  }
  data->Draw("esame");
  canv->RedrawAxis();

  //CMSPrelim(dataset, "#tau_{e}#tau_{#mu}", 0.17, 0.835);
  CMSPrelim(dataset, "", 0.16, 0.835);
  TPaveText* chan     = new TPaveText(0.20, (category_extra2 && category_extra2[0]=='\0') ? 0.65+0.061 : 0.65+0.061, 0.32, 0.75+0.161, "tlbrNDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText(category);
  chan->AddText(category_extra);
  chan->AddText(category_extra2);
  chan->Draw();

/*  TPaveText* cat      = new TPaveText(0.20, 0.71+0.061, 0.32, 0.71+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();

#ifdef MSSM
  TPaveText* massA      = new TPaveText(0.53, 0.50+0.061, 0.95, 0.50+0.161, "NDC");
  massA->SetBorderSize(   0 );
  massA->SetFillStyle(    0 );
  massA->SetTextAlign(   12 );
  massA->SetTextSize ( 0.03 );
  massA->SetTextColor(    1 );
  massA->SetTextFont (   62 );
  massA->AddText("m^{h}_{max} (m_{A}=$MA GeV, tan#beta=$TANB)");
  massA->Draw();
#endif
*/
#ifdef MSSM  
  TLegend* leg = new TLegend(0.53, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(ggH  , "#phi#rightarrow#tau#tau" , "L" );
#else
  TLegend* leg = new TLegend(0.50, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
#ifndef DROP_SIGNAL
  if(SIGNAL_SCALE!=1){
    leg->AddEntry(ggH  , TString::Format("%.0f#timesH(125 GeV)#rightarrow#tau#tau", SIGNAL_SCALE) , "L" );
  }
  else{
#ifdef HWW_BG
    leg->AddEntry(ggH  , "H(125 GeV)#rightarrow#tau#tau" , "L" );
#else
    leg->AddEntry(ggH  , "#splitline{H(125 GeV)#rightarrow#tau#tau}{H(125 GeV)#rightarrowWW}" , "L" );
    leg->AddEntry((TObject*)0, "", "");
#endif
  }
#endif
#endif
#ifdef ASIMOV
  leg->AddEntry(data , "sum(bkg) + H(125)"              , "LP");
#else
  leg->AddEntry(data , "observed"                       , "LP");
#endif
#ifdef HWW_BG
  leg->AddEntry(ggH_hww  , "H(125 GeV)#rightarrowWW" , "F" );
#endif
  leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
  leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
  leg->AddEntry(EWK  , "electroweak"                    , "F" );
  leg->AddEntry(Fakes, "Fakes"                          , "F" );
  $ERROR_LEGEND
  leg->Draw();

  /*
    Ratio Data over MC
  */
  TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
  canv0->SetGridx();
  canv0->SetGridy();
  canv0->cd();
#ifdef HWW_BG
  TH1F* model = (TH1F*)ggH_hww ->Clone("model");
#else
  TH1F* model = (TH1F*)Ztt ->Clone("model");
#endif
  TH1F* test1 = (TH1F*)data->Clone("test1"); 
  for(int ibin=0; ibin<test1->GetNbinsX(); ++ibin){
    //the small value in case of 0 entries in the model is added to prevent the chis2 test from failing
    model->SetBinContent(ibin+1, model->GetBinContent(ibin+1)>0 ? model->GetBinContent(ibin+1)*model->GetBinWidth(ibin+1) : 0.01);
    model->SetBinError  (ibin+1, CONVERVATIVE_CHI2 ? 0. : model->GetBinError  (ibin+1)*model->GetBinWidth(ibin+1));
    test1->SetBinContent(ibin+1, test1->GetBinContent(ibin+1)*test1->GetBinWidth(ibin+1));
    test1->SetBinError  (ibin+1, test1->GetBinError  (ibin+1)*test1->GetBinWidth(ibin+1));
  }
  double chi2prob = test1->Chi2Test      (model,"PUW");        std::cout << "chi2prob:" << chi2prob << std::endl;
  double chi2ndof = test1->Chi2Test      (model,"CHI2/NDFUW"); std::cout << "chi2ndf :" << chi2ndof << std::endl;
  double ksprob   = test1->KolmogorovTest(model);              std::cout << "ksprob  :" << ksprob   << std::endl;
  double ksprobpe = test1->KolmogorovTest(model,"DX");         std::cout << "ksprobpe:" << ksprobpe << std::endl;  

  std::vector<double> edges;
  TH1F* zero = (TH1F*)ref ->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)data->Clone("rat1"); 
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    rat1->SetBinContent(ibin+1, Ztt->GetBinContent(ibin+1)>0 ? data->GetBinContent(ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
    rat1->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? data->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
    zero->SetBinContent(ibin+1, 0.);
    zero->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? Ztt ->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat1->GetBinContent(ibin+1)-1.)+TMath::Abs(rat1->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
  }
  float range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+range);
  rat1->SetMinimum(-range);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
  rat1->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  rat1->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->SetMarkerSize(0.1);
  zero->Draw("e2histsame");
  canv0->RedrawAxis();

  TPaveText* stat1 = new TPaveText(0.20, 0.76+0.061, 0.32, 0.76+0.161, "NDC");
  stat1->SetBorderSize(   0 );
  stat1->SetFillStyle(    0 );
  stat1->SetTextAlign(   12 );
  stat1->SetTextSize ( 0.05 );
  stat1->SetTextColor(    1 );
  stat1->SetTextFont (   62 );
  stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f", chi2ndof, chi2prob));
  //stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f, P(KS)=%.3f", chi2ndof, chi2prob, ksprob));
  stat1->Draw();

  /*
    Ratio After fit over Prefit
  */
  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  edges.clear();
#ifdef HWW_BG
  TH1F* rat2 = (TH1F*) ggH_hww->Clone("rat2");
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    rat2->SetBinContent(ibin+1, ref->GetBinContent(ibin+1)>0 ? ggH_hww->GetBinContent(ibin+1)/ref->GetBinContent(ibin+1) : 0);
    rat2->SetBinError  (ibin+1, ref->GetBinContent(ibin+1)>0 ? ggH_hww->GetBinError  (ibin+1)/ref->GetBinContent(ibin+1) : 0);
  }
#else
  TH1F* rat2 = (TH1F*) Ztt->Clone("rat2");
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    rat2->SetBinContent(ibin+1, ref->GetBinContent(ibin+1)>0 ? Ztt->GetBinContent(ibin+1)/ref->GetBinContent(ibin+1) : 0);
    rat2->SetBinError  (ibin+1, ref->GetBinContent(ibin+1)>0 ? Ztt->GetBinError  (ibin+1)/ref->GetBinContent(ibin+1) : 0);
  }
#endif
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    if(rat2->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat2->GetBinContent(ibin+1)-1.)+TMath::Abs(rat2->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
    }
  }
  range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
#if defined MSSM
  if(!log){ rat2->GetXaxis()->SetRange(0, rat2->FindBin(345)); } else{ rat2->GetXaxis()->SetRange(0, rat2->FindBin(UPPER_EDGE)); };
#else
  rat2->GetXaxis()->SetRange(0, rat2->FindBin(345));
#endif
  rat2->SetNdivisions(505);
  rat2->SetLineColor(kRed+ 3);
  rat2->SetMarkerColor(kRed+3);
  rat2->SetMarkerSize(1.1);
  rat2->SetMaximum(+range);
  rat2->SetMinimum(-range);
  rat2->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  rat2->GetYaxis()->CenterTitle();
  rat2->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  rat2->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->Draw("e2histsame");
  canv1->RedrawAxis();

  /*
    Relative shift per sample
  */
  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
  canv2->SetGridx();
  canv2->SetGridy();
  canv2->cd();

  InitHist  (scales[0], "", "", kMagenta-10, 1001);
  InitHist  (scales[1], "", "", kRed    + 2, 1001);
  InitHist  (scales[2], "", "", kBlue   - 8, 1001);
  InitHist  (scales[3], "", "", kOrange - 4, 1001);
#ifdef HWW_BG
  InitHist(scales[4], "", "", kGreen + 2, 1001);
  InitHist(scales[5], "", "", kGreen + 2, 1001);
#endif
#ifndef DROP_SIGNAL
  InitSignal(scales[4+offset]);
  InitSignal(scales[5+offset]);
  InitSignal(scales[6+offset]);
#endif
  scales[0]->Draw();
  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{Fakes}");
  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{EWK}"  );
  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{ttbar}");
  scales[0]->GetXaxis()->SetBinLabel(4, "#bf{Ztt}"  );
#ifdef MSSM
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{bbH}"  );
  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{NONE}" );
#else
#ifdef HWW_BG
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH_hww}");
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{qqH_hww}");
#endif
  scales[0]->GetXaxis()->SetBinLabel(5+offset, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(6+offset, "#bf{qqH}"  );
  scales[0]->GetXaxis()->SetBinLabel(7+offset, "#bf{VH}"   );
#endif
  scales[0]->SetMaximum(+0.5);
  scales[0]->SetMinimum(-0.5);
  scales[0]->GetYaxis()->CenterTitle();
  scales[0]->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  scales[1]->Draw("same");
  scales[2]->Draw("same");
  scales[3]->Draw("same");
#ifdef HWW_BG
  scales[4]->Draw("same");
  scales[5]->Draw("same");
#endif
#ifndef DROP_SIGNAL
  scales[4+offset]->Draw("same");
  scales[5+offset]->Draw("same");
  scales[6+offset]->Draw("same");
#endif
  TH1F* zero_samples = (TH1F*)scales[0]->Clone("zero_samples"); zero_samples->Clear();
  zero_samples->SetBinContent(1,0.);
  zero_samples->Draw("same");
  canv2->RedrawAxis();

  /*
    prepare output
  */
  bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.png"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.pdf"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.eps"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  if(!log || FULLPLOTS)
  {
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }
  if((!log && scaled) || FULLPLOTS)
  {
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }

  TFile* output = new TFile(TString::Format("%s_%sfit_%s_%s.root", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"), "update");
  output->cd(); 
  data ->Write("data_obs");
  Fakes->Write("Fakes"   );
  EWK  ->Write("EWK"     );
  ttbar->Write("ttbar"   );
  Ztt  ->Write("Ztt"     );
#ifdef MSSM
  ggH  ->Write("ggH"     );
  bbH  ->Write("bbH"     );
#else
#ifdef HWW_BG
  ggH_hww  ->Write("ggH_hww"     );
#endif
#ifndef DROP_SIGNAL
  ggH  ->Write("ggH"     );
  qqH  ->Write("qqH"     );
  VH   ->Write("VH"      );
#endif
#endif
  if(errorBand){
    errorBand->Write("errorBand");
  }
  output->Close();
 
  delete errorBand;
  delete model;
  delete test1;
  delete zero;
  delete rat1;
  delete rat2;
  delete zero_samples;
  delete ref;
}