void Boost_To_Stop_Rest_Frame(TLorentzVector& stop4, TLorentzVector& chargino4, TLorentzVector& b4, TLorentzVector& neutralino4, TLorentzVector& W4, TLorentzVector& up4, TLorentzVector& down4, TLorentzVector& s4)
{
    TVector3 betaV(-stop4.Px()/stop4.Energy(),-stop4.Py()/stop4.Energy(),-stop4.Pz()/stop4.Energy());
    stop4.Boost(betaV);
    chargino4.Boost(betaV);
    b4.Boost(betaV);
    neutralino4.Boost(betaV);
    W4.Boost(betaV);
    up4.Boost(betaV);
    down4.Boost(betaV);
    s4.SetE(chargino4.P()/chargino4.M());
    s4.SetVect(chargino4.Vect().Unit()*chargino4.Gamma());
}
示例#2
0
Bool_t monojet::Process(Long64_t entry)
{
    GetEntry(entry);

    if( entry % 100000 == 0 ) cout << "Processing event number: " << entry << endl;
    //cout << "Processing event number: " << entry << endl;

    // To make the processing fast, apply a very looose selection
    if (((TLorentzVector*)((*metP4)[0]))->Pt() < 40. or jetP4->GetEntries() < 1) return kTRUE;

    //this is the type tree
    tm->SetValue("run",runNum);
    tm->SetValue("event",eventNum);
    tm->SetValue("lumi",lumiNum);

    float dR = 0.;
    TClonesArray *tightLep;
    TClonesArray *cleanJet;
    TClonesArray *cleanTau;

    tightLep = new TClonesArray("TLorentzVector",20);
    cleanJet = new TClonesArray("TLorentzVector",20);
    cleanTau = new TClonesArray("TLorentzVector",20);

    std::vector<bool>  jetMonojetId_clean;
    jetMonojetId_clean.clear();
    std::vector<bool>  jetMonojetIdLoose_clean;
    jetMonojetIdLoose_clean.clear();
    //std::vector<float> jetPuId_clean;
    //jetPuId_clean.clear();

    std::vector<float>  tauId_clean;
    tauId_clean.clear();
    std::vector<float>  tauIso_clean;
    tauIso_clean.clear();

    int n_tightlep = 0;

    // ********* Leptons ********** //
    for(int lepton = 0; lepton < lepP4->GetEntries(); lepton++) {
        TLorentzVector* Lepton = (TLorentzVector*) lepP4->At(lepton);
        // check if this is a tight lep, and check the overlap

        //iso_1 = divide(input_tree.lepIso[0],input_tree.lepP4[0].Pt())
        //if (input_tree.lepTightId[0]==0 or iso_1 > 0.12): continue

        if (Lepton->Pt() > 20. && (*lepTightId)[lepton] > 1) {
            n_tightlep +=1;
            new ( (*tightLep)[tightLep->GetEntriesFast()]) TLorentzVector(Lepton->Px(), Lepton->Py(), Lepton->Pz(), Lepton->Energy());

            //check overlap with jets
            for(int j = 0; j < jetP4->GetEntries(); j++) {
                TLorentzVector* Jet = (TLorentzVector*) jetP4->At(j);
                dR = deltaR(Lepton,Jet);
                if (dR > dR_cut) {
                    new ( (*cleanJet)[cleanJet->GetEntriesFast()]) TLorentzVector(Jet->Px(), Jet->Py(), Jet->Pz(), Jet->Energy());
                    jetMonojetId_clean.push_back((*jetMonojetId)[j]);
                    jetMonojetIdLoose_clean.push_back((*jetMonojetIdLoose)[j]);
                    //jetPuId_clean.push_back((*jetPuId)[j]);
                }
            }
            //check overlap with taus
            for(int tau = 0; tau < tauP4->GetEntries(); tau++) {
                TLorentzVector* Tau = (TLorentzVector*) tauP4->At(tau);
                dR = deltaR(Lepton,Tau);
                if (dR > dR_cut) new ( (*cleanTau)[cleanTau->GetEntriesFast()]) TLorentzVector(Tau->Px(), Tau->Py(), Tau->Pz(), Tau->Energy());
                tauId_clean.push_back((*tauId)[tau]);
                tauIso_clean.push_back((*tauIso)[tau]);
            } // tau overlap
        } // tight lepton selection
    }//lepton loop

    tm->SetValue("n_tightlep",n_tightlep);

    TLorentzVector fakeMET;

    // Z Selection
    TLorentzVector Z;
    if(lepP4->GetEntries() == 2 && n_tightlep > 0) {
        if (((*lepPdgId)[0]+(*lepPdgId)[1])==0 ) {
            Z = *((TLorentzVector*)((*lepP4)[0])) + *((TLorentzVector*)((*lepP4)[1]));
            fakeMET = *((TLorentzVector*)((*metP4)[0])) + Z;
        }
    }

    float MT = 0.0;
    //// W Selection
    if(lepP4->GetEntries() == 1 && n_tightlep == 1) {
        fakeMET = *((TLorentzVector*)((*metP4)[0])) + *((TLorentzVector*)((*lepP4)[0])) ;
        MT = transverseMass( ((TLorentzVector*)((*lepP4)[0]))->Pt(), ((TLorentzVector*)((*lepP4)[0]))->Phi(), ((TLorentzVector*)((*metP4)[0]))->Pt(), ((TLorentzVector*)((*metP4)[0]))->Phi());
    }

    tm->SetValue("mt",MT);

    // ********* Jets ********** //
    for(int jet = 0; jet < jetP4->GetEntries(); jet++) {
        TLorentzVector* Jet = (TLorentzVector*) jetP4->At(jet);
        //cout << (*jetMonojetId)[0] <<endl;
        //cout << Jet->Pt()<<endl;
    }

    // ********* Met ********** //
    // Here try to save all possible met variables
    // and the recoil vectors (for Z and Photon)

    TLorentzVector Recoil(-9999.,-9999.,-9999.,-9999);
    float uPar = -9999. ;
    float uPerp = -9999.;

    if(Z.Pt() > 0) {
        Recoil = *((TLorentzVector*)((*metP4)[0])) + Z;
        Recoil.RotateZ(TMath::Pi());
        Recoil.RotateZ(-Z.Phi());
        if (Z.Phi() > TMath::Pi())  uPar = Recoil.Px() - Z.Pt() ;
        else uPar = Recoil.Px() + Z.Pt();
        uPerp = Recoil.Py();
    }

    tm->SetValue("uperp",uPerp);
    tm->SetValue("upar",uPar);

    // Decide on the type of the event and fill the
    // type tree

    int type_event = -1;


    // forcing all regions to be orthogonal wrt to each other
    if (((TLorentzVector*)((*metP4)[0]))->Pt() > 100. &&
            jetP4->GetEntries() > 0 && lepP4->GetEntries() == 0) type_event=0;
    if (lepP4->GetEntriesFast() == 1) type_event=1; //&& (*lepTightId)[0] == 1) type_event=1;
    if (lepP4->GetEntriesFast() == 2) type_event=2; //&& ((*lepTightId)[0] == 1 || (*lepTightId)[1] == 1 )) type_event=2;

    if (  lepP4->GetEntriesFast() == 2 && type_event!=2 ) std::cout << "WTF??" << std::endl;
    tm->SetValue("event_type",type_event);

    // Now replace all the needed collections based
    // on the type

    if (type_event ==1 || type_event==2)
    {
        jetP4 = cleanJet;
        tauP4 = cleanTau;
        *jetMonojetId = jetMonojetId_clean;
        *jetMonojetIdLoose = jetMonojetIdLoose_clean;
        //*jetPuId = jetPuId_clean;
        *tauId = tauId_clean;
        *tauIso = tauIso_clean;
        *(TLorentzVector*)((*metP4)[0]) = fakeMET;
    }

    // final skim
    if(((TLorentzVector*)((*metP4)[0]))->Pt() < 100.) return kTRUE;

    //re-write the mc weight content to be +1 or -1
    if(mcWeight < 0) mcWeight = -1.0;
    if(mcWeight > 0) mcWeight =  1.0;


    // and fill both trees;
    tm ->TreeFill();
    eventstree->Fill();

    return kTRUE;
}
示例#3
0
void Ntp1Analyzer_QG::Loop()
{


   DEBUG_VERBOSE_ = false;

   if (fChain == 0) return;


   Long64_t nentries;

   if( DEBUG_ ) nentries = 100000;
   else nentries = fChain->GetEntries();


   Long64_t nbytes = 0, nb = 0;

   TRandom3 rand;

   for (Long64_t jentry=0; jentry<nentries;jentry++) {
     Long64_t ientry = LoadTree(jentry);
     if (ientry < 0) break;
     nb = fChain->GetEntry(jentry);   nbytes += nb;
     // if (Cut(ientry) < 0) continue;

if( DEBUG_VERBOSE_ ) std::cout << "entry n." << jentry << std::endl;

     if( (jentry%100000) == 0 ) std::cout << "Event #" << jentry  << " of " << nentries << std::endl;


   //HLT_Mu11_ = this->PassedHLT("HLT_Mu11");
   //HLT_Ele17_SW_EleId_L1R_ = this->PassedHLT("HLT_Ele17_SW_EleId_L1R");
   //HLT_DoubleMu3_ = this->PassedHLT("HLT_DoubleMu3");

     run_ = runNumber;
     LS_ = lumiBlock;
     event_ = eventNumber;
     eventWeight_ = -1.; //default
     nvertex_ = nPV;
     rhoPF_ = rhoFastjet;

     if( !isGoodEvent(jentry) ) continue; //this takes care also of integrated luminosity and trigger

     if( nPV==0 ) continue;
     bool goodVertex = (ndofPV[0] >= 4.0 && sqrt(PVxPV[0]*PVxPV[0]+PVyPV[0]*PVyPV[0]) < 2. && fabs(PVzPV[0]) < 24. );
     if( !goodVertex ) continue;
  
     for( unsigned iBX=0; iBX<nBX; ++iBX ) {
       if( bxPU[iBX]==0 ) nPU_ = nPU[iBX]; 
     }


     ptHat_ = (isMC_) ? genPtHat : ptHat_;

     if( isMC_ ) 
       if( (ptHat_ > ptHatMax_) || (ptHat_ < ptHatMin_) ) continue;


     bool noLeptons = false;
     TLorentzVector lept1MC, lept2MC;
     int zIndexqq=-1;
     int zIndexll=-1;



     // -----------------------------
     //      FROM NOW ON RECO
     // -----------------------------




     // ------------------
     // MUONS
     // ------------------

     std::vector<TLorentzVector> muons;
     int chargeFirstMuon;

     for( unsigned int iMuon=0; iMuon<nMuon && (muons.size()<2); ++iMuon ) {

       TLorentzVector thisMuon( pxMuon[iMuon], pyMuon[iMuon], pzMuon[iMuon], energyMuon[iMuon] );

       // --------------
       // kinematics:
       // --------------
       if( thisMuon.Pt() < 20. ) continue;


       // --------------
       // ID:
       // --------------
       if( !( (muonIdMuon[iMuon]>>8)&1 ) ) continue; //GlobalMuonPromptTight
       if( !( (muonIdMuon[iMuon]>>11)&1 ) ) continue; //AllTrackerMuons
       if( pixelHitsTrack[trackIndexMuon[iMuon]]==0 ) continue;


       // to compute dxy, look for primary vertex:
       int hardestPV = -1;
       float sumPtMax = 0.0;
       for(int v=0; v<nPV; v++) {
         if(SumPtPV[v] > sumPtMax) {
           sumPtMax = SumPtPV[v];
           hardestPV = v;
         }
       }  
   
       float dxy;
       if( hardestPV==-1 ) {
         dxy = 0.;
       } else {
         dxy = fabs(trackDxyPV(PVxPV[hardestPV], PVyPV[hardestPV], PVzPV[hardestPV],
                              trackVxTrack[trackIndexMuon[iMuon]], trackVyTrack[trackIndexMuon[iMuon]], trackVzTrack[trackIndexMuon[iMuon]],
                              pxTrack[trackIndexMuon[iMuon]], pyTrack[trackIndexMuon[iMuon]], pzTrack[trackIndexMuon[iMuon]]));
       }

       if( dxy > 0.02 ) continue;


       float dz = fabs(trackVzTrack[trackIndexMuon[iMuon]]-PVzPV[hardestPV]);
       if(dz > 1.0) continue;



       // --------------
       // isolation:
       // --------------
       // (this is sum pt tracks)
       //if( sumPt03Muon[iMuon] >= 3. ) continue;
       // combined isolation < 15%:
       if( (sumPt03Muon[iMuon] + emEt03Muon[iMuon] + hadEt03Muon[iMuon]) >= 0.15*thisMuon.Pt() ) continue;



       // for now simple selection, will have to optimize this (T&P?)
       if( muons.size()==0 ) {
         muons.push_back( thisMuon );
         chargeFirstMuon = chargeMuon[iMuon];
       } else {
         if( chargeMuon[iMuon]==chargeFirstMuon ) continue;
         if( fabs(muons[0].Eta())>2.1 && fabs(thisMuon.Eta())>2.1 ) continue;
         muons.push_back(thisMuon);
       }

     } //for muons



     // ------------------
     // ELECTRONS
     // ------------------

     std::vector<TLorentzVector> electrons;
     int chargeFirstEle = 0;
     bool firstPassedVBTF80 = false;

     for( unsigned int iEle=0; (iEle<nEle) && (electrons.size()<2); ++iEle ) {

       TLorentzVector thisEle( pxEle[iEle], pyEle[iEle], pzEle[iEle], energyEle[iEle] );

       // --------------
       // kinematics:
       // --------------
       if( thisEle.Pt() < 20. ) continue;
       if( (fabs(thisEle.Eta()) > 2.5) || ( fabs(thisEle.Eta())>1.4442 && fabs(thisEle.Eta())<1.566) ) continue;


       Float_t dr03TkSumPt_thresh95;
       Float_t dr03EcalRecHitSumEt_thresh95;
       Float_t dr03HcalTowerSumEt_thresh95;
       Float_t combinedIsoRel_thresh95;
       Float_t sigmaIetaIeta_thresh95;
       Float_t deltaPhiAtVtx_thresh95;
       Float_t deltaEtaAtVtx_thresh95;
       Float_t hOverE_thresh95;

       Float_t dr03TkSumPt_thresh80;
       Float_t dr03EcalRecHitSumEt_thresh80;
       Float_t dr03HcalTowerSumEt_thresh80;
       Float_t combinedIsoRel_thresh80;
       Float_t sigmaIetaIeta_thresh80;
       Float_t deltaPhiAtVtx_thresh80;
       Float_t deltaEtaAtVtx_thresh80;
       Float_t hOverE_thresh80;

       if( fabs(thisEle.Eta())<1.4442 ) {
         dr03TkSumPt_thresh95 = 0.15;
         dr03EcalRecHitSumEt_thresh95 = 2.;
         dr03HcalTowerSumEt_thresh95 = 0.12;
         combinedIsoRel_thresh95 = 0.15;

         dr03TkSumPt_thresh80 = 0.09;
         dr03EcalRecHitSumEt_thresh80 = 0.07;
         dr03HcalTowerSumEt_thresh80 = 0.10;
         combinedIsoRel_thresh80 = 0.07;

         sigmaIetaIeta_thresh95 = 0.01;
         deltaPhiAtVtx_thresh95 = 0.8;
         deltaEtaAtVtx_thresh95 = 0.007;
         hOverE_thresh95 = 0.15;

         sigmaIetaIeta_thresh80 = 0.01;
         deltaPhiAtVtx_thresh80 = 0.06;
         deltaEtaAtVtx_thresh80 = 0.004;
         hOverE_thresh80 = 0.04;
       } else {
         dr03TkSumPt_thresh95 = 0.08;
         dr03EcalRecHitSumEt_thresh95 = 0.06;
         dr03HcalTowerSumEt_thresh95 = 0.05;
         combinedIsoRel_thresh95 = 0.1;

         dr03TkSumPt_thresh80 = 0.04;
         dr03EcalRecHitSumEt_thresh80 = 0.05;
         dr03HcalTowerSumEt_thresh80 = 0.025;
         combinedIsoRel_thresh80 = 0.06;

         sigmaIetaIeta_thresh80 = 0.03;
         deltaPhiAtVtx_thresh80 = 0.7;
         deltaEtaAtVtx_thresh80 = 0.007;
         hOverE_thresh80 = 0.025;

         sigmaIetaIeta_thresh95 = 0.03;
         deltaPhiAtVtx_thresh95 = 0.7;
         deltaEtaAtVtx_thresh95 = 0.01; 
         hOverE_thresh95 = 0.07;
       }


       // --------------
       // isolation:
       // --------------
     //// no relative iso, using combined
     //if( dr03TkSumPtEle[iEle]/thisEle.Pt() > dr03TkSumPt_thresh ) continue;
     //if( dr03EcalRecHitSumEtEle[iEle]/thisEle.Pt() > dr03EcalRecHitSumEt_thresh ) continue;
     //if( dr03HcalTowerSumEtEle[iEle]/thisEle.Pt() > dr03HcalTowerSumEt_thresh ) continue;

       Float_t combinedIsoRel;
       if( fabs(thisEle.Eta())<1.4442 )
         combinedIsoRel = ( dr03TkSumPtEle[iEle] + TMath::Max(0., dr03EcalRecHitSumEtEle[iEle] - 1.) + dr03HcalTowerSumEtEle[iEle] ) / thisEle.Pt();
       else
         combinedIsoRel = ( dr03TkSumPtEle[iEle] + dr03EcalRecHitSumEtEle[iEle] + dr03HcalTowerSumEtEle[iEle] ) / thisEle.Pt();

       bool iso_VBTF95 = (combinedIsoRel < combinedIsoRel_thresh95);
       bool iso_VBTF80 = (combinedIsoRel < combinedIsoRel_thresh80);

       
       // --------------
       // electron ID:
       // --------------
       bool eleID_VBTF95 = (covIEtaIEtaSC[iEle] < sigmaIetaIeta_thresh95) &&
                           (fabs(deltaPhiAtVtxEle[iEle]) < deltaPhiAtVtx_thresh95) &&
                           (fabs(deltaEtaAtVtxEle[iEle]) < deltaEtaAtVtx_thresh95) &&
                           (hOverEEle[iEle] < hOverE_thresh95);

       bool eleID_VBTF80 = (covIEtaIEtaSC[iEle] < sigmaIetaIeta_thresh80) &&
                           (fabs(deltaPhiAtVtxEle[iEle]) < deltaPhiAtVtx_thresh80) &&
                           (fabs(deltaEtaAtVtxEle[iEle]) < deltaEtaAtVtx_thresh80) &&
                           (hOverEEle[iEle] < hOverE_thresh80);

       bool passed_VBTF95 = (iso_VBTF95 && eleID_VBTF95);
       bool passed_VBTF80 = (iso_VBTF80 && eleID_VBTF80);


       if( !passed_VBTF95 ) continue;

       // check that not matched to muon (clean electrons faked by muon MIP):
       bool matchedtomuon=false;
       for( std::vector<TLorentzVector>::iterator iMu=muons.begin(); iMu!=muons.end(); ++iMu )
         if( iMu->DeltaR(thisEle)<0.1 ) matchedtomuon=true;

       if( matchedtomuon ) continue;


       // for now simple selection, will have to optimize this (T&P?)
       // one electron required to pass VBTF80, the other VBTF95
       if( electrons.size()==0 ) {
         electrons.push_back( thisEle );
         chargeFirstEle = chargeEle[iEle];
         if( passed_VBTF80 ) firstPassedVBTF80 = true;
       } else if( chargeEle[iEle] != chargeFirstEle && ( firstPassedVBTF80||passed_VBTF80 ) ) {
         electrons.push_back( thisEle );
       }


     } //for electrons


     if( requireLeptons_ )
       if( electrons.size() < 2 && muons.size() < 2 ) continue;


     std::vector< TLorentzVector > leptons;

     if( electrons.size() == 2 && muons.size() == 2 ) { //veto H->ZZ->4l

       continue;

     } else if( electrons.size() == 2 ) {

       leptType_ = 1;

       if( electrons[0].Pt() > electrons[1].Pt() ) {

         leptons.push_back( electrons[0] );
         leptons.push_back( electrons[1] );

       } else {

         leptons.push_back( electrons[1] );
         leptons.push_back( electrons[0] );

       }

     } else if( muons.size() == 2 ) {

       leptType_ = 0;

       if( muons[0].Pt() > muons[1].Pt() ) {

         leptons.push_back( muons[0] );
         leptons.push_back( muons[1] );

       } else {

         leptons.push_back( muons[1] );
         leptons.push_back( muons[0] );

       }

     } else {

     //std::cout << "There must be an error this is not possible." << std::endl;
     //exit(9101);

     }

     
     eLept1_ = (leptons.size()>0) ? leptons[0].Energy() : 0.;
     ptLept1_ = (leptons.size()>0) ? leptons[0].Pt() : 0.;
     etaLept1_ = (leptons.size()>0) ? leptons[0].Eta() : 0.;
     phiLept1_ = (leptons.size()>0) ? leptons[0].Phi() : 0.;
     
     eLept2_ = (leptons.size()>1) ? leptons[1].Energy() : 0.;
     ptLept2_ = (leptons.size()>1) ? leptons[1].Pt() : 0.;
     etaLept2_ = (leptons.size()>1) ? leptons[1].Eta() : 0.;
     phiLept2_ = (leptons.size()>1) ? leptons[1].Phi() : 0.;


     // --------------------
     // match leptons to MC:
     // --------------------
     int correctIdMc = (leptType_==0 ) ? 13 : 11;

     for( unsigned iLept=0; iLept<leptons.size(); ++iLept ) {

       float deltaRmin = 100.;
       TLorentzVector matchedLeptonMC;

       for( unsigned iMc=0; iMc<nMc; ++iMc ) {

         if( statusMc[iMc]==1 && fabs(idMc[iMc])==correctIdMc && idMc[mothMc[mothMc[iMc]]]==23 ) {

           TLorentzVector* thisParticle = new TLorentzVector();
           thisParticle->SetPtEtaPhiE( pMc[iMc]*sin(thetaMc[iMc]), etaMc[iMc], phiMc[iMc], energyMc[iMc] );
           float thisDeltaR = leptons[iLept].DeltaR( *thisParticle );
           if( thisDeltaR < deltaRmin ) {
             deltaRmin = thisDeltaR;
             matchedLeptonMC = *thisParticle;
           }

           delete thisParticle;
           thisParticle = 0;

         } //if correct id mc

       } // for i mc


     } //for i leptons



     // ------------------
     // JETS
     // ------------------

     float jetPt_thresh = 20.;

     // first save leading jets in event:
     std::vector<AnalysisJet> leadJets;
     std::vector<int> leadJetsIndex; //index in the event collection (needed afterwards for PFCandidates)


     if( chargedHadronSubtraction_ ) {

       for( unsigned int iJet=0; iJet<nAK5PFNoPUJet; ++iJet ) {

         AnalysisJet thisJet( pxAK5PFNoPUJet[iJet], pyAK5PFNoPUJet[iJet], pzAK5PFNoPUJet[iJet], energyAK5PFNoPUJet[iJet] );

         // save at least 3 lead jets (if event has them) and all jets with pt>thresh:
         if( leadJets.size()>=3 && thisJet.Pt()<jetPt_thresh ) break;

         // far away from leptons:
         if( leptons.size()>0 )
           if( thisJet.DeltaR( leptons[0] ) <= 0.5 ) continue;
         if( leptons.size()>1 )
           if( thisJet.DeltaR( leptons[1] ) <= 0.5 ) continue;

         thisJet.nCharged = chargedHadronMultiplicityAK5PFNoPUJet[iJet] +
                            electronMultiplicityAK5PFNoPUJet[iJet] + 
                            muonMultiplicityAK5PFNoPUJet[iJet];
         thisJet.nNeutral = neutralHadronMultiplicityAK5PFNoPUJet[iJet] +
                            photonMultiplicityAK5PFNoPUJet[iJet] + 
                            HFHadronMultiplicityAK5PFNoPUJet[iJet] +
                            HFEMMultiplicityAK5PFNoPUJet[iJet];
         thisJet.ptD = ptDAK5PFNoPUJet[iJet];
         thisJet.rmsCand = rmsCandAK5PFNoPUJet[iJet];

         thisJet.axis1 = axis1AK5PFNoPUJet[iJet];
         thisJet.axis2 = axis2AK5PFNoPUJet[iJet];
         thisJet.pull = pullAK5PFNoPUJet[iJet];
         thisJet.tana = tanaAK5PFNoPUJet[iJet];

         thisJet.ptD_QC = ptD_QCAK5PFNoPUJet[iJet];
         thisJet.rmsCand_QC = rmsCand_QCAK5PFNoPUJet[iJet];
         thisJet.axis1_QC = axis1_QCAK5PFNoPUJet[iJet];
         thisJet.axis2_QC = axis2_QCAK5PFNoPUJet[iJet];
         thisJet.pull_QC = pull_QCAK5PFNoPUJet[iJet];
         thisJet.tana_QC = tana_QCAK5PFNoPUJet[iJet];

         thisJet.nChg_ptCut = nChg_ptCutAK5PFNoPUJet[iJet];
         thisJet.nChg_QC = nChg_QCAK5PFNoPUJet[iJet];
         thisJet.nChg_ptCut_QC = nChg_ptCut_QCAK5PFNoPUJet[iJet];
         thisJet.nNeutral_ptCut = nNeutral_ptCutAK5PFNoPUJet[iJet];

         thisJet.Rchg = RchgAK5PFNoPUJet[iJet];
         thisJet.Rneutral = RneutralAK5PFNoPUJet[iJet];
         thisJet.R = RAK5PFNoPUJet[iJet];
         thisJet.Rchg_QC = Rchg_QCAK5PFNoPUJet[iJet];

         thisJet.pTMax = pTMaxAK5PFNoPUJet[iJet];
         thisJet.pTMaxChg = pTMaxChgAK5PFNoPUJet[iJet];
         thisJet.pTMaxNeutral = pTMaxNeutralAK5PFNoPUJet[iJet];
         thisJet.pTMaxChg_QC = pTMaxChg_QCAK5PFNoPUJet[iJet];

         thisJet.betastar = betastarAK5PFNoPUJet[iJet];


         leadJets.push_back(thisJet);
         leadJetsIndex.push_back(iJet);


       } //for jets

     } else { // 'normal' PFJets:

       for( unsigned int iJet=0; iJet<nAK5PFPUcorrJet; ++iJet ) {

         AnalysisJet thisJet( pxAK5PFPUcorrJet[iJet], pyAK5PFPUcorrJet[iJet], pzAK5PFPUcorrJet[iJet], energyAK5PFPUcorrJet[iJet] );

         // save at least 3 lead jets (if event has them) and all jets with pt>thresh:
         if( leadJets.size()>=3 && thisJet.Pt()<jetPt_thresh ) break;

         // far away from leptons:
         if( leptons.size()>0 )
           if( thisJet.DeltaR( leptons[0] ) <= 0.5 ) continue;
         if( leptons.size()>1 )
           if( thisJet.DeltaR( leptons[1] ) <= 0.5 ) continue;

         thisJet.nCharged = chargedHadronMultiplicityAK5PFPUcorrJet[iJet] +
                            electronMultiplicityAK5PFPUcorrJet[iJet] + 
                            muonMultiplicityAK5PFPUcorrJet[iJet];
         thisJet.nNeutral = neutralHadronMultiplicityAK5PFPUcorrJet[iJet] +
                            photonMultiplicityAK5PFPUcorrJet[iJet] + 
                            HFHadronMultiplicityAK5PFPUcorrJet[iJet] +
                            HFEMMultiplicityAK5PFPUcorrJet[iJet];
         thisJet.ptD = ptDAK5PFPUcorrJet[iJet];
         thisJet.rmsCand = rmsCandAK5PFPUcorrJet[iJet];

         thisJet.axis1 = axis1AK5PFPUcorrJet[iJet];
         thisJet.axis2 = axis2AK5PFPUcorrJet[iJet];
         thisJet.pull = pullAK5PFPUcorrJet[iJet];
         thisJet.tana = tanaAK5PFPUcorrJet[iJet];

         thisJet.ptD_QC = ptD_QCAK5PFPUcorrJet[iJet];
         thisJet.rmsCand_QC = rmsCand_QCAK5PFPUcorrJet[iJet];
         thisJet.axis1_QC = axis1_QCAK5PFPUcorrJet[iJet];
         thisJet.axis2_QC = axis2_QCAK5PFPUcorrJet[iJet];
         thisJet.pull_QC = pull_QCAK5PFPUcorrJet[iJet];
         thisJet.tana_QC = tana_QCAK5PFPUcorrJet[iJet];

         thisJet.nChg_ptCut = nChg_ptCutAK5PFPUcorrJet[iJet];
         thisJet.nChg_QC = nChg_QCAK5PFPUcorrJet[iJet];
         thisJet.nChg_ptCut_QC = nChg_ptCut_QCAK5PFPUcorrJet[iJet];
         thisJet.nNeutral_ptCut = nNeutral_ptCutAK5PFPUcorrJet[iJet];

         thisJet.Rchg = RchgAK5PFPUcorrJet[iJet];
         thisJet.Rneutral = RneutralAK5PFPUcorrJet[iJet];
         thisJet.R = RAK5PFPUcorrJet[iJet];
         thisJet.Rchg_QC = Rchg_QCAK5PFPUcorrJet[iJet];

         thisJet.pTMax = pTMaxAK5PFPUcorrJet[iJet];
         thisJet.pTMaxChg = pTMaxChgAK5PFPUcorrJet[iJet];
         thisJet.pTMaxNeutral = pTMaxNeutralAK5PFPUcorrJet[iJet];
         thisJet.pTMaxChg_QC = pTMaxChg_QCAK5PFPUcorrJet[iJet];

         thisJet.betastar = betastarAK5PFPUcorrJet[iJet];


         leadJets.push_back(thisJet);
         leadJetsIndex.push_back(iJet);

       } //for jets

     } //if/else CHS


     nJet_ = 0;
     nPart_ = 0;


     for( unsigned iJet=0; iJet<leadJets.size(); ++iJet ) {
   
       AnalysisJet thisJet = leadJets[iJet];

       // --------------
       // kinematics:
       // --------------
       if( thisJet.Pt() < jetPt_thresh ) continue;
       //if( fabs(thisJet.Eta()) > 2.4 ) continue;


       if( nJet_ < 20 ) {

         eJet_[nJet_] = leadJets[nJet_].Energy();
         ptJet_[nJet_] = leadJets[nJet_].Pt();
         etaJet_[nJet_] = leadJets[nJet_].Eta();
         phiJet_[nJet_] = leadJets[nJet_].Phi();
         nCharged_[nJet_] = leadJets[nJet_].nCharged;
         nNeutral_[nJet_] = leadJets[nJet_].nNeutral;
         ptD_[nJet_] = leadJets[nJet_].ptD;
         rmsCand_[nJet_] = leadJets[nJet_].rmsCand;

         axis1_[nJet_] = thisJet.axis1;
         axis2_[nJet_] = thisJet.axis2;
         pull_[nJet_] = thisJet.pull;
         tana_[nJet_] = thisJet.tana;

         ptD_QC_[nJet_] = thisJet.ptD_QC;
         rmsCand_QC_[nJet_] = thisJet.rmsCand_QC;
         axis1_QC_[nJet_] = thisJet.axis1_QC;
         axis2_QC_[nJet_] = thisJet.axis2_QC;
         pull_QC_[nJet_] = thisJet.pull_QC;
         tana_QC_[nJet_] = thisJet.tana_QC;

         nChg_ptCut_[nJet_] = thisJet.nChg_ptCut;
         nChg_QC_[nJet_] = thisJet.nChg_QC;
         nChg_ptCut_QC_[nJet_] = thisJet.nChg_ptCut_QC;
         nNeutral_ptCut_[nJet_] = thisJet.nNeutral_ptCut;

         Rchg_[nJet_] = thisJet.Rchg;
         Rneutral_[nJet_] = thisJet.Rneutral;
         R_[nJet_] = thisJet.R;
         Rchg_QC_[nJet_] = thisJet.Rchg_QC;

         pTMax_[nJet_] = thisJet.pTMax;
         pTMaxChg_[nJet_] = thisJet.pTMaxChg;
         pTMaxNeutral_[nJet_] = thisJet.pTMaxNeutral;
         pTMaxChg_QC_[nJet_] = thisJet.pTMaxChg_QC;

         betastar_[nJet_] = thisJet.betastar;

         // match to gen jet:
         float deltaR_genJet_best = 999.;
         TLorentzVector foundGenJet;
         for( unsigned iGenJet=0; iGenJet<nAK5GenJet; ++iGenJet ) {

           TLorentzVector* thisGenJet = new TLorentzVector( pxAK5GenJet[iGenJet], pyAK5GenJet[iGenJet], pzAK5GenJet[iGenJet], energyAK5GenJet[iGenJet] );
           
           if( thisGenJet->Pt()<3. ) continue;
           float deltaR = thisGenJet->DeltaR(leadJets[nJet_]);

           if( deltaR<deltaR_genJet_best ) {
             deltaR_genJet_best = deltaR;
             foundGenJet = *thisGenJet;
           }
           
         } //for genjets

         if( deltaR_genJet_best<999. ) {

           eJetGen_[nJet_]   = foundGenJet.Energy();
           ptJetGen_[nJet_]  = foundGenJet.Pt();
           etaJetGen_[nJet_] = foundGenJet.Eta();
           phiJetGen_[nJet_] = foundGenJet.Phi();

         } else {

           eJetGen_[nJet_]   = 0.;
           ptJetGen_[nJet_]  = 0.;
           etaJetGen_[nJet_] = 0.;
           phiJetGen_[nJet_] = 0.;

         } 

         nJet_++;
          
       } //if less than 20

            
     } //for i



     if( isMC_ ) {

       // store event partons in tree:
       for( unsigned iMc=0; iMc<nMc; ++iMc ) {

         if( statusMc[iMc]==3 && (fabs(idMc[iMc])<=6 || idMc[iMc]==21) ) {

           TLorentzVector* thisParticle = new TLorentzVector();
           thisParticle->SetPtEtaPhiE( pMc[iMc]*sin(thetaMc[iMc]), etaMc[iMc], phiMc[iMc], energyMc[iMc] );

           if( nPart_<20 ) {

             ptPart_[nPart_] = thisParticle->Pt();
             etaPart_[nPart_] = thisParticle->Eta();
             phiPart_[nPart_] = thisParticle->Phi();
             ePart_[nPart_] = thisParticle->Energy();
             pdgIdPart_[nPart_] = idMc[iMc];

             nPart_++;

           } else {
      
             std::cout << "Found more than 20 partons, skipping." << std::endl;

           }

           delete thisParticle;
           thisParticle = 0;

         } //if correct id mc

       } // for i mc

     } // if is mc


     reducedTree_->Fill(); 


   } //for entries

} //loop
示例#4
0
void data13TeV() {
  //TFile f1("/tmp/rchawla/eos/cms/store/group/phys_smp/rchawla/nTuples/analysis_4March/SE_Run2015.root")
  TFile f1("eos/cms/store/group/phys_higgs/cmshww/arun/DYAnalysis_76X_Calibrated/Data/SE_2015.root");
  TTree *T1 = (TTree*)f1.Get("ntupler/ElectronTree");

  vector<float>   *genPostFSR_Pt;
  vector<float>   *genPostFSR_Eta;
  vector<float>   *genPostFSR_Rap;
  vector<float>   *genPostFSR_Phi;
  vector<float>   *genPostFSR_En;
  vector<int>     *passVetoId;
  vector<int>     *passLooseId;
  vector<int>     *passMediumId;
  vector<int>     *passTightId;
  vector<int>     *passHEEPId;
  vector<int>     *isPassMedium_NoPt;
  vector<int>     *isPassMedium_NoScEta;
  vector<int>     *isPassMedium_NoDEta;
  vector<int>     *isPassMedium_NoDPhi;
  vector<int>     *isPassMedium_NoSigmaEtaEta;
  vector<int>     *isPassMedium_NoHOverE;
  vector<int>     *isPassMedium_NoDxy;
  vector<int>     *isPassMedium_NoDz;
  vector<int>     *isPassMedium_NoEInvP;
  vector<int>     *isPassMedium_NoPFIso;
  vector<int>     *isPassMedium_NoConVeto;
  vector<int>     *isPassMedium_NoMissHits;
  vector<float>   *ptElec;
  vector<float>   *etaElec;
  vector<float>   *rapElec;
  vector<float>   *phiElec;
  vector<float>   *energyElec;
  vector<float>   *etaSC;
  Int_t           tauFlag;
  Double_t        theWeight;
  Bool_t          Ele23_WPLoose;
  Int_t           nPV;
  vector<double>  *pt_Ele23;
  vector<double>  *eta_Ele23;
  vector<double>  *phi_Ele23;

  genPostFSR_Pt = 0;
  genPostFSR_Eta = 0;
  genPostFSR_Rap = 0;
  genPostFSR_Phi = 0;
  genPostFSR_En = 0;
  ptElec = 0;
  etaElec = 0;
  rapElec = 0;
  phiElec = 0;
  energyElec = 0;
  etaSC = 0;
  passVetoId = 0;
  passLooseId = 0;
  passMediumId = 0;
  passTightId = 0;
  passHEEPId = 0;
  isPassMedium_NoPt = 0;
  isPassMedium_NoScEta = 0;
  isPassMedium_NoDEta = 0;
  isPassMedium_NoDPhi = 0;
  isPassMedium_NoSigmaEtaEta = 0;
  isPassMedium_NoHOverE = 0;
  isPassMedium_NoDxy = 0;
  isPassMedium_NoDz = 0;
  isPassMedium_NoEInvP = 0;
  isPassMedium_NoPFIso = 0;
  isPassMedium_NoConVeto = 0;
  isPassMedium_NoMissHits = 0;
  pt_Ele23 = 0;
  eta_Ele23 = 0;
  phi_Ele23 = 0;

  T1->SetBranchAddress("genPostFSR_Pt", &genPostFSR_Pt);
  T1->SetBranchAddress("genPostFSR_Eta", &genPostFSR_Eta);
  T1->SetBranchAddress("genPostFSR_Rap", &genPostFSR_Rap);
  T1->SetBranchAddress("genPostFSR_Phi", &genPostFSR_Phi);
  T1->SetBranchAddress("genPostFSR_En", &genPostFSR_En);
  T1->SetBranchAddress("ptElec", &ptElec);
  T1->SetBranchAddress("etaElec", &etaElec);
  T1->SetBranchAddress("rapElec", &rapElec);
  T1->SetBranchAddress("phiElec", &phiElec);
  T1->SetBranchAddress("energyElec", &energyElec);
  T1->SetBranchAddress("etaSC", &etaSC);
  T1->SetBranchAddress("passVetoId", &passVetoId);
  T1->SetBranchAddress("passLooseId", &passLooseId);
  T1->SetBranchAddress("passMediumId", &passMediumId);
  T1->SetBranchAddress("passTightId", &passTightId);
  T1->SetBranchAddress("passHEEPId", &passHEEPId);
  T1->SetBranchAddress("isPassMedium_NoPt", &isPassMedium_NoPt);
  T1->SetBranchAddress("isPassMedium_NoScEta", &isPassMedium_NoScEta);
  T1->SetBranchAddress("isPassMedium_NoDEta", &isPassMedium_NoDEta);
  T1->SetBranchAddress("isPassMedium_NoDPhi", &isPassMedium_NoDPhi);
  T1->SetBranchAddress("isPassMedium_NoSigmaEtaEta", &isPassMedium_NoSigmaEtaEta);
  T1->SetBranchAddress("isPassMedium_NoHOverE", &isPassMedium_NoHOverE);
  T1->SetBranchAddress("isPassMedium_NoDxy", &isPassMedium_NoDxy);
  T1->SetBranchAddress("isPassMedium_NoDz", &isPassMedium_NoDz);
  T1->SetBranchAddress("isPassMedium_NoEInvP", &isPassMedium_NoEInvP);
  T1->SetBranchAddress("isPassMedium_NoPFIso", &isPassMedium_NoPFIso);
  T1->SetBranchAddress("isPassMedium_NoConVeto", &isPassMedium_NoConVeto);
  T1->SetBranchAddress("isPassMedium_NoMissHits", &isPassMedium_NoMissHits);
  T1->SetBranchAddress("tauFlag", &tauFlag);
  T1->SetBranchAddress("theWeight", &theWeight);
  T1->SetBranchAddress("Ele23_WPLoose", &Ele23_WPLoose);
  T1->SetBranchAddress("nPV", &nPV);
  T1->SetBranchAddress("Ele23_WPLoose", &Ele23_WPLoose);
  T1->SetBranchAddress("pt_Ele23", &pt_Ele23);
  T1->SetBranchAddress("eta_Ele23", &eta_Ele23);
  T1->SetBranchAddress("phi_Ele23", &phi_Ele23);

  TFile *file = new TFile("MediumId_Calibrated/SingleElectron_UnScaleCorr.root", "recreate");
  TTree *tree = new TTree("tree"," after preselections tree");

  int mediumId, dzMaskId, passId;
  bool trigMatch_lead, trigMatch_slead;
  double dR, dR1, dR2;
  TLorentzVector ele1,ele2,dielectron;
  TLorentzVector recoElec;

  // Branch variable declaration
  double primVtx;
  double Ele1PT, Ele2PT, Ele1Eta, Ele2Eta, Ele1Phi, Ele2Phi, Ele1Enr, Ele2Enr;
  double ZMass, ZPT, ZEta, ZRapidity, ZPhi;
  bool BB, BE, EE;

  // Branch declaration
  tree->Branch("primVtx", &primVtx, "primVtx/D");
  tree->Branch("Ele1PT", &Ele1PT, "Ele1PT/D");
  tree->Branch("Ele2PT", &Ele2PT, "Ele2PT/D");
  tree->Branch("Ele1Eta", &Ele1Eta, "Ele1Eta/D");
  tree->Branch("Ele2Eta", &Ele2Eta, "Ele2Eta/D");
  tree->Branch("Ele1Phi", &Ele1Phi, "Ele1Phi/D");
  tree->Branch("Ele2Phi", &Ele2Phi, "Ele2Phi/D");
   tree->Branch("Ele1Enr", &Ele1Enr, "Ele1Enr/D");
    tree->Branch("Ele2Enr", &Ele2Enr, "Ele2Enr/D");
  tree->Branch("ZMass", &ZMass, "ZMass/D");
  tree->Branch("ZPT", &ZPT, "ZPT/D");
  tree->Branch("ZEta", &ZEta, "ZEta/D");
  tree->Branch("ZRapidity", &ZRapidity, "ZRapidity/D");
  tree->Branch("ZPhi", &ZPhi, "ZPhi/D");
  tree->Branch("BB", &BB, "BB/B");
  tree->Branch("BE", &BE, "BE/B");
  tree->Branch("EE", &EE, "EE/B");

  vector <double> newelePt; vector <double> neweleEta; vector <double> neweleEnr; vector <double> newelePhi;vector <double> newscEta;
  vector <double> elePt; vector <double> eleEta; vector <double> eleEnr; vector <double> elePhi; vector <double> elescEta;
  TClonesArray *eleP4 = new TClonesArray("TLorentzVector", 1500);

  int nentries = T1->GetEntries();
  //int nentries = 10000;
  cout<<"entries: "<<nentries<<endl;
  for (unsigned int jentry=0; jentry < nentries; jentry++) {
    T1->GetEntry(jentry);

    if(jentry%1000000 == 0){
      cout << "Events Processed :  " << jentry << endl;
    }

    trigMatch_lead = false; trigMatch_slead = false;
    dR = 0.; dR1 = 0.; dR2 = 0.;
    BB=false; BE=false; EE=false;
    mediumId = 0; dzMaskId = 0; passId =0;

    newelePt.clear(); neweleEta.clear(); newelePhi.clear(); neweleEnr.clear();newscEta.clear();
    elePt.clear(); eleEta.clear(); elePhi.clear(); eleEnr.clear();elescEta.clear();
    recoElec.SetPtEtaPhiE(0.,0.,0.,0.);
    eleP4->Clear();

    primVtx = nPV;

    if(!Ele23_WPLoose) continue;

    for(int i=0;i<ptElec->size();i++){

      recoElec.SetPtEtaPhiE(ptElec->at(i),etaElec->at(i), phiElec->at(i), energyElec->at(i));
      new ((*eleP4)[i]) TLorentzVector(recoElec);
      TLorentzVector* fourmom = (TLorentzVector*) eleP4->At(i);

   //  if(fourmom->Eta() < 1.4442) *fourmom *= 0.9994;
   //   if(fourmom->Eta() > 1.566) *fourmom *= 1.0034;

      if(fourmom->Eta() < 1.4442) *fourmom *= 1.0;
      if(fourmom->Eta() > 1.566) *fourmom *= 1.0;

     //   mediumId = passHEEPId->at(i);
       mediumId = passMediumId->at(i);

       passId = mediumId;

//      if (ptElec->at(i) < 500.) { passId = mediumId; }
//     else { passId = dzMaskId; }

      if(passId) {
	if(fabs(etaSC->at(i)) < 2.5 && !(fabs(etaSC->at(i)) > 1.4442 && fabs(etaSC->at(i)) < 1.566)){

	  newelePt.push_back(fourmom->Pt());
	  neweleEta.push_back(fourmom->Eta());
	  neweleEnr.push_back(fourmom->Energy());
	  newelePhi.push_back(fourmom->Phi());
          newscEta.push_back(etaSC->at(i));
	}
      }
    }

    // Sorting
    int index[newelePt.size()];
    float pt[newelePt.size()];

    for(unsigned int el=0; el<newelePt.size(); el++)
    { 
      pt[el]=newelePt.at(el);
    }

    int size = sizeof(pt)/sizeof(pt[0]);
    TMath::Sort(size,pt,index,true);

    if(newelePt.size()==2){

      for(unsigned int j = 0; j < pt_Ele23->size(); j++){

	double dR1_comp = 1000.;
	double dR2_comp = 1000.;

	dR1 = deltaR(neweleEta.at(index[0]), newelePhi.at(index[0]), eta_Ele23->at(j), phi_Ele23->at(j));
	dR2 = deltaR(neweleEta.at(index[1]), newelePhi.at(index[1]), eta_Ele23->at(j), phi_Ele23->at(j));

	if(dR1 < 0.1){
	  if (dR1 < dR1_comp)
	  {
	    dR1_comp = dR1;
	    trigMatch_lead = true;
	  }
	} // dR1

	if(dR2 < 0.1){
	  if (dR2 < dR2_comp)
	  {
	    dR2_comp = dR2; 
	    trigMatch_slead = true; 
	  }
	} // dR2
      } // pt_Ele23

      if(trigMatch_lead || trigMatch_slead){

	if(newelePt.at(index[0]) > 30. && newelePt.at(index[1]) > 10.) {

	  ele1.SetPtEtaPhiE(newelePt.at(index[0]),neweleEta.at(index[0]),newelePhi.at(index[0]),neweleEnr.at(index[0]));
	  ele2.SetPtEtaPhiE(newelePt.at(index[1]),neweleEta.at(index[1]),newelePhi.at(index[1]),neweleEnr.at(index[1]));
	  dielectron=ele1+ele2;

	  Ele1PT  = newelePt.at(index[0]);
	  Ele2PT  = newelePt.at(index[1]);
	  Ele1Eta = neweleEta.at(index[0]);
	  Ele2Eta = neweleEta.at(index[1]);
	  Ele1Phi = newelePhi.at(index[0]);
	  Ele2Phi = newelePhi.at(index[1]);

	  ZMass = dielectron.M();
	  ZPT = dielectron.Pt();
	  ZEta = dielectron.Eta();
	  ZRapidity = dielectron.Rapidity();
	  ZPhi = dielectron.Phi();
/*
	  if(fabs(neweleEta.at(index[0])) < 1.4442 && fabs(neweleEta.at(index[1])) < 1.4442) BB = true;
	  if((fabs(neweleEta.at(index[0])) < 1.4442 && fabs(neweleEta.at(index[1])) > 1.566) || (fabs(neweleEta.at(index[0])) > 1.566 && fabs(neweleEta.at(index[1])) < 1.4442)) BE =true;
	  if(fabs(neweleEta.at(index[0])) > 1.566 && fabs(neweleEta.at(index[1])) > 1.566) EE =true;
*/

          if(fabs(newscEta.at(index[0])) < 1.4442 && fabs(newscEta.at(index[1])) < 1.4442) BB = true;
          if((fabs(newscEta.at(index[0])) < 1.4442 && fabs(newscEta.at(index[1])) > 1.566) || (fabs(newscEta.at(index[0])) > 1.566 && fabs(newscEta.at(index[1])) < 1.4442)) BE =true;
          if(fabs(newscEta.at(index[0])) > 1.566 && fabs(newscEta.at(index[1])) > 1.566) EE =true;
	  tree->Fill();

	} // pt
      } // trig matching
    } // size==2
  } // event

  file->Write();
  file->Close();
}
示例#5
0
文件: PolMC.C 项目: hwoehri/UserCode
//==============================================
void PolMC::Loop(Int_t selDimuType)
{
  if (fChain == 0) return;

  Long64_t nentries = fChain->GetEntries();
  Long64_t countGenEvent = 0;
  Long64_t nb = 0;
  printf("number of entries = %d\n", (Int_t) nentries);

  //loop over the events
  for (Long64_t jentry=0; jentry<nentries;jentry++) {

    if(jentry % 100000 == 0) printf("event %d\n", (Int_t) jentry);

    Long64_t ientry = LoadTree(jentry);
    if (ientry < 0) break;
    nb = fChain->GetEntry(jentry);

    //protection against dummy events:
    if(muPosPx_Gen < -9900.)
      continue;

    hGen_StatEv->Fill(0.5);//count all events
    //do NOT select on the dimuon type (only a RECO variable)
    hGen_StatEv->Fill(1.5);//count all events

    Double_t enMuPos = sqrt(muPosPx_Gen*muPosPx_Gen + muPosPy_Gen*muPosPy_Gen + muPosPz_Gen*muPosPz_Gen + jpsi::muMass*jpsi::muMass);
    Double_t enMuNeg = sqrt(muNegPx_Gen*muNegPx_Gen + muNegPy_Gen*muNegPy_Gen + muNegPz_Gen*muNegPz_Gen + jpsi::muMass*jpsi::muMass);
    TLorentzVector *muPos = new TLorentzVector();
    TLorentzVector *muNeg = new TLorentzVector();
    muPos->SetPxPyPzE(muPosPx_Gen, muPosPy_Gen, muPosPz_Gen, enMuPos);
    muNeg->SetPxPyPzE(muNegPx_Gen, muNegPy_Gen, muNegPz_Gen, enMuNeg);
    Double_t etaMuPos = muPos->PseudoRapidity();
    Double_t etaMuNeg = muNeg->PseudoRapidity();
    Double_t pTMuPos = muPos->Pt();
    Double_t pTMuNeg = muNeg->Pt();

    //take muons only within a certain eta range
    if(TMath::Abs(etaMuPos) > jpsi::etaPS || TMath::Abs(etaMuNeg) > jpsi::etaPS){
      // printf("eta(pos. muon) = %f, eta(neg. muon) = %f\n", etaMuPos, etaMuNeg);
      continue;
    }
    hGen_StatEv->Fill(2.5);//count all events

    if(pTMuPos < jpsi::pTMuMin && pTMuNeg < jpsi::pTMuMin){
      // printf("pT(pos. muon) = %f, pT(neg. muon) = %f\n", pTMuPos, pTMuNeg);
      continue;
    }
    hGen_StatEv->Fill(3.5);

    //test according to Gavin's proposal:
    //if any of the two muons is within 1.4 < eta < 1.6 AND
    //the two muons are close in eta (deltaEta < 0.2)
    //reject the dimuon (no matter whether it is "Seagull" or 
    //"Cowboy"):
//     if(TMath::Abs(etaMuPos - etaMuNeg) < 0.2 &&
//        ((etaMuPos > 1.4 && etaMuPos < 1.6) || (etaMuNeg > 1.4 && etaMuNeg < 1.6))){
//       printf("rejecting the event!\n");
//       continue;
//     }

    //build the invariant mass, pt, ... of the two muons
    TLorentzVector *onia = new TLorentzVector();
    *onia = *(muPos) + *(muNeg);

    Double_t onia_mass = onia->M();
    Double_t onia_pt = onia->Pt();
    Double_t onia_P = onia->P();
    Double_t onia_eta = onia->PseudoRapidity();
    Double_t onia_rap = onia->Rapidity();
    Double_t onia_phi = onia->Phi();
    Double_t onia_mT = sqrt(onia_mass*onia_mass + onia_pt*onia_pt);

    // Int_t rapIndex = -1;
    // for(int iRap = 0; iRap < 2*jpsi::kNbRapBins; iRap++){
    //   if(onia_rap > jpsi::rapRange[iRap] && onia_rap < jpsi::rapRange[iRap+1]){
    // 	rapIndex = iRap+1;
    // 	break;
    //   }
    // }
    Int_t rapForPTIndex = -1;
    for(int iRap = 0; iRap < jpsi::kNbRapForPTBins; iRap++){
      if(TMath::Abs(onia_rap) > jpsi::rapForPTRange[iRap] && 
	 TMath::Abs(onia_rap) < jpsi::rapForPTRange[iRap+1]){
	 rapForPTIndex = iRap+1;
	break;
      }
    }
    Int_t pTIndex = -1;
    for(int iPT = 0; iPT < jpsi::kNbPTBins[rapForPTIndex]; iPT++){
      if(onia_pt > jpsi::pTRange[rapForPTIndex][iPT] && onia_pt < jpsi::pTRange[rapForPTIndex][iPT+1]){
	pTIndex = iPT+1;
	break;
      }
    }
    Int_t rapIntegratedPTIndex = -1;
    for(int iPT = 0; iPT < jpsi::kNbPTBins[0]; iPT++){
      if(onia_pt > jpsi::pTRange[0][iPT] && onia_pt < jpsi::pTRange[0][iPT+1]){
	rapIntegratedPTIndex = iPT+1;
	break;
      }
    }

    // if(rapIndex < 1){
    //   printf("rapIndex %d, rap(onia) = %f\n", rapIndex, onia_rap);
    //   continue;
    // }
    if(rapForPTIndex < 1){
      // printf("rapForPTIndex %d, rap(onia) = %f\n", rapForPTIndex, onia_rap);
      continue;
    }
    if(pTIndex < 1){
      // printf("pTIndex %d, pT(onia) = %f\n", pTIndex, onia_pt);
      continue;
    }

    hGen_StatEv->Fill(4.5);

    if(TMath::Abs(onia_rap) > jpsi::rapYPS)
      continue;

    hGen_StatEv->Fill(7.5);

    //remaining of the events will be used for the analysis
    countGenEvent++;

    //fill mass, phi, pt, eta and rap distributions
    //a) all bins
    hGen_Onia_mass[0][0]->Fill(onia_mass);
    hGen_Onia_mass[rapIntegratedPTIndex][0]->Fill(onia_mass);
    hGen_Onia_mass[0][rapForPTIndex]->Fill(onia_mass);
    //
    hGen_Onia_phi[0][0]->Fill(onia_phi);
    hGen_Onia_phi[rapIntegratedPTIndex][0]->Fill(onia_phi);
    hGen_Onia_phi[0][rapForPTIndex]->Fill(onia_phi);
      
    hGen_Onia_pt[0]->Fill(onia_pt);
    // hGen_Onia_eta[0]->Fill(onia_eta);
    // hGen_Onia_rap[0]->Fill(onia_rap);
    //b) individual pT and rap bins:
    hGen_Onia_mass[pTIndex][rapForPTIndex]->Fill(onia_mass);
    hGen_Onia_phi[pTIndex][rapForPTIndex]->Fill(onia_phi);
    hGen_Onia_pt[rapForPTIndex]->Fill(onia_pt);
    // hGen_Onia_eta[pTIndex]->Fill(onia_eta);
    // hGen_Onia_rap[pTIndex]->Fill(onia_rap);

    hGen_Onia_rap_pT->Fill(onia_rap, onia_pt);

    //=====================
    calcPol(*muPos, *muNeg);
    //=====================

    //test:
//     calcPol(*muNeg, *muPos);
//     //H: test:
//     if(jentry%2 == 0)
//       calcPol(*muPos, *muNeg);
//     else
//       calcPol(*muNeg, *muPos);

    //===================================================
    //calculate delta, the angle between the CS and HX frame
    //Formula from EPJC paper
    Double_t deltaHXToCS = TMath::ACos(onia_mass * onia->Pz() / (onia_mT * onia_P));
    //     Double_t deltaCSToHX = -deltaHXToCS;
    Double_t sin2Delta = pow((onia_pt * onia->Energy() / (onia_P * onia_mT)),2);
    //sin2Delta does not change sign when going from HX-->CS or vice versa
    hDelta[pTIndex][rapForPTIndex]->Fill(deltaHXToCS * 180./TMath::Pi());
    hSin2Delta[pTIndex][rapForPTIndex]->Fill(sin2Delta);
    //===================================================

    Double_t deltaPhi = muPos->Phi() - muNeg->Phi();
    if(deltaPhi < -TMath::Pi()) deltaPhi += 2.*TMath::Pi();
    else if(deltaPhi > TMath::Pi()) deltaPhi = 2.*TMath::Pi() - deltaPhi;

    //debugging histos
    hPhiPos_PhiNeg[pTIndex][rapForPTIndex]->Fill(180./TMath::Pi() * muNeg->Phi(), 180./TMath::Pi() * muPos->Phi());
    hPtPos_PtNeg[pTIndex][rapForPTIndex]->Fill(muNeg->Pt(), muPos->Pt());
    hEtaPos_EtaNeg[pTIndex][rapForPTIndex]->Fill(muNeg->PseudoRapidity(), muPos->PseudoRapidity());
    // hDeltaPhi[pTIndex][rapIndex]->Fill(deltaPhi);
    hDeltaPhi[pTIndex][rapForPTIndex]->Fill(deltaPhi);

    hGen_mupl_pt[pTIndex][rapForPTIndex]->Fill(muPos->Pt());
    hGen_mupl_eta[pTIndex][rapForPTIndex]->Fill(muPos->PseudoRapidity());
    hGen_mupl_phi[pTIndex][rapForPTIndex]->Fill(muPos->Phi());
      
    hGen_mumi_pt[pTIndex][rapForPTIndex]->Fill(muNeg->Pt());
    hGen_mumi_eta[pTIndex][rapForPTIndex]->Fill(muNeg->PseudoRapidity());
    hGen_mumi_phi[pTIndex][rapForPTIndex]->Fill(muNeg->Phi());

    //fill the histos for all the different frames
    for(int iFrame = 0; iFrame < jpsi::kNbFrames; iFrame++){

      thisCosPhi[iFrame] = TMath::Cos(2.*thisPhi_rad[iFrame]);

      Double_t weight = CalcPolWeight(onia_P, thisCosTh[iFrame]);

      //1a) polariztion histos - all pT
      // hGen_Onia_pol_pT[iFrame][0][jpsi::cosThPol]->Fill(thisCosTh[iFrame], weight);
      // hGen_Onia_pol_pT[iFrame][0][jpsi::phiPol]->Fill(thisPhi[iFrame], weight);
      // hGen_Onia_pol_pT[iFrame][0][jpsi::cos2PhiPol]->Fill(thisCosPhi[iFrame], weight);
      // hGen2D_Onia_pol_pT[iFrame][0]->Fill(thisCosTh[iFrame], thisPhi[iFrame], weight);

      //1b) polariztion histos - pT Bin
      // if(pTIndex > 0){
      // 	hGen_Onia_pol_pT[iFrame][pTIndex][jpsi::cosThPol]->Fill(thisCosTh[iFrame], weight);
      // 	hGen_Onia_pol_pT[iFrame][pTIndex][jpsi::phiPol]->Fill(thisPhi[iFrame], weight);
      // 	hGen_Onia_pol_pT[iFrame][pTIndex][jpsi::cos2PhiPol]->Fill(thisCosPhi[iFrame], weight);
      // 	hGen2D_Onia_pol_pT[iFrame][pTIndex]->Fill(thisCosTh[iFrame], thisPhi[iFrame], weight);
      // }

      // //2a) polariztion histos - all Rap
      // hGen_Onia_pol_rap[iFrame][0][jpsi::cosThPol]->Fill(thisCosTh[iFrame], weight);
      // hGen_Onia_pol_rap[iFrame][0][jpsi::phiPol]->Fill(thisPhi[iFrame], weight);
      // hGen_Onia_pol_rap[iFrame][0][jpsi::cos2PhiPol]->Fill(thisCosPhi[iFrame], weight);
      // hGen2D_Onia_pol_rap[iFrame][0]->Fill(thisCosTh[iFrame], thisPhi[iFrame], weight);

      // //2b) polariztion histos - rap Bin
      // if(rapIndex > 0){
      // 	hGen_Onia_pol_rap[iFrame][rapIndex][jpsi::cosThPol]->Fill(thisCosTh[iFrame], weight);
      // 	hGen_Onia_pol_rap[iFrame][rapIndex][jpsi::phiPol]->Fill(thisPhi[iFrame], weight);
      // 	hGen_Onia_pol_rap[iFrame][rapIndex][jpsi::cos2PhiPol]->Fill(thisCosPhi[iFrame], weight);
      // 	hGen2D_Onia_pol_rap[iFrame][rapIndex]->Fill(thisCosTh[iFrame], thisPhi[iFrame], weight);
      // }

      //3) polariztion histos - pT and rap Bin
      //all pT and rapidities
      hGen2D_Onia_pol_pT_rap[iFrame][0][0]->Fill(thisCosTh[iFrame], thisPhi[iFrame], weight);
      if(rapIntegratedPTIndex > 0)
	hGen2D_Onia_pol_pT_rap[iFrame][rapIntegratedPTIndex][0]->Fill(thisCosTh[iFrame], thisPhi[iFrame], weight);
      if(rapForPTIndex > 0)
	hGen2D_Onia_pol_pT_rap[iFrame][0][rapForPTIndex]->Fill(thisCosTh[iFrame], thisPhi[iFrame], weight);
      if(pTIndex > 0 && rapForPTIndex > 0){
	hGen_Onia_pol_pT_rap[iFrame][pTIndex][rapForPTIndex][jpsi::cosThPol]->Fill(thisCosTh[iFrame], weight);
	hGen_Onia_pol_pT_rap[iFrame][pTIndex][rapForPTIndex][jpsi::phiPol]->Fill(thisPhi[iFrame], weight);
	hGen_Onia_pol_pT_rap[iFrame][pTIndex][rapForPTIndex][jpsi::cos2PhiPol]->Fill(thisCosPhi[iFrame], weight);
	hGen2D_Onia_pol_pT_rap[iFrame][pTIndex][rapForPTIndex]->Fill(thisCosTh[iFrame], thisPhi[iFrame], weight);
      }
    }

    delete muPos;
    delete muNeg;
    delete onia;
  }//loop over entries

  printf("nb. of rec. events is %d of a total of %d events\n", (Int_t) countGenEvent, (Int_t) nentries);
}
void MassPlotterSingleTop::singleTopAnalysis(TList* allCuts, Long64_t nevents ,TString myfileName ){

  TopUtilities topUtils ;

  int lumi = 0;

  TIter nextcut(allCuts); 
  TObject *objcut; 

  std::vector<TString> alllabels;
  while( objcut = nextcut() ){
    ExtendedCut* thecut = (ExtendedCut*)objcut ;
    alllabels.push_back( thecut->Name );
  }  
  //alllabels.push_back( "NoCut" );
  alllabels.push_back( "Trigger" );
  //alllabels.push_back( "MuonSelection" );
  //alllabels.push_back( "MuonVeto1" );
  //alllabels.push_back( "MuonVeto" );
  alllabels.push_back( "== 1#mu" );
  alllabels.push_back( "== 2-Jets" );
  alllabels.push_back( "== 1-bJet" );
  alllabels.push_back( "MT >50 GeV" );
  //alllabels.push_back( "j'-bVeto" );
  alllabels.push_back( "mtop" );
  //cout << alllabels.size() << endl;

  ExtendedObjectProperty cutflowtable("" , "cutflowtable" , "1" , alllabels.size() ,  0 , alllabels.size() , "2", {}, &alllabels );  
  ExtendedObjectProperty cutflowtablew1("" , "cutflowtablew1" , "1" , alllabels.size() ,  0 , alllabels.size() , "2", {}, &alllabels );  
  

  TString fileName = fOutputDir;
  if(!fileName.EndsWith("/")) fileName += "/";
  Util::MakeOutputDir(fileName);

  bool printEventIds = false;
  vector< ofstream* > EventIdFiles;
  if(printEventIds){
    for( int i = 0 ; i < alllabels.size() ; i++ ){
      ofstream* filetxt = new ofstream(fileName + "/IPM_" + myfileName  + "_step" + boost::lexical_cast<string>(i) + ".txt" );
      EventIdFiles.push_back( filetxt );
    }
  }


  ExtendedObjectProperty nJetsBeforeCut("LeptonVeto" , "nJets" , "1" , 8 , 0 , 8 , "2", {});
  ExtendedObjectProperty nJets20_47("OneBjet" , "nJets20_47" , "1" , 8 , 0 , 8 , "2", {});
  ExtendedObjectProperty nJets20_24("OneBjet" , "nJets20_24" , "1" , 8 , 0 , 8 , "2", {});
  ExtendedObjectProperty nbJets("Jets" , "nbJets" , "1" , 3 , 0 , 3 , "2", {});

  ExtendedObjectProperty MTBeforeCut("OneBjetNoMT" , "MT" , "1" , 30 , 0 , 300 , "2", {});

  ExtendedObjectProperty nPVBeforeCutsUnCorr("nPVBeforeCutsUnCorr" , "nPVBeforeCutsUnCorr" , "1" , 100 , 0 , 100 , "2", {});
  ExtendedObjectProperty nPVBeforeCuts("nPVBeforeCuts" , "nPVBeforeCuts" , "1" , 100 , 0 , 100 , "2", {});
  ExtendedObjectProperty nPVAfterCutsUnCorr("nPVAfterCutsUnCorr" , "nPVAfterCutsUnCorr" , "1" , 100 , 0 , 100 , "2", {});
  ExtendedObjectProperty nPVAfterCuts("nPVAfterCuts" , "nPVAfterCuts" , "1" , 100 , 0 , 100 , "2", {});

  ExtendedObjectProperty TopMass("OneBjet" , "TopMass" , "1" , 30 , 100 , 400 , "2", {});
  ExtendedObjectProperty jprimeEta("OneBjet" , "jPrimeEta" , "1" , 10 , 0 , 5.0 , "2", {});
  ExtendedObjectProperty jprimeEtaSB("SideBand" , "jPrimeEtaSB" , "1" , 10 , 0 , 5.0 , "2", {});
  ExtendedObjectProperty jprimePt("OneBjet" , "jPrimePt" , "1" , 30 , 30 , 330 , "2", {});
  ExtendedObjectProperty muPtOneB("OneBjet" , "muPt" , "1" , 20 , 20 , 120 , "2", {});
  ExtendedObjectProperty muCharge("OneBjet" , "muCharge" , "1" , 40 , -2 , 2 , "2", {});
  ExtendedObjectProperty muEtaOneB("OneBjet" , "muEta" , "1" , 10 , -2.5 , 2.5 , "2", {});
  ExtendedObjectProperty METOneBSR("OneBjet" , "MET_SR" , "1" , 20 , 0 , 200 , "2", {});
  ExtendedObjectProperty METOneBSB("OneBjet" , "MET_SB" , "1" , 20 , 0 , 200 , "2", {});
  ExtendedObjectProperty METOneBAll("OneBjet" , "MET_ALL" , "1" , 20 , 0 , 200 , "2", {});
  ExtendedObjectProperty bPtOneB("OneBjet" , "bPt" , "1" , 30 , 30 , 330 , "2", {});
  ExtendedObjectProperty bEtaOneB("OneBjet" , "bEta" , "1" , 10 , 0 , 5.0 , "2", {});
  ExtendedObjectProperty nonbCSV("OneBjet" , "jpCSV" , "1" , 20 , 0 , 1.0 , "2", {});

  ExtendedObjectProperty nLbjets1EJ24("1EJ24" , "nLbJets_1EJ24" , "1" , 2 , 0 , 2  , "2", {});
  ExtendedObjectProperty nTbjets1EJ24("1EJ24" , "nTbJets_1EJ24" , "1" , 2 , 0 , 2  , "2", {});

  ExtendedObjectProperty nLbjets2EJ24("2EJ24" , "nLbJets_2EJ24" , "1" , 3 , 0 , 3  , "2", {});
  ExtendedObjectProperty nTbjets2EJ24("2EJ24" , "nTbJets_2EJ24" , "1" , 3 , 0 , 3  , "2", {});

  ExtendedObjectProperty nLbjets3EJ24("3EJ24" , "nLbJets_3EJ24" , "1" , 4 , 0 , 4  , "2", {});
  ExtendedObjectProperty nTbjets3EJ24("3EJ24" , "nTbJets_3EJ24" , "1" , 4 , 0 , 4  , "2", {});

  ExtendedObjectProperty nLbjets4EJ24("4EJ24" , "nLbJets_4EJ24" , "1" , 5 , 0 , 5  , "2", {});
  ExtendedObjectProperty nTbjets4EJ24("4EJ24" , "nTbJets_4EJ24" , "1" , 5 , 0 , 5  , "2", {});

  ExtendedObjectProperty nLbjets1EJ47("1EJ47" , "nLbJets_1EJ47" , "1" , 2 , 0 , 2  , "2", {});
  ExtendedObjectProperty nTbjets1EJ47("1EJ47" , "nTbJets_1EJ47" , "1" , 2 , 0 , 2  , "2", {});

  ExtendedObjectProperty nLbjets2EJ47("2EJ47" , "nLbJets_2EJ47" , "1" , 3 , 0 , 3  , "2", {});
  ExtendedObjectProperty nTbjets2EJ47("2EJ47" , "nTbJets_2EJ47" , "1" , 3 , 0 , 3  , "2", {});

  ExtendedObjectProperty nLbjets3EJ47("3EJ47" , "nLbJets_3EJ47" , "1" , 4 , 0 , 4  , "2", {});
  ExtendedObjectProperty nTbjets3EJ47("3EJ47" , "nTbJets_3EJ47" , "1" , 4 , 0 , 4  , "2", {});

  ExtendedObjectProperty nLbjets4EJ47("4EJ47" , "nLbJets_4EJ47" , "1" , 5 , 0 , 5  , "2", {});
  ExtendedObjectProperty nTbjets4EJ47("4EJ47" , "nTbJets_4EJ47" , "1" , 5 , 0 , 5  , "2", {});

  TH1* hTopMass = new TH1D("hTopMass" , "Top Mass" , 500 , 0 , 500 );
  TH1* hTopMassEtaJ = new TH2D( "hTopMassEtaJ" , "Top Mass" , 500 , 0 , 500 , 20 , 0 , 5.0 );

  TH1* hEtajPDFScales[102];
  double ScalesPDF[102];
  double CurrentPDFWeights[102];
  for(int i=0 ; i < 102 ; i++){
    TString s(to_string(i));
    hEtajPDFScales[i] = new TH1D( TString("hEtaJp_PDF")+s , "" , 10 , 0 , 5.0 );
    ScalesPDF[i] = 0 ;
    CurrentPDFWeights[i] = 0;
  }

  TH1* hEtajWScales[9];
  double WScalesTotal[9];
  double CurrentLHEWeights[9];
  for(int i=0; i < 9; i++){
    TString s(to_string(i));
    hEtajWScales[i] = new TH1D( TString("hEtaJp_")+s , "" , 10 , 0 , 5.0 );
    WScalesTotal[i] = 0 ;
    CurrentLHEWeights[i] = 0;
  }

  std::vector<ExtendedObjectProperty*> allProps = {&cutflowtable, &cutflowtablew1 , &nJetsBeforeCut , &nbJets , &MTBeforeCut, &TopMass , &jprimeEta , &jprimeEtaSB , &jprimePt , &muPtOneB, &muCharge, &muEtaOneB , &METOneBSR ,&METOneBSB , &METOneBAll , & bPtOneB , &bEtaOneB , &nonbCSV ,&nJets20_24, &nJets20_47,&nPVAfterCuts, &nPVBeforeCuts , &nPVAfterCutsUnCorr , &nPVBeforeCutsUnCorr};

  std::vector<ExtendedObjectProperty*> JbJOptimizationProps = {&nLbjets1EJ24,&nTbjets1EJ24,&nLbjets2EJ24,&nTbjets2EJ24,&nLbjets3EJ24,&nTbjets3EJ24,&nLbjets4EJ24,&nTbjets4EJ24,&nLbjets1EJ47,&nTbjets1EJ47,&nLbjets2EJ47,&nTbjets2EJ47,&nLbjets3EJ47,&nTbjets3EJ47,&nLbjets4EJ47,&nTbjets4EJ47};
  nextcut.Reset();


  //codes for 2j0t selection
  TFile *theTreeFile = NULL;
  if(IsQCD==1)
    theTreeFile = new TFile( (fileName+ myfileName + "_Trees.root" ).Data(), "RECREATE");    

  double MT_QCD_Tree , TOPMASS_QCD_Tree , MuIso_QCD_Tree , Weight_QCD_Tree;

  TTree* theQCD_Tree = NULL;
  //end of 2j0t

  for(int ii = 0; ii < fSamples.size(); ii++){

    int data = 0;
    sample Sample = fSamples[ii];

    TEventList* list = 0;
   
    if(Sample.type == "data"){
      data = 1;
    }else
      lumi = Sample.lumi; 

    if( theTreeFile ){
      TString treename = Sample.sname ;
      if( data )
	treename = "Data";
      if( theTreeFile->Get( treename ) ){
	theQCD_Tree = (TTree*) (theTreeFile->Get( treename )) ; 
      }else{
	theTreeFile->cd();
	theQCD_Tree = new TTree( treename , treename + " tree for QCD shape/normalization studies" );
	theQCD_Tree->Branch( "MT/D" , &MT_QCD_Tree );
	theQCD_Tree->Branch( "TOPMASS/D" , &TOPMASS_QCD_Tree );
	theQCD_Tree->Branch( "MuIso/D" , &MuIso_QCD_Tree );
	theQCD_Tree->Branch( "Weight/D" , &Weight_QCD_Tree );
      }
    }


    double Weight = Sample.xsection * Sample.kfact * Sample.lumi / (Sample.nevents*Sample.PU_avg_weight);
    //Weight = 1.0;
    if(data == 1)
      Weight = 1.0;

    Sample.Print(Weight);

    SingleTopTree fTree( Sample.tree );
    Sample.tree->SetBranchStatus("*", 1);

    string lastFileName = "";

    Long64_t nentries =  Sample.tree->GetEntries();
    Long64_t maxloop = min(nentries, nevents);

    int counter = 0;
    double EventsIsPSeudoData ;
    int cutPassCounter = 0;
    for (Long64_t jentry=0; jentry<maxloop;jentry++, counter++) {
      Sample.tree->GetEntry(jentry);
      // //cout << fTree.Event_EventNumber << endl;
      // if(  !(fTree.Event_EventNumber == 11112683 || fTree.Event_EventNumber == 11112881 ) ){
      // 	//cout << " " ;
      // 	continue;
      // }
      // else{
      // 	cutPassCounter ++ ;
      // 	cout << cutPassCounter << " : " << fTree.Event_EventNumber << " : " << endl;
      // }
      EventsIsPSeudoData = PSeudoDataRandom->Uniform();

      if( lastFileName.compare( ((TChain*)Sample.tree)->GetFile()->GetName() ) != 0 ) {
	for(auto prop : allProps)
	  prop->SetTree( Sample.tree , Sample.type, Sample.sname );
	for(auto prop2 : JbJOptimizationProps ) 
	  prop2->SetTree( Sample.tree , Sample.type, Sample.sname );

	nextcut.Reset();
	while( objcut = nextcut() ){
	  ExtendedCut* thecut = (ExtendedCut*)objcut ;
	  thecut->SetTree( Sample.tree ,  Sample.name , Sample.sname , Sample.type , Sample.xsection, Sample.nevents, Sample.kfact , Sample.PU_avg_weight);
	}

	lastFileName = ((TChain*)Sample.tree)->GetFile()->GetName() ;
	cout << "new file : " << lastFileName << endl;
      }

      if ( counter == 100000 ){  
	fprintf(stdout, "\rProcessed events: %6d of %6d ", jentry + 1, nentries);
	fflush(stdout);
	counter = 0;
      }
 
      nextcut.Reset();
      double weight = Weight;

      if( !data ){
	weight *= fTree.Event_puWeight ;
      }

      if( Sample.UseLHEWeight ){
	//cout << "SIGNAL" << endl;
	weight *= fTree.Event_LHEWeightSign ;
	// if(fTree.Event_LHEWeightSign < 0.0)
	//   cout << fTree.Event_LHEWeightSign << endl;
      }

      #ifdef SingleTopTreeLHEWeights_h
      for( int i = 0 ; i < 102 ; i++ ){
	CurrentPDFWeights[i] = fTree.GetPDFWeight(i)/fabs(fTree.Event_LHEWeight) ;
	ScalesPDF[i] += CurrentPDFWeights[i] ;
      }

      if( Sample.name == "WJets" || Sample.name == "Signal" ){

	
	if(fTree.GetLHEWeight(0) != fTree.Event_LHEWeight0) cout << "Wrong GetLHEWeight(0) Value" << endl;
	if(fTree.GetLHEWeight(1) != fTree.Event_LHEWeight1) cout << "Wrong GetLHEWeight(1) Value" << endl;
	if(fTree.GetLHEWeight(2) != fTree.Event_LHEWeight2) cout << "Wrong GetLHEWeight(2) Value" << endl;
	if(fTree.GetLHEWeight(3) != fTree.Event_LHEWeight3) cout << "Wrong GetLHEWeight(3) Value" << endl;
	if(fTree.GetLHEWeight(4) != fTree.Event_LHEWeight4) cout << "Wrong GetLHEWeight(4) Value" << endl;
	if(fTree.GetLHEWeight(5) != fTree.Event_LHEWeight5) cout << "Wrong GetLHEWeight(5) Value" << endl;
	if(fTree.GetLHEWeight(6) != fTree.Event_LHEWeight6) cout << "Wrong GetLHEWeight(6) Value" << endl;
	if(fTree.GetLHEWeight(7) != fTree.Event_LHEWeight7) cout << "Wrong GetLHEWeight(7) Value" << endl;
	if(fTree.GetLHEWeight(8) != fTree.Event_LHEWeight8) cout << "Wrong GetLHEWeight(8) Value" << endl;
	
	// CurrentLHEWeights[0] = fTree.Event_LHEWeight /fabs(fTree.Event_LHEWeight) ;
	// CurrentLHEWeights[1] = fTree.Event_LHEWeight1/fabs(fTree.Event_LHEWeight) ;
	// CurrentLHEWeights[2] = fTree.Event_LHEWeight2/fabs(fTree.Event_LHEWeight) ;
	// CurrentLHEWeights[3] = fTree.Event_LHEWeight3/fabs(fTree.Event_LHEWeight) ;
	// CurrentLHEWeights[4] = fTree.Event_LHEWeight4/fabs(fTree.Event_LHEWeight) ;
	// CurrentLHEWeights[5] = fTree.Event_LHEWeight5/fabs(fTree.Event_LHEWeight) ;
	// CurrentLHEWeights[6] = fTree.Event_LHEWeight6/fabs(fTree.Event_LHEWeight) ;
	// CurrentLHEWeights[7] = fTree.Event_LHEWeight7/fabs(fTree.Event_LHEWeight) ;
	// CurrentLHEWeights[8] = fTree.Event_LHEWeight8/fabs(fTree.Event_LHEWeight) ;
	
	for(int i = 0 ; i<9 ;i++){
	  CurrentLHEWeights[i] = fTree.GetLHEWeight(i)/fabs(fTree.Event_LHEWeight) ;
	  WScalesTotal[i] += CurrentLHEWeights[i];
	}
      }
      #endif
      
      double cutindex = 0.5;
      bool pass=true;
      while( objcut = nextcut() ){
	ExtendedCut* thecut = (ExtendedCut*)objcut ;
	pass &= thecut->Pass(jentry , weight);
	if(! pass ){
	  break;
	}else{
	  if( isfinite (weight) ){
	    cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
	    cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
	  }
	  else
	    cout << "non-finite weight : " << weight << endl;
	}
	cutindex+=1.0;
      }

      if(! pass)
	continue;

      int cut = 0;

      //cout << alllabels[ int(cutindex) ] << endl;
//       cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
//       cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
//       cutindex ++ ;

      // if( data && !(fTree.Event_passesHLT_IsoMu20_eta2p1_v2 > 0.5) )
      // 	continue;
      
      // if( !data && !(fTree.Event_passesHLT_IsoMu20_eta2p1_v1 > 0.5) )
      // 	continue;

      nPVBeforeCutsUnCorr.Fill( fTree.Event_nPV , weight/fTree.Event_puWeight , false , true );
      nPVBeforeCuts.Fill( fTree.Event_nPV , weight , false, true);

      // if( printEventIds )
      // 	(*(EventIdFiles[cutindex])) << fTree.Event_EventNumber << endl; 
      // cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
      // cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
      // cutindex ++ ;
      
      if( data && !(fTree.Event_passesHLT_IsoMu20_v2 > 0.5 || fTree.Event_passesHLT_IsoMu20_v1 > 0.5 || fTree.Event_passesHLT_IsoMu20_v3 > 0.5)  )
	continue;
      if(!data && !(fTree.Event_passesHLT_IsoMu20_v1 > 0.5) )
	continue;

      if( printEventIds )
	(*(EventIdFiles[cutindex])) << fTree.Event_EventNumber << endl;
      cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
      cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
      cutindex ++ ;
      

      //cout << "nMuons : " << fTree.muons_size << endl;
      int tightMuIndex =-1;
      int nonTightMuIndex = -1;
      int nLooseMuos   = 0;
      int nTightMuons = 0;
      int nTightNonIsoMuons = 0;

      for( int imu=0 ; imu < fTree.muons_size ; imu++ ){
	// cout << imu << " : " << fTree.muons_Pt[imu] << "-" << fTree.muons_Eta[imu] << "-"
	//      << fTree.muons_IsTightMuon[imu] << "-" << fTree.muons_Iso04[imu] << endl;
	
	bool isTight = false;
      	if( fTree.muons_Pt[imu] > 22.0 &&
	    fabs(fTree.muons_Eta[imu]) < 2.1 &&
	    fTree.muons_IsTightMuon[imu] > 0.5 ){


	  if( fTree.muons_Iso04[imu] < 0.06 ){ 
	    isTight = true;
	    nTightMuons ++;
	    if( tightMuIndex == -1 )
	      tightMuIndex = imu;
	  }else if( fTree.muons_Iso04[imu] < 0.15 ){
	    nTightNonIsoMuons ++;
	    if( nonTightMuIndex == -1 )
	      nonTightMuIndex = imu;
	  }
	}

	if( ! isTight )
	  if( fTree.muons_Pt[ imu ] > 10.0 &&
	      fTree.muons_IsLooseMuon[ imu ] > 0.5 &&
	      fabs(fTree.muons_Eta[imu]) < 2.5 && 
	      fTree.muons_Iso04[imu] < 0.20 ){
	    nLooseMuos++;
	  }
      }      

      if(IsQCD){
	nLooseMuos = nTightMuons ;	
	nTightMuons = nTightNonIsoMuons ;
	tightMuIndex = nonTightMuIndex ;
      }


      if( nTightMuons != 1 )
	  continue;

      bool isiso = true;

      if( nLooseMuos > 0 )
      	continue;

#ifdef MUONCHARGEP
      if(fTree.muons_Charge[tightMuIndex] < 0)
	continue;
#endif
#ifdef MUONCHARGEN
      if(fTree.muons_Charge[tightMuIndex] > 0)
	continue;
#endif

      // if( printEventIds )
      // 	(*(EventIdFiles[cutindex])) << (fTree.Event_EventNumber) << endl ;
      // cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
      // cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
      // cutindex ++ ;

      int nLooseElectrons = 0;
      for( int iele = 0 ; iele < fTree.electrons_size;iele ++ ){
      	if( fTree.electrons_Pt[iele] > 20 &&
	    fabs(fTree.electrons_Eta[iele]) < 2.5 && 
	    ( fabs(fTree.electrons_Eta[iele]) < 1.4442 || fabs(fTree.electrons_Eta[iele]) > 1.566) &&
	    fTree.electrons_vidVeto[iele] > 0.5 )
	  nLooseElectrons++;
      }
      
      if( nLooseElectrons > 0 )
      	continue;

      if( printEventIds )
	(*(EventIdFiles[cutindex])) << (fTree.Event_EventNumber) << endl ;
      cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
      cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
      cutindex ++ ;

      int j1index = -1;
      int j2index = -1;
      int j3index = -1;
      int nJets = 0 ;
      int howManyBJets = 0;
      int bjIndex = -1;
      int bj2Index = -1;
      int jprimeIndex ; 

      int nJetsPt20_47 = 0;

      int nJetsPt20_24 = 0;
      int nLbJetsPt20 = 0;
      int nTbJetsPt20 = 0;

      TLorentzVector muon;
      muon.SetPtEtaPhiE( fTree.muons_Pt[tightMuIndex] , fTree.muons_Eta[tightMuIndex] , fTree.muons_Phi[tightMuIndex] , fTree.muons_E[tightMuIndex] );
      if( muon.Energy() == 0.0 )
	cout << "ZERO???" <<endl;
      for( int jid = 0 ; jid < fTree.jetsAK4_size ; jid++ ){

	float NHF = fTree.jetsAK4_JetID_neutralHadronEnergyFraction[jid] ;
	float NEMF = fTree.jetsAK4_JetID_neutralEmEnergyFraction[jid] ;
	float NumConst = fTree.jetsAK4_JetID_numberOfDaughters[jid] ;
	float eta = fTree.jetsAK4_Eta[jid] ;
	float CHF = fTree.jetsAK4_JetID_chargedHadronEnergyFraction[jid] ;
	float CHM = fTree.jetsAK4_JetID_chargedMultiplicity[jid] ;
	float CEMF = fTree.jetsAK4_JetID_chargedEmEnergyFraction[jid] ;
	float NumNeutralParticle = fTree.jetsAK4_JetID_neutralMultiplicity[jid] ;


	bool looseid ;
	if(  abs(eta)<=3.0 ) {
	  looseid = (NHF<0.99 && NEMF<0.99 && NumConst>1) && ((abs(eta)<=2.4 && CHF>0 && CHM>0 && CEMF<0.99) || abs(eta)>2.4) ;
	}
	else
	  looseid = (NEMF<0.90 && NumNeutralParticle>10) ;

      	if( fTree.jetsAK4_CorrPt[jid] > 20 &&
	    fabs( fTree.jetsAK4_Eta[jid] ) < 4.7 &&
	    looseid
	    ){
	  TLorentzVector jet;
	  jet.SetPtEtaPhiE( fTree.jetsAK4_CorrPt[jid] , fTree.jetsAK4_Eta[jid] , fTree.jetsAK4_Phi[jid] , fTree.jetsAK4_CorrE[jid] );
	  double DR = muon.DeltaR( jet );

	  if ( DR > 0.3 ){

	    if( fTree.jetsAK4_CorrPt[jid] <= 40 ){
	      nJetsPt20_47 ++ ;
	      if( fabs( fTree.jetsAK4_Eta[jid] ) < 2.4 ){
		nJetsPt20_24 ++;
		if( fTree.jetsAK4_CSV[jid] > 0.97 )
		  nTbJetsPt20++;
		else if( fTree.jetsAK4_CSV[jid] > 0.605 )
		  nLbJetsPt20++;
	      }
	      
	      continue;
	    }	    
	    nJets++;
	    if( nJets == 1 )
	      j1index = jid ;
	    else if(nJets == 2 )
	      j2index = jid ;
	    else if( nJets == 3 )
	      j3index = jid ;
	    
	    if( fTree.jetsAK4_IsCSVT[jid] == true  && fabs( fTree.jetsAK4_Eta[jid] ) <= 2.4 ){
	      howManyBJets ++;
	      if(howManyBJets==1)
		bjIndex = jid ;
	      else if(howManyBJets==2)
		bj2Index = jid ;
	    }else
	      jprimeIndex = jid ;
	  }
	}
      }
      
      nJetsBeforeCut.Fill( nJets , weight , EventsIsPSeudoData < fabs(weight) , isiso );
      if (nJets != NUMBEROFJETS)
	continue;


      if( printEventIds )
	(*(EventIdFiles[cutindex])) << (fTree.Event_EventNumber) << endl ;
      cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
      cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
      cutindex ++ ;
      
      nbJets.Fill( howManyBJets , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      if( howManyBJets != NUMBEROFBJETS )
	continue;

      if( !data ){
	if( NUMBEROFBJETS == 2 )
	  weight *= fTree.Event_bWeight2CSVT ;
	else if (NUMBEROFBJETS == 1 )
	  weight *= fTree.Event_bWeight1CSVT ;
      }

      //weight = 1.0;

      if( printEventIds )
	(*(EventIdFiles[cutindex])) << (fTree.Event_EventNumber) << endl ;
      cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
      cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
      cutindex ++ ;

     
      double MT = sqrt( 2*fTree.met_Pt* fTree.muons_Pt[tightMuIndex]*(1-TMath::Cos( Util::DeltaPhi(fTree.met_Phi , fTree.muons_Phi[tightMuIndex]) ) )  ) ;
      MTBeforeCut.Fill( MT , weight , EventsIsPSeudoData < fabs(weight) , isiso );
      // if( fTree.met_Pt < 45 )
      // 	continue;
      if( MT < 50 && (NUMBEROFBJETS == 1 && NUMBEROFJETS == 2) && !IsQCD )
      	continue;

      if( printEventIds )
	(*(EventIdFiles[cutindex])) << (fTree.Event_EventNumber) << endl ;
     
      cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
      cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
      cutindex ++ ;

      nonbCSV.Fill( fTree.jetsAK4_CSV[jprimeIndex] , weight , EventsIsPSeudoData < fabs(weight) , isiso);

//       if( fTree.jetsAK4_CSV[jprimeIndex] > 0.605 )
// 	continue;

      // if( printEventIds )
      // 	(*(EventIdFiles[cutindex])) << (fTree.Event_EventNumber) << endl ;
      // cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
      // cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
      // cutindex ++ ;

      nJets20_47.Fill( nJetsPt20_47 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      nJets20_24.Fill( nJetsPt20_24 , weight , EventsIsPSeudoData < fabs(weight) , isiso);

      if(nJetsPt20_24 < 2){
	nLbjets1EJ24.Fill( nLbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	nTbjets1EJ24.Fill( nTbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }
      if(nJetsPt20_24 < 3){
	nLbjets2EJ24.Fill( nLbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	nTbjets2EJ24.Fill( nTbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }
      if(nJetsPt20_24 < 4){
	nLbjets3EJ24.Fill( nLbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	nTbjets3EJ24.Fill( nTbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }
      if(nJetsPt20_24 < 5){
	nLbjets4EJ24.Fill( nLbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	nTbjets4EJ24.Fill( nTbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }

      if(nJetsPt20_47 < 2){
	nLbjets1EJ47.Fill( nLbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	nTbjets1EJ47.Fill( nTbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }
      if(nJetsPt20_47 < 3){
	nLbjets2EJ47.Fill( nLbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	nTbjets2EJ47.Fill( nTbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }
      if(nJetsPt20_47 < 4){
	nLbjets3EJ47.Fill( nLbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	nTbjets3EJ47.Fill( nTbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }
      if(nJetsPt20_47 < 5){
	nLbjets4EJ47.Fill( nLbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	nTbjets4EJ47.Fill( nTbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }


      if( NUMBEROFBJETS == 2 )
	if( fTree.jetsAK4_CSV[bj2Index] > fTree.jetsAK4_CSV[bjIndex] )
	  std::swap( bj2Index , bjIndex );

      //int jprimeIndex = (bjIndex == j1index) ? j2index : j1index ;
      TLorentzVector muLV;
      muLV.SetPtEtaPhiE( fTree.muons_Pt[tightMuIndex] , fTree.muons_Eta[tightMuIndex] , fTree.muons_Phi[ tightMuIndex ] , fTree.muons_E[tightMuIndex] );
      TLorentzVector bjetLV;
      bjetLV.SetPtEtaPhiE( fTree.jetsAK4_CorrPt[ bjIndex ] , fTree.jetsAK4_Eta[ bjIndex ] , fTree.jetsAK4_Phi[ bjIndex ] , fTree.jetsAK4_CorrE[ bjIndex ] ) ; 
      double topMass = topUtils.top4Momentum( muLV , bjetLV , fTree.met_Px , fTree.met_Py ).mass();
      TopMass.Fill( topMass , weight , EventsIsPSeudoData < fabs(weight) , isiso ); //fTree.resolvedTopSemiLep_Mass[0]

      MT_QCD_Tree = MT;
      TOPMASS_QCD_Tree = topMass ;
      MuIso_QCD_Tree = fTree.muons_Iso04[tightMuIndex];
      Weight_QCD_Tree = weight ;

      if( IsQCD )
	theQCD_Tree->Fill();



      if( (130. < topMass && topMass < 225.) || NUMBEROFBJETS == 2 ){

	nPVAfterCutsUnCorr.Fill( fTree.Event_nPV , weight/fTree.Event_puWeight , EventsIsPSeudoData < fabs(weight) , isiso );
	nPVAfterCuts.Fill( fTree.Event_nPV , weight , EventsIsPSeudoData < fabs(weight) , isiso );

#ifdef SingleTopTreeLHEWeights_h
	for(int i = 0 ; i< 102 ; i++){
	  hEtajPDFScales[i]->Fill( fabs( fTree.jetsAK4_Eta[jprimeIndex] ) , weight*fabs( CurrentPDFWeights[i] ) );
	}
	if( Sample.name == "WJets" || Sample.name == "Signal"){
	  for(int i=0;i<9;i++)
	    hEtajWScales[i]->Fill( fabs( fTree.jetsAK4_Eta[jprimeIndex] ) , weight*fabs( CurrentLHEWeights[i] ) );
	}
#endif
	
	jprimeEta.Fill( fabs( fTree.jetsAK4_Eta[jprimeIndex] ) , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	jprimePt.Fill( fTree.jetsAK4_CorrPt[jprimeIndex] , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	muPtOneB.Fill( fTree.muons_Pt[tightMuIndex] , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	muCharge.Fill( fTree.muons_Charge[tightMuIndex] , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	muEtaOneB.Fill( fabs(fTree.muons_Eta[tightMuIndex]) , weight , EventsIsPSeudoData < fabs(weight), isiso );
	METOneBSR.Fill(  fTree.met_Pt , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	bPtOneB.Fill( fTree.jetsAK4_CorrPt[bjIndex] , weight , EventsIsPSeudoData < fabs(weight), isiso );
	bEtaOneB.Fill(fabs( fTree.jetsAK4_Eta[bjIndex] ) , weight , EventsIsPSeudoData < fabs(weight), isiso );

	if( printEventIds )
	  (*(EventIdFiles[cutindex])) << (fTree.Event_EventNumber) << endl ;
	cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
	cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
	cutindex++;
      }else{
	jprimeEtaSB.Fill( fabs( fTree.jetsAK4_Eta[jprimeIndex] ) , weight , EventsIsPSeudoData < fabs(weight) , isiso );
	METOneBSB.Fill(  fTree.met_Pt , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }

      METOneBAll.Fill(  fTree.met_Pt , weight , EventsIsPSeudoData < fabs(weight) , isiso);

      if(Sample.name == "Signal" )
	hTopMass->Fill( topMass , weight );
      if(Sample.name == "WJets")
	hTopMassEtaJ->Fill( topMass ,fabs( fTree.jetsAK4_Eta[jprimeIndex] )  );
    }
    theQCD_Tree->Write();
    
  }

  theTreeFile->Close();
      

  // TString fileName = fOutputDir;
  // if(!fileName.EndsWith("/")) fileName += "/";
  // Util::MakeOutputDir(fileName);
  fileName += myfileName + ".root" ;

  TFile *theFile = new TFile(fileName.Data(), "RECREATE");

  nonbCSV.CalcSig( 0 , 0 , -1 , 0 ) ; 
  nonbCSV.CalcSig( 0 , 4 , -1 , 0.1); 
  nonbCSV.CalcSig( 0 , 2 , -1 , 0 ) ; 

  nJets20_24.CalcSig( 0 , 0 , -1 , 0 ) ; 
  nJets20_24.CalcSig( 0 , 4 , -1 , 0.1 ) ; 
  nJets20_24.CalcSig( 0 , 2 , -1 , 0 ) ; 
  nJets20_47.CalcSig( 0 , 0 , -1 , 0 ) ; 
  nJets20_47.CalcSig( 0 , 4 , -1 , 0.1 ) ; 
  nJets20_47.CalcSig( 0 , 2 , -1 , 0 ) ; 

  muCharge.CalcSig( 0 , 0 , -1 , 0 ) ; 
  muCharge.CalcSig( 0 , 4 , -1 , 0.1 ) ; 
  muCharge.CalcSig( 0 , 2 , -1 , 0 ) ; 
  muCharge.CalcSig( 1 , 0 , -1 , 0 ) ; 
  muCharge.CalcSig( 1 , 4 , -1 , 0.1 ) ; 
  muCharge.CalcSig( 1 , 2 , -1 , 0 ) ; 

  for(auto prop : allProps)
    prop->Write( theFile , 1000  );

#ifdef SingleTopTreeLHEWeights_h
  TDirectory* dirWScales = theFile->mkdir("WJScales");
  dirWScales->cd();
  for(int i=0;i<9;i++){
    cout << "WScalesTotal[i]" << WScalesTotal[i] << "," << WScalesTotal[0]/WScalesTotal[i] << endl;
    hEtajWScales[i]->Scale( WScalesTotal[0]/WScalesTotal[i] );
    hEtajWScales[i]->Write();
  }

  TDirectory* dirPDFScales = theFile->mkdir("PDFScales");
  dirPDFScales->cd();
  for(int i=0;i<102;i++){
    cout << "PDFScales[i]" << ScalesPDF[i] << "," << WScalesTotal[0]/ScalesPDF[i] << endl;
    hEtajPDFScales[i]->Scale( WScalesTotal[0]/ScalesPDF[i] );
    hEtajPDFScales[i]->Write();
  }
#endif

  TDirectory* dir2 = theFile->mkdir("JbJOptimizationProps");
  dir2->cd();

  for(auto prop2 : JbJOptimizationProps){
    prop2->CalcSig( 0 , 0 , -1 , 0 ) ; 
    prop2->CalcSig( 0 , 4 , -1 , 0.1 ) ; 
    prop2->CalcSig( 0 , 2 , -1 , 0 ) ; 
    prop2->Write( dir2 , 1000  );
  }

  theFile->cd();
  hTopMass->Write();
  hTopMassEtaJ->Write();
  //cutflowtable.Print("cutflowtable");
  theFile->Close();
  if( printEventIds )
    for( auto a : EventIdFiles ){
      a->close();
    }
}
void MakeHist(TString infilename = "Graviton_genlevel_3000.root")
{
	TChain * chain = new TChain("demo/ExTree");
	chain->Add(infilename);


	vector<const reco::Candidate *> *phig;
	vector<const reco::Candidate *> *pmu;
	vector<const reco::Candidate *> *pele;
	vector<const reco::Candidate *> *pjet;
	vector<const reco::Candidate *> *pnu;
	vector<const reco::Candidate *> *pwplus;
	vector<const reco::Candidate *> *pwminus;
	chain-> SetBranchAddress("phig", &phig);
	chain-> SetBranchAddress("pmu", &pmu);
	chain-> SetBranchAddress("pele", &pele);
	chain-> SetBranchAddress("pjet", &pjet);
	chain-> SetBranchAddress("pnu", &pnu);
	chain-> SetBranchAddress("pwplus", &pwplus);
	chain-> SetBranchAddress("pwminus", &pwminus);

	//---------------------------------get  hist-----------------------------------------------
	//const float normal = 1000;// number of entries normalize to 1000

	//eta bin
	float inix= -2.5;
	float finx= 2.5;
	float nbinx= 20.0; 
	//pt bin
	float iniy= 0.0;
	float finy= 100.0;
	float nbiny= 20.0; 


	TH2F *h1= new TH2F("h1","h1",nbinx,inix,finx,nbiny,iniy,finy);
	h1->Sumw2();


	int nbins_lvjj      = 300;
	int masswindow_low  = 200;
	int masswindow_high = 4000;

	//histograms for differeny methods
	TH1F * hlvjj0 = new TH1F ("hlvjj0","hlvjj",nbins_lvjj,masswindow_low,masswindow_high);
	TH1F * hlvjj1 = new TH1F ("hlvjj1","hlvjj",nbins_lvjj,masswindow_low,masswindow_high);
	TH1F * hlvjj2 = new TH1F ("hlvjj2","hlvjj",nbins_lvjj,masswindow_low,masswindow_high);
	TH1F * hlvjj2_1 = new TH1F ("hlvjj2_1","hlvjj",nbins_lvjj,masswindow_low,masswindow_high);
	TH1F * hlvjj3 = new TH1F ("hlvjj3","hlvjj",nbins_lvjj,masswindow_low,masswindow_high);
	TH1F * hlvjj4 = new TH1F ("hlvjj4","hlvjj",nbins_lvjj,masswindow_low,masswindow_high);
	TH1F * hlvjj5 = new TH1F ("hlvjj5","hlvjj",nbins_lvjj,masswindow_low,masswindow_high);
	TH1F * hlvjj5_1 = new TH1F ("hlvjj5_1","hlvjj",nbins_lvjj,masswindow_low,masswindow_high);
	TH1F * hlvjj5_2 = new TH1F ("hlvjj5_2","hlvjj",nbins_lvjj,masswindow_low,masswindow_high);
	TH1F * hlvjj6 = new TH1F ("hlvjj6","hlvjj",nbins_lvjj,masswindow_low,masswindow_high);

	TH2F * h2= new TH2F("h2","h2",100,0,200,100,0,200); // for wlv and wjj
	TH2F * h3= new TH2F("h3","h3",5,0,200,5,0,200); // for percentage

	TH2F * hjjpt = new TH2F("hjjpt","hjjpt",10,0,1000,10,0,1000);
	TH2F * hlvpt = new TH2F("hlvpt","hlvpt",10,0,1000,10,0,1000);

	TH1F * hwlv = new TH1F("hwlv","hwlv",100,0,200);

	TH1F * hleppz_all = new TH1F("hleppz_all","hleppz_all",100,0,80);
	TH1F * hleppz_low = new TH1F("hleppz_low","hleppz_low",100,0,80);

	TH2F * hlvpz = new TH2F("hlvpz","hlvpz",10,0,1000,10,0,1000);

	double xbins[4] = {0,65,95,200};
	double ybins[4] = {0,65,95,200};
	h3->GetXaxis()->Set(3,xbins);
	h3->GetYaxis()->Set(3,ybins);


	//comparison hists
	TH1F * pz_comparison1 = new TH1F("pz_comparison1","pz_comparison",200,-1,1);
	TH1F * pz_comparison2 = new TH1F("pz_comparison2","pz_comparison",200,-1,1);
	TH1F * pz_comparison2_1 = new TH1F("pz_comparison2_1","pz_comparison",200,-1,1);
	TH1F * pz_comparison3 = new TH1F("pz_comparison3","pz_comparison",200,-1,1);
	TH1F * pz_comparison4 = new TH1F("pz_comparison4","pz_comparison",200,-1,1);
	TH1F * pz_comparison5 = new TH1F("pz_comparison5","pz_comparison",200,-1,1);
	TH1F * pz_comparison5_2 = new TH1F("pz_comparison5_2","pz_comparison",200,-1,1);
	TH1F * pz_comparison5_1 = new TH1F("pz_comparison5_1","pz_comparison",200,-1,1);
	TH1F * pz_comparison6 = new TH1F("pz_comparison6","pz_comparison",200,-1,1);
	TH1F * lvjj_comparison1 = new TH1F("lvjj_comparison1","lvjj_comparison",200,-1,1);
	TH1F * lvjj_comparison2 = new TH1F("lvjj_comparison2","lvjj_comparison",200,-1,1);
	TH1F * lvjj_comparison2_1 = new TH1F("lvjj_comparison2_1","lvjj_comparison",200,-1,1);
	TH1F * lvjj_comparison3 = new TH1F("lvjj_comparison3","lvjj_comparison",200,-1,1);
	TH1F * lvjj_comparison4 = new TH1F("lvjj_comparison4","lvjj_comparison",200,-1,1);
	TH1F * lvjj_comparison5 = new TH1F("lvjj_comparison5","lvjj_comparison",200,-1,1);
	TH1F * lvjj_comparison5_1 = new TH1F("lvjj_comparison5_1","lvjj_comparison",200,-1,1);
	TH1F * lvjj_comparison5_2 = new TH1F("lvjj_comparison5_2","lvjj_comparison",200,-1,1);
	TH1F * lvjj_comparison6 = new TH1F("lvjj_comparison6","lvjj_comparison",200,-1,1); 

	TCanvas * c1 = new TCanvas();	

	TLorentzVector lep;
	TLorentzVector jet1;
	TLorentzVector jet2;
	TLorentzVector neu;
	TLorentzVector temp;

	double mlvjj;
	double lvjjmass_true;
	cout<<chain->GetEntries()<<endl;
	for(int i=0; i<chain->GetEntries(); i++)
	{
		//if(i>5000)break;//for test
		if(i%5000==0)cout<<"Processing the events: "<<i<<endl;
		chain->GetEntry(i);
		//higgs 2D
		//h1->Fill(phig->at(0)->eta(),phig->at(0)->pt(),normal/(float)chain->GetEntries());

		//------------------------------neutrino pz
		if(!pmu->empty())lep.SetPtEtaPhiE(pmu->at(0)->pt(), pmu->at(0)->eta(),pmu->at(0)->phi(),pmu->at(0)->energy());
		else if(!pele->empty())lep.SetPtEtaPhiE(pele->at(0)->pt(), pele->at(0)->eta(),pele->at(0)->phi(),pele->at(0)->energy());
		else {
				cout<<"skip event: "<<i<<"  no lepton here"<<endl;
				//cout<<phig->size()<<endl;
				continue;
			}
		if(pjet->size()!=2)
		{
			cout<<"skip event: "<<i<<" jet sise != 2 "<<endl;
			continue;
		}
		jet1.SetPtEtaPhiE(pjet->at(0)->pt(), pjet->at(0)->eta(),pjet->at(0)->phi(),pjet->at(0)->energy());
		jet2.SetPtEtaPhiE(pjet->at(1)->pt(), pjet->at(1)->eta(),pjet->at(1)->phi(),pjet->at(1)->energy());
		if(jet1.Pt()<jet2.Pt())
		{
			temp=jet1;
			jet1=jet2;
			jet2=temp;
		}
		neu.SetPxPyPzE(pnu->at(0)->px(), pnu->at(0)->py(),pnu->at(0)->pz(),pnu->at(0)->energy());//real neutrino
		double px = pnu->at(0)->px();
		double py = pnu->at(0)->py();
		double pz=0;


		// ------------------------------- make cuts----------------------------
		//mt
		//double mt = sqrt(2. * lep.Pt() * neu.Pt() * ( 1 - cos(deltaPhi(lep.Phi(), neu.Phi()) ) ) );
		//if(mt>20)continue;

		//lepton pt,eta
		if(lep.Pt()<50)continue;
		//if(!pmu->empty()&&pmu->at(0)->pt()<24)continue;
		//if(!pele->empty()&&pele->at(0)->pt()<27)continue;
		//if(lep.Eta()>2.5)continue;

		//jet pt,eta
		if(jet1.Pt()<50)continue;
		//if(jet1.Eta()>2.4)continue;
		if(jet2.Pt()<50)continue;
		//if(jet2.Eta()>2.4)continue;

		//met or neutrino pt
		//double met = sqrt(px*px+py*py);
		if(neu.Pt()<50)continue;

		//mjj
		//double mjj = (jet1+jet2).M();
		//if(mjj>95||mjj<65)continue; //wjj on
		//if(mjj<95&&mjj>65)continue;   //wjj off


		// 0---------direct method
		pz = pnu->at(0)->pz();
		temp.SetPxPyPzE(px,py,pz,sqrt(px*px+py*py+pz*pz));
		mlvjj = (lep + jet1 + jet2 + temp).M();
		if (mlvjj>masswindow_low&&mlvjj<masswindow_high)hlvjj0->Fill(mlvjj);
		lvjjmass_true = mlvjj;

/*
		// 1----------nu pz = 0
		pz = 0;
		temp.SetPxPyPzE(px,py,pz,sqrt(px*px+py*py+pz*pz));
		mlvjj = (lep + jet1 + jet2 + temp).M();
		if (mlvjj>masswindow_low&&mlvjj<masswindow_high)hlvjj1->Fill(mlvjj);
        pz_comparison1->Fill((pz-pnu->at(0)->pz())/pnu->at(0)->pz());
        lvjj_comparison1->Fill((mlvjj-lvjjmass_true)/lvjjmass_true);

		// 2----------nu pz = lep pz
		pz=lep.Pz();
		temp.SetPxPyPzE(px,py,pz,sqrt(px*px+py*py+pz*pz));
		mlvjj = (lep + jet1 + jet2 + temp).M();
		if (mlvjj>masswindow_low&&mlvjj<masswindow_high)hlvjj2->Fill(mlvjj);
        pz_comparison2->Fill((pz-pnu->at(0)->pz())/pnu->at(0)->pz());
        lvjj_comparison2->Fill((mlvjj-lvjjmass_true)/lvjjmass_true);

		//--check pz
		//hleppz_all->Fill(pz);
		//if(mlvjj>130)continue;
		//hleppz_low->Fill(pz);

		//2_1 ---------nu pz =lep pz -x 
		pz=lep.Pz();
		int pz_correct=20;
		if(pz>pz_correct)pz=pz-pz_correct;
		if(pz<-pz_correct)pz=pz+pz_correct;
		temp.SetPxPyPzE(px,py,pz,sqrt(px*px+py*py+pz*pz));
		mlvjj = (lep + jet1 + jet2 + temp).M();
		if (mlvjj>masswindow_low&&mlvjj<masswindow_high)hlvjj2_1->Fill(mlvjj);
        pz_comparison2_1->Fill((pz-pnu->at(0)->pz())/pnu->at(0)->pz());
        lvjj_comparison2_1->Fill((mlvjj-lvjjmass_true)/lvjjmass_true);



		// 3----------nu pz = far jet pz----------------use theta to choose
		double angle1 = lep.Vect().Angle(jet1.Vect());
		double angle2 = lep.Vect().Angle(jet2.Vect());
		if(angle1>angle2)pz=jet1.Pz();
		else pz = jet2.Pz();
		temp.SetPxPyPzE(px,py,pz,sqrt(px*px+py*py+pz*pz));
		mlvjj = (lep + jet1 + jet2 + temp).M();
		if (mlvjj>masswindow_low&&mlvjj<masswindow_high)hlvjj3->Fill(mlvjj);
        pz_comparison3->Fill((pz-pnu->at(0)->pz())/pnu->at(0)->pz());
        lvjj_comparison3->Fill((mlvjj-lvjjmass_true)/lvjjmass_true);



		//4 ---------nu pz = far jet pz--------------------use DetaR to choose
		double dR1 = deltaR(lep.Eta(),lep.Phi(),jet1.Eta(),jet1.Phi());
		double dR2 = deltaR(lep.Eta(),lep.Phi(),jet2.Eta(),jet2.Phi());
		if(dR1>dR2)pz=jet1.Pz();
		else pz = jet2.Pz();
		temp.SetPxPyPzE(px,py,pz,sqrt(px*px+py*py+pz*pz));
		mlvjj = (lep + jet1 + jet2 + temp).M();
		if (mlvjj>masswindow_low&&mlvjj<masswindow_high)hlvjj4->Fill(mlvjj);
        pz_comparison4->Fill((pz-pnu->at(0)->pz())/pnu->at(0)->pz());
        lvjj_comparison4->Fill((mlvjj-lvjjmass_true)/lvjjmass_true);

*/
		// 5 ---------------------slove the function ------------milano

		float alpha = lep.Px()*pnu->at(0)->px() + lep.Py()*pnu->at(0)->py();

		float delta = (alpha + 0.5*80.399*80.399)*(alpha + 0.5*80.399*80.399) - lep.Pt()*lep.Pt()*pnu->at(0)->pt()*pnu->at(0)->pt();
		if( delta < 0. ) {
			delta = 0.;
		}
			//double wlv = (lep+neu).M();
			//hwlv->Fill(wlv);
			//cout<<"event with imaginary roots :"<<i<<" mwlv is  "<<wlv<<endl;
		
		//else continue;//use only imaginary root

		float pz1 = ( lep.Pz()*(alpha + 0.5*80.399*80.399) + lep.Energy()*sqrt(delta) ) / lep.Pt() / lep.Pt();
		float pz2 = ( lep.Pz()*(alpha + 0.5*80.399*80.399) - lep.Energy()*sqrt(delta) ) / lep.Pt() / lep.Pt();

		if( delta >= 0. )//choose the larger pz
		{
			if(fabs(pz1)<fabs(pz2))pz=pz2;
			else pz=pz1;   
		}
		//else continue;//discard unreal pz
		temp.SetPxPyPzE(px,py,pz,sqrt(px*px+py*py+pz*pz));
		mlvjj = (lep + jet1 + jet2 + temp).M();
		if (mlvjj>masswindow_low&&mlvjj<masswindow_high)hlvjj5->Fill(mlvjj);
        pz_comparison5->Fill((pz-pnu->at(0)->pz())/pnu->at(0)->pz());
        lvjj_comparison5->Fill((mlvjj-lvjjmass_true)/lvjjmass_true);


		//4 choose the smaller pz
		if( delta >= 0. )
        {   
            if(fabs(pz1)>fabs(pz2))pz=pz2;
            else pz=pz1;   
        }
        temp.SetPxPyPzE(px,py,pz,sqrt(px*px+py*py+pz*pz));
        mlvjj = (lep + jet1 + jet2 + temp).M();
        if (mlvjj>masswindow_low&&mlvjj<masswindow_high)hlvjj4->Fill(mlvjj);
        pz_comparison4->Fill((pz-pnu->at(0)->pz())/pnu->at(0)->pz());
        lvjj_comparison4->Fill((mlvjj-lvjjmass_true)/lvjjmass_true);

		//3 choose the one closest to lep pz
		
		if(fabs(pz1-lep.Pz())>fabs(pz2-lep.Pz()))pz=pz2;
		else pz=pz1;
        temp.SetPxPyPzE(px,py,pz,sqrt(px*px+py*py+pz*pz));
        mlvjj = (lep + jet1 + jet2 + temp).M();
        if (mlvjj>masswindow_low&&mlvjj<masswindow_high)hlvjj3->Fill(mlvjj);
        pz_comparison3->Fill((pz-pnu->at(0)->pz())/pnu->at(0)->pz());
        lvjj_comparison3->Fill((mlvjj-lvjjmass_true)/lvjjmass_true);


		//2  feimilab ---- choose the one closest to lep pz, when it is over 300, choose the central one
		if(pz>300)
		{
			if(fabs(pz1)>fabs(pz2))pz=pz2;
			else pz=pz1;
		}
        temp.SetPxPyPzE(px,py,pz,sqrt(px*px+py*py+pz*pz));
        mlvjj = (lep + jet1 + jet2 + temp).M();
        if (mlvjj>masswindow_low&&mlvjj<masswindow_high)hlvjj2->Fill(mlvjj);
        pz_comparison2->Fill((pz-pnu->at(0)->pz())/pnu->at(0)->pz());
        lvjj_comparison2->Fill((mlvjj-lvjjmass_true)/lvjjmass_true);



/*		
		// 5_1 ---------------- Sara---if you have real roots, take the solutions where neutrino and charged lepton are the closest in DR.
		if( delta >= 0. )	
		{
			pz=pz1;
			temp.SetPxPyPzE(px,py,pz,sqrt(px*px+py*py+pz*pz));
			//cout<<temp.Phi()<<" "<<neu.Phi()<<endl;
			double dR1 = deltaR(lep.Eta(),lep.Phi(),temp.Eta(),temp.Phi());
			pz=pz2;
			temp.SetPxPyPzE(px,py,pz,sqrt(px*px+py*py+pz*pz));
			double dR2 = deltaR(lep.Eta(),lep.Phi(),temp.Eta(),temp.Phi());
			if(dR1>dR2)pz=pz2;
			else pz=pz1;
		}
		//else continue;//discard unreal pz
		temp.SetPxPyPzE(px,py,pz,sqrt(px*px+py*py+pz*pz));
		mlvjj = (lep + jet1 + jet2 + temp).M();
		if (mlvjj>masswindow_low&&mlvjj<masswindow_high)hlvjj5_1->Fill(mlvjj);
		pz_comparison5_1->Fill((pz-pnu->at(0)->pz())/pnu->at(0)->pz());
		lvjj_comparison5_1->Fill((mlvjj-lvjjmass_true)/lvjjmass_true);
*/

		//5_2 -------------------- another method to select right real root
			//use also delta = 0 in real root case
			//use +delta root
		pz=pz1;		
        temp.SetPxPyPzE(px,py,pz,sqrt(px*px+py*py+pz*pz));
        mlvjj = (lep + jet1 + jet2 + temp).M();
        if (mlvjj>masswindow_low&&mlvjj<masswindow_high)hlvjj5_2->Fill(mlvjj);
        pz_comparison5_2->Fill((pz-pnu->at(0)->pz())/pnu->at(0)->pz());
        lvjj_comparison5_2->Fill((mlvjj-lvjjmass_true)/lvjjmass_true);
		
/*
		// 6 --------------------- Fracesco----boost case lepton and neutrino are like parallel
		pz = neu.Pt()/lep.Pt()*lep.Pz();
		temp.SetPxPyPzE(px,py,pz,sqrt(px*px+py*py+pz*pz));
		mlvjj = (lep + jet1 + jet2 + temp).M();
		if (mlvjj>masswindow_low&&mlvjj<masswindow_high)hlvjj6->Fill(mlvjj);
        pz_comparison6->Fill((pz-pnu->at(0)->pz())/pnu->at(0)->pz());
        lvjj_comparison6->Fill((mlvjj-lvjjmass_true)/lvjjmass_true);

*/


		//------------------------------2D plots of Wjj and Wlv mass----------------------------------------
		//double wlv = (lep+neu).M();
		//double wjj = (jet1+jet2).M();

		//hwlv->Fill(wlv);

		//h2-> Fill(wlv,wjj);
		//h3-> Fill(wlv,wjj,1.0/(float)chain->GetEntries());
		//h3-> Fill(wlv,wjj);

		//hjjpt->Fill(jet1.Pt(),jet2.Pt());
		//hlvpt->Fill(lep.Pt(),neu.Pt());
		//hlvpz->Fill(abs(lep.Pz()),abs(neu.Pz()));

	}

/*
	h2-> GetXaxis()->SetTitle("wlv");
	h2-> GetYaxis()->SetTitle("wjj");

	h3-> GetXaxis()->SetTitle("wlv");
	h3-> GetYaxis()->SetTitle("wjj");
	h3->Draw("COLZ");
	h3->Draw("TEXTEsame");
	h3->SetStats(0);
	c1->Print("percent.png","png");
	//h1->Draw("SURF1");


	hjjpt-> GetXaxis()->SetTitle("leading jet pt");
	hjjpt-> GetYaxis()->SetTitle("jet2 pt");
	hlvpt-> GetXaxis()->SetTitle("lepton pt");
	hlvpt-> GetYaxis()->SetTitle("neotrino pt");
	hjjpt->Draw("COLZ");
	hjjpt->Draw("TEXTEsame");
	c1->Print("jjpt.png","png");
	hlvpt->Draw("COLZ");
	hlvpt->Draw("TEXTEsame");
	c1->Print("lvpt.png","png");


	hlvpz-> GetXaxis()->SetTitle("lepton pz");
	hlvpz-> GetYaxis()->SetTitle("neotrino pz");
	hlvpz->Draw("COLZ");
	hlvpz->Draw("TEXTEsame");
	c1->Print("lvpz.png","png");

*/

	hlvjj0->Draw();
	hlvjj0->SetTitle("lvjj_original");
	c1->Print("lvjj_original.png","png");

/*
	hlvjj1->Draw();
	hlvjj1->SetTitle("lvjj_pz0");
	c1->Print("lvjj_pz0.png","png");
*/
	hlvjj2->Draw();
	hlvjj2->SetTitle("lvjj_fermilab");
	c1->Print("lvjj_fermilab.png","png");

//	hlvjj2_1->Draw();
//	hlvjj2_1->SetTitle("lvjj_leptonpz_improve");
//	c1->Print("lvjj_leptonpz_improve.png","png");

	hlvjj3->Draw();
	hlvjj3->SetTitle("lvjj_close_to_lep_pz");
	c1->Print("lvjj_close_to_lep_pz.png","png");

	hlvjj4->Draw();
	//hlvjj4->SetTitle("lvjj_jetpz_DeltaR");
	//c1->Print("lvjj_jetpz_DeltaR.png","png");
	hlvjj4->SetTitle("lvjj_function_smaller");
	c1->Print("lvjj_function_smaller.png","png");

	hlvjj5->Draw();
	hlvjj5->SetTitle("lvjj_function_larger");
	c1->Print("lvjj_function_larger.png","png");

	hlvjj5_1->Draw();
	hlvjj5_1->SetTitle("lvjj_function_sara");
	c1->Print("lvjj_function_sara.png","png");

    hlvjj5_2->Draw();
    hlvjj5_2->SetTitle("lvjj_function_pz1");
    c1->Print("lvjj_function_pz1.png","png");


	hlvjj6->Draw();
	hlvjj6->SetTitle("lvjj_Francesco");
	c1->Print("lvjj_Francesco.png","png");

	//hwlv->Draw();
	//hwlv->SetTitle("hwlv");
	//c1->Print("hwlv.png","png");

	//hleppz_all->Draw();
	//c1->Print("hleppz_all.png","png");
	//hleppz_low->Draw();
	//c1->Print("hleppz_low.png","png");


	TLegend *leg = new TLegend(0.65, 0.5, 1, 1, NULL, "brNDC");
	/*
	leg->AddEntry (pz_comparison1,"neu pz = 0","l") ;
*/
	leg->AddEntry (pz_comparison2,"neu pz = fermilab","l") ;
//	leg->AddEntry (pz_comparison2_1,"neu pz = lep pz - 20","l") ;
	leg->AddEntry (pz_comparison3,"neu pz = close to lep pz","l") ;
	//leg->AddEntry (pz_comparison4,"neu pz = dltaR far jet pz","l") ;

	leg->AddEntry (pz_comparison4,"neu pz = slove function smaller","l");
	leg->AddEntry (pz_comparison5,"neu pz = slove function larger","l") ;
	//leg->AddEntry (pz_comparison5_1,"neu pz = slove function sara","l") ;
	leg->AddEntry (pz_comparison5_2,"neu pz = slove function +delta","l") ;
	//leg->AddEntry (pz_comparison6,"neu pz = Francesco","l") ;

/*
	pz_comparison1->SetLineColor(kYellow+3);
	pz_comparison1->Draw();
*/
    pz_comparison2->SetLineColor(kOrange+7);
    pz_comparison2->Draw();
//    pz_comparison2_1->SetLineColor(kGrey;
//    pz_comparison2_1->Draw("same");

    pz_comparison3->SetLineColor(kYellow-2);
    pz_comparison3->Draw("same");

    pz_comparison4->SetLineColor(kMagenta+1);
    pz_comparison4->Draw("same");
    pz_comparison5->SetLineColor(kBlue);
    pz_comparison5->Draw("same");
	pz_comparison5_1->SetLineColor(kSpring-7);
	pz_comparison5_1->Draw("same");
	pz_comparison5_2->SetLineColor(kAzure+10);
	pz_comparison5_2->Draw("same");
    pz_comparison6->SetLineColor(kRed);
    pz_comparison6->Draw("same");
	leg->Draw();
	c1->Print("pz_comparison.png","png");

/*
    lvjj_comparison1->SetLineColor(kYellow+3);
    lvjj_comparison1->Draw();
*/
    lvjj_comparison2->SetLineColor(kOrange+7);
    lvjj_comparison2->Draw();
//    lvjj_comparison2_1->SetLineColor(kGrey);
//    lvjj_comparison2_1->Draw("same");
    lvjj_comparison3->SetLineColor(kYellow-2);
    lvjj_comparison3->Draw("same");

    lvjj_comparison4->SetLineColor(kMagenta+1);
    lvjj_comparison4->Draw("same");
    lvjj_comparison5->SetLineColor(kBlue);
    lvjj_comparison5->Draw("same");
	lvjj_comparison5_1->SetLineColor(kSpring-7);
	lvjj_comparison5_1->Draw("same");
    lvjj_comparison5_2->SetLineColor(kAzure+10);
    lvjj_comparison5_2->Draw("same");
    lvjj_comparison6->SetLineColor(kRed);
    lvjj_comparison6->Draw("same");
	leg->Draw();
    c1->Print("lvjj_comparison.png","png");

	leg->AddEntry (hlvjj0,"neu pz = true","l") ;

	hlvjj0->SetLineColor(kBlack);
	hlvjj0->SetTitle("hlvjj_allin");
	hlvjj0->Draw();
    /*
	hlvjj1->SetLineColor(kYellow+3);
    hlvjj1->Draw("same");
*/
    hlvjj2->SetLineColor(kOrange+7);
    hlvjj2->Draw("same");
//    hlvjj2_1->SetLineColor(kGrey);
//    hlvjj2_1->Draw("same");
    hlvjj3->SetLineColor(kYellow-2);
    hlvjj3->Draw("same");

    hlvjj4->SetLineColor(kMagenta+1);
    hlvjj4->Draw("same");
	hlvjj5->SetLineColor(kBlue);
    hlvjj5->Draw("same");
	hlvjj5_1->SetLineColor(kSpring-7);
	hlvjj5_1->Draw("same");
    hlvjj5_2->SetLineColor(kAzure+10);
    hlvjj5_2->Draw("same");
    hlvjj6->SetLineColor(kRed);
    hlvjj6->Draw("same");
	leg->Draw();
    c1->Print("hlvjj_allin.png","png");



}
示例#8
0
void Ntp1Analyzer_HWWlvjj::Loop(){

   DEBUG_VERBOSE_ = false;

   if (fChain == 0) return;

   Long64_t nentries;

   if( DEBUG_ ) nentries = 100000;
   else nentries = fChain->GetEntries();

   Long64_t nbytes = 0, nb = 0;

   TRandom3 rand;
   float Cont_inclusive=0., Cont_PV=0., Cont_MU=0., Cont_ELE=0., Cont_VetoMU=0., Cont_VetoELE=0., Cont_JetsELE=0., Cont_JetsMU=0.;
   Long64_t Jentry;

requiredTriggerElectron.push_back("1-164237:HLT_Ele27_CaloIdVT_CaloIsoT_TrkIdT_TrkIsoT_v");
requiredTriggerElectron.push_back("165085-166967:HLT_Ele32_CaloIdVT_CaloIsoT_TrkIdT_TrkIsoT_v");
requiredTriggerElectron.push_back("166968-999999:HLT_Ele52_CaloIdVT_TrkIdT_v");
requiredTriggerMuon.push_back("1-163261:HLT_Mu15_v");
requiredTriggerMuon.push_back("163262-164237:HLT_Mu24_v");
requiredTriggerMuon.push_back("165085-166967:HLT_Mu30_v");
requiredTriggerMuon.push_back("163262-166967:HLT_IsoMu17_v");
requiredTriggerMuon.push_back("167039-999999:HLT_IsoMu20_eta2p1_v");
   for (Long64_t jentry=0; jentry<nentries;jentry++) {
     Long64_t ientry = LoadTree(jentry);
     if (ientry < 0) break;
     nb = fChain->GetEntry(jentry);   nbytes += nb;
     // if (Cut(ientry) < 0) continue;

     Jentry=jentry;

     if( DEBUG_VERBOSE_ ) std::cout << "entry n." << jentry << std::endl;
     

     if( (jentry%100000) == 0 ) std::cout << "Event #" << jentry  << " of " << nentries << std::endl;
  
   //HLT_Mu11_ = this->PassedHLT("HLT_Mu11");
   //HLT_Ele17_SW_EleId_L1R_ = this->PassedHLT("HLT_Ele17_SW_EleId_L1R");
   //HLT_DoubleMu3_ = this->PassedHLT("HLT_DoubleMu3");

     run_ = runNumber;
     LS_ = lumiBlock;
     event_ = eventNumber;
     eventWeight_ = -1.; //default

     Cont_inclusive++;//Other;

     if( !isGoodEvent( jentry ) ) continue; //this takes care also of integrated luminosity and trigger

       if( nPV==0 ) continue;
     bool goodVertex = (ndofPV[0] >= 4.0 && sqrt(PVxPV[0]*PVxPV[0]+PVyPV[0]*PVyPV[0]) < 2. && fabs(PVzPV[0]) < 24. );
     if( !goodVertex ) continue;
     nvertex_ = nPV;
     rhoPF_ = rhoFastjet;

     Cont_PV++; //Other

     //trigger:
     // not yet

     if( !isMC_ ){
     reloadTriggerMask(runNumber);
     bool passedElectronTrigger=true, passedMuonTrigger=true;
     std::string SingEle("SingleElectron_6july");//WW
     std::string SingMuo("SingleMu_6july");
     int elect=dataset_.compare(SingEle), muo=dataset_.compare(SingMuo);
     if( elect==0 ){ passedElectronTrigger = hasPassedHLT(0); }
     if( muo==0 ){ passedMuonTrigger = hasPassedHLT(1); }
     if( elect!=0 && muo!=0  ){ std::cout<<"Trigger doesn't works; dataset wrong"<<std::endl; }
     if( !passedElectronTrigger && elect==0 ){ continue;}
     if( !passedMuonTrigger && muo==0 ){ continue;}
     }
         ptHat_ = (isMC_) ? genPtHat : ptHat_;

     //if( isMC_ ) 
     //  if( (ptHat_ > ptHatMax_) || (ptHat_ < ptHatMin_) ) continue;

     bool noLeptons = false;
     TLorentzVector lept1MC, lept2MC;
     int wIndexqq=-1;
     int wIndexll=-1;
   
     if( isMC_ ) {
       
       // first look for W->qq'
       std::vector<TLorentzVector> quarksMC;

       for( unsigned iMc=0; iMc<nMc && quarksMC.size()<2; ++iMc ) {

         // quarks have status 3
         if( statusMc[iMc] != 3 ) continue;

         TLorentzVector* thisParticle = new TLorentzVector();
         thisParticle->SetPtEtaPhiE( pMc[iMc]*sin(thetaMc[iMc]), etaMc[iMc], phiMc[iMc], energyMc[iMc] );

         if( fabs(idMc[iMc])<7 && fabs(idMc[mothMc[iMc]])==24 ) {
           wIndexqq = mothMc[iMc];
           quarksMC.push_back( *thisParticle );
         }
       }

       // (checked that always 2 quarks are found)
       if( quarksMC.size()==2 && wIndexqq!=-1 ) {
	   eQuark1_=quarksMC[0].E();
	   ptQuark1_=quarksMC[0].Pt();
	   etaQuark1_=quarksMC[0].Eta();
	   phiQuark1_=quarksMC[0].Phi();
	   eQuark2_=quarksMC[1].E();
	   ptQuark2_=quarksMC[1].Pt();
	   etaQuark2_=quarksMC[1].Eta();
	   phiQuark2_=quarksMC[1].Phi();
 
         TLorentzVector WqqMC;
         WqqMC.SetPtEtaPhiE( pMc[wIndexqq]*sin(thetaMc[wIndexqq]), etaMc[wIndexqq], phiMc[wIndexqq], energyMc[wIndexqq] );
         ptWqqMC_  = WqqMC.Pt();
         eWqqMC_   = WqqMC.Energy();
         etaWqqMC_ = WqqMC.Eta();
         phiWqqMC_ = WqqMC.Phi();
	 //float deltaRqq = quarksMC[0].DeltaR(quarksMC[1]);
	 // h1_deltaRqq->Fill(deltaRqq);
       }
       
       // now look for W->lv

       std::vector<TLorentzVector> electronMC;
       std::vector<TLorentzVector> muonMC;
       std::vector<TLorentzVector> neutrinoMC;

       for( unsigned iMc=0; iMc<nMc; ++iMc ) {
	 
	 if( statusMc[iMc] != 3 ) continue;
	 
         TLorentzVector* thisParticle = new TLorentzVector();
         thisParticle->SetPtEtaPhiE( pMc[iMc]*sin(thetaMc[iMc]), etaMc[iMc], phiMc[iMc], energyMc[iMc] );

           if( fabs(idMc[iMc])==11 && fabs(idMc[mothMc[iMc]])==24 ) {electronMC.push_back( *thisParticle ); wIndexll = mothMc[iMc]; }
	   if( fabs(idMc[iMc])==13 && fabs(idMc[mothMc[iMc]])==24 ) {muonMC.push_back( *thisParticle ); wIndexll = mothMc[iMc]; }
	   if( (fabs(idMc[iMc])==12 || fabs(idMc[iMc])==14 ) && fabs(idMc[mothMc[iMc]])==24 ) {
	     neutrinoMC.push_back( *thisParticle );  wIndexll = mothMc[iMc];
	       }//for comparison with fit
 
         delete thisParticle;
         thisParticle = 0;
       }
       
       if( electronMC.size()==1 && neutrinoMC.size()==1 ) {
	 lept1MC = electronMC[0];
	 lept2MC = neutrinoMC[0];
	
       	 if( (fabs(lept1MC.Eta()) < 2.5) && ( fabs(lept1MC.Eta())<1.4442 || fabs(lept1MC.Eta())>1.566) ){
       	 h1_nEvents_vs_ptEle->Fill( lept1MC.Pt() );}
       	 h1_nEvents_vs_ptEle->Fill( lept2MC.Pt() );
       	 }
       else if( muonMC.size()==1 && neutrinoMC.size()==1 ) {
	 lept1MC = muonMC[0];
	 lept2MC = neutrinoMC[0];

	 if( fabs(lept1MC.Eta()) < 2.4 ){ 
         h1_nEvents_vs_ptMuon->Fill( lept1MC.Pt() );} h1_nEvents_vs_ptMuon->Fill( lept2MC.Pt() );
       }
       else {
	 //taus
	 noLeptons=true;
       }

       if( !noLeptons ) {
       eLeptMC_=lept1MC.E();
       ptLeptMC_=lept1MC.Pt();
       etaLeptMC_=lept1MC.Eta();
       phiLeptMC_=lept1MC.Phi();       
       eNeuMC_=lept2MC.E();
       ptNeuMC_=lept2MC.Pt();
       etaNeuMC_=lept2MC.Eta();
       phiNeuMC_=lept2MC.Phi();
       }
       //if is a tau or a not recognized e/mu default values are setted
       if( noLeptons ) {
       eLeptMC_=1.;
       ptLeptMC_=1.;
       etaLeptMC_=10.;
       phiLeptMC_=1.;       
       eNeuMC_=1.;
       ptNeuMC_=1.;
       etaNeuMC_=10.;
       phiNeuMC_=1.;    
       }

       if( !noLeptons ) {
       TLorentzVector WllMC;
       WllMC.SetPtEtaPhiE( pMc[wIndexll]*sin(thetaMc[wIndexll]), etaMc[wIndexll], phiMc[wIndexll], energyMc[wIndexll] );
       
       ptWllMC_  = WllMC.Pt();
       eWllMC_   = WllMC.Energy();
       etaWllMC_ = WllMC.Eta();
       phiWllMC_ = WllMC.Phi();
       }
       
       // now look for the higgs:
       if( wIndexll!=-1 && wIndexqq!=-1 ) {
	 
         int higgsIndex = mothMc[wIndexll];
         if( idMc[higgsIndex] == 25 ) {
           TLorentzVector HiggsMC;
           HiggsMC.SetPtEtaPhiE( pMc[higgsIndex]*sin(thetaMc[higgsIndex]), etaMc[higgsIndex], phiMc[higgsIndex], energyMc[higgsIndex] );

           eHiggsMC_   = HiggsMC.Energy(); 
           ptHiggsMC_  = HiggsMC.Pt(); 
           etaHiggsMC_ = HiggsMC.Eta(); 
           phiHiggsMC_ = HiggsMC.Phi(); 
         } // if higgs

       } //if found two W's
     
     } //if isMC
    
     // -----------------------------
     //      FROM NOW ON RECO
     // -----------------------------

     energyPFMet_ = energyPFMet[0];
     phiPFMet_ = phiPFMet[0];
     pxPFMet_ = pxPFMet[0];
     pyPFMet_ = pyPFMet[0];     
     
     // -----------------------------
     //###      uncorrEnergyJet (to use in Neutrino's fit if you don't have SumEt)
     // -----------------------------
     
       for( int i=0;i<nAK5Jet;i++ ){
       uncorrEnergyAK5Jet_ += uncorrEnergyAK5Jet[i];
       }

     // -----------------------------
     //###      SumEt
     // -----------------------------
       
     SumEt_ = sumEtPFMet[0]; 
 
     // ------------------
     // MUON
     // ------------------

     std::vector<AnalysisMuon> muon;
     bool looseMuon=false;

     for( unsigned int iMuon=0; iMuon<nMuon; ++iMuon ) {

         AnalysisMuon thisMuon( pxMuon[iMuon], pyMuon[iMuon], pzMuon[iMuon], energyMuon[iMuon] );

       // --------------
       // kinematics:
       // --------------

       if( thisMuon.Pt() < 10. ) continue;
       if( fabs(thisMuon.Eta()) > 2.4 ) continue; //2.4 OtherMine

	 thisMuon.isGlobalMuonPromptTight = (muonIdMuon[iMuon]>>8)&1;
	 thisMuon.isAllTrackerMuon = (muonIdMuon[iMuon]>>11)&1;

       //     // --------------
       //     // ID:
       //     // --------------
       //     if( !( (muonIdMuon[iMuon]>>8)&1 ) ) continue; //GlobalMuonPromptTight
       //     if( !( (muonIdMuon[iMuon]>>11)&1 ) ) continue; //AllTrackerMuon
       //if( numberOfValidPixelBarrelHitsTrack[trackIndexMuon[iMuon]]==0 && numberOfValidPixelEndcapHitsTrack[trackIndexMuon[iMuon]]==0 ) continue;      
         
	thisMuon.pixelHits = numberOfValidPixelBarrelHitsTrack[trackIndexMuon[iMuon]]+numberOfValidPixelEndcapHitsTrack[trackIndexMuon[iMuon]];
        thisMuon.trackerHits = trackValidHitsTrack[trackIndexMuon[iMuon]];
        thisMuon.nMatchedStations = numberOfMatchesMuon[iMuon]; // This branch not exists yet in WW500

       // to compute dxy, look for leading primary vertex:
       int hardestPV = -1;
       float sumPtMax = 0.0;
       for(int v=0; v<nPV; v++) {
         if(SumPtPV[v] > sumPtMax) {
           sumPtMax = SumPtPV[v];
           hardestPV = v;
         }
       }  
      
       float dxy;
       if( hardestPV==-1 ) {
         dxy = 0.;
       } else {
         dxy = fabs(this->trackDxyPV(PVxPV[hardestPV], PVyPV[hardestPV], PVzPV[hardestPV],
                              trackVxTrack[trackIndexMuon[iMuon]], trackVyTrack[trackIndexMuon[iMuon]], trackVzTrack[trackIndexMuon[iMuon]],
				     pxTrack[trackIndexMuon[iMuon]], pyTrack[trackIndexMuon[iMuon]], pzTrack[trackIndexMuon[iMuon]]));
       }
 
       float dz = fabs(trackVzTrack[trackIndexMuon[iMuon]]-PVzPV[hardestPV]);
      
       thisMuon.dxy = dxy;
       thisMuon.dz = dz;
       
       thisMuon.sumPt03 = sumPt03Muon[iMuon];
       thisMuon.emEt03  = emEt03Muon[iMuon];
       thisMuon.hadEt03 = hadEt03Muon[iMuon];

       if( !thisMuon.passedVBTF() ) continue;
     
       // --------------
       // isolation:
       // --------------
       // (this is sum pt tracks)
       //if( sumPt03Muon[iMuon] >= 3. ) continue;
       // combined isolation < 15%:
       //if( (sumPt03Muon[iMuon] + emEt03Muon[iMuon] + hadEt03Muon[iMuon]) >= 0.15*thisMuon.Pt() ) continue;

       // looking at loose muon
       looseMuon=true;
       if( thisMuon.Pt()<20. ) continue;

       // for now simple selection, will have to optimize this (T&P?)
       chargeLept_=chargeMuon[iMuon];
     muon.push_back( thisMuon );
       looseMuon=false;

   } //for muon

     // ------------------
     // ELECTRON
     // ------------------

     std::vector<AnalysisElectron> electron;    
     bool looseEle = false; //Other
     
     for( unsigned int iEle=0; iEle<nEle ; ++iEle ) {

       AnalysisElectron thisEle( pxEle[iEle], pyEle[iEle], pzEle[iEle], energyEle[iEle] );

       // --------------
       // kinematics:
       // --------------
       if( thisEle.Pt() < 15. ) continue;
       if( (fabs(thisEle.Eta()) > 2.5) || ( fabs(thisEle.Eta())>1.4442 && fabs(thisEle.Eta())<1.566) ) continue;

       // isolation
       thisEle.dr03TkSumPt = dr03TkSumPtEle[iEle];
       thisEle.dr03EcalRecHitSumEt = dr03EcalRecHitSumEtEle[iEle];
       thisEle.dr03HcalTowerSumEt = dr03HcalTowerSumEtEle[iEle];

       // electron ID
       thisEle.sigmaIetaIeta = (superClusterIndexEle[iEle]>=0) ? covIEtaIEtaSC[superClusterIndexEle[iEle]] : covIEtaIEtaSC[PFsuperClusterIndexEle[iEle]];
       thisEle.deltaPhiAtVtx = deltaPhiAtVtxEle[iEle];
       thisEle.deltaEtaAtVtx = deltaEtaAtVtxEle[iEle];
       thisEle.hOverE = hOverEEle[iEle];

       // conversion rejection
       thisEle.expInnerLayersGsfTrack = expInnerLayersGsfTrack[gsfTrackIndexEle[iEle]];
       thisEle.convDist = convDistEle[iEle];
       thisEle.convDcot = convDcotEle[iEle];

       bool passed_VBTF95 = thisEle.passedVBTF95();
       bool passed_VBTF80 = thisEle.passedTrigger80();//thisEle.passedVBTF80();

       if( !passed_VBTF80 && passed_VBTF95 ) looseEle=true; //Other
       if( !passed_VBTF80 ) continue; 
       if( thisEle.Pt() < 20. ) continue; // if is not a loose ele I require a higher Pt     

       // check that not matched to muon (clean electron faked by muon MIP):
       bool matchedtomuon=false;
       for( std::vector<AnalysisMuon>::iterator iMu=muon.begin(); iMu!=muon.end(); ++iMu )
         if( iMu->DeltaR(thisEle)<0.1 ) matchedtomuon=true;

       if( matchedtomuon ) continue;

       // for now simple selection, will have to optimize this (T&P?)
       // one electron required to pass VBTF80, the other VBTF95
       chargeLept_=chargeEle[iEle];
       electron.push_back( thisEle );
     } //for electron 
                                         //  FILL LEPTONS
// Fill Efficiency for Others

bool findJetELE=false;
bool findJetMU=false;

if( electron.size() >= 1 ) { Cont_ELE++;
  if( electron.size() == 1 && muon.size()==0 && !looseEle && !looseMuon ) { Cont_VetoELE++; findJetELE=true; }
  }

if( muon.size() >= 1 ) { Cont_MU++;
  if( muon.size() == 1 && electron.size()==0 && !looseEle && !looseMuon ) { Cont_VetoMU++; findJetMU=true; }
  }
// Fill lepton
    if( electron.size() > 1 || muon.size() > 1 ) continue;

     if( electron.size() < 1 &&  muon.size() < 1 ) continue;
     
     //   // clean electron faked by muon MIP in ECAL
     //   for( std::vector<TLorentzVector>::iterator iEle=electron.begin(); iEle!=electron.end(); ++iEle ) {
     //     for( std::vector<TLorentzVector>::iterator iMu=muon.begin(); iMu!=muon.end(); ++iMu ) {
     //       if( iMu->DeltaR(*iEle)<0.1 ) {
     //         std::cout << "lll" << std::endl;
     //         electron.erase(iEle);
     //       }
     //     } //for ele
     //   } //for mu
     
     //   if( electron.size() < 2 && muon.size() < 1 ) continue;
    
     std::vector< AnalysisLepton > leptons;

     if( electron.size() == 1 && muon.size() == 1 ) continue;
     if( electron.size() == 1 && (looseEle || looseMuon) ) continue;
     if( muon.size() == 1 && (looseEle || looseMuon) ) continue;

     if( electron.size() == 1 && (!looseEle || !looseMuon) ) { //Other 
       leptType_ = 1;
       leptons.push_back( electron[0] );

     } else if( muon.size() == 1 && (!looseEle || !looseMuon) ) {
       leptType_ = 0;
       leptons.push_back( muon[0] );

     } else {
       std::cout << "There must be an error this is not possible." << std::endl;
       exit(9101);
     }

     eLept_ = leptons[0].Energy();
     ptLept_ = leptons[0].Pt();
     etaLept_ = leptons[0].Eta();
     phiLept_ = leptons[0].Phi(); //chargeLept_ filled before
    
     // --------------------
     // match leptons to MC:
     // --------------------
     int correctIdMc = (leptType_==0 ) ? 13 : 11;

	float deltaRmin = 100.;
	TLorentzVector matchedLeptonMC;
	for( unsigned iMc=0; iMc<nMc; ++iMc ){
	   if( statusMc[iMc]==1 && fabs(idMc[iMc])==correctIdMc && idMc[mothMc[mothMc[iMc]]]==24 ) {
	     
	     TLorentzVector* thisParticle = new TLorentzVector();
	     thisParticle->SetPtEtaPhiE( pMc[iMc]*sin(thetaMc[iMc]), etaMc[iMc], phiMc[iMc], energyMc[iMc] );
	     float thisDeltaR = leptons[0].DeltaR( *thisParticle );
	     if( thisDeltaR < deltaRmin ) {
	       deltaRmin = thisDeltaR;
	       matchedLeptonMC = *thisParticle;
	     }
	     
	     delete thisParticle;
	     thisParticle = 0; 
	   } //if correct id mc
	   
	  } // for i mc

	  if( !noLeptons ) {
	    if( leptType_==0 ) {
	      h1_deltaRmatching_muons->Fill( deltaRmin );
	      if( deltaRmin<0.1 ) {
		h1_passed_vs_ptMuon->Fill( matchedLeptonMC.Pt() );
	      }
	    } else if( leptType_==1 ) { 
	      h1_deltaRmatching_electrons->Fill( deltaRmin );
	      if( deltaRmin<0.1 ) {
		h1_passed_vs_ptEle->Fill( matchedLeptonMC.Pt() );
	      }
	    }  //if lept type
	  } //if yes leptons
   
      // ------------------
      // JETS
      // ------------------
	     
	float jetPt_thresh = 20.;
	bool matched=false;      
	
	// first save leading jets in event:
	std::vector<AnalysisJet> leadJets;
	std::vector<int> leadJetsIndex; //index in the event collection (needed afterwards for PFCandidates)
	int nJets30=0;
	
	//QGLikelihoodCalculator qglc;
     for( unsigned int iJet=0; iJet<nAK5PFPUcorrJet; ++iJet ) {
       
       AnalysisJet thisJet( pxAK5PFPUcorrJet[iJet], pyAK5PFPUcorrJet[iJet], pzAK5PFPUcorrJet[iJet], energyAK5PFPUcorrJet[iJet] );
       
       thisJet.eChargedHadrons = chargedHadronEnergyAK5PFPUcorrJet[iJet];
       thisJet.ePhotons        = photonEnergyAK5PFPUcorrJet[iJet];
       thisJet.eNeutralEm      = neutralEmEnergyAK5PFPUcorrJet[iJet];
       thisJet.eNeutralHadrons = neutralHadronEnergyAK5PFPUcorrJet[iJet];
       thisJet.eElectrons      = electronEnergyAK5PFPUcorrJet[iJet];
       thisJet.eMuons          = muonEnergyAK5PFPUcorrJet[iJet];

       thisJet.nChargedHadrons = chargedHadronMultiplicityAK5PFPUcorrJet[iJet];
       thisJet.nPhotons        = photonMultiplicityAK5PFPUcorrJet[iJet];
       thisJet.nNeutralHadrons = neutralHadronMultiplicityAK5PFPUcorrJet[iJet];
       thisJet.nElectrons      = electronMultiplicityAK5PFPUcorrJet[iJet];
       thisJet.nMuons          = muonMultiplicityAK5PFPUcorrJet[iJet];

       thisJet.nCharged = chargedHadronMultiplicityAK5PFPUcorrJet[iJet]+electronMultiplicityAK5PFPUcorrJet[iJet]+muonMultiplicityAK5PFPUcorrJet[iJet];
       thisJet.nNeutral = neutralHadronMultiplicityAK5PFPUcorrJet[iJet]+photonMultiplicityAK5PFPUcorrJet[iJet];
       thisJet.rmsCand =  rmsCandAK5PFPUcorrJet[iJet];
       thisJet.ptD =  ptDAK5PFPUcorrJet[iJet];

       thisJet.trackCountingHighEffBJetTag = trackCountingHighEffBJetTagsAK5PFPUcorrJet[iJet];

       if( thisJet.Pt()>jetPt_thresh ) nJets30++;

       // save at least 3 lead jets (if event has them) and all jets with pt>thresh:
       if( leadJets.size()>=3 && thisJet.Pt()<jetPt_thresh ) break;

       // far away from leptons:
      if( leptType_==0){ if(thisJet.DeltaR( leptons[0] ) < 0.5 ) continue;}    
      if( leptType_==1){ if(thisJet.DeltaR( leptons[0] ) < 0.5 ) continue;} 

       // jet ID:
       int multiplicity = thisJet.nCharged +  thisJet.nNeutral + HFEMMultiplicityAK5PFPUcorrJet[iJet] + HFHadronMultiplicityAK5PFPUcorrJet[iJet];
       if( multiplicity < 2 ) continue;
       if( fabs(thisJet.Eta())<2.4 && thisJet.nChargedHadrons == 0 ) continue;
       if( thisJet.eNeutralHadrons >= 0.99*thisJet.Energy() ) continue;
       if( thisJet.ePhotons >= 0.99*thisJet.Energy() ) continue;
       // match to genjet:

       float bestDeltaR=999.;
       TLorentzVector matchedGenJet;
       bool matched=false;
       for( unsigned iGenJet=0; iGenJet<nAK5GenJet; ++iGenJet ) {
         TLorentzVector thisGenJet(pxAK5GenJet[iGenJet], pyAK5GenJet[iGenJet], pzAK5GenJet[iGenJet], energyAK5GenJet[iGenJet]);
         if( thisGenJet.DeltaR(thisJet) < bestDeltaR ) {
           bestDeltaR=thisGenJet.DeltaR(thisJet);
           matchedGenJet=thisGenJet; matched==true;
         }
       }
       if(matched){
       thisJet.ptGen  = (isMC_) ? matchedGenJet.Pt() : 0.;
       thisJet.etaGen = (isMC_) ? matchedGenJet.Eta() : 20.;
       thisJet.phiGen = (isMC_) ? matchedGenJet.Phi() : 0.;
       thisJet.eGen   = (isMC_) ? matchedGenJet.Energy() : 0.;}
       else{
       thisJet.ptGen  = 0.;
       thisJet.etaGen = 20.;
       thisJet.phiGen = 0.;
       thisJet.eGen   = 0.;}
       // match to parton:
       float bestDeltaR_part=999.;
       TLorentzVector matchedPart;
       int pdgIdPart=0;
       for( unsigned iPart=0; iPart<nMc; ++iPart ) {
         if( statusMc[iPart]!=3 ) continue; //partons
         if( idMc[iPart]!=21 && abs(idMc[iPart])>6 ) continue; //quarks or gluons
         TLorentzVector thisPart;
         thisPart.SetPtEtaPhiE(pMc[iPart]*sin(thetaMc[iPart]), etaMc[iPart], phiMc[iPart], energyMc[iPart]);
         if( thisPart.DeltaR(thisJet) < bestDeltaR_part ) {
           bestDeltaR_part=thisPart.DeltaR(thisJet);
           matchedPart=thisPart;
           pdgIdPart=idMc[iPart];
         }
       }

       leadJets.push_back(thisJet);
       leadJetsIndex.push_back(iJet); 
     }//iJet

     h1_nJets30->Fill(nJets30);

     if( leadJets.size()<2 ) continue;
     if( leadJets[1].Pt()<jetPt_thresh ) continue; //at least 2 jets over thresh
   
     // now look for best invariant mass jet pair 
     float Wmass = 80.399;
     float bestMass = 0.;
     int best_i=-1;
     int best_j=-1;
     int best_i_eventIndex=-1;
     int best_j_eventIndex=-1;

     nPairs_ = 0;
     nPart_ = 0;
    
     for( unsigned iJet=0; iJet<leadJets.size(); ++iJet ) {
   
       AnalysisJet thisJet = leadJets[iJet];

       // --------------
       // kinematics:
       // --------------
       if( thisJet.Pt() < jetPt_thresh ) continue;
       if( fabs(thisJet.Eta()) > 2.4 ) continue;

       for( unsigned int jJet=iJet+1; jJet<leadJets.size(); ++jJet ) {

         AnalysisJet otherJet = leadJets[jJet];

         // --------------
         // kinematics:
         // --------------
         if( otherJet.Pt() < jetPt_thresh ) continue;
         if( fabs(otherJet.Eta()) > 2.4 ) continue;

         if( nPairs_>=50 ) {
        
           std::cout << "MORE than 50 jet pairs found. SKIPPING!!" << std::endl;

         } else {

           eJet1_[nPairs_] = leadJets[iJet].Energy();
           ptJet1_[nPairs_] = leadJets[iJet].Pt();
           etaJet1_[nPairs_] = leadJets[iJet].Eta();
           phiJet1_[nPairs_] = leadJets[iJet].Phi();
           eChargedHadronsJet1_[nPairs_] = leadJets[iJet].eChargedHadrons;
           ePhotonsJet1_[nPairs_]        = leadJets[iJet].ePhotons;
           eNeutralEmJet1_[nPairs_]      = leadJets[iJet].eNeutralEm;
           eNeutralHadronsJet1_[nPairs_] = leadJets[iJet].eNeutralHadrons;
           eElectronsJet1_[nPairs_]      = leadJets[iJet].eElectrons;
           eMuonsJet1_[nPairs_]          = leadJets[iJet].eMuons;
           nChargedHadronsJet1_[nPairs_] = leadJets[iJet].nChargedHadrons;
           nPhotonsJet1_[nPairs_]        = leadJets[iJet].nPhotons;
           nNeutralHadronsJet1_[nPairs_] = leadJets[iJet].nNeutralHadrons;
           nElectronsJet1_[nPairs_]      = leadJets[iJet].nElectrons;
           nMuonsJet1_[nPairs_]          = leadJets[iJet].nMuons;

           trackCountingHighEffBJetTagJet1_[nPairs_] = leadJets[iJet].trackCountingHighEffBJetTag;
           trackCountingHighEffBJetTagJet2_[nPairs_] = leadJets[jJet].trackCountingHighEffBJetTag;

           ptDJet1_[nPairs_] = leadJets[iJet].ptD;
           rmsCandJet1_[nPairs_] = leadJets[iJet].rmsCand;
           nChargedJet1_[nPairs_] = leadJets[iJet].nCharged;
           nNeutralJet1_[nPairs_] = leadJets[iJet].nNeutral;
           QGlikelihoodJet1_[nPairs_] = leadJets[iJet].QGlikelihood;

           eJet1Gen_[nPairs_] = leadJets[iJet].eGen;
           ptJet1Gen_[nPairs_] = leadJets[iJet].ptGen;
           etaJet1Gen_[nPairs_] = leadJets[iJet].etaGen;
           phiJet1Gen_[nPairs_] = leadJets[iJet].phiGen;
            
           eJet2_[nPairs_] = leadJets[jJet].Energy();
           ptJet2_[nPairs_] = leadJets[jJet].Pt();
           etaJet2_[nPairs_] = leadJets[jJet].Eta();
           phiJet2_[nPairs_] = leadJets[jJet].Phi();
           eChargedHadronsJet2_[nPairs_] = leadJets[jJet].eChargedHadrons;
           ePhotonsJet2_[nPairs_]        = leadJets[jJet].ePhotons;
           eNeutralEmJet2_[nPairs_]      = leadJets[jJet].eNeutralEm;
           eNeutralHadronsJet2_[nPairs_] = leadJets[jJet].eNeutralHadrons;
           eElectronsJet2_[nPairs_]      = leadJets[jJet].eElectrons;
           eMuonsJet2_[nPairs_]          = leadJets[jJet].eMuons;
           nChargedHadronsJet2_[nPairs_] = leadJets[jJet].nChargedHadrons;
           nPhotonsJet2_[nPairs_]        = leadJets[jJet].nPhotons;
           nNeutralHadronsJet2_[nPairs_] = leadJets[jJet].nNeutralHadrons;
           nElectronsJet2_[nPairs_]      = leadJets[jJet].nElectrons;
           nMuonsJet2_[nPairs_]          = leadJets[jJet].nMuons;

           ptDJet2_[nPairs_] = leadJets[jJet].ptD;
           rmsCandJet2_[nPairs_] = leadJets[jJet].rmsCand;
           nChargedJet2_[nPairs_] = leadJets[jJet].nCharged;
           nNeutralJet2_[nPairs_] = leadJets[jJet].nNeutral;
           QGlikelihoodJet2_[nPairs_] = leadJets[jJet].QGlikelihood;

           eJet2Gen_[nPairs_] = leadJets[jJet].eGen;
           ptJet2Gen_[nPairs_] = leadJets[jJet].ptGen;
           etaJet2Gen_[nPairs_] = leadJets[jJet].etaGen;
           phiJet2Gen_[nPairs_] = leadJets[jJet].phiGen;
            

           nPairs_++;
          
         }
	
       } //for j
     } //for i
   if( findJetELE && nPairs_>=1 ) {Cont_JetsELE++;} //Other 
   if( findJetMU && nPairs_>=1 ) {Cont_JetsMU++;} //Other 

 
     if( isMC_ ) {

       // store event partons in tree:
       for( unsigned iMc=0; iMc<nMc; ++iMc ) {

         //if( statusMc[iMc]==3 && (fabs(idMc[iMc])<=6 || idMc[iMc]==21) ) {
         if( statusMc[iMc]==3 && pMc[iMc]*sin(thetaMc[iMc])>0.1 ) {

           TLorentzVector* thisParticle = new TLorentzVector();
           thisParticle->SetPtEtaPhiE( pMc[iMc]*sin(thetaMc[iMc]), etaMc[iMc], phiMc[iMc], energyMc[iMc] );

           if( nPart_<20 ) {

             ptPart_[nPart_] = thisParticle->Pt();
             etaPart_[nPart_] = thisParticle->Eta();
             phiPart_[nPart_] = thisParticle->Phi();
             ePart_[nPart_] = thisParticle->Energy();
             pdgIdPart_[nPart_] = idMc[iMc];
             motherPart_[nPart_] = idMc[mothMc[iMc]];

             nPart_++;

           } else {
      
             std::cout << "Found more than 20 partons, skipping." << std::endl;

           }

           delete thisParticle;
           thisParticle = 0;

         } //if correct id mc

       } // for i mc

     } // if is mc

     reducedTree_->Fill(); 

   } //for entries
                       // Other
float proportion = 2061760. /*109989.*/ /Cont_inclusive;
	if( Jentry == (nentries-1) ){
//  std::cout << std::fixed << std::setprecision(6) << "Inclusive: " << Cont_inclusive*proportion << " PV: " << Cont_PV*proportion << " MU: " << Cont_MU*proportion << " ELE: " << Cont_ELE*proportion << " VetoMU: " << Cont_VetoMU*proportion 
  //<< " VetoELE: " << Cont_VetoELE*proportion << " JetsELE: " << Cont_JetsELE*proportion << " JetsMU: " << Cont_JetsMU*proportion << std::endl;

h1_Cont_inclusive->SetBinContent(1,Cont_inclusive*proportion);
h1_Cont_PV->SetBinContent(1,Cont_PV*proportion);
h1_Cont_TightMu->SetBinContent(1,Cont_MU*proportion);
h1_Cont_TightEle->SetBinContent(1,Cont_ELE*proportion);
h1_Cont_VetoMU->SetBinContent(1,Cont_VetoMU*proportion);
h1_Cont_VetoELE->SetBinContent(1,Cont_VetoELE*proportion);
h1_Cont_JetsELE->SetBinContent(1,Cont_JetsELE*proportion);
h1_Cont_JetsMU->SetBinContent(1,Cont_JetsMU*proportion);
}

} //loop