Example #1
0
int ScanChain( TChain* chain, int nEvents = -1, std::string skimFilePrefix="") {

  TObjArray *listOfFiles = chain->GetListOfFiles();

  unsigned int nEventsChain=0;
  if(nEvents==-1) 
    nEvents = chain->GetEntries();
  nEventsChain = nEvents;
  unsigned int nEventsTotal = 0;
  TDirectory *rootdir = gDirectory->GetDirectory("Rint:");

  TH1F *samplehisto = new TH1F("samplehisto", "Example histogram", 200,0,200);
  samplehisto->SetDirectory(rootdir);
  // file loop
  TIter fileIter(listOfFiles);
  TFile *currentFile = 0;
  while ( currentFile = (TFile*)fileIter.Next() ) {
    TFile f(currentFile->GetTitle());
    TTree *tree = (TTree*)f.Get("Events");
    cms2.Init(tree);
    
    //Event Loop
    unsigned int nEvents = tree->GetEntries();
    for( unsigned int event = 0; event < nEvents; ++event) {
      cms2.GetEntry(event);
      ++nEventsTotal;
      // Progress feedback to the user
      if(nEventsTotal%1000 == 0) {
        // xterm magic from L. Vacavant and A. Cerri
        if (isatty(1)) {
          printf("\015\033[32m ---> \033[1m\033[31m%4.1f%%"
          "\033[0m\033[32m <---\033[0m\015", (float)nEventsTotal/(nEventsChain*0.01));
          fflush(stdout);
        }
      }//if(nEventsTotal%20000 == 0) {


    }
    delete tree;
    f.Close();
  }

  if ( nEventsChain != nEventsTotal ) {
    std::cout << "ERROR: number of events from files is not equal to total number of events" << std::endl;
  }

  samplehisto->Draw();
  return 0;
}
Example #2
0
int genDump( TChain* chain, int first, int nev) {

  TObjArray *listOfFiles = chain->GetListOfFiles();

  //  unsigned int nEventsChain=0;
  int nEventsChain = chain->GetEntries();
  // nEventsChain = nEvents;
  unsigned int nEventsTotal = 0;
  int nDumped = 0;
  int nprocessed=0;

  // file loop
  TIter fileIter(listOfFiles);
  TFile *currentFile = 0;
  while ( currentFile = (TFile*)fileIter.Next() ) {
    TFile f(currentFile->GetTitle());
    TTree *tree = (TTree*)f.Get("Events");
    cms2.Init(tree);
    
    //Event Loop
    unsigned int nEvents = tree->GetEntries();
    for( unsigned int event = 0; event < nEvents; ++event) {
      cms2.GetEntry(event);
      ++nEventsTotal;
      // Progress feedback to the user
      if(nEventsTotal%1000 == 0) {
        // xterm magic from L. Vacavant and A. Cerri
        if (isatty(1)) {
          printf("\015\033[32m ---> \033[1m\033[31m%4.1f%%"
          "\033[0m\033[32m <---\033[0m\015", (float)nEventsTotal/(nEventsChain*0.01));
          fflush(stdout);
        }
      }//if(nEventsTotal%20000 == 0) {
      nprocessed++;
      if (nprocessed < first) continue;
      cout << "  " <<endl;
      cout << " Dumping entry " << nprocessed-1 << endl;
      dumpDocLines();
      nDumped++;
      if (nDumped >= nev) return 0;

    }
  }

  return 0;
}
Example #3
0
// void scan(float jetPtCut=40.0, TString tag = "", bool requireLeptonic = false, float mtLow = -1.0, float mtHigh = -1.0) {
void scan(float jetPtCut=40.0, TString tag = "", bool requireLeptonic = false) {

    TChain *ch = new TChain("Events");

    // ch->Add("/hadoop/cms/store/user/namin/mStop500to800_mLSP1/ntuple_78_2_RJ3.root");

    ch->Add("/hadoop/cms/store/user/namin/mStop825to900_mLSP1/ntuple_309_4_16a.root");
    ch->Add("/hadoop/cms/store/user/namin/mStop825to900_mLSP1/ntuple_253_1_f2L.root");
    ch->Add("/hadoop/cms/store/user/namin/mStop825to900_mLSP1/ntuple_343_3_l8P.root");
    ch->Add("/hadoop/cms/store/user/namin/mStop825to900_mLSP1/ntuple_329_3_4dB.root");
    ch->Add("/hadoop/cms/store/user/namin/mStop825to900_mLSP1/ntuple_336_1_yfv.root");
    ch->Add("/hadoop/cms/store/user/namin/mStop825to900_mLSP1/ntuple_358_1_IPX.root");
    ch->Add("/hadoop/cms/store/user/namin/mStop825to900_mLSP1/ntuple_346_1_ptQ.root");
    ch->Add("/hadoop/cms/store/user/namin/mStop825to900_mLSP1/ntuple_281_1_Qqp.root");
    ch->Add("/hadoop/cms/store/user/namin/mStop825to900_mLSP1/ntuple_362_1_NNy.root");
    ch->Add("/hadoop/cms/store/user/namin/mStop825to900_mLSP1/ntuple_361_1_Yhs.root");
    ch->Add("/hadoop/cms/store/user/namin/mStop825to900_mLSP1/ntuple_359_1_YrF.root");
    ch->Add("/hadoop/cms/store/user/namin/mStop825to900_mLSP1/ntuple_360_1_sfh.root");
    ch->Add("/hadoop/cms/store/user/namin/mStop150to475_mLSP1/*.root");
    ch->Add("/hadoop/cms/store/user/namin/mStop500to800_mLSP1/*.root");

    int nEventsTotal = ch->GetEntries();
    int nEventsSoFar = 0;
    int nGoodEvents = 0;

    TFile *currentFile = 0;
    TObjArray *listOfFiles = ch->GetListOfFiles();
    TIter fileIter(listOfFiles);

    vector<TH1F*> h1D_mindR_vec;
    TH1F* h1D_mindR = new TH1F("", "min #DeltaR between reco jet and quark;;Entries", 100, 0.0, 2.0); h1D_mindR_vec.push_back(h1D_mindR);

    vector<TH1F*> h1D_stop_mass_vec;
    TH1F* h1D_stop_mass = new TH1F("", "Stop mass (events have 2 matched jets);;Entries", 100, 100, 900); h1D_stop_mass_vec.push_back(h1D_stop_mass); 

    vector<TH1F*> h1D_stop_mass_lt2match_vec;
    TH1F* h1D_stop_mass_lt2match = new TH1F("", "Stop mass (events have <2 matched jets);;Entries", 100, 100, 900); h1D_stop_mass_lt2match_vec.push_back(h1D_stop_mass_lt2match); 

    vector<TH1F*> h1D_stop_mass_all_vec;
    TH1F* h1D_stop_mass_all = new TH1F("", "Stop mass (events passing W daughter reqs);;Entries", 100, 100, 900); h1D_stop_mass_all_vec.push_back(h1D_stop_mass_all); 

    vector<TH1F*> h1D_lonelyjet_vec;
    TH1F* h1D_lonelyjet = new TH1F("", "Just 1 jet;;Entries", 100, 100, 900); h1D_lonelyjet_vec.push_back(h1D_lonelyjet); 

    vector<TH1F*> h1D_nonlonelyjet_vec;
    TH1F* h1D_nonlonelyjet = new TH1F("", "2 jets;;Entries", 100, 100, 900); h1D_nonlonelyjet_vec.push_back(h1D_nonlonelyjet); 

    TH2F* h2D_dRqq_Wpt = new TH2F("", "#DeltaR_{qq} (no matching);W_{p_{T}};#DeltaR_{qq}", 50,0.0,900, 50,0.0,5.0);

    vector<TH1F*> h1D_njets_gen_vec;
    vector<TH1F*> h1D_njets_reco_vec;
    vector<TH1F*> h1D_dRjj_masses_vec;
    vector<TH1F*> h1D_dRqq_nomatch_vec;
    vector<TH1F*> h1D_dRcone_nomatch_vec;
    vector<TH1F*> h1D_leadjmass_masses_vec;
    vector<TH1F*> h1D_mt_masses_vec;
    for(int iStop = 0; iStop <= NSTOPMASSES; iStop++) {
        TH1F* h1D_njets_gen = new TH1F("", ";;Entries", 15, 0,15); h1D_njets_gen_vec.push_back(h1D_njets_gen);
        TH1F* h1D_njets_reco = new TH1F("", ";;Entries", 15, 0,15); h1D_njets_reco_vec.push_back(h1D_njets_reco);
        TH1F* h1D_dRjj_masses = new TH1F("", ";;Entries", 100, 0.0, 5.0); h1D_dRjj_masses_vec.push_back(h1D_dRjj_masses);
        TH1F* h1D_dRqq_nomatch = new TH1F("", ";;Entries", 100, 0.0, 5.0); h1D_dRqq_nomatch_vec.push_back(h1D_dRqq_nomatch);
        TH1F* h1D_dRcone_nomatch = new TH1F("", ";;Entries", 100, 0.0, 5.0); h1D_dRcone_nomatch_vec.push_back(h1D_dRcone_nomatch);
        TH1F* h1D_leadjmass_masses = new TH1F("", ";;Entries", 30, 0.0, 100.0); h1D_leadjmass_masses_vec.push_back(h1D_leadjmass_masses);
        TH1F* h1D_mt_masses = new TH1F("", ";;Entries", 45, 0.0, 900.0); h1D_mt_masses_vec.push_back(h1D_mt_masses);
    }

    initCounter();
    // File Loop
    while ( (currentFile = (TFile*)fileIter.Next()) ) { 

        // Get File Content
        TFile *file = new TFile( currentFile->GetTitle() );
        TTree *tree = (TTree*)file->Get("Events");
        cms2.Init(tree);

        TString filename(currentFile->GetTitle());

        // Loop over Events in current file
        unsigned int nEventsTree = tree->GetEntriesFast();
        for( unsigned int event = 0; event < nEventsTree; ++event) {


            // if(event > 300) break;

            addToCounter("total");

            // Get Event Content
            cms2.GetEntry(event);
            nEventsSoFar++;

            // each element of this vector is a pair of genps_ indices for the 2 quarks from a W
            vector<pair<int, int> > WtoqqIdxs; 
            // each element of this vector is a pair of goodJet indices for the 2 matched jets for the quarks
            vector<pair<int, int> > qqMatchedJets; 
            // indices of b quarks from same tops as Ws; this is in same order as WtoqqIdxs
            vector<int> bIdxs; 
            // indices of Ws
            vector<int> WIdxs;

            int stopMass = (int)sparm_values().at(0);
            int stopMassIdx = stopMassToIndex(stopMass);

            vector<int> WpDaughterIdxs, WmDaughterIdxs;
            for(unsigned int iPart = 0; iPart < genps_id().size(); iPart++) {
                //store Ws
                // if(genps_id().at(iPart) == 24) WIdxs[0] = iPart;
                // else if(genps_id().at(iPart) == -24) WIdxs[1] = iPart;

                if(genps_status().at(iPart) != 3) continue; // only look at status=3

                // same requirements on quarks as jets
                if (genps_p4().at(iPart).pt() < jetPtCut) continue;
                if (fabs(genps_p4().at(iPart).eta()) > 2.5) continue;

                if(genps_id_mother().at(iPart) == 24) {
                    WpDaughterIdxs.push_back(iPart);
                }
                else if(genps_id_mother().at(iPart) == -24) {
                    WmDaughterIdxs.push_back(iPart);
                }
                else continue;
            }


            int nLeptonicDecay = 0;
            int leptonIdx = -1;
            if(WpDaughterIdxs.size() == 2) {
                if(abs(genps_id().at( WpDaughterIdxs[0] )) < 7 && abs(genps_id().at( WpDaughterIdxs[1] )) < 7) 
                    WtoqqIdxs.push_back( std::make_pair(WpDaughterIdxs[0], WpDaughterIdxs[1]) );
                else if(genps_id().at( WpDaughterIdxs[0] ) * genps_id().at( WpDaughterIdxs[1] ) < 0) {  // opposite signs for pdg ids
                    if( abs( abs(genps_id().at( WpDaughterIdxs[0] )) - abs(genps_id().at( WpDaughterIdxs[1] )) ) == 1 ) {  // lep + nu are same flavor
                        nLeptonicDecay++;
                        // lepton pdg codes are odd
                        if( abs( genps_id().at( WpDaughterIdxs[0] ) ) % 2 != 0) leptonIdx = WpDaughterIdxs[0];
                        else leptonIdx = WpDaughterIdxs[1];
                    }
                }
            }
            if(WmDaughterIdxs.size() == 2) {
                if(abs(genps_id().at( WmDaughterIdxs[0] )) < 7 && abs(genps_id().at( WmDaughterIdxs[1] )) < 7) 
                    WtoqqIdxs.push_back( std::make_pair(WmDaughterIdxs[0], WmDaughterIdxs[1]) );
                else if(genps_id().at( WmDaughterIdxs[0] ) * genps_id().at( WmDaughterIdxs[1] ) < 0) {  // opposite signs for pdg ids
                    if( abs( abs(genps_id().at( WmDaughterIdxs[0] )) - abs(genps_id().at( WmDaughterIdxs[1] )) ) == 1 ) {  // lep + nu are same flavor
                        nLeptonicDecay++;
                        // lepton pdg codes are odd
                        if( abs( genps_id().at( WmDaughterIdxs[0] ) ) % 2 != 0) leptonIdx = WmDaughterIdxs[0];
                        else leptonIdx = WmDaughterIdxs[1];
                    }
                }
            }

            if(requireLeptonic) {
                // want 1 W to go hadronically and 1 leptonically
                if(WtoqqIdxs.size() != 1) continue;
                if(nLeptonicDecay != 1) continue;

                if(leptonIdx == -1) cout << "woah dude, error, leptonIdx is -1" << endl;

            } else {

                if(WtoqqIdxs.size() < 1) continue; // we don't even have 1 W->qq :(
            }

            // cout << endl;
            // // cout << "_______________" << endl;

            // find bs (and Ws) from top that Ws came from. then we have the whole familia: b,q,q
            for(unsigned int iPair = 0; iPair < WtoqqIdxs.size(); iPair++) {

                // take first quark for example and get W id 
                int Wid = genps_id_mother().at( WtoqqIdxs[iPair].first );
                // std::cout << " Wid: " << Wid << std::endl;


                // std::cout << " genps_id().size(): " << genps_id().size() << std::endl;
                
                for(unsigned int iPart = 0; iPart < genps_id().size(); iPart++) {

                    // iPart genps_id().at(iPart) Wid genps_id().at(iPart)==Wid
                    // std::cout << " iPart: " << iPart << " genps_id().at(iPart): " << genps_id().at(iPart) << " Wid: " << Wid  << std::endl;
                    // std::cout << " genps_id().at(iPart)-Wid: " << genps_id().at(iPart) - Wid << std::endl;
                    // std::cout << " iPart: " << iPart << " genps_id().at(iPart): " << genps_id().at(iPart) << " Wid: " << Wid << " genps_id().at(iPart)==Wid: " << genps_id().at(iPart)==Wid << std::endl;

                    if(genps_id().at(iPart) == Wid) WIdxs.push_back(iPart);
                    // std::cout << " iPart: " << iPart << std::endl;

                    // only consider b quarks
                    if(abs(genps_id().at(iPart)) != 5) continue;

                    int bid = genps_id().at(iPart);

                    // W+ goes with b; W- goes with bbar => product of W,b ID should be positive
                    if(Wid * bid > 0) {
                        bIdxs.push_back(iPart);
                        // break;
                    }
                }
                // if(WIdxs.size() < 1) { // XXX
                //     std::cout << " Wid: " << Wid << " WtoqqIdxs[iPair].first: " << WtoqqIdxs[iPair].first  << std::endl;
                //     for(unsigned int iPart = 0; iPart < genps_id().size(); iPart++) {
                //         std::cout << " iPart: " << iPart << " genps_id().at(iPart): " << genps_id().at(iPart) << std::endl;
                //     }
                // }
            }

            // if(WIdxs.size() < 1) { // XXX
            //     std::cout << " filename: " << filename << std::endl;
            //     dumpDocLines();
            // }
            // for(unsigned int iB = 0; iB < bIdxs.size(); iB++) {
            // std::cout << " genps_p4().at(bIxs[iB]).pt(): " << genps_p4().at(bIdxs[iB]).pt() << std::endl;
            // }
            if(bIdxs.size() != WtoqqIdxs.size() || WIdxs.size() < 1) {
                // t->qW, but q is mainly b. if it is not b, skip the event
                // also, for some reason, sometimes we can't find the W?! very rare, don't care to debug
                // dumpDocLines();
                continue;
            }

            // std::cout << " genps_p4().at(WIdxs[iPair]).pt(): " << genps_p4().at(WIdxs[0]).pt() << std::endl;


            // std::cout << " WIdxs.size(): " << WIdxs.size() << " bIdxs.size(): " << bIdxs.size() << " WtoqqIdxs.size(): " << WtoqqIdxs.size()  << std::endl;


            // mt stuff
            // sweet. gen met considers only lsps+neutrinos! 
            float mt = MT( genps_p4().at(leptonIdx), gen_met(), gen_metPhi() );
            fill(h1D_mt_masses_vec.at(stopMassIdx), mt);

            //             if(mtLow > 0 && mtHigh > 0) {
            //                 // std::cout << " mt: " << mt << " mtLow: " << mtLow << " mtHigh: " << mtHigh << std::endl;
            //                 if(mt > mtHigh || mt < mtLow) {
            //                     continue;
            //                 }
            //             }


            // end mt stuff

            fill(h1D_stop_mass_all, stopMass);

            std::vector<JetStruct> goodJets;
            std::vector<JetStruct> goodGenJets;
            for (unsigned int iJet = 0; iJet < pfjets_p4().size(); iJet++){
                if (pfjets_p4().at(iJet).pt()*pfjets_corL1FastL2L3().at(iJet) < jetPtCut) continue;
                if (fabs(pfjets_p4().at(iJet).eta()) > 2.5) continue;
                // if (!passesLoosePFJetID(iJet)) continue;


                ///// FIXME passesLoosePFJetID implementation
                float pfjet_chf_  = cms2.pfjets_chargedHadronE()[iJet] / cms2.pfjets_p4()[iJet].energy();
                float pfjet_nhf_  = cms2.pfjets_neutralHadronE()[iJet] / cms2.pfjets_p4()[iJet].energy();
                float pfjet_cef_  = cms2.pfjets_chargedEmE()[iJet] / cms2.pfjets_p4()[iJet].energy();
                float pfjet_nef_  = cms2.pfjets_neutralEmE()[iJet] / cms2.pfjets_p4()[iJet].energy();
                int   pfjet_cm_   = cms2.pfjets_chargedMultiplicity()[iJet];
                if (cms2.pfjets_pfcandIndicies().size() < 2) continue;
                if (pfjet_nef_ >= 0.99) continue;
                if (pfjet_nhf_ >= 0.99) continue;
                if (pfjet_cm_ < 1) continue;
                if (pfjet_chf_ < 1e-6) continue;
                if (pfjet_cef_ >= 0.99) continue;
                //// end passesLoosePFJetID implementation


                JetStruct myJet = {*(new LorentzVector()), 0.0, 999};
                myJet.jet = pfjets_p4().at(iJet);
                myJet.mindRToQuark = 9999;
                myJet.idx = iJet;

                goodJets.push_back(myJet);
            }
            for (unsigned int iJet = 0; iJet < genjets_p4().size(); iJet++) {
                if (genjets_p4().at(iJet).pt() < jetPtCut) continue;
                if (fabs(genjets_p4().at(iJet).eta()) > 2.5) continue;

                JetStruct myJet = {*(new LorentzVector()), 0.0, 999};
                myJet.jet = pfjets_p4().at(iJet);
                myJet.mindRToQuark = 9999;
                myJet.idx = iJet;

                goodGenJets.push_back(myJet);
            }

            fill(h1D_njets_gen_vec.at(stopMassIdx), goodGenJets.size());
            fill(h1D_njets_reco_vec.at(stopMassIdx), goodJets.size());

            for(unsigned int iPair = 0; iPair < WtoqqIdxs.size(); iPair++) {

                int q1idx = WtoqqIdxs[iPair].first;
                int q2idx = WtoqqIdxs[iPair].second;

                float mindR1 = 9999, mindR2 = 9999;
                int j1idx = -1, j2idx = -1;
                for(unsigned int iJet = 0; iJet < goodJets.size(); iJet++) {
                    float dR1 = deltaR( goodJets[iJet].jet, genps_p4().at(q1idx) );
                    float dR2 = deltaR( goodJets[iJet].jet, genps_p4().at(q2idx) );
                    if(dR1 < mindR1) {
                        mindR1 = dR1;
                        j1idx = iJet;
                    }
                    if(dR2 < mindR2) {
                        mindR2 = dR2;
                        j2idx = iJet;
                    }
                }

                float dRqq = deltaR( genps_p4().at(q1idx), genps_p4().at(q2idx) );
                fill(h1D_dRqq_nomatch_vec.at(stopMassIdx), dRqq);
                fill2D(h2D_dRqq_Wpt, genps_p4().at( WIdxs[iPair] ).pt(), dRqq);
                // cout << "before stuff" << endl; 
                // std::cout << " iPair: " << iPair << " WtoqqIdxs.size(): " << WtoqqIdxs.size() << std::endl;
                float dRq1b = deltaR( genps_p4().at( q1idx ), genps_p4().at( bIdxs[iPair] ) );
                float dRq2b = deltaR( genps_p4().at( q2idx ), genps_p4().at( bIdxs[iPair] ) );
                // cout << "after stuff" << endl; 
                float dRcone = max( max( dRq1b, dRq2b ), dRqq );
                fill(h1D_dRcone_nomatch_vec.at(stopMassIdx), dRcone);

                if(j1idx > -1 && j2idx > -1) {

                    if(j1idx != j2idx) {
                        goodJets[j1idx].mindRToQuark = mindR1;
                        goodJets[j2idx].mindRToQuark = mindR2;

                        qqMatchedJets.push_back( std::make_pair( j1idx, j2idx ) );

                        fill(h1D_nonlonelyjet, stopMass);
                    } else {
                        // cout << "just 1 jet that matches both quarks :(" << endl;
                        fill(h1D_lonelyjet, stopMass);

                    }
                } else {
                    // cout << "no good jets?!" << goodJets.size() << " " << pfjets_p4().size() <<  endl;
                }

                fill(h1D_mindR, mindR1);
                fill(h1D_mindR, mindR2);

            }

            for(unsigned int iPair = 0; iPair < qqMatchedJets.size(); iPair++) {
                int j1idx = qqMatchedJets[iPair].first;
                int j2idx = qqMatchedJets[iPair].second;

                int nMatchedJets = 0;
                if(goodJets[j1idx].mindRToQuark < 0.2) nMatchedJets++;
                if(goodJets[j2idx].mindRToQuark < 0.2) nMatchedJets++;

                if(nMatchedJets < 2) {
                    fill(h1D_stop_mass_lt2match, stopMass);
                    continue;
                }

                // at this point, both quarks for this pair have 2 matched jets

                float dRjj = deltaR( goodJets[j1idx].jet, goodJets[j2idx].jet );

                float leadingJetInvMass = goodJets[j1idx].jet.pt() > goodJets[j2idx].jet.pt() ? 
                    goodJets[j1idx].jet.mass() : goodJets[j2idx].jet.mass();

                fill(h1D_dRjj_masses_vec.at(stopMassIdx), dRjj);
                fill(h1D_leadjmass_masses_vec.at(stopMassIdx), leadingJetInvMass);
                // fill(h1D_njets_gen_vec.at(stopMassIdx), goodGenJets.size());
                // fill(h1D_njets_reco_vec.at(stopMassIdx), goodJets.size());

                fill(h1D_stop_mass, stopMass);
            } // outside of (beyond) this loop, only condition is that we have at least 1 W->qq

            CMS2::progress( nEventsSoFar, nEventsTotal );

            addToCounter("good events");

            // dumpDocLines();

            nGoodEvents++;

        }//event loop

    }//file loop MCMC

    printCounter();

    std::cout << " nGoodEvents: " << nGoodEvents << " nEventsTotal: " << nEventsTotal << std::endl;


    TString prefix("plots");
    prefix += tag;
    prefix += "/";

    TString common = "";
    // if(mtLow > 0 && mtHigh > 0) {
    //     common += " --label ";
    //     common += mtLow;
    //     common += " < M_{T} < ";
    //     common += mtHigh;
    // }

    TString massTitles = " --titles m_{#tilde{t}}=200| \
                          m_{#tilde{t}}=300| \
                          m_{#tilde{t}}=400| \
                          m_{#tilde{t}}=500| \
                          m_{#tilde{t}}=600| \
                          m_{#tilde{t}}=700| \
                          m_{#tilde{t}}=800| \
                          m_{#tilde{t}}=900| \
                          ";

    TH1F* dog = new TH1F("dog","",1,0,1);


    drawStacked(dog, h1D_lonelyjet_vec,prefix+"h1D_lonelyjet.pdf",""+common);
    h1D_lonelyjet->Divide(h1D_nonlonelyjet);
    drawStacked(dog, h1D_lonelyjet_vec,prefix+"h1D_lonelyjetfraction.pdf","--title lonely jet ratio (=1 jet/2 jets) (mindR, but no dR cut yet)"+common);

    drawStacked(dog, h1D_stop_mass_lt2match_vec,prefix+"h1D_stop_mass_lt2match.pdf",""+common);
    h1D_stop_mass_lt2match->Divide(h1D_stop_mass);
    drawStacked(dog, h1D_stop_mass_lt2match_vec,prefix+"h1D_jetmatchfraction.pdf","--title ratio of evts with <2 matched jets to 2 matched jets (after dR cut)"+common);

    drawStacked(dog, h1D_njets_gen_vec,prefix+"h1D_njets_gen.pdf","--keeporder --nostack --title Ngenjets --nofill --normalize --label normalized "+massTitles+common);
    drawStacked(dog, h1D_njets_reco_vec,prefix+"h1D_njets_reco.pdf","--keeporder --nostack --title Nrecojets --nofill --normalize --label normalized "+massTitles+common);
    drawStacked(dog, h1D_stop_mass_vec,prefix+"h1D_stop_mass.pdf",""+common);
    drawStacked(dog, h1D_stop_mass_all_vec,prefix+"h1D_stop_mass_all.pdf",""+common);
    drawStacked(dog, h1D_dRjj_masses_vec,prefix+"h1D_dRjj_masses.pdf","--keeporder --centerlabel --nostack --title dR between jj matched to qq --nofill "+massTitles+common);
    drawStacked(dog, h1D_dRqq_nomatch_vec,prefix+"h1D_dRqq_nomatch.pdf","--keeporder --centerlabel --nostack --title dR between qq (no matching at this point) --nofill "+massTitles+common);
    drawStacked(dog, h1D_dRcone_nomatch_vec,prefix+"h1D_dRcone_nomatch.pdf","--keeporder --centerlabel --nostack --title dR of cone with bqq (no matching at this point) --nofill "+massTitles+common);
    drawStacked(dog, h1D_leadjmass_masses_vec,prefix+"h1D_leadjmass_masses.pdf","--keeporder --centerlabel --nostack --title inv mass of leading j (of jj matched to qq) --nofill --normalize --label normalized "+massTitles+common);
    drawStacked(dog, h1D_mt_masses_vec,prefix+"h1D_mt_masses.pdf","--keeporder --centerlabel --nostack --title M_{T} --nofill --normalize --label normalized "+massTitles+common);
    drawStacked(dog, h1D_mindR_vec,prefix+"h1D_mindR.pdf","--centerlabel --title min #DeltaR between q-j --normalize --label normalized "+common);

    vector<float> thresholds;
    TString kTitles = " --titles ";
    thresholds.push_back(0.4); kTitles += "k = 0.4|";
    thresholds.push_back(0.5); kTitles += "k = 0.5|";
    thresholds.push_back(0.6); kTitles += "k = 0.6|";
    thresholds.push_back(0.7); kTitles += "k = 0.7|";
    thresholds.push_back(0.8); kTitles += "k = 0.8|";
    thresholds.push_back(0.9); kTitles += "k = 0.9|";
    thresholds.push_back(1.0); kTitles += "k = 1.0|";

    vector<float> masses;
    for(int iStop = 0; iStop <= NSTOPMASSES; iStop++) {
        masses.push_back(iStop*100+200);
    }

    vector<vector<float> > xvals;
    vector<vector<float> > yvals_jj, yvals_qq, yvals_bqq;
    for(unsigned int i = 0; i < thresholds.size(); i++) {
        vector<float> fatfractions, qqfractions, bqqfractions;

        for(int iStop = 0; iStop <= NSTOPMASSES; iStop++) {
            fatfractions.push_back( getFractionBetween(h1D_dRjj_masses_vec.at(iStop), 0.0, thresholds.at(i)) );
            qqfractions.push_back( getFractionBetween(h1D_dRqq_nomatch_vec.at(iStop), 0.0, thresholds.at(i)) );
            bqqfractions.push_back( getFractionBetween(h1D_dRcone_nomatch_vec.at(iStop), 0.0, thresholds.at(i)) );
        }

        xvals.push_back(masses);
        yvals_jj.push_back(fatfractions);
        yvals_qq.push_back(qqfractions);
        yvals_bqq.push_back(bqqfractions);
    }


    drawGraph(xvals, yvals_jj, prefix+"g1D_fatfraction.pdf", "--title Fraction of jj with #DeltaR_{jj}<k --xlabel m_{#tilde{t}}-m_{LSP} --ylabel fat fraction --legendposition bottom "+kTitles+common);
    drawGraph(xvals, yvals_qq, prefix+"g1D_qqfraction.pdf", "--title Fraction of qq (no match) with #DeltaR_{qq}<k --xlabel m_{#tilde{t}}-m_{LSP} --ylabel fraction --legendposition bottom "+kTitles+common);
    drawGraph(xvals, yvals_bqq, prefix+"g1D_bqqfraction.pdf", "--title Fraction of bqq cones (no match) with #DeltaR_{bqqcone}<k --xlabel m_{#tilde{t}}-m_{LSP} --ylabel fraction --legendposition bottom "+kTitles+common);

    vector<vector<float> > xval_masses;
    vector<vector<float> > yval_genjets, yval_recojets;
    for(int njets = 3; njets <= 4; njets++) {
        vector<float> genjetfractions, recojetfractions;

        for(int iStop = 0; iStop <= NSTOPMASSES; iStop++) {
            genjetfractions.push_back( getFractionBetween(h1D_njets_gen_vec.at(iStop), njets, 100) );
            recojetfractions.push_back( getFractionBetween(h1D_njets_reco_vec.at(iStop), njets, 100) );
        }

        yval_genjets.push_back(genjetfractions); 
        yval_recojets.push_back(recojetfractions); 
        xval_masses.push_back(masses); 
    }

    drawGraph(xval_masses, yval_genjets, prefix+"g1D_genjetfraction.pdf", "--title Fraction of ngenjets #geq k --xlabel m_{#tilde{t}}-m_{LSP} --ylabel fraction --legendposition bottom --titles k=3|k=4 "+common);
    drawGraph(xval_masses, yval_recojets, prefix+"g1D_recojetfraction.pdf", "--title Fraction of nrecojets #geq k --xlabel m_{#tilde{t}}-m_{LSP} --ylabel fraction --lerecodposition bottom --titles k=3|k=4 "+common);

    // 2D hists
    drawHist2D(h2D_dRqq_Wpt, prefix+"h2D_dRqq_Wpt.pdf");

    // return 0;
}
Example #4
0
int ScanChain( TChain* chain, bool fast = true, int nEvents = -1, string skimFilePrefix = "test") {

  int currentrun = -1;
  bool DCSonly = false;//KEEP THIS FALSE
  // Benchmark
  TBenchmark *bmark = new TBenchmark();
  bmark->Start("benchmark");

  // Example Histograms
  TDirectory *rootdir = gDirectory->GetDirectory("Rint:");

  map<string, TH1F*> histos;
  vector<string> histonames; histonames.clear();
  vector<int> hbins; hbins.clear();
  vector<float> hlow; hlow.clear();
  vector<float> hup; hup.clear();
  histonames.push_back("Mll");                       hbins.push_back(75); hlow.push_back(  15.); hup.push_back(390);
  histonames.push_back("Mud0");                      hbins.push_back(40); hlow.push_back( -0.4); hup.push_back(0.4);
  histonames.push_back("MudZ");                      hbins.push_back(40); hlow.push_back(  -1.); hup.push_back(1. );
  histonames.push_back("MuIP3d");                    hbins.push_back(40); hlow.push_back( -0.5); hup.push_back(0.5);
  histonames.push_back("MuRelIso03");                hbins.push_back(50); hlow.push_back(   0.); hup.push_back(2. );
  histonames.push_back("MuRelIso03EA");              hbins.push_back(50); hlow.push_back(   0.); hup.push_back(2. );
  histonames.push_back("MuRelIso03DB");              hbins.push_back(50); hlow.push_back(   0.); hup.push_back(2. );
  histonames.push_back("MuMiniIsoEA");               hbins.push_back(50); hlow.push_back(   0.); hup.push_back(2. );
  histonames.push_back("MuMiniIsoDB");               hbins.push_back(50); hlow.push_back(   0.); hup.push_back(2. );
  histonames.push_back("MuRelIso04");                hbins.push_back(50); hlow.push_back(   0.); hup.push_back(2. );
  histonames.push_back("MuAnnulus04");               hbins.push_back(25); hlow.push_back(   0.); hup.push_back(1. );
  histonames.push_back("MuRelIso03_MT30");           hbins.push_back(50); hlow.push_back(   0.); hup.push_back(2. );
  histonames.push_back("MuRelIso03EA_MT30");         hbins.push_back(50); hlow.push_back(   0.); hup.push_back(2. );
  histonames.push_back("MuRelIso03DB_MT30");         hbins.push_back(50); hlow.push_back(   0.); hup.push_back(2. );
  histonames.push_back("MuMiniIsoEA_MT30");          hbins.push_back(50); hlow.push_back(   0.); hup.push_back(2. );
  histonames.push_back("MuMiniIsoDB_MT30");          hbins.push_back(50); hlow.push_back(   0.); hup.push_back(2. );
  histonames.push_back("MuRelIso04_MT30");           hbins.push_back(50); hlow.push_back(   0.); hup.push_back(2. );
  histonames.push_back("MuAnnulus04_MT30");          hbins.push_back(25); hlow.push_back(   0.); hup.push_back(1. );
  histonames.push_back("MuID");                      hbins.push_back( 7); hlow.push_back(  -1.); hup.push_back(6. );
  histonames.push_back("MuvalidFraction");           hbins.push_back(25); hlow.push_back(   0.); hup.push_back(1. );
  histonames.push_back("MuisPF");                    hbins.push_back( 5); hlow.push_back(  -1.); hup.push_back(4. );
  histonames.push_back("Mugfit_normchi2");           hbins.push_back(40); hlow.push_back(   0.); hup.push_back(20.);
  histonames.push_back("Mugfit_validSTAHits");       hbins.push_back(10); hlow.push_back(   0.); hup.push_back(10.);
  histonames.push_back("MunumberOfMatchedStations"); hbins.push_back(10); hlow.push_back(   0.); hup.push_back(10.);
  histonames.push_back("Munlayers");                 hbins.push_back(20); hlow.push_back(   0.); hup.push_back(20.);
  histonames.push_back("Muchi2LocalPosition");       hbins.push_back(40); hlow.push_back(   0.); hup.push_back(40.);
  histonames.push_back("MutrkKink");                 hbins.push_back(50); hlow.push_back(   0.); hup.push_back(50.);
  histonames.push_back("MusegmCompatibility");       hbins.push_back(35); hlow.push_back(   0.); hup.push_back(1.4);
  histonames.push_back("MuvalidPixelHits");          hbins.push_back( 5); hlow.push_back(   0.); hup.push_back(5. );
  histonames.push_back("MuPt");                      hbins.push_back(30); hlow.push_back(   0.); hup.push_back(600);
  histonames.push_back("MuEta");                     hbins.push_back(60); hlow.push_back(   3.); hup.push_back(3. );
  histonames.push_back("MuPhi");                     hbins.push_back(32); hlow.push_back( -3.2); hup.push_back(3.2);
  histonames.push_back("MuCharge");                  hbins.push_back( 6); hlow.push_back(  -2.); hup.push_back(4. );
  histonames.push_back("MT");                        hbins.push_back(45); hlow.push_back(   0.); hup.push_back(450);
  histonames.push_back("ZPt");                       hbins.push_back(30); hlow.push_back(   0.); hup.push_back(600);
  histonames.push_back("Z_Pt");                      hbins.push_back(30); hlow.push_back(   0.); hup.push_back(600);
  histonames.push_back("ZEta");                      hbins.push_back(50); hlow.push_back(  -5.); hup.push_back(5. );
  histonames.push_back("ZPhi");                      hbins.push_back(32); hlow.push_back( -3.2); hup.push_back(3.2);
  histonames.push_back("DPhill");                    hbins.push_back(32); hlow.push_back(   0.); hup.push_back(3.2);
  histonames.push_back("DEtall");                    hbins.push_back(50); hlow.push_back(   0.); hup.push_back(5. );
  histonames.push_back("DRll");                      hbins.push_back(32); hlow.push_back(   0.); hup.push_back(6.4);
  histonames.push_back("MyMuPt");                      hbins.push_back(30); hlow.push_back(   0.); hup.push_back(600);
  histonames.push_back("MyMuEta");                     hbins.push_back(60); hlow.push_back(   3.); hup.push_back(3. );
  histonames.push_back("MyMuPhi");                     hbins.push_back(32); hlow.push_back( -3.2); hup.push_back(3.2);
  histonames.push_back("MyMuCharge");                  hbins.push_back( 6); hlow.push_back(  -2.); hup.push_back(4. );
  histonames.push_back("MET");                      hbins.push_back(40); hlow.push_back(   0.); hup.push_back(200);
  histonames.push_back("HT");                      hbins.push_back(40); hlow.push_back(   0.); hup.push_back(400);
  histonames.push_back("NJets");                      hbins.push_back(10); hlow.push_back(   0.); hup.push_back(10);
  histonames.push_back("NBJets");                      hbins.push_back(5); hlow.push_back(   0.); hup.push_back(5);
	      
  for(unsigned int i = 0; i<histonames.size(); ++i){
    int nbins = hbins[i];
    string mapname;
    for(unsigned int j = 0; j<11; ++j){
      string prefix = "";
      if(j==1) prefix = "NJ0_";
      else if(j==2) prefix = "NJ1_";
      else if(j==3) prefix = "NJ2_";
      else if(j==4) prefix = "NJge3_";
      else if(j==5) prefix = "NB0_";
      else if(j==6) prefix = "NBge1_";
      else if(j==7) prefix = "HTge100_";
      else if(j==8) prefix = "METge50_";
      else if(j==9) prefix = "METge25_";
      else if(j==10) prefix = "HTge150_";
      mapname = prefix + histonames[i]+"_"+skimFilePrefix;
      //cout << mapname << endl;
      if(histos.count(mapname) == 0 ) histos[mapname] = new TH1F(mapname.c_str(), "", nbins, hlow[i], hup[i]);
      histos[mapname]->Sumw2(); histos[mapname]->SetDirectory(rootdir);
    }
  }

  // Loop over events to Analyze
  unsigned int nEventsTotal = 0;
  unsigned int nEventsChain = chain->GetEntries();
  if( nEvents >= 0 ) nEventsChain = nEvents;
  TObjArray *listOfFiles = chain->GetListOfFiles();
  TIter fileIter(listOfFiles);
  TFile *currentFile = 0;

  //load json file
  const char* json_fileDCS = "myjsons/json_DCSONLY_Run2015B_snt.txt";
  const char* json_file = "myjsons/json_Golden_246908-251883_snt.txt";
  if(DCSonly) set_goodrun_file(json_fileDCS);
  else        set_goodrun_file(json_file);

  // File Loop
  while ( (currentFile = (TFile*)fileIter.Next()) ) {

    // Get File Content
    TFile *file = new TFile( currentFile->GetTitle() );
    TTree *tree = (TTree*)file->Get("t");
    if(fast) TTreeCache::SetLearnEntries(10);
    if(fast) tree->SetCacheSize(128*1024*1024);
    cms3.Init(tree);

    int nleps = 1;
    myevt p;//previous event
    myevt c;//current event
    resetEvent(p);
    resetEvent(c);
    vector<myevt> mu; mu.clear();

    // Loop over Events in current file
    if( nEventsTotal >= nEventsChain ) continue;
    unsigned int nEventsTree = tree->GetEntriesFast();
    for( unsigned int event = 0; event < nEventsTree; ++event) {
    
      // Get Event Content
      if( nEventsTotal >= nEventsChain ) continue;
      if(fast) tree->LoadTree(event);
      cms3.GetEntry(event);
      ++nEventsTotal;
    
      // Progress
      CMS3::progress(nEventsTotal, nEventsChain );
      if(evt_isRealData()&& !goodrun(evt_run(), evt_lumiBlock()) ) continue;

      //load my struct
      c.evt_pfmet   = evt_pfmet();
      c.evt_pfmetPhi   = evt_pfmetPhi();
      c.evt_trackmet   = evt_trackmet();
      c.evt_trackmetPhi   = evt_trackmetPhi();
      c.evt_pfsumet   = evt_pfsumet();
      c.evt_pfmetSig   = evt_pfmetSig();
      c.evt_event   = evt_event();
      c.evt_lumiBlock   = evt_lumiBlock();
      c.evt_run   = evt_run();
      c.filt_csc   = filt_csc();
      c.filt_hbhe   = filt_hbhe();
      c.filt_hcallaser   = filt_hcallaser();
      c.filt_ecaltp   = filt_ecaltp();
      c.filt_trkfail   = filt_trkfail();
      c.filt_eebadsc   = filt_eebadsc();
      c.evt_isRealData   = evt_isRealData(); 
      c.scale1fb   = scale1fb();
      c.evt_xsec_incl   = evt_xsec_incl();
      c.evt_kfactor   = evt_kfactor();
      c.gen_met   = gen_met();
      c.gen_metPhi   = gen_metPhi();
      c.njets   = njets();
      c.ht   = ht();
      c.jets  = jets();
      c.jets_disc  = jets_disc();
      c.sample  = sample();
      c.nvtx   = nvtx();
      c.HLT_Mu8_TrkIsoVVL   = HLT_Mu8_TrkIsoVVL();
      c.HLT_Mu17_TrkIsoVVL   = HLT_Mu17_TrkIsoVVL();
      c.HLT_Mu24_TrkIsoVVL   = HLT_Mu24_TrkIsoVVL();
      c.HLT_Mu34_TrkIsoVVL   = HLT_Mu34_TrkIsoVVL();
      c.HLT_Mu8   = HLT_Mu8();
      c.HLT_Mu17   = HLT_Mu17();
      c.HLT_Mu24   = HLT_Mu24();
      c.HLT_Mu34   = HLT_Mu34();
      c.HLT_Mu10_CentralPFJet30_BTagCSV0p5PF   = HLT_Mu10_CentralPFJet30_BTagCSV0p5PF();
      c.HLT_IsoMu24_eta2p1   = HLT_IsoMu24_eta2p1();
      c.HLT_IsoTkMu24_eta2p1   = HLT_IsoTkMu24_eta2p1(); 
      c.HLT_IsoMu27   = HLT_IsoMu27();
      c.HLT_IsoTkMu27   = HLT_IsoTkMu27(); 
      c.HLT_Mu45_eta2p1   = HLT_Mu45_eta2p1(); 
      c.HLT_Mu50   = HLT_Mu50();
      c.HLT_Ele8_CaloIdM_TrackIdM_PFJet30   = HLT_Ele8_CaloIdM_TrackIdM_PFJet30();
      c.HLT_Ele12_CaloIdM_TrackIdM_PFJet30   = HLT_Ele12_CaloIdM_TrackIdM_PFJet30();
      c.HLT_Ele18_CaloIdM_TrackIdM_PFJet30   = HLT_Ele18_CaloIdM_TrackIdM_PFJet30();
      c.HLT_Ele23_CaloIdM_TrackIdM_PFJet30   = HLT_Ele23_CaloIdM_TrackIdM_PFJet30();
      c.HLT_Ele33_CaloIdM_TrackIdM_PFJet30   = HLT_Ele33_CaloIdM_TrackIdM_PFJet30();
      c.HLT_Ele12_CaloIdL_TrackIdL_IsoVL_PFJet30   = HLT_Ele12_CaloIdL_TrackIdL_IsoVL_PFJet30();
      c.HLT_Ele18_CaloIdL_TrackIdL_IsoVL_PFJet30   = HLT_Ele18_CaloIdL_TrackIdL_IsoVL_PFJet30();
      c.HLT_Ele23_CaloIdL_TrackIdL_IsoVL_PFJet30   = HLT_Ele23_CaloIdL_TrackIdL_IsoVL_PFJet30();
      c.HLT_Ele33_CaloIdL_TrackIdL_IsoVL_PFJet30   = HLT_Ele33_CaloIdL_TrackIdL_IsoVL_PFJet30();
      c.HLT_Ele10_CaloIdM_TrackIdM_CentralPFJet30_BTagCSV0p5PF   = HLT_Ele10_CaloIdM_TrackIdM_CentralPFJet30_BTagCSV0p5PF();
      c.HLT_Ele27_eta2p1_WP75_Gsf   = HLT_Ele27_eta2p1_WP75_Gsf();
      c.HLT_Ele27_WP85_Gsf   = HLT_Ele27_WP85_Gsf();
      c.HLT_Ele27_eta2p1_WPLoose_Gsf   = HLT_Ele27_eta2p1_WPLoose_Gsf();
      c.HLT_Ele27_eta2p1_WPTight_Gsf   = HLT_Ele27_eta2p1_WPTight_Gsf();
      c.HLT_Ele32_eta2p1_WP75_Gsf   = HLT_Ele32_eta2p1_WP75_Gsf();
      c.HLT_Ele32_eta2p1_WPLoose_Gsf   = HLT_Ele32_eta2p1_WPLoose_Gsf();
      c.HLT_Ele32_eta2p1_WPTight_Gsf   = HLT_Ele32_eta2p1_WPTight_Gsf();
      c.HLT_Mu8_Ele8_CaloIdM_TrackIdM_Mass8_PFHT300   = HLT_Mu8_Ele8_CaloIdM_TrackIdM_Mass8_PFHT300();
      c.HLT_Mu23_TrkIsoVVL_Ele12_CaloIdL_TrackIdL_IsoVL   = HLT_Mu23_TrkIsoVVL_Ele12_CaloIdL_TrackIdL_IsoVL();
      c.HLT_Mu8_TrkIsoVVL_Ele23_CaloIdL_TrackIdL_IsoVL   = HLT_Mu8_TrkIsoVVL_Ele23_CaloIdL_TrackIdL_IsoVL();
      c.HLT_DoubleMu8_Mass8_PFHT300   = HLT_DoubleMu8_Mass8_PFHT300();
      c.HLT_Mu17_TrkIsoVVL_Mu8_TrkIsoVVL   = HLT_Mu17_TrkIsoVVL_Mu8_TrkIsoVVL();
      c.HLT_Mu17_TrkIsoVVL_TkMu8_TrkIsoVVL   = HLT_Mu17_TrkIsoVVL_TkMu8_TrkIsoVVL(); 
      c.HLT_Mu17_TrkIsoVVL_Mu8_TrkIsoVVL_DZ   = HLT_Mu17_TrkIsoVVL_Mu8_TrkIsoVVL_DZ();
      c.HLT_Mu17_TrkIsoVVL_TkMu8_TrkIsoVVL_DZ   = HLT_Mu17_TrkIsoVVL_TkMu8_TrkIsoVVL_DZ(); 
      c.HLT_DoubleEle8_CaloIdM_TrackIdM_Mass8_PFHT300   = HLT_DoubleEle8_CaloIdM_TrackIdM_Mass8_PFHT300();
      c.HLT_Ele23_Ele12_CaloIdL_TrackIdL_IsoVL_DZ   = HLT_Ele23_Ele12_CaloIdL_TrackIdL_IsoVL_DZ();
      c.pid_PFMuon   = pid_PFMuon();
      c.gfit_chi2   = gfit_chi2();
      c.gfit_ndof   = gfit_ndof();
      c.gfit_validSTAHits   = gfit_validSTAHits();
      c.numberOfMatchedStations   = numberOfMatchedStations();
      c.validPixelHits   = validPixelHits();
      c.nlayers   = nlayers();
      c.chi2LocalPosition   = chi2LocalPosition();
      c.trkKink   = trkKink();
      c.validHits   = validHits(); 
      c.lostHits   = lostHits();
      c.exp_outerlayers   = exp_outerlayers();
      c.segmCompatibility   = segmCompatibility();
      c.exp_innerlayers   = exp_innerlayers();
      c.passes_POG_vetoID   = passes_POG_vetoID();
      c.passes_POG_looseID   = passes_POG_looseID();
      c.passes_POG_mediumID   = passes_POG_mediumID();
      c.passes_POG_tightID   = passes_POG_tightID();
      c.ip3d   = ip3d();
      c.ip3derr   = ip3derr(); 
      c.type   = type();
      c.mt   = mt();
      c.ptrelv0   = ptrelv0();
      c.ptrelv1   = ptrelv1();
      c.miniiso   = miniiso();
      c.miniisoDB   = miniisoDB(); 
      c.reliso04   = reliso04();
      c.annulus04   = annulus04();
      c.p4  = p4();
      c.tag_p4  = tag_p4();
      c.dilep_p4  = dilep_p4();
      c.mc_p4  = mc_p4();
      c.mc_motherp4  = mc_motherp4();
      c.id   = id();
      c.idx   = idx();
      c.dxyPV   = dxyPV();
      c.dZ   = dZ();
      c.dxyPV_err   = dxyPV_err();
      c.motherID   = motherID();
      c.mc_id   = mc_id();
      c.RelIso03   = RelIso03();
      c.RelIso03EA   = RelIso03EA();
      c.RelIso03DB   = RelIso03DB();
      c.dilep_mass   = dilep_mass();
      c.dilep_p4   = dilep_p4();
      c.passes_SS_tight_noiso_v3 = passes_SS_tight_noiso_v3();
      c.passes_SS_fo_noiso_v3 = passes_SS_fo_noiso_v3();
      c.passes_POG_looseID = passLooseID(c);
      c.passes_POG_mediumID = passMediumID(c);
      c.passes_POG_tightID = passTightID(c);
     

      float weight = p.scale1fb*0.0403;
      if(skimFilePrefix=="DY_M10_50ns") weight *= 1.11;
      if(p.evt_isRealData) weight = 1.;
      if((skimFilePrefix=="SingleMuon"||skimFilePrefix=="DoubleMuon")&&fabs(weight-1.)>=0.001) cout <<__LINE__<< endl;
      // Analysis Code

      if(sameEvent(p,c)) { ++nleps; }


      if(((!sameEvent(p,c))||(nEventsChain==nEventsTotal)) && mu.size()>0) {

	int nbs = 0;
	int njs = 0;
	float HT = 0;
	double muovind[mu.size()];
	for(unsigned int i = 0; i<mu.size();++i){
	  muovind[i] = -1;
	  float minDR = 9999;
	  if(mu[i].jets.size()!=p.jets.size()) cout << "ERROR " << mu[i].jets.size() << " " << p.jets.size() << endl;
	  for(unsigned int j = 0; j<p.jets.size();++j){
	    float myDR = deltaR(mu[i].p4,p.jets[j]);
	    if(myDR<0.4 && myDR<minDR){
	      minDR = myDR;
	      muovind[i] = j;
	    }
	  }
	}
	for(unsigned int i = 0; i<p.jets.size();++i){
	  bool isoverlap = false;
	  for(unsigned int j = 0; j<mu.size();++j){
	    if(muovind[j]==i){
	      isoverlap = true;
	      break;
	    }
	  }
	  if(isoverlap) continue;
	  if(p.jets[i].Pt()<30) continue;
	  if(fabs(p.jets[i].Eta()>2.4)) continue;
	  ++njs;
	  HT += p.jets[i].Pt();
	  if(p.jets_disc[i]>0.890) ++nbs;
	}
      
	bool triggerbool2mu = false;
	bool triggerbool1mu = false;
	//now I reached full event!
	if(mu.size()>1) mu = sortbypt(mu);
	for(unsigned int i = 0; i<mu.size();++i){
	  if(mu[i].evt_isRealData) triggerbool2mu = triggerbool2mu || mu[i].HLT_Mu17_TrkIsoVVL_Mu8_TrkIsoVVL_DZ || mu[i].HLT_Mu17_TrkIsoVVL_TkMu8_TrkIsoVVL_DZ;
	  if(mu[i].evt_isRealData) triggerbool1mu = triggerbool1mu || mu[i].HLT_IsoMu24_eta2p1 || mu[i].HLT_IsoTkMu24_eta2p1 || mu[i].HLT_IsoMu27 || mu[i].HLT_IsoTkMu27 || mu[i].HLT_IsoMu20 || mu[i].HLT_IsoMu20;
	}
	if(!p.evt_isRealData){ triggerbool2mu = true; triggerbool1mu = true;}
	if(mu.size()==2){
	  triggerbool2mu = triggerbool2mu&&mu[0].p4.Pt()>20.&&fabs(mu[0].p4.Eta())<2.1&&mu[0].p4.Pt()>20.&&fabs(mu[0].p4.Eta())<2.1;//two muons passing nominal trigger w/o iso and dZ
	  triggerbool1mu = triggerbool1mu&&((mu[0].p4.Pt()>30.&&fabs(mu[0].p4.Eta())<2.1)||(mu[1].p4.Pt()>30.&&fabs(mu[1].p4.Eta())<2.1));//one muon passing nominal trigger w/o iso
	  LorentzVector Z = (mu[0].p4+mu[1].p4);
	  if((triggerbool1mu||triggerbool2mu)&& mu[0].passes_POG_tightID&&mu[1].passes_POG_tightID&&mu[0].miniisoDB<0.2&&mu[1].miniisoDB<0.2&&
	      fabs(mu[0].dZ)<0.1&&fabs(mu[1].dZ)<0.1&&fabs(mu[0].dxyPV)<0.02&&fabs(mu[1].dxyPV)<0.02){
	    //cout << "have a dilepton event: Z pt " << Z.Pt() << " and mass " << Z.M() << endl;
	    histos["Mll_"+skimFilePrefix]->Fill(Z.M(),weight);
	    if(njs==0) histos["NJ0_Mll_"+skimFilePrefix]->Fill(Z.M(),weight);
	    else if(njs==1) histos["NJ1_Mll_"+skimFilePrefix]->Fill(Z.M(),weight);
	    else if(njs==2) histos["NJ2_Mll_"+skimFilePrefix]->Fill(Z.M(),weight);
	    else histos["NJge3_Mll_"+skimFilePrefix]->Fill(Z.M(),weight);
	    if(nbs==0)  histos["NB0_Mll_"+skimFilePrefix]->Fill(Z.M(),weight);
	    else  histos["NBge1_Mll_"+skimFilePrefix]->Fill(Z.M(),weight);
	    if(HT>100.) histos["HTge100_Mll_"+skimFilePrefix]->Fill(Z.M(),weight);
	    if(HT>150.) histos["HTge150_Mll_"+skimFilePrefix]->Fill(Z.M(),weight);
	    if(p.evt_pfmet>50.) histos["METge50_Mll_"+skimFilePrefix]->Fill(Z.M(),weight);
	    if(p.evt_pfmet>25.) histos["METge25_Mll_"+skimFilePrefix]->Fill(Z.M(),weight);
	    if(Z.M()>75.&&Z.M()<105){
	      histos["ZPt_"+skimFilePrefix]->Fill(Z.Pt(),weight);
	      histos["ZEta_"+skimFilePrefix]->Fill(Z.Eta(),weight);
	      histos["ZPhi_"+skimFilePrefix]->Fill(Z.Phi(),weight);
	      histos["DPhill_"+skimFilePrefix]->Fill(getdphi(mu[0].p4.Phi(),mu[1].p4.Phi()),weight);
	      histos["DEtall_"+skimFilePrefix]->Fill(fabs(mu[0].p4.Eta()-mu[1].p4.Eta()),weight);
	      histos["DRll_"+skimFilePrefix]->Fill(dRbetweenVectors(mu[0].p4,mu[1].p4),weight);
	      histos["MET_"+skimFilePrefix]->Fill(p.evt_pfmet,weight);
	      histos["HT_"+skimFilePrefix]->Fill(HT,weight);
	      histos["NJets_"+skimFilePrefix]->Fill(njs,weight);
	      histos["NBJets_"+skimFilePrefix]->Fill(nbs,weight);
	      if(njs==0){
		histos["NJ0_ZPt_"+skimFilePrefix]->Fill(Z.Pt(),weight);
		histos["NJ0_ZEta_"+skimFilePrefix]->Fill(Z.Eta(),weight);
		histos["NJ0_ZPhi_"+skimFilePrefix]->Fill(Z.Phi(),weight);
		histos["NJ0_DPhill_"+skimFilePrefix]->Fill(getdphi(mu[0].p4.Phi(),mu[1].p4.Phi()),weight);
		histos["NJ0_DEtall_"+skimFilePrefix]->Fill(fabs(mu[0].p4.Eta()-mu[1].p4.Eta()),weight);
		histos["NJ0_DRll_"+skimFilePrefix]->Fill(dRbetweenVectors(mu[0].p4,mu[1].p4),weight);
	      } else if(njs==1){
		histos["NJ1_ZPt_"+skimFilePrefix]->Fill(Z.Pt(),weight);
		histos["NJ1_ZEta_"+skimFilePrefix]->Fill(Z.Eta(),weight);
		histos["NJ1_ZPhi_"+skimFilePrefix]->Fill(Z.Phi(),weight);
		histos["NJ1_DPhill_"+skimFilePrefix]->Fill(getdphi(mu[0].p4.Phi(),mu[1].p4.Phi()),weight);
		histos["NJ1_DEtall_"+skimFilePrefix]->Fill(fabs(mu[0].p4.Eta()-mu[1].p4.Eta()),weight);
		histos["NJ1_DRll_"+skimFilePrefix]->Fill(dRbetweenVectors(mu[0].p4,mu[1].p4),weight);
	      } else if(njs==2){
		histos["NJ2_ZPt_"+skimFilePrefix]->Fill(Z.Pt(),weight);
		histos["NJ2_ZEta_"+skimFilePrefix]->Fill(Z.Eta(),weight);
		histos["NJ2_ZPhi_"+skimFilePrefix]->Fill(Z.Phi(),weight);
		histos["NJ2_DPhill_"+skimFilePrefix]->Fill(getdphi(mu[0].p4.Phi(),mu[1].p4.Phi()),weight);
		histos["NJ2_DEtall_"+skimFilePrefix]->Fill(fabs(mu[0].p4.Eta()-mu[1].p4.Eta()),weight);
		histos["NJ2_DRll_"+skimFilePrefix]->Fill(dRbetweenVectors(mu[0].p4,mu[1].p4),weight);
	      } else {
		histos["NJge3_ZPt_"+skimFilePrefix]->Fill(Z.Pt(),weight);
		histos["NJge3_ZEta_"+skimFilePrefix]->Fill(Z.Eta(),weight);
		histos["NJge3_ZPhi_"+skimFilePrefix]->Fill(Z.Phi(),weight);
		histos["NJge3_DPhill_"+skimFilePrefix]->Fill(getdphi(mu[0].p4.Phi(),mu[1].p4.Phi()),weight);
		histos["NJge3_DEtall_"+skimFilePrefix]->Fill(fabs(mu[0].p4.Eta()-mu[1].p4.Eta()),weight);
		histos["NJge3_DRll_"+skimFilePrefix]->Fill(dRbetweenVectors(mu[0].p4,mu[1].p4),weight);
	      } if(nbs==0){
		histos["NB0_ZPt_"+skimFilePrefix]->Fill(Z.Pt(),weight);
		histos["NB0_ZEta_"+skimFilePrefix]->Fill(Z.Eta(),weight);
		histos["NB0_ZPhi_"+skimFilePrefix]->Fill(Z.Phi(),weight);
		histos["NB0_DPhill_"+skimFilePrefix]->Fill(getdphi(mu[0].p4.Phi(),mu[1].p4.Phi()),weight);
		histos["NB0_DEtall_"+skimFilePrefix]->Fill(fabs(mu[0].p4.Eta()-mu[1].p4.Eta()),weight);
		histos["NB0_DRll_"+skimFilePrefix]->Fill(dRbetweenVectors(mu[0].p4,mu[1].p4),weight);
	      } else {
		histos["NBge1_ZPt_"+skimFilePrefix]->Fill(Z.Pt(),weight);
		histos["NBge1_ZEta_"+skimFilePrefix]->Fill(Z.Eta(),weight);
		histos["NBge1_ZPhi_"+skimFilePrefix]->Fill(Z.Phi(),weight);
		histos["NBge1_DPhill_"+skimFilePrefix]->Fill(getdphi(mu[0].p4.Phi(),mu[1].p4.Phi()),weight);
		histos["NBge1_DEtall_"+skimFilePrefix]->Fill(fabs(mu[0].p4.Eta()-mu[1].p4.Eta()),weight);
		histos["NBge1_DRll_"+skimFilePrefix]->Fill(dRbetweenVectors(mu[0].p4,mu[1].p4),weight);
	      } if(HT>100.){
		histos["HTge100_ZPt_"+skimFilePrefix]->Fill(Z.Pt(),weight);
		histos["HTge100_ZEta_"+skimFilePrefix]->Fill(Z.Eta(),weight);
		histos["HTge100_ZPhi_"+skimFilePrefix]->Fill(Z.Phi(),weight);
		histos["HTge100_DPhill_"+skimFilePrefix]->Fill(getdphi(mu[0].p4.Phi(),mu[1].p4.Phi()),weight);
		histos["HTge100_DEtall_"+skimFilePrefix]->Fill(fabs(mu[0].p4.Eta()-mu[1].p4.Eta()),weight);
		histos["HTge100_DRll_"+skimFilePrefix]->Fill(dRbetweenVectors(mu[0].p4,mu[1].p4),weight);
	      } if(HT>150.){
		histos["HTge150_ZPt_"+skimFilePrefix]->Fill(Z.Pt(),weight);
		histos["HTge150_ZEta_"+skimFilePrefix]->Fill(Z.Eta(),weight);
		histos["HTge150_ZPhi_"+skimFilePrefix]->Fill(Z.Phi(),weight);
		histos["HTge150_DPhill_"+skimFilePrefix]->Fill(getdphi(mu[0].p4.Phi(),mu[1].p4.Phi()),weight);
		histos["HTge150_DEtall_"+skimFilePrefix]->Fill(fabs(mu[0].p4.Eta()-mu[1].p4.Eta()),weight);
		histos["HTge150_DRll_"+skimFilePrefix]->Fill(dRbetweenVectors(mu[0].p4,mu[1].p4),weight);
	      } if(p.evt_pfmet>50.){
		histos["METge50_ZPt_"+skimFilePrefix]->Fill(Z.Pt(),weight);
		histos["METge50_ZEta_"+skimFilePrefix]->Fill(Z.Eta(),weight);
		histos["METge50_ZPhi_"+skimFilePrefix]->Fill(Z.Phi(),weight);
		histos["METge50_DPhill_"+skimFilePrefix]->Fill(getdphi(mu[0].p4.Phi(),mu[1].p4.Phi()),weight);
		histos["METge50_DEtall_"+skimFilePrefix]->Fill(fabs(mu[0].p4.Eta()-mu[1].p4.Eta()),weight);
		histos["METge50_DRll_"+skimFilePrefix]->Fill(dRbetweenVectors(mu[0].p4,mu[1].p4),weight);
	      } if(p.evt_pfmet>25.){
		histos["METge25_ZPt_"+skimFilePrefix]->Fill(Z.Pt(),weight);
		histos["METge25_ZEta_"+skimFilePrefix]->Fill(Z.Eta(),weight);
		histos["METge25_ZPhi_"+skimFilePrefix]->Fill(Z.Phi(),weight);
		histos["METge25_DPhill_"+skimFilePrefix]->Fill(getdphi(mu[0].p4.Phi(),mu[1].p4.Phi()),weight);
		histos["METge25_DEtall_"+skimFilePrefix]->Fill(fabs(mu[0].p4.Eta()-mu[1].p4.Eta()),weight);
		histos["METge25_DRll_"+skimFilePrefix]->Fill(dRbetweenVectors(mu[0].p4,mu[1].p4),weight);	
	      }
	      for(unsigned int i = 0; i<mu.size(); ++i){
		float mucharge = 0; if(mu[i].id==13) mucharge = -1; else if(mu[i].id==-13) mucharge = +1; 
		histos["MuPt_"+skimFilePrefix]->Fill(mu[i].p4.Pt(),weight);
		histos["MuEta_"+skimFilePrefix]->Fill(mu[i].p4.Eta(),weight);
		histos["MuPhi_"+skimFilePrefix]->Fill(mu[i].p4.Phi(),weight);
		histos["MuCharge_"+skimFilePrefix]->Fill(mucharge,weight);
		if(njs==0){
		  histos["NJ0_MuPt_"+skimFilePrefix]->Fill(mu[i].p4.Pt(),weight);
		  histos["NJ0_MuEta_"+skimFilePrefix]->Fill(mu[i].p4.Eta(),weight);
		  histos["NJ0_MuPhi_"+skimFilePrefix]->Fill(mu[i].p4.Phi(),weight);
		  histos["NJ0_MuCharge_"+skimFilePrefix]->Fill(mucharge,weight);
		} else if(njs==1){
		  histos["NJ1_MuPt_"+skimFilePrefix]->Fill(mu[i].p4.Pt(),weight);
		  histos["NJ1_MuEta_"+skimFilePrefix]->Fill(mu[i].p4.Eta(),weight);
		  histos["NJ1_MuPhi_"+skimFilePrefix]->Fill(mu[i].p4.Phi(),weight);
		  histos["NJ1_MuCharge_"+skimFilePrefix]->Fill(mucharge,weight);
		} else if(njs==2){
		  histos["NJ2_MuPt_"+skimFilePrefix]->Fill(mu[i].p4.Pt(),weight);
		  histos["NJ2_MuEta_"+skimFilePrefix]->Fill(mu[i].p4.Eta(),weight);
		  histos["NJ2_MuPhi_"+skimFilePrefix]->Fill(mu[i].p4.Phi(),weight);
		  histos["NJ2_MuCharge_"+skimFilePrefix]->Fill(mucharge,weight);
		} else {
		  histos["NJge3_MuPt_"+skimFilePrefix]->Fill(mu[i].p4.Pt(),weight);
		  histos["NJge3_MuEta_"+skimFilePrefix]->Fill(mu[i].p4.Eta(),weight);
		  histos["NJge3_MuPhi_"+skimFilePrefix]->Fill(mu[i].p4.Phi(),weight);
		  histos["NJge3_MuCharge_"+skimFilePrefix]->Fill(mucharge,weight);
		} if(nbs==0){
		  histos["NB0_MuPt_"+skimFilePrefix]->Fill(mu[i].p4.Pt(),weight);
		  histos["NB0_MuEta_"+skimFilePrefix]->Fill(mu[i].p4.Eta(),weight);
		  histos["NB0_MuPhi_"+skimFilePrefix]->Fill(mu[i].p4.Phi(),weight);
		  histos["NB0_MuCharge_"+skimFilePrefix]->Fill(mucharge,weight);
		} else {
		  histos["NBge1_MuPt_"+skimFilePrefix]->Fill(mu[i].p4.Pt(),weight);
		  histos["NBge1_MuEta_"+skimFilePrefix]->Fill(mu[i].p4.Eta(),weight);
		  histos["NBge1_MuPhi_"+skimFilePrefix]->Fill(mu[i].p4.Phi(),weight);
		  histos["NBge1_MuCharge_"+skimFilePrefix]->Fill(mucharge,weight);
		} if(HT>100.){
		  histos["HTge100_MuPt_"+skimFilePrefix]->Fill(mu[i].p4.Pt(),weight);
		  histos["HTge100_MuEta_"+skimFilePrefix]->Fill(mu[i].p4.Eta(),weight);
		  histos["HTge100_MuPhi_"+skimFilePrefix]->Fill(mu[i].p4.Phi(),weight);
		  histos["HTge100_MuCharge_"+skimFilePrefix]->Fill(mucharge,weight);
		} if(HT>150.){
		  histos["HTge150_MuPt_"+skimFilePrefix]->Fill(mu[i].p4.Pt(),weight);
		  histos["HTge150_MuEta_"+skimFilePrefix]->Fill(mu[i].p4.Eta(),weight);
		  histos["HTge150_MuPhi_"+skimFilePrefix]->Fill(mu[i].p4.Phi(),weight);
		  histos["HTge150_MuCharge_"+skimFilePrefix]->Fill(mucharge,weight);
		} if(p.evt_pfmet>50.){
		  histos["METge50_MuPt_"+skimFilePrefix]->Fill(mu[i].p4.Pt(),weight);
		  histos["METge50_MuEta_"+skimFilePrefix]->Fill(mu[i].p4.Eta(),weight);
		  histos["METge50_MuPhi_"+skimFilePrefix]->Fill(mu[i].p4.Phi(),weight);
		  histos["METge50_MuCharge_"+skimFilePrefix]->Fill(mucharge,weight);
		} if(p.evt_pfmet>25.){
		  histos["METge25_MuPt_"+skimFilePrefix]->Fill(mu[i].p4.Pt(),weight);
		  histos["METge25_MuEta_"+skimFilePrefix]->Fill(mu[i].p4.Eta(),weight);
		  histos["METge25_MuPhi_"+skimFilePrefix]->Fill(mu[i].p4.Phi(),weight);
		  histos["METge25_MuCharge_"+skimFilePrefix]->Fill(mucharge,weight);
		}
	      }
	    }
	  }
	  if((triggerbool1mu||triggerbool2mu)&& mu[0].passes_POG_tightID&&mu[1].passes_POG_tightID&&fabs(mu[0].dZ)<0.1&&fabs(mu[1].dZ)<0.1&&fabs(mu[0].dxyPV)<0.02&&fabs(mu[1].dxyPV)<0.02){
	    if(Z.M()>75.&&Z.M()<105){
	      for(unsigned int i = 0; i<mu.size(); ++i){
		histos["MuRelIso03_"+skimFilePrefix]->Fill(mu[i].RelIso03,weight);
		histos["MuRelIso03EA_"+skimFilePrefix]->Fill(mu[i].RelIso03EA,weight);
		histos["MuRelIso03DB_"+skimFilePrefix]->Fill(mu[i].RelIso03DB,weight);
		histos["MuMiniIsoEA_"+skimFilePrefix]->Fill(mu[i].miniiso,weight);
		histos["MuMiniIsoDB_"+skimFilePrefix]->Fill(mu[i].miniisoDB,weight);
		histos["MuRelIso04_"+skimFilePrefix]->Fill(mu[i].reliso04,weight);
		histos["MuAnnulus04_"+skimFilePrefix]->Fill(mu[i].annulus04,weight);
		if(mu[0].mt>30&&mu[0].mt>30){
		  histos["MuRelIso03_MT30_"+skimFilePrefix]->Fill(mu[i].RelIso03,weight);
		  histos["MuRelIso03EA_MT30_"+skimFilePrefix]->Fill(mu[i].RelIso03EA,weight);
		  histos["MuRelIso03DB_MT30_"+skimFilePrefix]->Fill(mu[i].RelIso03DB,weight);
		  histos["MuMiniIsoEA_MT30_"+skimFilePrefix]->Fill(mu[i].miniiso,weight);
		  histos["MuMiniIsoDB_MT30_"+skimFilePrefix]->Fill(mu[i].miniisoDB,weight);
		  histos["MuRelIso04_MT30_"+skimFilePrefix]->Fill(mu[i].reliso04,weight);
		  histos["MuAnnulus04_MT30_"+skimFilePrefix]->Fill(mu[i].annulus04,weight);
		}
	      }
	    }
	  }
	  if((triggerbool1mu||triggerbool2mu)&& mu[0].passes_POG_tightID&&mu[1].passes_POG_tightID&&mu[0].miniisoDB<0.2&&mu[1].miniisoDB<0.2){
	    if(Z.M()>75.&&Z.M()<105){
	      for(unsigned int i = 0; i<mu.size(); ++i){
		histos["Mud0_"+skimFilePrefix]->Fill(mu[i].dxyPV,weight);
		histos["MudZ_"+skimFilePrefix]->Fill(mu[i].dZ,weight);
		histos["MuIP3d_"+skimFilePrefix]->Fill(mu[i].ip3d,weight);
	      }
	    }
	  }
	  if((triggerbool1mu||triggerbool2mu)&& mu[0].passes_POG_looseID&&mu[1].passes_POG_looseID&&mu[0].miniisoDB<0.2&&mu[1].miniisoDB<0.2&&
	      fabs(mu[0].dZ)<0.1&&fabs(mu[1].dZ)<0.1&&fabs(mu[0].dxyPV)<0.02&&fabs(mu[1].dxyPV)<0.02){
	    if(Z.M()>75.&&Z.M()<105){
	      for(unsigned int i = 0; i<mu.size(); ++i){
		if(mu[i].passes_POG_tightID) histos["MuID_"+skimFilePrefix]->Fill(3.,weight);
		else if(mu[i].passes_POG_mediumID) histos["MuID_"+skimFilePrefix]->Fill(2.,weight);
		else if(mu[i].passes_POG_looseID) histos["MuID_"+skimFilePrefix]->Fill(1.,weight);
		histos["MuvalidFraction_"+skimFilePrefix]->Fill((float)mu[i].validHits/((float)(mu[i].validHits+mu[i].lostHits+mu[i].exp_innerlayers+mu[i].exp_outerlayers)),weight);
		if(mu[i].gfit_ndof>0) histos["Mugfit_normchi2_"+skimFilePrefix]->Fill(mu[i].gfit_chi2/mu[i].gfit_ndof, weight);
		histos["Mugfit_validSTAHits_"+skimFilePrefix]->Fill(mu[i].gfit_validSTAHits,weight);
		histos["MunumberOfMatchedStations_"+skimFilePrefix]->Fill(mu[i].numberOfMatchedStations,weight);
		histos["MuvalidPixelHits_"+skimFilePrefix]->Fill(mu[i].validPixelHits,weight);
		histos["Munlayers_"+skimFilePrefix]->Fill(mu[i].nlayers,weight);
		histos["Muchi2LocalPosition_"+skimFilePrefix]->Fill(mu[i].chi2LocalPosition,weight);
		histos["MutrkKink_"+skimFilePrefix]->Fill(mu[i].trkKink,weight);
		histos["MusegmCompatibility_"+skimFilePrefix]->Fill(mu[i].segmCompatibility,weight);
	      }
	    }
	  }
	}//2 muons
	else if(mu.size()==1){
	  triggerbool1mu = triggerbool1mu&&((mu[0].p4.Pt()>30.&&fabs(mu[0].p4.Eta())<2.1));//one muon passing nominal trigger w/o iso
	  if(triggerbool1mu&&mu[0].passes_POG_tightID&&mu[0].miniisoDB<0.2&&fabs(mu[0].dZ)<0.1&&fabs(mu[0].dxyPV)<0.02&&mu[0].mt>40){//1 mu events.
	    float mucharge = 0; if(mu[0].id==13) mucharge = -1; else if(mu[0].id==-13) mucharge = +1; 
	    histos["MT_"+skimFilePrefix]->Fill(mu[0].mt,weight);
	    histos["MyMuPt_"+skimFilePrefix]->Fill(mu[0].p4.Pt(),weight);
	    histos["MyMuEta_"+skimFilePrefix]->Fill(mu[0].p4.Eta(),weight);
	    histos["MyMuPhi_"+skimFilePrefix]->Fill(mu[0].p4.Phi(),weight);
	    histos["MyMuCharge_"+skimFilePrefix]->Fill(mucharge,weight);
	    if(njs==0){
	      histos["NJ0_MT_"+skimFilePrefix]->Fill(mu[0].mt,weight);
	      histos["NJ0_MyMuPt_"+skimFilePrefix]->Fill(mu[0].p4.Pt(),weight);
	      histos["NJ0_MyMuEta_"+skimFilePrefix]->Fill(mu[0].p4.Eta(),weight);
	      histos["NJ0_MyMuPhi_"+skimFilePrefix]->Fill(mu[0].p4.Phi(),weight);
	      histos["NJ0_MyMuCharge_"+skimFilePrefix]->Fill(mucharge,weight);
	    } else if(njs==1){
	      histos["NJ1_MT_"+skimFilePrefix]->Fill(mu[0].mt,weight);
	      histos["NJ1_MyMuPt_"+skimFilePrefix]->Fill(mu[0].p4.Pt(),weight);
	      histos["NJ1_MyMuEta_"+skimFilePrefix]->Fill(mu[0].p4.Eta(),weight);
	      histos["NJ1_MyMuPhi_"+skimFilePrefix]->Fill(mu[0].p4.Phi(),weight);
	      histos["NJ1_MyMuCharge_"+skimFilePrefix]->Fill(mucharge,weight);	      
	    } else if(njs==2){
	      histos["NJ2_MT_"+skimFilePrefix]->Fill(mu[0].mt,weight);
	      histos["NJ2_MyMuPt_"+skimFilePrefix]->Fill(mu[0].p4.Pt(),weight);
	      histos["NJ2_MyMuEta_"+skimFilePrefix]->Fill(mu[0].p4.Eta(),weight);
	      histos["NJ2_MyMuPhi_"+skimFilePrefix]->Fill(mu[0].p4.Phi(),weight);
	      histos["NJ2_MyMuCharge_"+skimFilePrefix]->Fill(mucharge,weight);	      
	    } else {
	      histos["NJge3_MT_"+skimFilePrefix]->Fill(mu[0].mt,weight);
	      histos["NJge3_MyMuPt_"+skimFilePrefix]->Fill(mu[0].p4.Pt(),weight);
	      histos["NJge3_MyMuEta_"+skimFilePrefix]->Fill(mu[0].p4.Eta(),weight);
	      histos["NJge3_MyMuPhi_"+skimFilePrefix]->Fill(mu[0].p4.Phi(),weight);
	      histos["NJge3_MyMuCharge_"+skimFilePrefix]->Fill(mucharge,weight);	      
	    } if(nbs==0){
	      histos["NB0_MT_"+skimFilePrefix]->Fill(mu[0].mt,weight);
	      histos["NB0_MyMuPt_"+skimFilePrefix]->Fill(mu[0].p4.Pt(),weight);
	      histos["NB0_MyMuEta_"+skimFilePrefix]->Fill(mu[0].p4.Eta(),weight);
	      histos["NB0_MyMuPhi_"+skimFilePrefix]->Fill(mu[0].p4.Phi(),weight);
	      histos["NB0_MyMuCharge_"+skimFilePrefix]->Fill(mucharge,weight);	      
	    } else {
	      histos["NBge1_MT_"+skimFilePrefix]->Fill(mu[0].mt,weight);
	      histos["NBge1_MyMuPt_"+skimFilePrefix]->Fill(mu[0].p4.Pt(),weight);
	      histos["NBge1_MyMuEta_"+skimFilePrefix]->Fill(mu[0].p4.Eta(),weight);
	      histos["NBge1_MyMuPhi_"+skimFilePrefix]->Fill(mu[0].p4.Phi(),weight);
	      histos["NBge1_MyMuCharge_"+skimFilePrefix]->Fill(mucharge,weight);	      
	    } if(HT>100.){
	      histos["HTge100_MT_"+skimFilePrefix]->Fill(mu[0].mt,weight);
	      histos["HTge100_MyMuPt_"+skimFilePrefix]->Fill(mu[0].p4.Pt(),weight);
	      histos["HTge100_MyMuEta_"+skimFilePrefix]->Fill(mu[0].p4.Eta(),weight);
	      histos["HTge100_MyMuPhi_"+skimFilePrefix]->Fill(mu[0].p4.Phi(),weight);
	      histos["HTge100_MyMuCharge_"+skimFilePrefix]->Fill(mucharge,weight);	      
	    } if(HT>150.){
	      histos["HTge150_MT_"+skimFilePrefix]->Fill(mu[0].mt,weight);
	      histos["HTge150_MyMuPt_"+skimFilePrefix]->Fill(mu[0].p4.Pt(),weight);
	      histos["HTge150_MyMuEta_"+skimFilePrefix]->Fill(mu[0].p4.Eta(),weight);
	      histos["HTge150_MyMuPhi_"+skimFilePrefix]->Fill(mu[0].p4.Phi(),weight);
	      histos["HTge150_MyMuCharge_"+skimFilePrefix]->Fill(mucharge,weight);	      
	    } if(p.evt_pfmet>50.){
	      histos["METge50_MT_"+skimFilePrefix]->Fill(mu[0].mt,weight);
	      histos["METge50_MyMuPt_"+skimFilePrefix]->Fill(mu[0].p4.Pt(),weight);
	      histos["METge50_MyMuEta_"+skimFilePrefix]->Fill(mu[0].p4.Eta(),weight);
	      histos["METge50_MyMuPhi_"+skimFilePrefix]->Fill(mu[0].p4.Phi(),weight);
	      histos["METge50_MyMuCharge_"+skimFilePrefix]->Fill(mucharge,weight);	      
	    } if(p.evt_pfmet>25.){
	      histos["METge25_MT_"+skimFilePrefix]->Fill(mu[0].mt,weight);
	      histos["METge25_MyMuPt_"+skimFilePrefix]->Fill(mu[0].p4.Pt(),weight);
	      histos["METge25_MyMuEta_"+skimFilePrefix]->Fill(mu[0].p4.Eta(),weight);
	      histos["METge25_MyMuPhi_"+skimFilePrefix]->Fill(mu[0].p4.Phi(),weight);
	      histos["METge25_MyMuCharge_"+skimFilePrefix]->Fill(mucharge,weight);	      
	    }
	  }
	}
      }
      if(!sameEvent(p,c)){
	//finally start new event.
	if(abs(p.id)==13&&p.passes_POG_tightID&&p.miniisoDB<0.2&&fabs(p.dZ)<0.1&&fabs(p.dxyPV)<0.02&&p.dilep_mass>75.&&p.dilep_mass<105&&p.p4.Pt()>20&&fabs(p.p4.Eta())<2.1) {
	  if((p.evt_isRealData&&(p.HLT_Mu17_TrkIsoVVL_Mu8_TrkIsoVVL_DZ || p.HLT_Mu17_TrkIsoVVL_TkMu8_TrkIsoVVL_DZ || p.HLT_IsoMu24_eta2p1 || p.HLT_IsoTkMu24_eta2p1 || p.HLT_IsoMu27 || p.HLT_IsoTkMu27 || p.HLT_IsoMu20 || p.HLT_IsoMu20))||(!p.evt_isRealData)){
	    histos["Z_Pt_"+skimFilePrefix]->Fill(p.dilep_p4.Pt(),weight);
	  }
	}
	mu.clear();
	nleps = 1;
      }
      if(currentrun!=c.evt_run) { cout << "This is run " << c.evt_run << endl; currentrun = c.evt_run; }
      bool skip = false;
      //if(c.evt_run!=251244&&c.evt_run!=251251&&c.evt_run!=251252) skip = true;
      if(abs(c.id)!=13) skip = true;
      else if(c.p4.Pt()<20.) skip = true;
      else if(fabs(c.p4.Eta())>2.1) skip = true;
      else if(!c.passes_POG_looseID) skip = true;
      //else if(fabs(c.dZ)>0.5) skip = true;
      //else if(fabs(c.dxyPV)>0.2) skip = true;
      //else if(c.miniisoDB>0.5) skip = true;
      if(!skip) { mu.push_back(c); }
      p = c;
      resetEvent(c);
    }
  
    // Clean Up
    delete tree;
    file->Close();
    delete file;
  }
  if ( nEventsChain != nEventsTotal ) {
    cout << Form( "ERROR: number of events from files (%d) is not equal to total number of events (%d)", nEventsChain, nEventsTotal ) << endl;
  }
  
  // Example Histograms
  for(map<string,TH1F*>::iterator h=histos.begin(); h!=histos.end();++h){
    h->second->SetBinContent(h->second->GetNbinsX(), h->second->GetBinContent(h->second->GetNbinsX() )+ h->second->GetBinContent(h->second->GetNbinsX()+1) );
    h->second->SetBinError(h->second->GetNbinsX(), sqrt(pow(h->second->GetBinError(h->second->GetNbinsX() ),2)+pow(h->second->GetBinError(h->second->GetNbinsX()+1),2) ) );
  }
  for(map<string,TH1F*>::iterator h=histos.begin(); h!=histos.end();++h){
    h->second->SetBinContent(1, h->second->GetBinContent(1 )+ h->second->GetBinContent(0) );
    h->second->SetBinError(1, sqrt(pow(h->second->GetBinError(1 ),2)+pow(h->second->GetBinError(0),2) ) );
  }
  //string filename = "rootfiles/test/Histos_"+skimFilePrefix+".root";
  string filename = "rootfiles/first_20150727/Histos3_"+skimFilePrefix+".root";
  if(DCSonly) filename = "rootfiles/first_20150727/Histos3DCS_"+skimFilePrefix+".root";
  TFile *f = new TFile(filename.c_str(),"RECREATE");
  f->cd();
  for(map<string,TH1F*>::iterator h=    histos.begin(); h!=    histos.end();++h) h->second->Write();
  f->Close();
  cout << "Saved histos in " << f->GetName() << endl;  
  // return
  bmark->Stop("benchmark");
  cout << endl;
  cout << nEventsTotal << " Events Processed" << endl;
  cout << "------------------------------" << endl;
  cout << "CPU  Time:	" << Form( "%.01f", bmark->GetCpuTime("benchmark")  ) << endl;
  cout << "Real Time:	" << Form( "%.01f", bmark->GetRealTime("benchmark") ) << endl;
  cout << endl;
  delete bmark;
  return 0;
}
Example #5
0
void makeVictorTemplates::ScanChain (TChain* chain){

  
  int npass = 0;
  bookHistos();
  
  TObjArray *listOfFiles = chain->GetListOfFiles();

  unsigned int nEventsChain = 0;

  unsigned int nEvents = chain->GetEntries();
  nEventsChain = nEvents;
  unsigned int nEventsTotal = 0;

  if(debug) cout << "Begin file loop" << endl;

  // file loop
  TIter fileIter(listOfFiles);

  TFile* currentFile = 0;

  while ((currentFile = (TFile*)fileIter.Next())){

    TFile f(currentFile->GetTitle());
    TTree *tree = (TTree*)f.Get("jetTree");
    //cms2.Init(tree);
    setBranches(tree);

    // event loop
    //unsigned int nEvents = tree->GetEntries();
    nEvents = tree->GetEntries();

    for (unsigned int event = 0 ; event < nEvents; ++event){
   
      tree->GetEntry(event);
      ++nEventsTotal;

      // progress feedback to user
      if (nEventsTotal % 1000 == 0){
            
        // xterm magic from L. Vacavant and A. Cerri
        if (isatty(1)){
                
          printf("\015\033[32m ---> \033[1m\033[31m%4.1f%%"
                 "\033[0m\033[32m <---\033[0m\015", (float)nEventsTotal/(nEventsChain*0.01));
          fflush(stdout);
        }
      }

      if( nJets_ < 2 )        continue;
      if( maxjetpt_ < 30. )   continue;

      int iJetBin          = getJetBin( nJets_ );
      int iSumJetPtBin     = getSumJetPtBin( sumJetPt_ );
      //int iBosonPtBin      = getBosonPtBin( etg_ );
      int iVtxBin          = getVtxBin( nvtx_ );
      float templateWeight = 1;//jet15U_L1Prescale_ * jet15U_HLTPrescale_;

      //fill templates binned by njets, sumjetpt, boson pt        
      //fillUnderOverFlow( tcmetTemplate[ iJetBin ][ iSumJetPtBin ][ iBosonPtBin ]    ,  tcmet_    , templateWeight );
      //fillUnderOverFlow( pfmetTemplate[ iJetBin ][ iSumJetPtBin ][ iBosonPtBin ]    ,  pfmet_    , templateWeight );
      
      //fill templates binned by njets, sumjetpt, nVtx
      fillUnderOverFlow( tcmetTemplate_njets_ht_nvtx[ iJetBin ][ iSumJetPtBin ][ iVtxBin ]    ,  tcmet_    , templateWeight );
      fillUnderOverFlow( pfmetTemplate_njets_ht_nvtx[ iJetBin ][ iSumJetPtBin ][ iVtxBin ]    ,  pfmet_    , templateWeight );
    
      //fill templates binned by njets, sumjetpt
      fillUnderOverFlow( tcmetTemplate_combined[ iJetBin ][ iSumJetPtBin ]    ,  tcmet_    , templateWeight );
      fillUnderOverFlow( pfmetTemplate_combined[ iJetBin ][ iSumJetPtBin ]    ,  pfmet_    , templateWeight );
      
      ++npass;

      int iTrigBin = -1;

      if( firedJet15U_ == 1 ){
        
        templateWeight = jet15U_L1Prescale_ * jet15U_HLTPrescale_;
        iTrigBin = 0;

        fillUnderOverFlow( tcmetTemplate_qcd[ iTrigBin ][ iJetBin ][ iSumJetPtBin ]    ,  tcmet_    , templateWeight );
        fillUnderOverFlow( pfmetTemplate_qcd[ iTrigBin ][ iJetBin ][ iSumJetPtBin ]    ,  pfmet_    , templateWeight );

        fillUnderOverFlow( hleadJetPt15 , maxjetpt_ , templateWeight );
      }

      if( firedJet30U_ == 1 ){
        
        templateWeight = jet30U_L1Prescale_ * jet30U_HLTPrescale_;
        iTrigBin = 1;

        fillUnderOverFlow( tcmetTemplate_qcd[ iTrigBin ][ iJetBin ][ iSumJetPtBin ]    ,  tcmet_    , templateWeight );
        fillUnderOverFlow( pfmetTemplate_qcd[ iTrigBin ][ iJetBin ][ iSumJetPtBin ]    ,  pfmet_    , templateWeight );

        fillUnderOverFlow( hleadJetPt30 , maxjetpt_ , templateWeight );
      }
      
      if( firedJet50U_ == 1 ){
        
        templateWeight = jet50U_L1Prescale_ * jet50U_HLTPrescale_;
        iTrigBin = 2;

        fillUnderOverFlow( tcmetTemplate_qcd[ iTrigBin ][ iJetBin ][ iSumJetPtBin ]    ,  tcmet_    , templateWeight );
        fillUnderOverFlow( pfmetTemplate_qcd[ iTrigBin ][ iJetBin ][ iSumJetPtBin ]    ,  pfmet_    , templateWeight );

        fillUnderOverFlow( hleadJetPt50 , maxjetpt_ , templateWeight );
      }

      if( firedJet100U_ == 1 ){
        
        templateWeight = jet100U_L1Prescale_ * jet100U_HLTPrescale_;
        iTrigBin = 3;

        fillUnderOverFlow( tcmetTemplate_qcd[ iTrigBin ][ iJetBin ][ iSumJetPtBin ]    ,  tcmet_    , templateWeight );
        fillUnderOverFlow( pfmetTemplate_qcd[ iTrigBin ][ iJetBin ][ iSumJetPtBin ]    ,  pfmet_    , templateWeight );

        fillUnderOverFlow( hleadJetPt100 , maxjetpt_ , templateWeight );
      }


    } // end loop over events
  } // end loop over files
      
  cout << npass << " events passing selection" << endl;
  if (nEventsChain != nEventsTotal)
    std::cout << "ERROR: number of events from files is not equal to total number of events" << std::endl;
 

    
    for( int iJetBin = 0 ; iJetBin < nJetBins ; iJetBin++ ){
      for( int iSumJetPtBin = 0 ; iSumJetPtBin < nSumJetPtBins ; iSumJetPtBin++ ){
        for( int iBosonPtBin = 0 ; iBosonPtBin < nBosonPtBins ; iBosonPtBin++ ){
          
          float scale = tcmetTemplate[ iJetBin ][ iSumJetPtBin ][ iBosonPtBin ] -> Integral();
          if( scale > 0 )  tcmetTemplate[ iJetBin ][ iSumJetPtBin ][ iBosonPtBin ] -> Scale ( 1. / scale );
          
          scale = pfmetTemplate[ iJetBin ][ iSumJetPtBin ][ iBosonPtBin ] -> Integral();
          if( scale > 0 )  pfmetTemplate[ iJetBin ][ iSumJetPtBin ][ iBosonPtBin ] -> Scale ( 1. / scale );
          
        }
      }
    }

    for( int iJetBin = 0 ; iJetBin < nJetBins ; iJetBin++ ){
      for( int iSumJetPtBin = 0 ; iSumJetPtBin < nSumJetPtBins ; iSumJetPtBin++ ){
        for( int iVtxBin = 0 ; iVtxBin < nVtxBins ; iVtxBin++ ){
          
          float scale = tcmetTemplate_njets_ht_nvtx[ iJetBin ][ iSumJetPtBin ][ iVtxBin ] -> Integral();
          if( scale > 0 )  tcmetTemplate_njets_ht_nvtx[ iJetBin ][ iSumJetPtBin ][ iVtxBin ] -> Scale ( 1. / scale );
          
          scale = pfmetTemplate_njets_ht_nvtx[ iJetBin ][ iSumJetPtBin ][ iVtxBin ] -> Integral();
          if( scale > 0 )  pfmetTemplate_njets_ht_nvtx[ iJetBin ][ iSumJetPtBin ][ iVtxBin ] -> Scale ( 1. / scale );
          
        }
      }
    }

    for( int iJetBin = 0 ; iJetBin < nJetBins ; iJetBin++ ){
      for( int iSumJetPtBin = 0 ; iSumJetPtBin < nSumJetPtBins ; iSumJetPtBin++ ){
        
        float scale = tcmetTemplate_combined[ iJetBin ][ iSumJetPtBin ] -> Integral();
        if( scale > 0 )  tcmetTemplate_combined[ iJetBin ][ iSumJetPtBin ] -> Scale ( 1. / scale );
      
        scale = pfmetTemplate_combined[ iJetBin ][ iSumJetPtBin ] -> Integral();
        if( scale > 0 )  pfmetTemplate_combined[ iJetBin ][ iSumJetPtBin ] -> Scale ( 1. / scale );
        
        
      }
    }

    for( int iTrigBin = 0 ; iTrigBin < 4 ; ++iTrigBin ){
      for( int iJetBin = 0 ; iJetBin < nJetBins ; iJetBin++ ){
        for( int iSumJetPtBin = 0 ; iSumJetPtBin < nSumJetPtBins ; iSumJetPtBin++ ){
          
          float scale = tcmetTemplate_qcd[ iTrigBin ][ iJetBin ][ iSumJetPtBin ] -> Integral();
          if( scale > 0 )  tcmetTemplate_qcd[ iTrigBin ][ iJetBin ][ iSumJetPtBin ] -> Scale ( 1. / scale );
          
          scale = pfmetTemplate_qcd[ iTrigBin ][ iJetBin ][ iSumJetPtBin ] -> Integral();
          if( scale > 0 )  pfmetTemplate_qcd[ iTrigBin ][ iJetBin ][ iSumJetPtBin ] -> Scale ( 1. / scale );
          
        }
      }
    }


    // make histos rootfile
    TDirectory *rootdir = gDirectory->GetDirectory("Rint:");
    rootdir->cd();
    saveHist("qcd-mini-ntuple/victor_templates_2.root");
    deleteHistos();
  
} // end ScanChain
Example #6
0
int looperCR2lep( analysis* myAnalysis, sample* mySample, int nEvents = -1, bool fast = true) {

	// Benchmark
	TBenchmark *bmark = new TBenchmark();
	bmark->Start("benchmark");

	// Setup
	TChain *chain = mySample->GetChain();
	TString sampleName = mySample->GetLabel();
	const int nSigRegs = myAnalysis->GetSigRegionsAll().size();
	const int nVariations = mySample->IsData() ? 0 : myAnalysis->GetSystematics(false).size();
	bool isFastsim = mySample->IsSignal();
	cout << "\nSample: " << sampleName.Data() << " (CR2L";
	if(      myContext.GetJesDir() == contextVars::kUp )   cout << ", JES up";
	else if( myContext.GetJesDir() == contextVars::kDown ) cout << ", JES down";
	cout << ")" << endl;

	myContext.SetUseRl( true );

	/////////////////////////////////////////////////////////
	// Histograms
	TDirectory *rootdir = gDirectory->GetDirectory("Rint:");  // Use TDirectories to assist in memory management
	TDirectory *histdir = new TDirectory( "histdir", "histdir", "", rootdir );
	TDirectory *systdir = new TDirectory( "systdir", "systdir", "", rootdir );
	TDirectory *zerodir = new TDirectory( "zerodir", "zerodir", "", rootdir );

	TH1::SetDefaultSumw2();

	TH1D* h_bkgtype_sum[nSigRegs][nVariations+1];
	TH1D* h_evttype_sum[nSigRegs][nVariations+1];
	TH2D* h_sigyields[nSigRegs][nVariations+1];

	TH1D* h_bkgtype[nSigRegs][nVariations+1]; // per-file versions for zeroing
	TH1D* h_evttype[nSigRegs][nVariations+1];

	TH1D *h_mt[nSigRegs];
	TH1D *h_met[nSigRegs];
	TH1D *h_mt2w[nSigRegs];
	TH1D *h_chi2[nSigRegs];
	TH1D *h_htratio[nSigRegs];
	TH1D *h_mindphi[nSigRegs];
	TH1D *h_ptb1[nSigRegs];
	TH1D *h_drlb1[nSigRegs];
	TH1D *h_ptlep[nSigRegs];
	TH1D *h_metht[nSigRegs];
	TH1D *h_dphilw[nSigRegs];
	TH1D *h_njets[nSigRegs];
	TH1D *h_nbtags[nSigRegs];
	TH1D *h_ptj1[nSigRegs];
	TH1D *h_j1btag[nSigRegs];
	TH1D *h_modtop[nSigRegs];
	TH1D *h_dphilmet[nSigRegs];
	TH1D *h_mlb[nSigRegs];

	vector<TString> regNames = myAnalysis->GetSigRegionLabelsAll();
	vector<sigRegion*> sigRegions = myAnalysis->GetSigRegionsAll();
	vector<systematic*> variations = myAnalysis->GetSystematics(false);

	for( int i=0; i<nSigRegs; i++ ) {

		TString plotLabel = sampleName + "_" + regNames.at(i);
		systdir->cd();

		for( int j=1; j<=nVariations; j++ ) {
			TString varName = variations.at(j-1)->GetNameLong();
			h_bkgtype_sum[i][j] = new TH1D( "bkgtype_" + plotLabel + "_" + varName, "Yield by background type",  5, 0.5, 5.5);
			h_evttype_sum[i][j] = new TH1D( "evttype_" + regNames.at(i) + "_" + varName, "Yield by event type",  6, 0.5, 6.5);
			h_sigyields[i][j] = new TH2D( "sigyields_" + regNames.at(i) + "_" + varName, "Signal yields by mass point", 37,99,1024, 19,-1,474 );
		}

		histdir->cd();

		h_bkgtype_sum[i][0] = new TH1D( "bkgtype_" + plotLabel, "Yield by background type",  5, 0.5, 5.5);
		h_evttype_sum[i][0] = new TH1D( "evttype_" + regNames.at(i), "Yield by event type",  6, 0.5, 6.5);
		h_sigyields[i][0] = new TH2D( "sigyields_" + regNames.at(i), "Signal yields by mass point", 37,99,1024, 19,-1,474 );

		h_mt[i]       = new TH1D(  "mt_"      + plotLabel, "Transverse mass",          80, 0, 800);
		h_met[i]      = new TH1D(  "met_"     + plotLabel, "MET",                      40, 0, 1000);
		h_mt2w[i]     = new TH1D(  "mt2w_"    + plotLabel, "MT2W",                     50, 0, 500);
		h_chi2[i]     = new TH1D(  "chi2_"    + plotLabel, "Hadronic #chi^{2}",        50, 0, 15);
		h_htratio[i]  = new TH1D(  "htratio_" + plotLabel, "H_{T} ratio",              50, 0, 1);
		h_mindphi[i]  = new TH1D(  "mindphi_" + plotLabel, "min #Delta#phi(j12,MET)",  63, 0, 3.15);
		h_ptb1[i]     = new TH1D(  "ptb1_"    + plotLabel, "p_{T} (b1)",               50, 0, 500);
		h_drlb1[i]    = new TH1D(  "drlb1_"   + plotLabel, "#DeltaR (lep, b1)",        50, 0, 5);
		h_ptlep[i]    = new TH1D(  "ptlep_"   + plotLabel, "p_{T} (lep)",              50, 0, 500);
		h_metht[i]    = new TH1D(  "metht_"   + plotLabel, "MET/sqrt(HT)",             50, 0, 100);
		h_dphilw[i]   = new TH1D(  "dphilw_"  + plotLabel, "#Delta#phi (lep,W)",       63, 0, 3.15);
		h_njets[i]    = new TH1D(  "njets_"   + plotLabel, "Number of jets",           16, -0.5, 15.5);
		h_nbtags[i]   = new TH1D(  "nbtags_"  + plotLabel, "Number of b-tags",          7, -0.5, 6.5);
		h_ptj1[i]     = new TH1D(  "ptj1_"    + plotLabel, "Leading jet p_{T}",        40, 0, 1000);
		h_j1btag[i]   = new TH1D(  "j1btag_"  + plotLabel, "Is leading jet b-tagged?",  2, -0.5, 1.5);
		h_modtop[i]   = new TH1D(  "modtop_"  + plotLabel, "Modified topness",         30, -15., 15.);
		h_dphilmet[i] = new TH1D(  "dphilmet_"+ plotLabel, "#Delta#phi (lep1, MET)",   63, 0., 3.15);
		h_mlb[i]      = new TH1D(  "mlb_"     + plotLabel, "M_{lb}",                   50, 0., 500.);


		for( int j=0; j<=nVariations; j++ ) {

			TAxis* axis = h_bkgtype_sum[i][j]->GetXaxis();
			axis->SetBinLabel( 1, "2+lep" );
			axis->SetBinLabel( 2, "1lepW" );
			axis->SetBinLabel( 3, "1lepTop" );
			axis->SetBinLabel( 4, "ZtoNuNu" );
			axis->SetBinLabel( 5, "Other" );

			axis = h_evttype_sum[i][j]->GetXaxis();
			axis->SetBinLabel( 1, "Data" );
			axis->SetBinLabel( 2, "Signals" );
			axis->SetBinLabel( 3, "2+lep" );
			axis->SetBinLabel( 4, "1lepW" );
			axis->SetBinLabel( 5, "1lepTop" );
			axis->SetBinLabel( 6, "ZtoNuNu" );
		}

	}

	TH1D *h_yields_sum = new TH1D( Form("srYields_%s", sampleName.Data()), "Yield by signal region", nSigRegs, 0.5, float(nSigRegs)+0.5);
	for( int i=0; i<nSigRegs; i++ ) h_yields_sum->GetXaxis()->SetBinLabel( i+1, regNames.at(i) );

	// Set up copies of histograms, in order to zero out negative yields
	zerodir->cd();
	TH1D* h_yields = (TH1D*)h_yields_sum->Clone( "tmp_" + TString(h_yields_sum->GetName()) );

	for( int i=0; i<nSigRegs; i++ ) {
		for( int j=0; j<=nVariations; j++ ) {
			h_bkgtype[i][j] = (TH1D*)h_bkgtype_sum[i][j]->Clone( "tmp_" + TString(h_bkgtype_sum[i][j]->GetName()) );
			h_evttype[i][j] = (TH1D*)h_evttype_sum[i][j]->Clone( "tmp_" + TString(h_evttype_sum[i][j]->GetName()) );
		}
	}

	// Set up cutflow variables
	double yield_total = 0;
	double yield_unique = 0;
	double yield_filter = 0;
	double yield_vtx = 0;
	double yield_1goodlep = 0;
	double yield_lepSel = 0;
	double yield_2lepveto = 0;
	double yield_trkVeto = 0;
	double yield_2lepCR = 0;
	double yield_tauVeto = 0;
	double yield_njets = 0;
	double yield_1bjet = 0;
	double yield_METcut = 0;
	double yield_MTcut = 0;
	double yield_dPhi = 0;
	double yield_chi2 = 0;

	int yGen_total = 0;
	int yGen_unique = 0;
	int yGen_filter = 0;
	int yGen_vtx = 0;
	int yGen_1goodlep = 0;
	int yGen_lepSel = 0;
	int yGen_2lepveto = 0;
	int yGen_trkVeto = 0;
	int yGen_tauVeto = 0;
	int yGen_2lepCR = 0;
	int yGen_njets = 0;
	int yGen_1bjet = 0;
	int yGen_METcut = 0;
	int yGen_MTcut = 0;
	int yGen_dPhi = 0;
	int yGen_chi2 = 0;

	////////////////////////////////////////////////////////////////////
	// Set up data-specific filters

	if( mySample->IsData() ) {
		set_goodrun_file_json( "reference-files/Cert_271036-284044_13TeV_23Sep2016ReReco_Collisions16_JSON.txt" );
		duplicate_removal::clear_list();
	}


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

	// Loop over events to Analyze
	unsigned int nEventsTotal = 0;
	unsigned int nEventsChain = chain->GetEntries();
	if( nEvents >= 0 ) nEventsChain = nEvents;
	TObjArray *listOfFiles = chain->GetListOfFiles();
	TIter fileIter(listOfFiles);
	TFile *currentFile = 0;

	// File Loop
	while ( (currentFile = (TFile*)fileIter.Next()) ) {

		// Get File Content
		TFile file( currentFile->GetTitle() );
		TString filename = file.GetName();
		TTree *tree = (TTree*)file.Get("t");
		if(fast) TTreeCache::SetLearnEntries(10);
		if(fast) tree->SetCacheSize(128*1024*1024);
		cms3.Init(tree);

		// Load event weight histograms
		TH2F* hNEvts = (TH2F*)file.Get("histNEvts");
		TH3D* hCounterSMS = (TH3D*)file.Get("h_counterSMS");
		TH1D* hCounter = (TH1D*)file.Get("h_counter");
		myHelper.Setup( isFastsim, hCounter, hNEvts, hCounterSMS );

		// Reset zeroing histograms
		for( int i=0; i<nSigRegs; i++ ) {
			for( int j=0; j<=nVariations; j++ ) {
				h_bkgtype[i][j]->Reset();
				h_evttype[i][j]->Reset();
			}
		}
		h_yields->Reset();

		// Loop over Events in current file
		if( nEventsTotal >= nEventsChain ) continue;
		unsigned int nEventsTree = tree->GetEntriesFast();
		for( unsigned int event = 0; event < nEventsTree; ++event) {

			// Get Event Content
			if( nEventsTotal >= nEventsChain ) continue;
			if(fast) tree->LoadTree(event);
			cms3.GetEntry(event);
			++nEventsTotal;

			// Progress
			CMS3::progress( nEventsTotal, nEventsChain );

			////////////////////////////////////////////////////////////////////////////////////////////////////////
			// Analysis Code
			// ---------------------------------------------------------------------------------------------------//


			///////////////////////////////////////////////////////////////
			// Special filters to more finely categorize background events
			if(      sampleName == "tt2l"  && gen_nfromtleps_() != 2 ) continue;  //Require 2 leps from top in "tt2l" events
			else if( sampleName == "tt1l"  && gen_nfromtleps_() != 1 ) continue;  //Require 1 lep from top in "tt1l" events

			// Stitch W+NJets samples together by removing the MET<200 events from the non-nupT samples
			if( sampleName.Contains("wjets") && filename.Contains("JetsToLNu_madgraph") && nupt()>=200. ) continue;

			//FastSim anomalous event filter
			if( isFastsim && !context::filt_fastsimjets() ) continue;

			if( !mySample->PassSelections() ) continue;


			/////////////////////////////////
			// Set event weight

			double evtWeight = 1.;

			// Data should have a weight of 1.0
			if( is_data() || mySample->IsData() ) evtWeight = 1.;
			else {

				// Weight background MC using scale1fb
				evtWeight = myAnalysis->GetLumi() * scale1fb();

				// Weight signal MC using xsec and nEvents
				if( mySample->IsSignal() ) {
					myHelper.PrepSignal();
					double nEvtsSample = hNEvts->GetBinContent( hNEvts->FindBin( mass_stop(), mass_lsp() ) );
					evtWeight = myAnalysis->GetLumi() * 1000. * xsec() / nEvtsSample;
				}

				// Apply scale factors to correct the shape of the MC
				evtWeight *= myHelper.TrigEff2l();
				evtWeight *= myHelper.LepSF();
				evtWeight *= myHelper.BtagSF();
				if(  isFastsim ) evtWeight *= myHelper.LepSFfastsim();
				if( !isFastsim ) evtWeight *= myHelper.PileupSF();
				if( mySample->GetLabel() == "tt2l" || filename.Contains("W_5f_powheg_pythia8") ) {
					evtWeight *= myHelper.MetResSF();
					// evtWeight *= myHelper.TopSystPtSF();
				}
				else if( mySample->GetLabel() == "tt1l" || mySample->GetLabel() == "wjets" ) evtWeight *= myHelper.MetResSF();
				if( mySample->GetLabel() == "tt2l" || mySample->GetLabel() == "tt1l" || mySample->IsSignal() ) evtWeight *= myHelper.ISRnJetsSF();

				// Correct event weight when samples are merged together
				if(      filename.Contains("ttbar_diLept_madgraph_pythia8_ext1_25ns") ) evtWeight *= 23198554./(23198554.+5689986.);
				else if( filename.Contains("ttbar_diLept_madgraph_pythia8_25ns") ) evtWeight *= 5689986./(23198554.+5689986.);
				else if( filename.Contains("t_tW_5f_powheg_pythia8_noHadDecays_25ns") ) evtWeight *= 4473156./(4473156.+3145334.);
				else if( filename.Contains("t_tW_5f_powheg_pythia8_noHadDecays_ext1_25ns") ) evtWeight *= 3145334./(4473156.+3145334.);
				else if( filename.Contains("t_tbarW_5f_powheg_pythia8_noHadDecays_25ns") ) evtWeight *= 5029568./(5029568.+3146940.);
				else if( filename.Contains("t_tbarW_5f_powheg_pythia8_noHadDecays_ext1_25ns") ) evtWeight *= 3146940./(5029568.+3146940.);
			}

			// Count the number of events processed
			yield_total += evtWeight;
			yGen_total++;

			// Remove duplicate events in data
			if( is_data() ) {
				duplicate_removal::DorkyEventIdentifier id( run(), evt(), ls() );
				if( is_duplicate(id) ) continue;
				yield_unique += evtWeight;
				yGen_unique++;
			}

			// MET filters, bad event filters, and triggers for data
			if( is_data() ) {
				if( !goodrun( run(), ls() ) ) continue;
				if( !filt_met() ) continue;
				if( !filt_badChargedCandidateFilter() ) continue;
				if( !filt_badMuonFilter() ) continue;
				if( !context::filt_jetWithBadMuon() ) continue;
				if( !filt_pfovercalomet() ) continue;
				if( !HLT_MET() && !HLT_MET110_MHT110() && !HLT_MET120_MHT120() ) {
					if( !(HLT_SingleEl() && (abs(lep1_pdgid())==11 || abs(lep2_pdgid())==11) ) &&
					    !(HLT_SingleMu() && (abs(lep1_pdgid())==13 || abs(lep2_pdgid())==13) ) ) continue;
				}
				yield_filter += evtWeight;
				yGen_filter++;
			}

			// First vertex must be good
			if( nvtxs() < 1 ) continue;
			yield_vtx += evtWeight;
			yGen_vtx++;

			// Must have at least 1 good lepton
			if( ngoodleps() < 1 ) continue;
			yield_1goodlep += evtWeight;
			yGen_1goodlep++;

			// Lep 1 must pass lepton selections
			// if( abs(lep1_pdgid())==11 ) {
			// 	if( lep1_p4().pt() < 20. ) continue;
			// 	if( fabs(lep1_p4().eta()) > 1.4442 ) continue;
			// 	if( !lep1_passMediumID() ) continue;
			// }
			// else if( abs(lep1_pdgid())==13 ) {
			// 	if( lep1_p4().pt() < 20. ) continue;
			// 	if( fabs(lep1_p4().eta()) > 2.4 ) continue;
			// 	if( !lep1_passTightID() ) continue;
			// }
			yield_lepSel += evtWeight;
			yGen_lepSel++;


			///////////////////
			// Make 2-lepton CR

			int countGoodLeps = 0;

			// Count the number of veto leptons
			if( nvetoleps() >= 2 && lep2_p4().pt() > 10. ) countGoodLeps += nvetoleps();

			if( countGoodLeps > 1 ) {
				yield_2lepveto += evtWeight;
				yGen_2lepveto++;
			}

			// If we fail the track veto, count another good lepton
			// if( !PassTrackVeto() ) {
			// 	countGoodLeps++;
			// 	yield_trkVeto += evtWeight;
			// 	yGen_trkVeto++;
			// }

			// If we fail the tau veto, count another good lepton
			// if( !PassTauVeto() ) {
			// 	countGoodLeps++;
			// 	yield_tauVeto += evtWeight;
			// 	yGen_tauVeto++;
			// }

			if( countGoodLeps < 2 ) continue;
			yield_2lepCR += evtWeight;
			yGen_2lepCR++;


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

			// N-jet requirement
			if( context::ngoodjets() < 2 ) continue;
			yield_njets += evtWeight;
			yGen_njets++;

			j1pt = context::ak4pfjets_p4().at(0).pt();

			// B-tag requirement
			if( context::ngoodbtags() < 1 ) continue;
			yield_1bjet += evtWeight;
			yGen_1bjet++;

			j1_isBtag = context::ak4pfjets_passMEDbtag().at(0);

			// Baseline MET cut (with 2nd lepton pT added to MET)
			if( context::Met() < 250. ) continue;
			yield_METcut += evtWeight;
			yGen_METcut++;

			// MT cut (with 2nd lepton pT added to MET)
			if( context::MT_met_lep() < 150. ) continue;
			yield_MTcut += evtWeight;
			yGen_MTcut++;

			// Min delta-phi between MET and j1/j2 (with 2nd lepton pT added to MET)
			if( context::Mindphi_met_j1_j2() < 0.5 ) continue;
			yield_dPhi += evtWeight;
			yGen_dPhi++;

			// Chi^2 cut
			// if( hadronic_top_chi2() >= 10. ) continue;
			yield_chi2 += evtWeight;
			yGen_chi2++;


			//////////////////////////////////////////////////////////
			// Classify event based on number of leptons / neutrinos
			// Order of evaluation matters, because some events fall into multiple categories

			int bkgType = -99;
			if( filename.Contains("ZZTo2L2Nu") && isZtoNuNu() ) bkgType = 1; // Force ZZto2L2Nu to be 2lep
			else if( isZtoNuNu() )     bkgType = 4;   // Z to nu nu
			else if( is2lep() )        bkgType = 1;   // 2 or more leptons
			else if( is1lepFromTop() ) bkgType = 3;   // 1 lepton from top quark
			else if( is1lepFromW() )   bkgType = 2;   // 1 lepton from a W not from top
			else                       bkgType = 5;   // Other

			int evtType = -99;
			if(      mySample->IsData()   ) evtType = 1;
			else if( mySample->IsSignal() ) evtType = 2;
			else                            evtType = 2+bkgType;

			// Quickly calculate some variables
			double metSqHT = context::Met() / sqrt( context::ak4_HT() );

			const TVector3 lepVec( lep1_p4().x(), lep1_p4().y(), lep1_p4().z() );
			const TVector3 metVec( context::Met()*cos(context::MetPhi()), context::Met()*sin(context::MetPhi()), 0 );
			const TVector3 wVec = lepVec + metVec;
			double dPhiLepW = fabs( lepVec.DeltaPhi(wVec) );

			double drLepLeadb = ROOT::Math::VectorUtil::DeltaR( lep1_p4(), context::ak4pfjets_leadMEDbjet_p4() );

			lep1pt = lep1_p4().Pt();

			myMlb = context::Mlb_closestb();

			///////////////////////////////////////////
			// Signal region cuts and histo filling

			// If the event passes the SR cuts, store which background type this event is, and fill histograms
			for( int i=0; i<nSigRegs; i++ ) {

				if( !sigRegions.at(i)->PassAllCuts() ) continue;

				// Make some corrections that depend on the signal region
				double fillWeight = evtWeight;
				bool is_corridor = sigRegions.at(i)->GetLabel().Contains("corr");
				myHelper.SetCorridor( is_corridor );
				if(      !is_data() &&  is_corridor ) fillWeight *= sfhelp::MetResCorrectionCorridor();
				else if( !is_data() && !is_corridor ) fillWeight *= sfhelp::BtagCorrectionTight();

				h_bkgtype[i][0]->Fill( bkgType,                            fillWeight );
				h_evttype[i][0]->Fill( evtType,                            fillWeight );
				if( mySample->IsSignal() ) h_sigyields[i][0]->Fill( mass_stop(), mass_lsp(), fillWeight );

				h_mt[i]->Fill(      context::MT_met_lep(),                 fillWeight );
				h_met[i]->Fill(     context::Met(),                        fillWeight );
				h_mt2w[i]->Fill(    context::MT2W(),                       fillWeight );
				h_chi2[i]->Fill(    hadronic_top_chi2(),                   fillWeight );
				h_htratio[i]->Fill( context::ak4_htratiom(),               fillWeight );
				h_mindphi[i]->Fill( context::Mindphi_met_j1_j2(),          fillWeight );
				h_ptb1[i]->Fill( context::ak4pfjets_leadMEDbjet_p4().pt(), fillWeight );
				h_drlb1[i]->Fill(   drLepLeadb,                            fillWeight );
				h_ptlep[i]->Fill(   lep1_p4().pt(),                        fillWeight );
				h_metht[i]->Fill(   metSqHT,                               fillWeight );
				h_dphilw[i]->Fill(  dPhiLepW,                              fillWeight );
				h_njets[i]->Fill(   context::ngoodjets(),                  fillWeight );
				h_nbtags[i]->Fill(  context::ngoodbtags(),                 fillWeight );
				h_ptj1[i]->Fill(    j1pt,                                  fillWeight );
				h_j1btag[i]->Fill(  j1_isBtag,                             fillWeight );
				h_modtop[i]->Fill(  context::TopnessMod(),                 fillWeight );
				h_dphilmet[i]->Fill( context::lep1_dphiMET(),              fillWeight );
				h_mlb[i]->Fill(     myMlb,                                 fillWeight );

				h_yields->Fill(     double(i+1),                           fillWeight );

				// Special systematic variation histograms
				for( int j=1; j<=nVariations; j++ ) {
					h_bkgtype[i][j]->Fill( bkgType,  fillWeight * variations.at(j-1)->GetWeight() );
					h_evttype[i][j]->Fill( evtType,  fillWeight * variations.at(j-1)->GetWeight() );
					if( mySample->IsSignal() ) h_sigyields[i][j]->Fill( mass_stop(), mass_lsp(), fillWeight * variations.at(j-1)->GetWeight() );
				}

			}

			// ---------------------------------------------------------------------------------------------------//
			////////////////////////////////////////////////////////////////////////////////////////////////////////
		} //End of loop over events in file

		// Clean Up
		delete tree;
		file.Close();

		// Zero negative values in each signal region
		for( int i=0; i<nSigRegs; i++ ) {
			for( int j=0; j<=nVariations; j++ ) {
				bool negsFound = false;

				// First zero any decay modes with negative yields
				for( int k=1; k<= h_bkgtype[i][j]->GetNbinsX(); k++ ) {
					if( h_bkgtype[i][j]->GetBinContent(k) < 0.0 ) {
						h_bkgtype[i][j]->SetBinContent(k, 0.);
						h_bkgtype[i][j]->SetBinError(k, 0.);
						negsFound = true;
					}
					if( h_evttype[i][j]->GetBinContent(k+2) < 0.0 ) {
						h_evttype[i][j]->SetBinContent(k+2, 0.);
						h_evttype[i][j]->SetBinError(k+2, 0.);
					}
				}
				// If any negative yields were found in any decay mode, recalculate the total yield
				if( j==0 && negsFound ) {
					double newYield, newErr;
					newYield = h_bkgtype[i][0]->IntegralAndError( 0, -1, newErr );
					h_yields->SetBinContent(i+1, newYield);
					h_yields->SetBinError(i+1, newErr);
				}
				// Add zeroed histograms to total histograms
				h_bkgtype_sum[i][j]->Add( h_bkgtype[i][j] );
				h_evttype_sum[i][j]->Add( h_evttype[i][j] );
			}
		}
		h_yields_sum->Add( h_yields );

	} // End loop over files in the chain

	cout << "Cutflow yields:                        (yield)  (gen evts)" << endl;

	printf("Total number of events:             %10.2f %9i\n",   yield_total    , yGen_total    );
	if( mySample->IsData() ) {
		printf("Events passing duplicate removal:   %10.2f %9i\n", yield_unique   , yGen_unique   );
		printf("Events passing filters and trigger: %10.2f %9i\n", yield_filter   , yGen_filter   );
	}
	printf("Events with 1st vertex good:        %10.2f %9i\n",   yield_vtx      , yGen_vtx      );
	printf("Events with at least 1 good lepton: %10.2f %9i\n",   yield_1goodlep , yGen_1goodlep );
	printf("Events passing lepton selection:    %10.2f %9i\n",   yield_lepSel   , yGen_lepSel   );

	printf("\nEvents passing 2-lep requirement:   %10.2f %9i\n", yield_2lepCR   , yGen_2lepCR   );
	printf("   Events with veto lepton:         %10.2f %9i\n",   yield_2lepveto , yGen_2lepveto );
	printf("   Events with isolated track:      %10.2f %9i\n",   yield_trkVeto  , yGen_trkVeto  );
	printf("   Events with identified tau:      %10.2f %9i\n\n", yield_tauVeto  , yGen_tauVeto  );

	printf("Events with at least 2 jets:        %10.2f %9i\n",   yield_njets    , yGen_njets    );
	printf("Events with at least 1 b-tag:       %10.2f %9i\n",   yield_1bjet    , yGen_1bjet    );
	printf("Events with MET > 250 GeV:          %10.2f %9i\n",   yield_METcut   , yGen_METcut   );
	printf("Events with MT > 150 GeV:           %10.2f %9i\n",   yield_MTcut    , yGen_MTcut    );
	printf("Events with min dPhi > 0.5:         %10.2f %9i\n",   yield_dPhi     , yGen_dPhi     );
	// printf("Events with chi2 < 10:              %10.2f %9i\n",   yield_chi2     , yGen_chi2     );
	printf("Yield after preselection:           %10.2f %9i\n",   yield_chi2     , yGen_chi2     );

	if ( nEventsChain != nEventsTotal ) {
		cout << Form( "ERROR: number of events from files (%d) is not equal to total number of events (%d)", nEventsChain, nEventsTotal ) << endl;
	}


	///////////////////////////////////////////////////////////////////////////////
	// Store histograms and clean them up
	TFile* plotfile = new TFile( myAnalysis->GetPlotFileName(), "READ");
	TFile* systfile = new TFile( myAnalysis->GetSystFileName(), "READ");
	TFile* sourcefile;

	// Certain histograms are cumulative across multiple samples. For those histograms, add what the
	// looper has just collected to the cumulative version stored in our output files
	for( int j=0; j<=nVariations; j++ ) {

		if( j==0 ) sourcefile = plotfile;
		else       sourcefile = systfile;

		for( int i=0; i<nSigRegs; i++ ) {

			// Build up cumulative histo of SUSY scan yields
			TH2D* hTemp2 = (TH2D*)sourcefile->Get( h_sigyields[i][j]->GetName() );
			if( hTemp2 != 0 ) h_sigyields[i][j]->Add( hTemp2 );

			// Build up cumulative histo of yields by signal/background type
			TH1D* hTemp = (TH1D*)sourcefile->Get( h_evttype_sum[i][j]->GetName() );
			if( hTemp != 0 ) h_evttype_sum[i][j]->Add( hTemp );
		}
	}
	delete plotfile;
	delete systfile;

	// Take all histograms in histdir and write them to plotfile
	plotfile = new TFile( myAnalysis->GetPlotFileName(), "UPDATE");
	plotfile->cd();
	histdir->GetList()->Write( "", TObject::kOverwrite );
	delete plotfile;

	// Take all histograms in systdir and write them to systfile
	systfile = new TFile( myAnalysis->GetSystFileName(), "UPDATE");
	systfile->cd();
	systdir->GetList()->Write( "", TObject::kOverwrite );
	delete systfile;

	// Cleanup
	zerodir->Close();
	histdir->Close();
	systdir->Close();

	// return
	bmark->Stop("benchmark");
	cout << endl;
	cout << nEventsTotal << " Events Processed" << endl;
	cout << "------------------------------" << endl;
	cout << "CPU  Time:	" << Form( "%.01f", bmark->GetCpuTime("benchmark")  ) << endl;
	cout << "Real Time:	" << Form( "%.01f", bmark->GetRealTime("benchmark") ) << endl;
	cout << endl;
	delete bmark;
	return 0;
}
Example #7
0
int ScanChain( TChain* chain, bool fast = true, int nEvents = -1, string skimFilePrefix = "test") {

  // Benchmark
  TBenchmark *bmark = new TBenchmark();
  bmark->Start("benchmark");

  // Example Histograms
  TDirectory *rootdir = gDirectory->GetDirectory("Rint:");
  TH1F *samplehisto = new TH1F("samplehisto", "Example histogram", 200,0,200);
  samplehisto->SetDirectory(rootdir);

  // Loop over events to Analyze
  unsigned int nEventsTotal = 0;
  unsigned int nEventsChain = chain->GetEntries();
  if( nEvents >= 0 ) nEventsChain = nEvents;
  TObjArray *listOfFiles = chain->GetListOfFiles();
  TIter fileIter(listOfFiles);
  TFile *currentFile = 0;

  // File Loop
  while ( (currentFile = (TFile*)fileIter.Next()) ) {

    // Get File Content
    TFile *file = new TFile( currentFile->GetTitle() );
    TTree *tree = (TTree*)file->Get("t");
    if(fast) TTreeCache::SetLearnEntries(10);
    if(fast) tree->SetCacheSize(128*1024*1024);
    cms3.Init(tree);
    
    // Loop over Events in current file
    if( nEventsTotal >= nEventsChain ) continue;
    unsigned int nEventsTree = tree->GetEntriesFast();
    for( unsigned int event = 0; event < nEventsTree; ++event) {
    
      // Get Event Content
      if( nEventsTotal >= nEventsChain ) continue;
      if(fast) tree->LoadTree(event);
      cms3.GetEntry(event);
      ++nEventsTotal;
    
      // Progress
      StopBabies10012015::progress( nEventsTotal, nEventsChain );

      // Analysis Code

    }
  
    // Clean Up
    delete tree;
    file->Close();
    delete file;
  }
  if ( nEventsChain != nEventsTotal ) {
    cout << Form( "ERROR: number of events from files (%d) is not equal to total number of events (%d)", nEventsChain, nEventsTotal ) << endl;
  }
  
  // Example Histograms
  samplehisto->Draw();
  
  // return
  bmark->Stop("benchmark");
  cout << endl;
  cout << nEventsTotal << " Events Processed" << endl;
  cout << "------------------------------" << endl;
  cout << "CPU  Time:	" << Form( "%.01f", bmark->GetCpuTime("benchmark")  ) << endl;
  cout << "Real Time:	" << Form( "%.01f", bmark->GetRealTime("benchmark") ) << endl;
  cout << endl;
  delete bmark;
  return 0;
}
Example #8
0
int ScanChain( TChain* chain, bool fast = true, int nEvents = -1, string skimFilePrefix = "test") {

  
  // Benchmark
  TBenchmark *bmark = new TBenchmark();
  bmark->Start("benchmark");

  // Example Histograms
  TDirectory *rootdir = gDirectory->GetDirectory("Rint:");


  map<string, TH1F*> histos;
  vector<string> histonames; histonames.clear();
  vector<int> hbins;  hbins.clear();
  vector<float> hlow; hlow.clear();
  vector<float> hup;  hup.clear();

  histonames.push_back("MT");                       hbins.push_back(18); hlow.push_back( 50.); hup.push_back(500);
  histonames.push_back("MT_harder");                hbins.push_back(18); hlow.push_back( 50.); hup.push_back(500);
  histonames.push_back("MT2W");                     hbins.push_back(20); hlow.push_back(  0.); hup.push_back(500);
  histonames.push_back("MT2W_4j");                  hbins.push_back(20); hlow.push_back(  0.); hup.push_back(500);
  histonames.push_back("MET");                      hbins.push_back(26); hlow.push_back(100.); hup.push_back(750);
  histonames.push_back("MET_3j");                   hbins.push_back(26); hlow.push_back(100.); hup.push_back(750);
  histonames.push_back("MET_4j");                   hbins.push_back(26); hlow.push_back(100.); hup.push_back(750);
  histonames.push_back("MET_hMT2W");                hbins.push_back(26); hlow.push_back(100.); hup.push_back(750);
  histonames.push_back("MET_hMT2W_4j");             hbins.push_back(26); hlow.push_back(100.); hup.push_back(750);
  histonames.push_back("MinDPhi");                  hbins.push_back(16); hlow.push_back(  0.); hup.push_back(3.2);
  histonames.push_back("MinDPhi_harder");           hbins.push_back(16); hlow.push_back(  0.); hup.push_back(3.2);
  histonames.push_back("MinDPhi_3j");               hbins.push_back(16); hlow.push_back(  0.); hup.push_back(3.2);
  histonames.push_back("MinDPhi_4j");               hbins.push_back(16); hlow.push_back(  0.); hup.push_back(3.2);
  histonames.push_back("NJets");                    hbins.push_back(6 ); hlow.push_back(  2.); hup.push_back(8);
  histonames.push_back("NJets_hard");               hbins.push_back(6 ); hlow.push_back(  2.); hup.push_back(8);
  histonames.push_back("NJets_harder");             hbins.push_back(6 ); hlow.push_back(  2.); hup.push_back(8);
  histonames.push_back("tMod");                     hbins.push_back(30); hlow.push_back(-15.); hup.push_back(15);
  histonames.push_back("tMod_2j");                  hbins.push_back(30); hlow.push_back(-15.); hup.push_back(15);

  for(unsigned int b = 0; b<2; ++b){
    string samplename = skimFilePrefix;
    if(skimFilePrefix!="TTbar"&&b>0) continue;
    if(skimFilePrefix=="TTbar"&&b==0) samplename = "TTbar1l";
    if(skimFilePrefix=="TTbar"&&b==1) samplename = "TTbar2l";
    for(unsigned int i = 0; i<histonames.size(); ++i){
      string mapname = histonames[i] + "_"+samplename;
      if(histos.count(mapname) == 0 ) histos[mapname] = new TH1F(mapname.c_str(), "", hbins[i], hlow[i], hup[i]);
      histos[mapname]->Sumw2(); histos[mapname]->SetDirectory(rootdir);
    }
  }

  
  // Loop over events to Analyze
  unsigned int nEventsTotal = 0;
  unsigned int nEventsChain = chain->GetEntries();
  if( nEvents >= 0 ) nEventsChain = nEvents;
  TObjArray *listOfFiles = chain->GetListOfFiles();
  TIter fileIter(listOfFiles);
  TFile *currentFile = 0;
  
  TH1D* counterhist;
  double count1(0), count2(0);
  double count3(0), count4(0);

  // File Loop
  while ( (currentFile = (TFile*)fileIter.Next()) ) {

    // Get File Content
    TFile *file = new TFile( currentFile->GetTitle() );
    TTree *tree = (TTree*)file->Get("t");
    if(fast) TTreeCache::SetLearnEntries(10);
    if(fast) tree->SetCacheSize(128*1024*1024);
    cms3.Init(tree);

    // Loop over Events in current file
    if( nEventsTotal >= nEventsChain ) continue;
    unsigned int nEventsTree = tree->GetEntriesFast();
    for( unsigned int event = 0; event < nEventsTree; ++event) {
 
      // Get Event Content
      if( nEventsTotal >= nEventsChain ) continue;
      if(fast) tree->LoadTree(event);
      cms3.GetEntry(event);
      ++nEventsTotal;
    
      // Progress
      CMS3::progress( nEventsTotal, nEventsChain );
      
      float weight = cms3.scale1fb()*2.26;
      if(event==0) cout << "weight " << weight << " nEvents " << cms3.nEvents() << " filename " << currentFile->GetTitle() << endl;
      
      //ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > metlv;
      //metlv.SetPxPyPzE(pfmet()*TMath::Cos(pfmet_phi()),pfmet()*TMath::Sin(pfmet_phi()),0.,pfmet());
      int NSLeps = 0;
      int NAddVetoLeps = 0;
      if(lep1_is_mu()){
	if(lep1_pt()>20&&fabs(lep1_eta())<2.4) {++NSLeps;}
      } else if (lep1_is_el()){
	if(lep1_pt()>20&&fabs(lep1_eta())<1.4442) {++NSLeps; }
      } if(lep2_is_mu()){
	if(lep2_pt()>20&&fabs(lep2_eta())<2.4) {++NSLeps;}
      } else if (lep2_is_el()){
	if(lep2_pt()>20&&fabs(lep2_eta())<1.4442) {++NSLeps; }
      }
      if(lep2_is_mu()){
	if(lep2_pt()>10&&fabs(lep2_eta())<2.4) {++NAddVetoLeps;}
      } else if (lep2_is_el()){
	if(lep2_pt()>10&&fabs(lep2_eta())<2.4) {++NAddVetoLeps; }
      }


      if(nvtxs()<0)               continue;
      if(ngoodleps()!=1)          continue;
      if(nvetoleps()!=1)          continue;
      if(!PassTrackVeto_v3())     continue;
      if(!PassTauVeto())          continue;
      if(ngoodjets()<2)           continue;
      if(ngoodbtags()<1)          continue;
      if(pfmet()<100)             continue;
      if(mt_met_lep()< 50)        continue;
      //if(pfmet()<250)             continue;
      //if(mt_met_lep()<150)        continue;
      //if(mindphi_met_j1_j2()<0.8) continue;

      string samplename = skimFilePrefix;
      if(skimFilePrefix=="TTbar"){
	if(is2lep() ) samplename = "TTbar2l";
	else if(is1lepFromTop() ) samplename = "TTbar1l";
	else continue;
      }

      if(ngoodjets()>=2 && mindphi_met_j1_j2()>0.8 && pfmet()>250) histos["MT_"+samplename]->Fill(mt_met_lep(),weight);
      if(ngoodjets()>=2 && mindphi_met_j1_j2()>0.8 && pfmet()>350) histos["MT_harder_"+samplename]->Fill(mt_met_lep(),weight);
      if(ngoodjets()>=3 && mindphi_met_j1_j2()>0.8 && pfmet()>250 && mt_met_lep()>150) histos["MT2W_"+samplename]->Fill(MT2W(),weight);
      if(ngoodjets()>=4 && mindphi_met_j1_j2()>0.8 && pfmet()>250 && mt_met_lep()>150) histos["MT2W_4j_"+samplename]->Fill(MT2W(),weight);
      if(ngoodjets()>=2 && mindphi_met_j1_j2()>0.8 && mt_met_lep()>150) histos["MET_"+samplename]->Fill(pfmet(),weight);
      if(ngoodjets()>=3 && mindphi_met_j1_j2()>0.8 && mt_met_lep()>150) histos["MET_3j_"+samplename]->Fill(pfmet(),weight);
      if(ngoodjets()>=4 && mindphi_met_j1_j2()>0.8 && mt_met_lep()>150) histos["MET_4j_"+samplename]->Fill(pfmet(),weight);
      if(ngoodjets()>=3 && mindphi_met_j1_j2()>0.8 && mt_met_lep()>150 && MT2W()>200) histos["MET_hMT2W_"+samplename]->Fill(pfmet(),weight);
      if(ngoodjets()>=4 && mindphi_met_j1_j2()>0.8 && mt_met_lep()>150 && MT2W()>200) histos["MET_hMT2W_4j_"+samplename]->Fill(pfmet(),weight);
      if(ngoodjets()>=2 && pfmet()>250 && mt_met_lep()>150) histos["MinDPhi_"+samplename]->Fill(mindphi_met_j1_j2(),weight);
      if(ngoodjets()>=2 && pfmet()>350 && mt_met_lep()>150) histos["MinDPhi_harder_"+samplename]->Fill(mindphi_met_j1_j2(),weight);
      if(ngoodjets()>=3 && pfmet()>250 && mt_met_lep()>150) histos["MinDPhi_3j_"+samplename]->Fill(mindphi_met_j1_j2(),weight);
      if(ngoodjets()>=4 && pfmet()>250 && mt_met_lep()>150) histos["MinDPhi_4j_"+samplename]->Fill(mindphi_met_j1_j2(),weight);
      if(ngoodjets()>=2 && mindphi_met_j1_j2()>0.8 && pfmet()>250 && mt_met_lep()>150) histos["NJets_"+samplename]->Fill(ngoodjets(),weight);
      if(ngoodjets()==2 && mindphi_met_j1_j2()>0.8 && pfmet()>250 && mt_met_lep()>150 && topnessMod()>6.4) histos["NJets_hard_"+samplename]->Fill(ngoodjets(),weight);
      if(ngoodjets()>=3 && mindphi_met_j1_j2()>0.8 && pfmet()>250 && mt_met_lep()>150 && MT2W()>200)       histos["NJets_hard_"+samplename]->Fill(ngoodjets(),weight);
      if(ngoodjets()==2 && mindphi_met_j1_j2()>0.8 && pfmet()>350 && mt_met_lep()>150 && topnessMod()>6.4) histos["NJets_harder_"+samplename]->Fill(ngoodjets(),weight);
      if(ngoodjets()>=3 && mindphi_met_j1_j2()>0.8 && pfmet()>350 && mt_met_lep()>150 && MT2W()>200)       histos["NJets_harder_"+samplename]->Fill(ngoodjets(),weight);
      if(ngoodjets()>=2 && mindphi_met_j1_j2()>0.8 && pfmet()>250 && mt_met_lep()>150) histos["tMod_"+samplename]->Fill(topnessMod(),weight);
      if(ngoodjets()==2 && mindphi_met_j1_j2()>0.8 && pfmet()>250 && mt_met_lep()>150) histos["tMod_2j_"+samplename]->Fill(topnessMod(),weight);

    }//event loop
  
    // Clean Up
    delete tree;
    file->Close();
    delete file;
  }//file loop
  if ( nEventsChain != nEventsTotal ) {
    cout << Form( "ERROR: number of events from files (%d) is not equal to total number of events (%d)", nEventsChain, nEventsTotal ) << endl;
  }
  
  string filename = "rootfiles/PASfigure.root";
  TFile *f = new TFile(filename.c_str(),"update");
  f->cd();
  for(map<string,TH1F*>::iterator h=    histos.begin(); h!=    histos.end();++h) h->second->Write();
  f->Close();
  cout << "Saved histos in " << f->GetName() << endl;
  delete f;
  // return
  bmark->Stop("benchmark");
  cout << endl;
  cout << nEventsTotal << " Events Processed" << endl;
  cout << "------------------------------" << endl;
  cout << "CPU  Time:	" << Form( "%.01f", bmark->GetCpuTime("benchmark")  ) << endl;
  cout << "Real Time:	" << Form( "%.01f", bmark->GetRealTime("benchmark") ) << endl;
  cout << endl;
  delete bmark;
  return 0;
}
Example #9
0
//
// Functions
//
int looper( sampleInfo::ID sampleID, std::vector<analyzer*> analyzers, int nEvents, bool readFast ) {


  //
  // Intro
  //
  cout << "====================================================" << endl;
  cout << endl;
  cout << "  WELCOME TO STOP BABY ANALYZER! " << endl;
  cout << endl;
  cout << "====================================================" << endl;
  cout << endl;


  //
  // Benchmark
  //
  TBenchmark *bmark = new TBenchmark();
  bmark->Start("benchmark");
  

  //
  // Input SampleInfo
  //
  sampleInfo::sampleUtil sample( sampleID );

  bool sampleIsTTbar = false;
  if( sample.id == sampleInfo::k_ttbar_powheg_pythia8 ||
      sample.id == sampleInfo::k_ttbar_powheg_pythia8_ext4 ||
      sample.id == sampleInfo::k_ttbar_singleLeptFromT_madgraph_pythia8 ||
      sample.id == sampleInfo::k_ttbar_singleLeptFromT_madgraph_pythia8_ext1 ||
      sample.id == sampleInfo::k_ttbar_singleLeptFromTbar_madgraph_pythia8 ||
      sample.id == sampleInfo::k_ttbar_singleLeptFromTbar_madgraph_pythia8_ext1 ||
      sample.id == sampleInfo::k_ttbar_diLept_madgraph_pythia8 ||
      sample.id == sampleInfo::k_ttbar_diLept_madgraph_pythia8_ext1 ) {
    sampleIsTTbar = true;
  }
  
  //
  // Input chain
  //
  TChain *chain = new TChain("t");
  
  cout << "    Processing the following: " << endl;  
  for(int iFile=0; iFile<(int)sample.inputBabies.size(); iFile++) {
    
    // input directory
    string input = sample.baby_i_o.first;
      
    // input file
    input += sample.inputBabies[iFile];
      
    chain->Add( input.c_str() );
    cout << "      " << input << endl; 
  }
  cout << endl;
  
  
  //
  // Output File
  //

  // output dir
  string f_output_name = "";
  f_output_name += sample.baby_i_o.second;

  // output name
  f_output_name += sample.label;
  f_output_name += ".root";

  // output file
  TFile *f_output = new TFile( f_output_name.c_str(), "recreate" );

  // print output location
  cout << "    Output Written to: " << endl;
  cout << "      " << f_output_name << endl;
  cout << endl;


  //
  // JSON File Tools
  //
  const char* json_file = "../StopCORE/inputs/json_files/Cert_271036-284044_13TeV_23Sep2016ReReco_Collisions16_JSON.txt"; // 35.876fb final 2016 run
  if( sample.isData ) set_goodrun_file_json(json_file);
  

  //
  // Event Weight Utilities
  //
  cout << "    Loading eventWeight Utilities..." << endl << endl;
  wgtInfo.setUp( sample.id, useBTagSFs_fromFiles_, useLepSFs_fromFiles_, add2ndLepToMet_ );  
  wgtInfo.apply_cr2lTrigger_sf  = (apply_cr2lTrigger_sf_ && add2ndLepToMet_);
  wgtInfo.apply_bTag_sf         = apply_bTag_sf_;
  wgtInfo.apply_lep_sf          = apply_lep_sf_;
  wgtInfo.apply_vetoLep_sf      = apply_vetoLep_sf_;
  wgtInfo.apply_tau_sf          = apply_tau_sf_;
  wgtInfo.apply_lepFS_sf        = apply_lepFS_sf_;
  wgtInfo.apply_topPt_sf        = apply_topPt_sf_;
  wgtInfo.apply_metRes_sf       = apply_metRes_sf_;
  wgtInfo.apply_metTTbar_sf     = apply_metTTbar_sf_;
  wgtInfo.apply_ttbarSysPt_sf   = apply_ttbarSysPt_sf_;
  wgtInfo.apply_ISR_sf          = apply_ISR_sf_;
  wgtInfo.apply_pu_sf           = apply_pu_sf_;
  wgtInfo.apply_sample_sf       = apply_sample_sf_;


  //
  // Declare genClassification list
  //
  cout << "    Loading genClassyList: ";
  std::vector< genClassyInfo::Util > genClassyList;
  if( sample.isData ) {
    genClassyList.push_back(genClassyInfo::Util(genClassyInfo::k_incl));
  }
  else{
    for(int iGenClassy=0; iGenClassy<genClassyInfo::k_nGenClassy; iGenClassy++) {
      genClassyList.push_back( genClassyInfo::Util(genClassyInfo::ID(iGenClassy)) );
    }
  }
  const int nGenClassy=(int)genClassyList.size();
  cout << nGenClassy << " genClassifications" << endl << endl;

  
  //
  // Declare Systematics
  //
  cout << "    Loading systematicList: ";
  std::vector< sysInfo::Util > systematicList;
  if( sample.isData || analyzeFast_ ) {
    systematicList.push_back(sysInfo::Util(sysInfo::k_nominal));
  }
  else{
    for(int iSys=0; iSys<sysInfo::k_nSys; iSys++) {
      systematicList.push_back( sysInfo::Util(sysInfo::ID(iSys)) );
    }
  }  
  const int nSystematics = (int)systematicList.size();
  cout << nSystematics << " systematics" << endl << endl;


	// Count number of analyzers in the list
	const int nAnalyzers = analyzers.size();



  ////////////////////////
  //                    //
  // Declare Histograms //
  //                    //
  ////////////////////////
  //
  //
  //  For Using DownStream Scripts, please adhere to the conventions:
  //
  //
  //    histogram_name = "your_name_here"+"__"+regionList[i]+"__genClassy_"+genClassyObject.label+"__systematic_"+sysInfoObject.label;
  //
  //
  //  Where regionList is the list of "SR", "CR0b", "CR0b_tightBTagHighMlb" or "CR2l"
  //
  //    And systematicList[0] is the nominal selection
  //
  //    And if there is andditional selection involved in this histogram, please refer to it in "you name here"
  //

  cout << "    Preparing histograms" << endl << endl;


	//
	// Declare yield histograms
	//
  f_output->cd(); // All yield histos will belong to the output file
	for( analyzer* thisAnalyzer : analyzers ) {

		TH1D* h_template = thisAnalyzer->GetYieldTemplate();
		TH3D* h_template_signal = thisAnalyzer->GetYieldTemplateSignal();

		for( int iClassy=0; iClassy<nGenClassy; iClassy++ ) {
			for( int iSys=0; iSys<nSystematics; iSys++ ) {

				int histIndex = iClassy*nSystematics + iSys;

				// Gen and Systematic String
				TString reg_gen_sys_name = "__";
				reg_gen_sys_name += thisAnalyzer->GetLabel();
				reg_gen_sys_name += "__genClassy_";
				reg_gen_sys_name += genClassyList[iClassy].label;
				reg_gen_sys_name += "__systematic_";
				reg_gen_sys_name += systematicList[iSys].label;

				TH1* h_tmp = 0;

				TString yieldname = "h_yields";
				yieldname += reg_gen_sys_name;
				if( sample.isSignalScan ) h_tmp = (TH3D*)h_template_signal->Clone( yieldname );
				else                      h_tmp = (TH1D*)h_template->Clone( yieldname );
				thisAnalyzer->SetYieldHistogram( histIndex, h_tmp );

			} // End loop over systematics
		} // End loop over genClassys
	} // End loop over analyzers

  
  
  

  //
  // Declare non-yield histograms
  //

  int nMassPts = 1;
  if( sample.isSignalScan ) nMassPts = (int)sample.massPtList.size();

  const int nHistosVars = nAnalyzers*nGenClassy*nMassPts;

  // nJets
  TH1D *h_nJets[nHistosVars];
  
  // nBTags
  TH1D *h_nBTags[nHistosVars];
  
  // lep1 pT
  TH1D *h_lep1Pt_incl[nHistosVars];
  
  // lep2 pT
  TH1D *h_lep2Pt_incl[nHistosVars];
  
  // jet pT
  TH1D *h_jetPt_incl[nHistosVars];
  
  // jet1 pT
  TH1D *h_jet1Pt_incl[nHistosVars];
  
  // jet2 pT
  TH1D *h_jet2Pt_incl[nHistosVars];
  
  // DeepCSV jet1 pT
  TH1D *h_deepcsvJet1Pt_incl[nHistosVars];
  
  // DeepCSV jet2 pT
  TH1D *h_deepcsvJet2Pt_incl[nHistosVars];
  
  // met
  TH1D *h_met_incl[nHistosVars];
  TH1D *h_met_lt4j[nHistosVars];
  TH1D *h_met_ge4j[nHistosVars];

  // lep1lep2bbMetPt
  TH1D *h_lep1lep2bbMetPt_incl[nHistosVars];
  TH1D *h_lep1lep2bbMetPt_lt4j[nHistosVars];
  TH1D *h_lep1lep2bbMetPt_ge4j[nHistosVars];

  // mt
  TH1D *h_mt_incl[nHistosVars];
  
  // modTopness
  TH1D *h_modTopness_incl[nHistosVars];
  TH1D *h_modTopness_lt4j[nHistosVars];
  TH1D *h_modTopness_ge4j[nHistosVars];

  // mlb
  TH1D *h_mlb_incl[nHistosVars];
  TH1D *h_mlb_lt4j[nHistosVars];
  TH1D *h_mlb_ge4j[nHistosVars];

  // mlb
  TH1D *h_mlb_lt0modTopness[nHistosVars];
  TH1D *h_mlb_ge0modTopness[nHistosVars];
  TH1D *h_mlb_ge10modTopness[nHistosVars];
  
  // mlb, met sideband CR
  TH1D *h_mlb_150to250met_incl[nHistosVars];
  TH1D *h_mlb_150to250met_lt4j[nHistosVars];
  TH1D *h_mlb_150to250met_ge4j[nHistosVars];

  // ml2b
  TH1D *h_mlb_lep2_incl[nHistosVars];
  TH1D *h_mlb_lep2_lt4j[nHistosVars];
  TH1D *h_mlb_lep2_ge4j[nHistosVars];
  
  // ml2b
  TH1D *h_mlb_lep2_150to250met_incl[nHistosVars];
  TH1D *h_mlb_lep2_150to250met_lt4j[nHistosVars];
  TH1D *h_mlb_lep2_150to250met_ge4j[nHistosVars];

  // Gen ttbar system pT
  TH1D *h_gen_ttbarPt_incl[nHistosVars];
  TH1D *h_gen_ttbarPt_lt4j[nHistosVars];
  TH1D *h_gen_ttbarPt_ge4j[nHistosVars];

  // Gen 2nd lepton ID
  TH1D *h_gen_lep2_id_incl[nHistosVars];
  TH1D *h_gen_lep2_id_lt4j[nHistosVars];
  TH1D *h_gen_lep2_id_ge4j[nHistosVars];

  f_output->cd(); // All non-yield histos will belong to the output file
  
  for(int iReg=0; iReg<nAnalyzers; iReg++) {
    for(int iGen=0; iGen<nGenClassy; iGen++) {
      for(int iMassPt=0; iMassPt<nMassPts; iMassPt++) {

				// Histo Index
				int iHisto = iReg*nGenClassy*nMassPts + iGen*nMassPts + iMassPt;

				int mStop = 0;
				int mLSP  = 0;
				if(sample.isSignalScan) {
					mStop = sample.massPtList[iMassPt].first;
					mLSP  = sample.massPtList[iMassPt].second;
				}

				TString hName = "";
	
				TString reg_gen_sys_name = "__";
				reg_gen_sys_name += analyzers.at(iReg)->GetLabel();
				reg_gen_sys_name += "__genClassy_";
				reg_gen_sys_name += genClassyList[iGen].label;
				reg_gen_sys_name += "__systematic_";
				reg_gen_sys_name += systematicList[0].label;
				if( sample.isSignalScan ) {
					reg_gen_sys_name += "__mStop_";
					reg_gen_sys_name += mStop;
					reg_gen_sys_name += "__mLSP_";
					reg_gen_sys_name += mLSP;
				}

      
				//
				// Njets
				//
				hName = "h_nJets" + reg_gen_sys_name;
				h_nJets[iHisto] = new TH1D( hName, "Number of Selected Jets;nJets", 11, -0.5, 10.5);

				//
				// nBTags
				//
				hName = "h_nBTags" + reg_gen_sys_name;
				h_nBTags[iHisto] = new TH1D( hName, "Number of b-Tagged Jets;nBTags", 5, -0.5, 4.5);


				//
				// lep1Pt
				//

				// Incl Selection
				hName = "h_lep1Pt__inclSelection" + reg_gen_sys_name;
				h_lep1Pt_incl[iHisto] = new TH1D( hName, "Lepton p_{T};p_{T} [GeV]", 20.0, 0.0, 200.0 );
      
	

				//
				// lep2Pt
				//

				// Incl Selection
				hName = "h_lep2Pt__inclSelection" + reg_gen_sys_name;
				h_lep2Pt_incl[iHisto] = new TH1D( hName, "Trailing Lepton p_{T};p_{T} [GeV]", 20.0, 0.0, 200.0 );
      
				//
				// jetPt
				//

				// Incl Selection
				hName = "h_jetPt__inclSelection" + reg_gen_sys_name;
				h_jetPt_incl[iHisto] = new TH1D( hName, "Jet p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );
	
				//
				// jet1Pt
				//

				// Incl Selection
				hName = "h_jet1Pt__inclSelection" + reg_gen_sys_name;
				h_jet1Pt_incl[iHisto] = new TH1D( hName, "Leading Jet p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );
	
	

				//
				// jet2Pt
				//

				// Incl Selection
				hName = "h_jet2Pt__inclSelection" + reg_gen_sys_name;
				h_jet2Pt_incl[iHisto] = new TH1D( hName, "2nd Leading Jet p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );
      
	
				//
				// DeepCSVJet1Pt
				//

				// Incl Selection
				hName = "h_deepcsvJet1Pt__inclSelection" + reg_gen_sys_name;
				h_deepcsvJet1Pt_incl[iHisto] = new TH1D( hName, "Leading DeepCSV Jet p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );
      
	

				//
				// DeepCSVJet2Pt
				//

				// Incl Selection
				hName = "h_deepcsvJet2Pt__inclSelection" + reg_gen_sys_name;
				h_deepcsvJet2Pt_incl[iHisto] = new TH1D( hName, "2nd Leading DeepCSV Jet p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );
      
	

				//
				// met
				//

				// Incl Selection
				hName = "h_met__inclSelection" + reg_gen_sys_name;
				h_met_incl[iHisto] = new TH1D( hName, "MET;MET [GeV]", 32, 0.0, 800.0 );
      
				// <4j Selection
				hName = "h_met__lt4jSelection" + reg_gen_sys_name;
				h_met_lt4j[iHisto] = new TH1D( hName, "MET;MET [GeV]", 32, 0.0, 800.0 );

				// >=4j Selection
				hName = "h_met__ge4jSelection" + reg_gen_sys_name;
				h_met_ge4j[iHisto] = new TH1D( hName, "MET;MET [GeV]", 32, 0.0, 800.0 );


	

				//
				// lep1lep2bbMetPt
				//

				// Incl Selection
				hName = "h_lep1lep2bbMetPt__inclSelection" + reg_gen_sys_name;
				h_lep1lep2bbMetPt_incl[iHisto] = new TH1D( hName, "lep1(lep2)bbMet system p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );
	
				// <4j Selection
				hName = "h_lep1lep2bbMetPt__lt4jSelection" + reg_gen_sys_name;
				h_lep1lep2bbMetPt_lt4j[iHisto] = new TH1D( hName, "lep1(lep2)bbMet system p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );

				// >=4j Selection
				hName = "h_lep1lep2bbMetPt__ge4jSelection" + reg_gen_sys_name;
				h_lep1lep2bbMetPt_ge4j[iHisto] = new TH1D( hName, "lep1(lep2)bbMet system p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );


				//
				// mt
				//

				// Incl Selection
				hName = "h_mt__inclSelection" + reg_gen_sys_name;
				h_mt_incl[iHisto] = new TH1D( hName, "M_{T};M_{T} [GeV]", 24, 0.0, 600.0 );
      
	
				//
				// modTopness
				//

				// Incl Selection
				hName = "h_modTopness__inclSelection" + reg_gen_sys_name;
				h_modTopness_incl[iHisto] = new TH1D( hName, "Modified Topness;Modified Topness", 20, -20.0, 20.0 );
      
				// <4j Selection
				hName = "h_modTopness__lt4jSelection" + reg_gen_sys_name;
				h_modTopness_lt4j[iHisto] = new TH1D( hName, "Modified Topness;Modified Topness", 20, -20.0, 20.0 );

				// >=4j Selection
				hName = "h_modTopness__ge4jSelection" + reg_gen_sys_name;
				h_modTopness_ge4j[iHisto] = new TH1D( hName, "Modified Topness;Modified Topness", 20, -20.0, 20.0 );

      
				//
				// mlb
				//

				// Incl Selection
				hName = "h_mlb__inclSelection" + reg_gen_sys_name;
				h_mlb_incl[iHisto] = new TH1D( hName, "M_{lb};M_{lb} [GeV]", 24, 0.0, 600.0 );
      
				// <4j Selection
				hName = "h_mlb__lt4jSelection" + reg_gen_sys_name;
				h_mlb_lt4j[iHisto] = new TH1D( hName, "M_{lb};M_{lb} [GeV]", 24, 0.0, 600.0 );

				// >=4j Selection
				hName = "h_mlb__ge4jSelection" + reg_gen_sys_name;
				h_mlb_ge4j[iHisto] = new TH1D( hName, "M_{lb};M_{lb} [GeV]", 24, 0.0, 600.0 );

      

				//
				// mlb, inclusive nJets, modTopness bins
				//

				// <0 modTopness Selection
				hName = "h_mlb__lt0modTopnessSelection" + reg_gen_sys_name;
				h_mlb_lt0modTopness[iHisto] = new TH1D( hName, "M_{lb};M_{lb} [GeV]", 24, 0.0, 600.0 );

				// >=0 modTopness Selection
				hName = "h_mlb__ge0modTopnessSelection" + reg_gen_sys_name;
				h_mlb_ge0modTopness[iHisto] = new TH1D( hName, "M_{lb};M_{lb} [GeV]", 24, 0.0, 600.0 );
      
				// >=10 modTopness Selection
				hName = "h_mlb__ge10modTopnessSelection" + reg_gen_sys_name;
				h_mlb_ge10modTopness[iHisto] = new TH1D( hName, "M_{lb};M_{lb} [GeV]", 24, 0.0, 600.0 );


				//
				// mlb, met sideband CR
				//

				// Incl Selection
				hName = "h_mlb_150to250met__inclSelection" + reg_gen_sys_name;
				h_mlb_150to250met_incl[iHisto] = new TH1D( hName, "M_{lb};M_{lb} [GeV]", 24, 0.0, 600.0 );
      
				// <4j Selection
				hName = "h_mlb_150to250met__lt4jSelection" + reg_gen_sys_name;
				h_mlb_150to250met_lt4j[iHisto] = new TH1D( hName, "M_{lb};M_{lb} [GeV]", 24, 0.0, 600.0 );

				// >=4j Selection
				hName = "h_mlb_150to250met__ge4jSelection" + reg_gen_sys_name;
				h_mlb_150to250met_ge4j[iHisto] = new TH1D( hName, "M_{lb};M_{lb} [GeV]", 24, 0.0, 600.0 );


				//
				// mlb_lep2
				//

				// Incl Selection
				hName = "h_mlb_lep2__inclSelection" + reg_gen_sys_name;
				h_mlb_lep2_incl[iHisto] = new TH1D( hName, "M_{l2b};M_{l2b} [GeV]", 24, 0.0, 600.0 );
      
				// <4j Selection
				hName = "h_mlb_lep2__lt4jSelection" + reg_gen_sys_name;
				h_mlb_lep2_lt4j[iHisto] = new TH1D( hName, "M_{l2b};M_{l2b} [GeV]", 24, 0.0, 600.0 );

				// >=4j Selection
				hName = "h_mlb_lep2__ge4jSelection" + reg_gen_sys_name;
				h_mlb_lep2_ge4j[iHisto] = new TH1D( hName, "M_{l2b};M_{l2b} [GeV]", 24, 0.0, 600.0 );



				//
				// mlb_lep2, met CR sideband
				//

				// Incl Selection
				hName = "h_mlb_lep2_150to250met__inclSelection" + reg_gen_sys_name;
				h_mlb_lep2_150to250met_incl[iHisto] = new TH1D( hName, "M_{l2b};M_{l2b} [GeV]", 24, 0.0, 600.0 );
      
				// <4j Selection
				hName = "h_mlb_lep2_150to250met__lt4jSelection" + reg_gen_sys_name;
				h_mlb_lep2_150to250met_lt4j[iHisto] = new TH1D( hName, "M_{l2b};M_{l2b} [GeV]", 24, 0.0, 600.0 );

				// >=4j Selection
				hName = "h_mlb_lep2_150to250met__ge4jSelection" + reg_gen_sys_name;
				h_mlb_lep2_150to250met_ge4j[iHisto] = new TH1D( hName, "M_{l2b};M_{l2b} [GeV]", 24, 0.0, 600.0 );



	

				//
				// Gen ttbar pT
				//
				if( !sample.isData ) {
    
					// Incl Selection
					hName = "h_gen_ttbarPt__inclSelection" + reg_gen_sys_name;
					h_gen_ttbarPt_incl[iHisto] = new TH1D( hName, "Gen t#bar{t} system p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );
	
					// <4j Selection
					hName = "h_gen_ttbarPt__lt4jSelection" + reg_gen_sys_name;
					h_gen_ttbarPt_lt4j[iHisto] = new TH1D( hName, "Gen t#bar{t} system p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );

					// >=4j Selection
					hName = "h_gen_ttbarPt__ge4jSelection" + reg_gen_sys_name;
					h_gen_ttbarPt_ge4j[iHisto] = new TH1D( hName, "Gen t#bar{t} system p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );



					//
					// Gen Lep2 ID
					//
      
					// Incl Selection
					hName = "h_gen_lep2_id__inclSelection" + reg_gen_sys_name;
					h_gen_lep2_id_incl[iHisto] = new TH1D( hName, "Gen 2nd Lepton ID;ID", 7, 1.0, 8.0 );
					h_gen_lep2_id_incl[iHisto]->GetXaxis()->SetBinLabel(1, "ele");
					h_gen_lep2_id_incl[iHisto]->GetXaxis()->SetBinLabel(2, "mu");
					h_gen_lep2_id_incl[iHisto]->GetXaxis()->SetBinLabel(3, "lep tau, ele");
					h_gen_lep2_id_incl[iHisto]->GetXaxis()->SetBinLabel(4, "lep tau, mu");
					h_gen_lep2_id_incl[iHisto]->GetXaxis()->SetBinLabel(5, "had tau, 1 prong");
					h_gen_lep2_id_incl[iHisto]->GetXaxis()->SetBinLabel(6, "had tau, 3 prong");
					h_gen_lep2_id_incl[iHisto]->GetXaxis()->SetBinLabel(7, "\"other\" tau");
	
					// <4j Selection
					hName = "h_gen_lep2_id__lt4jSelection" + reg_gen_sys_name;
					h_gen_lep2_id_lt4j[iHisto] = new TH1D( hName, "Gen 2nd Lepton ID;ID", 7, 1.0, 8.0 );
					h_gen_lep2_id_lt4j[iHisto]->GetXaxis()->SetBinLabel(1, "ele");
					h_gen_lep2_id_lt4j[iHisto]->GetXaxis()->SetBinLabel(2, "mu");
					h_gen_lep2_id_lt4j[iHisto]->GetXaxis()->SetBinLabel(3, "lep tau, ele");
					h_gen_lep2_id_lt4j[iHisto]->GetXaxis()->SetBinLabel(4, "lep tau, mu");
					h_gen_lep2_id_lt4j[iHisto]->GetXaxis()->SetBinLabel(5, "had tau, 1 prong");
					h_gen_lep2_id_lt4j[iHisto]->GetXaxis()->SetBinLabel(6, "had tau, 3 prong");
					h_gen_lep2_id_lt4j[iHisto]->GetXaxis()->SetBinLabel(7, "\"other\" tau");

					// >=4j Selection
					hName = "h_gen_lep2_id__ge4jSelection" + reg_gen_sys_name;
					h_gen_lep2_id_ge4j[iHisto] = new TH1D( hName, "Gen 2nd Lepton ID;ID", 7, 1.0, 8.0 );
					h_gen_lep2_id_ge4j[iHisto]->GetXaxis()->SetBinLabel(1, "ele");
					h_gen_lep2_id_ge4j[iHisto]->GetXaxis()->SetBinLabel(2, "mu");
					h_gen_lep2_id_ge4j[iHisto]->GetXaxis()->SetBinLabel(3, "lep tau, ele");
					h_gen_lep2_id_ge4j[iHisto]->GetXaxis()->SetBinLabel(4, "lep tau, mu");
					h_gen_lep2_id_ge4j[iHisto]->GetXaxis()->SetBinLabel(5, "had tau, 1 prong");
					h_gen_lep2_id_ge4j[iHisto]->GetXaxis()->SetBinLabel(6, "had tau, 3 prong");
					h_gen_lep2_id_ge4j[iHisto]->GetXaxis()->SetBinLabel(7, "\"other\" tau");

	
				} // end if sample is ttbar
      

      } // end loop over mass pts (1 pt only if not signal scan)
    } // end loop over genClassifications for histogram arrays
  } // end loop over analyzers/regions for histogram arrays


	// Set up cutflow histograms
	TH1D* h_cutflow[nAnalyzers];
	for( int iAna=0; iAna<nAnalyzers; iAna++ ) {

		analyzer* thisAnalyzer = analyzers.at(iAna);
		std::string histName  = "h_cutflow_";
		std::string histTitle = "Cutflow histogram ";
		histName  += thisAnalyzer->GetLabel();
		histTitle += thisAnalyzer->GetLabel();

		h_cutflow[iAna] = selectionInfo::get_cutflowHistoTemplate( thisAnalyzer->GetSelections(), histName, histTitle );
	}


  //////////////////////
  //                  //
  // Loop Over Events //
  //                  //
  //////////////////////
    
  // Event Counters
  cout << "    Loading files to loop over" << endl << endl;
  unsigned int nEventsTotal = 0;
  unsigned int nEventsChain = chain->GetEntries();
  if( nEvents >= 0 ) nEventsChain = nEvents;
  
  // Grab list of files
  TObjArray *listOfFiles = chain->GetListOfFiles();
  TIter fileIter(listOfFiles);
  TFile *currentFile = 0;
  while ( (currentFile = (TFile*)fileIter.Next()) ) {
    
    
    //////////////////////
    //                  //
    // Get File Content //
    //                  //
    //////////////////////
    
    // Open File and Get Tree
    TFile *file = new TFile( currentFile->GetTitle(), "read" );
    TTree *tree = (TTree*)file->Get("t");
    if(readFast) TTreeCache::SetLearnEntries(10);
    if(readFast) tree->SetCacheSize(128*1024*1024);
    babyAnalyzer.Init(tree);
    
    // Get weight histogram from baby
    wgtInfo.getWeightHistogramFromBaby( file );
    
    // Loop over Events in current file
    if( nEventsTotal >= nEventsChain ) continue;
    unsigned int nEventsTree = tree->GetEntriesFast();
    for( unsigned int event = 0; event < nEventsTree; ++event) {

      
      ///////////////////////
      //                   //
      // Get Event Content //
      //                   //
      ///////////////////////
   
      // Read Tree
      if( nEventsTotal >= nEventsChain ) continue;
      if(readFast) tree->LoadTree(event);
      babyAnalyzer.GetEntry(event);
      ++nEventsTotal;

      // Progress
      stop_1l_babyAnalyzer::progress( nEventsTotal, nEventsChain );

      
      /////////////////////
      //                 //
      // Check Selection //
      //                 //
      /////////////////////


      // Check JSON
      if( sample.isData && applyjson ) {
	if( !goodrun(run(),ls()) ) continue;
      }
	
      // Check duplicate event
      if( sample.isData ) {
	duplicate_removal::DorkyEventIdentifier id(run(), evt(), ls());
	if( is_duplicate(id) ) continue;
      }

      // Check WNJets genPt
      if( sample.id == sampleInfo::k_W1JetsToLNu_madgraph_pythia8 ||
					sample.id == sampleInfo::k_W2JetsToLNu_madgraph_pythia8 ||
					sample.id == sampleInfo::k_W3JetsToLNu_madgraph_pythia8 ||
					sample.id == sampleInfo::k_W4JetsToLNu_madgraph_pythia8    ) {
				if( nupt()>200.0 ) continue;
      }

			// Pre-calculate all the event weights
      wgtInfo.getEventWeights();



      /////////////////////////////
      //                         //
      // Compute Event Variables //
      //                         //
      /////////////////////////////

      // Find the gen pT of the ttbar system
      double ttbarPt = -99.9;
      LorentzVector genTTbar_LV;
      int nFoundGenTop=0;
      if( sampleIsTTbar ) {
	
				for(int iGen=0; iGen<(int)genqs_p4().size(); iGen++) {
					if( abs(genqs_id().at(iGen))==6 && genqs_isLastCopy().at(iGen) ) {
						genTTbar_LV += genqs_p4().at(iGen);
						nFoundGenTop++;
					} // end if last copy of top
				} // end loop over gen quarks

				if( nFoundGenTop == 2 ) ttbarPt = genTTbar_LV.Pt();

      } // end if sample is ttbar

      
      // Find the gen ID of the 2nd lepton
      double matched_lep_dr = 0.1;

      int gen2ndLep__idx = -1;
      int gen2ndLep__id = -99;
      int gen2ndLep__tauDecay = -1;
      int fill_bin_genLep2ID = -1;
      if( !sample.isData && is2lep() ) {
	
				// match leading lepton first
				int genLep_matchedTo_selLep__idx = -1;
				for(int iGen=0; iGen<(int)genleps_p4().size(); iGen++) {
					if( abs(genleps_id().at(iGen)) != abs(lep1_pdgid()) ) continue;
					if( !genleps_isLastCopy().at(iGen) ) continue;
					if( !genleps_fromHardProcessFinalState().at(iGen) &&
							!genleps_fromHardProcessDecayed().at(iGen)       ) continue;
					if( ROOT::Math::VectorUtil::DeltaR(genleps_p4().at(iGen), lep1_p4()) < matched_lep_dr ) {
						genLep_matchedTo_selLep__idx = iGen;
						break;
					}
				}

				// If matched selected lepton, find lost gen lepton
				if( genLep_matchedTo_selLep__idx>0 ) {

					for(int iGen=0; iGen<(int)genleps_p4().size(); iGen++) {
						if( iGen == genLep_matchedTo_selLep__idx ) continue;
						if( !genleps_isLastCopy().at(iGen) ) continue;
						if( !genleps_fromHardProcessFinalState().at(iGen) &&
								!genleps_fromHardProcessDecayed().at(iGen)       ) continue;
						gen2ndLep__idx = iGen;
						gen2ndLep__id = genleps_id().at(iGen);
						gen2ndLep__tauDecay = genleps_gentaudecay().at(iGen);
					}

					// If found second lep
					if( gen2ndLep__idx>=0 ) {
	      
						if( abs(gen2ndLep__id)==11 ) fill_bin_genLep2ID = 1;  // "ele";
						if( abs(gen2ndLep__id)==13 ) fill_bin_genLep2ID = 2;  // "mu";
						if( abs(gen2ndLep__id)==15 ) {
							if( gen2ndLep__tauDecay==1 ) fill_bin_genLep2ID = 3;  // "lep tau, ele";
							if( gen2ndLep__tauDecay==2 ) fill_bin_genLep2ID = 4;  // "lep tau, mu";
							if( gen2ndLep__tauDecay==3 ) fill_bin_genLep2ID = 5;  // "had tau, 1 prong";
							if( gen2ndLep__tauDecay==4 ) fill_bin_genLep2ID = 6;  // "had tau, 3 prong";
							if( gen2ndLep__tauDecay==5 ) fill_bin_genLep2ID = 7;  // "\"other\" tau";
						} // end if 2nd lep is tau


					} // end if found 2nd gen lep
				} // end if found first gen lep, matched to selected lepton
      } // end if 2lep event and not data

      // Calculate p4 of (lep1 lep2 b b) system
      LorentzVector lep1lep2bb_TLV(0.0,0.0,0.0,0.0);

      LorentzVector lep1lep2bbMet_TLV(0.0,0.0,0.0,0.0);
      double lep1lep2bbMet_pt = -99.9;

      lep1lep2bb_TLV += lep1_p4();
      if(nvetoleps()>1) lep1lep2bb_TLV += lep2_p4();
      
      int jet1_idx = -1;
      double max_deepcsv = -99.9;
      for(int iJet=0; iJet<(int)ak4pfjets_p4().size(); iJet++) {
				if( ak4pfjets_deepCSV().at(iJet) > max_deepcsv ) {
					jet1_idx = iJet;
					max_deepcsv  = ak4pfjets_deepCSV().at(iJet);
				}
      }
      if(jet1_idx>=0) lep1lep2bb_TLV += ak4pfjets_p4().at(jet1_idx);
      
      int jet2_idx = -1;
      max_deepcsv = -99.9;
      for(int iJet=0; iJet<(int)ak4pfjets_p4().size(); iJet++) {
				if( iJet==jet1_idx ) continue;
				if( ak4pfjets_deepCSV().at(iJet) > max_deepcsv ) {
					jet2_idx = iJet;
					max_deepcsv = ak4pfjets_deepCSV().at(iJet);
				}
      }
      if(jet2_idx>=0) lep1lep2bb_TLV += ak4pfjets_p4().at(jet2_idx);
      
      // Calculate p4 of (lep1 lep2 b b MET) system
      lep1lep2bbMet_TLV = lep1lep2bb_TLV;
      LorentzVector met_TLV( pfmet()*cos(pfmet_phi()), pfmet()*sin(pfmet_phi()), 0.0, pfmet() );
      lep1lep2bbMet_TLV += met_TLV;
    
      lep1lep2bbMet_pt = lep1lep2bbMet_TLV.Pt();

      // Calculate mlb using lep2 instead of lep1
      LorentzVector lep2b_TLV(0.0,0.0,0.0,0.0);
      double minDr = 99.9;
      int minBJetIdx = -99;
      if(nvetoleps()>1) {
				lep2b_TLV += lep2_p4();
				for(int iJet=0; iJet<(int)ak4pfjets_p4().size(); iJet++) {
					if(!ak4pfjets_passMEDbtag().at(iJet)) continue;
					if(ROOT::Math::VectorUtil::DeltaR(ak4pfjets_p4().at(iJet),lep2_p4())<minDr) {
						minDr = ROOT::Math::VectorUtil::DeltaR(ak4pfjets_p4().at(iJet),lep2_p4());
						minBJetIdx = iJet;
					}
				} // end loop over jets
				if(minBJetIdx>=0) lep2b_TLV += ak4pfjets_p4().at(minBJetIdx);
      } // end if nvetoleps>1

      int mStop = mass_stop();
      int mLSP  = mass_lsp();



			/////////////////////////////////////////////////////////////
			//                                                         //
			// Loop over all analyzers, genClassy's, systematics, etc. //
			//                                                         //
			/////////////////////////////////////////////////////////////

			// Loop over all analyzers
			for( int iAna=0; iAna<nAnalyzers; iAna++ ) {
				analyzer* thisAnalyzer = analyzers.at(iAna);


				// Make an array of which genClassy's this event passes
				bool passedGenClassies[genClassyInfo::k_nGenClassy];
				for( genClassyInfo::Util thisGenClassy : thisAnalyzer->GetGenClassifications() ) {
					passedGenClassies[thisGenClassy.id] = thisGenClassy.eval_GenClassy();

					// Manually correct the ZZto2L2Nu sample
					if( sample.id==sampleInfo::k_ZZTo2L2Nu_powheg_pythia8 ) {
						if( thisGenClassy.id == genClassyInfo::k_ge2lep ||
								thisGenClassy.id == genClassyInfo::k_incl ) passedGenClassies[thisGenClassy.id] = true;
						else passedGenClassies[thisGenClassy.id] = false;
					}
				}

				// Check if this event passes selections with JES set to nominal
				//  (saves us having to evaluate this for every systematic)
				thisAnalyzer->SetJesType( 0 );
				bool pass_JESnominal = thisAnalyzer->PassSelections();

				// Fill cutflow histogram
				std::vector<bool> cutflow_results = selectionInfo::get_selectionResults( thisAnalyzer->GetSelections() );
				for( uint i=0; i<cutflow_results.size(); i++ ) {
					if( !cutflow_results.at(i) ) break;
					h_cutflow[iAna]->Fill( i+1 );
				}


				// Loop over all systematics in the analyzer
				for( sysInfo::Util thisSystematic : thisAnalyzer->GetSystematics() ) {

					// Check if this event passes selections, and also set the appropriate JES type for future use
					if( thisSystematic.id == sysInfo::k_JESUp ) {
						thisAnalyzer->SetJesType( 1 );
						if( !thisAnalyzer->PassSelections() ) continue;
					}
					else if( thisSystematic.id == sysInfo::k_JESDown ) {
						thisAnalyzer->SetJesType( -1 );
						if( !thisAnalyzer->PassSelections() ) continue;
					}
					else {
						thisAnalyzer->SetJesType( 0 );
						if( !pass_JESnominal ) continue;
					}

					// If we've passed selections, then get the event weight and the categories passed
					double weight = thisAnalyzer->GetEventWeight( thisSystematic.id );
					std::vector<int> categories_passed = thisAnalyzer->GetCategoriesPassed();

					// Loop over all the gen classifications that we passed
					for( genClassyInfo::Util thisGenClassy : thisAnalyzer->GetGenClassifications() ) {
						int iGen = thisGenClassy.id;
						if( !passedGenClassies[iGen] ) continue;

						// Get the index for the histogram corresponding to this genClassy and systematic
						int histIndex = iGen*nSystematics + thisSystematic.id;

						// Fill yield histograms
						for( int category : categories_passed ) {
							if( sample.isSignalScan ) {
								TH3D* yieldHisto = (TH3D*)thisAnalyzer->GetYieldHistogram( histIndex );
								yieldHisto->Fill( mStop, mLSP, category, weight );
							}
							else thisAnalyzer->GetYieldHistogram( histIndex )->Fill( category, weight );
						}

						/////////////////////////////////////
						//                                 //
						// Fill other non-yield histograms //
						//                                 //
						/////////////////////////////////////

						if( thisSystematic.id == sysInfo::k_nominal ) {

							for(int iMassPt=0; iMassPt<nMassPts; iMassPt++) {

								if( sample.isSignalScan && mStop!=sample.massPtList[iMassPt].first && mLSP!=sample.massPtList[iMassPt].second ) continue;
								//if(!isnormal(wgt_nominal)) cout << "NaN/inf weight: nEntries=" << wgtInfo.nEvents << ", lepSF=" << wgtInfo.sf_lep << ", vetoLep="<< wgtInfo.sf_vetoLep << ", btagSF=" << wgtInfo.sf_bTag << endl;
								// Histo Index
								int iHisto = iAna*nGenClassy*nMassPts + iGen*nMassPts + iMassPt;

								// Vars
								double nGoodJets = ngoodjets();

								bool add2ndLepToMet = thisAnalyzer->GetAdd2ndLep();

								double mt =         add2ndLepToMet ? mt_met_lep_rl() : mt_met_lep();
								double modTopness = add2ndLepToMet ? topnessMod_rl() : topnessMod();
								double met =        add2ndLepToMet ? pfmet_rl() : pfmet();

								double mlb = Mlb_closestb();
								if( TString(thisAnalyzer->GetLabel()).Contains("CR0b") ) mlb = ( lep1_p4() + ak4pfjets_leadbtag_p4() ).M();

								// Met Sideband CR area, met>=150

								if( met>=150 && met<250 ) {
									// mlb, met sideband CR
									h_mlb_150to250met_incl[iHisto]->Fill( mlb, weight );
									if( nGoodJets<4 )  h_mlb_150to250met_lt4j[iHisto]->Fill( mlb, weight );
									if( nGoodJets>=4 ) h_mlb_150to250met_ge4j[iHisto]->Fill( mlb, weight );
	      
									// mlb_lep2, met sideband CR
									if(nvetoleps()>1 && minBJetIdx>=0) {
										h_mlb_lep2_150to250met_incl[iHisto]->Fill( lep2b_TLV.M(), weight );
										if( nGoodJets<4 )  h_mlb_lep2_150to250met_lt4j[iHisto]->Fill( lep2b_TLV.M(), weight );
										if( nGoodJets>=4 ) h_mlb_lep2_150to250met_ge4j[iHisto]->Fill( lep2b_TLV.M(), weight );
									}

								} // end if 150<met<250

								// Signal Region Area, met>=250
								if( met<250.0 ) continue;
	    
								// nJets
								h_nJets[iHisto]->Fill( nGoodJets, weight );

								// nBTags
								h_nBTags[iHisto]->Fill( ngoodbtags(), weight );
	    
								// lep1 pT
								h_lep1Pt_incl[iHisto]->Fill( lep1_p4().Pt(), weight );

								// lep2 pT
								if( nvetoleps()>1 ) h_lep2Pt_incl[iHisto]->Fill( lep2_p4().Pt(), weight );

								// jet pT
								for(int iJet=0; iJet<(int)ak4pfjets_p4().size(); iJet++) h_jetPt_incl[iHisto]->Fill( ak4pfjets_p4().at(iJet).Pt(), weight );

								// jet1 pT
								h_jet1Pt_incl[iHisto]->Fill( ak4pfjets_p4().at(0).Pt(), weight );

								// jet2 pT
								h_jet2Pt_incl[iHisto]->Fill( ak4pfjets_p4().at(1).Pt(), weight );

								// DeepCSV jet1 pT
								if(jet1_idx>=0) h_deepcsvJet1Pt_incl[iHisto]->Fill( ak4pfjets_p4().at(jet1_idx).Pt(), weight );

								// DeepCSV jet2 pT
								if(jet2_idx>=0) h_deepcsvJet2Pt_incl[iHisto]->Fill( ak4pfjets_p4().at(jet2_idx).Pt(), weight );

								// met
								h_met_incl[iHisto]->Fill( met, weight );
								if( nGoodJets<4  ) h_met_lt4j[iHisto]->Fill( met, weight );
								if( nGoodJets>=4 ) h_met_ge4j[iHisto]->Fill( met, weight );

								// lep1lep2bbMetPt
								h_lep1lep2bbMetPt_incl[iHisto]->Fill( lep1lep2bbMet_pt, weight );
								if( nGoodJets<4  ) h_lep1lep2bbMetPt_lt4j[iHisto]->Fill( lep1lep2bbMet_pt, weight );
								if( nGoodJets>=4 ) h_lep1lep2bbMetPt_ge4j[iHisto]->Fill( lep1lep2bbMet_pt, weight );

								// mt
								h_mt_incl[iHisto]->Fill( mt, weight );

								// modTopness
								h_modTopness_incl[iHisto]->Fill( modTopness, weight );
								if( nGoodJets<4  ) h_modTopness_lt4j[iHisto]->Fill( modTopness, weight );
								if( nGoodJets>=4 ) h_modTopness_ge4j[iHisto]->Fill( modTopness, weight );

								// mlb
								h_mlb_incl[iHisto]->Fill( mlb, weight );
								if( nGoodJets<4 )  h_mlb_lt4j[iHisto]->Fill( mlb, weight );
								if( nGoodJets>=4 ) h_mlb_ge4j[iHisto]->Fill( mlb, weight );

								// mlb, modTopness bins
								if(modTopness<0.0)   h_mlb_lt0modTopness[iHisto]->Fill( mlb, weight );
								if(modTopness>=0.0)  h_mlb_ge0modTopness[iHisto]->Fill( mlb, weight );
								if(modTopness>=10.0) h_mlb_ge10modTopness[iHisto]->Fill( mlb, weight );

								// mlb_lep2
								if(nvetoleps()>1 && minBJetIdx>=0) {
									h_mlb_lep2_incl[iHisto]->Fill( lep2b_TLV.M(), weight );
									if( nGoodJets<4 )  h_mlb_lep2_lt4j[iHisto]->Fill( lep2b_TLV.M(), weight );
									if( nGoodJets>=4 ) h_mlb_lep2_ge4j[iHisto]->Fill( lep2b_TLV.M(), weight );
								}

								// Gen TTBar System
								if( sampleIsTTbar ) {
									h_gen_ttbarPt_incl[iHisto]->Fill( ttbarPt, weight );
									if( nGoodJets<4 )  h_gen_ttbarPt_lt4j[iHisto]->Fill( ttbarPt, weight );
									if( nGoodJets>=4 ) h_gen_ttbarPt_ge4j[iHisto]->Fill( ttbarPt, weight );
								}

								// Gen 2nd Lep ID
								if( !sample.isData && is2lep() && gen2ndLep__idx>=0 ) {
									h_gen_lep2_id_incl[iHisto]->Fill( fill_bin_genLep2ID, weight );
									if( ngoodjets()<4 )  h_gen_lep2_id_lt4j[iHisto]->Fill( fill_bin_genLep2ID, weight );
									if( ngoodjets()>=4 ) h_gen_lep2_id_ge4j[iHisto]->Fill( fill_bin_genLep2ID, weight );
								}

							} // end loop over mass points (1 if not signal scan)

						} // End filling of non-yield histograms

					} // End loop over genClassy's

				} // End loop over systematics

			} // End loop over analyzers

		} // End loop over events in tree


    //
    // Clean Up
    //
    delete tree;
    file->Close();
    delete file;

  } // end loop over file list


  //
  // Output Sanitation
  //
  if ( nEventsChain != nEventsTotal ) {
	  cout << Form( "ERROR: number of events from files (%d) is not equal to total number of events (%d)", nEventsChain, nEventsTotal ) << endl;
  }


  //
  // Print Selection Cutflow
  //
  cout << "====================================================" << endl;
  cout << endl;
  for(int iAna=0; iAna<nAnalyzers; iAna++) {
	  cout << "    " << analyzers.at(iAna)->GetLabel() << " Cutflow: " << endl;
	  for(int iCut=1; iCut<=(int)h_cutflow[iAna]->GetNbinsX(); iCut++) {
		  cout << "      nEvents pass " << h_cutflow[iAna]->GetXaxis()->GetBinLabel(iCut) << " = " << h_cutflow[iAna]->GetBinContent(iCut) << endl;
	  }
	  cout << endl;
	  cout << endl;
  }
  cout << "====================================================" << endl;


  //
  // Clean stopCORE objects
  //
  wgtInfo.cleanUp(); 


  //
  // Close Output File
  //
  f_output->Write();
  f_output->Close();


  //
  // Clean input chain
  // 
  chain->~TChain();
  if( sample.isData ) duplicate_removal::clear_list();

  //
  // Benchmark Reporting
  //
  bmark->Stop("benchmark");
  cout << endl;
  cout << nEventsTotal << " Events Processed" << endl;
  cout << "------------------------------" << endl;
  cout << "CPU  Time:	" << Form( "%.01f", bmark->GetCpuTime("benchmark")  ) << endl;
  cout << "Real Time:	" << Form( "%.01f", bmark->GetRealTime("benchmark") ) << endl;
  cout << endl;
  delete bmark;

  cout << "====================================================" << endl;
    
  //fclose(f_evtList);

  //
  // Return!
  //
  return 0;

} // End of function "looper"
Example #10
0
void looper::ScanChain (TChain* chain, const char* prefix, bool isData, int nEvents){

  bookHistos();

  set_goodrun_file("Cert_TopAug13_Merged_135059-142664_goodruns.txt");
  ofile.open( Form( "output/%s_%s_events.txt" , prefix , iter ) );

  TObjArray *listOfFiles = chain->GetListOfFiles();

  unsigned int nEventsChain = 0;
  if(nEvents == -1) 
    nEvents = chain->GetEntries();
  nEventsChain = nEvents;
  unsigned int nEventsTotal = 0;

  MakeBabyNtuple( Form( "output/%s_%s_baby.root" , prefix , iter) );

  DorkyEventIdentifier dei;

  //pass fail counters
  int nPassDuplicate  = 0;
  int nPassGoodRun    = 0;

  float nGoodMu = 0;
  float nGoodEl = 0;

  if( debug ) cout << "Begin looping over files" << endl;

  if( isData ){
    cout << "|" << setw(8)  << "run"          << setw(4) 
         << "|" << setw(6)  << "lumi"         << setw(4) 
         << "|" << setw(12) << "event"        << setw(4) 
         << "|" << setw(6)  << "type"         << setw(4) 
         << "|" << setw(6)  << "njets"        << setw(4) 
         << "|" << setw(6)  << "nbtags"       << setw(4) 
         << "|" << setw(8)  << "tcmet"        << setw(4) 
         << "|" << setw(8)  << "cltcmet"      << setw(4) 
         << "|" << setw(8)  << "pftcmet"      << setw(4) 
         << "|" << setw(8)  << "pfmet"        << setw(4) 
         << "|" << setw(8)  << "dphi"         << setw(4) << "|" << endl; 
  }

  // file loop
  TIter fileIter(listOfFiles);
  TFile* currentFile = 0;
  while ((currentFile = (TFile*)fileIter.Next()))
    {
      TFile f(currentFile->GetTitle());
      TTree *tree = (TTree*)f.Get("Events");
      cms2.Init(tree);

      // event loop
      unsigned int nEvents = tree->GetEntries();

      for (unsigned int event = 0; event < nEvents; ++event)
        {
          if( debug ) cout << "Event " << event << endl;

          cms2.GetEntry(event);
          ++nEventsTotal;

          // progress feedback to user
          if (nEventsTotal % 1000 == 0)
            {
              // xterm magic from L. Vacavant and A. Cerri
              if (isatty(1))
                {
                  printf("\015\033[32m ---> \033[1m\033[31m%4.1f%%"
                         "\033[0m\033[32m <---\033[0m\015", (float)nEventsTotal/(nEventsChain*0.01));
                  fflush(stdout);
                }
            }
	  

          //APPLY BASIC EVENT SELECTIONS
          //TRIGGER, TRACKING AND VERTEX
          if( dei.is_duplicate( DorkyEvent() ) ) continue;
          nPassDuplicate++;

          if (!isData || goodrun(cms2.evt_run(), cms2.evt_lumiBlock()))
            nPassGoodRun++;
	  else continue;
        
          float weight = 1.;
          if     ( strcmp(prefix,"data") == 0  ) weight = 1;
          else if( strcmp(prefix,"ZJets") == 0 ) weight = 1.27 * 2.2121427 * 0.84e-3;
          else if( strcmp(prefix,"TTBar") == 0 ) weight = 0.1112306 * 0.84e-3;
          else if( strcmp(prefix,"Vqq") == 0   ) weight = 0.0408562 * 0.84e-3;
          else{
            cout << "I DON'T RECOGNIZE " << prefix << endl;
            exit(0);
          }

          for( unsigned int hypIdx = 0 ; hypIdx < hyp_type().size() ; hypIdx++ ){
      
            InitBabyNtuple();
            
            int myType = 99;
            if (hyp_type()[hypIdx] == 3) myType = 0;                          // ee
            if (hyp_type()[hypIdx] == 0) myType = 1;                          // mm
            if (hyp_type()[hypIdx] == 1 || hyp_type()[hypIdx] == 2) myType=2; // em
            if (myType == 99) {
              cout << "Skipping unknown dilepton type = " << hyp_type()[hypIdx] << endl;
              continue;
            }

            //----------SELECTION----------------------------------------------------

            //pT > (20,20) GeV
            if( hyp_ll_p4()[hypIdx].pt() < 20 ) continue;
            if( hyp_lt_p4()[hypIdx].pt() < 20 ) continue;
 
            //ttbar muon ID
            if (abs(hyp_ll_id()[hypIdx]) == 13  && (! (fabs(hyp_ll_p4()[hypIdx].eta()) < 2.4 && muonId(hyp_ll_index()[hypIdx],NominalTTbar))))   continue;
            if (abs(hyp_lt_id()[hypIdx]) == 13  && (! (fabs(hyp_lt_p4()[hypIdx].eta()) < 2.4 && muonId(hyp_lt_index()[hypIdx],NominalTTbar))))   continue;
         
            //ttbarV1 electron ID
            if (abs(hyp_ll_id()[hypIdx]) == 11  && (! pass_electronSelection( hyp_ll_index()[hypIdx] , electronSelection_ttbarV1 , isData ))) continue;
            if (abs(hyp_lt_id()[hypIdx]) == 11  && (! pass_electronSelection( hyp_lt_index()[hypIdx] , electronSelection_ttbarV1 , isData ))) continue;

            //ttbar electron ID
            //if (abs(hyp_ll_id()[hypIdx]) == 11  && (! pass_electronSelection( hyp_ll_index()[hypIdx] , electronSelection_ttbar , isData ))) continue;
            //if (abs(hyp_lt_id()[hypIdx]) == 11  && (! pass_electronSelection( hyp_lt_index()[hypIdx] , electronSelection_ttbar , isData ))) continue;

            //nominal muon ID
            //if (abs(hyp_ll_id()[hypIdx]) == 13  && (! (fabs(hyp_ll_p4()[hypIdx].eta()) < 2.4 && muonId(hyp_ll_index()[hypIdx]))))   continue;
            //if (abs(hyp_lt_id()[hypIdx]) == 13  && (! (fabs(hyp_lt_p4()[hypIdx].eta()) < 2.4 && muonId(hyp_lt_index()[hypIdx]))))   continue;
         
            //ttbar electron ID
            //if (abs(hyp_ll_id()[hypIdx]) == 11  && (! pass_electronSelection( hyp_ll_index()[hypIdx] , electronSelection_cand01 ))) continue;
            //if (abs(hyp_lt_id()[hypIdx]) == 11  && (! pass_electronSelection( hyp_lt_index()[hypIdx] , electronSelection_cand01 ))) continue;

            //same flavor
            if( hyp_type()[hypIdx] == 1 ) continue;
            if( hyp_type()[hypIdx] == 2 ) continue;
            
            //opposite sign
            if( hyp_lt_id()[hypIdx] *  hyp_ll_id()[hypIdx] > 0 ) continue;

            //fill dilmass histo before cutting on dilmass
            dilMass_ = hyp_p4()[hypIdx].mass();
            fillHistos( hdilMass          , dilMass_  , weight , myType );

            if( dilMass_ < 76. || dilMass_ > 106. ) continue;

            if( myType == 0 ) nGoodEl+=weight;
            if( myType == 1 ) nGoodMu+=weight;

            //----------CORRECT TCMET FOR HYP MUONS---------------------------------------------

            metStruct tcmetStruct = correctTCMETforHypMuons( hypIdx , 
                                                             evt_tcmet() * cos( evt_tcmetPhi() ), 
                                                             evt_tcmet() * sin( evt_tcmetPhi() ),
                                                             evt_tcsumet() );
              
 

            // out-of-the-box  tcmet stuff (corrected for hyp muons)
            tcmet_    = tcmetStruct.met;
            tcmetphi_ = tcmetStruct.metphi;
            tcsumet_  = tcmetStruct.sumet;

            if( isData ){
              
              metStruct tcmetStructNewCalo = correctTCMETforHypMuons( hypIdx , 
                                                                      evtNew_tcmet() * cos( evtNew_tcmetPhi() ), 
                                                                      evtNew_tcmet() * sin( evtNew_tcmetPhi() ),
                                                                      evtNew_tcsumet() );
              tcmetNew_calo_ = tcmetStructNewCalo.met;

              metStruct tcmetStructNewPFC = correctTCMETforHypMuons( hypIdx , 
                                                                     evtNewPFC_tcmet() * cos( evtNewPFC_tcmetPhi() ), 
                                                                     evtNewPFC_tcmet() * sin( evtNewPFC_tcmetPhi() ),
                                                                     evtNewPFC_tcsumet() );
              tcmetNew_pfc_ = tcmetStructNewPFC.met;

            }else{
              tcmetNew_calo_ = tcmet_;
              tcmetNew_pfc_  = tcmet_;
            }


            //---------JET STUFF--------------------------------------------------------------

            int nJets        = 0;
            float sumJetPt   = 0;
            int nBTags       = 0;
            float maxcosdphi = -99;
            int imax         = -1;
            
            for (unsigned int ijet = 0; ijet < pfjets_p4().size(); ijet++) {

              LorentzVector vjet = pfjets_p4().at(ijet);
              LorentzVector vlt  = hyp_lt_p4()[hypIdx];
              LorentzVector vll  = hyp_ll_p4()[hypIdx];
              if (dRbetweenVectors(vjet, vll) < 0.4) continue;
              if (dRbetweenVectors(vjet, vlt) < 0.4) continue;
              
              if ( vjet.pt() > 30. && fabs(vjet.eta()) < 2.5 ) {
                nJets++;
                sumJetPt+=vjet.pt();
                fillHistos( hjetpt , vjet.pt() , weight , myType );

                float dRmin = 100;
                int imin = -1;
                
                if( fabs( cos( tcmetphi_ - vjet.phi() ) ) > maxcosdphi ){
                  maxcosdphi = fabs( cos( tcmetphi_ - vjet.phi() ) );
                  imax = ijet;
                  dphijetmet_ = fabs( tcmetphi_ - vjet.phi() );
                  if( dphijetmet_ > TMath::Pi() ) dphijetmet_ = TMath::TwoPi() - dphijetmet_;
                }

                //find closest calojet to use btagging info
                for( unsigned int icalojet = 0 ; icalojet < jets_p4().size() ; icalojet++ ){

                  LorentzVector vcalojet = jets_p4().at(icalojet);
                  if( vcalojet.pt() * jets_cor().at(icalojet) < 10 ) continue;
                  
                  float dR = dRbetweenVectors(vjet, vcalojet);
                  if( dR < dRmin ){
                    dRmin = dR;
                    imin = icalojet;
                  }
                }

                if( imin > -1 ){
                  if( jets_simpleSecondaryVertexHighEffBJetTag().at(imin) > 1.74 ) nBTags++;
                  //if( jets_trackCountingHighEffBJetTag().at(imin) > 1.7 ) nBTags++;
                }

              }
            }

          
            
      

            // event stuff
            run_    = cms2.evt_run();
            lumi_   = cms2.evt_lumiBlock();
            event_  = cms2.evt_event();

            // pf met stuff
            pfmet_    = cms2.evt_pfmet();
            pfmetphi_ = cms2.evt_pfmetPhi();
            pfsumet_  = cms2.evt_pfsumet();

            //calomet
            met_       = cms2.evt_met();
            metphi_    = cms2.evt_metPhi();
            sumet_     = cms2.evt_sumet();
     
            //electron eta
            if( myType == 0 ){
              if( tcmet_ < 20 ){
                fillUnderOverFlow( heleta_metlt20 , hyp_lt_p4()[hypIdx].eta() , weight );
                fillUnderOverFlow( heleta_metlt20 , hyp_ll_p4()[hypIdx].eta() , weight );
              }
              else if( tcmet_ > 30 ){
                fillUnderOverFlow( heleta_metgt30 , hyp_lt_p4()[hypIdx].eta() , weight );
                fillUnderOverFlow( heleta_metgt30 , hyp_ll_p4()[hypIdx].eta() , weight );
              }
            }

            //muon eta
            if( myType == 1 ){
              if( tcmet_ < 20 ){
                fillUnderOverFlow( hmueta_metlt20 , hyp_lt_p4()[hypIdx].eta() , weight );
                fillUnderOverFlow( hmueta_metlt20 , hyp_ll_p4()[hypIdx].eta() , weight );
              }
              else if( tcmet_ > 30 ){
                fillUnderOverFlow( hmueta_metgt30 , hyp_lt_p4()[hypIdx].eta() , weight );
                fillUnderOverFlow( hmueta_metgt30 , hyp_ll_p4()[hypIdx].eta() , weight );
              }
            }

            //look at track pT's near electron
            if( myType == 0 && tcmet_ > 30 ){
              for( unsigned int itrk = 0 ; itrk < trks_trk_p4().size() ; ++itrk ){
               
                if( isMuon( itrk ) )            continue;
                if( isElectron( itrk ) )        continue;
                if( !isGoodTrack( itrk ) )      continue;
             
                LorentzVector vtrk = trks_trk_p4().at(itrk);
                LorentzVector vlt  = hyp_lt_p4()[hypIdx];
                LorentzVector vll  = hyp_ll_p4()[hypIdx];

                float drll = dRbetweenVectors(vtrk, vll);
                float drlt = dRbetweenVectors(vtrk, vlt);

                if( drll < 0.3 || drlt < 0.3 ){
                  fillUnderOverFlow( htrkptnearel , trks_trk_p4().at(itrk).pt() , weight );
                  //printEvent();
                  //cout << "pt eta phi " << vtrk.pt() << " " << vtrk.eta() << " " << vtrk.phi() << endl;
                }
              }
            }

            string leptype[2]={"ee","mm"};

            if( isData && ( tcmet_ > 30. || pfmet_ > 30. ) ){

              if( calculateTCMET ){
                
                // calculate tcmet on-the-fly
                metStruct structMET = correctedTCMET( true, ofile );
                
              }

              cout << "|" << setw(8)  << evt_run()                   << setw(4) 
                   << "|" << setw(6)  << evt_lumiBlock()             << setw(4) 
                   << "|" << setw(12) << evt_event()                 << setw(4) 
                   << "|" << setw(6)  << leptype[myType]             << setw(4) 
                   << "|" << setw(6)  << nJets                       << setw(4) 
                   << "|" << setw(6)  << nBTags                      << setw(4) 
                   << "|" << setw(8)  << fround(tcmet_,1)            << setw(4) 
                   << "|" << setw(8)  << fround(tcmetNew_calo_,1)    << setw(4) 
                   << "|" << setw(8)  << fround(tcmetNew_pfc_,1)     << setw(4) 
                   << "|" << setw(8)  << fround(pfmet_,1)            << setw(4) 
                   << "|" << setw(8)  << fround(dphijetmet_,2)       << setw(4) << "|" << endl; 
            }

            if( imax > -1 ){

              if( tcmet_ < 20 )
                fillHistos( hdphijetmet_metlt20  , dphijetmet_    , weight , myType , nJets  );

              if( tcmet_ > 30 )
                fillHistos( hdphijetmet_metgt30  , dphijetmet_    , weight , myType , nJets  );

            }

            fillHistos( hnjets            , nJets            , weight , myType );
            fillHistos( htcmet            , tcmet_           , weight , myType , nJets );
            fillHistos( htcmetNew_calo    , tcmetNew_calo_   , weight , myType , nJets  );
            fillHistos( htcmetNew_pfc     , tcmetNew_pfc_    , weight , myType , nJets  );
            fillHistos( hpfmet            , pfmet_           , weight , myType , nJets  );
            
            njets_   = nJets;
            leptype_ = myType;

            eventTree_->Fill();
          }// end loop over hypotheses
        } // end loop over events
    } // end loop over files
  
  cout << "\n\n********************SUMMARY********************" << endl;
  cout << "Total number of events: " << nEventsTotal << endl;
  cout << "Total number of events that pass dup veto: " << nPassDuplicate 
       << " (" << 100*(double)nPassDuplicate/nEventsTotal << "% of total)" << endl;
  cout << "Total number of events that pass good run/lumi: " << nPassGoodRun 
       << " (" << 100*(double)nPassGoodRun/nEventsTotal << "% of total)" << endl;

  cout << nGoodEl << " ee events in Z mass window" << endl;
  cout << nGoodMu << " mm events in Z mass window" << endl;

  if (nEventsChain != nEventsTotal)
    std::cout << "ERROR: number of events from files is not equal to total number of events" << std::endl;

  CloseBabyNtuple();

  TDirectory *rootdir = gDirectory->GetDirectory("Rint:");
  rootdir->cd();
  saveHist( Form( "output/%s_%s_histos.root" , prefix , iter ) );
  deleteHistos();

  
} // end ScanChain
//
// Fucntions
//
void skimThisBaby(TString inPath, TString inFileName, TString inTreeName, TString outPath){

  // Talk to user
  cout << "  Skimming: "<< endl;
  cout << "     " << inPath+inFileName <<endl;
  
  // Load input TChain
  TChain *ch = new TChain(inTreeName);
  TString inFile = inPath;
  inFile += inFileName;
  ch->Add(inFile);
  Long64_t nentries = ch->GetEntries();
  TTreeCache::SetLearnEntries(10);
  ch->SetCacheSize(128*1024*1024);

  // Initialize Branches
  babyAnalyzer.Init(ch->GetTree());
  babyAnalyzer.LoadAllBranches();
  
  // Setup output file name and path
  TString outFileName = outPath;
  outFileName += inFileName;
  outFileName.ReplaceAll("*", "");
  outFileName.ReplaceAll(".root", "_skimmed.root");

  cout << "  Output will be written to: " << endl;
  cout << "      "  << outFileName << endl << endl;

  // Open outputfile and Clone input TTree
  TFile *newfile = new TFile(outFileName, "recreate");
  TTree *newtree  = (TTree*)ch->GetTree()->CloneTree(0);
  if(!newtree) cout << "BAD TTREE CLONE" << endl;

  TH1D *newCounter=NULL;
  
  // Get nEntries
  unsigned int nEventsTotal = 0;
  unsigned int nEventsChain = ch->GetEntries();
  
  // Grab list of files
  TObjArray *listOfFiles = ch->GetListOfFiles();
  TIter fileIter(listOfFiles);
  TFile *currentFile = 0;

  // File Loop
  int iFile=0;
  while ( (currentFile = (TFile*)fileIter.Next()) ) {

    // Get File Content
    TFile *file = new TFile( currentFile->GetTitle() );
    TTree *tree = (TTree*)file->Get("t");
    TTreeCache::SetLearnEntries(10);
    tree->SetCacheSize(128*1024*1024);
    babyAnalyzer.Init(tree);

    if(iFile==0){
      TH1D *temp = (TH1D*)file->Get("h_counter");
      newCounter = (TH1D*)temp->Clone("h_counter");
      newCounter->SetDirectory(newfile);
    }
    //else{
    //TH1D *temp = (TH1D*)file->Get("h_counter");
    //newCounter->Add(temp);
    //}

    // Loop over Events in current file 
    if( nEventsTotal >= nEventsChain ) continue;
    unsigned int nEventsTree = tree->GetEntriesFast();
    for( unsigned int event = 0; event < nEventsTree; ++event) {
      
      // Progress
      stop_1l_babyAnalyzer::progress( nEventsTotal, nEventsChain );
    
      // Load Tree
      tree->LoadTree(event);
      babyAnalyzer.GetEntry(event);
      ++nEventsTotal;

      // Selection
      if(nvetoleps()<1) continue;
      if(nvetoleps()<2 && PassTrackVeto_v3() && PassTauVeto()) continue;
      if(ngoodjets()<2) continue;
      if(mt_met_lep()<150.0) continue;
      if(pfmet()<200.0) continue;

      // Turn on all branches on input
      babyAnalyzer.LoadAllBranches();      
      
      // Fill output tree
      newtree->Fill();
    
    } // end loop over entries
   
    iFile++;
  } // end loop over files in TChain

  // Clean up
  //newtree->Print();
  //newtree->AutoSave();
  newfile->Write();
  newfile->Close();
  delete ch;
  delete newfile;

}
int ScanChain( TChain* chain, bool fast = true, int nEvents = -1, string skimFilePrefix = "test") {

  // Benchmark
  TBenchmark *bmark = new TBenchmark();
  bmark->Start("benchmark");

  // Example Histograms
  TDirectory *rootdir = gDirectory->GetDirectory("Rint:");
  /*
   // This loads the library
   TMVA::Tools::Instance();

   // to get access to the GUI and all tmva macros
   TString thisdir = gSystem->DirName(gInterpreter->GetCurrentMacroName());
   gROOT->SetMacroPath(thisdir + ":" + gROOT->GetMacroPath());
   gROOT->ProcessLine(".L TMVAGui.C");
*/

  map<string, TH1F*> histos; //massive
  vector<string> histonames; histonames.clear();
  vector<string> histonameshelp; histonameshelp.clear();
  vector<int> histobinn; histobinn.clear();
  vector<double> histobinl; histobinl.clear();
  vector<double> histobinu; histobinu.clear();
  map<string, float> value;

  histonames.push_back("MT2W");               histobinn.push_back(25); histobinl.push_back(0.); histobinu.push_back(500.);
  //histonames.push_back("MT2_b_b");            histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(750.);
  histonames.push_back("MT2_lb_b");           histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(750.);
  //histonames.push_back("MT2_lb_bq");          histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(750.);
  histonames.push_back("MT2_lb_bqq");         histobinn.push_back(25); histobinl.push_back(0.); histobinu.push_back(1000.);
  //histonames.push_back("MT2_l_q");            histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(300.);
  histonames.push_back("MT2_lb_b_mless");     histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(750.);
  //histonames.push_back("MT2_lb_bq_mless");    histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(750.);
  histonames.push_back("MT2_lb_bqq_mless");   histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(750.);
  //histonames.push_back("MT2_l_qq_mless");     histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(750.);
  histonames.push_back("Mlb");                histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(750.);
  //histonames.push_back("Mlbb");               histobinn.push_back(25); histobinl.push_back(0.); histobinu.push_back(1000.);
  histonames.push_back("M3b");                histobinn.push_back(25); histobinl.push_back(0.); histobinu.push_back(1000.);
  histonames.push_back("MTb");                histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(750.);
  //histonames.push_back("MTq");                histobinn.push_back(20); histobinl.push_back(0.); histobinu.push_back(500.);
  histonames.push_back("MTqmax");             histobinn.push_back(25); histobinl.push_back(0.); histobinu.push_back(1500.);
  //histonames.push_back("MTq_boostmax");       histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(1500.);
  //histonames.push_back("MTq_boost300");       histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(1500.);
  histonames.push_back("MTq_boostLeadJet");   histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(1500.);
  //histonames.push_back("MTqq");               histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(750.);
  histonames.push_back("Topness");            histobinn.push_back(30); histobinl.push_back(-15.); histobinu.push_back(15.);
  histonames.push_back("MT");                 histobinn.push_back(40); histobinl.push_back(0.); histobinu.push_back(400.);
  histonames.push_back("MET");                histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(750.);
  histonames.push_back("HT");                 histobinn.push_back(25); histobinl.push_back(0.); histobinu.push_back(1000.);
  histonames.push_back("METoverSqrtHT");      histobinn.push_back(20); histobinl.push_back(0.); histobinu.push_back(40.);
  histonames.push_back("HTratio");            histobinn.push_back(20); histobinl.push_back(0.); histobinu.push_back(1.);
  histonames.push_back("dRLepBJet");          histobinn.push_back(25); histobinl.push_back(0.); histobinu.push_back(10.);
  histonames.push_back("dRbb");               histobinn.push_back(25); histobinl.push_back(0.); histobinu.push_back(10.);
  histonames.push_back("chi2");               histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(30.);
  histonames.push_back("NBJets");             histobinn.push_back( 5); histobinl.push_back(0.); histobinu.push_back(5.);
  histonames.push_back("NJets");              histobinn.push_back(10); histobinl.push_back(0.); histobinu.push_back(10.);
  //histonames.push_back("minDPhi");            histobinn.push_back(32); histobinl.push_back(0.); histobinu.push_back(3.2);
  histonames.push_back("minDPhiJ3");          histobinn.push_back(32); histobinl.push_back(0.); histobinu.push_back(3.2);
  //histonames.push_back("minDPhiB");           histobinn.push_back(32); histobinl.push_back(0.); histobinu.push_back(3.2);
  //histonames.push_back("pTlb");               histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(600.);
  histonames.push_back("pTlbb");              histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(600.);
  histonames.push_back("pTl");                histobinn.push_back(27); histobinl.push_back(0.); histobinu.push_back(405.);
  histonames.push_back("pTleadj");            histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(750.);
  histonames.push_back("pTleadb");            histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(750.);
  //histonames.push_back("pTtrailb");           histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(750.);
  //histonames.push_back("sumak8prunedmass");   histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(750.);
  histonames.push_back("DeltaPhiWl");         histobinn.push_back(32); histobinl.push_back(0.); histobinu.push_back(3.2);

  TFile *outfile[3];
  TTree *outtree[3];
  for(unsigned int b = 0; b<histonames.size(); ++b){
    value[histonames[b] ] = -99;
    histonameshelp.push_back(histonames[b]+(string)"/F");
  }
  for(unsigned int b = 0; b<3; ++b){
    string samplename = skimFilePrefix;
    if(skimFilePrefix!="TTbar"&&b>0) continue;
    if(skimFilePrefix=="TTbar"&&b==0) samplename = "TTbar1l";
    if(skimFilePrefix=="TTbar"&&b==1) samplename = "TTbar2l";
    if(skimFilePrefix=="TTbar"&&b==2) samplename = "TTbarH";
    TString fileName = "rootfiles/TestmysmallBDTvartree_"+samplename+".root";
    outfile[b] = new TFile(fileName,"RECREATE");
    outtree[b] = new TTree(samplename.c_str(),"");
    for(unsigned int a = 0; a<histonames.size(); ++a){
      outtree[b]->Branch(histonames[a].c_str(), &value[histonames[a] ], histonameshelp[a].c_str() );
    }
  }



  // Loop over events to Analyze
  unsigned int nEventsTotal = 0;
  unsigned int nEventsChain = chain->GetEntries();
  if( nEvents >= 0 ) nEventsChain = nEvents;
  TObjArray *listOfFiles = chain->GetListOfFiles();
  TIter fileIter(listOfFiles);
  TFile *currentFile = 0;

  // File Loop
  while ( (currentFile = (TFile*)fileIter.Next()) ) {

    // Get File Content
    TFile *file = new TFile( currentFile->GetTitle() );
    TTree *tree = (TTree*)file->Get("t");
    if(fast) TTreeCache::SetLearnEntries(10);
    if(fast) tree->SetCacheSize(128*1024*1024);
    cms3.Init(tree);
    
    // Loop over Events in current file
    if( nEventsTotal >= nEventsChain ) continue;
    unsigned int nEventsTree = tree->GetEntriesFast();
    for( unsigned int event = 0; event < nEventsTree; ++event) {
 
      // Get Event Content
      if( nEventsTotal >= nEventsChain ) continue;
      if(fast) tree->LoadTree(event);
      cms3.GetEntry(event);
      ++nEventsTotal;
   
      // Progress
      CMS3::progress( nEventsTotal, nEventsChain );

      int sampleid = 0;
      string samplename = skimFilePrefix;
      if(skimFilePrefix=="TTbar"){
	if(cms3.gen_nfromtmus_() + cms3.gen_nfromtels_() + cms3.gen_nfromttaus_() ==2) { samplename = "TTbar2l"; sampleid=1; }
	else if(cms3.gen_nfromtmus_() + cms3.gen_nfromtels_() + cms3.gen_nfromttaus_() ==1) { samplename = "TTbar1l"; sampleid=0; }
	else { samplename = "TTbarH"; sampleid=2; }
      }
      // Analysis Code
      float weight = cms3.scale1fb()*10.;
      int NLeps = cms3.ngoodlep();
      string ds = cms3.dataset();
      float MET = cms3.pfmet();
      float METPhi = cms3.pfmet_phi();
      float METx = MET*TMath::Cos(METPhi);
      float METy = MET*TMath::Sin(METPhi);
      float MT2W = cms3.MT2W_lep1();
      float MT = cms3.MT_MET_lep1();
      float dRLepBJet = cms3.dR_lep1_leadb();
      float chi2 = cms3.chi2();
      //float genmet = cms3.genmet();
      //int NJets = cms3.ak4GoodPFJets();
      //int NBJets = cms3.ak4_nBTags_Med();
      float HT = cms3.ak4_HT();
      float HTratio = cms3.ak4_htratiom();
      int nvtxs = cms3.nvtxs();
      float minDPhi = cms3.mindphi_met_j1_j2();
      vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > jetslv = cms3.ak4pfjets_p4();
      vector<float> jetsbtag = cms3.ak4pfjets_btag_disc();
      vector<bool> jetsID = cms3.ak4pfjets_loose_pfid();
      ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > lep1lv = cms3.lep1_p4();
      float lep1pt = cms3.lep1_pt();
      float lep1eta = cms3.lep1_eta();
      //float lep1dr03isoDB = cms3.lep1_relIso03DB();
      bool lep1eIDl = cms3.lep1_is_eleid_loose();
      bool lep1eIDm = cms3.lep1_is_eleid_medium();
      bool lep1mIDt = cms3.lep1_is_muoid_tight();
      bool lep1ismu = cms3.lep1_is_mu();
      bool lep1isel = cms3.lep1_is_el();
      ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > lep2lv = cms3.lep1_p4();
      float lep2pt = cms3.lep2_pt();
      float lep2eta = cms3.lep2_eta();
      //float lep2dr03isoDB = cms3.lep2_relIso03DB();
      bool lep2eIDl = cms3.lep2_is_eleid_loose();
      bool lep2eIDm = cms3.lep2_is_eleid_medium();
      bool lep2mIDt = cms3.lep2_is_muoid_tight();
      bool lep2ismu = cms3.lep2_is_mu();
      bool lep2isel = cms3.lep2_is_el();
      
      bool trackveto = cms3.PassTrackVeto();
      bool tauveto = cms3.PassTauVeto();

      int NGLeps = 0;
      int NSLeps = 0;
      int NGJets = 0;
      int NGBJets = 0;

      int l1=-1;
      if(lep1ismu){
	//if(lep1pt>20&&fabs(lep1eta)<99&&lep1mIDt) ++NGLeps;
	//if(lep1pt>25&&fabs(lep1eta)<2.1&&lep1mIDt&&lep1dr03isoDB*lep1pt<TMath::Min(5.,0.15*lep1pt)) {++NSLeps; l1 = 1;}
	if(lep1pt>30&&fabs(lep1eta)<2.1&&fabs(cms3.lep1_d0())<0.02&&fabs(cms3.lep1_dz())<0.1&&cms3.lep1_miniRelIsoDB()<0.1) {++NSLeps; l1 = 1; }
      } else if (lep1isel){
	//if(lep1pt>20&&fabs(lep1eta)<99&&lep1eIDl) ++NGLeps;
	//if(lep1pt>30&&fabs(lep1eta)<1.442&&lep1eIDm&&lep1dr03isoDB*lep1pt<TMath::Min(5.,0.15*lep1pt)) {++NSLeps; l1 = 1;}
	if(lep1pt>40&&fabs(lep1eta)<2.1&&cms3.lep1_is_phys14_medium_noIso()&&cms3.lep1_miniRelIsoDB()<0.1) {++NSLeps; l1 = 1; }
      }
      if(lep2ismu){
	//if(lep2pt>20&&fabs(lep2eta)<99&&lep2mIDt) ++NGLeps;
	//if(lep2pt>25&&fabs(lep2eta)<2.1&&lep2mIDt&&lep2dr03isoDB*lep2pt<TMath::Min(5.,0.15*lep2pt)) {++NSLeps; if(l1!=1) l1 = 2; else l1=-2;}
	if(lep2pt>30&&fabs(lep2eta)<2.1&&fabs(cms3.lep2_d0())<0.02&&fabs(cms3.lep2_dz())<0.1&&cms3.lep2_miniRelIsoDB()<0.1) {++NSLeps; l1 = 1; if(l1!=1) l1 = 2; else l1=-2; }
      } else if (lep2isel){
	//if(lep2pt>20&&fabs(lep2eta)<99&&lep2eIDl) ++NGLeps;
	//if(lep2pt>30&&fabs(lep2eta)<1.442&&lep2eIDm&&lep2dr03isoDB*lep2pt<TMath::Min(5.,0.15*lep2pt)) {++NSLeps; if(l1!=1) l1 = 2; else l1=-2;}
	if(lep2pt>40&&fabs(lep2eta)<2.1&&cms3.lep2_is_phys14_medium_noIso()&&cms3.lep2_miniRelIsoDB()<0.1) {++NSLeps; if(l1!=1) l1 = 2; else l1=-2;}
      }
      NGLeps = NLeps;

      ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > leplv;
      if(l1==1) leplv = lep1lv;
      else if(l1==2) leplv = lep2lv;

      ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > metlv;
      metlv.SetPxPyPzE(METx,METy,0.,MET);

      //if(NGLeps != NLeps) cout << "NGLeps = " << NGLeps << " NLeps = " << NLeps << endl;
      //NGLeps = NLeps;
      vector<int> jind;
      vector<int> bind;
      ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > jsumlv;
      vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > jetlv;
      vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > boostjetlv;
      vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > bjetlv;
      vector<float> btag;
      int jj1(-1), jj2(-1), jj3(-1);// j1(-1), j2(-1), jm(-1);
      float jj1d(-1), jj2d(-1), jj3d(-1);// jjmm(-1);
      for(unsigned int nj = 0; nj<jetsbtag.size(); ++nj){
	if(jetslv[nj].Pt()<30) continue;
	if(fabs(jetslv[nj].Eta())>2.4) continue;
	if(jetsID[nj]==false) continue;
	jind.push_back(nj);
	jetlv.push_back(jetslv[nj]);
	if(jetslv[nj].Pt()>250) boostjetlv.push_back(jetslv[nj]);
	btag.push_back(jetsbtag[nj]);
	++NGJets;
	if(jetsbtag[nj]>0.814) {++NGBJets; bind.push_back(nj); bjetlv.push_back(jetslv[nj]);}
	if(jetslv[nj].Pt()>jj1d){
	  jj3d = jj2d; jj2d = jj1d; jj1d = jetslv[nj].Pt();
	  jj3 = jj2; jj2 = jj1; jj1 = nj;
	} else if(jetslv[nj].Pt()>jj2d){
	  jj3d = jj2d; jj2d = jetslv[nj].Pt();
	  jj3 = jj2; jj2 = nj;
	} else if(jetslv[nj].Pt()>jj3d){
	  jj3d = jetslv[nj].Pt();
	  jj3 = nj;
	}
      }

      if(nvtxs<0) continue; 
      if(NGLeps!=1) continue; 
      if(NSLeps!=1) continue; 
      if(!trackveto) continue; 
      if(!tauveto) continue; 
      if(NGJets<4) continue;
      //if(NGBJets<1) continue; 
      if(MET<30) continue; 
      //if(MT>80) continue;

      for(unsigned int i = 0; i<histonames.size(); ++i){
	value[histonames[i] ] = -99;//reset values
      }
      //vector<LorentzVector > btaggedjets = JetUtil::BJetSelector(jetlv,btag,0.814,2,3,1);
      vector<LorentzVector > btaggedjets = JetUtil::BJetSelector(jetlv,btag,0.814,2,2,2);

      vector<LorentzVector > dummybjets;dummybjets.clear();
      LorentzVector dummybjet; dummybjet.SetPxPyPzE(0.,0.,0.,0.); dummybjets.push_back(dummybjet);dummybjets.push_back(dummybjet);
      
      //value["MT2W"]                  = CalculateMT2W_(btaggedjets,leplv,MET,METPhi,true);
      value["MT2W"] = MT2W;
      value["Topness"]               = Gettopness_(MET,METPhi,leplv,btaggedjets,1);
      value["MT2_b_b"]               = MT2_b_b_(MET,METPhi,btaggedjets,true, 0);
      value["MT2_lb_b_mless"]        = MT2_lb_b_(MET,METPhi,leplv,btaggedjets,false,0);
      value["MT2_lb_b"]              = MT2_lb_b_(MET,METPhi,leplv,btaggedjets,true ,0);
      value["MT2_lb_bq_mless"]       = MT2_lb_bq_( MET,METPhi,leplv,btaggedjets,jetlv,false,0);
      value["MT2_lb_bq"]             = MT2_lb_bq_( MET,METPhi,leplv,btaggedjets,jetlv,true ,0);
      value["MT2_lb_bqq_mless"]      = MT2_lb_bqq_(MET,METPhi,leplv,btaggedjets,jetlv,false,0);
      value["MT2_lb_bqq"]            = MT2_lb_bqq_(MET,METPhi,leplv,btaggedjets,jetlv,true ,0);
      value["MT2_l_q"]               = MT2_lb_bq_( MET,METPhi,leplv,dummybjets,jetlv,true ,0);
      value["MT2_l_qq_mless"]        = MT2_lb_bqq_(MET,METPhi,leplv,dummybjets,jetlv,true ,0);

      int leadb(-1), trailb(-1);
      for(unsigned int n = 0; n<btaggedjets.size();++n){
	if(leadb<0) leadb = n;
	else if(trailb<0) trailb = n;
	else if(btaggedjets[n].Pt() > btaggedjets[leadb].Pt()){ trailb = leadb; leadb = n; }
	else if(btaggedjets[n].Pt() > btaggedjets[trailb].Pt()){ trailb = n; }
	LorentzVector temp = btaggedjets[n]+leplv;
	if(temp.M()<value["Mlb"]) value["Mlb"] = temp.M();  else if(value["Mlb"]<0) value["Mlb"] = temp.M();
	if(temp.Pt()<value["pTlb"]) value["pTlb"] = temp.Pt();  else if(value["pTlb"]<0) value["pTlb"] = temp.Pt();
	float tmp = getMT(btaggedjets[n],metlv);
	if(tmp<value["MTb"]) value["MTb"] = tmp;  else if(value["MTb"]<0) value["MTb"] = tmp;
	tmp = JetUtil::deltaR(btaggedjets[n],leplv);
	tmp = JetUtil::deltaPhi(btaggedjets[n],metlv);
	if(tmp<value["minDPhiB"]) value["minDPhiB"] = tmp;  else if(value["minDPhiB"]<0) value["minDPhiB"] = tmp;
	for(unsigned int m = n+1; m<btaggedjets.size();++m){
	  temp = btaggedjets[n]+btaggedjets[m]+leplv;
	  if(temp.M()<value["Mlbb"]) value["Mlbb"] = temp.M();  else if(value["Mlbb"]<0) value["Mlbb"] = temp.M();
	  if(temp.Pt()<value["pTlbb"]) value["pTlbb"] = temp.Pt();  else if(value["pTlbb"]<0) value["pTlbb"] = temp.Pt();
	  tmp = JetUtil::deltaR(btaggedjets[n],btaggedjets[m]);
	  if(tmp<value["dRbb"]) value["dRbb"] = tmp;  else if(value["dRbb"]<0) value["dRbb"] = tmp;
	}
      }
      float myleadjpt = -1.;
      int bj1(-1), bj2(-1),bj3(-1);
      for(unsigned int n = 0; n<jetlv.size();++n){
	float tmp = getMT(jetlv[n],metlv);
  	if(tmp<value["MTq"]) value["MTq"] = tmp;  else if(value["MTq"]<0) value["MTq"] = tmp;
  	if(tmp>value["MTqmax"]) value["MTqmax"] = tmp;  else if(value["MTqmax"]<0) value["MTqmax"] = tmp;
	if(jetlv[n].Pt()>250.){ if(tmp>value["MTq_boostmax"]) value["MTq_boostmax"] = tmp;  else if(value["MTq_boostmax"]<0) value["MTq_boostmax"] = tmp; }
	if(jetlv[n].Pt()>300.){ if(tmp<value["MTq_boost300"]) value["MTq_boost300"] = tmp;  else if(value["MTq_boost300"]<0) value["MTq_boost300"] = tmp; }
	if(jetlv[n].Pt()>myleadjpt){ value["MTq_boostLeadJet"] = tmp; myleadjpt = jetlv[n].Pt(); }// else if(value["MTq_boostLeadJet"]<0) value["MTq_boostLeadJet"] = tmp;
	for(unsigned int m = n+1; m<jetlv.size();++m){
	  tmp = getMT(jetlv[n]+jetlv[m],metlv);
	  if(tmp<value["MTqq"]) value["MTqq"] = tmp;  else if(value["MTqq"]<0) value["MTqq"] = tmp;
	}
	if(n<3){
	  tmp = JetUtil::deltaPhi(jetlv[n],metlv);
	  if(tmp<value["minDPhiJ3"]) value["minDPhiJ3"] = tmp;  else if(value["minDPhiJ3"]<0) value["minDPhiJ3"] = tmp;
	}
	float dP1l(-1), dP2l(-1), dP3l(-1);
	if(bj1>0) dP1l = JetUtil::deltaPhi(jetlv[bj1],leplv);
	if(bj2>0) dP2l = JetUtil::deltaPhi(jetlv[bj2],leplv);
	if(bj3>0) dP3l = JetUtil::deltaPhi(jetlv[bj3],leplv);
	if(JetUtil::deltaPhi(jetlv[n],leplv)>dP1l){ bj3 = bj2; bj2 = bj1; bj1 = n;}
	else if(JetUtil::deltaPhi(jetlv[n],leplv)>dP2l){ bj3 = bj2; bj2 = n;}
	else if(JetUtil::deltaPhi(jetlv[n],leplv)>dP3l){ bj3 = n;}
      }

      LorentzVector bjsumlep = jetlv[bj1] + jetlv[bj2] + jetlv[bj3];
      value["M3b"] = bjsumlep.M();

      float prune=0.;
      for(unsigned int n = 0; n<cms3.ak8pfjets_pruned_mass().size();++n) prune += cms3.ak8pfjets_pruned_mass()[n];
      
      //cout << __LINE__<<endl;
      value["sumak8prunedmass"]   = prune;
      value["MT"] = MT;
      value["MET"] = MET;
      value["HT"] = HT;
      if(HT>0) {
	value["METoverSqrtHT"] = MET/TMath::Sqrt(HT);
      }
      value["HTratio"] = HTratio;
      value["dRLepBJet"] = dRLepBJet;
      value["chi2"] = chi2;
      value["NBJets"] = NGBJets;
      value["NJets"] = NGJets;
      value["minDPhi"] = minDPhi;
      value["pTl"] = leplv.Pt();
      value["pTleadj"] = myleadjpt;
      value["pTleadb"] = btaggedjets[leadb].Pt();
      value["pTtrailb"] = btaggedjets[trailb].Pt();
      value["DeltaPhiWl"] = JetUtil::deltaPhi(leplv,metlv+leplv);

      outtree[sampleid]->Fill();


      for(unsigned int i = 0; i<histonames.size(); ++i){
	value[histonames[i] ] = -99;//reset values
      }
    }
  
    // Clean Up
    delete tree;
    file->Close();
    delete file;
  }
  if ( nEventsChain != nEventsTotal ) {
    cout << Form( "ERROR: number of events from files (%d) is not equal to total number of events (%d)", nEventsChain, nEventsTotal ) << endl;
  }

  for(unsigned int b = 0; b<3; ++b){
    if(skimFilePrefix!="TTbar"&&b>0) continue;
    outfile[b]->cd();
    outtree[b]->Write();
    outfile[b]->Close();
    cout << "Tree for making BDT saved in " << outfile[b]->GetName() << endl;
  }

  // return
  bmark->Stop("benchmark");
  cout << endl;
  cout << nEventsTotal << " Events Processed" << endl;
  cout << "------------------------------" << endl;
  cout << "CPU  Time:	" << Form( "%.01f", bmark->GetCpuTime("benchmark")  ) << endl;
  cout << "Real Time:	" << Form( "%.01f", bmark->GetRealTime("benchmark") ) << endl;
  cout << endl;
  delete bmark;
  return 0;
}
Example #13
0
int ScanChain( TChain* chain, bool fast = true, int nEvents = -1, string skimFilePrefix = "test") {


  set_goodrun_file("Merged_190456-208686_8TeV_PromptReReco_Collisions12_goodruns.txt");

  // Benchmark
  TBenchmark *bmark = new TBenchmark();
  bmark->Start("benchmark");

  // Example Histograms
  TDirectory *rootdir = gDirectory->GetDirectory("Rint:");
  //add hists
  TH1F *h_mll_ee_inc = new TH1F("h_mll_ee_inc", "ee Dilepton Mass", 200,0,200);//200,0,2000
  h_mll_ee_inc->SetDirectory(rootdir);
  h_mll_ee_inc->Sumw2();
  
  TH1F* h_mll_mumu_inc = new TH1F("h_mll_mumu_inc","MuMu Dilepton Mass",200,0,200);
  h_mll_mumu_inc->SetDirectory(rootdir);
  h_mll_mumu_inc->Sumw2();

  TH1F* h_mll_ee_tar = new TH1F("h_mll_ee_tar","ee Dilepton Mass (Targeted)",200,0,200);
  h_mll_ee_tar->SetDirectory(rootdir);
  h_mll_ee_tar->Sumw2();

  TH1F* h_mll_mumu_tar = new TH1F("h_mll_mumu_tar","MuMu Dilepton Mass (Targeted)",200,0,200);
  h_mll_mumu_tar->SetDirectory(rootdir);
  h_mll_mumu_tar->Sumw2();

  TH1F* h_met_ee_inc = new TH1F("h_met_ee_inc","ee MET (Inclusive)",350,0,350);//350,0,350 for all met histos
  h_met_ee_inc->SetDirectory(rootdir);
  h_met_ee_inc->Sumw2();

  TH1F* h_met_mumu_inc = new TH1F("h_met_mumu_inc","mumu MET (Inclusive)",350,0,350);
  h_met_mumu_inc->SetDirectory(rootdir);
  h_met_mumu_inc->Sumw2();

  TH2F* h_met_ll_inc = new TH2F("h_met_ll_inc","ee+mumu MET (Inclusive)",700,-350,350,700,-350,350);//positive and negative met.  2D!
  h_met_ll_inc->SetDirectory(rootdir);
  h_met_ll_inc->Sumw2();

  TH2F* h_met_emu2_inc = new TH2F("h_met_emu2_inc","emu MET (Inclusive)",700,-350,350,700,-350,350);//positive and negative met.  2D!
  h_met_emu2_inc->SetDirectory(rootdir);
  h_met_emu2_inc->Sumw2();

  TH1F* h_met_emu_inc = new TH1F("h_met_emu_inc","emu MET (Inclusive)",350,0,350);
  h_met_emu_inc->SetDirectory(rootdir);
  h_met_emu_inc->Sumw2();

  TH1F* h_met_ee_tar_njets0 = new TH1F("h_met_ee_tar_njets0","ee MET (Targeted, no jets)",350,0,350);
  h_met_ee_tar_njets0->SetDirectory(rootdir);
  h_met_ee_tar_njets0->Sumw2();

  TH1F* h_met_mumu_tar_njets0 = new TH1F("h_met_mumu_tar_njets0","mumu MET (Targeted, no jets)",350,0,350);
  h_met_mumu_tar_njets0->SetDirectory(rootdir);
  h_met_mumu_tar_njets0->Sumw2();

  TH2F* h_met_ll_tar_njets0 = new TH2F("h_met_ll_tar_njets0","ee+mumu MET (Targeted, no jets)",700,-350,350,700,-350,350);//positive and negative met.  2D!
  h_met_ll_tar_njets0->SetDirectory(rootdir);
  h_met_ll_tar_njets0->Sumw2();

  TH2F* h_met_emu2_tar_njets0 = new TH2F("h_met_emu2_tar_njets0","emu MET (Targeted, no jets)",700,-350,350,700,-350,350);//positive and negative met.  2D!
  h_met_emu2_tar_njets0->SetDirectory(rootdir);
  h_met_emu2_tar_njets0->Sumw2();

  TH1F* h_met_emu_tar_njets0 = new TH1F("h_met_emu_tar_njets0","emu MET (Targeted, no jets)",350,0,350);
  h_met_emu_tar_njets0->SetDirectory(rootdir);
  h_met_emu_tar_njets0->Sumw2();

  TH1F* h_met_ee_tar_njets2 = new TH1F("h_met_ee_tar_njets2","ee MET (Targeted, njets >= 2)",350,0,350);
  h_met_ee_tar_njets2->SetDirectory(rootdir);
  h_met_ee_tar_njets2->Sumw2();

  TH1F* h_met_mumu_tar_njets2 = new TH1F("h_met_mumu_tar_njets2","mumu MET (Targeted, njets >= 2)",350,0,350);
  h_met_mumu_tar_njets2->SetDirectory(rootdir);
  h_met_mumu_tar_njets2->Sumw2();

  TH2F* h_met_ll_tar_njets2 = new TH2F("h_met_ll_tar_njets2","ee+mumu MET (Targeted, njets >= 2)",700,-350,350,700,-350,350);//positive and negative met.  2D!
  h_met_ll_tar_njets2->SetDirectory(rootdir);
  h_met_ll_tar_njets2->Sumw2();

  TH2F* h_met_emu2_tar_njets2 = new TH2F("h_met_emu2_tar_njets2","emu MET (Targeted, njets >= 2)",700,-350,350,700,-350,350);//positive and negative met.  2D!
  h_met_emu2_tar_njets2->SetDirectory(rootdir);
  h_met_emu2_tar_njets2->Sumw2();

  TH1F* h_met_emu_tar_njets2 = new TH1F("h_met_emu_tar_njets2","emu MET (Targeted, njets >= 2)",350,0,350);
  h_met_emu_tar_njets2->SetDirectory(rootdir);
  h_met_emu_tar_njets2->Sumw2();

  TH1F* h_nvtx_scaled= new TH1F("h_nvtx_scaled","Number of Vertices (scaled)",35,0,35);
  h_nvtx_scaled->SetDirectory(rootdir);
  h_nvtx_scaled->Sumw2();

  TH1F* h_nvtx_unscaled= new TH1F("h_nvtx_unscaled","Number of Vertices (unscaled)",35,0,35);
  h_nvtx_unscaled->SetDirectory(rootdir);
  h_nvtx_unscaled->Sumw2();

  TH1F* h_phi= new TH1F("h_phi","phi distribution",40,-TMath::Pi(),TMath::Pi());
  h_phi->SetDirectory(rootdir);
  h_phi->Sumw2();
  //-------
  TFile *InputFile = new TFile("phiRatio.root","read");
  TH1F *h_phi_ratio = (TH1F*) InputFile->Get("h_phidata_clone_scaled")->Clone("h_phi_ratio");
  //-------
  TH1F* h_sumet_ee_inc = new TH1F("h_sumet_ee_inc","ee SumET (Inclusive)",2500,0,2500);//350,0,350 for all met histos
  h_sumet_ee_inc->SetDirectory(rootdir);
  h_sumet_ee_inc->Sumw2();

  TH1F* h_sumet_mumu_inc = new TH1F("h_sumet_mumu_inc","mumu SumET (Inclusive)",2500,0,2500);//350,0,350 for all met histos
  h_sumet_mumu_inc->SetDirectory(rootdir);
  h_sumet_mumu_inc->Sumw2();

  TH1F* h_sumet_emu_inc = new TH1F("h_sumet_emu_inc","emu SumET (Inclusive)",2500,0,2500);//350,0,350 for all met histos
  h_sumet_emu_inc->SetDirectory(rootdir);
  h_sumet_emu_inc->Sumw2();
  //-------
  TFile *InputFile_sumet = new TFile("sumet_Ratio.root","read");
  TH1F *h_sumet_ratio = (TH1F*) InputFile_sumet->Get("h_sumet_ee_inc_data_clone_scaled")->Clone("h_sumet_ratio");
  //-------

  // Loop over events to Analyze
  unsigned int nEventsTotal = 0;
  unsigned int nEventsChain = chain->GetEntries();
  if( nEvents >= 0 ) nEventsChain = nEvents;
  TObjArray *listOfFiles = chain->GetListOfFiles();
  TIter fileIter(listOfFiles);
  TFile *currentFile = 0;

  // File Loop
  while ( (currentFile = (TFile*)fileIter.Next()) ) {

    // Get File Content
    TFile *file = new TFile( currentFile->GetTitle() );
    TTree *tree = (TTree*)file->Get("T1");
    if(fast) TTreeCache::SetLearnEntries(10);
    if(fast) tree->SetCacheSize(128*1024*1024);
    zmet.Init(tree);
    
    // Loop over Events in current file
    if( nEventsTotal >= nEventsChain ) continue;
    unsigned int nEventsTree = tree->GetEntriesFast();
    for( unsigned int event = 0; event < nEventsTree; ++event) {
    
      // Get Event Content
      if( nEventsTotal >= nEventsChain ) continue;
      if(fast) tree->LoadTree(event);
      zmet.GetEntry(event);
      ++nEventsTotal;
    
      // Progress
      ZMET::progress( nEventsTotal, nEventsChain );
	  
	  //------------------------- CUT --------------------------------------------
	 
	  //
	  if( (zmet.leptype() != 0) && (zmet.leptype() != 1) && (zmet.leptype() != 2) ){ continue;} // 0 -> e's,  1 -> Mu's, 2->emu


	  float ptcutoff=20.;
	  if( ( zmet.lep1().Pt() <= ptcutoff) || ( zmet.lep2().Pt() <= ptcutoff) ) {continue;}

	  float etacutoff=2.4;
	  if( ( abs( zmet.lep1().Eta()) >= etacutoff) || ( abs( zmet.lep2().Eta()) >= etacutoff) ) {continue;}
	  
	  //barrel/endcap eta cuts
	  if( ( abs( zmet.lep1().Eta()) > 1.4 && abs( zmet.lep1().Eta()) < 1.6) || ( abs( zmet.lep2().Eta()) > 1.4 && abs( zmet.lep2().Eta()) < 1.6) ) 
		{continue;}

	  double weight_mc=zmet.weight()*19.5*zmet.trgeff()*zmet.vtxweight()*( h_phi_ratio->GetBinContent(h_phi_ratio->FindBin(zmet.pfmetphi())) )*( h_sumet_ratio->GetBinContent(h_sumet_ratio->FindBin(zmet.pfsumet())) );
	  double weight_data=1.;
	  //cout<< h_phi_ratio->GetBinContent(h_phi_ratio->FindBin(zmet.pfmetphi()))<<endl;
	  
	  //---------------------------------------
	  if (zmet.lep3().Pt() > 10.){continue;}
	  //---------------------------------------
	  //if (zmet.nvtx() > 7.) {continue;}
	  //---------------------------------------
	  //if (zmet.nvtx() <= 7. || zmet.nvtx() >= 20.) {continue;}
	  //---------------------------------------
	  //if (zmet.nvtx() < 20.) {continue;}

	  //Data cuts
	  if(zmet.isdata() && goodrun( zmet.run(), zmet.lumi() )  )
		{
		  if(!(zmet.csc()==0 && 
			   zmet.hbhe()==1 && 
			   zmet.hcallaser()==1 && 
			   //zmet.ecallaser()==1 && 
			   zmet.ecaltp()==1 && 
			   zmet.trkfail()==1 && 
			   zmet.eebadsc()==1 && 
			   zmet.hbhenew()==1))     
			continue;    //met filter variables and trigger variables
		}

	  if(zmet.isdata() && goodrun( zmet.run(), zmet.lumi() )  )
		{
		  if( zmet.leptype()==0 )
			{
			  if( zmet.ee()==0 )  
				{continue;}
			}
		  else if( zmet.leptype()==1 )
			{
			  if( zmet.mm()==0 )              
				{continue;}
			}
		  else if( zmet.leptype()==2 )
			{
			  if( zmet.em()==0 && zmet.me()==0 )
				{continue;}
			}
		}

	  //Fill  histograms
	  if (zmet.isdata() && goodrun( zmet.run(), zmet.lumi() )  )  //If it is data from good run
		{
		  if (zmet.leptype()==0 || zmet.leptype()==1 || zmet.leptype()==2)
			{
			  h_nvtx_scaled->Fill(zmet.nvtx(),weight_data);
			  h_nvtx_unscaled->Fill(zmet.nvtx(),weight_data);
			  h_phi->Fill(zmet.pfmetphi(), weight_data);
			}
		  if (zmet.leptype() == 0)
			{
			  h_mll_ee_inc->Fill(zmet.dilmass(),weight_data);
			 
			  if(zmet.dilmass() > 81. && zmet.dilmass() < 101. /*&& zmet.lep3().Pt() <= 10.*/ )             //Check this.  Only apply to MET histos
				{
				  h_met_ee_inc->Fill(zmet.pfmet(),weight_data);
				  fillHist(h_sumet_ee_inc, zmet.pfsumet(),weight_data);
				  h_met_ll_inc->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_data);
				 
				  if(zmet.njets()==0)
					{
					  h_met_ee_tar_njets0->Fill(zmet.pfmet(),weight_data);
					  h_met_ll_tar_njets0->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_data);
					}
				  else if(zmet.njets()>=2)
					{
					  h_met_ee_tar_njets2->Fill(zmet.pfmet(),weight_data);
					  h_met_ll_tar_njets2->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_data);
					}
				}

			  if ( zmet.lep3().Pt() <= 10.  &&  zmet.njets()>=2  &&  zmet.nbcsvm()==0 && (zmet.mjj() > 70. && zmet.mjj() < 110.) )
				 {h_mll_ee_tar->Fill(zmet.dilmass(),weight_data);}
			}
		  else if (zmet.leptype()==1)
			{
			  h_mll_mumu_inc->Fill(zmet.dilmass(),weight_data);
			 
			  if(zmet.dilmass() > 81. && zmet.dilmass() < 101. /*&& zmet.lep3().Pt() <= 10.*/)             //check this.
				{		  
				  h_met_mumu_inc->Fill(zmet.pfmet(),weight_data);
				  fillHist(h_sumet_mumu_inc, zmet.pfsumet(),weight_data);
				  h_met_ll_inc->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_data);
			
				  if(zmet.njets()==0)
					{
					  h_met_mumu_tar_njets0->Fill(zmet.pfmet(),weight_data);
					  h_met_ll_tar_njets0->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_data);					
					}
				  else if(zmet.njets()>=2)
					{
					  h_met_mumu_tar_njets2->Fill(zmet.pfmet(),weight_data);
					  h_met_ll_tar_njets2->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_data);					
					}

				}

			  if ( zmet.lep3().Pt() <= 10.   &&  zmet.njets()>=2  &&  zmet.nbcsvm()==0 && (zmet.mjj() > 70. && zmet.mjj() < 110.) )  
				 {h_mll_mumu_tar->Fill(zmet.dilmass(),weight_data);}
			}
		  else if (zmet.leptype()==2)
			{
			  //h_mll_mumu_inc->Fill(zmet.dilmass(),weight_data);
			 
			  if(zmet.dilmass() > 81. && zmet.dilmass() < 101. /*&& zmet.lep3().Pt() <= 10.*/)             //check this.
				{		  
				  h_met_emu_inc->Fill(zmet.pfmet(),weight_data);
				  fillHist(h_sumet_emu_inc, zmet.pfsumet(),weight_data);
				  h_met_emu2_inc->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_data);
			
				  if(zmet.njets()==0)
					{
					  h_met_emu_tar_njets0->Fill(zmet.pfmet(),weight_data);
					  h_met_emu2_tar_njets0->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_data);
					}
				  else if(zmet.njets()>=2)
					{
					  h_met_emu_tar_njets2->Fill(zmet.pfmet(),weight_data);
					  h_met_emu2_tar_njets2->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_data);
					}
				}

			  // if ( zmet.lep3().Pt() <= 10.   &&  zmet.njets()>=2  &&  zmet.nbcsvm()==0 && (zmet.mjj() > 70. && zmet.mjj() < 110.) )  
			  // {h_mll_mumu_tar->Fill(zmet.dilmass(),weight_data);}
			}
		}


	  else if (!zmet.isdata())   //If it is MC
		{
		  if (zmet.leptype()==0 || zmet.leptype()==1 || zmet.leptype()==2)
			{
			  h_nvtx_scaled->Fill(zmet.nvtx(), zmet.weight()*19.5*zmet.trgeff()*zmet.vtxweight() );
			  h_nvtx_unscaled->Fill(zmet.nvtx(), zmet.weight()*19.5*zmet.trgeff() );
			  h_phi->Fill(zmet.pfmetphi(), weight_mc);			}

		  if (zmet.leptype() == 0)
			{
			  h_mll_ee_inc->Fill(zmet.dilmass(),weight_mc);
			  
			  if(zmet.dilmass() > 81. && zmet.dilmass() < 101. /* && zmet.lep3().Pt() <= 10.*/)
				{
				  h_met_ee_inc->Fill(zmet.pfmet(),weight_mc);
				  fillHist(h_sumet_ee_inc, zmet.pfsumet(),weight_mc);
				  h_met_ll_inc->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_mc);
				
				  if(zmet.njets()==0)
					{
					  h_met_ee_tar_njets0->Fill(zmet.pfmet(),weight_mc);
					  h_met_ll_tar_njets0->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_mc);
					}
				  else if(zmet.njets()>=2)
					{
					  h_met_ee_tar_njets2->Fill(zmet.pfmet(),weight_mc);
					  h_met_ll_tar_njets2->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_mc);
					}
				}
			  if (zmet.lep3().Pt() <= 10.  &&  zmet.njets()>=2  &&  zmet.nbcsvm()==0 && (zmet.mjj() > 70. && zmet.mjj() < 110.) )        
   				{h_mll_ee_tar->Fill(zmet.dilmass(),weight_mc);}
			}
		  else if (zmet.leptype()==1)
			{
			  h_mll_mumu_inc->Fill(zmet.dilmass(),weight_mc);
			
			  if(zmet.dilmass() > 81. && zmet.dilmass() < 101. /* && zmet.lep3().Pt() <= 10.*/)
				{
				  h_met_mumu_inc->Fill(zmet.pfmet(),weight_mc);
				  fillHist(h_sumet_mumu_inc, zmet.pfsumet(),weight_mc);
				  h_met_ll_inc->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_mc);

				  if(zmet.njets()==0)
					{
					  h_met_mumu_tar_njets0->Fill(zmet.pfmet(),weight_mc);
					  h_met_ll_tar_njets0->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_mc);
					}
				  else if(zmet.njets()>=2)
					{
					  h_met_mumu_tar_njets2->Fill(zmet.pfmet(),weight_mc);
					  h_met_ll_tar_njets2->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_mc);
					}
				}

			  if (zmet.lep3().Pt() <= 10.  &&  zmet.njets()>=2  &&  zmet.nbcsvm()==0 && (zmet.mjj() > 70. && zmet.mjj() < 110.) )
   				{h_mll_mumu_tar->Fill(zmet.dilmass(),weight_mc);}
			}
 
		  else if (zmet.leptype()==2)
			{
			  // h_mll_mumu_inc->Fill(zmet.dilmass(),weight_mc);
			
			  if(zmet.dilmass() > 81. && zmet.dilmass() < 101. /* && zmet.lep3().Pt() <= 10.*/)
				{
				  h_met_emu_inc->Fill(zmet.pfmet(),weight_mc);
				  fillHist(h_sumet_emu_inc, zmet.pfsumet(),weight_mc);
				  h_met_emu2_inc->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_mc);

				  if(zmet.njets()==0)
					{
					  h_met_emu_tar_njets0->Fill(zmet.pfmet(),weight_mc);
					  h_met_emu2_tar_njets0->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_mc);
					}
				  else if(zmet.njets()>=2)
					{
					  h_met_emu_tar_njets2->Fill(zmet.pfmet(),weight_mc);
					  h_met_emu2_tar_njets2->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_mc);
					}
				}

			  // if (zmet.lep3().Pt() <= 10.  &&  zmet.njets()>=2  &&  zmet.nbcsvm()==0 && (zmet.mjj() > 70. && zmet.mjj() < 110.) )
			  //	{h_mll_mumu_tar->Fill(zmet.dilmass(),weight_mc);}
			}
	}

	
  

 //---------------------------------------------------------------------------------------------------------
    }    //end events loop.
 
    // Clean Up
    delete tree;
    file->Close();
    delete file;
  }
  if ( nEventsChain != nEventsTotal ) {
    cout << Form( "ERROR: number of events from files (%d) is not equal to total number of events (%d)", nEventsChain, nEventsTotal ) << endl;
  }


  //Write to file
  TFile *OutputFile = new TFile(Form("%s.root", skimFilePrefix.c_str()),"recreate");
  OutputFile->cd();
  h_mll_ee_inc->Write();
  h_mll_mumu_inc->Write();
  h_mll_ee_tar->Write();
  h_mll_mumu_tar->Write();
  h_met_ee_inc->Write();
  h_met_mumu_inc->Write();
  h_met_ll_inc->Write();
  h_met_emu_inc->Write();
  h_met_emu2_inc->Write();
  h_met_ee_tar_njets0->Write();
  h_met_mumu_tar_njets0->Write();
  h_met_ll_tar_njets0->Write();
  h_met_emu_tar_njets0->Write();
  h_met_emu2_tar_njets0->Write();
  h_met_ee_tar_njets2->Write();
  h_met_mumu_tar_njets2->Write();
  h_met_ll_tar_njets2->Write();
  h_met_emu_tar_njets2->Write();
  h_met_emu2_tar_njets2->Write();
  h_nvtx_scaled->Write();
  h_nvtx_unscaled->Write();
  h_phi->Write();
  h_sumet_ee_inc->Write();
  h_sumet_mumu_inc->Write();
  h_sumet_emu_inc->Write();

  OutputFile->Close();


  // return
  bmark->Stop("benchmark");
  cout << endl;
  cout << nEventsTotal << " Events Processed" << endl;
  cout << "------------------------------" << endl;
  cout << "CPU  Time:	" << Form( "%.01f", bmark->GetCpuTime("benchmark")  ) << endl;
  cout << "Real Time:	" << Form( "%.01f", bmark->GetRealTime("benchmark") ) << endl;
  cout << endl;
  delete bmark;

  return 0;
}
Example #14
0
//Main function
int ScanChain::looper(TChain* chain, TString output_name, int nEvents){

  //Print warning!
  cout << "Careful!! Path is " << path << endl;

  createAndInitMVA("CORE");

  //readMVA* localEleMVAreader = new readMVA();
  //localEleMVAreader->InitMVA("CORE"); 

  //Set up loop over chain
  unsigned int nEventsDone = 0;
  unsigned int nEventsToDo = chain->GetEntries();
  if( nEvents >= 0 ) nEventsToDo = nEvents;
  TObjArray *listOfFiles = chain->GetListOfFiles();
  TIter fileIter(listOfFiles);
  TFile *currentFile = 0;
  std::map<std::string, TH1*> h_1d;

  // File Loop
  while ( (currentFile = (TFile*)fileIter.Next()) ) { 

    // Get File Content
    if(nEventsDone >= nEventsToDo) continue;
    TFile *file = new TFile( currentFile->GetTitle() );
    TTree *tree = (TTree*)file->Get("Events");
    cms3.Init(tree);
  
    // Loop over Events in current file
    unsigned int nEventsTree = tree->GetEntriesFast();
    for(unsigned int evt = 0; evt < nEventsTree; evt++){
	  
      //cout<<"\nEvent loop again"<<endl;	  

      // Get Event Content
      if(nEventsDone >= nEventsToDo) continue;   
      cms3.GetEntry(evt);
      nEventsDone++;


      //Debug mode
      if (verbose && tas::evt_event() != evt_cut) continue;
      if (verbose) cout << "file name is " << file->GetName() << endl;

     
      // Progress
      CMS3::progress(nEventsDone, nEventsToDo);

      for (unsigned int iel = 0; iel < els_p4().size(); ++iel) {
	LorentzVector el_p4 = els_p4().at(iel);
	float pt = el_p4.pt();
	plot1D("h_pt", pt,  1, h_1d, "pT [GeV]", 150, 0, 150);
      }
      
    }// end of event loop
    
    file->Close();
    delete file;
    //delete tree;
    cout<<"\nFile done"<<endl;

  }//end of  file loop
  
  cout<<"\nWriting file"<<endl;
  savePlots(h_1d, output_name+".root");
  
  return 0;  
  
}
int ScanChain( TChain* chain, bool fast = true, int nEvents = -1, string skimFilePrefix = "test") {
  int version = 4;
  // Benchmark
  TBenchmark *bmark = new TBenchmark();
  bmark->Start("benchmark");

  // Example Histograms
  TDirectory *rootdir = gDirectory->GetDirectory("Rint:");


  map<string, TH1F*> histos;
  vector<string> histonames; histonames.clear();

  int nbins = 9; float blow = 0.5; float bup = 9.5; bool storeh = true;
  if(version== 1){ nbins =  8; blow = 0.5; bup =  8.5; storeh = true; }
  if(version== 2){ nbins =  8; blow = 0.5; bup =  8.5; storeh = true; }
  if(version== 3){ nbins =  8; blow = 0.5; bup =  8.5; storeh = true; }
  if(version== 4){ nbins =  8; blow = 0.5; bup =  8.5; storeh = true; }
  if(version== 5){ nbins =  6; blow = 0.5; bup =  6.5; storeh = true; }
  if(version== 6){ nbins =  8; blow = 0.5; bup =  8.5; storeh = true; }
  if(version== 7){ nbins =  8; blow = 0.5; bup =  8.5; storeh = true; }
  if(version== 8){ nbins =  7; blow = 0.5; bup =  7.5; storeh = true; }
  if(version== 9){ nbins =  7; blow = 0.5; bup =  7.5; storeh = true; }
  if(version==10){ nbins =  8; blow = 0.5; bup =  8.5; storeh = true; }
  if(version==11){ nbins =  6; blow = 0.5; bup =  6.5; storeh = true; }
  if(version==12){ nbins =  8; blow = 0.5; bup =  8.5; storeh = true; }
  if(version==13){ nbins =  6; blow = 0.5; bup =  6.5; storeh = true; }
  if(version==14){ nbins =  8; blow = 0.5; bup =  8.5; storeh = true; }
  if(version==15){ nbins =  5; blow = 0.5; bup =  5.5; storeh = true; }
  if(version==16){ nbins =  9; blow = 0.5; bup =  9.5; storeh = true; }
  if(version==17){ nbins = 11; blow = 0.5; bup = 11.5; storeh = true; }

  //AllBGCorr
  //CorrName1Name2Name3 with NameX being sampleX
  //CorrAllBG CorrAll means correlated among all backgrounds, or everything (bg+sig)
  histonames.push_back("SRyield");
  histonames.push_back("CRyield");
  histonames.push_back("StatUnc");
  histonames.push_back("SystUnc");
 
  for(unsigned int b = 0; b<2; ++b){
    string samplename = skimFilePrefix;
    TString helper = TString(samplename);
    //cout << helper << endl;
    if(skimFilePrefix!="TTbar"&&b>0) continue;
    if(skimFilePrefix=="TTbar"&&b==0) samplename = "TTbar1l";
    if(skimFilePrefix=="TTbar"&&b==1) samplename = "TTbar2l";
    if(skimFilePrefix=="TTbar"&&b==2) samplename = "TTbarH";
    string mapname;
    for(unsigned int i = 0; i<histonames.size();++i){
      mapname = histonames[i] + "_" + samplename;
      //cout << mapname << " " << nbins << " " << blow << " " << bup << endl;
      if(histos.count(mapname) == 0 ) histos[mapname] = new TH1F(mapname.c_str(), "", nbins, blow, bup);
      histos[mapname]->Sumw2(); histos[mapname]->SetDirectory(rootdir);
      //cout << mapname << endl;
      //cout << mapname << endl;
    }
  }

  // Loop over events to Analyze
  unsigned int nEventsTotal = 0;
  unsigned int nEventsChain = chain->GetEntries();
  if( nEvents >= 0 ) nEventsChain = nEvents;
  TObjArray *listOfFiles = chain->GetListOfFiles();
  TIter fileIter(listOfFiles);
  TFile *currentFile = 0;

  // File Loop
  while ( (currentFile = (TFile*)fileIter.Next()) ) {

    // Get File Content
    TFile *file = new TFile( currentFile->GetTitle() );
    TTree *tree = (TTree*)file->Get("t");
    if(fast) TTreeCache::SetLearnEntries(10);
    if(fast) tree->SetCacheSize(128*1024*1024);
    cms3.Init(tree);
    
    // Loop over Events in current file
    if( nEventsTotal >= nEventsChain ) continue;
    unsigned int nEventsTree = tree->GetEntriesFast();
    for( unsigned int event = 0; event < nEventsTree; ++event) {
    
      // Get Event Content
      if( nEventsTotal >= nEventsChain ) continue;
      if(fast) tree->LoadTree(event);
      cms3.GetEntry(event);
      ++nEventsTotal;
      
      // Progress
      CMS3::progress( nEventsTotal, nEventsChain );
      
      string samplename = skimFilePrefix;
      if(skimFilePrefix=="TTbar"){
	if(genlepsfromtop() ==2) samplename = "TTbar2l";
	else if(genlepsfromtop() ==1) samplename = "TTbar1l";
	else { samplename = "TTbarH"; continue; }// cout << "no gen lep" << " " << genlepsfromtop() << endl; }
      }
      TString helper = TString(samplename);
      /*if(helper.Contains("Signal")){
	if(helper.Contains("T2tt")){
	  TString signalname = Form("%s_%d_%d",samplename.c_str(),(int)mass_stop(),(int)mass_lsp());
	  samplename = signalname.Data();
	}
      }*/
      
      // Analysis Code
      float weight = cms3.scale1fb()*3.;
      if(samplename == "Data") weight = 1.;
      if(is_data()) weight = 1.;
      if(event==0) cout << "weight " << weight << " nEvents " << cms3.nEvents() << " filename " << currentFile->GetTitle() << endl;
      //bool trackveto = cms3.PassTrackVeto();
      //bool tauveto = cms3.PassTauVeto();

      int NGLeps = 0;
      int NSLeps = 0;
      int NGJets = 0;
      int NGBJets = 0;

      if(lep1_is_mu()){
	if(lep1_pt()>30&&fabs(lep1_eta())<2.1&&lep1_passMediumID()&&fabs(lep1_d0())<0.02&&fabs(lep1_dz())<0.1&&lep1_MiniIso()<0.1) {++NSLeps; }
	//if(lep1_pt()>30&&fabs(lep1_eta())<2.4&&fabs(lep1_d0())<0.02&&fabs(lep1_dz())<0.1&&lep1_MiniIso()<0.1) {++NGLeps; }
      } else if (lep1_is_el()){
	if(lep1_pt()>40&&fabs(lep1_eta())<2.1&&lep1_passMediumID()&&lep1_MiniIso()<0.1) {++NSLeps; }
	//if(lep1_pt()>40&&fabs(lep1_eta())<2.5&&lep1_is_phys14_medium_noIso()&&lep1_MiniIso()<0.1) {++NGLeps; }
      }
      if(lep2_is_mu()){
       	if(lep2_pt()>30&&fabs(lep2_eta())<2.1&&lep2_passMediumID()&&fabs(lep2_d0())<0.02&&fabs(lep2_dz())<0.1&&lep2_MiniIso()<0.1) {++NSLeps; }
      	//if(lep2_pt()>30&&fabs(lep2_eta())<2.4&&fabs(lep2_d0())<0.02&&fabs(lep2_dz())<0.1&&lep2_MiniIso()<0.1) {++NGLeps; }
      } else if (lep2_is_el()){
	if(lep2_pt()>40&&fabs(lep2_eta())<2.1&&lep2_passMediumID()&&lep2_MiniIso()<0.1) {++NSLeps; }
	//if(lep2_pt()>40&&fabs(lep2_eta())<2.5&&lep2_is_phys14_medium_noIso()&&lep2_MiniIso()<0.1) {++NGLeps; }
      }
      NGLeps = nvetoleps();
      
      for(unsigned int nj = 0; nj<ak4pfjets_CSV().size(); ++nj){
	if(ak4pfjets_p4()[nj].Pt()<30) continue;
	if(fabs(ak4pfjets_p4()[nj].Eta())>2.4) continue;
	if(ak4pfjets_loose_pfid()[nj]==false) continue;
	++NGJets;

	if(ak4pfjets_CSV()[nj]>0.890) {++NGBJets; }
      }

      if(nvtxs()<0)        continue;
      if(nvetoleps()!=1)   continue;
      //if(NSLeps!=1)        continue;
      if(ngoodleps()!=1)   continue;
      if(!PassTrackVeto_v3()) continue;
      if(!PassTauVeto())   continue;
      if(NGJets<3)         continue;
      if(NGBJets<1)        continue;
      if(mindphi_met_j1_j2()<0.8) continue;
      //if(hadronic_top_chi2()>10) continue;
      if(pfmet()<250)       continue;
      if(mt_met_lep()<150)  continue;

      //cout << __LINE__ << " version " << version << endl;
      bool ge4j = NGJets>=4;
      float met = pfmet();
      bool m2w = MT2W()>200.;
      bool mlb = Mlb_lead_bdiscr()>175.;
      float bpt = ak4pfjets_leadMEDbjet_p4().Pt();

      //NOTE that we already have MET>=250!
      float mybin = -1;
      
      if(version==16){
	if(bpt<=100){
	  if(!m2w) mybin = 1; else if(!mlb) mybin = 2; else mybin = 3;
	}
	else if(!m2w) mybin = 4;
	else if(!mlb){
	  if(met>375) mybin = 6; else mybin = 5;
	}
	else if(met>400) mybin = 9; else if(met>325) mybin = 8; else mybin = 7;
      }
      if(version==17){
	if(!mlb){
	  if(!m2w){
	    if(bpt<=150){
	      if(met>325) mybin = 2; else mybin = 1;
	    } else mybin = 8;
	  } else if(bpt<=150){
	    if(met>375) mybin = 4; else mybin = 3;
	  } else mybin = 9;
	}
	else if(!m2w) mybin = 5;
	else if(bpt<=150){
	  if(met>350) mybin = 7; else mybin = 6;
	}
	else if(met>350) mybin = 11; else mybin = 10;
      }
      
      if(!ge4j) continue;
      
      if(version==1){
	if(bpt<=100){
	  if(mlb) mybin = 3; else if(m2w) mybin = 2; else mybin = 1;
	} else {
	  if(!m2w) mybin = 4; else if(!mlb) mybin = 5;
	  else if(met>400) mybin = 8; else if(met>325) mybin = 7; else mybin = 6;
	}
      }
      if(version==2){
	if(bpt<=100){
	  if(!m2w) mybin = 1; else if(met>350) mybin = 3; else mybin = 2;
	} else {
	  if(!m2w) mybin = 4;
	  else if(met>450) mybin = 8; else if(met>350) mybin = 7; else if(met>300) mybin = 6; else mybin = 5;
	}
      }
      if(version==3){
	if(bpt<=100){
	  if(mlb) mybin = 3; else if(met>350) mybin = 2; else mybin = 1;
	} else if(bpt>100){
	  if(mlb){
	    if(met>400) mybin = 8; else if(met>300) mybin = 7; else mybin = 6;
	  } else if(met>350) mybin = 5; else mybin = 4;
	}
      }
      if(version==4){
	if(bpt<=100){
	  if(met>400) mybin = 3; else if(met>300) mybin = 2; else mybin = 1;
	} else {
	  if(met>450) mybin = 8; else if(met>375) mybin = 7; else if(met>325) mybin = 6; else if(met>275) mybin = 5; else mybin = 4;
	}
      }
      if(version==5){
	if(!mlb){
	  if(bpt>150) mybin = 4; else if(m2w) mybin = 2; else mybin = 1;
	} else {
	  if(m2w){
	    if(met>350&&bpt>150) mybin = 6; else if(bpt>150) mybin = 5;
	  } else mybin = 3;
	}
      }
      if(version==6){
	if(bpt<=150){
	  if(!m2w) mybin = 1; else if(met>400) mybin = 4; else if(met>300) mybin = 3; else mybin = 2;
	} else {
	  if(!m2w) mybin = 5; else if(met>400) mybin = 8; else if(met>300) mybin = 7; else mybin = 6;
	}
      }
      if(version==7){
	if(bpt<=150){
	  if(mlb){ if(met>300) mybin = 5; else mybin = 4; }
	  else if(met>400) mybin = 3; else if(met>300) mybin = 2; else mybin = 1;
	} else {
	  if(!mlb) mybin = 6; else if(met>350) mybin = 8; else mybin = 7;
	}
      }
      if(version==8){
	if(bpt<=150){
	  if(met>425) mybin = 4; else if(met>350) mybin = 3; else if(met>300) mybin = 2; else mybin = 1;
	} else if(met>400) mybin = 7; else if(met>325) mybin = 6; else mybin = 5;
      }
      if(version==9){
	if(bpt>200){
	  if(met>350) mybin = 7; else mybin = 6;
	} else if(m2w) {
	  if(met>400) mybin = 5; else if(met>325) mybin = 4; else mybin = 3;
	} else {
	  if(met>325) mybin = 2; else mybin = 1;
	}
      }
      if(version==10){
	if(bpt>200){
	  if(met>350) mybin = 8; else mybin = 7;
	} else if(mlb){
	  if(met>375) mybin = 6; else if(met>300) mybin = 5; else mybin = 4;
	} else {
	  if(met>400) mybin = 3; else if(met>325) mybin = 2; else mybin = 1;
	}
      }
      if(version==11){
	if(bpt>200){
	  if(met>350) mybin = 6; else mybin = 5;
	}
	else if(met>450) mybin = 4; else if(met>350) mybin = 3; else if(met>300) mybin = 2; else mybin = 1;
      }
      if(version==12){
	if(!mlb){
	  if(!m2w){
	    if(met>325) mybin = 2; else mybin = 1;
	  }
	  else if(met>375) mybin = 4; else mybin = 3;
	} else if(!m2w) mybin = 5; else if(met>400) mybin = 8; else if(met>300) mybin = 7; else mybin = 6;
      }
      if(version==13){
	if(mlb){
	  if(met>350) mybin = 6; else if(met>300) mybin = 5; else mybin = 4;
	}
	else if(met>425) mybin = 3; else if(met>325) mybin = 2; else mybin = 1;
      }
      if(version==14){
	if(m2w){
	  if(met>500) mybin = 8; else if(met>400) mybin = 7; else if(met>350) mybin = 6; else if(met>300) mybin = 5; else mybin = 4;
	}
	else if(met>350) mybin = 3; else if(met>300) mybin = 2; else mybin = 1;
      }
      if(version==15){
	if(met>500) mybin = 5; else if(met>400) mybin = 4; else if(met>350) mybin = 3; else if(met>300) mybin = 2; else mybin = 1;
      }
      //cout << __LINE__ << " mybin " << mybin << " " << samplename << endl;
      //cout << "SRyield_" + samplename << endl;
      histos["SRyield_" + samplename]->Fill(mybin,weight);

    }
  
    // Clean Up
    delete tree;
    file->Close();
    delete file;
  }
  if ( nEventsChain != nEventsTotal ) {
    cout << Form( "ERROR: number of events from files (%d) is not equal to total number of events (%d)", nEventsChain, nEventsTotal ) << endl;
  }

  //do all postrunning modifications here - maybe need some additional code if running over additional types of babies
  //i.e.if we have additional babies, run extra, hadd files and do further modifications (note you might need to store additional histos)
  for(unsigned int b = 0; b<2; ++b){
    string samplename = skimFilePrefix;
    TString helper = TString(samplename);
    if(skimFilePrefix!="TTbar"&&b>0) continue;
    if(skimFilePrefix=="TTbar"&&b==0) samplename = "TTbar1l";
    if(skimFilePrefix=="TTbar"&&b==1) samplename = "TTbar2l";
    if(skimFilePrefix=="TTbar"&&b==2) samplename = "TTbarH";
    string mapname;
    for(int i = 1; i<=histos["SRyield_"+samplename]->GetNbinsX();++i){
      if(histos["SRyield_"+samplename]->Integral()>0) {
	if(histos["SRyield_"+samplename]->GetBinContent(i)>0){
	  histos["StatUnc_"+samplename]->SetBinContent(i, histos["SRyield_"+samplename]->GetBinError(i)/histos["SRyield_"+samplename]->GetBinContent(i));
	}
	else histos["StatUnc_"+samplename]->SetBinContent(i, -999);
	histos["SystUnc_"+samplename]->SetBinContent(i, 0.3);
      }
    }
  }  

  //save all relevant histograms into some rootfiles
  for(unsigned int b = 0; b<2; ++b){
    string samplename = skimFilePrefix;
    TString helper = TString(samplename);
    if(skimFilePrefix!="TTbar"&&b>0) continue;
    if(skimFilePrefix=="TTbar"&&b==0) samplename = "TTbar1l";
    if(skimFilePrefix=="TTbar"&&b==1) samplename = "TTbar2l";
    if(skimFilePrefix=="TTbar"&&b==2) continue;
    string filename = "inputfiles/"+samplename+".root";
    if(version== 1) filename = "inputfiles/v1/"+samplename+".root";
    if(version== 2) filename = "inputfiles/v2/"+samplename+".root";
    if(version== 3) filename = "inputfiles/v3/"+samplename+".root";
    if(version== 4) filename = "inputfiles/v4/"+samplename+".root";
    if(version== 5) filename = "inputfiles/v5/"+samplename+".root";
    if(version== 6) filename = "inputfiles/v6/"+samplename+".root";
    if(version== 7) filename = "inputfiles/v7/"+samplename+".root";
    if(version== 8) filename = "inputfiles/v8/"+samplename+".root";
    if(version== 9) filename = "inputfiles/v9/"+samplename+".root";
    if(version==10) filename = "inputfiles/v10/"+samplename+".root";
    if(version==11) filename = "inputfiles/v11/"+samplename+".root";
    if(version==12) filename = "inputfiles/v12/"+samplename+".root";
    if(version==13) filename = "inputfiles/v13/"+samplename+".root";
    if(version==14) filename = "inputfiles/v14/"+samplename+".root";
    if(version==15) filename = "inputfiles/v15/"+samplename+".root";
    if(version==16) filename = "inputfiles/v16/"+samplename+".root";
    if(version==17) filename = "inputfiles/v17/"+samplename+".root";
    TFile *f = new TFile(filename.c_str(),"RECREATE");
    f->cd();
    string mapname;
    for(unsigned int i = 0; i<histonames.size();++i){
      mapname = histonames[i] + "_" + samplename;
      if(storeh) histos[mapname]->Write();
    }
    f->Close();
    cout << "Saved histos in " << f->GetName() << endl;
  }

  // return
  bmark->Stop("benchmark");
  cout << endl;
  cout << nEventsTotal << " Events Processed" << endl;
  cout << "------------------------------" << endl;
  cout << "CPU  Time:	" << Form( "%.01f", bmark->GetCpuTime("benchmark")  ) << endl;
  cout << "Real Time:	" << Form( "%.01f", bmark->GetRealTime("benchmark") ) << endl;
  cout << endl;
  delete bmark;
  return 0;
}
Example #16
0
int ScanChain( TChain* chain, bool fast = true, int nEvents = -1, string skimFilePrefix = "test") {

  // Benchmark
  TBenchmark *bmark = new TBenchmark();
  bmark->Start("benchmark");

  // Example Histograms
  TDirectory *rootdir = gDirectory->GetDirectory("Rint:");
  // samplehisto->SetDirectory(rootdir);

  TH1F *h_muonCount = new TH1F("h_muonCount", "Number of Muons in this event", 90, 0, 5);

  // MuonTagAndProbe: define the trigger to check here
  vector<string> triggerNames;
  triggerNames.push_back("HLT_IsoMu24");
  triggerNames.push_back("HLT_IsoTkMu24");
  // triggerNames.push_back("HLT_IsoMu20");
  // triggerNames.push_back("HLT_IsoTkMu20");
  // triggerNames.push_back("HLT_Ele27_eta2p1_WPLoose_Gsf");
  // triggerNames.push_back("HLT_Ele22_eta2p1_WPLoose_Gsf");

  // Separate vector to store the pt cut to be used for eta and phi
  vector<float> triggerPtCuts(triggerNames.size(), 50);
  // triggerPtCuts[2] = 25;
  // triggerPtCuts[3] = 25;

  vector<map<histType,TH1F*>> muonHists = creatMuonHists(triggerNames);
  vector<map<histType,TH1F*>> muonHists1 = creatMuonHists(triggerNames, "_1");
  vector<map<histType,TH1F*>> muonHists2 = creatMuonHists(triggerNames, "_2");
  vector<map<histType,TH1F*>> muonHists3 = creatMuonHists(triggerNames, "_3");

  // Loop over events to Analyze
  unsigned int nEventsTotal = 0;
  unsigned int nEventsChain = chain->GetEntries();
  if (nEvents >= 0) nEventsChain = nEvents;
  TObjArray *listOfFiles = chain->GetListOfFiles();
  TIter fileIter(listOfFiles);
  TFile *currentFile = 0;

  // File Loop
  while ( (currentFile = (TFile*)fileIter.Next()) ) {

    // Get File Content
    TFile file( currentFile->GetTitle() );
    TTree *tree = (TTree*)file.Get("t");
    if (fast) TTreeCache::SetLearnEntries(10);
    if (fast) tree->SetCacheSize(128*1024*1024);
    t.Init(tree);

    int evt_num = -1;
    int nMuonCount = 0;
    int isTriggerMuon = 0;
    LorentzVector p4mu;
    LorentzVector tag_p4mu;

    vector<TBranch*> trigBranches = setupTriggerBranches(triggerNames, tree);
    vector<TBranch*> tagTrigBranches = setupTagTriggerBranches(triggerNames, tree);

    // Loop over Events in current file
    if (nEventsTotal >= nEventsChain) continue;
    unsigned int nEventsTree = tree->GetEntriesFast();
    for (unsigned int event = 0; event < nEventsTree; ++event) {

      // Get Event Content
      if (nEventsTotal >= nEventsChain) continue;
      if (fast) tree->LoadTree(event);
      t.GetEntry(event);
      ++nEventsTotal;

      // Progress
      LepTree::progress(nEventsTotal, nEventsChain);

      // Analysis Code

      if (evt_isRealData() && evt_run() < 273423) continue;  // Get runs after fixing the L1 interface problem

      int nevt = evt_event();
      if (nevt != evt_num) {
        h_muonCount->Fill(nMuonCount);
        nMuonCount = 0;
        isTriggerMuon = 0;
      }

      // --- New Tag & Probe ---
      if (abs(id()) != 13) continue;
      if (p4().pt() < 10) continue;
      if (fabs(p4().eta()) > 2.4 ) continue;
      if (charge()*tag_charge() > 0) continue;
      if (tag_p4().pt() < 25) continue;
      if (tag_RelIso03EA() > 0.1) continue;
      if (dilep_mass() < 81.2 || dilep_mass() > 101.2) continue;
      if (!pid_PFMuon()) continue;

      ++nMuonCount;
      // if (nMuonCount > 2) continue;

      for (unsigned int i=0; i<triggerNames.size(); i++) {
        if (getTriggerValue(tagTrigBranches[i], event) <= 0) continue;

        fillTagMuonHists(muonHists[i],  triggerPtCuts[i]);
        if (passes_IsoCut() && passes_leptonID())
          fillProbeMuonHists(muonHists[i], trigBranches[i], event, triggerPtCuts[i]);

        fillTagMuonHists(muonHists1[i], triggerPtCuts[i]);
        fillTagMuonHists(muonHists2[i], triggerPtCuts[i]);
        fillTagMuonHists(muonHists3[i], triggerPtCuts[i]);

        fillDenMuonHists(muonHists1[i], triggerPtCuts[i]);
        if (passes_IsoCut() && passes_leptonID())
          fillNumMuonHists(muonHists1[i], triggerPtCuts[i]);

        if (passes_IsoCut()) {
          fillDenMuonHists(muonHists2[i], triggerPtCuts[i]);
          if (passes_leptonID())
            fillNumMuonHists(muonHists2[i], triggerPtCuts[i]);
        }

        if (passes_leptonID()) {
          fillDenMuonHists(muonHists3[i], triggerPtCuts[i]);
          if (passes_IsoCut())
            fillNumMuonHists(muonHists3[i], triggerPtCuts[i]);
        }
      }

      // End of Analysis Code
    }

    // Clean Up
    delete tree;
    file.Close();
  }
  if ( nEventsChain != nEventsTotal ) {
    cout << Form( "ERROR: number of events from files (%d) is not equal to total number of events (%d)", nEventsChain, nEventsTotal ) << endl;
  }

  // return
  bmark->Stop("benchmark");

  TFile* outfile = new TFile("hists.root", "RECREATE");

  for (unsigned int i=0; i<triggerNames.size(); i++) {
    TDirectory * dir = (TDirectory*) outfile->mkdir(triggerNames[i].c_str());
    dir->cd();
    TDirectory * dir2 = (TDirectory*) dir->mkdir("trigeff");
    dir2->cd();
    writeEfficiencyPlots(muonHists[i], triggerNames[i], outfile);
    dir2 = (TDirectory*) dir->mkdir("ID+ISO");
    dir2->cd();
    writeEfficiencyPlots(muonHists1[i], triggerNames[i], outfile);
    dir2 = (TDirectory*) dir->mkdir("ID");
    dir2->cd();
    writeEfficiencyPlots(muonHists2[i], triggerNames[i], outfile);
    dir2 = (TDirectory*) dir->mkdir("ISO");
    dir2->cd();
    writeEfficiencyPlots(muonHists3[i], triggerNames[i], outfile);
  }

  h_muonCount->Write();

  outfile->Close();

  cout << endl;
  cout << nEventsTotal << " Events Processed" << endl;
  cout << "------------------------------" << endl;
  cout << "CPU  Time:	" << Form( "%.01f", bmark->GetCpuTime("benchmark")  ) << endl;
  cout << "Real Time:	" << Form( "%.01f", bmark->GetRealTime("benchmark") ) << endl;
  cout << endl;
  delete bmark;
  return 0;
}
Example #17
0
int ScanChain( TChain* chain, TString outfile, TString option="", bool fast = true, int nEvents = -1, string skimFilePrefix = "test") {

  // Benchmark
  TBenchmark *bmark = new TBenchmark();
  bmark->Start("benchmark");

  bool noSIP = false;
  if (option.Contains("noSIP")) noSIP = true;

  bool usePtRel = false;
  if (option.Contains("ptRel")) usePtRel = true;

  bool doBonly = false;
  if (option.Contains("doBonly")) doBonly = true;

  bool doConly = false;
  if (option.Contains("doConly")) doConly = true;

  bool doLightonly = false;
  if (option.Contains("doLightonly")) doLightonly = true;

  // Example Histograms
  TDirectory *rootdir = gDirectory->GetDirectory("Rint:");

  TH2D *pTrelvsIso_histo_el = new TH2D("pTrelvsIso_histo_el", "pTrel vs Iso (Electrons)", 10, 0., 1., 15, 0., 30.);
  pTrelvsIso_histo_el->SetDirectory(rootdir);
  pTrelvsIso_histo_el->Sumw2();

  TH2D *pTrelvsIso_histo_mu = new TH2D("pTrelvsIso_histo_mu", "pTrel vs Iso (Muons)", 10, 0., 1., 15, 0., 30.);
  pTrelvsIso_histo_mu->SetDirectory(rootdir);
  pTrelvsIso_histo_mu->Sumw2();
  //----------------------

  // Loop over events to Analyze
  unsigned int nEventsTotal = 0;
  unsigned int nEventsChain = chain->GetEntries();
  if( nEvents >= 0 ) nEventsChain = nEvents;
  TObjArray *listOfFiles = chain->GetListOfFiles();
  TIter fileIter(listOfFiles);
  TFile *currentFile = 0;

  // File Loop
  while ( (currentFile = (TFile*)fileIter.Next()) ) {

    // Get File Content
    TFile *file = new TFile( currentFile->GetTitle() );
    TTree *tree = (TTree*)file->Get("t");
    if(fast) TTreeCache::SetLearnEntries(10);
    if(fast) tree->SetCacheSize(128*1024*1024);
    ss.Init(tree);
    
    // Loop over Events in current file   //ACTUALLY A LEPTON "EVENT" LOOP
    if( nEventsTotal >= nEventsChain ) continue;
    unsigned int nEventsTree = tree->GetEntriesFast();
    for( unsigned int event = 0; event < nEventsTree; ++event) {
    
      // Get Event Content
      if( nEventsTotal >= nEventsChain ) continue;
      if(fast) tree->LoadTree(event);
      ss.GetEntry(event);
      ++nEventsTotal;
    
      // Progress
      lepfilter::progress( nEventsTotal, nEventsChain );
	  
      // Analysis Code
	  float weight = ss.scale1fb()*10.0;
	  if(ss.scale1fb() > 100000.) continue;  //excludes 5to10 and 10to20 EM Enriched
	  
	  bool jetptcut = false;
	  int jetidx = 0;

	  while( (jetidx < ss.jets().size()) && !jetptcut) //check to see if at least one jet w/ pt > 40
	  	{
	  	  if( ss.jets()[jetidx].pt() > 40. )
	  		{jetptcut = true;}
	  	  jetidx++;
	  	}
	  
	  if( !(jetptcut && ss.met() < 20. && ss.mt() < 20) )
	  	{continue;}

	  // if(ss.nFOs() != 1) //if more than 1 FO in event
	  // 	{continue;}
   
	  int nbtags = 0;
	  for(int i = 0; i < ss.jets().size(); i++){
		  if(ss.jets_disc()[i] > 0.814) nbtags++;
		}
	  if (nbtags > 2.) nbtags = 2;

	  if(ss.p4().pt() > 100. || ss.p4().pt() < 10. || fabs(ss.p4().eta()) > 2.4) //What do we want here? 
	  	{continue;}

	  //------------------------------------------------------------------------------------------
	  //---------------------------------Find e = f(Pt,eta)---------------------------------------
	  //------------------------------------------------------------------------------------------

	  //Find ratio of nonprompt leps passing tight to nonprompt leps passing at least loose.  This is the fake rate 
	  // Use lep_passes_id to see if num.  Use FO to see if Fakable Object (denom)
	  //Calculate e=Nt/(Nl) where l->loose  (as opposed to loose-not-tight).
	  
	  //Using gen level info to see if prompt -> no prompt contamination in measurement region
	  //everything else is RECO (p4, id, passes_id, FO, etc.)
	  

	  if( ss.motherID() != 1 && (doBonly==0 || ss.motherID() == -1) && (doConly==0 || ss.motherID() == -2) && (doLightonly==0 || ss.motherID() == 0) )  //if el is nonprompt (GEN info)
		{
		  if( abs( ss.id() ) == 11 ) // it's an el
			{
			  if(ss.FO_NoIso())  pTrelvsIso_histo_el->Fill( ss.iso(), ss.ptrelv1() );
			}
		  if( abs( ss.id() ) == 13 ) // it's a mu
			{
 			  if(ss.FO_NoIso())  pTrelvsIso_histo_mu->Fill( ss.iso(), ss.ptrelv1() );
			}
		} 

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

	}//end event loop
  
    // Clean Up
    delete tree;
    file->Close();
    delete file;
  }
  if ( nEventsChain != nEventsTotal ) {
    cout << Form( "ERROR: number of events from files (%d) is not equal to total number of events (%d)", nEventsChain, nEventsTotal ) << endl;
  }

  pTrelvsIso_histo_el->GetXaxis()->SetTitle("Iso");
  pTrelvsIso_histo_el->GetYaxis()->SetTitle("pTrel");
  pTrelvsIso_histo_mu->GetXaxis()->SetTitle("Iso");
  pTrelvsIso_histo_mu->GetYaxis()->SetTitle("pTrel");

  gStyle->SetOptStat(0);
  gStyle->SetPaintTextFormat("1.3f");

  TCanvas *c9=new TCanvas("c9","B pTrel vs Iso (el)",800,800);
  pTrelvsIso_histo_el->Draw("colz,texte");
  TCanvas *c10=new TCanvas("c10","B pTrel vs Iso (mu)",800,800);
  pTrelvsIso_histo_mu->Draw("colz,texte");

  //---save histos-------//
  TFile *OutputFile = new TFile(outfile,"recreate");
  pTrelvsIso_histo_el->Write();
  pTrelvsIso_histo_mu->Write();

  OutputFile->Close();

  // return
  bmark->Stop("benchmark");
  cout << endl;
  cout << nEventsTotal << " Events Processed" << endl;
  cout << "------------------------------" << endl;
  cout << "CPU  Time:	" << Form( "%.01f", bmark->GetCpuTime("benchmark")  ) << endl;
  cout << "Real Time:	" << Form( "%.01f", bmark->GetRealTime("benchmark") ) << endl;
  cout << endl;
  delete bmark;
  return 0;
}
int ScanChain( TChain* chain, bool fast = true, int nEvents = -1, string skimFilePrefix = "test") {

  //load PUweights
  TFile *fPU = new TFile("puWeights.root","READ");
  TH1D *puWeight     = (TH1D*)fPU->Get("puWeight");
  TH1D *puWeightUp   = (TH1D*)fPU->Get("puWeightUp");
  TH1D *puWeightDown = (TH1D*)fPU->Get("puWeightDown");

  TFile *fxsec = new TFile("xsec_stop_13TeV.root","READ");
  TH1D *hxsec     = (TH1D*)fxsec->Get("stop");

  TFile *f_el_SF       = new TFile("lepsf/kinematicBinSFele.root", "read");
  TFile *f_mu_SF_id    = new TFile("lepsf/TnP_MuonID_NUM_MediumID_DENOM_generalTracks_VAR_map_pt_eta.root", "read");
  TFile *f_mu_SF_iso   = new TFile("lepsf/TnP_MuonID_NUM_MiniIsoTight_DENOM_LooseID_VAR_map_pt_eta.root");
  TFile *f_mu_SF_veto_id  = new TFile("lepsf/TnP_MuonID_NUM_LooseID_DENOM_generalTracks_VAR_map_pt_eta.root", "read");
  TFile *f_mu_SF_veto_iso = new TFile("lepsf/TnP_MuonID_NUM_MiniIsoTight_DENOM_LooseID_VAR_map_pt_eta.root");
  //TFile *f_mu_SF_veto_iso = new TFile("lepsf/TnP_MuonID_NUM_MiniIsoLoose_DENOM_LooseID_VAR_map_pt_eta.root");
  //TFile *f_vetoLep_eff = new TFile("lepsf/lepeff__ttbar_powheg_pythia8_25ns.root", "read");
  TFile *f_vetoLep_eff = new TFile("lepsf/lepeff__ttbar_powheg_pythia8_25ns__SRcuts.root", "read");  
  TH2D *h_el_SF_id_temp      = (TH2D*)f_el_SF->Get("CutBasedMedium");
  TH2D *h_el_SF_iso_temp     = (TH2D*)f_el_SF->Get("MiniIso0p1_vs_AbsEta");
  TH2D *h_el_SF_veto_id_temp  = (TH2D*)f_el_SF->Get("CutBasedVeto");
  TH2D *h_el_SF_veto_iso_temp = (TH2D*)f_el_SF->Get("MiniIso0p4_vs_AbsEta");
  TH2D *h_mu_SF_id_temp      = (TH2D*)f_mu_SF_id->Get("pt_abseta_PLOT_pair_probeMultiplicity_bin0_&_tag_combRelIsoPF04dBeta_bin0_&_tag_pt_bin0_&_tag_IsoMu20_pass");
  TH2D *h_mu_SF_iso_temp     = (TH2D*)f_mu_SF_iso->Get("pt_abseta_PLOT_pair_probeMultiplicity_bin0_&_tag_combRelIsoPF04dBeta_bin0_&_tag_pt_bin0_&_PF_pass_&_tag_IsoMu20_pass");
  TH2D *h_mu_SF_veto_id_temp  = (TH2D*)f_mu_SF_veto_id->Get("pt_abseta_PLOT_pair_probeMultiplicity_bin0_&_tag_combRelIsoPF04dBeta_bin0_&_tag_pt_bin0_&_tag_IsoMu20_pass");
  TH2D *h_mu_SF_veto_iso_temp = (TH2D*)f_mu_SF_veto_iso->Get("pt_abseta_PLOT_pair_probeMultiplicity_bin0_&_tag_combRelIsoPF04dBeta_bin0_&_tag_pt_bin0_&_PF_pass_&_tag_IsoMu20_pass");
  //TH2D *h_el_vetoLepEff_temp = (TH2D*)f_vetoLep_eff->Get("h2_lepEff_vetoSel_Eff_el");
  //TH2D *h_mu_vetoLepEff_temp = (TH2D*)f_vetoLep_eff->Get("h2_lepEff_vetoSel_Eff_mu");
  TH2D *h_el_vetoLepEff_temp = (TH2D*)f_vetoLep_eff->Get("h2_lepEff_vetoSel_rebin_Eff_el");
  TH2D *h_mu_vetoLepEff_temp = (TH2D*)f_vetoLep_eff->Get("h2_lepEff_vetoSel_rebin_Eff_mu");
  TH2D *h_el_SF_id  = (TH2D*)h_el_SF_id_temp->Clone("h_el_SF_id");
  TH2D *h_el_SF_iso = (TH2D*)h_el_SF_iso_temp->Clone("h_el_SF_iso");
  TH2D *h_mu_SF_id  = (TH2D*)h_mu_SF_id_temp->Clone("h_mu_SF_id");
  TH2D *h_mu_SF_iso = (TH2D*)h_mu_SF_iso_temp->Clone("h_mu_SF_iso");
  TH2D *h_el_SF_veto_id  = (TH2D*)h_el_SF_veto_id_temp->Clone("h_el_SF_veto_id");
  TH2D *h_el_SF_veto_iso = (TH2D*)h_el_SF_veto_iso_temp->Clone("h_el_SF_veto_iso");
  TH2D *h_mu_SF_veto_id  = (TH2D*)h_mu_SF_veto_id_temp->Clone("h_mu_SF_veto_id");
  TH2D *h_mu_SF_veto_iso = (TH2D*)h_mu_SF_veto_iso_temp->Clone("h_mu_SF_veto_iso");
  //This is are the important ones
  TH2D *h_el_vetoLepEff = (TH2D*)h_el_vetoLepEff_temp->Clone("h_el_vetoLepEff");
  TH2D *h_mu_vetoLepEff = (TH2D*)h_mu_vetoLepEff_temp->Clone("h_mu_vetoLepEff");
  TH2D *h_el_SF = (TH2D*)h_el_SF_id->Clone("h_el_SF");
  h_el_SF->Multiply(h_el_SF_iso);
  TH2D *h_el_SF_veto = (TH2D*)h_el_SF_veto_id->Clone("h_el_SF_veto");
  TH2D *h_mu_SF = (TH2D*)h_mu_SF_id->Clone("h_mu_SF");
  h_mu_SF->Multiply(h_mu_SF_iso);
  TH2D *h_mu_SF_veto = (TH2D*)h_mu_SF_veto_id->Clone("h_mu_SF_veto");
  h_mu_SF_veto->Multiply(h_mu_SF_veto_iso);
  TFile *f_el_FS_ID       = new TFile("lepsf/sf_el_mediumCB.root", "read");
  TFile *f_el_FS_Iso      = new TFile("lepsf/sf_el_mini01.root", "read");
  TFile *f_mu_FS_ID       = new TFile("lepsf/sf_mu_mediumID.root", "read");
  TFile *f_mu_FS_Iso      = new TFile("lepsf/sf_mu_mini02.root", "read");
  TH2D *h_el_FS_ID_temp  = (TH2D*)f_el_FS_ID ->Get("histo2D");
  //TH2D *h_el_FS_ID       = (TH2D*)h_el_FS_ID_temp ->Clone("h_el_FS_ID");
  TH2D *h_el_FS          = (TH2D*)h_el_FS_ID_temp ->Clone("h_el_FS");
  TH2D *h_el_FS_Iso_temp = (TH2D*)f_el_FS_Iso->Get("histo2D");
  //TH2D *h_el_FS_Iso      = (TH2D*)h_el_FS_Iso_temp->Clone("h_el_FS_Iso");
  h_el_FS->Multiply(h_el_FS_Iso_temp);
  TH2D *h_mu_FS_ID_temp  = (TH2D*)f_mu_FS_ID ->Get("histo2D");
  //TH2D *h_mu_FS_ID       = (TH2D*)h_mu_FS_ID_temp ->Clone("h_mu_FS_ID");
  TH2D *h_mu_FS          = (TH2D*)h_mu_FS_ID_temp ->Clone("h_mu_FS");
  TH2D *h_mu_FS_Iso_temp = (TH2D*)f_mu_FS_Iso->Get("histo2D");
  //TH2D *h_mu_FS_Iso      = (TH2D*)h_mu_FS_Iso_temp->Clone("h_mu_FS_ID");
  h_mu_FS->Multiply(h_mu_FS_Iso_temp);

  
  // Benchmark
  TBenchmark *bmark = new TBenchmark();
  bmark->Start("benchmark");

  // Example Histograms
  TDirectory *rootdir = gDirectory->GetDirectory("Rint:");


  map<string, TH3D*> histos;//use D histos as weights can vary a lot among the signal
  vector<string> histonames; histonames.clear();
  //  vector<int> hbins; hbins.clear();
  //  vector<float> hlow; hlow.clear();
  //  vector<float> hup; hup.clear();

  //lumi, trigger, stats done
  histonames.push_back("SRyield");
  histonames.push_back("SR_Bup_HF");//done
  histonames.push_back("SR_Bdown_HF");
  histonames.push_back("SR_Bup_LF");//done
  histonames.push_back("SR_Bdown_LF");
  histonames.push_back("SR_JESup");
  histonames.push_back("SR_JESdown");
  histonames.push_back("SR_muRFup");
  histonames.push_back("SR_muRFdown");
  //histonames.push_back("SR_PDFup");
  //histonames.push_back("SR_PDFdown");
  histonames.push_back("SR_ISRup");//done preliminary
  histonames.push_back("SR_ISRdown");
  histonames.push_back("SR_PUup");//done preliminary
  histonames.push_back("SR_PUdown");
  histonames.push_back("SR_LepEffup");//done - I guess we need no renormalization - no fastsim in, no vetoSF
  histonames.push_back("SR_LepEffdown");
  histonames.push_back("SR_LepEffFSup");//done - I guess we need no renormalization - no fastsim in, no vetoSF
  histonames.push_back("SR_LepEffFSdown");
  histonames.push_back("SR_Xsecup");//done
  histonames.push_back("SR_Xsecdown");
  histonames.push_back("CR1l_sigcontamination");//scaled to signalreg yield
  histonames.push_back("CR2l_sigcontamination");//scaled to signalreg yield
  /*
  histonames.push_back("eventsum");
  histonames.push_back("rawweightsum");
  histonames.push_back("totweightsum");
  histonames.push_back("ISRsum");
  histonames.push_back("BSFsum");
  histonames.push_back("PUweightsum");
  histonames.push_back("xsecsum");
  histonames.push_back("nevtsum");
  histonames.push_back("lepsum");
  histonames.push_back("lepSFsum");
  */
  for(unsigned int i = 0; i<histonames.size(); ++i){
    string mapname = histonames[i];
    if(histos.count(mapname) == 0 ) histos[mapname] = new TH3D(mapname.c_str(), "", 37,99,1024, 19,-1,474, 13, -0.5,12.5);
    //mStop 100-1000, mLSP 0-450, SR 1-12, 9200 bins, SR 0 is non-SR - in case it it needed!!
      histos[mapname]->Sumw2(); histos[mapname]->SetDirectory(rootdir);
    }

  
  
  // Loop over events to Analyze
  unsigned int nEventsTotal = 0;
  unsigned int nEventsChain = chain->GetEntries();
  if( nEvents >= 0 ) nEventsChain = nEvents;
  TObjArray *listOfFiles = chain->GetListOfFiles();
  TIter fileIter(listOfFiles);
  TFile *currentFile = 0;

  //get the reweighting histograms
  TIter fileIterFirst(listOfFiles);
  TFile *currentFileFirst = 0;
  TH3D* counterhistSig;
  TH2F* histNEvts;
  bool thisisfirst = true;
  // File Loop for adding correct histograms
  while ( (currentFileFirst = (TFile*)fileIterFirst.Next()) ) {
    TFile *file = new TFile( currentFileFirst->GetTitle() );
    file->cd();
    if(thisisfirst){
      counterhistSig = (TH3D*)file->Get("h_counterSMS");
      counterhistSig->SetDirectory(0); 
      histNEvts = (TH2F*)file->Get("histNEvts");
      histNEvts->SetDirectory(0);
      thisisfirst = false;
    } else {
      TH3D *tempcounterhistSig = (TH3D*)file->Get("h_counterSMS");
      tempcounterhistSig->SetDirectory(0); 
      TH2F *temphistNEvts = (TH2F*)file->Get("histNEvts");
      temphistNEvts->SetDirectory(0);
      counterhistSig->Add(tempcounterhistSig);
      histNEvts->Add(temphistNEvts);
      tempcounterhistSig->Delete();
      temphistNEvts->Delete();
    }
    file->Close();
    delete file;
  }

  // File Loop
  while ( (currentFile = (TFile*)fileIter.Next()) ) {

    // Get File Content
    TFile *file = new TFile( currentFile->GetTitle() );
    TTree *tree = (TTree*)file->Get("t");
    if(fast) TTreeCache::SetLearnEntries(10);
    if(fast) tree->SetCacheSize(128*1024*1024);
    cms3.Init(tree);
    
    // Loop over Events in current file
    if( nEventsTotal >= nEventsChain ) continue;
    unsigned int nEventsTree = tree->GetEntriesFast();
    for( unsigned int event = 0; event < nEventsTree; ++event) {
 
      // Get Event Content
      if( nEventsTotal >= nEventsChain ) continue;
      if(fast) tree->LoadTree(event);
      cms3.GetEntry(event);
      ++nEventsTotal;
    
      // Progress
      CMS3::progress( nEventsTotal, nEventsChain );

      // Analysis Code

      float mStop = mass_stop();
      float mLSP = mass_lsp();
      float mCharg = mass_chargino();
      //float xVal = mass_lsp();
      int Nevts = histNEvts->GetBinContent(histNEvts->FindBin(mStop,mLSP));
      double nevts = double(Nevts);
      //float weight = cms3.scale1fb()*2.11;
      double PUweight     = puWeight    ->GetBinContent(puWeight    ->FindBin(pu_ntrue() ) );
      double PUweightUp   = puWeightUp  ->GetBinContent(puWeightUp  ->FindBin(pu_ntrue() ) );
      double PUweightDown = puWeightDown->GetBinContent(puWeightDown->FindBin(pu_ntrue() ) );
      PUweightUp = 1; PUweightDown = PUweight; PUweight = 1; //now PU syst is applying vs not applying
     double ISRnorm = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,19));
      double ISRnormup = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,20));
      double ISRnormdown = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,21));
      double ISRweight = weight_ISR();
      double BSFnorm = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,14));
      double BSFnormHup = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,15));
      double BSFnormLup = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,16));
      double BSFnormHdown = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,17));
      double BSFnormLdown = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,18));
      double BSFweight = weight_btagsf();
      double muRFnorm = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,1));
      double muRFnormup = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,5));
      double muRFnormdown = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,9));
      if(ISRnorm>0) ISRweight*=nevts/ISRnorm;
      if(ISRnorm<=0||ISRnormup<=0||ISRnormdown<=0){ ISRnormdown=1.; ISRnormup=1.; ISRnorm=1.;}
      if(ISRweight!=weight_ISR()) cout << "ISRw " << ISRweight << " wISR " << weight_ISR() << " nevts " << nevts << " ISRn " << ISRnorm << endl;
      if(BSFnorm>0) BSFweight *=nevts/BSFnorm;
      if(BSFnorm<=0||BSFnormHup<=0||BSFnormLup<=0||BSFnormHdown<=0||BSFnormLdown<=0){
	BSFnorm=1; BSFnormHup=1; BSFnormLup=1; BSFnormHdown=1; BSFnormLdown=1;
      }
      if(muRFnorm<=0||muRFnormup<=0||muRFnormdown<=0){ muRFnormdown=1; muRFnormup=1; muRFnorm=1; }
      //lepSF is done below
      double xsection = hxsec->GetBinContent(hxsec->FindBin(mStop));
      double xsectionerr = hxsec->GetBinError(hxsec->FindBin(mStop));
      //double rawweight = xsec()*2260./nevts;
      //double weight = xsec()*2260./nevts*PUweight*ISRweight*BSFweight;//xsec given in pb
      double rawweight = xsection*2260./nevts;
      double weight = xsection*2260./nevts*PUweight*ISRweight*BSFweight;//xsec given in pb
      //did put ISRweight which should be ==1
      if(ISRweight!=1) cout << "ISRw " << ISRweight << endl;
      if(event==0) cout << "weight " << weight << " nEvents " << nEventsTree << " filename " << currentFile->GetTitle() << endl;

      int NSLeps = 0;
      int NAddVetoLeps = 0;
      if(lep1_is_mu()){
	if(lep1_pt()>20&&fabs(lep1_eta())<2.4) {++NSLeps;}
      } else if (lep1_is_el()){
	if(lep1_pt()>20&&fabs(lep1_eta())<1.4442) {++NSLeps; }
      } if(lep2_is_mu()){
	if(lep2_pt()>20&&fabs(lep2_eta())<2.4) {++NSLeps;}
      } else if (lep2_is_el()){
	if(lep2_pt()>20&&fabs(lep2_eta())<1.4442) {++NSLeps; }
      }
      if(lep2_is_mu()){
	if(lep2_pt()>10&&fabs(lep2_eta())<2.4) {++NAddVetoLeps;}
      } else if (lep2_is_el()){
	if(lep2_pt()>10&&fabs(lep2_eta())<2.4) {++NAddVetoLeps; }
      }
      if(NSLeps<1) continue;//temp
      float lepSF_pt_cutoff = 100.0;
      float lepSF_pt_min    = 10.0;
      double lepSF    = 1.0;
      double lepSF_Up = 1.0;
      double lepSF_Dn = 1.0;
      float lepSF_FS_pt_cutoff = 200.0;
      double lepSF_FS    = 1.0;
      double lepSF_FS_Up = 1.0;
      double lepSF_FS_Dn = 1.0;	
      if(lep1_is_el()){
	int binX = h_el_SF->GetXaxis()->FindBin( std::min(lepSF_pt_cutoff, (float)lep1_p4().Pt()) );
	int binY = h_el_SF->GetYaxis()->FindBin( fabs(lep1_p4().Eta()) );
	lepSF    = h_el_SF->GetBinContent( binX, binY );
	lepSF_Up = lepSF + h_el_SF->GetBinError( binX, binY );
	lepSF_Dn = lepSF - h_el_SF->GetBinError( binX, binY );
	int bin = h_el_FS->FindBin(  std::min(lepSF_FS_pt_cutoff, (float)lep1_p4().Pt()), fabs(lep1_p4().Eta()) );
	lepSF_FS = h_el_FS->GetBinContent(bin);
	lepSF_FS_Up = lepSF_FS + h_el_FS->GetBinError(bin);
	lepSF_FS_Dn = lepSF_FS + h_el_FS->GetBinError(bin);
      }
      if(lep1_is_mu()){
	int binX = h_mu_SF->GetXaxis()->FindBin( std::min(lepSF_pt_cutoff, (float)lep1_p4().Pt()) );
	int binY = h_mu_SF->GetYaxis()->FindBin( fabs(lep1_p4().Eta()) );
	lepSF    = h_mu_SF->GetBinContent( binX, binY );
	lepSF_Up = lepSF + h_mu_SF->GetBinError( binX, binY );
	lepSF_Dn = lepSF - h_mu_SF->GetBinError( binX, binY );
	int bin = h_mu_FS->FindBin(  std::min(lepSF_FS_pt_cutoff, (float)lep1_p4().Pt()), fabs(lep1_p4().Eta()) );
	lepSF_FS = h_mu_FS->GetBinContent(bin);
	lepSF_FS_Up = lepSF_FS + h_mu_FS->GetBinError(bin);
	lepSF_FS_Dn = lepSF_FS + h_mu_FS->GetBinError(bin);
      }
      weight *= (lepSF*lepSF_FS);

      
      if(nvtxs()<0)               continue;
      if(ngoodleps()<1)           continue;//accomodate 2l-CR
      if(nvetoleps()<1)           continue;//accomodate 2l-CR
    //if(!PassTrackVeto_v3())     continue;//accomodate 2l-CR
    //if(!PassTauVeto())          continue;//accomodate 2l-CR
      if(ngoodjets()<2)           continue;
      if(ngoodbtags()<0)          continue;//accomodate 1l-CR
      if(pfmet()<250)             continue;
      if(mt_met_lep()<150)        continue;
      if(mindphi_met_j1_j2()<0.8) continue;


      int SR = -1;
      int compressedSR = -1;
      if(ngoodleps()==1&&nvetoleps()==1&&PassTrackVeto_v3()&&PassTauVeto()&&ngoodbtags()>=1){//basis for SR 1l, >=1b
	if(ngoodjets()>=4){
	  if(MT2W()<=200){
	    if(pfmet()>325) SR = 2;
	    else SR = 1;
	  } else { //high MT2W
	    if(pfmet()>450) SR = 5;
	    else if(pfmet()>350) SR = 4;
	    else SR = 3;
	  }
	} else if(ngoodjets()==3 && MT2W()>200 && pfmet()>350) {
	  SR = 6;
	} else if(MT2W()>200&&topnessMod()>(-3)) { //2 or 3 jets
	  if(ngoodbtags()==1){
	    if(pfmet()>400) SR = 8;
	    else SR = 7;
	  } else {//ge2 jets
	    if(pfmet()>400) SR = 10;
	    else SR = 9;
	  }
	}
	//compressed region (jets are sorted by pt
	if(ngoodjets()>=5&&ak4pfjets_passMEDbtag()[0]==false&&ak4pfjets_pt()[0]>200.){
	  if(MT2W()<=200) compressedSR = 11;
	  else compressedSR = 12;
	}
      }

      //CR-1l
      int CR1l = -1;
      if(ngoodleps()==1&&nvetoleps()==1&&PassTrackVeto_v3()&&PassTauVeto()&&ngoodbtags()==0&&ngoodjets()>=3&&MT2W()>200){
	if(ngoodjets()==3){
	  CR1l = 1;
	} else {
	  CR1l = 2;
	}
      }
      //CR1l  1 --> SR  6
      //CR1l  2 --> SR  3-5
      float CR1l_1_6 = 0.37*0.18;
      float CR1l_2_3 = 0.55*0.15;
      float CR1l_2_4 = 0.25*0.29;
      float CR1l_2_5 = 0.20*0.40;

      //CR2l = -1;
      int lepind = -1;
      if(ngoodleps()>=2&&NSLeps==2) lepind = 5;
      else if(ngoodleps()==2&&NSLeps==2) lepind = 4;//exactly two leptons,CR4
      else if(ngoodleps()==1&&NSLeps==1&&NAddVetoLeps>=1) lepind = 3;//one lepton, but more than 1 add. loose,1l,>2l
      //else if(ngoodleps()==1&&NSLeps==1&&nvetoleps()==2) lepind = 2;//one lepton + 1 add. loose,CR5
      else if(ngoodleps()==1&&NSLeps==1&&nvetoleps()==0&&(!PassTrackVeto_v3()||!PassTauVeto())) lepind = 1;//exactly one lepton, but do not pass track/tau veto - i.e. one additional track or tau, CR6
      int CR2l = -1;
      if((lepind==4||lepind==3||lepind==1)&&ngoodjets()>=3&&ngoodbtags()>=1){
	if(MT2W()<=200) CR2l = 1;
	else CR2l = 2;
      }
      float CR2l_1_1 = 0.61*0.48;
      float CR2l_1_2 = 0.61*0.19;
      float CR2l_2_3 = 0.44*0.39;
      float CR2l_2_4 = 0.44*0.11;
      float CR2l_2_5 = 0.44*0.07;
      float CR2l_2_6 = 0.44*0.11;

      if(SR==(-1)&&CR1l==(-1)&&CR2l==(-1)&&compressedSR==(-1)) continue;
      //implement some sanity checks
      if(CR1l!=(-1)&&CR2l!=(-1)) cout << "WTF CR1l " << CR1l << " CR2l " << CR2l << endl;
      if(SR!=(-1)&&CR1l!=(-1)) cout << "WTF SR " << SR << " CR1l " << CR1l << endl;
      if(SR!=(-1)&&CR2l!=(-1)) cout << "WTF SR " << SR << " CR2l " << CR2l << endl;

      //ISR reweighting, get stop pair using last copy:
      double ISRup = weight_ISRup()/weight_ISR()*ISRnorm/ISRnormup;
      double ISRdown = weight_ISRdown()/weight_ISR()*ISRnorm/ISRnormdown;
      //double XSup = (xsec()+xsec_uncert())/xsec();
      //double XSdown = (xsec()-xsec_uncert())/xsec();
      double XSup = (xsection+xsectionerr)/xsection;
      double XSdown = (xsection-xsectionerr)/xsection;
      double PUup = PUweightUp/PUweight;
      double PUdown = PUweightDown/PUweight;
      double lEffup = lepSF_Up/lepSF;
      double lEffdown = lepSF_Dn/lepSF;
      double lEffFSup = lepSF_FS_Up/lepSF_FS;
      double lEffFSdown = lepSF_FS_Dn/lepSF_FS;
      double BSFHup = weight_btagsf_heavy_UP()/weight_btagsf()*BSFnorm/BSFnormHup;
      double BSFLup = weight_btagsf_light_UP()/weight_btagsf()*BSFnorm/BSFnormHup;
      double BSFHdown = weight_btagsf_heavy_DN()/weight_btagsf()*BSFnorm/BSFnormHup;
      double BSFLdown = weight_btagsf_light_DN()/weight_btagsf()*BSFnorm/BSFnormHup;
      double muRFup = genweights().at(4)/genweights().at(0)*muRFnorm/muRFnormup;
      double muRFdown = genweights().at(8)/genweights().at(0)*muRFnorm/muRFnormdown;
      //cout << genweights().at(0) << " " << genweights().at(4) << " " << genweights().at(8) << " " << mStop << " " << mLSP << endl;

      if(CR1l>0){
	if(ngoodleps()!=1) cout << __LINE__ << " " << ngoodleps() << endl;
	if(NSLeps!=1) cout << __LINE__ << " " << NSLeps << endl;
	if(nvetoleps()!=1) cout << __LINE__ << " " << nvetoleps() << endl;
	if(ngoodbtags()>=1) cout << __LINE__ << " " << ngoodbtags() << endl;
	//signal contamination in 0b control region, do correlations later during datacard making
	if(CR1l==1){
	  histos["CR1l_sigcontamination"]->Fill(mStop,mLSP,6,weight*CR1l_1_6);
	} else if(CR1l==2){
	  histos["CR1l_sigcontamination"]->Fill(mStop,mLSP,3,weight*CR1l_2_3);
	  histos["CR1l_sigcontamination"]->Fill(mStop,mLSP,4,weight*CR1l_2_4);
	  histos["CR1l_sigcontamination"]->Fill(mStop,mLSP,5,weight*CR1l_2_5);
	}
      } else if(CR2l>0){
	if(nvetoleps()<=1||(nvetoleps()==1&&(!PassTrackVeto_v3()||!PassTauVeto()))) cout << __LINE__ << " " << nvetoleps() << " " << PassTrackVeto_v3() << " " << PassTauVeto() << endl;
	if(ngoodbtags()<1) cout << __LINE__ << " " << ngoodbtags() << endl;
	//signal contamination in 2l control region, do correlations later during datacard making
	if(CR2l==1){
	  histos["CR2l_sigcontamination"]->Fill(mStop,mLSP,1,weight*CR2l_1_1);
	  histos["CR2l_sigcontamination"]->Fill(mStop,mLSP,2,weight*CR2l_1_2);
	} else if(CR2l==2){
	  histos["CR2l_sigcontamination"]->Fill(mStop,mLSP,3,weight*CR2l_2_3);
	  histos["CR2l_sigcontamination"]->Fill(mStop,mLSP,4,weight*CR2l_2_4);
	  histos["CR2l_sigcontamination"]->Fill(mStop,mLSP,5,weight*CR2l_2_5);
	  histos["CR2l_sigcontamination"]->Fill(mStop,mLSP,6,weight*CR2l_2_6);

	}
      } else if(SR>0){
	if(ngoodleps()!=1) cout << __LINE__ << " " << ngoodleps() << endl;
	if(NSLeps!=1) cout << __LINE__ << " " << NSLeps << endl;
	if(nvetoleps()!=1) cout << __LINE__ << " " << nvetoleps() << endl;
	if(!PassTrackVeto_v3())  cout << __LINE__ << endl;
	if(!PassTauVeto())  cout << __LINE__ << endl;
	if(SR<=6&&ngoodjets()<3) cout << __LINE__ << " " << ngoodjets() << endl;
	if(ngoodbtags()<1) cout << __LINE__ << " " << ngoodbtags() << endl;
	/*
	histos["eventsum"]->Fill(mStop,mLSP,SR,1.);
	histos["rawweightsum"]->Fill(mStop,mLSP,SR,rawweight);
	histos["totweightsum"]->Fill(mStop,mLSP,SR,weight);
	histos["ISRsum"]->Fill(mStop,mLSP,SR,ISRweight);
	histos["BSFsum"]->Fill(mStop,mLSP,SR,BSFweight);
	histos["PUweightsum"]->Fill(mStop,mLSP,SR,PUweight);
	histos["xsecsum"]->Fill(mStop,mLSP,SR,xsection);
	histos["nevtsum"]->Fill(mStop,mLSP,SR,nevts);
	histos["lepsum"]->Fill(mStop,mLSP,SR,lepSF);
	histos["lepSFsum"]->Fill(mStop,mLSP,SR,lepSF_FS);
	*/
	//finally - do signal regions!
	histos["SRyield"]->Fill(mStop,mLSP,SR,weight);
	histos["SR_ISRup"]->Fill(mStop,mLSP,SR,weight*ISRup);
	histos["SR_ISRdown"]->Fill(mStop,mLSP,SR,weight*ISRdown);
	histos["SR_Xsecup"]->Fill(mStop,mLSP,SR,weight*XSup);
	histos["SR_Xsecdown"]->Fill(mStop,mLSP,SR,weight*XSdown);
	histos["SR_PUup"]->Fill(mStop,mLSP,SR,weight*PUup);
	histos["SR_PUdown"]->Fill(mStop,mLSP,SR,weight*PUdown);
	histos["SR_Bup_HF"]->Fill(mStop,mLSP,SR,weight*BSFHup);
	histos["SR_Bup_LF"]->Fill(mStop,mLSP,SR,weight*BSFLup);
	histos["SR_Bdown_HF"]->Fill(mStop,mLSP,SR,weight*BSFHdown);
	histos["SR_Bdown_LF"]->Fill(mStop,mLSP,SR,weight*BSFLdown);
	histos["SR_LepEffup"]->Fill(mStop,mLSP,SR,weight*lEffup);
	histos["SR_LepEffdown"]->Fill(mStop,mLSP,SR,weight*lEffdown);
	histos["SR_LepEffFSup"]->Fill(mStop,mLSP,SR,weight*lEffFSup);
	histos["SR_LepEffFSdown"]->Fill(mStop,mLSP,SR,weight*lEffFSdown);
	histos["SR_muRFup"]->Fill(mStop,mLSP,SR,weight*muRFup);
	histos["SR_muRFdown"]->Fill(mStop,mLSP,SR,weight*muRFdown);
      }
      if(compressedSR>0){
	if(compressedSR<=6) cout << __LINE__ << " " << compressedSR << endl;
	//compressedSR is defined to not overlap with SR - can use same histogram!
	histos["SRyield"]->Fill(mStop,mLSP,compressedSR,weight);
	histos["SR_ISRup"]->Fill(mStop,mLSP,compressedSR,weight*ISRup);
	histos["SR_ISRdown"]->Fill(mStop,mLSP,compressedSR,weight*ISRdown);
	histos["SR_Xsecup"]->Fill(mStop,mLSP,compressedSR,weight*XSup);
	histos["SR_Xsecdown"]->Fill(mStop,mLSP,compressedSR,weight*XSdown);
	histos["SR_PUup"]->Fill(mStop,mLSP,compressedSR,weight*PUup);
	histos["SR_PUdown"]->Fill(mStop,mLSP,compressedSR,weight*PUdown);
	histos["SR_Bup_HF"]->Fill(mStop,mLSP,compressedSR,weight*BSFHup);
	histos["SR_Bup_LF"]->Fill(mStop,mLSP,compressedSR,weight*BSFLup);
	histos["SR_Bdown_HF"]->Fill(mStop,mLSP,compressedSR,weight*BSFHdown);
	histos["SR_Bdown_LF"]->Fill(mStop,mLSP,compressedSR,weight*BSFLdown);
	histos["SR_LepEffup"]->Fill(mStop,mLSP,compressedSR,weight*lEffup);
	histos["SR_LepEffdown"]->Fill(mStop,mLSP,compressedSR,weight*lEffdown);
	histos["SR_LepEffFSup"]->Fill(mStop,mLSP,compressedSR,weight*lEffFSup);
	histos["SR_LepEffFSdown"]->Fill(mStop,mLSP,compressedSR,weight*lEffFSdown);
	histos["SR_muRFup"]->Fill(mStop,mLSP,compressedSR,weight*muRFup);
	histos["SR_muRFdown"]->Fill(mStop,mLSP,compressedSR,weight*muRFdown);
      }

    }//event loop
  
    // Clean Up
    delete tree;
    file->Close();
    delete file;
  }//file loop
  if ( nEventsChain != nEventsTotal ) {
    cout << Form( "ERROR: number of events from files (%d) is not equal to total number of events (%d)", nEventsChain, nEventsTotal ) << endl;
  }
  
  // Example Histograms
  // samplehisto->Draw();

  /*
  for(map<string,TH3D*>::iterator h=histos.begin(); h!=histos.end();++h){
    //add overflow
    //h->second->SetBinContent(h->second->GetNbinsX(), h->second->GetBinContent(h->second->GetNbinsX() )+ h->second->GetBinContent(h->second->GetNbinsX()+1) );
    //h->second->SetBinError(h->second->GetNbinsX(), sqrt(pow(h->second->GetBinError(h->second->GetNbinsX() ),2)+pow(h->second->GetBinError(h->second->GetNbinsX()+1),2) ) );
    //add underfloe
    //h->second->SetBinContent(1, h->second->GetBinContent(1)+ h->second->GetBinContent(0) );
    //h->second->SetBinError(1, sqrt(pow(h->second->GetBinError(1),2)+pow(h->second->GetBinError(0),2) ) );
  }
  */
  string filename = "rootfiles/signalyields/Histos_"+skimFilePrefix+".root";
  TFile *f = new TFile(filename.c_str(),"RECREATE");
  f->cd();
  for(map<string,TH3D*>::iterator h=    histos.begin(); h!=    histos.end();++h) h->second->Write();
  f->Close();
  cout << "Saved histos in " << f->GetName() << endl;

  f_el_SF->Close();
  f_mu_SF_id->Close();
  f_mu_SF_iso->Close();
  f_mu_SF_veto_id->Close();
  f_mu_SF_veto_iso->Close();
  f_vetoLep_eff->Close();
  f_el_FS_ID->Close();
  f_el_FS_Iso->Close();
  f_mu_FS_ID->Close();
  f_mu_FS_Iso->Close();
  // return
  bmark->Stop("benchmark");
  cout << endl;
  cout << nEventsTotal << " Events Processed" << endl;
  cout << "------------------------------" << endl;
  cout << "CPU  Time:	" << Form( "%.01f", bmark->GetCpuTime("benchmark")  ) << endl;
  cout << "Real Time:	" << Form( "%.01f", bmark->GetRealTime("benchmark") ) << endl;
  cout << endl;
  delete bmark;
  delete fPU;//delete PU file
  delete f_el_SF;
  delete f_mu_SF_id;
  delete f_mu_SF_iso;
  delete f_mu_SF_veto_id;
  delete f_mu_SF_veto_iso;
  delete f_vetoLep_eff;
  delete f_el_FS_ID;
  delete f_el_FS_Iso;
  delete f_mu_FS_ID;
  delete f_mu_FS_Iso;
  return 0;
}
Example #19
0
int ScanChain( TChain* chain, bool fast = true, int nEvents = -1, string skimFilePrefix = "test") {

  // Benchmark
  TBenchmark *bmark = new TBenchmark();
  bmark->Start("benchmark");
////////////////////////////////////////////////////////////////////////////////////////////
int mt2_l_bin = 0;
int mt2_h_bin = 200;
int mt2_n_bin = 20;

int mt_l_bin = 0;
int mt_h_bin = 300;
int mt_n_bin = 30;

int met_l_bin = 0;
int met_h_bin = 225;
int met_n_bin = 45;

int jet_n_bin = 10;
int jet_h_bin = 10;

	TH1F   *fake_wpt_h = new TH1F("fake_w_pt_","fake_W_pt",50,0,100);
	TH1F   *landau_h = new TH1F("landau_h_","landau_H",60,0,mt_h_bin);
	TH1F   *gammaM_h = new TH1F("gammaM_","gamma",120,1,6);

	TH1F *mt2_h_data = new TH1F("mt2_data_","MT2_data",mt2_n_bin,0,mt2_h_bin);
	TH1F  *mt_h_data = new  TH1F("mt_data_", "MT_data",mt_n_bin,0,mt_h_bin);
	TH1F   *met_data = new TH1F("met_data_","met_data",met_n_bin,0,met_h_bin);
	TH1F   *jets_data= new TH1F("jets_data_","Jets_data",jet_n_bin,0,jet_h_bin);
	TH1F   *data_w_pt = new     TH1F("data_w_pt_","data_W_pt",60,0,mt_h_bin);
	TH1F   *data_lep_pt = new     TH1F("data_lep_pt_","data_Lep_pt",60,0,mt_h_bin);

	TH1F *mt2_h_ttbar = new TH1F("mt2_ttbar_","MT2_ttbar",mt2_n_bin,0,mt2_h_bin);
	TH1F  *mt_h_ttbar = new  TH1F("mt_ttbar_", "MT_ttbar",mt_n_bin,0,mt_h_bin);
	TH1F   *met_ttbar = new TH1F("met_ttbar_","met_ttbar",met_n_bin,0,met_h_bin);
	TH1F   *jets_ttbar  = new TH1F("jets_ttbar_","Jets_ttbar",jet_n_bin,0,jet_h_bin);
	TH1F   *ttbar_w_pt = new     TH1F("ttbar_w_pt_","ttbar_W_pt",60,0,mt_h_bin);
	TH1F   *ttbar_lep_pt = new     TH1F("ttbar_lep_pt_","ttbar_Lep_pt",60,0,mt_h_bin);

	TH1F *mt2_h_wjets = new TH1F("mt2_wjets_","MT2_wjets",mt2_n_bin,0,mt2_h_bin);
	TH1F  *mt_h_wjets = new  TH1F("mt_wjets_", "MT_wjets",mt_n_bin,0,mt_h_bin);
	TH1F   *met_wjets = new TH1F("met_wjets_","met_wjets",met_n_bin,0,met_h_bin);
	TH1F   *jets_wjets  = new TH1F("jets_wjets_","Jets_wjets",jet_n_bin,0,jet_h_bin);
	TH1F   *wjets_w_pt = new     TH1F("wjets_w_pt_","wjets_W_pt",60,0,mt_h_bin);
	TH1F   *wjets_lep_pt = new     TH1F("wjets_lep_pt_","wjets_Lep_pt",60,0,mt_h_bin);

	wjets_lep_pt->SetLineColor(kRed);
	data_lep_pt->SetLineColor(kYellow);
	ttbar_lep_pt->SetLineColor(kCyan);

	wjets_lep_pt->SetLineWidth(4);
	 data_lep_pt->SetLineWidth(4);
	ttbar_lep_pt->SetLineWidth(4);

////MUONS////
	TH1F *mt2_h_data_mu = new TH1F("mt2_data_mu_","MT2_data_mu",mt2_n_bin,0,mt2_h_bin);
	TH1F  *mt_h_data_mu = new  TH1F("mt_data_mu_", "MT_data_mu",mt_n_bin,0,mt_h_bin);
	TH1F   *met_data_mu = new TH1F("met_data_mu_","met_data_mu",met_n_bin,0,met_h_bin);
	TH1F   *jets_data_mu= new TH1F("jets_data_mu_","Jets_data_mu",jet_n_bin,0,jet_h_bin);
	TH1F   *data_w_pt_mu = new     TH1F("data_w_pt_mu_","data_W_pt_mu",60,0,mt_h_bin);
	TH1F   *data_lep_pt_mu = new     TH1F("data_lep_pt_mu_","data_Lep_pt_mu",60,0,mt_h_bin);

	TH1F *mt2_h_ttbar_mu = new TH1F("mt2_ttbar_mu_","MT2_ttbar_mu",mt2_n_bin,0,mt2_h_bin);
	TH1F  *mt_h_ttbar_mu = new  TH1F("mt_ttbar_mu_", "MT_ttbar_mu",mt_n_bin,0,mt_h_bin);
	TH1F   *met_ttbar_mu = new TH1F("met_ttbar_mu_","met_ttbar_mu",met_n_bin,0,met_h_bin);
	TH1F   *jets_ttbar_mu  = new TH1F("jets_ttbar_mu_","Jets_ttbar_mu",jet_n_bin,0,jet_h_bin);
	TH1F   *ttbar_w_pt_mu = new     TH1F("ttbar_w_pt_mu_","ttbar_W_pt_mu",60,0,mt_h_bin);
	TH1F   *ttbar_lep_pt_mu = new     TH1F("ttbar_lep_pt_mu_","ttbar_Lep_pt_mu",60,0,mt_h_bin);

	TH1F *mt2_h_wjets_mu = new TH1F("mt2_wjets_mu_","MT2_wjets_mu",mt2_n_bin,0,mt2_h_bin);
	TH1F  *mt_h_wjets_mu = new  TH1F("mt_wjets_mu_", "MT_wjets_mu",mt_n_bin,0,mt_h_bin);
	TH1F   *met_wjets_mu = new TH1F("met_wjets_mu_","met_wjets_mu",met_n_bin,0,met_h_bin);
	TH1F   *jets_wjets_mu  = new TH1F("jets_wjets_mu_","Jets_wjets_mu",jet_n_bin,0,jet_h_bin);
	TH1F   *wjets_w_pt_mu = new     TH1F("wjets_w_pt_mu_","wjets_W_pt_mu",60,0,mt_h_bin);
	TH1F   *wjets_lep_pt_mu = new     TH1F("wjets_lep_pt_mu_","wjets_Lep_pt_mu",60,0,mt_h_bin);

////ELECTRONS////
	TH1F *mt2_h_data_el = new TH1F("mt2_data_el_","MT2_data_el",mt2_n_bin,0,mt2_h_bin);
	TH1F  *mt_h_data_el = new  TH1F("mt_data_el_", "MT_data_el",mt_n_bin,0,mt_h_bin);
	TH1F   *met_data_el = new TH1F("met_data_el_","met_data_el",met_n_bin,0,met_h_bin);
	TH1F   *jets_data_el= new TH1F("jets_data_el_","Jets_data_el",jet_n_bin,0,jet_h_bin);
	TH1F   *data_w_pt_el = new     TH1F("data_w_pt_el_","data_W_pt_el",60,0,mt_h_bin);
	TH1F   *data_lep_pt_el = new     TH1F("data_lep_pt_el_","data_Lep_pt_el",60,0,mt_h_bin);

	TH1F *mt2_h_ttbar_el = new TH1F("mt2_ttbar_el_","MT2_ttbar_el",mt2_n_bin,0,mt2_h_bin);
	TH1F  *mt_h_ttbar_el = new  TH1F("mt_ttbar_el_", "MT_ttbar_el",mt_n_bin,0,mt_h_bin);
	TH1F   *met_ttbar_el = new TH1F("met_ttbar_el_","met_ttbar_el",met_n_bin,0,met_h_bin);
	TH1F   *jets_ttbar_el  = new TH1F("jets_ttbar_el_","Jets_ttbar_el",jet_n_bin,0,jet_h_bin);
	TH1F   *ttbar_w_pt_el = new     TH1F("ttbar_w_pt_el_","ttbar_W_pt_el",60,0,mt_h_bin);
	TH1F   *ttbar_lep_pt_el = new     TH1F("ttbar_lep_pt_el_","ttbar_Lep_pt_el",60,0,mt_h_bin);

	TH1F *mt2_h_wjets_el = new TH1F("mt2_wjets_el_","MT2_wjets_el",mt2_n_bin,0,mt2_h_bin);
	TH1F  *mt_h_wjets_el = new  TH1F("mt_wjets_el_", "MT_wjets_el",mt_n_bin,0,mt_h_bin);
	TH1F   *met_wjets_el = new TH1F("met_wjets_el_","met_wjets_el",met_n_bin,0,met_h_bin);
	TH1F   *jets_wjets_el  = new TH1F("jets_wjets_el_","Jets_wjets_el",jet_n_bin,0,jet_h_bin);
	TH1F   *wjets_w_pt_el = new     TH1F("wjets_w_pt_el_","wjets_W_pt_el",60,0,mt_h_bin);
	TH1F   *wjets_lep_pt_el = new     TH1F("wjets_lep_pt_el_","wjets_Lep_pt_el",60,0,mt_h_bin);
/*
  TFile* f1 = new TFile("/home/users/sanil/single/may15hists/data_w_pt.root");
  TH1F* wp_dist   = (TH1F*) f1->Get("w_pt_"); // 
  f1->Close();
	TH1F *mt2_h_wwjets = new TH1F("mt2_wwjets_","MT2_wwjets",mt2_n_bin,0,mt2_h_bin);
	TH1F  *mt_h_wwjets = new  TH1F("mt_wwjets_", "MT_wwjets",mt_n_bin,0,mt_h_bin);
	TH1F   *met_wwjets = new TH1F("met_wwjets_","met_wwjets",met_n_bin,0,met_h_bin);
	TH1F   *jets_wwjets = new TH1F("jets_wwjets_","Jets_wwjets",jet_n_bin,0,jet_h_bin);

	TH1F *mt2_h_ttwjets = new TH1F("mt2_ttwjets_","MT2_ttwjets",mt2_n_bin,0,mt2_h_bin);
	TH1F  *mt_h_ttwjets = new  TH1F("mt_ttwjets_", "MT_ttwjets",mt_n_bin,0,mt_h_bin);
	TH1F   *met_ttwjets = new TH1F("met_ttwjets_","met_ttwjets",met_n_bin,0,met_h_bin);

	TH1F *mt2_h_ttzjets = new TH1F("mt2_ttzjets_","MT2_ttzjets",mt2_n_bin,0,mt2_h_bin);
	TH1F  *mt_h_ttzjets = new  TH1F("mt_ttzjets_", "MT_ttzjets",mt_n_bin,0,mt_h_bin);
	TH1F   *met_ttzjets = new TH1F("met_ttzjets_","met_ttzjets",met_n_bin,0,met_h_bin);

	TH1F *mt2_h_dy = new TH1F("mt2_dy_","MT2_dy",mt2_n_bin,0,mt2_h_bin);
	TH1F  *mt_h_dy = new  TH1F("mt_dy_", "MT_dy",mt_n_bin,0,mt_h_bin);
	TH1F   *met_dy = new TH1F("met_dy_","met_dy",met_n_bin,0,met_h_bin);
*/


////////////// RANDOM NUMBERS GET W momentum


TRandom1  d;  
TRandom3 rx;
TRandom3 ry;

//mt2_h_data->Sumw2();
//mt_h_data ->Sumw2();
//met_data  ->Sumw2();

/////////////////////////////////////////////////////////////////////////////////////////////
  // Loop over events to Analyze
  unsigned int nEventsTotal = 0;
  unsigned int nEventsChain = chain->GetEntries();
  if( nEvents >= 0 ) nEventsChain = nEvents;
  TObjArray *listOfFiles = chain->GetListOfFiles();
  TIter fileIter(listOfFiles);
  TFile *currentFile = 0;
typedef ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > LorentzVec;
//GLOBAL COUNTERS//
int file_count = 1;

  // File Loop
  while ( (currentFile = (TFile*)fileIter.Next()) ) {

float mt2_0_counter = 0, //0 bin counter
     mt2_10_counter = 0, //0-10 geV counter
     mt2_20_counter = 0, //10-20 geV counter etc.
     mt2_30_counter = 0,
     mt2_40_counter = 0,
     mt2_50_counter = 0,
     mt2_60_counter = 0,
     mt2_70_counter = 0,
     mt2_80_counter = 0,
     mt2_90_counter = 0,
    mt2_100_counter = 0,
    mt2_110_counter = 0,
    mt2_120_counter = 0,
    mt2_130_counter = 0,
    mt2_140_counter = 0,
    mt2_150_counter = 0,
    mt2_160_counter = 0,
    mt2_170_counter = 0,
    mt2_180_counter = 0,
    mt2_190_counter = 0,
    mt2_200_counter = 0,
    mt2_G200_counter = 0,
    totalEvents = 0;

    // Get File Content
    TFile *file = new TFile( currentFile->GetTitle() );
    TTree *tree = (TTree*)file->Get("tree");
    if(fast) TTreeCache::SetLearnEntries(10);
    if(fast) tree->SetCacheSize(128*1024*1024);
    single.Init(tree);
    
    // Loop over Events in current file
    if( nEventsTotal >= nEventsChain ) continue;
    unsigned int nEventsTree = tree->GetEntriesFast();
    for( unsigned int event = 0; event < nEventsTree; ++event) {

	float lepton_weight = 0;
	
    
      // Get Event Content
      if( nEventsTotal >= nEventsChain ) continue;
      if(fast) tree->LoadTree(event);
      single.GetEntry(event);
      ++nEventsTotal;
    
      // Progress
      SL::progress( nEventsTotal, nEventsChain );

      // Analysis Code
//event based variables
	//COUNTERS
	int el_count = 0, mu_count = 0, nJets = 0, nBtags = 0, good_index = -1, mu_index = -1, el_index = -1;

      float metx = met() * cos( metPhi() );
      float mety = met() * sin( metPhi() );

///metPhi correction//

      float cmetx = met() * cos( metPhi() );
      float cmety = met() * sin( metPhi() );
      float shiftx = 0.;
      float shifty = 0.;

      shiftx = (! isRealData()) ? (0.1166 + 0.0200*nvtxs()) : (0.2661 + 0.3217*nvtxs());
      shifty = (! isRealData()) ? (0.2764 - 0.1280*nvtxs()) : (-0.2251 - 0.1747*nvtxs());

      cmetx -= shiftx;
      cmety -= shifty;

	//problem with this metPhi modulation correction right now
	//keep using cmet, too lazy to change all the variables
	float cmet = met();
     	float cmetphi = metPhi();
	 //float cmetphi = atan2( mety , metx );
      //float cmet = sqrt( cmetx*cmetx + cmety*cmety ); // cmet == corrected met
LorentzVector met_vec;
met_vec.SetPxPyPzE(metx,mety,0,0);

float lepy = lr_p4().py();
float lepx = lr_p4().px();

float w_x = sqrt ( metx*metx + lepx*lepx );
float w_y = sqrt ( mety*mety + lepy*lepy );

float w_pt_ = sqrt (w_x*w_x + w_y*w_y); 


//jet looper
      for (unsigned int k = 0; k < jets_p4().size(); k++){
        if (jets_p4().at(k).pt()*jets_p4Correction().at(k) < 30) continue;
        if (fabs(jets_p4().at(k).eta()) > 2.5) continue;
        if (ROOT::Math::VectorUtil::DeltaR(jets_p4().at(k), lr_p4()) < 0.4) continue;
        nJets++;
        if (btagDiscriminant().at(k) < 0.244) continue;
        nBtags++;
      }

       //metPhi Correction//
//////////// SELECTION ///////
//Event Requirements
//muon eta > 2.1
//electron eta > 2.4
if(lr_p4().pt() < 30) continue;
if(nJets < 2) continue;
if(nBtags != 0) continue;
if(cmet < 40 ) continue;
//Event Requirements

//TRIGGER WEIGH//
if(abs(lr_id()) == 13){
lepton_weight = electronTriggerWeight(lr_p4().pt(),lr_p4().eta());
}
else if(abs(lr_id()) == 11){ 
lepton_weight = muonTriggerWeight(lr_p4().pt(),lr_p4().eta());
}

//float w_pt_ = (lr_p4() + met_vec).pt();

//met FILL
if(file_count == 1){
met_data->Fill(cmet);
	if (abs(lr_id()) == 13){
met_data_mu->Fill(cmet);
	}
	if (abs(lr_id()) == 11){
met_data_el->Fill(cmet);
	}
}

else if(file_count == 2){
met_ttbar->Fill(cmet,scale_1fb()*lepton_weight*5.2);
	if (abs(lr_id()) == 13){
met_ttbar_mu->Fill(cmet,scale_1fb()*lepton_weight*5.2);
	}
	if (abs(lr_id()) == 11){
met_ttbar_el->Fill(cmet,scale_1fb()*lepton_weight*5.2);
	}
}

else if(file_count == 3){
met_wjets->Fill(cmet,scale_1fb()*lepton_weight*5.2);
	if (abs(lr_id()) == 13){
met_wjets_mu->Fill(cmet,scale_1fb()*lepton_weight*5.2);
	}
	if (abs(lr_id()) == 11){
met_wjets_el->Fill(cmet,scale_1fb()*lepton_weight*5.2);
	}
}
/*
		\\\~*~*~*~\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\|||||/////////////////////////////////////~*~*~*~///
		///~*~*~*~///////////////////////////////////////|||||\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\~*~*~*~\\\
*/
/////////////    ADD FAKE    ////////////
//W FAKE
//W vector variables
float xw = 0, yw = 0, phiw = 0 , thetaw = 0;
float w_p = -1, w_px = -1, w_py = -1, w_pz = -1;
float b[2];

//lepton vector variables
float xc = 0 , yc = 0, zc = 0;
float r = 40, x = 0, y = 0, phi =0 , theta = 0;
float a[2];
float gammaM;
	//random w momentum from the histogram
	//w_p = d.Landau(95.0291,10.3062);
float rand_pt = d.Landau(40.5,17);

	w_p = rand_pt;

	ry.RndmArray(2,b);
	xw = b[0];
	yw = b[1];

//angles for W vector intial direction
	thetaw = acos(2*xw-1);	   
 	phiw = 2*3.14156265359*(yw-0.5);       

//Change of coordinate to XYZ and scale by magnitude of p
      w_px = w_p* sin(thetaw)* cos(phiw); 
      w_py = w_p* sin(thetaw)* sin(phiw);
      w_pz = w_p* cos(thetaw);
//LEPTON
//Create Lepton fake
	LorentzVector fake_lep, fake_met;
//use TLorentVector to boost
	TLorentzVector lep_boost, met_boost;

//do while eta > 2.4 for the lepton
	do{
//random numbers x,y
//rx TRandom class
	rx.RndmArray(2,a);
	x = a[0];
	y = a[1];

//calculate phi and theta
	phi = (x-0.5)*2*3.14156265359;
	theta = acos(2*y - 1);

//calculate cartesian coordinates of the momentum
	 xc = r*sin(theta)*cos(phi);
	 yc = r*sin(theta)*sin(phi);
	 zc = r*cos(theta);

//lepton momentum and met momentum should be oppositely signed
	lep_boost.SetPxPyPzE(xc,yc,zc,40); 
	met_boost.SetPxPyPzE(-xc,-yc,-zc,40);

//BOOST
//gammaM is gamma * mass, reduces to sqrt(momentum^2 + mass^2)
	float gammaM_ = sqrt(w_p*w_p + 80.2*80.2);
	gammaM = gammaM_;

//Boost lepton
	lep_boost.Boost(w_px / (gammaM), w_py / (gammaM), w_pz / (gammaM) );

		} while  (lep_boost.Eta() > 2.4 ); //make sure lepton is within the eta requirement

//boost the neutrino
	met_boost.Boost(w_px / (gammaM), w_py / (gammaM), w_pz / (gammaM) );

//switch from boost-able TLorentzVector into LorentzVector, 
//some things work different in TLorentzVector
	fake_lep.SetPxPyPzE(lep_boost.Px(),lep_boost.Py(),lep_boost.Pz(),0);
	fake_met.SetPxPyPzE(met_boost.Px(),met_boost.Py(),met_boost.Pz(),0);

//now vector addition using fake_metPhi, metPhi, met, and 40(momentum of the new neutrino)
	float met_x = cos(cmetphi)*cmet;
	float met_y = sin(cmetphi)*cmet;

//real met vector
	LorentzVector real_met;
	real_met.SetPxPyPzE(met_x,met_y,0,0); 

//new met vector
	LorentzVector new_met;
	new_met = real_met + fake_met;
///////////////  END FAKE   ////////////////////////////////////
float fake_W_pt = (fake_lep+fake_met).pt();
if(file_count == 1) fake_wpt_h->Fill(fake_W_pt);
/*
		\\\~*~*~*~\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\|||||/////////////////////////////////////~*~*~*~///
		///~*~*~*~///////////////////////////////////////|||||\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\~*~*~*~\\\
*/

////////  MT //////
float dphi = lr_p4().Phi() - cmetphi;
if(dphi > 3.1415) dphi = 6.28 - dphi;
float MT = sqrt(2 * lr_p4().pt() * cmet *(1 - cos(dphi))); 
////////  MT //////

double mt2_event = MT2(new_met.Pt(),new_met.Phi(), lr_p4(), fake_lep);
////////  MT2 //////
if(file_count == 1){
if(mt2_event == 0)				  mt2_0_counter+=1;
else if(0 < mt2_event && mt2_event <= 10)	 mt2_10_counter+=1; 
else if(10 < mt2_event && mt2_event <= 20)	 mt2_20_counter+=1; 
else if(20 < mt2_event && mt2_event <= 30)	 mt2_30_counter+=1;
else if(30 < mt2_event && mt2_event <= 40)	 mt2_40_counter+=1; 
else if(40 < mt2_event && mt2_event <= 50)	 mt2_50_counter+=1;
else if(50 < mt2_event && mt2_event <= 60)	 mt2_60_counter+=1;
else if(60 < mt2_event && mt2_event <= 70)	 mt2_70_counter+=1;
else if(70 < mt2_event && mt2_event <= 80)	 mt2_80_counter+=1;
else if(80 < mt2_event && mt2_event <= 90)	 mt2_90_counter+=1;
else if(90 < mt2_event && mt2_event <= 100)	mt2_100_counter+=1;
else if(100 < mt2_event && mt2_event <= 110)	mt2_110_counter+=1;
else if(110 < mt2_event && mt2_event <= 120)	mt2_120_counter+=1;
else if(120 < mt2_event && mt2_event <= 130)	mt2_130_counter+=1;
else if(130 < mt2_event && mt2_event <= 140)	mt2_140_counter+=1;
else if(140 < mt2_event && mt2_event <= 150)	mt2_150_counter+=1;
else if(150 < mt2_event && mt2_event <= 160)	mt2_160_counter+=1;
else if(160 < mt2_event && mt2_event <= 170)	mt2_170_counter+=1;
else if(170 < mt2_event && mt2_event <= 180)	mt2_180_counter+=1;
else if(180 < mt2_event && mt2_event <= 190)	mt2_190_counter+=1;
else if(190 < mt2_event && mt2_event <= 200)	mt2_200_counter+=1;
else if( mt2_event > 200)		       mt2_G200_counter+=1;
	} //data

if(file_count == 2 || file_count == 3){
if(mt2_event == 0)			   	  mt2_0_counter += 1*lepton_weight;
else if(0 < mt2_event && mt2_event <= 10)	 mt2_10_counter += 1*lepton_weight; 
else if(10 < mt2_event && mt2_event <= 20)	 mt2_20_counter += 1*lepton_weight; 
else if(20 < mt2_event && mt2_event <= 30)	 mt2_30_counter += 1*lepton_weight;
else if(30 < mt2_event && mt2_event <= 40)	 mt2_40_counter += 1*lepton_weight; 
else if(40 < mt2_event && mt2_event <= 50)	 mt2_50_counter += 1*lepton_weight;
else if(50 < mt2_event && mt2_event <= 60)	 mt2_60_counter += 1*lepton_weight;
else if(60 < mt2_event && mt2_event <= 70)	 mt2_70_counter += 1*lepton_weight;
else if(70 < mt2_event && mt2_event <= 80)	 mt2_80_counter += 1*lepton_weight;
else if(80 < mt2_event && mt2_event <= 90)	 mt2_90_counter += 1*lepton_weight;
else if(90 < mt2_event && mt2_event <= 100)	mt2_100_counter += 1*lepton_weight;
else if(100 < mt2_event && mt2_event <= 110)	mt2_110_counter += 1*lepton_weight;
else if(110 < mt2_event && mt2_event <= 120)	mt2_120_counter += 1*lepton_weight;
else if(120 < mt2_event && mt2_event <= 130)	mt2_130_counter += 1*lepton_weight;
else if(130 < mt2_event && mt2_event <= 140)	mt2_140_counter += 1*lepton_weight;
else if(140 < mt2_event && mt2_event <= 150)	mt2_150_counter += 1*lepton_weight;
else if(150 < mt2_event && mt2_event <= 160)	mt2_160_counter += 1*lepton_weight;
else if(160 < mt2_event && mt2_event <= 170)	mt2_170_counter += 1*lepton_weight;
else if(170 < mt2_event && mt2_event <= 180)	mt2_180_counter += 1*lepton_weight;
else if(180 < mt2_event && mt2_event <= 190)	mt2_190_counter += 1*lepton_weight;
else if(190 < mt2_event && mt2_event <= 200)	mt2_200_counter += 1*lepton_weight;
else if( mt2_event > 200)		       mt2_G200_counter += 1*lepton_weight;
	} //MC 
////////  MT2 //////
float lep_pt = lr_p4().pt();

////////  FILL //////
// JETS, MT, MT2, W_pT
//DATA
if(file_count == 1){
totalEvents+=1;
	data_w_pt->Fill(w_pt_);
	data_lep_pt->Fill(lep_pt);
	jets_data->Fill(nJets);
	mt2_h_data->Fill(mt2_event);
	mt_h_data->Fill(MT);
if (abs(lr_id()) == 13){
	data_lep_pt_mu->Fill(lep_pt);
	mt2_h_data_mu->Fill(mt2_event);
	mt_h_data_mu->Fill(MT);
	jets_data_mu->Fill(nJets);
	}
if (abs(lr_id()) == 11){
	data_lep_pt_el->Fill(lep_pt);
	mt2_h_data_el->Fill(mt2_event);
	mt_h_data_el->Fill(MT);
	jets_data_el->Fill(nJets);
	}
}
//TTBAR
else if(file_count == 2){
totalEvents+=1*lepton_weight*scale_1fb()*5.2;
	ttbar_w_pt->Fill(w_pt_,scale_1fb()*lepton_weight*5.2);
	ttbar_lep_pt->Fill(lep_pt,scale_1fb()*lepton_weight*5.2);
	mt2_h_ttbar->Fill(mt2_event,scale_1fb()*lepton_weight*5.2);
	mt_h_ttbar->Fill(MT,scale_1fb()*lepton_weight*5.2);
	jets_ttbar->Fill(nJets,scale_1fb()*lepton_weight*5.2);
if (abs(lr_id()) == 13){
	ttbar_lep_pt_mu->Fill(lep_pt,scale_1fb()*lepton_weight*5.2);
	mt2_h_ttbar_mu->Fill(mt2_event,scale_1fb()*lepton_weight*5.2);
	mt_h_ttbar_mu->Fill(MT,scale_1fb()*lepton_weight*5.2);
	jets_ttbar_mu->Fill(nJets,scale_1fb()*lepton_weight*5.2);
	}
if (abs(lr_id()) == 11){
	ttbar_lep_pt_el->Fill(lep_pt,scale_1fb()*lepton_weight*5.2);
	mt2_h_ttbar_el->Fill(mt2_event,scale_1fb()*lepton_weight*5.2);
	mt_h_ttbar_el->Fill(MT,scale_1fb()*lepton_weight*5.2);
	jets_ttbar_el->Fill(nJets,scale_1fb()*lepton_weight*5.2);
	}
}
//WJETS
else if(file_count == 3){
totalEvents+=1*lepton_weight*scale_1fb()*5.2;
	wjets_w_pt ->Fill(w_pt_,scale_1fb()*lepton_weight*5.2);	
	wjets_lep_pt ->Fill(lep_pt,scale_1fb()*lepton_weight*5.2);	
	mt2_h_wjets->Fill(mt2_event,scale_1fb()*lepton_weight*5.2);
	mt_h_wjets ->Fill(MT,scale_1fb()*lepton_weight*5.2);
	jets_wjets ->Fill(nJets,scale_1fb()*lepton_weight*5.2);
if (abs(lr_id()) == 13){
	wjets_lep_pt_mu->Fill(lep_pt,scale_1fb()*lepton_weight*5.2);
	mt2_h_wjets_mu->Fill(mt2_event,scale_1fb()*lepton_weight*5.2);
	mt_h_wjets_mu->Fill(MT,scale_1fb()*lepton_weight*5.2);
	jets_wjets_mu->Fill(nJets,scale_1fb()*lepton_weight*5.2);
	}
if (abs(lr_id()) == 11){
	wjets_lep_pt_el->Fill(lep_pt,scale_1fb()*lepton_weight*5.2);
	mt2_h_wjets_el->Fill(mt2_event,scale_1fb()*lepton_weight*5.2);
	mt_h_wjets_el->Fill(MT,scale_1fb()*lepton_weight*5.2);
	jets_wjets_el->Fill(nJets,scale_1fb()*lepton_weight*5.2);
	}
}
	/////FILL END //////
	}//event 
///////////////// write histograms ////////////
char* date = "may30";
if(file_count == 1){
     TFile* fout = new TFile(Form("/home/users/sanil/single/%shists/data_sl5_bv_lep30.root",date),"RECREATE");
	mt2_h_data->Write();
	mt_h_data->Write();
	met_data->Write();
	jets_data->Write();
	data_w_pt->Write();
	data_lep_pt->Write();

	data_lep_pt_mu->Write();
	mt2_h_data_mu->Write();
	mt_h_data_mu->Write();
	met_data_mu->Write();
	data_w_pt_mu->Write();
	jets_data_mu->Write();

	data_lep_pt_el->Write();
	mt2_h_data_el->Write();
	mt_h_data_el->Write();
	met_data_el->Write();
	data_w_pt_el->Write();
	jets_data_el->Write();

	//cout << "DATA mt2 tail:    " << mt2tailCounter << endl;
	cout << endl;
	cout << "DATA totalEvents:    " << totalEvents << endl;
	cout << endl;
  fout->Close();
}
else if(file_count == 2){
    TFile* fout = new TFile(Form("/home/users/sanil/single/%shists/ttbar_sl5_bv_lep30.root",date),"RECREATE");
	mt2_h_ttbar->Write();
	mt_h_ttbar->Write();
	met_ttbar->Write();
	jets_ttbar->Write();
	ttbar_w_pt->Write();
	ttbar_lep_pt->Write();


	ttbar_lep_pt_mu->Write();
	mt2_h_ttbar_mu->Write();
	mt_h_ttbar_mu->Write();
	met_ttbar_mu->Write();
	ttbar_w_pt_mu->Write();
	jets_ttbar_mu->Write();

	ttbar_lep_pt_el->Write();
	mt2_h_ttbar_el->Write();
	mt_h_ttbar_el->Write();
	met_ttbar_el->Write();
	ttbar_w_pt_el->Write();
	jets_ttbar_el->Write();
	//cout << "ttbar mt2 tail: " << mt2tailCounter*scale_1fb()*lepton_weight*5.2 << endl;
	cout << endl;
	cout << "ttbar totalEvents:    " << totalEvents << endl;
	cout << endl;
  fout->Close();
}
else if(file_count == 3){
	//TCanvas *c75 = new TCanvas("c75","c75");
    TFile* fout = new TFile(Form("/home/users/sanil/single/%shists/wjets_sl5_bv_lep30.root",date),"RECREATE");
	mt2_h_wjets->Write();
	mt_h_wjets->Write();
	met_wjets->Write();
	jets_wjets->Write();
	wjets_w_pt->Write();
	wjets_lep_pt->Write();

	wjets_lep_pt_mu->Write();
	mt2_h_wjets_mu->Write();
	mt_h_wjets_mu->Write();
	met_wjets_mu->Write();
	wjets_w_pt_mu->Write();
	jets_wjets_mu->Write();

	wjets_lep_pt_el->Write();
	mt2_h_wjets_el->Write();
	mt_h_wjets_el->Write();
	met_wjets_el->Write();
	wjets_w_pt_el->Write();
	jets_wjets_el->Write();
	//cout << "wjets mt2 tail: " << mt2tailCounter*scale_1fb()*lepton_weight*5.2 << endl;
	cout << endl;
	cout << "wjets totalEvents:    " << totalEvents << endl;
	cout << endl;
  fout->Close();
}
///////////////// write histograms END ////////////
		// +++++++++ //

       	//MT2 count writing//

	///txt output///
if(file_count == 1){
ofstream file_d(Form("/home/users/sanil/single/%shists/lep30data_mt2_bin.txt",date));
	if(!file_d.is_open()){return 0;}
	if( file_d.is_open()){
file_d << "total DATA events: " << totalEvents << endl; 
file_d << "starts with 0 < MT2 <= 10, and goes on increments of 10 geV; " << endl;
file_d << mt2_0_counter   << endl;
file_d << mt2_10_counter  << endl;
file_d << mt2_20_counter  << endl;
file_d << mt2_30_counter  << endl;
file_d << mt2_40_counter  << endl;
file_d << mt2_50_counter  << endl;
file_d << mt2_60_counter  << endl;
file_d << mt2_70_counter  << endl;
file_d << mt2_80_counter  << endl;
file_d << mt2_90_counter  << endl;
file_d << mt2_100_counter << endl;
file_d << mt2_110_counter << endl;
file_d << mt2_120_counter << endl;
file_d << mt2_130_counter << endl;
file_d << mt2_140_counter << endl;
file_d << mt2_150_counter << endl;
file_d << mt2_160_counter << endl;
file_d << mt2_170_counter << endl;
file_d << mt2_180_counter << endl;
file_d << mt2_190_counter << endl;
file_d << mt2_200_counter << endl;
file_d << mt2_G200_counter << endl;
file_d << "^^^ MT2 > 200: " << endl;
	}
}
else if (file_count == 3){
ofstream file_w(Form("/home/users/sanil/single/%shists/lep30wjets_mt2_bin.txt",date));
	if(!file_w.is_open()){return 0;}
	if( file_w.is_open()){
file_w << "total W+Jets events: " << totalEvents << endl; 
file_w << "starts with 0 < MT2 <= 10, and goes on increments of 10 geV; " << endl;
file_w << mt2_0_counter   *scale_1fb()*5.2 << endl;
file_w << mt2_10_counter  *scale_1fb()*5.2 << endl;
file_w << mt2_20_counter  *scale_1fb()*5.2 << endl;
file_w << mt2_30_counter  *scale_1fb()*5.2 << endl;
file_w << mt2_40_counter  *scale_1fb()*5.2 << endl;
file_w << mt2_50_counter  *scale_1fb()*5.2 << endl;
file_w << mt2_60_counter  *scale_1fb()*5.2 << endl;
file_w << mt2_70_counter  *scale_1fb()*5.2 << endl;
file_w << mt2_80_counter  *scale_1fb()*5.2 << endl;
file_w << mt2_90_counter  *scale_1fb()*5.2 << endl;
file_w << mt2_100_counter *scale_1fb()*5.2 << endl;
file_w << mt2_110_counter *scale_1fb()*5.2 << endl;
file_w << mt2_120_counter *scale_1fb()*5.2 << endl;
file_w << mt2_130_counter *scale_1fb()*5.2 << endl;
file_w << mt2_140_counter *scale_1fb()*5.2 << endl;
file_w << mt2_150_counter *scale_1fb()*5.2 << endl;
file_w << mt2_160_counter *scale_1fb()*5.2 << endl;
file_w << mt2_170_counter *scale_1fb()*5.2 << endl;
file_w << mt2_180_counter *scale_1fb()*5.2 << endl;
file_w << mt2_190_counter *scale_1fb()*5.2 << endl;
file_w << mt2_200_counter *scale_1fb()*5.2 << endl;
file_w << mt2_G200_counter*scale_1fb()*5.2 << endl;
file_w << "^^^ MT2 > 200 ^^^" << endl;
	}
}
else if (file_count == 2){
ofstream file_t(Form("/home/users/sanil/single/%shists/lep30ttbar_mt2_bin.txt",date));
	if(!file_t.is_open()){return 0;}
	if( file_t.is_open()){
file_d << "total tt~ events: " << totalEvents << endl; 
file_t << "starts with 0 < MT2 <= 10, and goes on increments of 10 geV; " << endl;
file_t << mt2_0_counter  *scale_1fb()*5.2 << endl;
file_t << mt2_10_counter *scale_1fb()*5.2 << endl;
file_t << mt2_20_counter *scale_1fb()*5.2 << endl;
file_t << mt2_30_counter *scale_1fb()*5.2 << endl;
file_t << mt2_40_counter *scale_1fb()*5.2 << endl;
file_t << mt2_50_counter *scale_1fb()*5.2 << endl;
file_t << mt2_60_counter *scale_1fb()*5.2 << endl;
file_t << mt2_70_counter *scale_1fb()*5.2 << endl;
file_t << mt2_80_counter *scale_1fb()*5.2 << endl;
file_t << mt2_90_counter *scale_1fb()*5.2 << endl;
file_t << mt2_100_counter*scale_1fb()*5.2 << endl;
file_t << mt2_110_counter*scale_1fb()*5.2 << endl;
file_t << mt2_120_counter*scale_1fb()*5.2 << endl;
file_t << mt2_130_counter*scale_1fb()*5.2 << endl;
file_t << mt2_140_counter*scale_1fb()*5.2 << endl;
file_t << mt2_150_counter*scale_1fb()*5.2 << endl;
file_t << mt2_160_counter*scale_1fb()*5.2 << endl;
file_t << mt2_170_counter*scale_1fb()*5.2 << endl;
file_t << mt2_180_counter*scale_1fb()*5.2 << endl;
file_t << mt2_190_counter*scale_1fb()*5.2 << endl;
file_t << mt2_200_counter*scale_1fb()*5.2 << endl;
file_t << mt2_G200_counter*scale_1fb()*5.2 << endl;
file_t << "^^^ MT2 > 200 ^^^" << endl;
	}
	///txt output end///
}
       	//MT2 count writing END//

    // Clean Up
    delete tree;
    file->Close();
    delete file;

	file_count++;
  }	//file_loop
fake_wpt_h->Draw();

  if ( nEventsChain != nEventsTotal ) {
    cout << Form( "ERROR: number of events from files (%d) is not equal to total number of events (%d)", nEventsChain, nEventsTotal ) << endl;
  }

  
  // return
  bmark->Stop("benchmark");
  cout << endl;
  cout << nEventsTotal << " Events Processed" << endl;
  cout << "------------------------------" << endl;
  cout << "CPU  Time:	" << Form( "%.01f", bmark->GetCpuTime("benchmark")  ) << endl;
  cout << "Real Time:	" << Form( "%.01f", bmark->GetRealTime("benchmark") ) << endl;
  cout << endl;
  delete bmark;
  return 0;
	}
int ScanChain( TChain* chain) {

  TObjArray *listOfFiles = chain->GetListOfFiles();

  unsigned int nEventsChain=chain->GetEntries();;
  unsigned int nEventsTotal = 0;

  // book histograms
  TDirectory *rootdir = gDirectory->GetDirectory("Rint:");
  rootdir->cd();

  unsigned int nBinsPt 	= 55;
  float lowBinsPt 	= 0.;
  float highBinsPt 	= 110.;

  unsigned int nBinsEta = 52;
  float lowBinsEta      = -2.6;
  float highBinsEta     =  2.6;
  
  TH1F *els_pt_sim 			= book1DHist("els_pt_sim", 
						     "true Electron: p_{T}^{true}",
						     nBinsPt,
						     lowBinsPt,
						     highBinsPt,
						     "p_{T}^{true} [GeV]",
						     "Electrons",2);
  TH1F *els_eta_sim 			= book1DHist("els_eta_sim", 
						     "true Electron: #eta^{true}",
						     nBinsEta,
						     lowBinsEta,
						     highBinsEta,
						     "#eta^{true}",
						     "Electrons",2);
  TH1F *els_pt_recosim 			= book1DHist("els_pt_recosim", 
						     "true Electron: p_{T}^{true}",
						     nBinsPt,
						     lowBinsPt,
						     highBinsPt,
						     "p_{T}^{true} [GeV]",
						     "Electrons",2);
  TH1F *els_eta_recosim 		= book1DHist("els_eta_recosim", 
						     "true Electron: #eta^{true}",
						     nBinsEta,
						     lowBinsEta,
						     highBinsEta,
						     "#eta^{true}",
						     "Electrons",2);
  TH1F *els_pt_reco 			= book1DHist("els_pt_reco", 
						     "reco Electron: p_{T}^{true}",
						     nBinsPt,
						     lowBinsPt,
						     highBinsPt,
						     "p_{T}^{true} [GeV]",
						     "Electrons",2);
  TH1F *els_eta_reco 			= book1DHist("els_eta_reco", 
						     "reco Electron: #eta^{true}",
						     nBinsEta,
						     lowBinsEta,
						     highBinsEta,
						     "#eta^{true}",
						     "Electrons",2);
  TH1F *els_pt_recosim_incorCharge 	= book1DHist("els_pt_recosim_incorCharge", 
						     "true Electron with incorrect reconstructed Charge: p_{T}^{true}",
						     nBinsPt,
						     lowBinsPt,
						     highBinsPt,
						     "p_{T}^{true} [GeV]",
						     "Electrons",2);
  TH1F *els_eta_recosim_incorCharge 	= book1DHist("els_eta_recosim_incorCharge", 
						     "true Electron with incorrect reconstructed Charge: #eta^{true}",
						     nBinsEta,
						     lowBinsEta,
						     highBinsEta,
						     "#eta^{true}",
						     "Electrons",2);
  TH1F *els_pt_recosim_corCharge 	= book1DHist("els_pt_recosim_corCharge", 
						     "true Electron with correct reconstructed Charge: p_{T}^{true}",
						     nBinsPt,
						     lowBinsPt,
						     highBinsPt,
						     "p_{T}^{true} [GeV]",
						     "Electrons",2);
  TH1F *els_eta_recosim_corCharge 	= book1DHist("els_eta_recosim_corCharge", 
						     "true Electron with correct reconstructed Charge: #eta^{true}",
						     nBinsEta,
						     lowBinsEta,
						     highBinsEta,
						     "#eta^{true}",
						     "Electrons",2);
  TH1F *els_pt_reco_corCharge 		= book1DHist("els_pt_reco_corCharge", 
						     "reco Electron with correct reconstructed Charge: p_{T}^{true}",
						     nBinsPt,
						     lowBinsPt,
						     highBinsPt,
						     "p_{T}^{true} [GeV]",
						     "Electrons",2);
  TH1F *els_eta_reco_corCharge 		= book1DHist("els_eta_reco_corCharge", 
						     "reco Electron with correct reconstructed Charge: #eta^{true}",
						     nBinsEta,
						     lowBinsEta,
						     highBinsEta,
						     "#eta^{true}",
						     "Electrons",2);

  TH1F *els_trkId         		= book1DHist("els_trkId", 
						     "Track ID of associated to reco Electron",
						     30,
						     -1050.,
						     450.,
						     "Track ID",
						     "Electrons",2);


  // file loop
  TIter fileIter(listOfFiles);
  TFile *currentFile = 0;
  while ( currentFile = (TFile*)fileIter.Next() ) {
    TFile f(currentFile->GetTitle());
    TTree *tree = (TTree*)f.Get("Events");
    cms2.Init(tree);
    
    //Event Loop
    unsigned int nEvents = tree->GetEntries();
    // nEvents = 100;
    for( unsigned int event = 0; event < nEvents; ++event) {
      cms2.GetEntry(event);
      ++nEventsTotal;
      
      if ( nEventsTotal%10000 == 0 ) {
	std::cout << "Event: " << nEventsTotal << endl;
      }

      // loop over true electrons
      for ( unsigned int els = 0;
	    els < genps_p4().size();
	    ++els ) {

	// check for true electron
	if ( TMath::Abs(genps_id()[els]) != 11 ) continue;

	// check for pT >= 10 GeV
	if ( genps_p4()[els].pt() < 10. ) continue;

	// fill true histrograms
	els_pt_sim->Fill(genps_p4()[els].pt());
	els_eta_sim->Fill(genps_p4()[els].eta());

      }

      // loop over reco electrons
      for (unsigned int els = 0; 
           els < els_p4().size(); 
	   ++els) {

	// cuts

	// check for pT >= 10 GeV
	if ( els_p4()[els].pt() < 10. ) continue;

// 	if ( !goodElectronWithoutIsolation(els) ) continue;
	if ( !goodElectronIsolated(els,true) ) continue;
	if ( conversionElectron(els) ) continue;
	// Yanjun's conversion removal
// 	if ( conversionElectron_PIXHIT(els) ) continue;

	// check how many electrons don't have an associated track
	els_trkId->Fill(els_trkidx().at(els));

	// tmp charge variable
	double charge = els_charge().at(els);

	// if electron has associated track and track charge is not equal to electron charge, veto
 	int trk = els_trkidx().at(els);
	if ( (trk >= 0) && (charge != trks_charge().at(trk)) ) {
	  continue;
	}

	// exclude reco electron which is not a true electron
	if ( abs(els_mc_id()[els]) != 11 ) continue;

	// fill reco
	els_pt_reco->Fill(els_p4().at(els).Pt());
	els_eta_reco->Fill(els_p4().at(els).eta());

	// fill reco_corCharge
	if ( (charge == -1 && els_mc_id().at(els) == 11) || (charge == 1 && els_mc_id().at(els) == -11) ) {
	  els_pt_reco_corCharge->Fill(els_p4().at(els).Pt());
	  els_eta_reco_corCharge->Fill(els_p4().at(els).eta());
	}

	// fill recosim
	els_pt_recosim->Fill(els_mc_p4().at(els).Pt());
	els_eta_recosim->Fill(els_mc_p4().at(els).eta());

	// correct charge identified
	if ( (charge == -1 && els_mc_id().at(els) == 11) || (charge == 1 && els_mc_id().at(els) == -11) ) {

	  els_pt_recosim_corCharge->Fill(els_mc_p4().at(els).Pt());
	  els_eta_recosim_corCharge->Fill(els_mc_p4().at(els).eta());

	  // incorrect charge identified
	} else {

	  els_pt_recosim_incorCharge->Fill(els_mc_p4().at(els).Pt());
	  els_eta_recosim_incorCharge->Fill(els_mc_p4().at(els).eta());
	}

      }
      
    }
    
  }

  if ( nEventsChain != nEventsTotal ) {
    std::cout << "ERROR: number of events from files is not equal to total number of events" << std::endl;
  }

  return 0;
}
Example #21
0
File: scan.C Project: aminnj/WZ
// float scan(unsigned int njetsCut=0, int btagCut=9999, TString tag="", float manualScale=-1.0){
int scan(unsigned int njetsLow=0, unsigned int njetsHigh=9999, int btagCut=9999, int metLow=0, int metHigh=9999, int htLow=0, int htHigh=9999, TString tag=""){
    //njetsLow, njetsHigh, btagCut, metLow, metHigh, htLow, htHigh, tag, manualScale
    //

    // TH1F* h1D_dummy_data = new TH1F("dummy", "dummyhisto", 10, 0, 10); 

    TH1F* h1D_njets_data = new TH1F("njets", "", 15, 0, 15); 
    TH1F* h1D_ht_data = new TH1F("ht", "", 20, 0, 600); 
    TH1F* h1D_met_data = new TH1F("met", "", 20, 0, 300); 
    TH1F* h1D_mt_data = new TH1F("mt", "", 20, 0, 400); 
    TH1F* h1D_mtW_data = new TH1F("mtW", "", 40, 0, 200); 
    TH1F* h1D_zmass_data = new TH1F("zmass", "", 42, 70, 112); 
    TH1F* h1D_lepeta_data = new TH1F("lepeta", "", 50, -3.0, 3.0); 
    TH1F* h1D_leppt_data = new TH1F("leppt", "", 50, 0, 150); 
    TH1F* h1D_Wleppt_data = new TH1F("Wleppt", "", 30, 0, 150); 

    TH1F* h1D_nbtags_data = new TH1F("nbtags", "", 15, 0, 15); 
    TH1F* h1D_btagval_data = new TH1F("btagval", "", 20, 0, 1); 
    TH1F* h1D_ptZ_data = new TH1F("ptZ", "", 25, 0, 400);
    TH1F* h1D_st_data = new TH1F("st", "", 25, 100, 800);
    TH1F* h1D_minRLeadingJet_data = new TH1F("minRLeadingJet", "",10,0,5);
    TH1F* h1D_ptj1_data = new TH1F("ptj1", "", 25, 0, 300);
    TH1F* h1D_ptj2_data = new TH1F("ptj2", "", 25, 0, 300);
    TH1F* h1D_massZj1_data = new TH1F("massZj1", "", 25, 100, 600);
    TH1F* h1D_massZj2_data = new TH1F("massZj2", "", 25, 100, 600);
    TH1F* h1D_ptjj_data = new TH1F("ptjj", "", 25, 0, 400);
    TH1F* h1D_massjj_data = new TH1F("massjj", "", 25, 0, 600);

    TH1F* h1D_mtWeemu_data = new TH1F("mtWeem", "", 40, 0, 200); 
    TH1F* h1D_mtWmumue_data = new TH1F("mtWmme", "", 40, 0, 200); 
    TH1F* h1D_mtWeee_data = new TH1F("mtWeee", "", 40, 0, 200); 
    TH1F* h1D_mtWmumumu_data = new TH1F("mtWmmm", "", 40, 0, 200); 
    TH1F* h1D_lepetae_data = new TH1F("lepetae", "", 50, -3.0, 3.0); 
    TH1F* h1D_lepetamu_data = new TH1F("lepetamu", "", 50, -3.0, 3.0); 

    float luminosity = 19.407;
    float ptCut = 20; // threshold for "high-pT" in AN
    float zmassCut = 15; // line 212 of AN
    float btagDiscriminant = 0.679; // line 230 of AN

    map<int, vector<int> > runLumi;
    cout << ">>> tag is " << tag << endl;
    cout << ">>> excluding events with #btaggedjets>= " << btagCut << endl;
    cout << ">>> considering events with njets in [" << njetsLow << "," << njetsHigh << "]" << endl;
    cout << ">>> considering events with met in [" << metLow << "," << metHigh << "]" << endl;
    cout << ">>> considering events with ht in [" << htLow << "," << htHigh << "]" << endl;
    // cout << ">>> manualScale is " << manualScale << endl;
    // DATADATA
    {
        initCounter();

        clear_seen();

        TChain *ch = new TChain("tree");

        ch->Add("/home/users/namin/sandbox/condorTest/output/baby_2012ABCD.root");

        int nEventsTotal = ch->GetEntries();
        int nEventsSoFar = 0;
        int nGoodEvents = 0;
        float scale = 1.0;

        TFile *currentFile = 0;
        TObjArray *listOfFiles = ch->GetListOfFiles();
        TIter fileIter(listOfFiles);

        // File Loop
        while ( (currentFile = (TFile*)fileIter.Next()) ) { 
            TFile *file = new TFile( currentFile->GetTitle() );
            TTree *tree = (TTree*)file->Get("tree");
            cms2.Init(tree);
            // Set Good Run List
            if(evt_isRealData()) set_goodrun_file("final_19p49fb_cms2.txt");

            TString filename(currentFile->GetTitle());

            // Loop over Events in current file
            unsigned int nEventsTree = tree->GetEntriesFast();
            for( unsigned int event = 0; event < nEventsTree; ++event) {

                // if(event > 30000) break;

                // Get Event Content
                cms2.GetEntry(event);
                nEventsSoFar++;

                // Progress
                CMS2::progress( nEventsSoFar, nEventsTotal );

                // Select Good Runs
                if( evt_isRealData() && !goodrun( evt_run(), evt_lumiBlock() ) ) continue;

                if(evt_isRealData()){
                    DorkyEventIdentifier id = { evt_run(), evt_event(), evt_lumiBlock() };
                    if ( is_duplicate(id) ){
                        continue;
                    }
                }

                std::vector<LorentzVector> goodEls;
                std::vector<LorentzVector> goodMus;
                std::vector<JetStruct> maybeGoodJets;
                std::vector<JetStruct> goodJets;
                std::map<int, int> goodToP4MapEl; // map indices in good{Els,Mus} to {els,mus}_p4 indices
                std::map<int, int> goodToP4MapMu;

                pair<float,float> p = getPhiCorrMET(pfmet_type1cor(), metphi(), evt_nvtxs(), evt_isRealData());
                float met = p.first;
                float metPhi = p.second;
                // float met = pfmet_type1cor();
                // float metPhi = metphi();


                if(met < metLow || met > metHigh) continue;

                // make electron quality cuts
                for(unsigned int iEl = 0; iEl < els_p4().size(); iEl++) {

                    if(!looseEl().at(iEl)) continue;
                    if(els_p4().at(iEl).pt() < ptCut) continue;
                    if(fabs(els_p4().at(iEl).eta()) > 2.4) continue;

                    goodToP4MapEl[goodEls.size()] = iEl;
                    goodEls.push_back(els_p4().at(iEl));


                }
                // mirror for muons
                for(unsigned int iMu = 0; iMu < mus_p4().size(); iMu++) {

                    if(!looseMu().at(iMu)) continue;
                    if(mus_p4().at(iMu).pt() < ptCut) continue;
                    if(fabs(mus_p4().at(iMu).eta()) > 2.4) continue;

                    goodToP4MapMu[goodMus.size()] = iMu;
                    goodMus.push_back(mus_p4().at(iMu));

                }

                // require that we have 3 good leptons
                if(goodMus.size() + goodEls.size() != 3) continue;

                // select good jets
                for (unsigned int iJet = 0; iJet < pfjets_p4().size(); iJet++){
                    if (pfjets_p4().at(iJet).pt()*pfjets_corL1FastL2L3().at(iJet) < 40) continue;
                    if (fabs(pfjets_p4().at(iJet).eta()) > 2.4) continue;
                    if (!passesLoosePFJetID().at(iJet)) continue;

                    JetStruct myJet = {*(new LorentzVector()), 0.0, -1};
                    myJet.jet = pfjets_p4().at(iJet);
                    myJet.pt = pfjets_p4().at(iJet).pt()*pfjets_corL1FastL2L3().at(iJet);
                    myJet.idx = iJet;

                    maybeGoodJets.push_back(myJet);
                }

                vector<int> closestJetsMu; 
                for(unsigned int iMu = 0; iMu < goodMus.size(); iMu++) {
                    double mindR = 999.0;
                    int iClosestJet = -1;
                    for(unsigned int iJet = 0; iJet < maybeGoodJets.size(); iJet++) {
                        double dR = deltaR(goodMus.at(iMu),maybeGoodJets.at(iJet).jet);
                        if( dR < min(mindR, 0.4) ) {
                            mindR = dR;
                            iClosestJet = iJet;
                        }
                    }
                    if(iClosestJet != -1) {
                        closestJetsMu.push_back(iClosestJet);
                    }
                }
                vector<int> closestJetsEl; 
                for(unsigned int iEl = 0; iEl < goodEls.size(); iEl++) {
                    double mindR = 999.0;
                    int iClosestJet = -1;
                    for(unsigned int iJet = 0; iJet < maybeGoodJets.size(); iJet++) {
                        double dR = deltaR(goodEls.at(iEl),maybeGoodJets.at(iJet).jet);
                        if( dR < min(mindR, 0.4) ) {
                            mindR = dR;
                            iClosestJet = iJet;
                        }
                    }
                    if(iClosestJet != -1) {
                        closestJetsEl.push_back(iClosestJet);
                    }
                }
                float ht = 0;
                for(unsigned int iJet = 0; iJet < maybeGoodJets.size(); iJet++) {
                    bool tooClose = false;
                    for(unsigned int iMu = 0; iMu < closestJetsMu.size(); iMu++) {
                        if(iJet == closestJetsMu.at(iMu)) tooClose = true;
                    }
                    for(unsigned int iEl = 0; iEl < closestJetsEl.size(); iEl++) {
                        if(iJet == closestJetsEl.at(iEl)) tooClose = true;
                    }
                    if(tooClose) continue;

                    goodJets.push_back(maybeGoodJets.at(iJet));
                    ht += maybeGoodJets.at(iJet).pt;
                }


                if(ht < htLow || ht > htHigh) continue;



                vector<int> pair = findZPair(goodEls, goodMus);
                vector<LorentzVector> leps;
                float mtW = 0.0, mass = 0.0;
                if( pair[0] != -1 && pair[1] != -1 && pair[2] != -1 && 
                        pair[3] != -1 && pair[4] != -1 ) {
                    if(pair[0] == 0) { // el
                        mass += (goodEls.at(pair[1])+goodEls.at(pair[2])).mass();
                        leps.push_back(goodEls.at(pair[1]));
                        leps.push_back(goodEls.at(pair[2]));
                    } else { // mu
                        mass += (goodMus.at(pair[1])+goodMus.at(pair[2])).mass();
                        leps.push_back(goodMus.at(pair[1]));
                        leps.push_back(goodMus.at(pair[2]));
                    }

                    if(pair[3] == 0) { // W lep is el
                        if( !tightEl().at(goodToP4MapEl[pair[4]]) ) continue;
                        leps.push_back(goodEls.at(pair[4]));

                        mtW = MT(goodEls.at(pair[4]), met, metPhi);

                    } else { // W lep is mu
                        if( !tightMu().at(goodToP4MapMu[pair[4]]) ) continue;
                        leps.push_back(goodMus.at(pair[4]));

                        mtW = MT(goodMus.at(pair[4]), met, metPhi);

                    }
                } else {
                    cout << "shouldn't end up with pair[i] == -1" << endl;
                }


                // XXX
                if(abs(mass - 91.2) > zmassCut) continue;
                if(goodJets.size() < njetsLow ||
                        goodJets.size() > njetsHigh ) continue;


                int nbtags = 0;
                float minRLeadingJet = 9999.0;
                std::sort(goodJets.begin(), goodJets.end(), jetCompare); // sort jets in descending pt
                for(unsigned int iJet = 0; iJet < goodJets.size(); iJet++) {

                    float dR = deltaR(goodJets[iJet].jet, goodJets[0].jet);
                    if(iJet != 0 && dR < minRLeadingJet) minRLeadingJet = dR;

                    // float looseB = 0.244, mediumB = 0.679, tightB = 0.898;
                    float btagval = pfjets_combinedSecondaryVertexBJetTag().at(goodJets[iJet].idx);
                    fill(h1D_btagval_data, btagval, scale);
                    // fill(h1D_btagval_data, btagval, scale);

                    if(btagval > btagDiscriminant) {
                        nbtags++;
                    }
                }

                if(nbtags >= btagCut) continue; // FIXME


                // fill(h1D_dummy_data, 5.0,scale);

                // We are now in the region of interest


                for(unsigned int iMu = 0; iMu < goodMus.size(); iMu++) {
                    fill(h1D_leppt_data,goodMus.at(iMu).pt(), scale);
                    fill(h1D_lepeta_data, goodMus.at(iMu).eta(), scale);
                    fill(h1D_lepetamu_data, goodMus.at(iMu).eta(), scale);
                }
                for(unsigned int iEl = 0; iEl < goodEls.size(); iEl++) {
                    fill(h1D_leppt_data,goodEls.at(iEl).pt(), scale);
                    fill(h1D_lepeta_data, goodEls.at(iEl).eta(), scale);
                    fill(h1D_lepetae_data, goodEls.at(iEl).eta(), scale);
                }




                // FIXME
                if(goodMus.size() == 2 && goodEls.size() == 1) { // mumue
                    mtW = MT(goodEls[0], met, metPhi);
                    fill(h1D_mtWmumue_data, mtW, scale);


                } else if(goodMus.size() == 1 && goodEls.size() == 2) { //eemu
                    mtW = MT(goodMus[0], met, metPhi);
                    fill(h1D_mtWeemu_data, mtW, scale);


                } else { 
                    if(goodMus.size() == 3) { //mumumu
                        fill(h1D_mtWmumumu_data, mtW, scale);
                    } else { // eee
                        fill(h1D_mtWeee_data, mtW, scale);
                    }
                }


                double mt = MT(leps[0]+leps[1]+leps[2], met, metPhi);
                float ptZ = (leps[0]+leps[1]).pt();
                float st = ht + leps[0].pt() + leps[1].pt() + leps[2].pt() + met;

                fill(h1D_ptZ_data, ptZ, scale);
                fill(h1D_Wleppt_data,leps[2].pt(), scale);
                if(minRLeadingJet < 9000) fill(h1D_minRLeadingJet_data, minRLeadingJet, scale);
                fill(h1D_st_data, st, scale);
                fill(h1D_mt_data,mt, scale);
                fill(h1D_mtW_data, mtW, scale);
                fill(h1D_zmass_data,mass, scale); 
                fill(h1D_njets_data,goodJets.size(), scale);
                fill(h1D_ht_data,ht, scale);
                fill(h1D_met_data,met, scale);
                fill(h1D_nbtags_data, nbtags, scale);

                nGoodEvents++;
                addToCounter(filename, scale);

                if(goodJets.size() < 1) continue;

                float ptj1 = goodJets[0].pt;
                float massZj1 = (goodJets[0].jet + leps[0]+leps[1]).mass();

                fill(h1D_ptj1_data, ptj1, scale);
                fill(h1D_massZj1_data, massZj1, scale);

                if(goodJets.size() < 2) continue;

                float ptjj = (goodJets[0].jet + goodJets[1].jet).pt();
                float massjj = (goodJets[0].jet + goodJets[1].jet).mass();
                float ptj2 = goodJets[1].pt;
                float massZj2 = (goodJets[1].jet + leps[0]+leps[1]).mass();

                fill(h1D_ptjj_data, ptjj, scale);
                fill(h1D_massjj_data, massjj, scale);
                fill(h1D_ptj2_data, ptj2, scale);
                fill(h1D_massZj2_data, massZj2, scale);



            }//event loop

        }//file loop


        std::cout << " nGoodEvents: " << nGoodEvents << " nEventsTotal: " << nEventsTotal << std::endl;
        std::cout << "ASDF DATA " << tag << " " << nGoodEvents << std::endl;

        // std::cout << "This dataset (A+B+C+D) has 19.4 fb^-1 of data" << std::endl;
        // std::cout << " nGoodEvents scaled to 1/fb: " << nGoodEvents*(1.0/luminosity) << std::endl;
        // std::cout << " nGoodEvents scaled to 19.4/fb: " << nGoodEvents*(19.4/luminosity) << std::endl;

        printCounter();


    } // DATADATA

    // MCMC
    TChain *ch = new TChain("tree");

    ch->Add("/home/users/namin/sandbox/condorTest/output/baby_WZ.root");
    ch->Add("/home/users/namin/sandbox/condorTest/output/baby_TTZJets.root");
    ch->Add("/home/users/namin/sandbox/condorTest/output/baby_ZZJets.root");
    ch->Add("/home/users/namin/sandbox/condorTest/output/baby_DYJetsToLL.root");
    ch->Add("/home/users/namin/sandbox/condorTest/output/baby_TBZToLL.root");
    ch->Add("/home/users/namin/sandbox/condorTest/output/baby_TTJets.root");
    ch->Add("/home/users/namin/sandbox/condorTest/output/baby_TTW.root");
    ch->Add("/home/users/namin/sandbox/condorTest/output/baby_VVV.root");
    ch->Add("/home/users/namin/sandbox/condorTest/output/baby_WJetsToLNu.root");

    int nEventsTotal = ch->GetEntries();
    int nEventsSoFar = 0;
    int nGoodEvents = 0;
    float nGoodEventsWeighted = 0;

    TFile *currentFile = 0;
    TObjArray *listOfFiles = ch->GetListOfFiles();
    TIter fileIter(listOfFiles);


    // vector<TH1F*> h1D_dummy_vec;

    vector<TH1F*> h1D_njets_vec;
    vector<TH1F*> h1D_ht_vec;
    vector<TH1F*> h1D_met_vec;
    vector<TH1F*> h1D_mt_vec;
    vector<TH1F*> h1D_mtW_vec;
    vector<TH1F*> h1D_zmass_vec;
    vector<TH1F*> h1D_lepeta_vec;
    vector<TH1F*> h1D_leppt_vec;
    vector<TH1F*> h1D_Wleppt_vec;

    // btag+jet stuff
    vector<TH1F*> h1D_nbtags_vec;
    vector<TH1F*> h1D_btagval_vec;
    vector<TH1F*> h1D_ptZ_vec;
    vector<TH1F*> h1D_st_vec;
    vector<TH1F*> h1D_minRLeadingJet_vec;
    vector<TH1F*> h1D_ptj1_vec;
    vector<TH1F*> h1D_ptj2_vec;
    vector<TH1F*> h1D_massZj1_vec;
    vector<TH1F*> h1D_massZj2_vec;
    vector<TH1F*> h1D_ptjj_vec;
    vector<TH1F*> h1D_massjj_vec;

    // w mt debugging
    vector<TH1F*> h1D_mtWeemu_vec;
    vector<TH1F*> h1D_mtWmumue_vec;
    vector<TH1F*> h1D_mtWeee_vec;
    vector<TH1F*> h1D_mtWmumumu_vec;
    vector<TH1F*> h1D_lepetae_vec;
    vector<TH1F*> h1D_lepetamu_vec;

    vector<TH1F*> h1D_test_mete_vec;
    vector<TH1F*> h1D_test_dphie_vec;
    vector<TH1F*> h1D_test_pte_vec;

    vector<TH1F*> h1D_test_metm_vec;
    vector<TH1F*> h1D_test_dphim_vec;
    vector<TH1F*> h1D_test_ptm_vec;

    vector<TH1F*> h1D_test_dphinu_vec;

    vector<TH1F*> h1D_gen_dR_vec;
    vector<TH1F*> h1D_gen_id_vec;

    vector<TH1F*> h1D_metphie_vec;
    vector<TH1F*> h1D_metphim_vec;


    initCounter();
    TH1D* error = new TH1D("error","",1,0,1);
    // error->Sumw2();

    // File Loop
    int iFile = 0;
    while ( (currentFile = (TFile*)fileIter.Next()) ) { 

        // Get File Content
        TFile *file = new TFile( currentFile->GetTitle() );
        TTree *tree = (TTree*)file->Get("tree");
        cms2.Init(tree);

        iFile++; 
        TString filename(currentFile->GetTitle());


        // TH1F* h1D_dummy_file = new TH1F("dummy"+filename, "dummyhisto", 10, 0, 10); 

        TH1F* h1D_njets_file = new TH1F("njets"+filename, "Njets;;Entries", 15, 0, 15); 
        TH1F* h1D_ht_file = new TH1F("ht"+filename, "H_{T};GeV;Entries", 20, 0, 600); 
        TH1F* h1D_met_file = new TH1F("met"+filename, "#slash{E}_{T};GeV;Entries", 20, 0, 300); 
        TH1F* h1D_mt_file = new TH1F("mt"+filename, "M_{T};GeV;Entries", 20, 0, 400); 
        TH1F* h1D_mtW_file = new TH1F("mtW"+filename, "W lep M_{T};GeV;Entries", 40, 0, 200); 
        TH1F* h1D_zmass_file = new TH1F("zmass"+filename, "Z Mass;GeV;Entries", 42, 70, 112); 
        TH1F* h1D_lepeta_file = new TH1F("lepeta"+filename, "lepton #eta;#eta;Entries", 50, -3.0, 3.0); 
        TH1F* h1D_leppt_file = new TH1F("leppt"+filename, "lepton p_{T};p_{T} [GeV];Entries", 50, 0, 150); 
        TH1F* h1D_Wleppt_file = new TH1F("Wleppt"+filename, "W lepton p_{T};p_{T} [GeV];Entries", 30, 0, 150); 

        TH1F* h1D_nbtags_file = new TH1F("nbtags"+filename, "N btagged jets;;Entries", 15, 0, 15); 
        TH1F* h1D_btagval_file = new TH1F("btagval"+filename, "Value of csv bjet tag;;Entries", 20, 0, 1); 
        TH1F* h1D_ptZ_file = new TH1F("ptZ"+filename, "Z p_{T};[GeV];Entries", 25, 0, 400);
        TH1F* h1D_st_file = new TH1F("st"+filename, "S_{T}=H_{T}+#Sigma p_{T,leps}+#slash{E}_{T};S_{T} [GeV];Entries", 25, 100, 800);
        TH1F* h1D_minRLeadingJet_file = new TH1F("minRLeadingJet"+filename, "Minimum dR between jet 1 and another jet",10,0,5);
        TH1F* h1D_ptj1_file = new TH1F("ptj1"+filename, "j1 p_{T};[GeV];Entries", 25, 0, 300);
        TH1F* h1D_ptj2_file = new TH1F("ptj2"+filename, "j2 p_{T};[GeV];Entries", 25, 0, 300);
        TH1F* h1D_massZj1_file = new TH1F("massZj1"+filename, "Zj1 mass;[GeV];Entries", 25, 100, 600);
        TH1F* h1D_massZj2_file = new TH1F("massZj2"+filename, "Zj2 mass;[GeV];Entries", 25, 100, 600);
        TH1F* h1D_ptjj_file = new TH1F("ptjj"+filename, "j1j2 p_{T};[GeV];Entries", 25, 0, 400);
        TH1F* h1D_massjj_file = new TH1F("massjj"+filename, "j1j2 mass;[GeV];Entries", 25, 0, 600);

        TH1F* h1D_mtWeemu_file = new TH1F("mtWeem"+filename, "ee#mu W lep M_{T};GeV;Entries", 40, 0, 200); 
        TH1F* h1D_mtWmumue_file = new TH1F("mtWmme"+filename, "#mu#mue W lep M_{T};GeV;Entries", 40, 0, 200); 
        TH1F* h1D_mtWeee_file = new TH1F("mtWeee"+filename, "eee W lep M_{T};GeV;Entries", 40, 0, 200); 
        TH1F* h1D_mtWmumumu_file = new TH1F("mtWmmm"+filename, "#mu#mu#mu W lep M_{T};GeV;Entries", 40, 0, 200); 
        TH1F* h1D_lepetae_file = new TH1F("lepetae"+filename, "e #eta;#eta;Entries", 50, -3.0, 3.0); 
        TH1F* h1D_lepetamu_file = new TH1F("lepetamu"+filename, "#mu #eta;#eta;Entries", 50, -3.0, 3.0); 

        TH1F* h1D_test_mete_file = new TH1F("testmete"+filename, "met for e;GeV;Entries", 40, 0, 200); 
        TH1F* h1D_test_dphie_file = new TH1F("testphie"+filename, "dphi(met,e);;Entries", 40, 0, M_PI+0.1); 
        TH1F* h1D_test_pte_file = new TH1F("testpte"+filename, "pt for e;GeV;Entries", 40, 0, 200); 

        TH1F* h1D_test_metm_file = new TH1F("testmetm"+filename, "met for mu;GeV;Entries", 40, 0, 200); 
        TH1F* h1D_test_dphim_file = new TH1F("testphim"+filename, "dphi(met,mu);;Entries", 40, 0, M_PI+0.1); 
        TH1F* h1D_test_ptm_file = new TH1F("testptm"+filename, "pt for mu;GeV;Entries", 40, 0, 200); 

        TH1F* h1D_test_dphinu_file = new TH1F("testphinu"+filename, "dphi(W lep,gen nu);;Entries", 40, 0, M_PI+0.1); 

        TH1F* h1D_gen_dR_file = new TH1F("gendr"+filename, "#DeltaR between reco W lepton and closest gen lepton", 60, 0, 0.4); 
        TH1F* h1D_gen_id_file = new TH1F("genid"+filename, "abs(mother id) for gen particle matched to reco W lept;;Entries", 40, 0, 40); 

        TH1F* h1D_metphie_file = new TH1F("metphie"+filename, "metphi for e from W;;Entries", 30, -3.2, 3.2); 
        TH1F* h1D_metphim_file = new TH1F("metphim"+filename, "metphi for m from W;;Entries", 30, -3.2, 3.2); 

        h1D_njets_vec.push_back(h1D_njets_file); 
        h1D_ht_vec.push_back(h1D_ht_file); 
        h1D_met_vec.push_back(h1D_met_file); 
        h1D_mt_vec.push_back(h1D_mt_file); 
        h1D_mtW_vec.push_back(h1D_mtW_file); 
        h1D_zmass_vec.push_back(h1D_zmass_file); 
        h1D_lepeta_vec.push_back(h1D_lepeta_file);
        h1D_leppt_vec.push_back(h1D_leppt_file); 
        h1D_Wleppt_vec.push_back(h1D_Wleppt_file); 

        h1D_nbtags_vec.push_back(h1D_nbtags_file);
        h1D_btagval_vec.push_back(h1D_btagval_file);
        h1D_ptZ_vec.push_back(h1D_ptZ_file);
        h1D_st_vec.push_back(h1D_st_file);
        h1D_minRLeadingJet_vec.push_back(h1D_minRLeadingJet_file);
        h1D_ptj1_vec.push_back(h1D_ptj1_file);
        h1D_ptj2_vec.push_back(h1D_ptj2_file);
        h1D_massZj1_vec.push_back(h1D_massZj1_file);
        h1D_massZj2_vec.push_back(h1D_massZj2_file);
        h1D_ptjj_vec.push_back(h1D_ptjj_file);
        h1D_massjj_vec.push_back(h1D_massjj_file);

        h1D_mtWeemu_vec.push_back(h1D_mtWeemu_file);
        h1D_mtWmumue_vec.push_back(h1D_mtWmumue_file);
        h1D_mtWeee_vec.push_back(h1D_mtWeee_file);
        h1D_mtWmumumu_vec.push_back(h1D_mtWmumumu_file);
        h1D_lepetae_vec.push_back(h1D_lepetae_file);
        h1D_lepetamu_vec.push_back(h1D_lepetamu_file);

        h1D_test_mete_vec.push_back(h1D_test_mete_file);
        h1D_test_dphie_vec.push_back(h1D_test_dphie_file);
        h1D_test_pte_vec.push_back(h1D_test_pte_file);

        h1D_test_metm_vec.push_back(h1D_test_metm_file);
        h1D_test_dphim_vec.push_back(h1D_test_dphim_file);
        h1D_test_ptm_vec.push_back(h1D_test_ptm_file);

        h1D_test_dphinu_vec.push_back(h1D_test_dphinu_file);

        h1D_gen_dR_vec.push_back(h1D_gen_dR_file);
        h1D_gen_id_vec.push_back(h1D_gen_id_file);

        h1D_metphie_vec.push_back(h1D_metphie_file);
        h1D_metphim_vec.push_back(h1D_metphim_file);

        // Loop over Events in current file
        unsigned int nEventsTree = tree->GetEntriesFast();
        for( unsigned int event = 0; event < nEventsTree; ++event) {

            // if(event > 30000) break;

            // Get Event Content
            cms2.GetEntry(event);
            nEventsSoFar++;

            if(event == 0) {
                std::cout << " evt_scale1fb(): " << evt_scale1fb() << " filename: " << filename << std::endl;
            }
            // Progress
            CMS2::progress( nEventsSoFar, nEventsTotal );

            std::vector<LorentzVector> goodEls;
            std::vector<LorentzVector> goodMus;
            std::vector<JetStruct> maybeGoodJets;
            std::vector<JetStruct> goodJets;
            std::map<int, int> goodToP4MapEl; // map indices in good{Els,Mus} to {els,mus}_p4 indices
            std::map<int, int> goodToP4MapMu;

            float scale = evt_scale1fb()  * luminosity;

            pair<float,float> p = getPhiCorrMET(pfmet_type1cor(), metphi(), evt_nvtxs(), evt_isRealData());
            float met = p.first;
            float metPhi = p.second;


            if(met < metLow || met > metHigh) continue;

            // make electron quality cuts
            for(unsigned int iEl = 0; iEl < els_p4().size(); iEl++) {

                if(!looseEl().at(iEl)) continue;
                if(els_p4().at(iEl).pt() < ptCut) continue;
                if(fabs(els_p4().at(iEl).eta()) > 2.4) continue;

                goodToP4MapEl[goodEls.size()] = iEl;
                goodEls.push_back(els_p4().at(iEl));


            }
            // mirror for muons
            for(unsigned int iMu = 0; iMu < mus_p4().size(); iMu++) {

                if(!looseMu().at(iMu)) continue;
                if(mus_p4().at(iMu).pt() < ptCut) continue;
                if(fabs(mus_p4().at(iMu).eta()) > 2.4) continue;

                goodToP4MapMu[goodMus.size()] = iMu;
                goodMus.push_back(mus_p4().at(iMu));

            }

            // require that we have 3 good leptons
            if(goodMus.size() + goodEls.size() != 3) continue;

            // select good jets
            for (unsigned int iJet = 0; iJet < pfjets_p4().size(); iJet++){
                if (pfjets_p4().at(iJet).pt()*pfjets_corL1FastL2L3().at(iJet) < 40) continue;
                if (fabs(pfjets_p4().at(iJet).eta()) > 2.4) continue;
                if (!passesLoosePFJetID().at(iJet)) continue;

                JetStruct myJet = {*(new LorentzVector()), 0.0, -1};
                myJet.jet = pfjets_p4().at(iJet);
                myJet.pt = pfjets_p4().at(iJet).pt()*pfjets_corL1FastL2L3().at(iJet);
                myJet.idx = iJet;

                maybeGoodJets.push_back(myJet);
            }

            vector<int> closestJetsMu; 
            for(unsigned int iMu = 0; iMu < goodMus.size(); iMu++) {
                double mindR = 999.0;
                int iClosestJet = -1;
                for(unsigned int iJet = 0; iJet < maybeGoodJets.size(); iJet++) {
                    double dR = deltaR(goodMus.at(iMu),maybeGoodJets.at(iJet).jet);
                    if( dR < min(mindR, 0.4) ) {
                        mindR = dR;
                        iClosestJet = iJet;
                    }
                }
                if(iClosestJet != -1) {
                    closestJetsMu.push_back(iClosestJet);
                }
            }
            vector<int> closestJetsEl; 
            for(unsigned int iEl = 0; iEl < goodEls.size(); iEl++) {
                double mindR = 999.0;
                int iClosestJet = -1;
                for(unsigned int iJet = 0; iJet < maybeGoodJets.size(); iJet++) {
                    double dR = deltaR(goodEls.at(iEl),maybeGoodJets.at(iJet).jet);
                    if( dR < min(mindR, 0.4) ) {
                        mindR = dR;
                        iClosestJet = iJet;
                    }
                }
                if(iClosestJet != -1) {
                    closestJetsEl.push_back(iClosestJet);
                }
            }
            float ht = 0;
            for(unsigned int iJet = 0; iJet < maybeGoodJets.size(); iJet++) {
                bool tooClose = false;
                for(unsigned int iMu = 0; iMu < closestJetsMu.size(); iMu++) {
                    if(iJet == closestJetsMu.at(iMu)) tooClose = true;
                }
                for(unsigned int iEl = 0; iEl < closestJetsEl.size(); iEl++) {
                    if(iJet == closestJetsEl.at(iEl)) tooClose = true;
                }
                if(tooClose) continue;

                goodJets.push_back(maybeGoodJets.at(iJet));
                ht += maybeGoodJets.at(iJet).pt;
            }


            if(ht < htLow || ht > htHigh) continue;

            vector<int> pair = findZPair(goodEls, goodMus);
            vector<LorentzVector> leps;
            float mtW = 0.0, mass = 0.0;
            if( pair[0] != -1 && pair[1] != -1 && pair[2] != -1 && 
                    pair[3] != -1 && pair[4] != -1 ) {
                if(pair[0] == 0) { // el
                    mass += (goodEls.at(pair[1])+goodEls.at(pair[2])).mass();
                    leps.push_back(goodEls.at(pair[1]));
                    leps.push_back(goodEls.at(pair[2]));
                } else { // mu
                    mass += (goodMus.at(pair[1])+goodMus.at(pair[2])).mass();
                    leps.push_back(goodMus.at(pair[1]));
                    leps.push_back(goodMus.at(pair[2]));
                }

                if(pair[3] == 0) { // W lep is el
                    if( !tightEl().at(goodToP4MapEl[pair[4]]) ) continue;
                    leps.push_back(goodEls.at(pair[4]));

                    mtW = MT(goodEls.at(pair[4]), met, metPhi);

                } else { // W lep is mu
                    if( !tightMu().at(goodToP4MapMu[pair[4]]) ) continue;
                    leps.push_back(goodMus.at(pair[4]));

                    mtW = MT(goodMus.at(pair[4]), met, metPhi);

                }
            } else {
                cout << "shouldn't end up with pair[i] == -1" << endl;
            }


            // XXX
            if(abs(mass - 91.2) > zmassCut) continue;
            if(goodJets.size() < njetsLow ||
                    goodJets.size() > njetsHigh ) continue;


            int nbtags = 0;
            float minRLeadingJet = 9999.0;
            std::sort(goodJets.begin(), goodJets.end(), jetCompare); // sort jets in descending pt
            for(unsigned int iJet = 0; iJet < goodJets.size(); iJet++) {

                float dR = deltaR(goodJets[iJet].jet, goodJets[0].jet);
                if(iJet != 0 && dR < minRLeadingJet) minRLeadingJet = dR;

                // float looseB = 0.244, mediumB = 0.679, tightB = 0.898;
                float btagval = pfjets_combinedSecondaryVertexBJetTag().at(goodJets[iJet].idx);
                fill(h1D_btagval_file, btagval, scale);
                // fill(h1D_btagval_file, btagval, scale);

                if(btagval > btagDiscriminant) {
                    nbtags++;
                }
            }

            if(nbtags >= btagCut) continue; // FIXME


            // We are now in the region of interest

            // try to match W lepton to genps
            float mindR = 9999.0;
            int brotherIdx = -1;
            for(unsigned int iLep = 0; iLep < genps_p4().size(); iLep++) {
                if( abs(genps_id().at(iLep)) != 11 && abs(genps_id().at(iLep)) != 13 ) continue;
                float dR = deltaR(genps_p4().at(iLep), leps[2]);
                if(dR <= mindR) {
                    mindR = dR;
                    brotherIdx = iLep;
                }

                // now try to find matching neutrino (id of same flavor neutrino = 1 + id of lepton)

                for(unsigned int iNu = 0; iNu < genps_p4().size(); iNu++) {
                    if( abs(genps_id().at(iNu)) == abs(genps_id().at(iLep)) + 1) {
                        // fill(h1D_test_dphinu_file, deltaPhi(genps_p4().at(iNu).phi(), genps_p4().at(iLep).phi()), scale);
                        fill(h1D_test_dphinu_file, deltaPhi(genps_p4().at(iNu).phi(), genps_p4().at(iLep).phi()), scale);
                        break;
                    }
                }

            }
            if(brotherIdx >= 0) {
                fill(h1D_gen_dR_file, mindR, scale);
                if(mindR < 0.15) {
                    fill(h1D_gen_id_file, abs(genps_id_mother().at(brotherIdx)), scale);
                }
            } else {
                // cout << "ERROR: " << mindR << " " << brotherIdx << " " << endl;
            }


            for(unsigned int iMu = 0; iMu < goodMus.size(); iMu++) {
                fill(h1D_leppt_file,goodMus.at(iMu).pt(), scale);
                fill(h1D_lepeta_file, goodMus.at(iMu).eta(), scale);
                fill(h1D_lepetamu_file, goodMus.at(iMu).eta(), scale);
            }
            for(unsigned int iEl = 0; iEl < goodEls.size(); iEl++) {
                fill(h1D_leppt_file,goodEls.at(iEl).pt(), scale);
                fill(h1D_lepeta_file, goodEls.at(iEl).eta(), scale);
                fill(h1D_lepetae_file, goodEls.at(iEl).eta(), scale);
            }




            // FIXME
            if(goodMus.size() == 2 && goodEls.size() == 1) { // mumue
                mtW = MT(goodEls[0], met, metPhi);
                fill(h1D_mtWmumue_file, mtW, scale);

                if(true || mtW < 40) { // XXX XXX XXX
                    fill(h1D_test_mete_file, met);
                    float dphi = deltaPhi(metPhi,goodEls.at(0).phi());
                    // cout << "electron " << " metPhi: " << metPhi << " elphi: " << goodEls.at(0).phi() << " dphi: " << dphi << endl;
                    fill(h1D_test_dphie_file, dphi, scale);
                    fill(h1D_test_pte_file, goodEls.at(0).pt(), scale);
                    fill(h1D_metphie_file, metPhi, scale);
                }

            } else if(goodMus.size() == 1 && goodEls.size() == 2) { //eemu
                mtW = MT(goodMus[0], met, metPhi);
                fill(h1D_mtWeemu_file, mtW, scale);

                if(true || mtW < 40) { // XXX XXX XXX
                    fill(h1D_test_metm_file, met);
                    float dphi = deltaPhi(metPhi,goodMus.at(0).phi());
                    // cout << "muon     " << " metPhi: " << metPhi << " muphi: " << goodMus.at(0).phi() << " dphi: " << dphi << endl;
                    fill(h1D_test_dphim_file, dphi, scale);
                    fill(h1D_test_ptm_file, goodMus.at(0).pt(), scale);
                    fill(h1D_metphim_file, metPhi, scale);
                }

            } else { 
                if(goodMus.size() == 3) { //mumumu
                    fill(h1D_mtWmumumu_file, mtW, scale);
                } else { // eee
                    fill(h1D_mtWeee_file, mtW, scale);
                }
            }


            double mt = MT(leps[0]+leps[1]+leps[2], met, metPhi);
            float ptZ = (leps[0]+leps[1]).pt();
            float st = ht + leps[0].pt() + leps[1].pt() + leps[2].pt() + met;

            fill(h1D_ptZ_file, ptZ, scale);
            fill(h1D_Wleppt_file,leps[2].pt(), scale);
            if(minRLeadingJet < 9000) fill(h1D_minRLeadingJet_file, minRLeadingJet, scale);
            fill(h1D_st_file, st, scale);
            fill(h1D_mt_file,mt, scale);
            fill(h1D_mtW_file, mtW, scale);
            fill(h1D_zmass_file,mass, scale); 
            fill(h1D_njets_file,goodJets.size(), scale);
            fill(h1D_ht_file,ht, scale);
            fill(h1D_met_file,met, scale);
            fill(h1D_nbtags_file, nbtags, scale);

            error->Fill(0.5,scale);
            addToCounter(filename, scale);
            nGoodEvents++;
            nGoodEventsWeighted+=scale*1.0;

            if(goodJets.size() < 1) continue;

            float ptj1 = goodJets[0].pt;
            float massZj1 = (goodJets[0].jet + leps[0]+leps[1]).mass();

            fill(h1D_ptj1_file, ptj1, scale);
            fill(h1D_massZj1_file, massZj1, scale);

            if(goodJets.size() < 2) continue;

            float ptjj = (goodJets[0].jet + goodJets[1].jet).pt();
            float massjj = (goodJets[0].jet + goodJets[1].jet).mass();
            float ptj2 = goodJets[1].pt;
            float massZj2 = (goodJets[1].jet + leps[0]+leps[1]).mass();

            fill(h1D_ptjj_file, ptjj, scale);
            fill(h1D_massjj_file, massjj, scale);
            fill(h1D_ptj2_file, ptj2, scale);
            fill(h1D_massZj2_file, massZj2, scale);


        }//event loop

    }//file loop MCMC

    std::cout << " nGoodEvents: " << nGoodEvents << " nEventsTotal: " << nEventsTotal << std::endl;
    std::cout << " nGoodEventsWeighted to 19.4 1/fb: " << error->GetBinContent(1) << std::endl;

    // std::cout << " error->GetBinContent(1): " << error->GetBinContent(1) << " error->GetBinError(1): " << error->GetBinError(1) << std::endl;

    std::cout << "ASDF MC " << tag << " " << error->GetBinContent(1)  << " " << error->GetBinError(1) << std::endl;

    printCounter();

    TString prefix("plots");
    prefix += tag;
    prefix += "/";

    // stringstream ss; ss << njetsCut;
    // std::string common = " --luminosity 19.4 --percentages --scaletodata --label njets#geq"+ss.str();
    // TString common = " --luminosity 19.4 --percentages --scaletodata --label njets#geq" + TString::Itoa(njetsCut,10);
    // TString common = " --luminosity 19.4 --percentages ";
    TString common = " --luminosity 19.4 --percentages --scaletodata";
    // std::string common = " --luminosity 19.4 --percentages --label njets>="+ss.str();

    // drawStacked(h1D_dummy_data, h1D_dummy_vec,prefix+"h1D_dummy.pdf",""+common);

    drawStacked(h1D_njets_data, h1D_njets_vec, prefix+"h1D_njets.pdf", "--centerlabel --printbins"+common);
    drawStacked(h1D_ht_data, h1D_ht_vec,prefix+"h1D_ht.pdf","--logscale --binsize --centerlabel"+common);
    drawStacked(h1D_leppt_data, h1D_leppt_vec,prefix+"h1D_leppt.pdf","--logscale --centerlabel"+common);
    drawStacked(h1D_Wleppt_data, h1D_Wleppt_vec,prefix+"h1D_Wleppt.pdf","--logscale --centerlabel"+common);
    drawStacked(h1D_met_data, h1D_met_vec,prefix+"h1D_met.pdf","--binsize --centerlabel"+common);
    drawStacked(h1D_mt_data, h1D_mt_vec,prefix+"h1D_mt.pdf","--binsize --centerlabel"+common);
    drawStacked(h1D_mtW_data, h1D_mtW_vec,prefix+"h1D_mtW.pdf","--binsize "+common);
    drawStacked(h1D_lepeta_data, h1D_lepeta_vec,prefix+"h1D_lepeta.pdf",""+common);
    drawStacked(h1D_zmass_data, h1D_zmass_vec,prefix+"h1D_zmass.pdf","--binsize --reorderstack"+common);

    drawStacked(h1D_mtWeemu_data, h1D_mtWeemu_vec,prefix+"h1D_mtWeemu.pdf","--binsize "+common);
    drawStacked(h1D_mtWmumue_data, h1D_mtWmumue_vec,prefix+"h1D_mtWmumue.pdf","--binsize "+common);
    drawStacked(h1D_mtWmumumu_data, h1D_mtWmumumu_vec,prefix+"h1D_mtWmumumu.pdf","--binsize "+common);
    drawStacked(h1D_mtWeee_data, h1D_mtWeee_vec,prefix+"h1D_mtWeee.pdf","--binsize "+common);
    drawStacked(h1D_lepetae_data, h1D_lepetae_vec,prefix+"h1D_lepetae.pdf",""+common);
    drawStacked(h1D_lepetamu_data, h1D_lepetamu_vec,prefix+"h1D_lepetamu.pdf",""+common);

    drawStacked(h1D_btagval_data, h1D_btagval_vec, prefix+"h1D_btagval.pdf", "--centerlabel "+common);
    drawStacked(h1D_nbtags_data, h1D_nbtags_vec, prefix+"h1D_nbtags.pdf", "--centerlabel --logscale"+common);

    drawStacked(h1D_ptZ_data, h1D_ptZ_vec, prefix+"h1D_ptZ.pdf","--centerlabel "+common);
    drawStacked(h1D_st_data, h1D_st_vec, prefix+"h1D_st.pdf","--centerlabel "+common);
    drawStacked(h1D_minRLeadingJet_data, h1D_minRLeadingJet_vec, prefix+"h1D_minRLeadingJet.pdf","--centerlabel "+common);
    drawStacked(h1D_ptj1_data, h1D_ptj1_vec, prefix+"h1D_ptj1.pdf","--centerlabel "+common);
    drawStacked(h1D_ptj2_data, h1D_ptj2_vec, prefix+"h1D_ptj2.pdf","--centerlabel "+common);
    drawStacked(h1D_massZj1_data, h1D_massZj1_vec, prefix+"h1D_massZj1.pdf","--centerlabel "+common);
    drawStacked(h1D_massZj2_data, h1D_massZj2_vec, prefix+"h1D_massZj2.pdf","--centerlabel "+common);
    drawStacked(h1D_ptjj_data, h1D_ptjj_vec, prefix+"h1D_ptjj.pdf","--centerlabel "+common);
    drawStacked(h1D_massjj_data, h1D_massjj_vec, prefix+"h1D_massjj.pdf","--centerlabel "+common);

    TH1F* dog = new TH1F("dog","",1,0,1);

    drawStacked(dog, h1D_test_metm_vec,prefix+"h1D_test_metm.pdf",""+common);
    drawStacked(dog, h1D_test_dphim_vec,prefix+"h1D_test_dphim.pdf",""+common);
    drawStacked(dog, h1D_test_ptm_vec,prefix+"h1D_test_ptm.pdf",""+common);

    drawStacked(dog, h1D_test_dphinu_vec,prefix+"h1D_test_dphinu.pdf",""+common);

    drawStacked(dog, h1D_test_mete_vec,prefix+"h1D_test_mete.pdf",""+common);
    drawStacked(dog, h1D_test_dphie_vec,prefix+"h1D_test_dphie.pdf",""+common);
    drawStacked(dog, h1D_test_pte_vec,prefix+"h1D_test_pte.pdf",""+common);

    drawStacked(dog, h1D_gen_dR_vec,prefix+"h1D_gen_dR.pdf","--logscale --centerlabel "+common);
    drawStacked(dog, h1D_gen_id_vec,prefix+"h1D_gen_id.pdf",""+common);

    drawStacked(dog, h1D_metphie_vec,prefix+"h1D_metphie.pdf",""+common);
    drawStacked(dog, h1D_metphim_vec,prefix+"h1D_metphim.pdf",""+common);

    return 0;
}
Example #22
0
void makePhotonBabies::ScanChain (TChain* chain, const char* prefix, bool isData, 
                                  bool calculateTCMET, int nEvents, float kFactor){

  set_goodrun_file( jsonfilename );
  
  if( isData ){
    ofile_tcmet.open(  Form( "photonTemplates/%s/%s_tcmetprintout.txt" , iter , prefix  ) );
    ofile_events.open( Form( "photonTemplates/%s/%s_highmetevents.txt" , iter , prefix  ) );


    ofile_events << "|" << setw(8)  << "run"          << setw(4) 
                 << "|" << setw(6)  << "lumi"         << setw(4) 
                 << "|" << setw(12) << "event"        << setw(4) 
                 << "|" << setw(6)  << "njets"        << setw(4) 
                 << "|" << setw(6)  << "nbtags"       << setw(4) 
                 << "|" << setw(8)  << "tcmet"        << setw(4) 
                 << "|" << setw(8)  << "pfmet"        << setw(4) 
                 << "|" << setw(8)  << "dphi"         << setw(4) << "|" << endl; 
  }

  
  bookHistos();

  int npass = 0;
  
  // make a baby ntuple
  //stringstream babyfilename;
  //babyfilename << prefix << "_baby.root";
  MakeBabyNtuple( Form("photonTemplates/%s/%s_baby.root", iter , prefix ) );

  TObjArray *listOfFiles = chain->GetListOfFiles();

  unsigned int nEventsChain = 0;
  if(nEvents == -1) 
    nEvents = chain->GetEntries();
  nEventsChain = nEvents;
  unsigned int nEventsTotal = 0;
  
  //pass fail counters
  int nSkip_els_conv_dist = 0;
  if(debug) cout << "Begin file loop" << endl;

  // file loop
  TIter fileIter(listOfFiles);
  TFile* currentFile = 0;
  while ((currentFile = (TFile*)fileIter.Next())){
    
    TFile f(currentFile->GetTitle());
    TTree *tree = (TTree*)f.Get("Events");
    cms2.Init(tree);

    // event loop
    unsigned int nEvents = tree->GetEntries();
 
    for (unsigned int event = 0 ; event < nEvents; ++event){
        
      cms2.GetEntry(event);
      ++nEventsTotal;

      // progress feedback to user
      if (nEventsTotal % 1000 == 0){
            
        // xterm magic from L. Vacavant and A. Cerri
        if (isatty(1)){
                
          printf("\015\033[32m ---> \033[1m\033[31m%4.1f%%"
                 "\033[0m\033[32m <---\033[0m\015", (float)nEventsTotal/(nEventsChain*0.01));
          fflush(stdout);
        }
      }
      
      if( isData ) {
	DorkyEventIdentifier id = { evt_run(),evt_event(), evt_lumiBlock() };
	if (is_duplicate(id) )
	  continue;
      }
      /*
      //skip events with bad els_conv_dist 
      bool skipEvent = false;
      for( unsigned int iEl = 0 ; iEl < els_conv_dist().size() ; ++iEl ){
        if( els_conv_dist().at(iEl) != els_conv_dist().at(iEl) ){
          skipEvent = true;
        }
      }
      
      if( skipEvent ){
        cout << "SKIPPING EVENT WITH BAD ELS_CONV_DIST" << endl;       
        nSkip_els_conv_dist++;
        continue;
      }
      */
      
      //good run+event selection-----------------------------------------------------------

      if( isData && !goodrun(cms2.evt_run(), cms2.evt_lumiBlock()) ) continue;
      if( !cleaning_standardAugust2010( isData) )                    continue;

      
      if(debug) cout << "Pass event selection" << endl;

      InitBabyNtuple();

      // event stuff
      strcpy(dataset_, cms2.evt_dataset().Data());
      run_     = cms2.evt_run();
      lumi_    = cms2.evt_lumiBlock();
      event_   = cms2.evt_event();

      weight_ = 1.;
      pthat_  = -1;
      if( !isData ){
        weight_ = cms2.evt_scale1fb() * kFactor * lumi;
        pthat_  = cms2.genps_pthat();
      }

      float maxphotonpt = -1;
     
      //stitching together PhotonJet_Pt15 and PhotonJet_Pt30
      if( strcmp( prefix , "PhotonJet") == 0 ){

        if( TString(currentFile->GetTitle()).Contains("PhotonJet_Pt15") ){
          if( cms2.genps_pthat() > 30. ) continue;
        }
        if( TString(currentFile->GetTitle()).Contains("PhotonJet_Pt30") ){
          if( cms2.genps_pthat() > 80. ) continue;
        }
        if( TString(currentFile->GetTitle()).Contains("PhotonJet_Pt80") ){
          if( cms2.genps_pthat() > 170. ) continue;
        }

        for( unsigned int ig = 0 ; ig < photons_p4().size() ; ++ig ){
          if( photons_p4().at(ig).pt() > maxphotonpt ) 
            maxphotonpt = photons_p4().at(ig).pt();
        }
 
        fillUnderOverFlow( hgenps_pthat  , genps_pthat() , weight_ );
        fillUnderOverFlow( hphotonpt     , maxphotonpt   , weight_ );
      }
      
      

      //access HLT triggers------------------------------------------------------------------
      

      //triggers for data (cleaned)
      
      //first check if trigger is present
      for( unsigned int itrig = 0 ; itrig < hlt_trigNames().size() ; ++itrig ){

        if( strcmp( hlt_trigNames().at(itrig) , "HLT_Photon20_Cleaned_L1R" )    == 0 ) HLT_Photon20_Cleaned_L1R_    = 0;
        if( strcmp( hlt_trigNames().at(itrig) , "HLT_Photon30_Cleaned_L1R" )    == 0 ) HLT_Photon30_Cleaned_L1R_    = 0;
        if( strcmp( hlt_trigNames().at(itrig) , "HLT_Photon50_Cleaned_L1R" )    == 0 ) HLT_Photon50_Cleaned_L1R_    = 0;
        if( strcmp( hlt_trigNames().at(itrig) , "HLT_Photon50_Cleaned_L1R_v1" ) == 0 ) HLT_Photon50_Cleaned_L1R_    = 0;
        if( strcmp( hlt_trigNames().at(itrig) , "HLT_Photon70_Cleaned_L1R_v1" ) == 0 ) HLT_Photon70_Cleaned_L1R_    = 0;

      }

      HLT_prescale_Photon20_Cleaned_L1R_    = -1;
      HLT_prescale_Photon30_Cleaned_L1R_    = -1;
      HLT_prescale_Photon50_Cleaned_L1R_    = -1;
      HLT_prescale_Photon70_Cleaned_L1R_    = -1;
  
      if( passHLTTrigger( "HLT_Photon20_Cleaned_L1R" ) ){
        HLT_Photon20_Cleaned_L1R_           = 1;
        HLT_prescale_Photon20_Cleaned_L1R_  = HLT_prescale( "HLT_Photon20_Cleaned_L1R" );
      }

      if( passHLTTrigger( "HLT_Photon30_Cleaned_L1R" ) ){
        HLT_Photon30_Cleaned_L1R_           = 1;
        HLT_prescale_Photon30_Cleaned_L1R_  = HLT_prescale( "HLT_Photon30_Cleaned_L1R" );
      }

      if( passHLTTrigger( "HLT_Photon50_Cleaned_L1R" ) ){
        HLT_Photon50_Cleaned_L1R_           = 1;
        HLT_prescale_Photon50_Cleaned_L1R_  = HLT_prescale( "HLT_Photon50_Cleaned_L1R" );
      }

      if( passHLTTrigger( "HLT_Photon50_Cleaned_L1R_v1" ) ){
        HLT_Photon50_Cleaned_L1R_           = 1;
        HLT_prescale_Photon50_Cleaned_L1R_  = HLT_prescale( "HLT_Photon50_Cleaned_L1R_v1" );
      }
      
      if( passHLTTrigger( "HLT_Photon70_Cleaned_L1R_v1" ) ){
        HLT_Photon70_Cleaned_L1R_           = 1;
        HLT_prescale_Photon70_Cleaned_L1R_  = HLT_prescale( "HLT_Photon70_Cleaned_L1R_v1" );
      }


      //triggers for MC (not cleaned)      

      //first check if trigger is present
      for( unsigned int itrig = 0 ; itrig < hlt_trigNames().size() ; ++itrig ){

        if( strcmp( hlt_trigNames().at(itrig) , "HLT_Photon20_L1R" )    == 0 ) HLT_Photon20_L1R_    = 0;
        if( strcmp( hlt_trigNames().at(itrig) , "HLT_Photon30_L1R" )    == 0 ) HLT_Photon30_L1R_    = 0;
        if( strcmp( hlt_trigNames().at(itrig) , "HLT_Photon50_L1R" )    == 0 ) HLT_Photon50_L1R_    = 0;
        if( strcmp( hlt_trigNames().at(itrig) , "HLT_Photon50_L1R_v1" ) == 0 ) HLT_Photon50_L1R_    = 0;
        if( strcmp( hlt_trigNames().at(itrig) , "HLT_Photon70_L1R_v1" ) == 0 ) HLT_Photon70_L1R_    = 0;

      }

      HLT_prescale_Photon20_L1R_    = -1;
      HLT_prescale_Photon30_L1R_    = -1;
      HLT_prescale_Photon50_L1R_    = -1;
      HLT_prescale_Photon70_L1R_    = -1;


      if( passHLTTrigger( "HLT_Photon20_L1R" ) ){
        HLT_Photon20_L1R_           = 1;
        HLT_prescale_Photon20_L1R_  = HLT_prescale( "HLT_Photon20_L1R" );
      }
      
      if( passHLTTrigger( "HLT_Photon30_L1R" ) ){
        HLT_Photon30_L1R_           = 1;
        HLT_prescale_Photon30_L1R_  = HLT_prescale( "HLT_Photon30_L1R" );
      }

      if( passHLTTrigger( "HLT_Photon50_L1R" ) ){
        HLT_Photon50_L1R_           = 1;
        HLT_prescale_Photon50_L1R_  = HLT_prescale( "HLT_Photon50_L1R" );
      }

      if( passHLTTrigger( "HLT_Photon50_L1R_v1" ) ){
        HLT_Photon50_L1R_           = 1;
        HLT_prescale_Photon50_L1R_  = HLT_prescale( "HLT_Photon50_L1R_v1" );
      }
      
      if( passHLTTrigger( "HLT_Photon70_L1R_v1" ) ){
        HLT_Photon70_L1R_           = 1;
        HLT_prescale_Photon70_L1R_  = HLT_prescale( "HLT_Photon70_L1R_v1" );
      }
      
              
      // calomet, pfmet, genmet
      met_       = cms2.evt_met();
      metphi_    = cms2.evt_metPhi();
      sumet_     = cms2.evt_sumet();

      pfmet_    = cms2.evt_pfmet();
      pfmetphi_ = cms2.evt_pfmetPhi();
      pfsumet_  = cms2.evt_pfsumet();

      if (!isData){
        genmet_     = cms2.gen_met();
        genmetphi_  = cms2.gen_metPhi();
        gensumet_   = cms2.gen_sumEt();
      }
      
      //tcmet stuff------------------------------------------------------------------- 

      // out-of-the-box  tcmet stuff
      tcmet_    = evt_tcmet();
      tcmetphi_ = evt_tcmetPhi();
      tcsumet_  = evt_tcsumet();

      if( calculateTCMET ){
        
        metStruct tcmetNewStruct = correctedTCMET();
        tcmetNew_     = tcmetNewStruct.met;
        tcmetphiNew_  = tcmetNewStruct.metphi;
        tcsumetNew_   = tcmetNewStruct.sumet;
        
      }else{
        
        tcmetNew_    = -9999;
        tcmetphiNew_ = -9999;
        tcsumetNew_  = -9999;
       
      }

      nGoodVertex_ = 0;
      for (size_t v = 0; v < cms2.vtxs_position().size(); ++v){
        if(isGoodVertex(v)) nGoodVertex_++;
      }

                  
      //photon stuff------------------------------------------------------------------ 

      int ijetg    = -1; //index of jet matched to photon
  
      
      nPhotons_           =  0;
      float maxPhotonPt   = -1;
      int   igmax         = -1;
      
      if( photons_p4().size() == 0 ) continue;
      
      //count photons pt > 10 GeV
      for (unsigned int iphoton = 0 ; iphoton < photons_p4().size() ; iphoton++) {
        
        LorentzVector vphoton = photons_p4().at(iphoton);
        
        if(vphoton.pt() > 10){
          nPhotons_++;
          if(vphoton.pt() > maxPhotonPt){
            maxPhotonPt  = vphoton.pt();
            igmax        = iphoton;
          }
        }
      }
      
      if( igmax < 0 ) continue;
      
      ijetg = isGoodEMObject(igmax);
      
      if( ijetg < 0 ) continue;
      
      etg_        = photons_p4().at(igmax).pt();
      etag_       = photons_p4().at(igmax).eta();
      
      phig_       = photons_p4().at(igmax).phi();
      hoe_        = photons_hOverE().at(igmax);
      swiss_      = photons_swissSeed().at(igmax);
      int scind   = photons_scindex().at(igmax) ;
      
      if( scind > - 1 ){
        seed_       = scs_eSeed().at(scind) ;
        s4_         = swiss_ - seed_ ;
        r4_         = 1 - s4_ / seed_ ;
      }else{
        seed_ = -9999.;
        s4_   = -9999.;
        r4_   = -9999.;
      }
      
      photon_scidx_            = photons_scindex().at(igmax);
      photon_pixelseed_        = photons_haspixelSeed().at(igmax) ? 1 : 0;
      photon_e15_              = photons_e1x5().at(igmax);      
      photon_e25max_           = photons_e2x5Max().at(igmax);      
      photon_e33_              = photons_e3x3().at(igmax);           
      photon_e55_              = photons_e5x5().at(igmax);           
      photon_ecalIso03_        = photons_ecalIso03().at(igmax);      
      photon_ecalIso04_        = photons_ecalIso04().at(igmax);      
      photon_hcalIso03_        = photons_hcalIso03().at(igmax);      
      photon_hcalIso04_        = photons_hcalIso04().at(igmax);      
      photon_ntkIsoHollow03_   = photons_ntkIsoHollow03().at(igmax);
      photon_ntkIsoHollow04_   = photons_ntkIsoHollow04().at(igmax);
      photon_ntkIsoSolid03_    = photons_ntkIsoSolid03().at(igmax); 
      photon_ntkIsoSolid04_    = photons_ntkIsoSolid04().at(igmax); 
      photon_sigmaEtaEta_      = photons_sigmaEtaEta().at(igmax);    
      photon_sigmaIEtaIEta_    = photons_sigmaIEtaIEta().at(igmax);
      photon_tkisoHollow03_    = photons_tkIsoHollow03().at(igmax);
      photon_tkisoHollow04_    = photons_tkIsoHollow04().at(igmax); 
      photon_tkisoSolid03_     = photons_tkIsoSolid03().at(igmax);   
      photon_tkisoSolid04_     = photons_tkIsoSolid04().at(igmax);  
      
      LorentzVector myvjet = pfjets_cor().at(ijetg) * pfjets_p4().at(ijetg);
      LorentzVector myvg   = photons_p4().at(igmax);
      
      jet_dr_             = dRbetweenVectors(myvjet, myvg);
      jet_pt_             = pfjets_p4().at(ijetg).pt();
      jet_energy_         = pfjets_p4().at(ijetg).energy();
      jet_eta_            = pfjets_p4().at(ijetg).eta();
      jet_chg_emfrac_     = pfjets_chargedEmE().at(ijetg)     / jet_energy_;
      jet_chg_hadfrac_    = pfjets_chargedHadronE().at(ijetg) / jet_energy_;
      jet_neu_emfrac_     = pfjets_neutralEmE().at(ijetg)     / jet_energy_;
      jet_neu_hadfrac_    = pfjets_neutralHadronE().at(ijetg) / jet_energy_;
      jet_nchg_           = pfjets_chargedMultiplicity().at(ijetg);
      jet_nmuon_          = pfjets_muonMultiplicity().at(ijetg);
      jet_nneu_           = pfjets_neutralMultiplicity().at(ijetg);
      jet_dphimet_        = deltaPhi( pfjets_p4().at(ijetg).phi() , tcmetphi_);
      jet_pfjetid_        = passesPFJetID( ijetg ) ? 1 : 0;
      
      //jet stuff--------------------------------------------------------------------- 
                    
      nJets_        = 0;
      sumJetPt_     = 0.;
      nJets40_      = 0;
      nJets10_      = 0;
      nJets15_      = 0;
      nJets20_      = 0;
      sumJetPt10_   = 0.;
      nbtags_       = 0;

      LorentzVector jetSystem(0.,0.,0.,0.);        
      float maxcosdphi  = -99;
      //int   imaxcosdphi = -1;
      int   imaxjet     = -1;
      float maxpt       = -1;

      VofP4         good_pfjets15_p4;
      vector<float> good_pfjets15_cor;
      VofP4         good_pfjets30_p4;
      vector<float> good_pfjets30_cor;

      failjetid_ =  0;
      maxemf_    = -1;
      
      //loop over pfjets pt > 30 GeV |eta| < 2.5
      for (unsigned int ijet = 0 ; ijet < pfjets_p4().size() ; ijet++) {
        
        //skip jet matched to photon
        if( (int)ijet == ijetg ) continue;
 
        LorentzVector vjet      = pfjets_cor().at(ijet) * pfjets_p4().at(ijet);
        if( fabs( vjet.eta() ) > 2.5 )           continue;

        if( !passesPFJetID(ijet) ){
          failjetid_ = 1;
          continue;
        }

        if ( vjet.pt() > 10. ){
          sumJetPt10_ += vjet.pt();
        }
        if ( vjet.pt() > 15. ){
          sumJetPt_ += vjet.pt();
          jetSystem += vjet;
          good_pfjets15_p4.push_back ( pfjets_p4().at(ijet)  );
          good_pfjets15_cor.push_back( pfjets_cor().at(ijet) );

          float emfrac = pfjets_neutralEmE().at(ijet) / pfjets_p4().at(ijet).energy();
          if( emfrac > maxemf_ ) maxemf_ = emfrac;
        }

        if ( vjet.pt() > 10. ) nJets10_++;
        if ( vjet.pt() > 15. ) nJets15_++;
        if ( vjet.pt() > 20. ) nJets20_++;
              
        if( vjet.pt() < 30. )                    continue;

        good_pfjets30_p4.push_back ( pfjets_p4().at(ijet)  );
        good_pfjets30_cor.push_back( pfjets_cor().at(ijet) );
        
        //find max jet pt
        if( vjet.pt() > maxpt ){
          maxpt   = vjet.pt();
          imaxjet = ijet;
        }

        //find jet (anti-)aligned with tcmet
        if( fabs( cos( tcmetphi_ - vjet.phi() ) ) > maxcosdphi ){
          maxcosdphi  = fabs( cos( tcmetphi_ - vjet.phi() ) );
          dphijetmet_ = fabs( tcmetphi_ - vjet.phi() );
          if( dphijetmet_ > TMath::Pi() ) dphijetmet_ = TMath::TwoPi() - dphijetmet_;
        }
        
        //find closest calojet to use btagging info
        float dRmin    = 100;
        int   iCaloJet = -1;
          
        for( unsigned int iC = 0 ; iC < jets_p4().size() ; iC++ ){
            
          LorentzVector vcalojet = jets_p4().at(iC);
          if( vcalojet.pt() * jets_cor().at(iC) < 10 ) continue;
            
          float dR = dRbetweenVectors(vjet, vcalojet);
          if( dR < dRmin ){
            dRmin = dR;
            iCaloJet = iC;
          }
        }
                  
        if( iCaloJet > -1 ){
          if( jets_simpleSecondaryVertexHighEffBJetTag().at(iCaloJet) > 1.74 ) ++nbtags_;
          //if( jets_trackCountingHighEffBJetTag().at(iCaloJet) > 1.7 ) ++nbtags_;
        }

        if ( vjet.pt() > 30. ) nJets_++;
        if ( vjet.pt() > 40. ) nJets40_++;
          
      }
                            
      

      jetmax_pt_ = -1;

      if( imaxjet > -1 ){
        jetmax_pt_       = pfjets_cor().at(imaxjet) * pfjets_p4().at(imaxjet).pt();
        jetmax_dphimet_  = deltaPhi( pfjets_p4().at(imaxjet).phi() , tcmetphi_);
      }

      vecJetPt_ = jetSystem.pt();


      VofP4         good_jpts15_p4;
      vector<float> good_jpts15_cor;
      VofP4         good_jpts30_p4;
      vector<float> good_jpts30_cor;
  
      for (unsigned int ijet = 0; ijet < jpts_p4().size(); ijet++) {

        //skip jet matched to photon
        if( (int)ijet == ijetg ) continue;
        
        LorentzVector vjet = jpts_p4().at(ijet) * jpts_cor().at(ijet); 
        
        if( fabs( vjet.eta() ) > 2.5 )         continue;
        if( !passesCaloJetID( vjet ) )         continue;
        
        if ( vjet.pt() > 15. ){
          good_jpts15_p4.push_back ( jpts_p4().at(ijet)  );
          good_jpts15_cor.push_back( jpts_cor().at(ijet) );
        }
        if ( vjet.pt() > 30. ){
          good_jpts30_p4.push_back ( jpts_p4().at(ijet)  );
          good_jpts30_cor.push_back( jpts_cor().at(ijet) );
        }
      }
      

      //calculate type1 METs
      
      metStruct type1PFMET30 = customType1Met( evt_pfmet() * cos( evt_pfmetPhi() ) , 
                                               evt_pfmet() * cos( evt_pfmetPhi() ) , 
                                               evt_pfsumet() ,
                                               good_pfjets30_p4 , 
                                               good_pfjets30_cor );

      pfmet_type1_pt30_ = type1PFMET30.met;

      metStruct type1PFMET15 = customType1Met( evt_pfmet() * cos( evt_pfmetPhi() ) , 
                                               evt_pfmet() * cos( evt_pfmetPhi() ) , 
                                               evt_pfsumet() ,
                                               good_pfjets15_p4 , 
                                               good_pfjets15_cor );
      
      pfmet_type1_pt15_ = type1PFMET15.met;
      
      metStruct type1TCMET30 = customType1Met( tcmetNew_ * cos( tcmetphiNew_ ) , 
                                               tcmetNew_ * sin( tcmetphiNew_ ) , 
                                               tcsumetNew_ ,
                                               good_jpts30_p4 , 
                                               good_jpts30_cor );

      tcmetNew_type1_pt30_ = type1TCMET30.met;

      metStruct type1TCMET15 = customType1Met( tcmetNew_ * cos( tcmetphiNew_ )  , 
                                               tcmetNew_ * sin( tcmetphiNew_ )  , 
                                               tcsumetNew_ ,
                                               good_jpts15_p4 , 
                                               good_jpts15_cor );
      
      tcmetNew_type1_pt15_ = type1TCMET15.met;
      

      //fill histos and ntuple----------------------------------------------------------- 
              
      npass++;
      FillBabyNtuple();
      
      //fillHistos( htcmet            , tcmet_           , weight_ , leptype_ , nJets_ );
      //fillHistos( htcmetNew         , tcmetNew_        , weight_ , leptype_ , nJets_ );
      //fillHistos( hpfmet            , pfmet_           , weight_ , leptype_ , nJets_  );
              
      if( isData && ( tcmet_ > 30 || pfmet_ > 30 ) ){

        metStruct dummyStruct = correctedTCMET( true, ofile_tcmet );

        ofile_events << "|" << setw(8)  << evt_run()                   << setw(4) 
                     << "|" << setw(6)  << evt_lumiBlock()             << setw(4) 
                     << "|" << setw(12) << evt_event()                 << setw(4) 
                     << "|" << setw(6)  << nJets_                      << setw(4) 
                     << "|" << setw(6)  << nbtags_                     << setw(4) 
                     << "|" << setw(8)  << fround(tcmet_,1)            << setw(4) 
                     << "|" << setw(8)  << fround(pfmet_,1)            << setw(4) 
                     << "|" << setw(8)  << fround(dphijetmet_,2)       << setw(4) << "|" << endl; 
       
      }
    } // end loop over events
  } // end loop over files

  if( nSkip_els_conv_dist > 0 ){
    cout << "Skipped " << nSkip_els_conv_dist << " events due to nan in els_conv_dist branch" << endl;
  }

  if (nEventsChain != nEventsTotal)
    std::cout << "ERROR: number of events from files is not equal to total number of events" << std::endl;
  
  CloseBabyNtuple();

  cout << "numEvents passing selection " << npass << endl;

  // make histos rootfile
  //TDirectory *rootdir = gDirectory->GetDirectory("Rint:");
  //rootdir->cd();
  //saveHist( Form("output/%s/%s_templates.root", iter , prefix ) );
  deleteHistos();
  
} // end ScanChain
Example #23
0
void looper::ScanChain (TChain* chain, const char* prefix, bool isData, bool calculateTCMET, metAlgo algo, int nEvents, float kFactor){

  algo_ = algo;

  if( algo_ == e_makeTemplate )    cout << "metAlgo makeTemplate" << endl;
  if( algo_ == e_photonSelection ) cout << "metAlgo photonSelection" << endl;
  if( algo_ == e_ZSelection )      cout << "metAlgo ZSelection" << endl;

  TFile *metTemplateFile;
  string metTemplateString = "";
  
  DorkyEventIdentifier dei;

  //select templates
  if( algo_ != e_makeTemplate){
    if( isData ){
      metTemplateString = "_dataTemplate";
      metTemplateFile = TFile::Open("root/JetMETTau_250nb.root");
    }else{
      metTemplateString = "_mcTemplate";
      metTemplateFile = TFile::Open("root/QCD_Pt15_1p9pb.root");
    }
  }

  //set_goodrun_file("Cert_TopAug13_Merged_135059-142664_goodruns.txt");
  //set_goodrun_file("Cert_TopAug25_Merged_135059-143336_goodruns.txt");
  //set_goodrun_file("Cert_TopAug26_Merged_135059-143835_recover_noESDCS_goodruns.txt");
  set_goodrun_file("Cert_TopAug30_Merged_135059-144114_recover_noESDCS_goodruns.txt");

  bookHistos();

  // make a baby ntuple
  stringstream babyfilename;
  babyfilename << prefix << "_baby.root";
  MakeBabyNtuple( Form("root/%s_%s_baby.root", prefix , iter ) );

  TObjArray *listOfFiles = chain->GetListOfFiles();

  unsigned int nEventsChain = 0;
  if(nEvents == -1) 
    nEvents = chain->GetEntries();
  nEventsChain = nEvents;
  unsigned int nEventsTotal = 0;
  
  //pass fail counters
  int nPassGoodRun    = 0;
  int nPassBPTX       = 0;
  int nPassBSC        = 0;
  int nPassBeamHalo   = 0;
  int nPassGoodTracks = 0;
  int nPassGoodVertex = 0;
  int nSkip_els_conv_dist = 0;
  if(debug) cout << "Begin file loop" << endl;

  // file loop
  TIter fileIter(listOfFiles);
  TFile* currentFile = 0;
  while ((currentFile = (TFile*)fileIter.Next())){
    
    TFile f(currentFile->GetTitle());
    TTree *tree = (TTree*)f.Get("Events");
    cms2.Init(tree);

    // event loop
    unsigned int nEvents = tree->GetEntries();
 
    for (unsigned int event = 0 ; event < nEvents; ++event){
      
      cout << endl << "-------------------------------------------------------------" << endl;
        
      cms2.GetEntry(event);
      ++nEventsTotal;

      cout << "Event " << event << " nhyp " << hyp_type().size() << endl;

      // progress feedback to user
      if (nEventsTotal % 1000 == 0){
            
        // xterm magic from L. Vacavant and A. Cerri
        if (isatty(1)){
                
          printf("\015\033[32m ---> \033[1m\033[31m%4.1f%%"
                 "\033[0m\033[32m <---\033[0m\015", (float)nEventsTotal/(nEventsChain*0.01));
          fflush(stdout);
        }
      }

      //duplicate event veto CHECK THIS
      bool myduplicate = dei.is_duplicate(DorkyEvent());
      if(myduplicate) continue;
      
      //skip events with bad els_conv_dist 
      bool skipEvent = false;
      for( unsigned int iEl = 0 ; iEl < els_conv_dist().size() ; ++iEl ){
        if( els_conv_dist().at(iEl) != els_conv_dist().at(iEl) ){
          skipEvent = true;
        }
      }
      
      if( skipEvent ){
        cout << "SKIPPING EVENT WITH BAD ELS_CONV_DIST" << endl;       
        nSkip_els_conv_dist++;
        continue;
      }

      //basic event selection----------------------------------------------------------------

      if (!isData || goodrun(cms2.evt_run(), cms2.evt_lumiBlock()))
        nPassGoodRun++;
      else continue;
          
      // determine if current event passes BPTX triggers
      if (cleaning_BPTX( isData ))
        nPassBPTX++;
      else continue;

      // determine if current event passes BSC triggers
      if (cleaning_BSC())
        nPassBSC++;
      else continue;

      // determine if current event passes beam halo triggers
      if (cleaning_beamHalo())
        nPassBeamHalo++;
      else continue;

      // determine if current event is a beam scraping event
      if (cleaning_goodTracks())
        nPassGoodTracks++;
      else continue;

      // determine if current event has a good vertex
      if (cleaning_goodVertexAugust2010())
        nPassGoodVertex++;
      else continue;
      
      if ( !cleaning_standard( isData ) ) continue;
      
      if(debug) cout << "Pass event selection" << endl;

      cout << "Pass event cleaning" << endl;
      InitBabyNtuple();

      // event stuff
      run_    = cms2.evt_run();
      lumi_   = cms2.evt_lumiBlock();
      event_  = cms2.evt_event();

      weight_ = 1.;
      pthat_  = -1;
      if( !isData ){
        weight_ = cms2.evt_scale1fb() * kFactor * lumi;
        pthat_  = cms2.genps_pthat();
      }

      /*
      //cout << "pthat " << endl;
      //cout << cms2.genps_pthat() << endl;

      float maxphotonpt = -1;
     
      //stitching together PhotonJet_Pt15 and PhotonJet_Pt30
      if( strcmp( prefix , "PhotonJet") == 0 ){
       
        //cout << "Stitching, file " << currentFile->GetTitle() << endl;
        
        if( TString(currentFile->GetTitle()).Contains("PhotonJet_Pt15") ){
          //cout << "Pt15" << endl;
          //weight_ *= 1.245;
          if( cms2.genps_pthat() > 30. ) continue;
        }   
        for( unsigned int ig = 0 ; ig < photons_p4().size() ; ++ig ){
          if( photons_p4().at(ig).pt() > maxphotonpt ) 
            maxphotonpt = photons_p4().at(ig).pt();
        }
      }
 
      fillUnderOverFlow( hgenps_pthat  , genps_pthat() , weight_ );
      fillUnderOverFlow( hphotonpt     , maxphotonpt   , weight_ );
      */


      //access HLT triggers------------------------------------------------------------------

      for( unsigned int itrig = 0 ; itrig < hlt_trigNames().size() ; ++itrig ){

        if( strcmp( hlt_trigNames().at(itrig) , "HLT_L1Jet6U" ) == 0 ){
          if( passHLTTrigger("HLT_L1Jet6U") )                  HLT_L1Jet6U_ = 1;
          else                                                 HLT_L1Jet6U_ = 0;
        }

        if( strcmp( hlt_trigNames().at(itrig) , "HLT_L1Jet10U" ) == 0 ){
          if( passHLTTrigger("HLT_L1Jet10U") )                 HLT_L1Jet10U_ = 1;
          else                                                 HLT_L1Jet10U_ = 0;
        }
        
        if( strcmp( hlt_trigNames().at(itrig) , "HLT_Jet15U" ) == 0 ){
          if( passHLTTrigger("HLT_Jet15U") )                   HLT_Jet15U_ = 1;
          else                                                 HLT_Jet15U_ = 0;
        }

        if( strcmp( hlt_trigNames().at(itrig) , "HLT_Jet30U" ) == 0 ){
          if( passHLTTrigger("HLT_Jet30U") )                   HLT_Jet30U_ = 1;
          else                                                 HLT_Jet30U_ = 0;
        }

        if( strcmp( hlt_trigNames().at(itrig) , "L1_SingleEG5" ) == 0 ){
          if( passHLTTrigger("L1_SingleEG5") )                 L1_SingleEG5_ = 1;
          else                                                 L1_SingleEG5_ = 0;
        }

        if( strcmp( hlt_trigNames().at(itrig) , "HLT_Photon10_L1R" ) == 0 ){
          if( passHLTTrigger("HLT_Photon10_L1R") )             HLT_Photon10_L1R_ = 1;
          else                                                 HLT_Photon10_L1R_ = 0;
        }

        if( strcmp( hlt_trigNames().at(itrig) , "HLT_Photon15_L1R" ) == 0 ){
          if( passHLTTrigger("HLT_Photon15_L1R") )             HLT_Photon15_L1R_ = 1;
          else                                                 HLT_Photon15_L1R_ = 0;
        }

        if( strcmp( hlt_trigNames().at(itrig) , "HLT_Photon10_Cleaned_L1R" ) == 0 ){
          if( passHLTTrigger("HLT_Photon10_Cleaned_L1R") )     HLT_Photon10_Cleaned_L1R_ = 1;
          else                                                 HLT_Photon10_Cleaned_L1R_ = 0;
        }

        if( strcmp( hlt_trigNames().at(itrig) , "HLT_Photon15_Cleaned_L1R" ) == 0 ){
          if( passHLTTrigger("HLT_Photon15_Cleaned_L1R") )     HLT_Photon15_Cleaned_L1R_ = 1;
          else                                                 HLT_Photon15_Cleaned_L1R_ = 0;
        }

        if( strcmp( hlt_trigNames().at(itrig) , "HLT_Photon20_Cleaned_L1R" ) == 0 ){
          if( passHLTTrigger("HLT_Photon20_Cleaned_L1R") )     HLT_Photon20_Cleaned_L1R_ = 1;
          else                                                 HLT_Photon20_Cleaned_L1R_ = 0;
        }
      }      
      //met quantities--------------------------------------------------------------------------
      
      //calomet
      met_       = cms2.evt_met();
      metphi_    = cms2.evt_metPhi();
      sumet_     = cms2.evt_sumet();

      // pf met stuff
      pfmet_    = cms2.evt_pfmet();
      pfmetphi_ = cms2.evt_pfmetPhi();
      pfsumet_  = cms2.evt_pfsumet();

      //muon-corrected met stuff
      mumet_    = cms2.evt_metMuonCorr();
      mumetphi_ = cms2.evt_metMuonCorrPhi();
      musumet_  = cms2.evt_sumetMuonCorr();

      //muon-corrected JES met stuff
      mujesmet_    = cms2.evt_metMuonJESCorr();
      mujesmetphi_ = cms2.evt_metMuonJESCorrPhi();
      mujessumet_  = -9999.; //cms2.evt_sumetMuonJESCorr(); //branch doesn't exist!!!

      // genmet stuff
      if (!isData){
//         genmet_     = cms2.gen_met();
//         genmetphi_  = cms2.gen_metPhi();
//         gensumet_   = cms2.gen_sumEt();
      }

      //looper-level tcmet
      if( calculateTCMET ){
        metStruct tcmetNewStruct = correctedTCMET();
        tcmetNew_     = tcmetNewStruct.met;
        tcmetphiNew_  = tcmetNewStruct.metphi;
        tcsumetNew_   = tcmetNewStruct.sumet;
      }

      //just take tcmet from event
      tcmet_     = evt_tcmet();
      tcmetphi_  = evt_tcmetPhi();
      tcsumet_   = evt_tcsumet();

      //photon quantities-----------------------------------------------------------------------

      if(debug) cout << "Get photon quantities" << endl;

      if(debug) cout << "run lumi event " << evt_run() << " " << evt_lumiBlock() << " " << evt_event() << endl;
      
      nPhotons_         =  0;
      float maxPhotonPt = -1;
      int igmax         = -1;

      if( photons_p4().size() == 0 && algo_ == e_photonSelection ) continue;
      
      //count photons pt > 10 GeV
      for (unsigned int iphoton = 0 ; iphoton < photons_p4().size() ; iphoton++) {

        LorentzVector vphoton = photons_p4().at(iphoton);

        if(vphoton.pt() > 10){
          nPhotons_++;
          if(vphoton.pt() > maxPhotonPt){
            maxPhotonPt  = vphoton.pt();
            igmax        = iphoton;
          }
        }
      }

      //if( igmax < 0 && algo_ == e_photonSelection ) continue;

      if( igmax > -1 ){
        etg_   = photons_p4()[igmax].pt();
        etag_  = photons_p4()[igmax].eta();
        phig_  = photons_p4()[igmax].phi();
        hoe_   = photons_hOverE()[igmax];
        //eciso_ = photons_ecalIso()[igmax];
        //hciso_ = photons_hcalIso()[igmax];
        //tkiso_ = photons_tkIsoSolid()[igmax];

        /*
        photon_pixelseed_        = photons_haspixelSeed()[igmax] ? 1 : 0;
	photon_e15_              = photons_e1x5()[igmax];      
	photon_e25max_           = photons_e2x5Max()[igmax];      
	photon_e33_              = photons_e3x3()[igmax];           
	photon_e55_              = photons_e5x5()[igmax];           
	photon_ecalIso03_        = photons_ecalIso03()[igmax];      
	photon_ecalIso04_        = photons_ecalIso04()[igmax];      
	photon_hcalIso03_        = photons_hcalIso03()[igmax];      
	photon_hcalIso04_        = photons_hcalIso04()[igmax];      
	photon_ntkIsoHollow03_   = photons_ntkIsoHollow03()[igmax];
        photon_ntkIsoHollow04_   = photons_ntkIsoHollow04()[igmax];
	photon_ntkIsoSolid03_    = photons_ntkIsoSolid03()[igmax]; 
	photon_ntkIsoSolid04_    = photons_ntkIsoSolid04()[igmax]; 
	photon_sigmaEtaEta_      = photons_sigmaEtaEta()[igmax];    
	photon_sigmaIEtaIEta_    = photons_sigmaIEtaIEta()[igmax];
	photon_tkisoHollow03_    = photons_tkIsoHollow03()[igmax];
	photon_tkisoHollow04_    = photons_tkIsoHollow04()[igmax]; 
	photon_tkisoSolid03_     = photons_tkIsoSolid03()[igmax];   
	photon_tkisoSolid04_     = photons_tkIsoSolid04()[igmax];  
        */

        swiss_      = photons_swissSeed()[igmax];
        int scind   = photons_scindex()[igmax] ;
        seed_       = scs_eSeed()[scind] ;
        s4_         = swiss_ - seed_ ;
        r4_         = 1 - s4_ / seed_ ;
        
        drel_ = 1000;

        for( unsigned int iel = 0 ; iel < els_p4().size() ; iel++ ){
        
          if( els_p4().at(iel).pt() < 5 ) continue;

          float deta = etag_ - trks_trk_p4().at(iel).eta();
          float dphi = fabs( phig_ - trks_trk_p4().at(iel).phi() );
          if( dphi > TMath::Pi() ) dphi = TMath::TwoPi() - dphi;
          float dr = sqrt( deta * deta + dphi * dphi );
          if( dr < drel_ ) drel_ = dr;

        }
      }
      
      //photon-matched jet quantities---------------------------------------------------------------

      if(debug) cout << "Get jet quantities" << endl;

      jet_dr_      = 10000;
      int   ijetg  = -1;

      //find jet corresponding to photon
      for (unsigned int ijet = 0 ; ijet < pfjets_p4().size() ; ijet++) {

        float etajet = pfjets_p4().at(ijet).eta();
        
        if( etajet > 3 ) continue;
        
        float phijet = pfjets_p4().at(ijet).phi();
        float deta   = etajet - etag_;
        float dphi   = phijet - phig_;
        if( dphi > TMath::Pi() ) dphi = TMath::TwoPi() - dphi;
        
        float deltaR = sqrt( deta*deta + dphi*dphi );

        if( deltaR < jet_dr_ ){
          jet_dr_ = deltaR;
          ijetg   = ijet;
        }
      }

    
      if( ijetg < 0 && algo_ == e_photonSelection ) continue;

      if( ijetg > -1 ){
      
        jet_pt_             = pfjets_p4().at(ijetg).pt();
        jet_energy_         = pfjets_p4().at(ijetg).energy();
        jet_eta_            = pfjets_p4().at(ijetg).eta();

        //energy component fractions (add protection for index out of range)
        jet_chg_emfrac_     = pfjets_chargedEmE().at(ijetg)     / jet_energy_;
        jet_chg_hadfrac_    = pfjets_chargedHadronE().at(ijetg) / jet_energy_;
        jet_neu_emfrac_     = pfjets_neutralEmE().at(ijetg)     / jet_energy_;
        jet_neu_hadfrac_    = pfjets_neutralHadronE().at(ijetg) / jet_energy_;
        
        //multiplicities
        jet_nchg_           = pfjets_chargedMultiplicity().at(ijetg);
        jet_nmuon_          = pfjets_muonMultiplicity().at(ijetg);
        jet_nneu_           = pfjets_neutralMultiplicity().at(ijetg);
        
        //deltaPhi( jet - met )
        jet_dphimet_          = deltaPhi( pfjets_p4().at(ijetg).phi() , tcmetphi_);
      
//         if(!isData){
          
//           //deltaR match to genjet
//           int iMin    = -1;
//           float dRmin = -1;
          
//           for (unsigned int igenjet = 0 ; igenjet < genjets_p4().size() ; igenjet++ ){
            
//             LorentzVector vgenjet = genjets_p4().at(igenjet);
            
//             float dR = dRbetweenVectors(pfjets_p4().at(ijetg), vgenjet);
            
//             if(dR < dRmin){
//               iMin = igenjet;
//               dRmin = dR;
//             }
//           }
          
//           if(iMin > -1){
//             jet_dpt_   = jet_pt_ - genjets_p4().at(iMin).pt();
//             jet_drgen_ = dRmin;
//           }
//         }
      }

      //find leading jet------------------------------------------------------------------------

      int imaxjet = -1;
      float maxpt = -1;

      for (unsigned int ijet = 0 ; ijet < pfjets_p4().size() ; ijet++) {

        if( fabs( pfjets_p4().at(ijet).eta() ) > 5.) continue;
        
        if( pfjets_p4().at(ijet).pt() > maxpt ){
          maxpt = pfjets_p4().at(ijet).pt();
          imaxjet = ijet;
        }

      }
      
      if( imaxjet > -1 ){
        jetmax_pt_       = pfjets_p4().at(imaxjet).pt();
        jetmax_dphimet_  = deltaPhi( pfjets_p4().at(imaxjet).phi() , tcmetphi_);
      }
      
      //loop over pfjets, find nJets and sumJetPt-----------------------------------------------

      if(debug) cout << "Get nJets and sumJetPt" << endl;

      nJets_        = 0;
      sumJetPt_     = 0.;
      nJets40_      = 0;
      sumJetPt10_   = 0.;

      LorentzVector jetSystem(0.,0.,0.,0.);

      for (unsigned int ijet = 0 ; ijet < pfjets_p4().size() ; ijet++) {

        LorentzVector vjet = pfjets_p4().at(ijet);
        
        bool skipJet = false;

        //skip jet matched to photon
        if( (int)ijet == ijetg && algo_ == e_photonSelection ){
          skipJet = true;
        }
       
        //skip all hyp leptons
        if( algo_ == e_ZSelection ) { 

          for( unsigned int hypIdx = 0 ; hypIdx < hyp_p4().size() ; hypIdx++ ) {
         
            LorentzVector vlt  = hyp_lt_p4()[hypIdx];
            LorentzVector vll  = hyp_ll_p4()[hypIdx];
            
            if (dRbetweenVectors(vjet, vll) < 0.4) skipJet = true;
            if (dRbetweenVectors(vjet, vlt) < 0.4) skipJet = true;
         
          }
        }
  
        if( skipJet ) continue;

        if( fabs( vjet.eta() ) < 5.){
          
          if ( vjet.pt() > 30. ){
            nJets_++;
          }        
          if ( vjet.pt() > 15. ){
            sumJetPt_ += vjet.pt();
            jetSystem += vjet;
          }
          
          if ( vjet.pt() > 40. ){
            nJets40_++;
          }
          if ( vjet.pt() > 10. ){
            sumJetPt10_ += vjet.pt();
          }
        }
      }

      vecJetPt_ = jetSystem.pt();

      cout << "Check Z selection" << endl;

      if( algo_ == e_ZSelection ){
        
        cout << "hyp_p4 size " << hyp_p4().size() << endl;
        if( hyp_p4().size() != 1 ) continue;       
      
        passz_ = passZSelection() ? 1 : 0;
      
        pdgid_ = 0;
      
        unsigned int i_lt = cms2.hyp_lt_index()[0];
        unsigned int i_ll = cms2.hyp_ll_index()[0];

        if( hyp_type()[0] == 0 ){
          pdgid_ = 13; 
          passm_nom_          = passMuon_Nominal()        ? 1 : 0;
          passm_nomttbar_     = passMuon_NominalTTbar()   ? 1 : 0;
          passm_nomttbarV2_   = passMuon_NominalTTbarV2() ? 1 : 0;
          flagll_             = mus_tcmet_flag().at(i_ll);
          flaglt_             = mus_tcmet_flag().at(i_lt);
        }
        if( hyp_type()[0] == 3 ){
          pdgid_ = 11;
          passe_ttbarV1_    = passElectron_ttbarV1( isData)  ? 1 : 0;
          passe_ttbar_      = passElectron_ttbar( isData)    ? 1 : 0;
          passe_cand01_     = passElectron_cand01()          ? 1 : 0;

        }

        ptll_             = hyp_ll_p4()[0].pt();
        ptlt_             = hyp_lt_p4()[0].pt();
        etall_            = hyp_ll_p4()[0].eta();
        etalt_            = hyp_lt_p4()[0].eta();
        dilmass_          = hyp_p4()[0].mass(); 
        dilpt_            = hyp_p4()[0].pt(); 

        metStruct tcmetStruct = correctTCMETforHypMuons( 0 ,  
                                                         evt_tcmet() * cos( evt_tcmetPhi() ), 
                                                         evt_tcmet() * sin( evt_tcmetPhi() ), 
                                                         evt_tcsumet() );
        
        // out-of-the-box  tcmet stuff (corrected for hyp muons)
        tcmet_    = tcmetStruct.met;
        tcmetphi_ = tcmetStruct.metphi;
        tcsumet_  = tcmetStruct.sumet;   

        metStruct tcmetNewStruct = correctTCMETforHypMuons( 0 ,  
                                                            tcmetNew_ * cos( tcmetphiNew_ ), 
                                                            tcmetNew_ * sin( tcmetphiNew_ ), 
                                                            tcsumetNew_ );
            
        // looper-level  tcmet stuff (corrected for hyp muons)
        tcmetNew_    = tcmetNewStruct.met;
        tcmetphiNew_ = tcmetNewStruct.metphi;
        tcsumetNew_  = tcmetNewStruct.sumet;   

      }

      nGoodVertex_ = 0;
      for (size_t v = 0; v < cms2.vtxs_position().size(); ++v){
        if(isGoodVertex(v)) nGoodVertex_++;
      }
      
      cout << "Check jets" << endl;
      //fill baby ntuple
      if ( nJets_ < 1 )     continue;
      if( jetmax_pt_ < 30 ) continue;

      cout << "Pass jet selection" << endl;
      FillBabyNtuple();

      //require at least 2 jets
      if ( nJets_ < 2 )     continue;

      //require leading jet pt > 50
      if( jetmax_pt_ < 50 ) continue;

      dphixmet_  = deltaPhi( tcmetphi_ , jetSystem.phi() );
      metPar_    = tcmet_ * cos( dphixmet_ );
      metPerp_   = tcmet_ * sin( dphixmet_ );
      
      //fill met template-----------------------------------------------------------------------
      
      if( algo_ == e_makeTemplate ) {

        if( HLT_Jet15U_ == 0 ) continue;
        
        //dphixmet_  = deltaPhi( tcmetphi_ , jetSystem.phi() );
        //metPar_    = -1 * tcmet_ * cos( dphixmet_ );
        //metPerp_   = tcmet_ * sin( dphixmet_ );
        
        int iJetBin      = getJetBin( nJets_ );
        int iSumJetPtBin = getSumJetPtBin( sumJetPt_ );
        
        if( debug ) {
          cout << "nJets " << nJets_ << " sumJetPt " << sumJetPt_ << endl;
          cout << "iJetBin " << iJetBin << " iSumJetPtBin " << iSumJetPtBin << " tcmet " << tcmet_ << endl;
        }

        fillUnderOverFlow( metTemplate[ iJetBin ][ iSumJetPtBin ]     , tcmet_   , weight_ );
        fillUnderOverFlow( metParTemplate[ iJetBin ][ iSumJetPtBin ]  , metPar_  , weight_ );
        fillUnderOverFlow( metPerpTemplate[ iJetBin ][ iSumJetPtBin ] , metPerp_ , weight_ );
        
      }

      
      //apply good photon selection-------------------------------------------------------------
  
      if( algo_ == e_photonSelection ) {

        if( HLT_Photon10_L1R_ == 0         &&         
            HLT_Photon15_L1R_ == 0         && 
            HLT_Photon10_Cleaned_L1R_ == 0 && 
            HLT_Photon15_Cleaned_L1R_ == 0  ) continue;
          
        if ( etg_ < 20 )                                 continue;
        if ( r4_ < 0.05 )                                continue;
        if ( hoe_ > 0.1 )                                continue;
        if ( jet_dr_ > 0.5 )                             continue;
        //if ( jet_neu_emfrac_ + jet_chg_emfrac_< 0.95 )   continue; 
        //if ( drel_ < 0.3 )                               continue;
        if ( jet_neu_emfrac_ < 0.95 )                    continue; 
        //if ( sumJetPt_ < 200. )                          continue;
        
        //dphixmet_  = deltaPhi( tcmetphi_ , phig_ );
        //metPar_    = tcmet_ * cos( dphixmet_ );
        //metPerp_   = tcmet_ * sin( dphixmet_ );
        
      }

      //apply Z selection-----------------------------------------------------------------------

      if( algo_ == e_ZSelection ) {
        
        //if( vecJetPt_  < 100)                                       continue;
        if( hyp_p4().size() != 1 )                                  continue;
        if( hyp_lt_id()[0] * hyp_ll_id()[0] > 0 )                   continue;
        if( hyp_type()[0]==1 || hyp_type()[0]==2)                   continue;
        if( hyp_p4()[0].mass() < 76. || hyp_p4()[0].mass() > 106.)  continue;
        if( hyp_ll_p4()[0].pt() < 10 )                              continue;
        if( hyp_lt_p4()[0].pt() < 10 )                              continue;
        //if ( sumJetPt_ < 200. )                                     continue;
        
        //ttbar muon ID
        if (abs(hyp_ll_id()[0]) == 13  && (!(fabs(hyp_ll_p4()[0].eta()) < 2.4 && muonId(hyp_ll_index()[0],NominalTTbarV2))))   continue;
        if (abs(hyp_lt_id()[0]) == 13  && (!(fabs(hyp_lt_p4()[0].eta()) < 2.4 && muonId(hyp_lt_index()[0],NominalTTbarV2))))   continue;
        
        //ttbarV1 electron ID
        if (abs(hyp_ll_id()[0]) == 11  && (! pass_electronSelection( hyp_ll_index()[0] , electronSelection_ttbarV1 , isData ))) continue;
        if (abs(hyp_lt_id()[0]) == 11  && (! pass_electronSelection( hyp_lt_index()[0] , electronSelection_ttbarV1 , isData ))) continue;

        //ttbar electron ID
        //if (abs(hyp_ll_id()[0]) == 11  && (! pass_electronSelection( hyp_ll_index()[0] , electronSelection_ttbar , isData ))) continue;
        //if (abs(hyp_lt_id()[0]) == 11  && (! pass_electronSelection( hyp_lt_index()[0] , electronSelection_ttbar , isData ))) continue;
        
        //nominal muon ID
        //if (abs(hyp_ll_id()[0]) == 13  && (! (fabs(hyp_ll_p4()[0].eta()) < 2.4 && muonId(hyp_ll_index()[0]))))   continue;
        //if (abs(hyp_lt_id()[0]) == 13  && (! (fabs(hyp_lt_p4()[0].eta()) < 2.4 && muonId(hyp_lt_index()[0]))))   continue;
        
        //ttbar electron ID
        //if (abs(hyp_ll_id()[0]) == 11  && (! pass_electronSelection( hyp_ll_index()[0] , electronSelection_cand01 ))) continue;
        //if (abs(hyp_lt_id()[0]) == 11  && (! pass_electronSelection( hyp_lt_index()[0] , electronSelection_cand01 ))) continue;

        //dphixmet_  = deltaPhi( tcmetphi_ , hyp_p4()[0].phi() );
        //metPar_    = tcmet_ * cos( dphixmet_ );
        //metPerp_   = tcmet_ * sin( dphixmet_ );

  


//         if( tcmet_ > 60 ){
//           cout << "tcmet " << tcmet_ << " type " << hyp_type()[0] << endl;
//         }
      }

     

      //fill predicted and observed met histos--------------------------------------------------

      if( algo_ != e_makeTemplate){
        
        int iJetBin      = getJetBin( nJets_ );
        int iSumJetPtBin = getSumJetPtBin( sumJetPt_ );
        TH1F* hmet     = (TH1F*) metTemplateFile->Get(Form("metTemplate_%i_%i",iJetBin,iSumJetPtBin));
        TH1F* hmetPar  = (TH1F*) metTemplateFile->Get(Form("metParTemplate_%i_%i",iJetBin,iSumJetPtBin));
        TH1F* hmetPerp = (TH1F*) metTemplateFile->Get(Form("metPerpTemplate_%i_%i",iJetBin,iSumJetPtBin));
        
        fillUnderOverFlow( metObserved_njets[iJetBin]  ,  tcmet_ , weight_ );
        metPredicted_njets[iJetBin]->Add( hmet );
        
        fillUnderOverFlow( metObserved , tcmet_ , weight_  );
        metPredicted->Add( hmet );

        fillUnderOverFlow( metParObserved , metPar_ , weight_  );
        metParPredicted->Add( hmetPar );

        fillUnderOverFlow( metPerpObserved ,  metPerp_ , weight_ );
        metPerpPredicted->Add( hmetPerp );
        
        delete hmet;

      }
    } // end loop over events
  } // end loop over files
  
  cout << "\n\n********************SUMMARY********************" << endl;
  cout << "Total number of events: " << nEventsTotal << endl;
  cout << "Total number of events that pass good run/lumi: " << nPassGoodRun 
       << " (" << 100*(double)nPassGoodRun/nEventsTotal << "% of total)" << endl;
  cout << "Total number of events that pass BPTX trigger: " << nPassBPTX
       << " (" << 100*(double)nPassBPTX/nPassGoodRun << "%)" << endl;
  cout << "Total number of events that pass BSC trigger: " << nPassBSC
       << " (" << 100*(double)nPassBSC/nPassBPTX << "%)" << endl;
  cout << "Total number of events that pass BeamHalo trigger: " << nPassBeamHalo
       << " (" << 100*(double)nPassBeamHalo/nPassBSC << "%)" << endl;
  cout << "Total number of events that pass tracking cuts: " << nPassGoodTracks
       << " (" << 100*(double)nPassGoodTracks/nPassBeamHalo << "%)" << endl;
  cout << "Total number of events that pass vertex cuts: " << nPassGoodVertex
       << " (" << 100*(double)nPassGoodVertex/nPassGoodTracks << "%)" << endl;
  cout << endl << endl;

  if( nSkip_els_conv_dist > 0 ){
    cout << "Skipped " << nSkip_els_conv_dist << " events due to nan in els_conv_dist branch" << endl;
  }

  if (nEventsChain != nEventsTotal)
    std::cout << "ERROR: number of events from files is not equal to total number of events" << std::endl;
  
  CloseBabyNtuple();

  //normalize met templates
  if( algo_ == e_makeTemplate ) {
    
    for( int iJetBin = 0 ; iJetBin < nJetBins ; iJetBin++ ){
      for( int iSumJetPtBin = 0 ; iSumJetPtBin < nSumJetPtBins ; iSumJetPtBin++ ){
       
        float scale = metTemplate[ iJetBin ][ iSumJetPtBin ] -> Integral();
        
        if( scale > 0 )
          metTemplate[ iJetBin ][ iSumJetPtBin ] -> Scale ( 1. / scale );

        scale = metParTemplate[ iJetBin ][ iSumJetPtBin ] -> Integral();
        
        if( scale > 0 )
          metParTemplate[ iJetBin ][ iSumJetPtBin ] -> Scale ( 1. / scale );

        scale = metPerpTemplate[ iJetBin ][ iSumJetPtBin ] -> Integral();
        
        if( scale > 0 )
          metPerpTemplate[ iJetBin ][ iSumJetPtBin ] -> Scale ( 1. / scale );
    
      }
    }
  }


  // make histos rootfile
  //stringstream rootfilename;
  //rootfilename << "root/" << prefix << metTemplateString << ".root";
  TDirectory *rootdir = gDirectory->GetDirectory("Rint:");
  rootdir->cd();
  saveHist( Form("root/%s_%s%s.root", prefix , iter , metTemplateString.c_str() ) );
  //saveHist(rootfilename.str().c_str());
  deleteHistos();
  
} // end ScanChain
Example #24
0
int bTagEffMaker::looper(TChain* chain, char* output_name, int nEvents, char* path){

  //
  // Set output file path
  //
  bTagEffPath = path;
  
  //
  // Benchmark
  //
  TBenchmark *bmark = new TBenchmark();
  bmark->Start("benchmark");
  
  //
  //Set up loop over chain
  //
  unsigned int nEvents_processed = 0;
  unsigned int nEventsToDo = chain->GetEntries();

  if( nEvents >= 0 ) nEventsToDo = nEvents;
  TObjArray *listOfFiles = chain->GetListOfFiles();
  TIter fileIter(listOfFiles);
  TFile *currentFile = 0;

  //
  // Make BTagEff Ntuple  
  //
  TH1::SetDefaultSumw2();
  
  MakeBTagEffNtuple( Form("bTagEfficiency__%s.root", output_name) );

  
  //
  // File Loop
  //
  while ( (currentFile = (TFile*)fileIter.Next()) ) { 

    //
    // Get File Content
    //
    if(nEvents_processed >= nEventsToDo) continue;
    TFile *file = new TFile( currentFile->GetTitle() );
    TTree *tree = (TTree*)file->Get("Events");
    cms3.Init(tree);
    cout << "file name is " << file->GetName() << endl;

    //
    // Loop over Events in current file
    //
    unsigned int nEventsTree = tree->GetEntriesFast();

    for(unsigned int evt = 0; evt < nEventsTree; evt++){

      //
      // Get Event Content
      //
      if(nEvents_processed >= nEventsToDo) break;
      cms3.GetEntry(evt);
      nEvents_processed++;

      //
      // Progress
      //
      CMS3::progress(nEvents_processed, nEventsToDo);

      //
      // Fill Histograms
      //
      for(size_t idx = 0; idx < pfjets_p4().size(); ++idx){
	
	double pt  = pfjets_p4().at(idx).Pt();
	double eta = pfjets_p4().at(idx).Eta();

	// Selection 
	if( pt < skim_jet_pt ) continue;
	if( fabs(eta) > skim_jet_eta ) continue;


	int flav   = pfjets_hadronFlavour().at(idx);
	
	double csv = getbtagvalue("pfCombinedInclusiveSecondaryVertexV2BJetTags", idx);
      

	// b-jets
	if( abs(flav) == 5 ){

	  h2_BTaggingEff_csv_Denom_b->Fill( std::min(pt,pt_max), std::min(fabs(eta),eta_max) );

	  h2_BTaggingEff_csv_fineBinning_Denom_b->Fill( std::min(pt,pt_max_fine), std::min(fabs(eta),eta_max_fine) );
	  
	  if( csv > csv_wp_loose ){
	    h2_BTaggingEff_csv_loose_Num_b->Fill( std::min(pt,pt_max), std::min(fabs(eta),eta_max) );
	    h2_BTaggingEff_csv_fineBinning_loose_Num_b->Fill( std::min(pt,pt_max_fine), std::min(fabs(eta),eta_max_fine) );
	  }
	  if( csv > csv_wp_med ){
	    h2_BTaggingEff_csv_med_Num_b->Fill( std::min(pt,pt_max), std::min(fabs(eta),eta_max) );
	    h2_BTaggingEff_csv_fineBinning_med_Num_b->Fill( std::min(pt,pt_max_fine), std::min(fabs(eta),eta_max_fine) );
	  }
	  if( csv > csv_wp_tight ){
	    h2_BTaggingEff_csv_tight_Num_b->Fill( std::min(pt,pt_max), std::min(fabs(eta),eta_max) );
	    h2_BTaggingEff_csv_fineBinning_tight_Num_b->Fill( std::min(pt,pt_max_fine), std::min(fabs(eta),eta_max_fine) );
	  }

	} // end if b-jet


	// c-jets
	if( abs(flav) == 4 ){

	  h2_BTaggingEff_csv_Denom_c->Fill( std::min(pt,pt_max), std::min(fabs(eta),eta_max) );
	  h2_BTaggingEff_csv_fineBinning_Denom_c->Fill( std::min(pt,pt_max_fine), std::min(fabs(eta),eta_max_fine) );
	  
	  if( csv > csv_wp_loose ){
	    h2_BTaggingEff_csv_loose_Num_c->Fill( std::min(pt,pt_max), std::min(fabs(eta),eta_max) );
	    h2_BTaggingEff_csv_fineBinning_loose_Num_c->Fill( std::min(pt,pt_max_fine), std::min(fabs(eta),eta_max_fine) );
	  }
	  if( csv > csv_wp_med ){
	    h2_BTaggingEff_csv_med_Num_c->Fill( std::min(pt,pt_max), std::min(fabs(eta),eta_max) );
	    h2_BTaggingEff_csv_fineBinning_med_Num_c->Fill( std::min(pt,pt_max_fine), std::min(fabs(eta),eta_max_fine) );
	  }
	  if( csv > csv_wp_tight ){
	    h2_BTaggingEff_csv_tight_Num_c->Fill( std::min(pt,pt_max), std::min(fabs(eta),eta_max) );
	    h2_BTaggingEff_csv_fineBinning_tight_Num_c->Fill( std::min(pt,pt_max_fine), std::min(fabs(eta),eta_max_fine) );
	  }

	} // end if c-jet

	// udsg-jets
	if( abs(flav) == 3 ||
	    abs(flav) == 2 || 
	    abs(flav) == 1 ||
	    abs(flav) == 0 ||
	    abs(flav) == 21   ){

	  h2_BTaggingEff_csv_Denom_udsg->Fill( std::min(pt,pt_max), std::min(fabs(eta),eta_max) );
	  h2_BTaggingEff_csv_fineBinning_Denom_udsg->Fill( std::min(pt,pt_max_fine), std::min(fabs(eta),eta_max_fine) );
	  
	  if( csv > csv_wp_loose ){
	    h2_BTaggingEff_csv_loose_Num_udsg->Fill( std::min(pt,pt_max), std::min(fabs(eta),eta_max) );
	    h2_BTaggingEff_csv_fineBinning_loose_Num_udsg->Fill( std::min(pt,pt_max_fine), std::min(fabs(eta),eta_max_fine) );
	  }
	  if( csv > csv_wp_med ){
	    h2_BTaggingEff_csv_med_Num_udsg->Fill( std::min(pt,pt_max), std::min(fabs(eta),eta_max) );
	    h2_BTaggingEff_csv_fineBinning_med_Num_udsg->Fill( std::min(pt,pt_max_fine), std::min(fabs(eta),eta_max_fine) );
	  }
	  if( csv > csv_wp_tight ){
	    h2_BTaggingEff_csv_tight_Num_udsg->Fill( std::min(pt,pt_max), std::min(fabs(eta),eta_max) );
	    h2_BTaggingEff_csv_fineBinning_tight_Num_udsg->Fill( std::min(pt,pt_max_fine), std::min(fabs(eta),eta_max_fine) );
	  }

	} // end if udsg-jet



      } // end loop over jets
          
    
    }//close event loop
    

    //
    // Close input file
    //
    file->Close();
    delete file;

  }//close file loop


  //
  // Write and Close baby file
  //
  BTagEffFile->cd();
  BTagEffFile->Write();
  BTagEffFile->Close();


  //
  // Benchmarking
  //
  bmark->Stop("benchmark");
  

  //
  // Print Skim Cutflow
  //
  cout << endl;
  cout << "Wrote babies into file " << BTagEffFile->GetName() << endl;
  cout << "-----------------------------" << endl;
  cout << "Events Processed                     " << nEvents_processed << endl;
    cout << "-----------------------------" << endl;
  cout << "CPU  Time:   " << Form( "%.01f", bmark->GetCpuTime("benchmark")  ) << endl;                                                                                          
  cout << "Real Time:   " << Form( "%.01f", bmark->GetRealTime("benchmark") ) << endl;
  cout << endl;
  delete bmark;

  return 0;  

}
Example #25
0
void makePhotonTemplates::ScanChain ( TChain* chain , char* iter , char* sample ){

  bool useHGGTriggers = true;
  //if( TString(sample).Contains("DoubleElectron") ) useHGGTriggers = true;

  cout << "Sample : " << sample << endl;
  if( useHGGTriggers ) cout << "Using H->gg triggers" << endl;
  else                 cout << "Using standard triggers" << endl;

  if( vtxreweight ) cout << "Doing vtx reweighting" << endl;
  else              cout << "NO vtx reweighting"    << endl;

  if( bveto )       cout << "Doing b-veto" << endl;
  else              cout << "NO b-veto"    << endl;

  if( mjjcut )      cout << "Doing mjj cut" << endl;
  else              cout << "NO mjj cut"    << endl;

  if( pt40 )        cout << "Require >=2 40 GeV jets with HT > 100 GeV"        << endl;
  else              cout << "DO NOT require >=2 40 GeV jets with HT > 100 GeV" << endl;

  int npass = 0;
  bookHistos();
  
  TObjArray *listOfFiles = chain->GetListOfFiles();

  unsigned int nEventsChain = 0;

  unsigned int nEvents = chain->GetEntries();
  nEventsChain = nEvents;
  unsigned int nEventsTotal = 0;

  if(debug) cout << "Begin file loop" << endl;

  TH1F* reweightHist[5];

  if( vtxreweight ){ 

    char* vtxfile = (char*) "vtxreweight_DoubleElectron_19fb.root";
    //if( TString(sample).Contains("DoubleElectron") ) vtxfile = (char*) "vtxreweight_DoubleElectron_9p2fb.root";
    //if( TString(sample).Contains("DoubleElectron") ) vtxfile = (char*) "vtxreweight_DoubleElectron_9p2fb_2012AB.root";
    //if( TString(sample).Contains("DoubleElectron") ) vtxfile = (char*) "vtxreweight_DoubleElectron_9p2fb_2012C.root";
    //if( TString(sample).Contains("DoubleElectron") ) vtxfile = (char*) "vtxreweight_DoubleElectron_19fb.root";

    cout << "Using vtx reweighting file " << vtxfile << endl;

    TFile *reweightFile = reweightFile = TFile::Open(vtxfile);
    reweightHist[0] = (TH1F*) reweightFile->Get("hratio20");
    reweightHist[1] = (TH1F*) reweightFile->Get("hratio30");
    reweightHist[2] = (TH1F*) reweightFile->Get("hratio50");
    reweightHist[3] = (TH1F*) reweightFile->Get("hratio70");
    reweightHist[4] = (TH1F*) reweightFile->Get("hratio90");
  }

  // file loop
  TIter fileIter(listOfFiles);

  TFile* currentFile = 0;

  while ((currentFile = (TFile*)fileIter.Next())){

    TFile f(currentFile->GetTitle());
    TTree *tree = (TTree*)f.Get("T1");
    //cms2.Init(tree);
    setBranches(tree);

    // event loop
    //unsigned int nEvents = tree->GetEntries();
    nEvents = tree->GetEntries();

    for (unsigned int event = 0 ; event < nEvents; ++event){

      tree->GetEntry(event);
      ++nEventsTotal;

      // progress feedback to user
      if (nEventsTotal % 1000 == 0){
            
        // xterm magic from L. Vacavant and A. Cerri
        if (isatty(1)){
                
          printf("\015\033[32m ---> \033[1m\033[31m%4.1f%%"
                 "\033[0m\033[32m <---\033[0m\015", (float)nEventsTotal/(nEventsChain*0.01));
          fflush(stdout);
        }
      }

      int vtxbin = -1;
      if( nvtx_ < 5 )                 vtxbin = 1;
      if( nvtx_ >=  5 && nvtx_ < 10 ) vtxbin = 2;
      if( nvtx_ >= 10 && nvtx_ < 15 ) vtxbin = 3;
      if( nvtx_ >= 15 && nvtx_ < 20 ) vtxbin = 4;
      if( nvtx_ >= 20 && nvtx_ < 25 ) vtxbin = 5;
      if( nvtx_ >= 25 && nvtx_ < 30 ) vtxbin = 6;
      if( nvtx_ >= 30 )               vtxbin = 7;

      int h20 = hlt20_;
      int h30 = hlt30_;
      int h50 = hlt50_;
      int h75 = hlt75_;
      int h90 = hlt90_;
      
      if( useHGGTriggers ){
	h20 = hgg22_;
	h30 = hgg36_;
	h50 = hgg50_;
	h75 = hgg75_;
	h90 = hgg90_;
      }

      //float mjj = ( *jet1_ + *jet2_ ).mass();
      //if( mjjcut && ( mjj < 70.0 || mjj > 110.0 ) )         continue; // apply dijet mass cut

      // event selection 
      if( nJets_ < 2 )                                      continue; // >=2 jets
      if( etg_ <  20 )                                      continue; // photon pt  > 20 GeV
      if( fabs( etag_ ) > 2 )                               continue; // photon eta < 2
      if( hoe_ > 0.1 )                                      continue; // H/E < 0.1
      if( photon_pixelseed_ == 1 )                          continue; // veto pixel match
      if( jetneutralemfrac_ < 0.7 )                         continue; // jet neutral EM fraction cut
      if( jet_pt_     - etg_ < -5 )                         continue; // pfjet cleaning
      //if( calojet_pt_ - etg_ < -5 )                         continue; // calojet cleaning
      if( elveto_ == 1 )                                    continue; // remove photons with nearby electrons
      if( maxleppt_ > 20.0 )                                continue; // veto leptons pt > 20 GeV
      if( acos( cos( phig_ - pfmetphi_ ) ) < 0.14 )         continue; // kill photons aligned with MET
      if( bveto && nbm_ > 0 )                               continue; // apply b-veto 
      //if( bveto && nbl_ > 0 )                               continue; // apply b-veto 
      if( pt40 && ( nJets40_ < 2 || ht40_ < 100.0 ) )       continue; // require 2 pT > 40 GeV jets with HT > 100 GeV
      if( !(csc_==0 && hbhe_==1 && hcallaser_==1 && ecaltp_==1 && trkfail_==1 && eebadsc_==1 && hbhenew_==1) ) continue; // MET filters
      //if( run_ > 196531 )                                   continue; // 2012 A+B
      //if( run_ <= 196531 )                                  continue; // 2012 C
      //if( run_ >= 197556 && run_ <= 198913 )                continue; // veto 2012C-PromptReco-v1
      // //if( pfjetid_ != 1 )                                                     continue; // pass PFJetID
      
      //if( h20 < 1 && h30 < 1 && h50 < 1 && h75 < 1 && h90 < 1 )                    continue; // require trig
      if( h20 < 1 && h50 < 1 && h75 < 1 && h90 < 1 )                    continue; // require trig

      int iJetBin;
      int iSumJetPtBin;

      if( pt40 ){
	iJetBin          = getJetBin       ( nJets40_    );
	iSumJetPtBin     = getSumJetPtBin  ( ht40_       );
      }
      else{
	iJetBin          = getJetBin       ( nJets_  );
	iSumJetPtBin     = getSumJetPtBin  ( ht_     );
      }

      int iBosonPtBin      = getBosonPtBin   ( etg_      );
      int iVtxBin          = getVtxBin       ( nvtx_     );
      float templateWeight = 1;

      /*
      //fill templates binned by njets, sumjetpt, boson pt        
      fillUnderOverFlow( tcmetTemplate[ iJetBin ][ iSumJetPtBin ][ iBosonPtBin ]    ,  tcmet_    , templateWeight );
      fillUnderOverFlow( pfmetTemplate[ iJetBin ][ iSumJetPtBin ][ iBosonPtBin ]    ,  pfmet_    , templateWeight );
      
      //fill templates binned by njets, sumjetpt, nVtx
      fillUnderOverFlow( tcmetTemplate_njets_ht_nvtx[ iJetBin ][ iSumJetPtBin ][ iVtxBin ]    ,  tcmet_    , templateWeight );
      fillUnderOverFlow( pfmetTemplate_njets_ht_nvtx[ iJetBin ][ iSumJetPtBin ][ iVtxBin ]    ,  pfmet_    , templateWeight );
    
      //fill templates binned by njets, sumjetpt
      fillUnderOverFlow( tcmetTemplate_combined[ iJetBin ][ iSumJetPtBin ]    ,  tcmet_    , templateWeight );
      fillUnderOverFlow( pfmetTemplate_combined[ iJetBin ][ iSumJetPtBin ]    ,  pfmet_    , templateWeight );
      */

      ++npass;

      int iTrigBin = -1;

      if( h20 > 0 )  fillUnderOverFlow( hphotonPt20 , etg_ , h20 );
      if( h30 > 0 )  fillUnderOverFlow( hphotonPt30 , etg_ , h30 );
      if( h50 > 0 )  fillUnderOverFlow( hphotonPt50 , etg_ , h50 );
      if( h75 > 0 )  fillUnderOverFlow( hphotonPt70 , etg_ , h75 );
      if( h90 > 0 )  fillUnderOverFlow( hphotonPt90 , etg_ , h90 );

      if     ( h90 > 0 )  templateWeight = h90;
      else if( h75 > 0 )  templateWeight = h75;
      else if( h50 > 0 )  templateWeight = h50;
      else if( h20 > 0 )  templateWeight = h20;

      if( etg_ > 90.0 ){
	//if( h90 > 0 ){
        //templateWeight = h90;
        iTrigBin = 4;

	fillUnderOverFlow( hphotonPt90_exc , etg_ , templateWeight );
	fillUnderOverFlow( hphotonAll , etg_  , templateWeight );
	fillUnderOverFlow( hnvtxPt90  , nvtx_ , templateWeight );
	fillUnderOverFlow( hnvtxAll   , nvtx_ , templateWeight );

	if( vtxreweight ) templateWeight *= reweightHist[4]->GetBinContent(vtxbin);

	//cout << "nvtx vtxbin weight " << nvtx_ << " " << vtxbin << " " << reweightHist[4]->GetBinContent(vtxbin) << endl;

        fillUnderOverFlow(   tcmetTemplate_photon[ iTrigBin ][ iJetBin ][ iSumJetPtBin ]    ,  tcmet_         , templateWeight );
        fillUnderOverFlow(   pfmetTemplate_photon[ iTrigBin ][ iJetBin ][ iSumJetPtBin ]    ,  pfmet_         , templateWeight );
        fillUnderOverFlow( t1pfmetTemplate_photon[ iTrigBin ][ iJetBin ][ iSumJetPtBin ]    ,  pfmett1_       , templateWeight );
        fillUnderOverFlow( t1newpfmetTemplate_photon[ iTrigBin ][ iJetBin ][ iSumJetPtBin ] ,  pfmett1new_    , templateWeight );
      }
      
      else if( etg_ > 75.0 ){
	//else if( h75 > 0 ){
        //templateWeight = h75;
        iTrigBin = 3;

	fillUnderOverFlow( hphotonPt70_exc , etg_ , templateWeight );
	fillUnderOverFlow( hphotonAll , etg_  , templateWeight );
	fillUnderOverFlow( hnvtxPt70  , nvtx_ , templateWeight );
	fillUnderOverFlow( hnvtxAll   , nvtx_ , templateWeight );

	if( vtxreweight ) templateWeight *= reweightHist[3]->GetBinContent(vtxbin);

        fillUnderOverFlow(   tcmetTemplate_photon[ iTrigBin ][ iJetBin ][ iSumJetPtBin ]    ,  tcmet_         , templateWeight );
        fillUnderOverFlow(   pfmetTemplate_photon[ iTrigBin ][ iJetBin ][ iSumJetPtBin ]    ,  pfmet_         , templateWeight );
        fillUnderOverFlow( t1pfmetTemplate_photon[ iTrigBin ][ iJetBin ][ iSumJetPtBin ]    ,  pfmett1_       , templateWeight );
        fillUnderOverFlow( t1newpfmetTemplate_photon[ iTrigBin ][ iJetBin ][ iSumJetPtBin ] ,  pfmett1new_    , templateWeight );
      }

      else if( etg_ > 50.0 ){
	//else if( h50 > 0 ){
        //templateWeight = h50;
        iTrigBin = 2;

	fillUnderOverFlow( hphotonPt50_exc , etg_ , templateWeight );
	fillUnderOverFlow( hphotonAll , etg_  , templateWeight );
	fillUnderOverFlow( hnvtxPt50  , nvtx_ , templateWeight );
	fillUnderOverFlow( hnvtxAll   , nvtx_ , templateWeight );

	if( vtxreweight ) templateWeight *= reweightHist[2]->GetBinContent(vtxbin);

        fillUnderOverFlow(   tcmetTemplate_photon[ iTrigBin ][ iJetBin ][ iSumJetPtBin ]    ,  tcmet_         , templateWeight );
        fillUnderOverFlow(   pfmetTemplate_photon[ iTrigBin ][ iJetBin ][ iSumJetPtBin ]    ,  pfmet_         , templateWeight );
        fillUnderOverFlow( t1pfmetTemplate_photon[ iTrigBin ][ iJetBin ][ iSumJetPtBin ]    ,  pfmett1_       , templateWeight );
        fillUnderOverFlow( t1newpfmetTemplate_photon[ iTrigBin ][ iJetBin ][ iSumJetPtBin ] ,  pfmett1new_    , templateWeight );
      }

      else if( etg_ > 36.0 ){
	//else if( h30 > 0 ){
	//templateWeight = h30;
	iTrigBin = 1;

	fillUnderOverFlow( hphotonPt30_exc , etg_ , templateWeight );
	fillUnderOverFlow( hphotonAll , etg_  , templateWeight );
	fillUnderOverFlow( hnvtxPt30  , nvtx_ , templateWeight );
	fillUnderOverFlow( hnvtxAll   , nvtx_ , templateWeight );

	if( vtxreweight ) templateWeight *= reweightHist[1]->GetBinContent(vtxbin);

	fillUnderOverFlow(   tcmetTemplate_photon[ iTrigBin ][ iJetBin ][ iSumJetPtBin ]    ,  tcmet_         , templateWeight );
	fillUnderOverFlow(   pfmetTemplate_photon[ iTrigBin ][ iJetBin ][ iSumJetPtBin ]    ,  pfmet_         , templateWeight );
	fillUnderOverFlow( t1pfmetTemplate_photon[ iTrigBin ][ iJetBin ][ iSumJetPtBin ]    ,  pfmett1_       , templateWeight );
	fillUnderOverFlow( t1newpfmetTemplate_photon[ iTrigBin ][ iJetBin ][ iSumJetPtBin ] ,  pfmett1new_    , templateWeight );
      }

      else if( etg_ > 20.0 ){
	//else if( h20 > 0 ){
        //templateWeight = h20;
        iTrigBin = 0;

	fillUnderOverFlow( hphotonPt20_exc , etg_ , templateWeight );
	fillUnderOverFlow( hphotonAll , etg_  , templateWeight );
	fillUnderOverFlow( hnvtxPt20  , nvtx_ , templateWeight );
	fillUnderOverFlow( hnvtxAll   , nvtx_ , templateWeight );

	if( vtxreweight ) templateWeight *= reweightHist[0]->GetBinContent(vtxbin);

        fillUnderOverFlow(   tcmetTemplate_photon[ iTrigBin ][ iJetBin ][ iSumJetPtBin ]    ,  tcmet_         , templateWeight );
        fillUnderOverFlow(   pfmetTemplate_photon[ iTrigBin ][ iJetBin ][ iSumJetPtBin ]    ,  pfmet_         , templateWeight );
        fillUnderOverFlow( t1pfmetTemplate_photon[ iTrigBin ][ iJetBin ][ iSumJetPtBin ]    ,  pfmett1_       , templateWeight );
        fillUnderOverFlow( t1newpfmetTemplate_photon[ iTrigBin ][ iJetBin ][ iSumJetPtBin ] ,  pfmett1new_    , templateWeight );
      }

      else{
	cout << "NO TRIGGERS PASS!!!" << endl;
	exit(0);
      }

    } // end loop over events
  } // end loop over files
      


  cout << npass << " events passing selection" << endl;
  if (nEventsChain != nEventsTotal)
    std::cout << "ERROR: number of events from files is not equal to total number of events" << std::endl;
  
  //-------------------------------------------
  // normalize templates
  //-------------------------------------------
   
    for( int iJetBin = 0 ; iJetBin < nJetBins ; iJetBin++ ){
      for( int iSumJetPtBin = 0 ; iSumJetPtBin < nSumJetPtBins ; iSumJetPtBin++ ){
        for( int iBosonPtBin = 0 ; iBosonPtBin < nBosonPtBins ; iBosonPtBin++ ){
          
          float scale = tcmetTemplate[ iJetBin ][ iSumJetPtBin ][ iBosonPtBin ] -> Integral();
          if( scale > 0 )  tcmetTemplate[ iJetBin ][ iSumJetPtBin ][ iBosonPtBin ] -> Scale ( 1. / scale );
          
          scale = pfmetTemplate[ iJetBin ][ iSumJetPtBin ][ iBosonPtBin ] -> Integral();
          if( scale > 0 )  pfmetTemplate[ iJetBin ][ iSumJetPtBin ][ iBosonPtBin ] -> Scale ( 1. / scale );
          
        }
      }
    }

    for( int iJetBin = 0 ; iJetBin < nJetBins ; iJetBin++ ){
      for( int iSumJetPtBin = 0 ; iSumJetPtBin < nSumJetPtBins ; iSumJetPtBin++ ){
        for( int iVtxBin = 0 ; iVtxBin < nVtxBins ; iVtxBin++ ){
          
          float scale = tcmetTemplate_njets_ht_nvtx[ iJetBin ][ iSumJetPtBin ][ iVtxBin ] -> Integral();
          if( scale > 0 )  tcmetTemplate_njets_ht_nvtx[ iJetBin ][ iSumJetPtBin ][ iVtxBin ] -> Scale ( 1. / scale );
          
          scale = pfmetTemplate_njets_ht_nvtx[ iJetBin ][ iSumJetPtBin ][ iVtxBin ] -> Integral();
          if( scale > 0 )  pfmetTemplate_njets_ht_nvtx[ iJetBin ][ iSumJetPtBin ][ iVtxBin ] -> Scale ( 1. / scale );
          
        }
      }
    }

    for( int iJetBin = 0 ; iJetBin < nJetBins ; iJetBin++ ){
      for( int iSumJetPtBin = 0 ; iSumJetPtBin < nSumJetPtBins ; iSumJetPtBin++ ){
        
        float scale = tcmetTemplate_combined[ iJetBin ][ iSumJetPtBin ] -> Integral();
        if( scale > 0 )  tcmetTemplate_combined[ iJetBin ][ iSumJetPtBin ] -> Scale ( 1. / scale );
      
        scale = pfmetTemplate_combined[ iJetBin ][ iSumJetPtBin ] -> Integral();
        if( scale > 0 )  pfmetTemplate_combined[ iJetBin ][ iSumJetPtBin ] -> Scale ( 1. / scale );
        
        
      }
    }

    for( int iTrigBin = 0 ; iTrigBin < 5 ; ++iTrigBin ){
      for( int iJetBin = 0 ; iJetBin < nJetBins ; iJetBin++ ){
        for( int iSumJetPtBin = 0 ; iSumJetPtBin < nSumJetPtBins ; iSumJetPtBin++ ){
          
          float scale = tcmetTemplate_photon[ iTrigBin ][ iJetBin ][ iSumJetPtBin ] -> Integral();
          if( scale > 0 )  tcmetTemplate_photon[ iTrigBin ][ iJetBin ][ iSumJetPtBin ] -> Scale ( 1. / scale );
          
          scale = pfmetTemplate_photon[ iTrigBin ][ iJetBin ][ iSumJetPtBin ] -> Integral();
          if( scale > 0 )  pfmetTemplate_photon[ iTrigBin ][ iJetBin ][ iSumJetPtBin ] -> Scale ( 1. / scale );

          scale = t1pfmetTemplate_photon[ iTrigBin ][ iJetBin ][ iSumJetPtBin ] -> Integral();
          if( scale > 0 )  t1pfmetTemplate_photon[ iTrigBin ][ iJetBin ][ iSumJetPtBin ] -> Scale ( 1. / scale );

          scale = t1newpfmetTemplate_photon[ iTrigBin ][ iJetBin ][ iSumJetPtBin ] -> Integral();
          if( scale > 0 )  t1newpfmetTemplate_photon[ iTrigBin ][ iJetBin ][ iSumJetPtBin ] -> Scale ( 1. / scale );
          
        }
      }
    }


    // make histos rootfile
    TDirectory *rootdir = gDirectory->GetDirectory("Rint:");
    rootdir->cd();

    char* vtxchar = "";
    if( vtxreweight ) vtxchar = "_vtxreweight";

    char* bvetochar = "";
    if( bveto ) bvetochar = "_bveto";

    char* mjjchar = "";
    if( mjjcut ) mjjchar = "_mjjcut";

    char* pt40char = "";
    //if( pt40 ) pt40char = "_pt40";
    //if( pt40 ) pt40char = "_pt40_2012AB";
    if( pt40 ) pt40char = "_pt40_2012C";

    cout << "Writing templates to " << Form("../photon_output/%s/%s_templates%s%s%s%s.root",iter,sample,vtxchar,bvetochar,mjjchar,pt40char) << endl;
    saveHist(Form("../photon_output/%s/%s_templates%s%s%s%s.root",iter,sample,vtxchar,bvetochar,mjjchar,pt40char));

    //deleteHistos();

    // TFile* fout = TFile::Open(Form("../photon_output/%s/%s_templateHistos.root",iter,sample),"RECREATE");
    // fout->cd();
    // hphotonPt20->Write();
    // hphotonPt30->Write();
    // hphotonPt50->Write();
    // hphotonPt70->Write();
    // hphotonPt90->Write();
    // hphotonAll->Write();
    // fout->Close();
  
} // end ScanChain
Example #26
0
void babylooper::ScanChain (TChain* chain, const char* version, const char* prefix, bool isData){

  char* outversion = (char*) "V00-00-09";
  bool doSigCont   = true;

  TObjArray *listOfFiles = chain->GetListOfFiles();
  unsigned int nEventsTotal = 0;

  //---------------------------------------
  // declare histograms
  //---------------------------------------

  const int   nm0points    = 100;
  const float m0min        = 20.;
  const float m0max        = 2020.;
  const int   nm12points   = 38;
  const float m12min       = 20.;
  const float m12max       = 780.;

  const unsigned int nbins = 6;

  float KKC[nbins] = { 2.74 , 2.74 , 2.59 , 2.59 , 1.81 , 1.81 };

  TH2F* h[nbins];
  TH2F* hptll[nbins];
  TH2F* hjup[nbins];
  TH2F* hjdn[nbins];
  //TH2F* hptlljup[nbins];
  //TH2F* hptlljdn[nbins];
  TH2F* hkup[nbins];
  TH2F* hkdn[nbins];

  for( unsigned int i = 0 ; i < nbins ; ++i ){
    h[i]        = new TH2F( Form("h_%i",i)        , Form("h_%i",i)           , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
    hjup[i]     = new TH2F( Form("hjup_%i",i)     , Form("hjup_%i",i)        , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
    hjdn[i]     = new TH2F( Form("hjdn_%i",i)     , Form("hjdn_%i",i)        , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
    hkup[i]     = new TH2F( Form("hkup_%i",i)     , Form("hkup_%i",i)        , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
    hkdn[i]     = new TH2F( Form("hkdn_%i",i)     , Form("hkdn_%i",i)        , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
    hptll[i]    = new TH2F( Form("hptll_%i",i)    , Form("hptll_%i",i)       , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
    //hptlljup[i] = new TH2F( Form("hptlljup_%i",i) , Form("hptlljup_%i",i)    , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
    //hptlljdn[i] = new TH2F( Form("hptlljdn_%i",i) , Form("hptlljdn_%i",i)    , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);

    h[i]    ->Sumw2();
    hjup[i] ->Sumw2();
    hjdn[i] ->Sumw2();
    hkup[i] ->Sumw2();
    hkdn[i] ->Sumw2();

    hptll[i]->Sumw2();
    //hptlljup[i]->Sumw2();
    //hptlljdn[i]->Sumw2();
  }

  TH2F* hall    = new TH2F( "hall"    , "hall"    , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
  TH2F* hkupall = new TH2F( "hkupall" , "hkupall" , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
  TH2F* hjdnall = new TH2F( "hjdnall" , "hjdnall" , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
  TH2F* hkdnall = new TH2F( "hkdnall" , "hkdnall" , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
  
  hall->Sumw2();
  hkupall->Sumw2();
  hkdnall->Sumw2();


  // file loop
  TIter fileIter(listOfFiles);
  TFile* currentFile = 0;
  while ((currentFile = (TFile*)fileIter.Next())){
    
    TFile f(currentFile->GetTitle());
    TTree *tree = (TTree*)f.Get("t");

    setBranches(tree);

    // event loop
    unsigned int nEvents = tree->GetEntries();
 
    for (unsigned int event = 0 ; event < nEvents; ++event){
        
      tree->GetEntry(event);
      ++nEventsTotal;

      // progress feedback to user
      if (nEventsTotal % 1000 == 0){
            
        // xterm magic from L. Vacavant and A. Cerri
        if (isatty(1)){
                
          printf("\015\033[32m ---> \033[1m\033[31m%4.1f%%"
                 "\033[0m\033[32m <---\033[0m\015", (float)nEventsTotal/(nEvents*0.01));
          fflush(stdout);
        }
      }
      
      float weight      = weight_ * 4.7 * ndavtxweight_ * trgeff_ * lepscale_;

      bool presel	= pfmet_>50 && njets_>=2 && ht_>100 && passz_==0;
      bool preselptll	= pfmet_>50 && njets_>=2 && ht_>100 && passz_==0 && ( (leptype_==2) || (leptype_<2 && pfmet_>75) );
      bool preseljup	= pfmetUp_>50   && njetsUp_>=2   && htUp_>100   && passz_==0;
      bool preseljdn	= pfmetDown_>50 && njetsDown_>=2 && htDown_>100 && passz_==0;
      bool SF		= leptype_==0 || leptype_==1;
      bool OF		= leptype_==2;

      bool sig		= (ht_>300 && pfmet_>275) || (ht_>600 && pfmet_>200);  
      bool sigdn	= (htDown_>300 && pfmetDown_>275) || (htDown_>600 && pfmetDown_>200);

      bool SR1		= ht_>300 && ht_<600 && pfmet_>275;
      bool SR2		= ht_>600 && pfmet_>275;
      bool SR3		= ht_>600 && pfmet_>200 && pfmet_<275;

      bool SR1ptll	= ht_>300 && ht_<600 && dilpt_>275;
      bool SR2ptll	= ht_>600 && dilpt_>275;
      bool SR3ptll	= ht_>600 && dilpt_>200 && dilpt_<275;

      bool SR1jup	= htUp_>300 && htUp_<600 && pfmetUp_>275;
      bool SR2jup	= htUp_>600 && pfmetUp_>275;
      bool SR3jup	= htUp_>600 && pfmetUp_>200 && pfmetUp_<275;

      // bool SR1ptlljup	= htUp_>300 && htUp_<600 && dilpt_>275;
      // bool SR2ptlljup	= htUp_>600 && dilpt_>275;
      // bool SR3ptlljup	= htUp_>600 && dilpt_>200 && dilpt_<275;

      bool SR1jdn	= htDown_>300 && htDown_<600 && pfmetDown_>275;
      bool SR2jdn	= htDown_>600 && pfmetDown_>275;
      bool SR3jdn	= htDown_>600 && pfmetDown_>200 && pfmetDown_<275;

      // bool SR1ptlljdn	= htDown_>300 && htDown_<600 && dilpt_>275;
      // bool SR2ptlljdn	= htDown_>600 && dilpt_>275;
      // bool SR3ptlljdn	= htDown_>600 && dilpt_>200 && dilpt_<275;

      //----------------------------
      // nominal
      //----------------------------

      if( presel ){
	if( SR1 && SF ) h[0]->Fill( m0_ , m12_ , weight );
	if( SR1 && OF ) h[1]->Fill( m0_ , m12_ , weight );
	if( SR2 && SF ) h[2]->Fill( m0_ , m12_ , weight );
	if( SR2 && OF ) h[3]->Fill( m0_ , m12_ , weight );
	if( SR3 && SF ) h[4]->Fill( m0_ , m12_ , weight );
	if( SR3 && OF ) h[5]->Fill( m0_ , m12_ , weight );
	if( sig       ) hall->Fill( m0_ , m12_ , weight );
      }

      // ch->Draw("m12:m0>>h_0"        , (presel + SR1 + SF) * weight );
      // ch->Draw("m12:m0>>h_1"        , (presel + SR1 + OF) * weight );
      // ch->Draw("m12:m0>>h_2"        , (presel + SR2 + SF) * weight );
      // ch->Draw("m12:m0>>h_3"        , (presel + SR2 + OF) * weight );
      // ch->Draw("m12:m0>>h_4"        , (presel + SR3 + SF) * weight );
      // ch->Draw("m12:m0>>h_5"        , (presel + SR3 + OF) * weight );
      // ch->Draw("m12:m0>>hall"       , (presel + sig     ) * weight );

      //----------------------------
      // ptll control region
      //----------------------------

      if( preselptll ){
	if( SR1ptll && SF ) hptll[0]->Fill( m0_ , m12_ , weight );
	if( SR1ptll && OF ) hptll[1]->Fill( m0_ , m12_ , weight );
	if( SR2ptll && SF ) hptll[2]->Fill( m0_ , m12_ , weight );
	if( SR2ptll && OF ) hptll[3]->Fill( m0_ , m12_ , weight );
	if( SR3ptll && SF ) hptll[4]->Fill( m0_ , m12_ , weight );
	if( SR3ptll && OF ) hptll[5]->Fill( m0_ , m12_ , weight );
      }

      // ch->Draw("m12:m0>>hptll_0"    , (preselptll + SR1ptll) * weight );
      // ch->Draw("m12:m0>>hptll_1"    , (preselptll + SR1ptll) * weight );
      // ch->Draw("m12:m0>>hptll_2"    , (preselptll + SR2ptll) * weight );
      // ch->Draw("m12:m0>>hptll_3"    , (preselptll + SR2ptll) * weight );
      // ch->Draw("m12:m0>>hptll_4"    , (preselptll + SR3ptll) * weight );
      // ch->Draw("m12:m0>>hptll_5"    , (preselptll + SR3ptll) * weight );

      //----------------------------
      // JES up
      //----------------------------

      if( preseljup ){
	if( SR1jup && SF ) hjup[0]->Fill( m0_ , m12_ , weight );
	if( SR1jup && OF ) hjup[1]->Fill( m0_ , m12_ , weight );
	if( SR2jup && SF ) hjup[2]->Fill( m0_ , m12_ , weight );
	if( SR2jup && OF ) hjup[3]->Fill( m0_ , m12_ , weight );
	if( SR3jup && SF ) hjup[4]->Fill( m0_ , m12_ , weight );
	if( SR3jup && OF ) hjup[5]->Fill( m0_ , m12_ , weight );
      }

      //cout << "Filling JES up histos" << endl;
      // ch->Draw("m12:m0>>hjup_0"     , (preseljup + SR1jup + SF) * weight );
      // ch->Draw("m12:m0>>hjup_1"     , (preseljup + SR1jup + OF) * weight );
      // ch->Draw("m12:m0>>hjup_2"     , (preseljup + SR2jup + SF) * weight );
      // ch->Draw("m12:m0>>hjup_3"     , (preseljup + SR2jup + OF) * weight );
      // ch->Draw("m12:m0>>hjup_4"     , (preseljup + SR3jup + SF) * weight );
      // ch->Draw("m12:m0>>hjup_5"     , (preseljup + SR3jup + OF) * weight );

      //----------------------------
      // JES down
      //----------------------------

      if( preseljdn ){
	if( SR1jdn && SF ) hjdn[0]->Fill( m0_ , m12_ , weight );
	if( SR1jdn && OF ) hjdn[1]->Fill( m0_ , m12_ , weight );
	if( SR2jdn && SF ) hjdn[2]->Fill( m0_ , m12_ , weight );
	if( SR2jdn && OF ) hjdn[3]->Fill( m0_ , m12_ , weight );
	if( SR3jdn && SF ) hjdn[4]->Fill( m0_ , m12_ , weight );
	if( SR3jdn && OF ) hjdn[5]->Fill( m0_ , m12_ , weight );
	if( sigdn        ) hjdnall->Fill( m0_ , m12_ , weight );
      }
  
      //JES down
      // cout << "Filling JES dn histos" << endl;
      // ch->Draw("m12:m0>>hjdn_0"     , (preseljdn + SR1jdn + SF) * weight );
      // ch->Draw("m12:m0>>hjdn_1"     , (preseljdn + SR1jdn + OF) * weight );
      // ch->Draw("m12:m0>>hjdn_2"     , (preseljdn + SR2jdn + SF) * weight );
      // ch->Draw("m12:m0>>hjdn_3"     , (preseljdn + SR2jdn + OF) * weight );
      // ch->Draw("m12:m0>>hjdn_4"     , (preseljdn + SR3jdn + SF) * weight );
      // ch->Draw("m12:m0>>hjdn_5"     , (preseljdn + SR3jdn + OF) * weight );
      // ch->Draw("m12:m0>>hjdnall"    , (preseljdn + sigdn      ) * weight );

      
    }// end loop over events
  } // end loop over files
  

  ofstream* doScript = new ofstream();
  doScript->open(Form("cards/%s/doLimits.sh",outversion));

  ofstream* doScript_CLs = new ofstream();
  doScript_CLs->open(Form("cards/%s/doLimits_CLs.sh",outversion));

  ofstream* doScript_CLs1 = new ofstream();
  doScript_CLs1->open(Form("cards/%s/doLimits_CLs1.sh",outversion));

  ofstream* doScript_CLs2 = new ofstream();
  doScript_CLs2->open(Form("cards/%s/doLimits_CLs2.sh",outversion));

  ofstream* doScript_CLs3 = new ofstream();
  doScript_CLs3->open(Form("cards/%s/doLimits_CLs3.sh",outversion));

  ofstream* doScript_CLs4 = new ofstream();
  doScript_CLs4->open(Form("cards/%s/doLimits_CLs4.sh",outversion));

  ofstream* filelist = new ofstream();
  filelist->open(Form("cards/%s/file_list.txt",outversion));

  ofstream* filelist_CLs = new ofstream();
  filelist_CLs->open(Form("cards/%s/file_list_CLs.txt",outversion));


  //------------------------------------------
  // loop over CMSSM points
  //------------------------------------------

  int counter = 0;

  for( int m0bin = 1 ; m0bin <= hall->GetXaxis()->GetNbins() ; m0bin++ ){
    for( int m12bin = 1 ; m12bin <= hall->GetYaxis()->GetNbins() ; m12bin++ ){

      //------------------------------------------
      // require nentries = 10
      //------------------------------------------
      
      //int ngen = hscan->GetBinContent(m0bin,m12bin);
      //if( ngen != 10000 )  continue;
      
      //int m0  = hall->GetXaxis()->GetBinCenter(m0bin);
      //int m12 = hall->GetXaxis()->GetBinCenter(m12bin);

      //if( m0 > 1000 )                                  continue;
      if( hjdnall->GetBinContent(m0bin,m12bin) < 1e-10 ) continue;


      float nom = hall->GetBinContent(m0bin,m12bin);
      float kdn = hkupall->GetBinContent(m0bin,m12bin);
      float kup = hkdnall->GetBinContent(m0bin,m12bin);
	     
      float dup = kup / nom - 1;
      float ddn = 1 - kdn / nom;
      float kerr = 0.5 * ( dup + ddn );

      //---------------------------------------
      // make root file
      //---------------------------------------

      TH1F* histo_CMSSM               = new TH1F( Form("histo_CMSSM_%i_%i"              ,m0bin,m12bin) , Form("histo_CMSSM_%i_%i"              ,m0bin,m12bin) , nbins,0,nbins);
      TH1F* histo_CMSSM_JES_shapeUp   = new TH1F( Form("histo_CMSSM_%i_%i_JES_shapeUp"  ,m0bin,m12bin) , Form("histo_CMSSM_%i_%i_JES_shapeUp"  ,m0bin,m12bin) , nbins,0,nbins);
      TH1F* histo_CMSSM_JES_shapeDown = new TH1F( Form("histo_CMSSM_%i_%i_JES_shapeDown",m0bin,m12bin) , Form("histo_CMSSM_%i_%i_JES_shapeDown",m0bin,m12bin) , nbins,0,nbins);

      float sigtot    = 0;
      float sigtotjdn = 0;

      for( unsigned int ibin = 0 ; ibin < nbins ; ibin++ ){
	float yieldnom = h[ibin]->GetBinContent(m0bin,m12bin);
	float yieldjup = hjup[ibin]->GetBinContent(m0bin,m12bin);
	float yieldjdn = hjdn[ibin]->GetBinContent(m0bin,m12bin);

	if( doSigCont ){
	  float ptll = hptll[ibin]->GetBinContent(m0bin,m12bin) * 0.5 * KKC[ibin];

	  if( ptll < yieldnom ){
	    float scale = (yieldnom-ptll)/yieldnom;
	    yieldnom -= ptll;
	    yieldjup *= scale;
	    yieldjdn *= scale;
	  }
	  
	  else{
	    yieldnom = 0.0;
	    yieldjup = 0.0;
	    yieldjdn = 0.0;
	  }

	}

	sigtot    += yieldnom;
	sigtotjdn += yieldjdn;

	histo_CMSSM->SetBinContent              ( ibin + 1 , yieldnom );
	histo_CMSSM_JES_shapeUp->SetBinContent  ( ibin + 1 , yieldjup );
	histo_CMSSM_JES_shapeDown->SetBinContent( ibin + 1 , yieldjdn );
      }

      if( sigtotjdn < 1e-10 ) continue;
      if( sigtot    < 2     ) continue;
      if( sigtot    > 80    ) continue;

      //float sigtot = hall->GetBinContent(m0bin,m12bin);

      counter++;

      char* fitoptions = "-M Hybrid --freq  --nToysForCLsb 1500 --nToysForCLb 500  --scanRs 1 -vR [0.2,5,x1.1]";
      //char* fitoptions = "-M Hybrid --freq --ExpectationHints Asymptotic --scanRs 1 --freq --nToysForCLsb 3000 --nToysForCLb 1500 --seed 1234 -rMin 0 -rMax 5";

      *doScript << Form("../../../../test/lands.exe -M Bayesian -d CMSSM_%i_%i.txt",m0bin,m12bin)         << endl;

      *doScript_CLs << Form("../../../../test/lands.exe -d CMSSM_%i_%i.txt %s  -n CMSSM_%i_%i",m0bin,m12bin,fitoptions,m0bin,m12bin) << endl;

       if( counter%4 == 0 ) *doScript_CLs1 << Form("../../../../test/lands.exe -d CMSSM_%i_%i.txt %s  -n CMSSM_%i_%i",m0bin,m12bin,fitoptions,m0bin,m12bin) << endl;

       if( counter%4 == 1 ) *doScript_CLs2 << Form("../../../../test/lands.exe -d CMSSM_%i_%i.txt %s  -n CMSSM_%i_%i",m0bin,m12bin,fitoptions,m0bin,m12bin) << endl;

       if( counter%4 == 2 ) *doScript_CLs3 << Form("../../../../test/lands.exe -d CMSSM_%i_%i.txt %s  -n CMSSM_%i_%i",m0bin,m12bin,fitoptions,m0bin,m12bin) << endl;

       if( counter%4 == 3 ) *doScript_CLs4 << Form("../../../../test/lands.exe -d CMSSM_%i_%i.txt %s  -n CMSSM_%i_%i",m0bin,m12bin,fitoptions,m0bin,m12bin) << endl;

      *filelist << Form("cards/%s/CMSSM_%i_%i.txt_Bayesian_bysObsLimit.root",outversion,m0bin,m12bin)        << endl;

      *filelist_CLs << Form("cards/%s/CMSSM_%i_%i_m2lnQ2.root",outversion,m0bin,m12bin)        << endl;

      printCard( Form("CMSSM_%i_%i",m0bin,m12bin) , sigtot ,  outversion );
      
      //signal regions                         R1(SF)      R1(OF)    R2(SF)     R2(OF)      R3(SF)   R3(OF)
      int     data_yield[nbins]           = {    9     ,    10    ,    6     ,    5     ,     5    ,    13  };
      float   bkg_yield[nbins]            = {   5.7    ,    5.7   ,   5.2    ,   5.2    ,    5.6   ,   5.6  };
      float   bkg_syst[nbins]             = {   2.8    ,    2.8   ,   1.9    ,   1.9    ,    2.1   ,   2.1  };
      float   bkg_stat[nbins]             = {   5.1    ,    5.1   ,   4.1    ,   4.1    ,    3.4   ,   3.4  };

      TH1F* histo_Data = new TH1F("histo_Data","histo_Data",nbins,0,nbins);

      for( unsigned int ibin = 0 ; ibin < nbins ; ibin++){
	histo_Data->SetBinContent( ibin+1 , data_yield[ibin] );
      }

      TH1F* histo_bkg               = new TH1F("histo_bkg","histo_bkg",nbins,0,nbins);
      TH1F* histo_bkg_statUp        = new TH1F("histo_bkg_statUp"  ,"histo_bkg_statUp"  ,nbins,0,nbins);
      TH1F* histo_bkg_statDown      = new TH1F("histo_bkg_statDown","histo_bkg_statDown",nbins,0,nbins);
      TH1F* histo_bkg_systUp        = new TH1F("histo_bkg_systUp"  ,"histo_bkg_systUp"  ,nbins,0,nbins);
      TH1F* histo_bkg_systDown      = new TH1F("histo_bkg_systDown","histo_bkg_systDown",nbins,0,nbins);
      
      for( unsigned int ibin = 0 ; ibin < nbins ; ibin++){
	histo_bkg               -> SetBinContent(ibin+1,bkg_yield[ibin]);
	histo_bkg_statUp        -> SetBinContent(ibin+1, bkg_yield[ibin] + bkg_stat[ibin] );
	histo_bkg_statDown      -> SetBinContent(ibin+1, TMath::Max(bkg_yield[ibin] - bkg_stat[ibin],(float)0.0) );
	histo_bkg_systUp        -> SetBinContent(ibin+1, bkg_yield[ibin] + bkg_syst[ibin] );
	histo_bkg_systDown      -> SetBinContent(ibin+1, TMath::Max(bkg_yield[ibin] - bkg_syst[ibin],(float)0.0) );
      }


      TFile *f = TFile::Open( Form("rootfiles/%s/CMSSM_%i_%i.root",outversion,m0bin,m12bin) , "RECREATE");
      f->cd();
      histo_Data->Write();
      histo_bkg->Write();
      histo_bkg_statUp->Write();
      histo_bkg_statDown->Write();
      histo_bkg_systUp->Write();
      histo_bkg_systDown->Write();
      histo_CMSSM->Write();
      histo_CMSSM_JES_shapeUp->Write();
      histo_CMSSM_JES_shapeDown->Write();
      f->Close();

      delete histo_Data;
      delete histo_bkg;
      delete histo_bkg_statUp;
      delete histo_bkg_statDown;
      delete histo_bkg_systUp;
      delete histo_bkg_systDown;
      delete histo_CMSSM;
      delete histo_CMSSM_JES_shapeUp;
      delete histo_CMSSM_JES_shapeDown;
    }
  }

  cout << "Looped over " << nEventsTotal << " events" << endl;
  
  TFile* f = TFile::Open("histos.root","RECREATE");
  f->cd();
  for( unsigned int i = 0 ; i < nbins ; ++i ){
    h[i]        ->Write();
    hjup[i]     ->Write();
    hjdn[i]     ->Write();
    hkup[i]     ->Write();
    hkdn[i]     ->Write();
    hptll[i]    ->Write();
    //hptlljup[i] ->Write();
    //hptlljdn[i] ->Write();
  }
  f->Close();

} // end ScanChain