コード例 #1
0
ファイル: twodimvar.C プロジェクト: asmagina1995/roottest
void tread(const char* input) {

  std::cout << "Input  file : " << input << std::endl;

  A*   a = new A();
  
  TFile* tfi = new TFile(input,"READ");
  TTree* tree = (TTree*)tfi->Get("tree");
  
  tree->SetBranchAddress("A",&a);

  Int_t nevent = Int_t(tree->GetEntries()); 

  for (Int_t jentry=0; jentry<nevent;jentry++) {

   Int_t ientry = tree->LoadTree(jentry);
   if (ientry < 0) break;
   tree->GetEntry(jentry);
   //a->Dump();
   a->Dump2();
  }
  tfi->Close();

  delete a;
  
}
コード例 #2
0
ファイル: CalibTree.C プロジェクト: tj710/TTEmulator
Long64_t CalibTree::LoadTree(Long64_t entry) {
  // Set the environment to read one entry
  if (!fChain) return -5;
  Long64_t centry = fChain->LoadTree(entry);
  if (centry < 0) return centry;
  if (fChain->GetTreeNumber() != fCurrent) {
    fCurrent = fChain->GetTreeNumber();
    Notify();
  }
  return centry;
}
コード例 #3
0
ファイル: CalibSort.C プロジェクト: owen234/cmssw
Long64_t CalibSort::LoadTree(Long64_t entry) {
  // Set the environment to read one entry
  if (!fChain) return -5;
  Long64_t centry = fChain->LoadTree(entry);
  if (centry < 0) return centry;
  if (!fChain->InheritsFrom(TChain::Class()))  return centry;
  TChain *chain = (TChain*)fChain;
  if (chain->GetTreeNumber() != fCurrent) {
    fCurrent = chain->GetTreeNumber();
    Notify();
  }
  return centry;
}
コード例 #4
0
ファイル: runcircular.C プロジェクト: asmagina1995/roottest
int runcircular() {
   int i = 0;
   int j = 1;
   // int k = 2;;
   TTree *master = new TTree("master","master");
   master->Branch("i",&i);
   TTree *slave = new TTree("slave","slave");
   slave->Branch("j",&j);
   for(int s=0; s<10; ++s) master->Fill();
   for(int s=0; s<15; ++s) slave->Fill();
   cout << "Alone\n";
   cout << master->LoadTree(3) << endl;
   cout << master->LoadTree(12) << endl;
   cout << master->LoadTree(20) << endl;

   master->AddFriend(slave);
   cout << "Friend\n";
   cout << master->LoadTree(3) << endl;
   cout << master->LoadTree(12) << endl;
   cout << master->LoadTree(20) << endl;

   slave->AddFriend(master);
   cout << "Indirect Circular\n";
   cout << master->LoadTree(3) << endl;
   cout << master->LoadTree(12) << endl;
   cout << master->LoadTree(20) << endl;

   master->AddFriend(master);
   cout << "Direct Circular\n";
   cout << master->LoadTree(3) << endl;
   cout << master->LoadTree(12) << endl;
   cout << master->LoadTree(20) << endl;

   if (master->LoadTree(20) != -2) {
     cout << "A circular TTree friendship leads to LoadTree incorrectly returning: " << master->LoadTree(20) << " when it should return -2 (out of bound entry)\n";
     return 1;
   }
   return 0; 
}
コード例 #5
0
ファイル: h2fastnew_main.cpp プロジェクト: nevermatch/davix
void h2fast(const char *url , Bool_t draw=kFALSE, Long64_t cachesize=10000000, Int_t learn=1) {
// gEnv->SetValue("TFile.DavixLog", 10);
//  gDebug= 0x02;
   TStopwatch sw;
   TTree* T = NULL;
   sw.Start();
   Long64_t oldb = TFile::GetFileBytesRead();
   TFile *f = TFile::Open(url);
  
   if (!f || f->IsZombie()) {
      printf("File h1big.root does not exist\n");
      exit (-1);
   }
   

//   TTreeCacheUnzip::SetParallelUnzip(TTreeCacheUnzip::kEnable);

   T= (TTree*)f->Get("h42");
   Long64_t nentries = T->GetEntries();
   T->SetCacheSize(cachesize);
   TTreeCache::SetLearnEntries(learn);
   TFileCacheRead *tpf = f->GetCacheRead();
   //tpf->SetEntryRange(0,nentries);
   
   if (draw) T->Draw("rawtr","E33>20");
   else {
      TBranch *brawtr = T->GetBranch("rawtr");
      TBranch *bE33   = T->GetBranch("E33");
      Float_t E33; 
      bE33->SetAddress(&E33);
      for (Long64_t i=0;i<nentries;i++) {
         T->LoadTree(i);
         bE33->GetEntry(i);
         if (E33 > 0) brawtr->GetEntry(i);
      } 
   } 
   if (tpf) tpf->Print();
   printf("Bytes read = %lld\n",TFile::GetFileBytesRead()-oldb);
   printf("Real Time = %7.3f s, CPUtime = %7.3f s\n",sw.RealTime(),sw.CpuTime());
   delete T;
   delete f;
}
コード例 #6
0
ファイル: ScanChain.C プロジェクト: mialiu149/StopLoopers
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;
}
コード例 #7
0
void PlotSIPversusT_byRUNS(string tag="PromptGT"){

  //gROOT->ProcessLine(".L TkAlStyle.cc+");
  //TkAlStyle::set(INPROGRESS);	// set publication status

  //gROOT->ProcessLine(".L ./setTDRStyle.C++");
  //setTDRStyle();

  //string tag="ORIGINAL";//"TBDkb";
  //ORIGINAL_DzDisparity_byRUNS.root
  //TBDkb_newIOV_DzDisparity_byRUNS_fromJuly1.root

  string inFileName=tag+".root";
  TFile *f = new TFile(inFileName.c_str());
  TTree* t = (TTree*) f->Get("SIPValidationTree");

  const int DummyNumEvents = int(t->GetEntries());
  const int NumEvents=DummyNumEvents;
  cout<<"NumEvents = "<<NumEvents <<endl;
  
  double lanWidth,lanMPV,area,GWidth;
  double err_lanWidth,err_lanMPV,err_area,err_GWidth;
  double fitChisqNdof;

  int run;

  double x[NumEvents];
  double x_err[NumEvents];
  double y_fake[NumEvents];
  double y_lanWidth[NumEvents];
  double y_lanMPV[NumEvents];
  double y_area[NumEvents];
  double y_GWidth[NumEvents];
  double y_err_lanWidth[NumEvents];
  double y_err_lanMPV[NumEvents];
  double y_err_area[NumEvents];
  double y_err_GWidth[NumEvents];

  double noDatax[10000];
  double noDatay[10000];

  t->SetBranchAddress("run"             , &run         );
  t->SetBranchAddress("lanWidth"        , &lanWidth    );                                                                         
  t->SetBranchAddress("lanMPV"          , &lanMPV      );                                                                         
  t->SetBranchAddress("area"            , &area        );                                                                         
  t->SetBranchAddress("GWidth"          , &GWidth      );                                                                         
                                                                                                                        
  t->SetBranchAddress("err_lanWidth"    , &err_lanWidth);                                                                         
  t->SetBranchAddress("err_lanMPV"      , &err_lanMPV  );                                                                         
  t->SetBranchAddress("err_area"        , &err_area    );                                                                         
  t->SetBranchAddress("err_GWidth"      , &err_GWidth  );                                                                         
  t->SetBranchAddress("fitChisqNdof"    , &fitChisqNdof);  

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

  int numEventsGood=0;
  int numEventsBad=0;
  
  t->BuildIndex("run");
  TTreeIndex *index = (TTreeIndex*)t->GetTreeIndex();
  for( int i = 0; i <= index->GetN(); i++ ) {
    Long64_t local = t->LoadTree( index->GetIndex()[i] );
   
    t->GetEntry(local);

    if(fitChisqNdof<0.)
      continue;
    
    if(fitChisqNdof>100.){
      noDatay[numEventsBad] = -999.;
      noDatax[numEventsBad] = i;
      numEventsBad++;

    } else {

      y_fake   [numEventsGood]      = 0.;
      y_lanWidth[numEventsGood]     = lanWidth;
      y_lanMPV[numEventsGood]       = lanMPV;
      y_area[numEventsGood]         = area;
      y_GWidth[numEventsGood]       = GWidth;
      
      y_err_lanWidth[numEventsGood] = err_lanWidth;
      y_err_lanMPV[numEventsGood]   = err_lanMPV;
      y_err_area[numEventsGood]     = err_area;
      y_err_GWidth[numEventsGood]   = err_GWidth;
      
      //x[numEventsGood] = run;
      x_err[numEventsGood] = 0.;
      x[numEventsGood] = numEventsGood;

      cout<<" x[" << numEventsGood << "]" << x[numEventsGood] << " y_lanMPV["<<numEventsGood<<"] " <<  y_lanMPV[numEventsGood] << " +/- y_err_lanMPV["<<numEventsGood<<"] " <<   y_err_lanMPV[numEventsGood] << endl; 
      numEventsGood++;
      
    }

  }

  //////***************************************************///////

  Double_t max_scale = 0.9;
  Double_t min_scale = 0.4;

  TGraphErrors *dummyGraph = new TGraphErrors(numEventsGood,x,y_fake,0,0);

  TCanvas *c = new TCanvas("c","", 1000,500);
  c->SetFillColor(0);
  c->SetBottomMargin(0.14);
  c->SetLeftMargin(0.07);
  c->SetRightMargin(0.05);
  c->SetTopMargin(0.08);  
  c->SetGrid();

  TGraphErrors *graph_lanMPV = new TGraphErrors(numEventsGood,x,y_lanMPV,x_err,y_err_lanMPV);
  TGraph *graph_lanMPV_shade = new TGraph(2*numEventsGood);
  for (Int_t i=0;i<numEventsGood;i++) {
    graph_lanMPV_shade->SetPoint(i,x[i],y_lanMPV[i]+1*y_err_lanMPV[i]);
    graph_lanMPV_shade->SetPoint(numEventsGood+i,x[numEventsGood-i-1],y_lanMPV[numEventsGood-i-1]-1*y_err_lanMPV[numEventsGood-i-1]);
    //graph_dxy_phi->GetXaxis()->SetBinLabel(i+1,Form("%i",x[i]));
  }
  graph_lanMPV_shade->SetFillStyle(3013);
  graph_lanMPV_shade->SetFillColor(kBlue);

  makeNiceTGraph(graph_lanMPV);

  graph_lanMPV->GetXaxis()->SetTitle("Run Number index");
  graph_lanMPV->GetYaxis()->SetTitle("MPV of SIP_{3D}");
  graph_lanMPV->SetTitle("MPV(SIP_{3D}) vs. time");
  graph_lanMPV->SetMarkerStyle(20);
  graph_lanMPV->SetMarkerSize(1.2);
  graph_lanMPV->SetMarkerColor(kRed);
  graph_lanMPV->SetLineColor(kRed);

  c->cd();
  dummyGraph->GetYaxis()->SetRangeUser(min_scale,max_scale);
  graph_lanMPV->Draw("alpsame");
  graph_lanMPV_shade->Draw("fsame");

  //******************************

  TCanvas *c2 = new TCanvas("c2","", 1000,500);
  c2->SetFillColor(0);
  c2->SetBottomMargin(0.14);
  c2->SetLeftMargin(0.07);
  c2->SetRightMargin(0.05);
  c2->SetTopMargin(0.08);  
  c2->SetGrid();

  TGraphErrors *graph_GWidth = new TGraphErrors(numEventsGood,x,y_GWidth,x_err,y_err_GWidth);
  TGraph *graph_GWidth_shade = new TGraph(2*numEventsGood);
  for (Int_t i=0;i<numEventsGood;i++) {
    graph_GWidth_shade->SetPoint(i,x[i],y_GWidth[i]+1*y_err_GWidth[i]);
    graph_GWidth_shade->SetPoint(numEventsGood+i,x[numEventsGood-i-1],y_GWidth[numEventsGood-i-1]-1*y_err_GWidth[numEventsGood-i-1]);
    //graph_dxy_phi->GetXaxis()->SetBinLabel(i+1,Form("%i",x[i]));
  }
  graph_GWidth_shade->SetFillStyle(3013);
  graph_GWidth_shade->SetFillColor(kBlue);

  makeNiceTGraph(graph_GWidth);

  graph_GWidth->GetXaxis()->SetTitle("Run Number index");
  graph_GWidth->GetYaxis()->SetTitle("Gaussian width of SIP_{3D}");
  graph_GWidth->SetTitle("#sigma_{G}(SIP_{3D}) vs. time");
  graph_GWidth->SetMarkerStyle(20);
  graph_GWidth->SetMarkerSize(1.2);
  graph_GWidth->SetMarkerColor(kRed);
  graph_GWidth->SetLineColor(kRed);

  c2->cd();
  dummyGraph->GetYaxis()->SetRangeUser(min_scale,max_scale);
  graph_GWidth->Draw("alpsame");
  graph_GWidth_shade->Draw("fsame");

  //******************************

  TCanvas *c3 = new TCanvas("c3","", 1000,500);
  c3->SetFillColor(0);
  c3->SetBottomMargin(0.14);
  c3->SetLeftMargin(0.07);
  c3->SetRightMargin(0.05);
  c3->SetTopMargin(0.08);  
  c3->SetGrid();

  TGraphErrors *graph_area = new TGraphErrors(numEventsGood,x,y_area,x_err,y_err_area);
  TGraph *graph_area_shade = new TGraph(2*numEventsGood);
  for (Int_t i=0;i<numEventsGood;i++) {
    graph_area_shade->SetPoint(i,x[i],y_area[i]+1*y_err_area[i]);
    graph_area_shade->SetPoint(numEventsGood+i,x[numEventsGood-i-1],y_area[numEventsGood-i-1]-1*y_err_area[numEventsGood-i-1]);
    //graph_dxy_phi->GetXaxis()->SetBinLabel(i+1,Form("%i",x[i]));
  }
  graph_area_shade->SetFillStyle(3013);
  graph_area_shade->SetFillColor(kBlue);

  makeNiceTGraph(graph_area);

  graph_area->GetXaxis()->SetTitle("Run Number index");
  graph_area->GetYaxis()->SetTitle("Area parameter of SIP_{3D}");
  graph_area->SetTitle("A(SIP_{3D}) vs. time");
  graph_area->SetMarkerStyle(20);
  graph_area->SetMarkerSize(1.2);
  graph_area->SetMarkerColor(kRed);
  graph_area->SetLineColor(kRed);

  c3->cd();
  // dummyGraph->GetYaxis()->SetRangeUser(min_scale,max_scale);
  graph_area->Draw("alpsame");
  graph_area_shade->Draw("fsame");

  //******************************

  TCanvas *c4 = new TCanvas("c4","", 1000,500);
  c4->SetFillColor(0);
  c4->SetBottomMargin(0.14);
  c4->SetLeftMargin(0.07);
  c4->SetRightMargin(0.05);
  c4->SetTopMargin(0.08);  
  c4->SetGrid();

  TGraphErrors *graph_lanWidth = new TGraphErrors(numEventsGood,x,y_lanWidth,x_err,y_err_lanWidth);
  TGraph *graph_lanWidth_shade = new TGraph(2*numEventsGood);
  for (Int_t i=0;i<numEventsGood;i++) {
    graph_lanWidth_shade->SetPoint(i,x[i],y_lanWidth[i]+1*y_err_lanWidth[i]);
    graph_lanWidth_shade->SetPoint(numEventsGood+i,x[numEventsGood-i-1],y_lanWidth[numEventsGood-i-1]-1*y_err_lanWidth[numEventsGood-i-1]);
    //graph_dxy_phi->GetXaxis()->SetBinLabel(i+1,Form("%i",x[i]));
  }
  graph_lanWidth_shade->SetFillStyle(3013);
  graph_lanWidth_shade->SetFillColor(kBlue);

  makeNiceTGraph(graph_lanWidth);

  graph_lanWidth->GetXaxis()->SetTitle("Run Number index");
  graph_lanWidth->GetYaxis()->SetTitle("Landau width of SIP_{3D}");
  graph_lanWidth->SetTitle("#sigma_{L}(SIP_{3D}) vs. time");
  graph_lanWidth->SetMarkerStyle(20);
  graph_lanWidth->SetMarkerSize(1.2);
  graph_lanWidth->SetMarkerColor(kRed);
  graph_lanWidth->SetLineColor(kRed);

  c4->cd();
  // dummyGraph->GetYaxis()->SetRangeUser(min_scale,max_scale);
  graph_lanWidth->Draw("alpsame");
  graph_lanWidth_shade->Draw("fsame");

}
コード例 #8
0
ファイル: test.C プロジェクト: asmagina1995/roottest
template <class HolderClass> bool read(const char *dirname, const char *testname, int nEntry, bool current) {
   HolderClass *holder = 0;
   bool result = true;
   bool testingTopLevelVectors = true; 

   TString filename = gSystem->ConcatFileName(dirname, testname );
   filename += ".root";

   if (!current && gSystem->AccessPathName(filename, kFileExists)) {
      // when reading old directory a missing files is not an error.
      // For example this happens if the run of roottest at the time was done
      // with FAST=yes
      return true;
   }

   TFile file(filename,"READ");

   if (file.IsZombie()) return false;

   holder = dynamic_cast<HolderClass*>( file.Get("holder") );
   if (!holder) {
      TestError("Reading",Form("Missing object: holder"));
      result = false;
   } else {
      result &= holder->Verify(0,Form("%s: write in dir",testname),0);
   }

   TTree *chain = dynamic_cast<TTree*>( file.Get("stltree") );

   if (!chain) {
      TestError("treeReading",Form("Missing TTree: stltree"));
      return false;
   }

   if (nEntry==0 || nEntry>chain->GetEntriesFast()) nEntry = (Int_t)chain->GetEntriesFast();
   for ( Int_t entryInChain = 0, entryInTree = chain->LoadTree(0);
         entryInTree >= 0 && entryInChain<nEntry;
         entryInChain++, entryInTree = chain->LoadTree(entryInChain)
         ) {

      if ( chain->GetEntry(entryInChain) == 0 ) {
         TestError("treeReading",Form("Nothing read for entry #%d",entryInChain));
         break;
      }

      result &= verifyBranch<HolderClass>(testname,chain,"split_2.");
      result &= verifyBranch<HolderClass>(testname,chain,"split_1.");
      result &= verifyBranch<HolderClass>(testname,chain,"split0.");
      result &= verifyBranch<HolderClass>(testname,chain,"split1.");
      result &= verifyBranch<HolderClass>(testname,chain,"split2.");
      result &= verifyBranch<HolderClass>(testname,chain,"split99.");

      if (testingTopLevelVectors) {
         // we know that they all fail! (missing dictionary)
         result &= verifyBranch<HolderClass>(testname,chain,"scalar0",1);
         result &= verifyBranch<HolderClass>(testname,chain,"scalar1",1);
         result &= verifyBranch<HolderClass>(testname,chain,"scalar2",1);
         result &= verifyBranch<HolderClass>(testname,chain,"scalar99",1);
         
         result &= verifyBranch<HolderClass>(testname,chain,"object0",2);
         result &= verifyBranch<HolderClass>(testname,chain,"object1",2);
         result &= verifyBranch<HolderClass>(testname,chain,"object2",2);
         result &= verifyBranch<HolderClass>(testname,chain,"object99",2);
         
         result &= verifyBranch<HolderClass>(testname,chain,"nested0",3);
         result &= verifyBranch<HolderClass>(testname,chain,"nested1",3);
         result &= verifyBranch<HolderClass>(testname,chain,"nested2",3);
         result &= verifyBranch<HolderClass>(testname,chain,"nested99",3);  
      }
   }
   return result;
}
コード例 #9
0
int main(int argc, char** argv){

  // Set it to kTRUE if you do not run interactively
  gROOT->SetBatch(kFALSE); 

  // Initialize Root application
  TRint* app = new TRint("CMS Root Application", &argc, argv);

  // Canvas
  TCanvas* c1 = new TCanvas("c1","Top2012 analysis");
  gStyle->SetOptStat(1111111);
  gStyle->SetMarkerStyle(20);
  gStyle->SetMarkerSize(1.0);

  // Input root file
  TString sample = "Data.root";
  
  // Declare histograms
  TH1D* hbtag = new TH1D("hbtag", "CSV discriminant, most significant jet", 25, 0., 1.);
  hbtag->Sumw2();
  
  // Initialize pointers to summary and full event structure
  Summary summary;
  Summary* pointerToSummary = &summary;
  Event ev;
  Event* pointerToEvent = &ev;
  TTree* tree;
  TBranch* bSummary;
  TBranch* bEvent;

  // Open file, get tree, set branches
  printf("Processing sample '%s' ...\n", sample.Data());
  TFile* pinput_sample = TFile::Open(sample,"READONLY");
  TFile& input_sample = *pinput_sample;
  tree = (TTree*)input_sample.Get("MUTREE");
  if (!tree) input_sample.GetObject("MuTree/MUTREE",tree);
  bSummary = tree->GetBranch("summary");
  bEvent = tree->GetBranch("event");
  bSummary->SetAddress(&pointerToSummary);
  bEvent->SetAddress(&pointerToEvent);

  // Watch number of entries
  int nentries = tree->GetEntriesFast();
  printf("Number of entries = %d\n", nentries);

  // Typical way to normalize the MC to data
  double lumi = 20000.; // 1/pb
  double xsection = 200.; // pb
  double skimFilterEfficiency = 1.; // different from 1 if MC was already skimmed
  double weight = lumi*xsection*skimFilterEfficiency / nentries;

  for (Long64_t iEvent=0; iEvent<nentries; iEvent++) {
      if (tree->LoadTree(iEvent)<0) break;

      // First, access the summary
      bSummary->GetEntry(iEvent);

      // Cut on summary information to save processing time
      if (summary.nMuons==0) continue; // look for events with at least 1 muon
      if (summary.maxMT<30.) continue; // look for events with maxMT>30
      if (summary.nJets<2) continue; // look for events with at least 2 jets

      // Now get the full event, once we know that summary conditions are satisfied
      bEvent->GetEntry(iEvent);

      // Get the most significant b jet
      unsigned int njets = ev.jets.size();
      double btag = 0.;
      for (unsigned int ij=0; ij<njets; ++ij) {
            Jet jet = ev.jets[ij];
            if (jet.btagCSV>btag) {
                  btag = jet.btagCSV;
            }
      }
      
      // Fill histogram
      hbtag->Fill(btag, weight);
  }

  hbtag->Draw("e");

  c1->SaveAs("btag.jpg");

  if (!gROOT->IsBatch()) app->Run();

  return 0;
}
コード例 #10
0
void SkimClassification(TString process="ZnnH125")
{
    gROOT->LoadMacro("HelperFunctions.h" );  // make functions visible to TTreeFormula
    gROOT->SetBatch(1);

    //TChain * chain  = new TChain("tree");
    //TString fname   = "";
    //TString dijet   = "DiJetPt_";
    //TString dirMC   = "dcache:/pnfs/cms/WAX/resilient/jiafu/ZnunuHbb/" + tagMC + "/";
    //TString dirData = "dcache:/pnfs/cms/WAX/resilient/jiafu/ZnunuHbb/" + tagData + "/";
    TString indir   = "/afs/cern.ch/work/d/degrutto/public/MiniAOD/ZnnHbb_Spring15_PU20bx25/skimV12_v2/step3/";
    TString outdir  = "/afs/cern.ch/work/d/degrutto/public/MiniAOD/ZnnHbb_Spring15_PU20bx25/skimV12_v2/step3/skim_ZnnH_classification/";
    TString prefix  = "Step3_";
    TString suffix  = ".root";

    TFile *input = TFile::Open(indir + prefix + process + suffix);
    if (!input) {
        std::cout << "ERROR: Could not open input file." << std::endl;
        exit(1);
    }
    TTree *tree   = (TTree *) input->Get("tree");
    Long64_t entries = tree->GetEntriesFast();
    
    // Make output directory if it doesn't exist
    if (gSystem->AccessPathName(outdir))
        gSystem->mkdir(outdir);
    TString outname = outdir + prefix + Form("%s.root", process.Data());

    TFile* output = TFile::Open(outname, "RECREATE");

    // Get selections
    const std::vector < std::string > & selExpressions = GetSelExpressions("ZnunuHighPt") ;
    //    const UInt_t nsels = 3;  // ZnunuHighPt, ZnunuLowPt, ZnunuLowCSV
    const UInt_t nsels = 1;  // just one now...  ZnunuHighPt, ZnunuLowPt, ZnunuLowCSV

    //    assert(nsels == selExpressions.size()); <-- fixME
    // even-number events for training, odd-number events for testing
    TCut evenselection = "evt  %2 == 0";
    TCut oddselection  = "evt %2 == 1";

    TTreeFormula *ttf = 0;
    std::vector < TTreeFormula * >::const_iterator formIt, formItEnd;

    // Loop over selections
    std::vector<Long64_t> ventries;
    for (unsigned int i = 0; i < nsels; i++) {
        TString selname = "ZnunuHighPt";
        if (i == 1) {
            selname = "ZnunuMedPt";
	    //	    selExpressions = GetSelExpressions("ZnunuMedPt") ;
        } else if (i == 2) {
            selname = "ZnunuLowPt";
	    // selExpressions = GetSelExpressions("ZnunuLowPt") ;
        }

        TTree *t1 = (TTree*) tree->CloneTree(0);
        TTree *t2 = (TTree*) tree->CloneTree(0);
        
        t1->SetName(TString::Format("%s_%s_train", tree->GetName(), selname.Data()));
        t2->SetName(TString::Format("%s_%s", tree->GetName(), selname.Data()));
        
        // The clones should not delete any shared i/o buffers.
        ResetDeleteBranches(t1);
        ResetDeleteBranches(t2);
        
        ttf = new TTreeFormula(Form("ttfsel%i", i), selExpressions.at(i).c_str(), tree);
        ttf->SetQuickLoad(1);
        TTreeFormula *ttf1 = new TTreeFormula(Form("ttfeven%i", i), evenselection, tree);
        ttf1->SetQuickLoad(1);
        TTreeFormula *ttf2 = new TTreeFormula(Form("ttfodd%i", i), oddselection, tree);
        ttf2->SetQuickLoad(1);
        if (!ttf || !ttf->GetNdim()) {
            std::cerr << "ERROR: Failed to find any TTree variable from the selection: " << selExpressions.at(i) << std::endl;
            return;
        }

        
        /// Loop over events
        Int_t curTree = tree->GetTreeNumber();
        const Long64_t nentries = tree->GetEntries();
        for (Long64_t ievt = 0; ievt < nentries; ievt++) {
            Long64_t entryNumber = tree->GetEntryNumber(ievt);
            if (entryNumber < 0)  break;
            Long64_t localEntry = tree->LoadTree(entryNumber);
            if (localEntry < 0)  break;
            if (tree->GetTreeNumber() != curTree) {
                curTree = tree->GetTreeNumber();
                ttf ->UpdateFormulaLeaves();  // if using TChain
                ttf1->UpdateFormulaLeaves();  // if using TChain
                ttf2->UpdateFormulaLeaves();  // if using TChain
            }
            
            const Int_t ndata = ttf->GetNdata();
            Bool_t keep = kFALSE;
            for(Int_t current = 0; current<ndata && !keep; current++) {
                keep |= (bool(ttf->EvalInstance(current)) != 0);
            }
            if (!keep)  continue;


            bool even  = (bool) ttf1->EvalInstance();
            bool odd   = (bool) ttf2->EvalInstance();
            if (even && odd) {
                std::cerr << "ERROR: An event cannot be even and odd at the same time." << std::cout;
                return;
            }

            tree->GetEntry(entryNumber, 1);  // get all branches
            if (even) {
                t1->Fill();
            } else {
                t2->Fill();
            }
        }  // end loop over events

        t1->Write();
        t2->Write();
        
        ventries.push_back(t1->GetEntriesFast() + t2->GetEntriesFast());
        
        delete ttf;
        delete ttf1;
        delete ttf2;
    }
    
    std::clog << process << ": skimmed from " << entries << " to " << ventries[0] << " (ZnunuHighPt), " << ventries[1] << " (ZnunuLowPt), " << ventries[2] << " (ZnunuLowCSV) " << " entries." << std::endl;

    output->Close();
    input->Close();

    delete output;
    delete input;

    return;
}
コード例 #11
0
// Parse the root file located at path and parse the Ttree treeName.
// prefix identifies the track which is to be used, e.g.
// trk_, trkSiSpSeeded_, pseudoTrk_
  int
EventReader::parse (const char* path, const char* treeName, const char* prefix)
{
  TFile *file;
  TTree *tree;

  // Open data file and read TTree
  file = new TFile (path, "READ", "TrackFitData Access");

  if (!file) {
    std::cerr << "Could not open " << path << std::endl;
    return -1;
  }

  tree = ( TTree* )file->Get (treeName);

  if (!tree) {
    std::cerr << "Could not get tree " << treeName << std::endl;
    delete file;
    return -1;
  }

  // Read events and their tracks. Each data attribute is represented
  // by a branch in the TTree.
  resetAttributeVectors ( );

  if (loadBranches (tree, prefix) == -1) {
    PRINT_ERR ("loadBranches failed!");
    resetAttributeVectors ( );
    delete file;
    return -1;
  }

  mEvents.clear ( );

  // Loop over all events
  for (Long64_t events = 0; events < tree->GetEntriesFast ( ); ++events) {
    Long64_t local_events = tree->LoadTree (events);

    if (local_events < 0) {
      PRINT_ERR ("LoadTree returned value < 0");
      resetAttributeVectors ( );
      delete file;
      return -1;
    }

    // Load branches into the matching vectors
    if (tree->GetEntry (events) <= 0) {
      PRINT_ERR ("tree->GetEntry failed!");
      resetAttributeVectors ( );
      delete file;
      return -1;
    }

    if (eventSanityCheck ( ) == -1) {
      PRINT_ERR ("Event sanity check failed!");
      resetAttributeVectors ( );
      delete file;
      return -1;
    }

    KF_Event_t newEvent;
    Track_t newTrack;
    TrackHit_t trackHit;
#if HAS_COMPETING_ROTS
    for (int i = 0; i < MAXROTS; ++i) {
      trackHit.rotIds[i] = 0;
    }
#endif
    newEvent.clear();

    // Loop over all tracks
    for (unsigned int track = 0; track < mLocX->size ( ); ++track) {
      newTrack.track.clear ( );

      // phi, theta, qoverp are values referring to a complete track
      newTrack.info.d0     = (*mD0)[track];
      newTrack.info.z0     = (*mZ0)[track];
      newTrack.info.phi    = (*mPhi)[track];
      newTrack.info.theta  = (*mTheta)[track];
      newTrack.info.qoverp = (*mQoverP)[track];

      // FIXME: has to check whether MC index is valid!
      //int tti = (*mTTTI)[ (*mMCI)[track] ];
      // FIXME: has to check whether truth track index is valid!
      //std::cout << "Track:" << track <<  " TruthTrackIndex: " << tti <<std::endl;
      newTrack.truthTrackInfo.d0 = -999.;
      newTrack.truthTrackInfo.z0 = -999.;
      newTrack.truthTrackInfo.phi = -999.;
      newTrack.truthTrackInfo.theta = -999.;
      newTrack.truthTrackInfo.qoverp = -999.;
      int mcindex = (*mMCI)[track];
      if (mcindex > -1) {
	if (mMCPerigeeOk->at(mcindex)) {
	  newTrack.truthTrackInfo.d0 = (*mTTD0)[mcindex];
	  newTrack.truthTrackInfo.z0 = (*mTTZ0)[mcindex];
	  newTrack.truthTrackInfo.phi = (*mTTPhi)[mcindex];
	  newTrack.truthTrackInfo.theta = (*mTTTheta)[mcindex];
	  newTrack.truthTrackInfo.qoverp = (*mTTQoverP)[mcindex];
	}
      }
      bool validTrack = true;
      //             std::cout<< "track " << track << std::endl;
      // Loop over all hits
      for (unsigned int hit = 0; hit < (*mLocX)[track].size ( ); ++hit) {
	// No NULL-pointer check, since eventSanityCheck passed
	trackHit.normal[0]  = (*mLocX)[track][hit];
	trackHit.normal[1]  = (*mLocY)[track][hit];
	trackHit.err_locX   = (*mErr_locX)[track][hit];
	trackHit.err_locY   = (*mErr_locY)[track][hit];
	trackHit.cov_locXY  = (*mCov_locXY)[track][hit];
	trackHit.detType    = (*mDetType)[track][hit];
	trackHit.bec        = (*mBec)[track][hit];
	trackHit.ref[0]     = (*mRefLocX)[track][hit];
	trackHit.ref[1]     = (*mRefLocY)[track][hit];
	trackHit.ref[2]     = (*mRefPhi)[track][hit];
	trackHit.ref[3]     = (*mRefTheta)[track][hit];
	trackHit.ref[4]     = (*mRefQoverP)[track][hit];
#if HAS_MATERIAL_EFFECTS
	trackHit.sigmaDeltaThetaSquared = pow(mSigmaDeltaTheta->at(track).at(hit), 2);
	trackHit.sigmaDeltaPhiSquared = pow(mSigmaDeltaPhi->at(track).at(hit), 2);
	//trackHit.sigmaDeltaQoverPSquared = (trackHit.ref[4]*trackHit.ref[4]>0.) ? ( mSigmaDeltaE->at(track).at(hit) * sqrt(PionMassSquared + 1./(trackHit.ref[4]*trackHit.ref[4])) * fabs(pow(trackHit.ref[4],3)) ) : 0.;
	const double qOverPSquared=trackHit.ref[4]*trackHit.ref[4];
	trackHit.sigmaDeltaQoverPSquared = (qOverPSquared>0.) ? ( pow(mSigmaDeltaE->at(track).at(hit),2) * (PionMassSquared + 1./qOverPSquared) * pow(qOverPSquared,3) ) : 0.;
#endif // #if HAS_MATERIAL_EFFECTS
#if HAS_COMPETING_ROTS
	trackHit.competingRotIds = (*mCompetingRotIds)[track][hit];
	//std::cout << "read compRot " << trackHit.competingRotIds << " track " << track << " hit " << hit << std::endl;
	for (unsigned int rot = 0; rot < (*mRotLocX)[track][hit].size(); ++rot) {
	  trackHit.rotLocX[rot] = (*mRotLocX)[track][hit][rot];
	  trackHit.rotLocY[rot] = (*mRotLocY)[track][hit][rot];
	  trackHit.rotIds[rot] = (*mRotIds)[track][hit][rot];
	  trackHit.rotProbs[rot] = (*mRotProbs)[track][hit][rot];

	  trackHit.rotCov[rot][0] = (*mRotCov00)[track][hit][rot];
	  trackHit.rotCov[rot][1] = (*mRotCov01)[track][hit][rot];
	  trackHit.rotCov[rot][2] = (*mRotCov10)[track][hit][rot];
	  trackHit.rotCov[rot][3] = (*mRotCov11)[track][hit][rot];
	  //                    if (DBG_LVL == 0) if ((*mRotLocY)[track][hit].size() > 1) std::cout << rot << "/" << (*mRotLocY)[track][hit].size() - 1 << " id " << trackHit.rotIds[rot] << " locY " << trackHit.rotLocY[rot] << " effY " << trackHit.measurement[1] << " cov " << trackHit.rotCov[rot][1] << std::endl;
	  //                    std::cout << "\trot " << trackHit.rotIds[rot] << std::endl;
	}
#endif
	if (abs(trackHit.normal[1] + 99999.) > 1.E-4) {
	  trackHit.is2Dim = 1;
	} else {
	  trackHit.is2Dim = 0;
	}
	// no measurement at all (pure material surface):
	if (!(fabs(trackHit.normal[0] + 99999.) > 1.E-4)) {
	  trackHit.is2Dim = 3;
	  //                     std::cout<< "mat lay: sigmaDeltaPhi=" << mSigmaDeltaPhi->at(track).at(hit)
	  //                              << " sigmaDeltaTheta=" << mSigmaDeltaTheta->at(track).at(hit)
	  //                              << " sigmaDeltaE=" << mSigmaDeltaE->at(track).at(hit) << std::endl;
	}// else {
	//                     std::cout<< "meas lay: sigmaDeltaPhi=" << mSigmaDeltaPhi->at(track).at(hit)
	//                              << " sigmaDeltaTheta=" << mSigmaDeltaTheta->at(track).at(hit)
	//                              << " sigmaDeltaE=" << mSigmaDeltaE->at(track).at(hit) << std::endl;
	//                 }
	//Check if this track has valid Data
	//if (abs(trackHit.normal[0] + 999.) < 1.E-4 || abs(trackHit.normal[1] + 999.) < 1.E-4 || abs(trackHit.ref[0] + 999.) < 1.E-4 || abs(trackHit.ref[1] + 999.) < 1.E-4) {
	if (abs(trackHit.ref[0] + 999.) < 1.E-4 || abs(trackHit.ref[1] + 999.) < 1.E-4) {
	  validTrack = false;
	  break;
	}            
	// Ignore Detector-Type 3
	if (trackHit.detType == 3) {
	  break;
	}

	if (setJacobiMatrix (trackHit.jacobi, track, hit) == -1) {
	  PRINT_WARN ("Could not set JacobiMatrix for hit!");
	  break;
	}
#if USE_EIGEN_MATRIX_INVERSION
	matrixInverseEigen(trackHit.jacobi, trackHit.jacobiInverse, ORDER, ORDER);
#else
	matrixInverse(trackHit.jacobi, trackHit.jacobiInverse, ORDER, ORDER);
#endif
	newTrack.track.push_back (trackHit);
      }
      //             if(validTrack)
      //             	newEvent.push_back (newTrack);
      if (!validTrack)
	newTrack.track.clear ( );
      newEvent.push_back (newTrack);
      }
      mEvents.push_back (newEvent);
    }

    resetAttributeVectors ( );

    delete file;

    return 0;
  }
コード例 #12
0
int main(int argc, char** argv){

  // Set it to "true" if you do not want to see the histograms interactively
  gROOT->SetBatch(IS_BATCH);
  gStyle->SetOptStat(1111111);
  gStyle->SetOptFit(1111);

  // Open the input root file and set branches
  // On pcciet3a, pcciet3b, pccmscie6
  //TString sampleFile = "/data4/Fall11_WplusC_Trees_July2012/TTbar.root";
  // Just for some checks (there are selection cuts applied on the following file)
  //TString sampleFile = "/data4/Fall11_WplusC_Trees_July2012/TTbar_SSVHPNOMTNOISOreduced.root";
  // Stop file
//  TString sampleFile = "/data4/Fall11_WplusC_Trees_July2012/Stop.root";
  TString sampleFile = "dcap://gaeds015.ciemat.es:22125/pnfs/ciemat.es/data/cms/store/user/delacruz/STop2012/NTuplesFeb2013/v1/merge_stops_signalmc_T2tt_Mstop-225to1200_mLSP-0to1000_Pythia_new.root";

  Event ev;
  Event* pointerToEvent = &ev;
  printf("Processing sample '%s'...\n", sampleFile.Data());
  TFile input_sample(sampleFile,"READONLY");
  TTree* tree = 0;
  input_sample.GetObject("MUTREE/MUTREE",tree);
  if (!tree) input_sample.GetObject("MUTREE",tree);
  tree->SetBranchAddress("event", &pointerToEvent);

  int nentriesInTree = tree->GetEntriesFast();
  if (maxEventsUsed<0) maxEventsUsed = nentriesInTree;
  printf("\tThere are %d events in the file; running on %d events\n", nentriesInTree, maxEventsUsed);

  TH1D* hCosb = new TH1D("hCosb", "cos(#theta_{tb})", 50, -1.0, 1.0);

  printf("Input thetaEff for topPol %.3f is: %.3f\n", 1., GetThetaMixing(1., 950., 175., 425.));
  printf("Input thetaEff for topPol %.3f is: %.3f\n", 0.5, GetThetaMixing(0.5, 950., 175., 425.));
  printf("Input thetaEff for topPol %.3f is: %.3f\n", 0., GetThetaMixing(0., 950., 175., 425.));
  printf("Input thetaEff for topPol %.3f is: %.3f\n", -0.5, GetThetaMixing(-0.5, 950., 175., 425.));
  printf("Input thetaEff for topPol %.3f is: %.3f\n", -1., GetThetaMixing(-1., 950., 175., 425.));

  // Event loop
  for (int iEvent=0; iEvent<maxEventsUsed; iEvent++) {
    if (tree->LoadTree(iEvent)<0) break;
    tree->GetEntry(iEvent);

    if (ev.genInfos.size()<=0) {
      printf("This is not a MC file, EXIT!!!\n");
      return -1;
    }

    if (iEvent%1000000==0) printf("... event index %d\n", iEvent);
    
    unsigned int ngen = ev.genParticles.size();

    //double m_stop = 0.;
    //double m_chi0 = 0.;
    //double m_top = 0.;
    std::vector<SUSYGenParticle> genParticles;
    for (unsigned int ig=0; ig<ngen; ++ig) {
      GenParticle gen = ev.genParticles[ig];
      if (gen.status!=3) break;
      SUSYGenParticle part;
      part.pdgId = gen.pdgId;
      part.energy = gen.energy;
      part.pt = gen.pt;
      part.eta = gen.eta;
      part.phi = gen.phi;
      part.firstMother = -1; if (gen.mothers.size()>0) part.firstMother = gen.mothers[0];
      //if (abs(gen.pdgId)==1000006) m_stop = sqrt(pow(gen.energy,2)-pow(gen.pt*cosh(gen.eta),2));
      //if (abs(gen.pdgId)==1000022) m_chi0 = sqrt(pow(gen.energy,2)-pow(gen.pt*cosh(gen.eta),2));
      //if (abs(gen.pdgId)==6) m_top = sqrt(pow(gen.energy,2)-pow(gen.pt*cosh(gen.eta),2));

      genParticles.push_back(part);
    }
    //printf("m_stop: %.3f, m_top: %.3f, m_chi0: %.3f\n", m_stop, m_top, m_chi0);

    //double pol_new = POL;
    //double pol_new = AverageTopPolarization_Stop_to_TopChi0(-1.1, genParticles);
    //double weight = Reweight_Stop_to_TopChi0_TopOnshell (genParticles, 0., pol_new);

    // m_stop=950 GeV, m_chi0=425 GeV, m_top=175 GeV
    double thetaMixingTarget = -1.134; // Pol=-1
    //double thetaMixingTarget = -0.437; // Pol=+1
    double weight = Reweight_Stop_to_TopChi0_with_SUSYmodel (genParticles, thetaMixingTarget);

    for (unsigned int ig=0; ig<ngen; ++ig) {
      GenParticle gen = ev.genParticles[ig];
      if (gen.status!=3) break;
      if (abs(gen.pdgId)!=5) continue;
      if (gen.mothers.size()!=1) continue;
      GenParticle genTop = ev.genParticles[gen.mothers[0]];
      if (abs(genTop.pdgId)!=6) continue;

      if (genTop.pdgId*gen.pdgId<0) continue;

      double etop = genTop.energy;
      double pxtop = genTop.pt*cos(genTop.phi);
      double pytop = genTop.pt*sin(genTop.phi);
      double pztop = genTop.pt*sinh(genTop.eta);
      double ptop  = sqrt(pxtop*pxtop+pytop*pytop+pztop*pztop);
      double mtop  = sqrt(etop*etop-ptop*ptop);
      double pxb   = gen.pt*cos(gen.phi);
      double pyb   = gen.pt*sin(gen.phi);
      double pzb   = gen.pt*sinh(gen.eta);
      double pb    = sqrt(pxb*pxb+pyb*pyb+pzb*pzb);

      // We also need a stop
      if (genTop.mothers.size()==0) continue;
      GenParticle genStop = ev.genParticles[genTop.mothers[0]];
      if (abs(genStop.pdgId)!=1000006) continue;

      // Move top and fermion to the stop center-of-mass frame
      TLorentzVector stop4;
      stop4.SetPtEtaPhiE(genStop.pt, genStop.eta, genStop.phi, genStop.energy);
      TVector3 betaS(-stop4.Px()/stop4.Energy(),-stop4.Py()/stop4.Energy(),-stop4.Pz()/stop4.Energy());
      TLorentzVector topRef(pxtop,pytop,pztop,etop);
      topRef.Boost(betaS); // keept this vector to calculate costh
      TLorentzVector top4(pxtop,pytop,pztop,etop);
      top4.Boost(betaS);
      TLorentzVector b4(pxb,pyb,pzb,pb);
      b4.Boost(betaS);

      TVector3 betaV(-top4.Px()/top4.Energy(),-top4.Py()/top4.Energy(),-top4.Pz()/top4.Energy());
      top4.Boost(betaV);
      b4.Boost(betaV);

      double costh = (topRef.Px()*b4.Px()+topRef.Py()*b4.Py()+topRef.Pz()*b4.Pz())/topRef.P()/b4.P();

      hCosb->Fill(costh,weight);

    }

  }

  // To see things interactively (if IS_BATCH == false);
  TRint* app = new TRint("Wprime Analysis", &argc, argv);

  hCosb->SetMinimum(0.);
  hCosb->Draw();

  // Fitting slope
  TF1* f1 = new TF1("f1","[0]*(1+[1]*x)");
  f1->SetParName(0,"ValueAt0");
  f1->SetParName(1,"Slope");
  hCosb->Fit(f1,"","same");

  gROOT->GetListOfCanvases()->At(0)->SaveAs("costhb.jpg");

  app->Run();

  return 0;
}
コード例 #13
0
double TrimEventContent(Int_t iRapBin = 1,
		      Int_t iPTBin = 1,
		      Double_t fracL = 0.5, Double_t nSigma = 2., 
		      Int_t nUpsState=0,//[0]... 1S, [1]... 2S, [2]... 3S
		      bool UpsMC=false,
		      bool f_BG_zero=false,
		      bool ProjectLSBdata=false,
		      bool ProjectRSBdata=false,
		      bool CombineSignalPeaks=false,
		      bool Y1Sto2S_SB=false,
		      bool LeftSided=false,
		      bool RightSided=false,
		      bool MassScan=false,
		      bool adjustOverlapBorders=true
		      ){

  printf("\n\n\nfracL = %1.3f, nSigma = %1.1f, iState = %d, rap %d, pT %d\n", fracL, nSigma, nUpsState, iRapBin, iPTBin);

  Char_t name[100], title[100];
  Char_t fileNameIn[100];
  sprintf(fileNameIn, "tmpFiles/data_Ups_rap%d_pT%d.root", iRapBin, iPTBin);
  //==============================
  //read inputs from input file:
  TFile *fIn = new TFile(fileNameIn);
  TLorentzVector *lepP;
  TLorentzVector *lepN;
  TTree *treeIn = (TTree *) gDirectory->Get("selectedData");
  if(gDirectory->Get("selectedData")==NULL){
    printf("\n\n\nskip processing this bin.\n\n\n");
    return -999.;
  }

  TH2D *hBG_cosThetaPhiLR[onia::kNbFrames][2];
  for(int iFrame = 0; iFrame < onia::kNbFrames; iFrame++){
    sprintf(name, "hBG_cosThetaPhi_%s_L", onia::frameLabel[iFrame]);
    hBG_cosThetaPhiLR[iFrame][L] = (TH2D *) gDirectory->Get(name);
    sprintf(name, "hBG_cosThetaPhi_%s_R", onia::frameLabel[iFrame]);
    hBG_cosThetaPhiLR[iFrame][R] = (TH2D *) gDirectory->Get(name);
  }
  //==============================

  //definition of output variables 
  Char_t fileNameOut[100];
  sprintf(fileNameOut, "AllStates_%1.2fSigma_FracLSB%dPercent/data_%dSUps_rap%d_pT%d.root", nSigma, int(fracL*100), nUpsState+1, iRapBin, iPTBin);
  TFile *fOut = new TFile(fileNameOut, "RECREATE");
  gStyle->SetPadRightMargin(0.2);
  TTree *treeOut = treeIn->CloneTree(0);
  // treeOut->SetName("data");
  TH2D *hBG_cosThetaPhi[onia::kNbFrames];
  // TH2D *hBG_cosThetaPhiSignal[onia::kNbFrames];
  for(int iFrame = 0; iFrame < onia::kNbFrames; iFrame++){
    // //book the histo for the signal
    // sprintf(name, "total_%s", onia::frameLabel[iFrame]);
    // sprintf(title, ";cos#theta_{%s};#phi_{%s} [deg]", onia::frameLabel[iFrame], onia::frameLabel[iFrame]);
    // hBG_cosThetaPhiSignal[iFrame] = new TH2D(name, title, onia::kNbBinsCosT, onia::cosTMin, onia::cosTMax, 
    // 					  onia::kNbBinsPhiPol, onia::phiPolMin, onia::phiPolMax);
    // hBG_cosThetaPhiSignal[iFrame]->Sumw2();
    //copy the L and R sideband histos into one output BG histogram
    hBG_cosThetaPhiLR[iFrame][L]->Scale(fracL/hBG_cosThetaPhiLR[iFrame][L]->Integral());
    hBG_cosThetaPhiLR[iFrame][R]->Scale((1.-fracL)/hBG_cosThetaPhiLR[iFrame][R]->Integral());
    sprintf(name, "background_costhphi%s", onia::frameLabel[iFrame]);
    hBG_cosThetaPhi[iFrame] = (TH2D *) hBG_cosThetaPhiLR[iFrame][L]->Clone(name);
    hBG_cosThetaPhi[iFrame]->Add(hBG_cosThetaPhiLR[iFrame][R]);
  }

  //==========================================================
  //reading fit parameters to establish signal mass window
  //as well as the L and R sideband window for the 3D BG histo
  //==========================================================
  fIn->cd();
  TTree *treeFitPar = (TTree *) gDirectory->Get("massFitParameters");
  TF1 *fUps[kNbSpecies], *fBG = 0;
  fUps[0] = 0, fUps[1] = 0, fUps[2] = 0;
  treeFitPar->SetBranchAddress("fUps1S", &fUps[0]);
  treeFitPar->SetBranchAddress("fUps2S", &fUps[1]);
  treeFitPar->SetBranchAddress("fUps3S", &fUps[2]);
  treeFitPar->SetBranchAddress("fBG", &fBG);
  treeFitPar->LoadTree(0);
  treeFitPar->GetEntry(0);


  Double_t mass[kNbSpecies], sigma[kNbSpecies];
  for(int iState = 0; iState < kNbSpecies; iState++){
    mass[iState] = fUps[iState]->GetParameter(1);
    sigma[iState] = fUps[iState]->GetParameter(2);
  }
  printf("1S: mass = %1.3f GeV, sigma = %1.3f GeV\n", mass[UPS1S], sigma[UPS1S]);
  printf("2S: mass = %1.3f GeV, sigma = %1.3f GeV\n", mass[UPS2S], sigma[UPS2S]);
  printf("3S: mass = %1.3f GeV, sigma = %1.3f GeV\n", mass[UPS3S], sigma[UPS3S]);
  Double_t poleMass = mass[nUpsState], massMin, massMax;
  massMin = poleMass - nSigma*sigma[nUpsState];
  massMax = poleMass + nSigma*sigma[nUpsState];

  if(LeftSided){
	  massMin = poleMass - nSigma*sigma[nUpsState];
	  massMax = poleMass;
  }

  if(RightSided){
	  massMin = poleMass;
	  massMax = poleMass + nSigma*sigma[nUpsState];
  }

//	  massMin = poleMass - 3.*sigma[nUpsState];
//	  massMax = poleMass - 1.*sigma[nUpsState];

//	  massMin = poleMass + 1.*sigma[nUpsState];
//	  massMax = poleMass + 3.*sigma[nUpsState];

  cout<<"massMin = "<<massMin<<endl;
  cout<<"massMax = "<<massMax<<endl;


  if(adjustOverlapBorders){
  if( nUpsState==2 && mass[2]-nSigma*sigma[2]<mass[1]+nSigma*sigma[1] ){
	  cout<<"adjusting lower border of Y(3S) mass window due to overlap"<<endl;
	  massMin=(sigma[2]*mass[1]+sigma[1]*mass[2])/(sigma[1]+sigma[2]);
  }
  if( nUpsState==1 && mass[1]-nSigma*sigma[1]<mass[0]+nSigma*sigma[0] ){
	  cout<<"adjusting lower border of Y(2S) mass window due to overlap"<<endl;
	  massMin=(sigma[1]*mass[0]+sigma[0]*mass[1])/(sigma[1]+sigma[0]);
  }
  if( nUpsState==1 && mass[2]-nSigma*sigma[2]<mass[1]+nSigma*sigma[1] ){
	  cout<<"adjusting upper border of Y(2S) mass window due to overlap"<<endl;
	  massMax=(sigma[2]*mass[1]+sigma[1]*mass[2])/(sigma[1]+sigma[2]);
  }
  if( nUpsState==0 && mass[1]-nSigma*sigma[1]<mass[0]+nSigma*sigma[0] ){
	  cout<<"adjusting upper border of Y(1S) mass window due to overlap"<<endl;
	  massMax=(sigma[1]*mass[0]+sigma[0]*mass[1])/(sigma[1]+sigma[0]);
  }
  }


  if( nUpsState==0){
  contamination2Sin1S=fUps[1]->Integral(massMin, massMax)/(fUps[0]->Integral(massMin, massMax)+fUps[1]->Integral(massMin, massMax));
  cout<<"Contamination of the 1S sample by 2S events = "<<contamination2Sin1S*100<<" %"<<endl;
  }
  if( nUpsState==1){
  contamination1Sin2S=fUps[0]->Integral(massMin, massMax)/(fUps[0]->Integral(massMin, massMax)+fUps[1]->Integral(massMin, massMax));
  contamination3Sin2S=fUps[2]->Integral(massMin, massMax)/(fUps[2]->Integral(massMin, massMax)+fUps[1]->Integral(massMin, massMax));
  cout<<"Contamination of the 2S sample by 1S events = "<<contamination1Sin2S*100<<" %"<<endl;
  cout<<"Contamination of the 2S sample by 3S events = "<<contamination3Sin2S*100<<" %"<<endl;
  }
  if( nUpsState==2){
  contamination2Sin3S=fUps[1]->Integral(massMin, massMax)/(fUps[2]->Integral(massMin, massMax)+fUps[1]->Integral(massMin, massMax));
  cout<<"Contamination of the 3S sample by 2S events = "<<contamination2Sin3S*100<<" %"<<endl;
  }

  if(CombineSignalPeaks) {
	  massMin=9.15;
	  massMax=10.65;
  }

  if(Y1Sto2S_SB){
	  massMin = mass[0] + 3.*sigma[0];
	  massMax = mass[1] - 4.*sigma[1];
  }

////////////////// Background mass scan
const int nMassScan=12;
int nMassScanCurrent;
//double MassScanBorders[nMassScan+1] = {8.6, 8.95, 9.3, 9.45, 9.6, 9.85, 10.0125, 10.175, 10.3425, 10.51, 10.8, 11.1, 11.4};
double MassScanBorders[nMassScan+1] = {8.6, 8.95, 9.3, 9.45, 9.6, 9.85, 10.0125, 10.175, 10.3425, 10.51, 10.8, 11.1, 11.4};

for(int i=1;i<nMassScan+1;i++){
if(nSigma<i+0.5) {nMassScanCurrent=i; break;}
}

double BuffMinL=onia::massMinL;
double BuffMaxL=mass[UPS1S] - onia::nSigmaL*sigma[UPS1S];
double BuffMinR=mass[UPS3S] + onia::nSigmaR*sigma[UPS3S];
double BuffMaxR=onia::massMaxR;

double MassScanMin=MassScanBorders[nMassScanCurrent-1];
double MassScanMax=MassScanBorders[nMassScanCurrent];

if(nSigma==1){
	MassScanMin=BuffMinL;
	MassScanMax=BuffMinL+1./3.*(BuffMaxL-BuffMinL);
}
if(nSigma==2){
	MassScanMin=BuffMinL+1./3.*(BuffMaxL-BuffMinL);
	MassScanMax=BuffMinL+2./3.*(BuffMaxL-BuffMinL);
}
if(nSigma==3){
	MassScanMin=BuffMinL+2./3.*(BuffMaxL-BuffMinL);
	MassScanMax=BuffMaxL;
}
if(nSigma==4){
	MassScanMin=BuffMinL;
	MassScanMax=BuffMaxL;
}

if(nSigma==5){
	MassScanMin=BuffMinR;
	MassScanMax=BuffMinR+1./3.*(BuffMaxR-BuffMinR);
}
if(nSigma==6){
	MassScanMin=BuffMinR+1./3.*(BuffMaxR-BuffMinR);
	MassScanMax=BuffMinR+2./3.*(BuffMaxR-BuffMinR);
}
if(nSigma==7){
	MassScanMin=BuffMinR+2./3.*(BuffMaxR-BuffMinR);
	MassScanMax=BuffMaxR;
}
if(nSigma==8){
	MassScanMin=BuffMinR;
	MassScanMax=BuffMaxR;
}
if(nSigma>8){
	BuffMaxL=mass[UPS1S] - 7*sigma[UPS1S];
	BuffMinR=mass[UPS3S] + onia::nSigmaR*sigma[UPS3S];
}
if(nSigma==9){
	MassScanMin=BuffMinL;
	MassScanMax=BuffMinL+1./3.*(BuffMaxL-BuffMinL);
}
if(nSigma==10){
	MassScanMin=BuffMinL+1./3.*(BuffMaxL-BuffMinL);
	MassScanMax=BuffMinL+2./3.*(BuffMaxL-BuffMinL);
}
if(nSigma==11){
	MassScanMin=BuffMinL+2./3.*(BuffMaxL-BuffMinL);
	MassScanMax=BuffMaxL;
}
if(nSigma==12){
	MassScanMin=BuffMinL;
	MassScanMax=BuffMaxL;
}


  if(MassScan){
  massMin=MassScanMin;
  massMax=MassScanMax;
  }
/////////////////////////////////////

  printf("--> signal mass window: %1.3f < M < %1.3f GeV\n", massMin, massMax);

  //calculate the fraction of BG under the signal mass window
  Double_t nBG = fBG->Integral(massMin, massMax);
//  Double_t nSignal = fUps[nUpsState]->Integral(massMin, massMax);
  Double_t nSignal = fUps[0]->Integral(massMin, massMax)+fUps[1]->Integral(massMin, massMax)+fUps[2]->Integral(massMin, massMax);
  Double_t fracBG = nBG / (nBG + nSignal);
  sprintf(name, ";;fraction of BG in %1.1f sigma window", nSigma);
  TH1D *hFracBG = new TH1D("background_fraction", name, 1, 0., 1.);
  if(!UpsMC&&!f_BG_zero) hFracBG->SetBinContent(1, fracBG);
  if(UpsMC||f_BG_zero)  hFracBG->SetBinContent(1, 0.001);

 /* fBG->ReleaseParameter(1);
  cout<<"fBG "<<fBG->Integral(massMin, massMax) / (fBG->Integral(massMin, massMax) + fUps[nUpsState]->Integral(massMin, massMax))<<endl;
  double fBGPar0=fBG->GetParameter(1);
  double err_fBGPar0=fBG->GetParError(1);
  cout<<"fBGPar0 "<<fBGPar0<<endl;
  cout<<"err_fBGPar0 "<<err_fBGPar0<<endl;

  fBG->FixParameter(1,fBGPar0+100*err_fBGPar0);
  cout<<"fBGPar0 "<<fBG->GetParameter(1)<<endl;
  cout<<"fBG "<<fBG->Integral(massMin, massMax) / (fBG->Integral(massMin, massMax) + fUps[nUpsState]->Integral(massMin, massMax))<<endl;
  fBG->SetParameter(1,fBGPar0);
  cout<<"fBG "<<fBG->Integral(massMin, massMax) / (fBG->Integral(massMin, massMax) + fUps[nUpsState]->Integral(massMin, massMax))<<endl;
*/

  if(Y1Sto2S_SB){
cout<<"Y1Sto2S_SB fBG = "<<fBG->Integral(massMin, massMax) / (fBG->Integral(massMin, massMax) + fUps[0]->Integral(massMin, massMax)+fUps[1]->Integral(massMin, massMax))<<endl;
  }

  backgroundFrac=fracBG;

  //calculate the L and R mass windows:
  Double_t massMinBG[2], massMaxBG[2];
  massMinBG[L] = onia::massMinL;
  massMaxBG[L] = mass[UPS1S] - onia::nSigmaL*sigma[UPS1S];
  massMinBG[R] = mass[UPS3S] + onia::nSigmaR*sigma[UPS3S];
  massMaxBG[R] = onia::massMaxR;
  printf("--> L mass window: %1.3f < M < %1.3f GeV\n", massMinBG[L], massMaxBG[L]);
  printf("--> R mass window: %1.3f < M < %1.3f GeV\n", massMinBG[R], massMaxBG[R]);
//cout<<"here?"<<endl;
  bool PseudoBin=false;

  if(CombineSignalPeaks) {
	  massMin=9.15;
	  massMax=10.65;
  }

  if(!UpsMC){
  if(massMaxBG[L] > massMin){
    printf("the right sideband window is LARGER than the left signal window!!!!\n\n\n\n");
    massMaxBG[L]=9.;
    massMinBG[L]=8.6;
    massMin=9.;
    PseudoBin=true;
//    exit(0);
  }
  if(massMinBG[R] < massMax){
    printf("the left sideband window is SMALLER than the right signal window!!!!\n\n\n\n");
    massMaxBG[R]=11.4;
    massMinBG[R]=11.;
    massMax=10.;
    PseudoBin=true;
//    exit(0);
  }
  }

  if(ProjectLSBdata){
	  massMin=massMinBG[L];
	  massMax=massMaxBG[L];
  }
  if(ProjectRSBdata){
	  massMin=massMinBG[R];
	  massMax=massMaxBG[R];
  }

  if(CombineSignalPeaks) {
	  massMin=9.15;
	  massMax=10.65;
  }

  double meanMass=0;
  double MassDistCurrent=0.001;
  TH1D *hMassScanInfo = new TH1D("hMassScanInfo", "hMassScanInfo", 2, 0., 1.);

  if(MassScan){
  massMin=MassScanMin;
  massMax=MassScanMax;

  double IntCurrent = fBG->Integral(massMin, massMax);
  for(int i=1;i<1000000;i++){
	  if(fBG->Integral(massMin, massMin+i*MassDistCurrent)>IntCurrent/2.) {meanMass=massMin+i*MassDistCurrent; break;}
  }

  hMassScanInfo->SetBinContent(1,meanMass);
  hMassScanInfo->SetBinContent(2,1-fracBG);

  }

  if(Y1Sto2S_SB){
	  massMin = mass[0] + 3.*sigma[0];
	  massMax = mass[1] - 4.*sigma[1];

	  double IntCurrent = fBG->Integral(massMin, massMax);
	  for(int i=1;i<1000000;i++){
		  if(fBG->Integral(massMin, massMin+i*MassDistCurrent)>IntCurrent/2.) {meanMass=massMin+i*MassDistCurrent; break;}
	  }
	  hMassScanInfo->SetBinContent(1,meanMass);
	  hMassScanInfo->SetBinContent(2,1-fracBG);
  }


  if(UpsMC&&iPTBin>5&&fracL<0.35){
	  cout<<"using exact mass window definition of data"<<endl;

  Double_t massMinUps1S_1sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 9.38372, 9.38435, 9.38425, 9.38487, 9.38326},
    {0,0,0,0,0, 9.35644, 9.3574, 9.35555, 9.35522, 9.34896}};
  Double_t massMaxUps1S_1sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 9.518, 9.51711, 9.51826, 9.51701, 9.51941},
    {0,0,0,0,0, 9.53728, 9.53853, 9.5394, 9.54169, 9.54538}};

  Double_t massMinUps2S_1sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 9.94218, 9.94285, 9.94275, 9.9434, 9.94169},
    {0,0,0,0,0, 9.91328, 9.91429, 9.91234, 9.91198, 9.90535}};
  Double_t massMaxUps2S_1sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 10.0844, 10.0835, 10.0847, 10.0834, 10.086},
    {0,0,0,0,0, 10.1049, 10.1062, 10.1071, 10.1096, 10.1135}};

  Double_t massMinUps3S_1sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 10.2715, 10.2722, 10.2721, 10.2728, 10.271},
    {0,0,0,0,0, 10.2416, 10.2427, 10.2407, 10.2403, 10.2335}};
  Double_t massMaxUps3S_1sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 10.4185, 10.4175, 10.4188, 10.4174, 10.42},
    {0,0,0,0,0, 10.4396, 10.441, 10.4419, 10.4444, 10.4485}};

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

  Double_t massMinUps1S_3sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 9.24945, 9.2516, 9.25025, 9.25273, 9.24711},
    {0,0,0,0,0, 9.1756, 9.17626, 9.17171, 9.16874, 9.15253}};
  Double_t massMaxUps1S_3sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 9.65227, 9.64987, 9.65227, 9.64915, 9.65557},
    {0,0,0,0,0, 9.71811, 9.71966, 9.72048, 9.72149, 9.72017}};

  Double_t massMinUps2S_3sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 9.79992, 9.80219, 9.80076, 9.80339, 9.79744},
    {0,0,0,0,0, 9.72168, 9.72238, 9.72048, 9.72149, 9.72017}};
  Double_t massMaxUps2S_3sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 10.1765, 10.1763, 10.1769, 10.1765, 10.177},
    {0,0,0,0,0, 10.1721, 10.1733, 10.1728, 10.1739, 10.1725}};

  Double_t massMinUps3S_3sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 10.1765, 10.1763, 10.1769, 10.1765, 10.177},
    {0,0,0,0,0, 10.1721, 10.1733, 10.1728, 10.1739, 10.1725}};
  Double_t massMaxUps3S_3sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 10.5655, 10.5628, 10.5655, 10.562, 10.5691},
    {0,0,0,0,0, 10.6375, 10.6392, 10.6432, 10.6485, 10.6635}};


  if(nSigma==1){
	  if(nUpsState==0){
		  massMin=massMinUps1S_1sigma[iRapBin][iPTBin-1];
		  massMax=massMaxUps1S_1sigma[iRapBin][iPTBin-1];
	  }
	  if(nUpsState==1){
		  massMin=massMinUps2S_1sigma[iRapBin][iPTBin-1];
		  massMax=massMaxUps2S_1sigma[iRapBin][iPTBin-1];
	  }
	  if(nUpsState==2){
		  massMin=massMinUps3S_1sigma[iRapBin][iPTBin-1];
		  massMax=massMaxUps3S_1sigma[iRapBin][iPTBin-1];
	  }
  }

  if(nSigma==3){
	  if(nUpsState==0){
		  massMin=massMinUps1S_3sigma[iRapBin][iPTBin-1];
		  massMax=massMaxUps1S_3sigma[iRapBin][iPTBin-1];
	  }
	  if(nUpsState==1){
		  massMin=massMinUps2S_3sigma[iRapBin][iPTBin-1];
		  massMax=massMaxUps2S_3sigma[iRapBin][iPTBin-1];
	  }
	  if(nUpsState==2){
		  massMin=massMinUps3S_3sigma[iRapBin][iPTBin-1];
		  massMax=massMaxUps3S_3sigma[iRapBin][iPTBin-1];
	  }
  }

  if(nSigma==0.5){
	  if(nUpsState==0){
		  massMin=massMinUps1S_1sigma[iRapBin][iPTBin-1]+(massMaxUps1S_1sigma[iRapBin][iPTBin-1]-massMinUps1S_1sigma[iRapBin][iPTBin-1])/4.;
		  massMax=massMaxUps1S_1sigma[iRapBin][iPTBin-1]-(massMaxUps1S_1sigma[iRapBin][iPTBin-1]-massMinUps1S_1sigma[iRapBin][iPTBin-1])/4.;
	  }
	  if(nUpsState==1){
		  massMin=massMinUps2S_1sigma[iRapBin][iPTBin-1]+(massMaxUps2S_1sigma[iRapBin][iPTBin-1]-massMinUps2S_1sigma[iRapBin][iPTBin-1])/4.;
		  massMax=massMaxUps2S_1sigma[iRapBin][iPTBin-1]-(massMaxUps2S_1sigma[iRapBin][iPTBin-1]-massMinUps2S_1sigma[iRapBin][iPTBin-1])/4.;
	  }
	  if(nUpsState==2){
		  massMin=massMinUps3S_1sigma[iRapBin][iPTBin-1]+(massMaxUps3S_1sigma[iRapBin][iPTBin-1]-massMinUps3S_1sigma[iRapBin][iPTBin-1])/4.;
		  massMax=massMaxUps3S_1sigma[iRapBin][iPTBin-1]-(massMaxUps3S_1sigma[iRapBin][iPTBin-1]-massMinUps3S_1sigma[iRapBin][iPTBin-1])/4.;
	  }
  }

  if(nSigma==0.1){
	  if(nUpsState==0){
		  massMin=massMinUps1S_1sigma[iRapBin][iPTBin-1]+(massMaxUps1S_1sigma[iRapBin][iPTBin-1]-massMinUps1S_1sigma[iRapBin][iPTBin-1])/20.;
		  massMax=massMaxUps1S_1sigma[iRapBin][iPTBin-1]-(massMaxUps1S_1sigma[iRapBin][iPTBin-1]-massMinUps1S_1sigma[iRapBin][iPTBin-1])/20.;
	  }
	  if(nUpsState==1){
		  massMin=massMinUps2S_1sigma[iRapBin][iPTBin-1]+(massMaxUps2S_1sigma[iRapBin][iPTBin-1]-massMinUps2S_1sigma[iRapBin][iPTBin-1])/20.;
		  massMax=massMaxUps2S_1sigma[iRapBin][iPTBin-1]-(massMaxUps2S_1sigma[iRapBin][iPTBin-1]-massMinUps2S_1sigma[iRapBin][iPTBin-1])/20.;
	  }
	  if(nUpsState==2){
		  massMin=massMinUps3S_1sigma[iRapBin][iPTBin-1]+(massMaxUps3S_1sigma[iRapBin][iPTBin-1]-massMinUps3S_1sigma[iRapBin][iPTBin-1])/20.;
		  massMax=massMaxUps3S_1sigma[iRapBin][iPTBin-1]-(massMaxUps3S_1sigma[iRapBin][iPTBin-1]-massMinUps3S_1sigma[iRapBin][iPTBin-1])/20.;
	  }
  }

  if(nSigma==9){
	  if(nUpsState==0){
		  massMin=massMinUps1S_1sigma[iRapBin][iPTBin-1];
		  massMax=massMaxUps1S_1sigma[iRapBin][iPTBin-1]-(massMaxUps1S_1sigma[iRapBin][iPTBin-1]-massMinUps1S_1sigma[iRapBin][iPTBin-1])/2.;
	  }
	  if(nUpsState==1){
		  massMin=massMinUps2S_1sigma[iRapBin][iPTBin-1];
		  massMax=massMaxUps2S_1sigma[iRapBin][iPTBin-1]-(massMaxUps2S_1sigma[iRapBin][iPTBin-1]-massMinUps2S_1sigma[iRapBin][iPTBin-1])/2.;
	  }
	  if(nUpsState==2){
		  massMin=massMinUps3S_1sigma[iRapBin][iPTBin-1];
		  massMax=massMaxUps3S_1sigma[iRapBin][iPTBin-1]-(massMaxUps3S_1sigma[iRapBin][iPTBin-1]-massMinUps3S_1sigma[iRapBin][iPTBin-1])/2.;
	  }
  }

  if(nSigma==10){
	  if(nUpsState==0){
		  massMax=massMaxUps1S_1sigma[iRapBin][iPTBin-1];
		  massMin=massMaxUps1S_1sigma[iRapBin][iPTBin-1]-(massMaxUps1S_1sigma[iRapBin][iPTBin-1]-massMinUps1S_1sigma[iRapBin][iPTBin-1])/2.;
	  }
	  if(nUpsState==1){
		  massMax=massMaxUps2S_1sigma[iRapBin][iPTBin-1];
		  massMin=massMaxUps2S_1sigma[iRapBin][iPTBin-1]-(massMaxUps2S_1sigma[iRapBin][iPTBin-1]-massMinUps2S_1sigma[iRapBin][iPTBin-1])/2.;
	  }
	  if(nUpsState==2){
		  massMax=massMaxUps3S_1sigma[iRapBin][iPTBin-1];
		  massMin=massMaxUps3S_1sigma[iRapBin][iPTBin-1]-(massMaxUps3S_1sigma[iRapBin][iPTBin-1]-massMinUps3S_1sigma[iRapBin][iPTBin-1])/2.;
	  }
  }


}





  ActualMassMin=massMin;
  ActualMassMax=massMax;


  //calculate central fracL

  double fracLCentral;

  if(!f_BG_zero){
  double mean_LSB;
  double mean_RSB;
  double mean_nS;

  double MassDist=0.001;
  double IntLSB = fBG->Integral(massMinBG[L], massMaxBG[L]);
  for(int i=1;i<1000000;i++){
	  if(fBG->Integral(massMinBG[L], massMinBG[L]+i*MassDist)>IntLSB/2.) {mean_LSB=massMinBG[L]+i*MassDist; break;}
  }
  double IntRSB = fBG->Integral(massMinBG[R], massMaxBG[R]);
  for(int i=1;i<1000000;i++){
	  if(fBG->Integral(massMinBG[R], massMinBG[R]+i*MassDist)>IntRSB/2.) {mean_RSB=massMinBG[R]+i*MassDist; break;}
  }
  double IntSig = fBG->Integral(massMin, massMax);
  for(int i=1;i<1000000;i++){
	  if(fBG->Integral(massMin, massMin+i*MassDist)>IntSig/2.) {mean_nS=massMin+i*MassDist; break;}
  }

  fracLCentral=1-(mean_nS-mean_LSB)/(mean_RSB-mean_LSB);
  cout<<"Median LSB: "<<mean_LSB<<endl;
  cout<<"Median RSB: "<<mean_RSB<<endl;
  cout<<"Median signal region: "<<mean_nS<<endl;
  cout<<"Central FracL: "<<fracLCentral<<endl;


  }



  //build the 3D (pT, |y|, M) histos for the L and R mass sideband 
  TH3D *hBG_pTRapMass[2];
  hBG_pTRapMass[L] = new TH3D("hBG_pTRapMass_L", ";p_{T} [GeV/c]; |y|; M [GeV]", 
			      7, onia::pTRange[iRapBin][iPTBin-1], onia::pTRange[iRapBin][iPTBin],
			      2, onia::rapForPTRange[iRapBin-1], onia::rapForPTRange[iRapBin],
			      7, massMin, massMax);//*signal* mass window!
  hBG_pTRapMass[L]->Sumw2();
  //
  hBG_pTRapMass[R] = new TH3D("hBG_pTRapMass_R", ";p_{T} [GeV/c]; |y|; M [GeV]", 
			      7, onia::pTRange[iRapBin][iPTBin-1], onia::pTRange[iRapBin][iPTBin],
			      2, onia::rapForPTRange[iRapBin-1], onia::rapForPTRange[iRapBin],
			      7, massMin, massMax);//*signal* mass window!
  hBG_pTRapMass[R]->Sumw2();

  lepP = 0; lepN = 0;
  treeIn->SetBranchAddress("lepP", &lepP);
  treeIn->SetBranchAddress("lepN", &lepN);
  TLorentzVector *onia = new TLorentzVector();


  Double_t onia_mass;
  for(int iEn = 0; iEn < treeIn->GetEntries(); iEn++){ 
    Long64_t iEntry = treeIn->LoadTree(iEn);
    treeIn->GetEntry(iEntry);
    if(iEn % 10000 == 0)
      cout << "entry " << iEntry << " out of " << treeIn->GetEntries() << endl;

    *onia = *(lepP) + *(lepN);
    onia_mass = onia->M();

	  if(UpsMC||f_BG_zero) hBG_pTRapMass[L]->Fill(onia->Pt(), TMath::Abs(onia->Rapidity()), gRandom->Uniform(massMin, massMax));
	  if(UpsMC||f_BG_zero) hBG_pTRapMass[R]->Fill(onia->Pt(), TMath::Abs(onia->Rapidity()), gRandom->Uniform(massMin, massMax));

	  if(!UpsMC&&!f_BG_zero){
    if(onia_mass  > massMinBG[L] && onia_mass < massMaxBG[L])
      hBG_pTRapMass[L]->Fill(onia->Pt(), TMath::Abs(onia->Rapidity()), fBG->GetRandom(massMin, massMax));
    else if(onia_mass > massMinBG[R] && onia_mass < massMaxBG[R])
      hBG_pTRapMass[R]->Fill(onia->Pt(), TMath::Abs(onia->Rapidity()), fBG->GetRandom(massMin, massMax));
	  }

    if(onia_mass > massMin && onia_mass < massMax){
      treeOut->Fill(); //stores TLorenzVectors of the two muons

      // //store now the cosTheta and phi distributions of the signal window:
      // calcPol(*lepP, *lepN);

      // for(int iFrame = 0; iFrame < onia::kNbFrames; iFrame++)
      // 	hCosThetaPhiSignal[iFrame]->Fill(thisCosTh[iFrame], thisPhi[iFrame]);
    }


  }



/*  Char_t name2[100];
  sprintf(name2, "Reco_Onia_mass_rap%d_pT%d", iRapBin, iPTBin);
  TH1F* hMass = (TH1F*) gDirectory->Get(name2);
  hMass->Rebin(2);
  double binWidth = hMass->GetBinWidth(1); //valid only for an equal bin histogram!
  printf("binwidth = %1.2e\n", binWidth);
*/
  double nY[3];
  double nBG_;
  double binWidth = 0.02; //You have to manually change that parameter from the mass fit!!!

    nY[2] = fUps[2]->Integral(massMin, massMax)/binWidth;
    nY[1] = fUps[1]->Integral(massMin, massMax)/binWidth;
    nY[0] = fUps[0]->Integral(massMin, massMax)/binWidth;
    nBG_ = fBG->Integral(massMin, massMax)/binWidth;
    double nAll=nY[0]+nY[1]+nY[2]+nBG_;

    printf("1 sigma region num background = %1.3f\n",nBG_);
    printf("1 sigma region num 1S = %1.3f\n",nY[0]);
    printf("1 sigma region num 2S = %1.3f\n",nY[1]);
    printf("1 sigma region num 3S = %1.3f\n",nY[2]);
    printf("1 sigma region num all = %1.3f\n",nAll);
    printf("1 sigma region calcNumAll - numEventsInDataSet = %1.3f\n",nAll-treeOut->GetEntries());

    double tempBfrac=nBG_/(treeOut->GetEntries());
    printf("1 sigma region background fraction = %1.3f\n",tempBfrac);
    printf("Used           background fraction = %1.3f\n",backgroundFrac);

    SignalEvents=nY[nUpsState];

    double BackgroundEvents=SignalEvents*(1-backgroundFrac)/backgroundFrac;

    err_backgroundFrac=TMath::Power(SignalEvents*BackgroundEvents,0.5)/TMath::Power(SignalEvents+BackgroundEvents,1.5);

  //now, add the L and R 3D (pT, |y|, M) histos
  TH3D *hBG_pTRapMassSum;
  hBG_pTRapMass[L]->Scale(fracL/hBG_pTRapMass[L]->Integral());
  hBG_pTRapMass[R]->Scale((1.-fracL)/hBG_pTRapMass[R]->Integral());
  sprintf(name, "background_pTrapMass");
  hBG_pTRapMassSum = (TH3D*) hBG_pTRapMass[L]->Clone(name);
  hBG_pTRapMassSum->Add(hBG_pTRapMass[R]);

  //write the output
  fOut->cd();
  treeOut->Write();

  for(int iFrame = 0; iFrame < onia::kNbFrames; iFrame++){
    hBG_cosThetaPhi[iFrame]->Write();
    hBG_cosThetaPhiLR[iFrame][L]->Write();
    hBG_cosThetaPhiLR[iFrame][R]->Write();
    // hCosThetaPhiSignal[iFrame]->Write();
  }
  hBG_pTRapMassSum->Write();
  hFracBG->Write();
  if(MassScan){
	  hMassScanInfo->Write();
  }
  fOut->Close();
  fIn->Close();

  return fracLCentral;
}
コード例 #14
0
ファイル: GetSomePASHistos.C プロジェクト: haweber/OneLepStop
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;
}
コード例 #15
0
void execCheckErrors(bool what = 0)
{
  TTree *tree = 0;
  TFile *file = 0;
  if (what == 0) {
    tree = new TTree("ntuple","");
    float px = 0;
    tree->Branch("px",&px);
    TString str;
    tree->Branch("str",&str);
    tree->Fill();
    tree->ResetBranchAddresses(); 
  } else if (what == 1) {
    file = new TFile("hsimple.root");
    tree = (TTree*)file->Get("ntuple");
  } else {
    tree = new TChain("ntuple", "ntuple");
    ((TChain*)tree)->Add("hsimple.root");
  }
  // tree->SetBranchStatus("*", 1);
  // tree->SetBranchStatus("px", 1);
  // std::cout << "fTreeNumber = " << tree->GetTreeNumber() << std::endl;
  tree->LoadTree(0); // REQUIRED
  // std::cout << "fTreeNumber = " << tree->GetTreeNumber() << std::endl;
  
  TBranch *p = ((TBranch *)-1);
  Int_t r;
  
  Float_t px, fake_px;
  Float_t *pxp = new Float_t();
  Float_t *fake_pxp = new Float_t();
  
  Int_t ix;
  Int_t *ixp = new Int_t();
  
  TString s;
  TString *sp = new TString();
  
  TObjString os;
  TObjString *osp = new TObjString();
  
  // Float_t ... (should be fine)
  std::cout << std::endl << "ALL should be FINE ... " << std::endl;
  p = ((TBranch *)-1);
  r = tree->SetBranchAddress("px", &px, &p);
  std::cout << "Float_t ... " << r << std::endl;
  if (p==((TBranch*)-1)) {
     std::cout << "p unchanged\n";
  } else if (p==0) {
     std::cout << "p set to zero\n";
  } else {
     std::cout << "p set to the branch address\n";
  }
  r = tree->SetBranchAddress("px", &px);
  std::cout << "Float_t ... "  << r << std::endl;
  r = tree->SetBranchAddress("px", pxp);
  std::cout << "Float_t ... "  << r << std::endl;
  r = tree->SetBranchAddress("px", &pxp);
  std::cout << "Float_t ... "  << r << std::endl;
  
  // Int_t ...  (should fail)
  std::cout << std::endl << "ALL should FAIL ... " << std::endl;
  p = ((TBranch *)-1);
  r = tree->SetBranchAddress("px", &ix, &p);
  std::cout << "Int_t ...  "  << r << std::endl;
  if (p==((TBranch*)-1)) {
     std::cout << "p unchanged\n";
  } else if (p==0) {
     std::cout << "p set to zero\n";
  } else {
     std::cout << "p set to the branch address\n";
  }
  r = tree->SetBranchAddress("px", &ix);
  std::cout << "Int_t ...  "  << r << std::endl;
  r = tree->SetBranchAddress("px", ixp);
  std::cout << "Int_t ...  "  << r << std::endl;
  r = tree->SetBranchAddress("px", &ixp);
  std::cout << "Int_t ...  "  << r << std::endl;
  
  // TString ... (should fail)
  std::cout << std::endl << "ALL should FAIL ... " << std::endl;
  p = ((TBranch *)-1);
  r = tree->SetBranchAddress("px", &s, &p);
  std::cout << "TString ... "  << r << std::endl;
  if (p==((TBranch *)-1)) {
     std::cout << "p unchanged\n";
  } else if (p==0) {
     std::cout << "p set to zero\n";
  } else {
     std::cout << "p set to the branch address\n";
  }
  r = tree->SetBranchAddress("px", sp);
  std::cout << "TString ... "  << r << std::endl;
  r = tree->SetBranchAddress("px", &sp);
  std::cout << "TString ... "  << r << std::endl;
  
  // TObjString ... (should fail)
  std::cout << std::endl << "ALL should FAIL ... " << std::endl;
  p = ((TBranch *)-1);
  r = tree->SetBranchAddress("px", &os, &p);
  std::cout << "TObjString ... "  << r << std::endl;
  if (p==((TBranch*)-1)) {
     std::cout << "p unchanged\n";
  } else if (p==0) {
     std::cout << "p set to zero\n";
  } else {
     std::cout << "p set to the branch address\n";
  }
  r = tree->SetBranchAddress("px", osp);
  std::cout << "TObjString ... "  << r << std::endl;
  r = tree->SetBranchAddress("px", &osp);
  std::cout << "TObjString ... "  << r << std::endl;
  
  // nonexistent branch ... (should fail)
  std::cout << std::endl << "ALL should FAIL ... " << std::endl;
  p = ((TBranch *)-1);
  r = tree->SetBranchAddress("fake_px", &fake_px, &p);
  std::cout << "nonexistent branch ... "  << r << std::endl;
  if (p==((TBranch*)-1)) {
     std::cout << "p unchanged\n";
  } else if (p==0) {
     std::cout << "p set to zero\n";
  } else {
     std::cout << "p set to the branch address\n";
  }
  r = tree->SetBranchAddress("fake_px", &fake_px);
  std::cout << "nonexistent branch ... "  << r << std::endl;
  r = tree->SetBranchAddress("fake_px", fake_pxp);
  std::cout << "nonexistent branch ... "  << r << std::endl;
  r = tree->SetBranchAddress("fake_px", &fake_pxp);
  std::cout << "nonexistent branch ... "  << r << std::endl;

  // Float for TString ... (should fail)
  std::cout << std::endl << "ALL should FAIL ... " << std::endl;
  p = ((TBranch *)-1);
  r = tree->SetBranchAddress("str", &px, &p);
  std::cout << "Float ... "  << r << std::endl;
  if (p==((TBranch*)-1)) {
     std::cout << "p unchanged\n";
  } else if (p==0) {
     std::cout << "p set to zero\n";
  } else {
     std::cout << "p set to the branch address\n";
  }
  r = tree->SetBranchAddress("str", &px);
  std::cout << "Float ... "  << r << std::endl;
  r = tree->SetBranchAddress("str", pxp);
  std::cout << "Float ... "  << r << std::endl;
  r = tree->SetBranchAddress("str", &pxp);
  std::cout << "Float ... "  << r << std::endl;
  
   
  TChain *ch = new TChain("MonoData");
  ch->Add("memleak.root");
  ch->LoadTree(0);
  r = ch->SetBranchAddress("mono", &sp, &p);
  std::cout << "From chain, TString ... "  << r << std::endl;

  TTree *treech = ch;
  r = treech->SetBranchAddress("mono", &sp, &p);
  std::cout << "From tree, TString ... "  << r << std::endl;
   
}
コード例 #16
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;
}
コード例 #17
0
ファイル: ScanChain.C プロジェクト: wsicheng/MuonTagAndProbe
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;
}
コード例 #18
0
int main() {
	
		//get the run list ,set branch addresses and
	TString inputFiles="input.txt";

	BranchBase *t = new BranchBase(inputFiles);

	//get the tree holding the DPD variables
	TTree* itsTree = t->fChain;
	  
	//output file and tree
	TFile *outfile   = new TFile("skimmed.root","recreate");
	TTree *MyTree    = new TTree("data","data");

	//in the output tree
	MuonBranch *mu = new MuonBranch;
	mu->Set_Muon_Branches(MyTree);

	//Set the global/trigger branches to be stored
	//in the output tree
	TrigGlobalBranch* glob = new TrigGlobalBranch;
  	glob->Set_Trig_and_Global_Branches(MyTree);

	//set branch status and make sure
	//entries!=0
	int result = t->TurnOnBranches();

	if (result!=0) {

		std::cout << "Exiting program. " << std::endl; 
    		system("rm skimmed.root");

		exit(0);
	}

	int nentries = itsTree->GetEntries();
	if (nentries==0) {

		std::cout << "Zero entries in itsTree. Exiting program. " << std::endl;
		exit(0);
	}

	//event loop
	for (Long64_t jentry=0; jentry<nentries;jentry++){
		
		//Long64_t ientry = t->fChain->LoadTree(jentry);
		//if(jentry==1000) break; //temp hack
		Long64_t ientry = itsTree->LoadTree(jentry);
		if (ientry < 0) break;

		itsTree->GetEntry(jentry); //  nbytes += nb;
		//t->fChain->GetEntry(jentry); //  nbytes += nb;
		//std::cout << "muons:" << mu->mu_muid_n <<std::endl;
    		
		if(jentry%1000==0) printf("running event %5dk\n",(int) jentry/1000);

		bool event = t->EventCuts();
		if(!event) continue;

    			mu->Fill_Muon_Branches();
    			glob->Fill_Trig_and_Global_Branches();
    			//Fill_FCal_Branches           ();
    			//Fill_Track_Branches          (); 

    		MyTree->Fill();

	} //event loop

	outfile->cd();
  	outfile->Write();
  	outfile -> Close();
	
	delete mu;
	delete glob;
	delete t;
  	return 0;

}
コード例 #19
0
ファイル: looperCR2lep.C プロジェクト: dsklein/StopLooper
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;
}
コード例 #20
0
ファイル: GrowTree.C プロジェクト: swang373/VHbbUF
////////////////////////////////////////////////////////////////////////////////
/// Main                                                                     ///
////////////////////////////////////////////////////////////////////////////////
void GrowTree(TString process, std::string regMethod="BDTG", Long64_t beginEntry=0, Long64_t endEntry=-1)
{
    gROOT->SetBatch(1);
    TH1::SetDefaultSumw2(1);
    gROOT->LoadMacro("HelperFunctions.h");  //< make functions visible to TTreeFormula

    if (!TString(gROOT->GetVersion()).Contains("5.34")) {
        std::cout << "INCORRECT ROOT VERSION! Please use 5.34:" << std::endl;
        std::cout << "source /uscmst1/prod/sw/cms/slc5_amd64_gcc462/lcg/root/5.34.02-cms/bin/thisroot.csh" << std::endl;
        std::cout << "Return without doing anything." << std::endl;
        return;
    }

    const TString indir   = "/afs/cern.ch/work/d/degrutto/public/MiniAOD/ZnnHbb_Phys14_PU20bx25/skimV11/";
    const TString outdir  = "/afs/cern.ch/work/d/degrutto/public/MiniAOD/ZnnHbb_Phys14_PU20bx25/skimV11/step3/";
    const TString prefix  = "skim_";
    const TString suffix  = ".root";

    TFile *input = TFile::Open(indir + prefix + process + suffix);
    if (!input) {
        std::cout << "ERROR: Could not open input file." << std::endl;
        exit(1);
    }
    /// Make output directory if it doesn't exist
    if (gSystem->AccessPathName(outdir))
        gSystem->mkdir(outdir);

    std::cout << "--- GrowTree                 : Using input file: " << input->GetName() << std::endl;
    TTree *inTree = (TTree *) input->Get("tree");
    TH1F  *hcount = (TH1F *) input->Get("Count");
    TFile *output(0);
    if (beginEntry == 0 && endEntry == -1)
        output = TFile::Open(outdir + "Step3_" + process + suffix, "RECREATE");
    else
        output = TFile::Open(outdir + "Step3_" + process + TString::Format("_%Li_%Li", beginEntry, endEntry) + suffix, "RECREATE");
    TTree *outTree = inTree->CloneTree(0); // Do no copy the data yet
    /// The clone should not delete any shared i/o buffers.
    ResetDeleteBranches(outTree);
    


    ///-- Set branch addresses -------------------------------------------------
    EventInfo EVENT;
    double hJet_pt[MAXJ], hJet_eta[MAXJ], hJet_phi[MAXJ], hJet_m[MAXJ], hJet_ptRaw[MAXJ], hJet_genPt[MAXJ];
    int hJCidx[2];

    inTree->SetBranchStatus("*", 1);

    inTree->SetBranchStatus("hJCidx",1);
    inTree->SetBranchStatus("Jet_*",1);
    inTree->SetBranchAddress("hJCidx", &hJCidx);
    inTree->SetBranchAddress("Jet_pt", &hJet_pt);

    inTree->SetBranchAddress("Jet_eta", &hJet_eta);
    inTree->SetBranchAddress("Jet_phi", &hJet_phi);
    inTree->SetBranchAddress("Jet_mass", &hJet_m);
    inTree->SetBranchAddress("Jet_rawPt", &hJet_ptRaw);

    inTree->SetBranchAddress("Jet_mcPt", &hJet_genPt);


    ///-- Make new branches ----------------------------------------------------
    int EVENT_run, EVENT_event;  // set these as TTree index?
    float lumi_ = lumi, efflumi, efflumi_old, 
        efflumi_UEPS_up, efflumi_UEPS_down;
    float hJet_ptReg[2];
    float HptNorm, HptGen, HptReg;
    float HmassNorm, HmassGen, HmassReg;

    outTree->Branch("EVENT_run", &EVENT_run, "EVENT_run/I");
    outTree->Branch("EVENT_event", &EVENT_event, "EVENT_event/I");
    outTree->Branch("lumi", &lumi_, "lumi/F");
    outTree->Branch("efflumi", &efflumi, "efflumi/F");
    outTree->Branch("efflumi_old", &efflumi_old, "efflumi_old/F");
    outTree->Branch("efflumi_UEPS_up", &efflumi_UEPS_up, "efflumi_UEPS_up/F");
    outTree->Branch("efflumi_UEPS_down", &efflumi_UEPS_down, "efflumi_UEPS_down/F");
    outTree->Branch("hJet_ptReg", &hJet_ptReg, "hJet_ptReg[2]/F");
    
    outTree->Branch("HptNorm", &HptNorm, "HptNorm/F");
    outTree->Branch("HptGen", &HptGen, "HptGen/F");
    outTree->Branch("HptReg", &HptReg, "HptReg/F");
    outTree->Branch("HmassNorm", &HmassNorm, "HmassNorm/F");
    outTree->Branch("HmassGen", &HmassGen, "HmassGen/F");
    outTree->Branch("HmassReg", &HmassReg, "HmassReg/F");

    /// Get effective lumis
    std::map < std::string, float > efflumis = GetLumis();
    efflumi = efflumis[process.Data()];
    assert(efflumi > 0);
    efflumi_old       = efflumi;
    efflumi_UEPS_up   = efflumi * hcount->GetBinContent(2) / hcount->GetBinContent(3);
    efflumi_UEPS_down = efflumi * hcount->GetBinContent(2) / hcount->GetBinContent(4);



    TTreeFormula* ttf_lheweight = new TTreeFormula("ttf_lheweight", Form("%f", efflumi), inTree);
#ifdef STITCH
    std::map < std::string, std::string > lheweights = GetLHEWeights();
    TString process_lhe = process;
    if (process_lhe.BeginsWith("WJets") && process_lhe != "WJetsHW")
        process_lhe = "WJets";
    else if (process_lhe.BeginsWith("ZJets") && process_lhe != "ZJetsHW")
        process_lhe = "ZJets";
    else 
        process_lhe = "";
    TString lheweight = lheweights[process_lhe.Data()];
    if (lheweight != "") {
        delete ttf_lheweight;
        
        // Bug fix for ZJetsPtZ100
        if (process == "ZJetsPtZ100")
            lheweight.ReplaceAll("lheV_pt", "999");
        std::cout << "BUGFIX: " << lheweight << std::endl;
        ttf_lheweight = new TTreeFormula("ttf_lheweight", lheweight, inTree);
    }
#endif
    ttf_lheweight->SetQuickLoad(1);

    // regression stuff here

    
    ///-- Setup TMVA Reader ----------------------------------------------------
    TMVA::Tools::Instance();  //< This loads the library
    TMVA::Reader * reader = new TMVA::Reader("!Color:!Silent");

    /// Get the variables
    const std::vector < std::string > & inputExpressionsReg = GetInputExpressionsReg();
    
   const UInt_t nvars = inputExpressionsReg.size();
   
    Float_t readerVars[nvars];
    int idx_rawpt = -1, idx_pt = -1, idx_et = -1, idx_mt = -1;
   
    for (UInt_t iexpr = 0; iexpr < nvars; iexpr++) {
        const TString& expr = inputExpressionsReg.at(iexpr);
        reader->AddVariable(expr, &readerVars[iexpr]);
        if      (expr.BeginsWith("breg_rawptJER := "))  idx_rawpt = iexpr;
        else if (expr.BeginsWith("breg_pt := "))        idx_pt = iexpr;
        else if (expr.BeginsWith("breg_et := "))        idx_et = iexpr;
        else if (expr.BeginsWith("breg_mt := "))        idx_mt = iexpr;
    }
    //    assert(idx_rawpt!=-1 && idx_pt!=-1 && idx_et!=-1 && idx_mt!=-1);
    assert(idx_rawpt!=-1 && idx_pt!=-1 );

    /// Setup TMVA regression inputs
    const std::vector < std::string > & inputExpressionsReg0 = GetInputExpressionsReg0();
    const std::vector < std::string > & inputExpressionsReg1 = GetInputExpressionsReg1();
    assert(inputExpressionsReg0.size() == nvars);
    assert(inputExpressionsReg1.size() == nvars);

    /// Load TMVA weights
    TString weightdir  = "weights/";
    TString weightfile = weightdir + "TMVARegression_" + regMethod + ".testweights.xml";
    reader->BookMVA(regMethod + " method", weightfile);
    
    TStopwatch sw;
    sw.Start();


    /// Create TTreeFormulas
    TTreeFormula *ttf = 0;
    std::vector < TTreeFormula * >::const_iterator formIt, formItEnd;
    std::vector < TTreeFormula * > inputFormulasReg0;
    std::vector < TTreeFormula * > inputFormulasReg1;
    std::vector < TTreeFormula * > inputFormulasFJReg0;
    std::vector < TTreeFormula * > inputFormulasFJReg1;
    std::vector < TTreeFormula * > inputFormulasFJReg2;

    
    for (UInt_t iexpr = 0; iexpr < nvars; iexpr++) {
        ttf = new TTreeFormula(Form("ttfreg%i_0", iexpr), inputExpressionsReg0.at(iexpr).c_str(), inTree);
        ttf->SetQuickLoad(1);
        inputFormulasReg0.push_back(ttf);
        ttf = new TTreeFormula(Form("ttfreg%i_1", iexpr), inputExpressionsReg1.at(iexpr).c_str(), inTree);
        ttf->SetQuickLoad(1);
        inputFormulasReg1.push_back(ttf);
    }
 


    ///-- Loop over events -----------------------------------------------------
    Int_t curTree = inTree->GetTreeNumber();
    const Long64_t nentries = inTree->GetEntries();
    if (endEntry < 0)  endEntry = nentries;

    Long64_t ievt = 0;
    for (ievt=TMath::Max(ievt, beginEntry); ievt<TMath::Min(nentries, endEntry); ievt++) {
        if (ievt % 2000 == 0)
            std::cout << "--- ... Processing event: " << ievt << std::endl;
    
        const Long64_t local_entry = inTree->LoadTree(ievt);  // faster, but only for TTreeFormula
        if (local_entry < 0)  break;
        inTree->GetEntry(ievt);  // same event as received by LoadTree()

        if (inTree->GetTreeNumber() != curTree) {
            curTree = inTree->GetTreeNumber();

            for (formIt=inputFormulasReg0.begin(), formItEnd=inputFormulasReg0.end(); formIt!=formItEnd; formIt++)
                (*formIt)->UpdateFormulaLeaves();  // if using TChain
            for (formIt=inputFormulasReg1.begin(), formItEnd=inputFormulasReg1.end(); formIt!=formItEnd; formIt++)
                (*formIt)->UpdateFormulaLeaves();  // if using TChain
            for (formIt=inputFormulasFJReg0.begin(), formItEnd=inputFormulasFJReg0.end(); formIt!=formItEnd; formIt++)
                (*formIt)->UpdateFormulaLeaves();  // if using TChain
            for (formIt=inputFormulasFJReg1.begin(), formItEnd=inputFormulasFJReg1.end(); formIt!=formItEnd; formIt++)
                (*formIt)->UpdateFormulaLeaves();  // if using TChain
            for (formIt=inputFormulasFJReg2.begin(), formItEnd=inputFormulasFJReg2.end(); formIt!=formItEnd; formIt++)
                (*formIt)->UpdateFormulaLeaves();  // if using TChain

            ttf_lheweight->UpdateFormulaLeaves();
        }


        /// These need to be called when arrays of variable size are used in TTree.
        for (formIt=inputFormulasReg0.begin(), formItEnd=inputFormulasReg0.end(); formIt!=formItEnd; formIt++)
            (*formIt)->GetNdata();
        for (formIt=inputFormulasReg1.begin(), formItEnd=inputFormulasReg1.end(); formIt!=formItEnd; formIt++)
            (*formIt)->GetNdata();
        for (formIt=inputFormulasFJReg0.begin(), formItEnd=inputFormulasFJReg0.end(); formIt!=formItEnd; formIt++)
            (*formIt)->GetNdata();
        for (formIt=inputFormulasFJReg1.begin(), formItEnd=inputFormulasFJReg1.end(); formIt!=formItEnd; formIt++)
            (*formIt)->GetNdata();
        for (formIt=inputFormulasFJReg2.begin(), formItEnd=inputFormulasFJReg2.end(); formIt!=formItEnd; formIt++)
            (*formIt)->GetNdata();

        ttf_lheweight->GetNdata();
        /// Fill branches
        EVENT_run = EVENT.run;
        EVENT_event = EVENT.event;



#ifdef STITCH        
        efflumi           = ttf_lheweight->EvalInstance();
	//        efflumi_UEPS_up   = efflumi * hcount->GetBinContent(2) / hcount->GetBinContent(3);
        //efflumi_UEPS_down = efflumi * hcount->GetBinContent(2) / hcount->GetBinContent(4);
#endif
    
        bool verbose = false;
 
	for (Int_t ihj = 0; ihj < 2; ihj++) {

   
            /// Evaluate TMVA regression output
            for (UInt_t iexpr = 0; iexpr < nvars; iexpr++) {
                if (ihj==0) {
                    readerVars[iexpr] = inputFormulasReg0.at(iexpr)->EvalInstance();

                } else if (ihj==1) {
                    readerVars[iexpr] = inputFormulasReg1.at(iexpr)->EvalInstance();
                }
            }

	    hJet_ptReg[ihj]               = (reader->EvaluateRegression(regMethod + " method"))[0];
            if (verbose)  std::cout << readerVars[idx_pt] << " " << readerVars[idx_rawpt] <<  " " << hJet_pt[ihj] << " " << hJet_ptReg[ihj] << " " << hJet_genPt[ihj] << std::endl;
        const TLorentzVector p4Zero                     = TLorentzVector(0., 0., 0., 0.);
	//	int idx =  hJCidx[0] ;
	//	std::cout << "the regressed pt for jet 0 is " << hJet_ptReg[0] << "; the hJCidx is " << hJCidx[0] << ", hence the origianl pt is " <<  hJet_pt[idx] << std::endl;

	
       
        const TLorentzVector& hJet_p4Norm_0             = makePtEtaPhiM(hJet_pt[hJCidx[0]]                , hJet_pt[hJCidx[0]], hJet_eta[hJCidx[0]], hJet_phi[hJCidx[0]], hJet_m[hJCidx[0]]);
        const TLorentzVector& hJet_p4Norm_1             = makePtEtaPhiM(hJet_pt[hJCidx[1]]                , hJet_pt[hJCidx[1]], hJet_eta[hJCidx[1]], hJet_phi[hJCidx[1]], hJet_m[hJCidx[1]]);
        const TLorentzVector& hJet_p4Gen_0              = hJet_genPt[hJCidx[0]] > 0 ? 
                                                          makePtEtaPhiM(hJet_genPt[hJCidx[0]]             , hJet_pt[hJCidx[0]], hJet_eta[hJCidx[0]], hJet_phi[hJCidx[0]], hJet_m[hJCidx[0]]) : p4Zero;
        const TLorentzVector& hJet_p4Gen_1              = hJet_genPt[hJCidx[1]] > 0 ? 
                                                          makePtEtaPhiM(hJet_genPt[hJCidx[1]]             , hJet_pt[hJCidx[1]], hJet_eta[hJCidx[1]], hJet_phi[hJCidx[1]], hJet_m[hJCidx[1]]) : p4Zero;
        const TLorentzVector& hJet_p4Reg_0              = makePtEtaPhiM(hJet_ptReg[0]             , hJet_pt[hJCidx[0]], hJet_eta[hJCidx[0]], hJet_phi[hJCidx[0]], hJet_m[hJCidx[0]]);
        const TLorentzVector& hJet_p4Reg_1              = makePtEtaPhiM(hJet_ptReg[1]             , hJet_pt[hJCidx[1]], hJet_eta[hJCidx[1]], hJet_phi[hJCidx[1]], hJet_m[hJCidx[1]]);
        HptNorm             = (hJet_p4Norm_0             + hJet_p4Norm_1            ).Pt();
        HptGen              = (hJet_p4Gen_0              + hJet_p4Gen_1             ).Pt();
        HptReg              = (hJet_p4Reg_0              + hJet_p4Reg_1             ).Pt();
        HmassNorm             = (hJet_p4Norm_0             + hJet_p4Norm_1            ).M();
        HmassGen              = (hJet_p4Gen_0              + hJet_p4Gen_1             ).M();
        HmassReg              = (hJet_p4Reg_0              + hJet_p4Reg_1             ).M();
	//        std::cout << "HmassReg is " << HmassReg << std::endl; 
	
	}
        outTree->Fill();  // fill it!
    }  // end loop over TTree entries

    /// Get elapsed time
    sw.Stop();
    std::cout << "--- End of event loop: ";
    sw.Print();

    output->cd();
    outTree->Write();
    output->Close();
    input->Close();

    delete input;
    delete output;
    for (formIt=inputFormulasReg0.begin(), formItEnd=inputFormulasReg0.end(); formIt!=formItEnd; formIt++)
        delete *formIt;
    for (formIt=inputFormulasReg1.begin(), formItEnd=inputFormulasReg1.end(); formIt!=formItEnd; formIt++)
        delete *formIt;
    for (formIt=inputFormulasFJReg0.begin(), formItEnd=inputFormulasFJReg0.end(); formIt!=formItEnd; formIt++)
        delete *formIt;
    for (formIt=inputFormulasFJReg1.begin(), formItEnd=inputFormulasFJReg1.end(); formIt!=formItEnd; formIt++)
        delete *formIt;
    for (formIt=inputFormulasFJReg2.begin(), formItEnd=inputFormulasFJReg2.end(); formIt!=formItEnd; formIt++)
        delete *formIt;

    delete ttf_lheweight;

    std::cout << "==> GrowTree is done!" << std::endl << std::endl;
    return;
}
コード例 #21
0
void computeElectronIDEfficiency(WpType wp)
{

  // This statement below should not be needed, but in one particular node I had to
  // add it, somehow the vector header was not loaded automatically there.
  gROOT->ProcessLine("#include <vector>"); 

  if( (int)wp<0 || (int)wp>nWP) assert(0);
  printf("Compute the efficiencies for the working point %s\n", wpName[wp].Data());

  //
  // Find the tree
  //
  TFile *file1 = new TFile(fname);
  if( !file1 )
    assert(0);
  TTree *tree = (TTree*)file1->Get(treename);
  if( !tree )
    assert(0);

  // Event-level variables:
  int nEle;
  // Per-electron variables
  // Kinematics
  std::vector <float> *pt = 0;     
  std::vector <float> *eta = 0;    
  std::vector <float> *dz = 0;    
  std::vector <int> *passConversionVeto = 0;    
  std::vector <int> *passChosenId = 0;    
  std::vector <int> *isTrue = 0;    

  // Declare branches
  TBranch *b_nEle = 0;
  TBranch *b_pt = 0;
  TBranch *b_eta = 0;
  TBranch *b_dz = 0;
  TBranch *b_passConversionVeto = 0;
  TBranch *b_passChosenId = 0;
  TBranch *b_isTrue = 0;

  // Connect variables and branches to the tree with the data
  tree->SetBranchAddress("nEle", &nEle, &b_nEle);
  tree->SetBranchAddress("pt", &pt, &b_pt);
  tree->SetBranchAddress("eta", &eta, &b_eta);

  tree->SetBranchAddress("dz", &dz, &b_dz);
  tree->SetBranchAddress("passConversionVeto", &passConversionVeto, &b_passConversionVeto);

  if( wp == WP_VETO )
    tree->SetBranchAddress("passVetoId", &passChosenId, &b_passChosenId);
  else if( wp == WP_LOOSE )
    tree->SetBranchAddress("passLooseId", &passChosenId, &b_passChosenId);
  else if( wp == WP_MEDIUM)
    tree->SetBranchAddress("passMediumId", &passChosenId, &b_passChosenId);
  else if( wp == WP_TIGHT)
    tree->SetBranchAddress("passTightId", &passChosenId, &b_passChosenId);
  else
    assert(0);
  tree->SetBranchAddress("isTrue", &isTrue, &b_isTrue);

  // Declare event counters for efficiency calculations
  double sumSignalDenomEB = 0;
  double sumSignalNumEB   = 0;
  double sumSignalDenomEE = 0;
  double sumSignalNumEE   = 0;
  double sumBackDenomEB = 0;
  double sumBackNumEB   = 0;
  double sumBackDenomEE = 0;
  double sumBackNumEE   = 0;

  double sumSignalDenomEBErr2 = 0;
  double sumSignalNumEBErr2   = 0;
  double sumSignalDenomEEErr2 = 0;
  double sumSignalNumEEErr2   = 0;
  double sumBackDenomEBErr2 = 0;
  double sumBackNumEBErr2   = 0;
  double sumBackDenomEEErr2 = 0;
  double sumBackNumEEErr2   = 0;

  // 
  // Loop over events
  //
  UInt_t maxEvents = tree->GetEntries();
  if( smallEventCount )
    maxEvents = std::min((float)10000, (float)maxEvents);
  if(verbose)
    printf("Start loop over events, total events = %lld\n", 
           tree->GetEntries() );
  for(UInt_t ievent = 0; ievent < maxEvents; ievent++){

    if( ievent%100000 == 0){
      printf("."); fflush(stdout);
    }
    Long64_t tentry = tree->LoadTree(ievent);

    // Load the value of the number of the electrons in the event    
    b_nEle->GetEntry(tentry);
    if(verbose)
      printf("Event %d, number of electrons %u\n", ievent, nEle);

    // Get data for all electrons in this event, only vars of interest
    b_pt->GetEntry(tentry);
    b_eta->GetEntry(tentry);
    b_dz->GetEntry(tentry);
    b_passConversionVeto->GetEntry(tentry);
    b_passChosenId->GetEntry(tentry);
    b_isTrue->GetEntry(tentry);

    // Loop over electrons
    for(int iele = 0; iele < nEle; iele++){
      
      // Preselection
      if( !(pt->at(iele) > ptmin && pt->at(iele) < ptmax ) ) continue;
      if( fabs(eta->at(iele))>1.4442 && fabs(eta->at(iele))<1.566) continue;
      if( fabs(eta->at(iele))>2.5 ) continue;
      // 
      if( ! (fabs(dz->at(iele))<1) ) continue;
      if( ! (passConversionVeto->at(iele) == 1) ) continue;

      bool isBarrel = (fabs(eta->at(iele)) < 1.479);
      
      if(verbose)
	printf(" next electron pt=%f id decision is %d\n",
	       pt->at(iele),
	       passChosenId->at(iele));

      double weight = 1.0;

      int isMatched = isTrue->at(iele);

      // Fill signal counters
      if( isMatched == 1 ) {

	if( isBarrel ) {
	  sumSignalDenomEB += weight;
	  sumSignalDenomEBErr2 += weight*weight;
	  if( passChosenId->at(iele) ) {
	    sumSignalNumEB += weight;
	    sumSignalNumEBErr2 += weight*weight;
	  }
	} else {
	  sumSignalDenomEE += weight;
	  sumSignalDenomEEErr2 += weight*weight;          
	  if( passChosenId->at(iele) ) {
	    sumSignalNumEE += weight;
	    sumSignalNumEEErr2 += weight*weight;
	  }
	  
	}// end barrel / endcap
      } // end if signal
      
      // Fill background counters
      // (use unmatched (0) or matched to non-prompt non-tau electrons (3) )
      if( isMatched==0 || isMatched==3 ) {
	
        if( isBarrel ) {
	  
          sumBackDenomEB += weight;
          sumBackDenomEBErr2 += weight*weight;
          if( passChosenId->at(iele) ) {
            sumBackNumEB += weight;
            sumBackNumEBErr2 += weight*weight;
          }
        } else {
          sumBackDenomEE += weight;
          sumBackDenomEEErr2 += weight*weight;    
          if( passChosenId->at(iele) ) {
            sumBackNumEE += weight;
            sumBackNumEEErr2 += weight*weight;
          }
	  
        }// end barrel / endcap
      } // end if background
      
    } // end loop over photons
    
    
  }// end loop over events  

  // DEBUG
  //if(verbose){
    printf("barrel signal pass=%.1f   total=%.1f\n", sumSignalNumEB, sumSignalDenomEB);
    printf("endcap signal pass=%.1f   total=%.1f\n", sumSignalNumEE, sumSignalDenomEE);
    //}

  printf("\nEfficiencies for the working point %s\n", wpName[wp].Data());

  // Compute signal efficiencies
  double effSignalEB = sumSignalNumEB / sumSignalDenomEB;
  double effSignalEBErr = sqrt( sumSignalDenomEBErr2 
                                * effSignalEB*(1-effSignalEB)
                                /(sumSignalDenomEB*sumSignalDenomEB) );
  printf("Signal barrel efficiency: %5.1f +- %5.1f %%\n", 
         effSignalEB*100, effSignalEBErr*100 );

  double effSignalEE = sumSignalNumEE / sumSignalDenomEE;
  double effSignalEEErr = sqrt( sumSignalDenomEEErr2 
                                * effSignalEE*(1-effSignalEE)
                                /(sumSignalDenomEE*sumSignalDenomEE) );
  printf("Signal endcap efficiency: %5.1f +- %5.1f %%\n", 
         effSignalEE*100, effSignalEEErr*100 );

  // Compute background efficiencies
  double effBackEB = sumBackNumEB / sumBackDenomEB;
  double effBackEBErr = sqrt( sumBackDenomEBErr2 
                                * effBackEB*(1-effBackEB)
                                /(sumBackDenomEB*sumBackDenomEB) );
  printf("Background barrel efficiency: %5.1f +- %5.1f %%\n", 
         effBackEB*100, effBackEBErr*100 );

  double effBackEE = sumBackNumEE / sumBackDenomEE;
  double effBackEEErr = sqrt( sumBackDenomEEErr2 
                                * effBackEE*(1-effBackEE)
                                /(sumBackDenomEE*sumBackDenomEE) );
  printf("Background endcap efficiency: %5.1f +- %5.1f %%\n", 
         effBackEE*100, effBackEEErr*100 );

}
コード例 #22
0
void inflateTree(const char *name = "h42",
                 const char *in = "root://eospps.cern.ch///eos/ppsscratch/test/h1big.root",
                 const char *out = "/tmp/h1big.root",  Int_t fact = 1)
{
	TStopwatch sw;
	sw.Start();
	
   // Get the input tree from the input file
   TFile *fin = TFile::Open(in);
   if (!fin || fin->IsZombie()) {
      Printf("inflateTree", "could not open input file: %s", in);
      return;
   }
   TTree *tin = (TTree *) fin->Get(name);
   if (!tin) {
      Printf("inflateTree", "could not find tree '%s' in %s", name, in);
      delete fin;
      return;
   }
   Long64_t nin = tin->GetEntriesFast();
   Printf("Input tree '%s' has %lld entries", name, nin);
   // Create output file
   TFile *fout = TFile::Open(out, "RECREATE", 0, 1);
   if (!fout || fout->IsZombie()) {
      Printf("inflateTree", "could not open input file: %s", in);
      delete fin;
      return;
   }
   // Clone the header of the initial tree
   TTree *tout= (TTree *) tin->CloneTree(0);
   tout->SetMaxTreeSize(19000000000);


   // Duplicate all entries once
#if 0
   Int_t nc = fact;
   while (nc--) {
      Printf("Writing copy %d ...", fact - nc);
      tout->CopyEntries(tin);
   }
#else
   for (Long64_t i = 0; i < nin; ++i) {
      if (tin->LoadTree(i) < 0) {
         break;
      }
      tin->GetEntry(i);
      Int_t nc = fact;
      while (nc--) {
         tout->Fill();
      }
      if (i > 0 && !(i%1000)) {
         Printf("%d copies of %lld entries filled ...", fact, i);
      }
   }
#endif
   // Finalize the writing out
   tout->Write();
   
   // print perf stats
   

    sw.Stop();
    std::cout << "Drawing. Realtime: " <<      sw.RealTime()  << std::endl;
    std::cout << "Drawing. Cputime : " <<      sw.CpuTime()  << std::endl;
	tin->PrintCacheStats();   
   
   
   // Close the files
   fout->Close();
   fin->Close();
   // Cleanup
   delete fout;
   delete fin;
}
コード例 #23
0
ファイル: applyenergy.C プロジェクト: ECALELFS/ECALpro
void applyenergy() {

  ROOT::Cintex::Cintex::Enable();   

  
  //printf("include: %s\n",gSystem->GetIncludePath());
  //return;
  
  Long64_t maxentries = -1;
  
  


  //TFile *fmc = new TFile("/home/bendavid/cms/hist/hgg-v0-Sept1/local/filefi/merged/hgg-v0_s11-h120gg-gf-v11-pu_noskim.root","READ");
  //TFile *fmc = new TFile("/scratch/bendavid/cms/hist/hgg-v0/merged/hgg-v0_f11--h121gg-gf-v14b-pu_noskim.root","READ");
  TFile *fmc = new TFile("/scratch/bendavid/cms/hist/hgg-v0/merged/hgg-v0_f11-zjets-v14b-pu_noskim.root","READ");  
  //TFile *fmc = new TFile("/scratch/bendavid/cms/hist/hgg-v0/t2mit/filefi/025/f11--h121gg-gf-v14b-pu/hgg-v0_f11--h121gg-gf-v14b-pu_noskim_0000.root","READ");
  TDirectory *dir = (TDirectory*)fmc->FindObjectAny("PhotonTreeWriterPresel");
  TTree *hmcph = (TTree*)dir->Get("hPhotonTree");

  TDirectory *dirsingle = (TDirectory*)fmc->FindObjectAny("PhotonTreeWriterSingle");
  TTree *hmcsingleph = (TTree*)dirsingle->Get("hPhotonTree");

  TFile *fmcele = new TFile("/scratch/bendavid/cms/hist/hgg-v0/merged/hgg-v0_f11-zjets-v14b-pu_noskim.root","READ");  
  TDirectory *direle = (TDirectory*)fmcele->FindObjectAny("PhotonTreeWriterE");
  TTree *hmcele = (TTree*)direle->Get("hPhotonTree");
  TDirectory *direlesingle = (TDirectory*)fmcele->FindObjectAny("PhotonTreeWriterE");
  TTree *hmcelesingle = (TTree*)direlesingle->Get("hPhotonTreeSingle");

  
  TFile *fdele = new TFile("/scratch/bendavid/cms/hist/hgg-v0/MergedDel2011J16.root","READ");  
  TDirectory *dirdele = (TDirectory*)fdele->FindObjectAny("PhotonTreeWriterE");
  TTree *hdele = (TTree*)dirdele->Get("hPhotonTree");  
  TDirectory *dirdelesingle = (TDirectory*)fdele->FindObjectAny("PhotonTreeWriterE");
  TTree *hdelesingle = (TTree*)dirdelesingle->Get("hPhotonTreeSingle");  
  
  TFile *fgbropt = new TFile("fgbrtraintest.root","READ");
  const GBRForest *gbropt = (GBRForest*)fgbropt->Get("gbrtrain");      
  
  std::vector<std::string> *varlist = (std::vector<std::string>*)fgbropt->Get("varlist");

  
  std::vector<std::string> *varlisteb = varlist;
  std::vector<std::string> *varlistee = varlist;
  
  const GBRForest *gbr = 0;
  const GBRForest *gbreb = gbropt;
  const GBRForest *gbree = gbropt;
  
  UInt_t nvarseb = varlisteb->size();
  UInt_t nvarsee = varlistee->size();
  
  Float_t *vals = 0;
  
  Float_t *valseb = new Float_t[nvarseb];
  Float_t *valsee = new Float_t[nvarsee];
 
  
  TFile *fmvacor = new TFile("fmvacor.root","RECREATE");
  
  TTree *hmvacorph = new TTree("hmvacorph","");
  TTree *hmvacorele = new TTree("hmvacorele","");
  TTree *hmvacorelesingle = new TTree("hmvacorelesingle","");

  TTree *hmvacordele = new TTree("hmvacordele","");
  TTree *hmvacordelesingle = new TTree("hmvacordelesingle","");
  
  TTree *hmvacorqcdsingle = new TTree("hmvacorqcdsingle","");
  
  hmvacorele->SetAutoFlush(-1000000000);
  hmvacorelesingle->SetAutoFlush(-1000000000);

  hmvacordele->SetAutoFlush(-1000000000);
  hmvacordelesingle->SetAutoFlush(-1000000000);  
  
  
  Float_t massmvacor=0.;
  Float_t massmvacorerr=0.;
  Float_t massmvacorerrlo=0.;
  Float_t massmvacorerrhi=0.;
  Float_t ph1emvacor=0.;
  Float_t ph1emvacorerr=0.;
  Float_t ph1emvacorerrlo=0.;
  Float_t ph1emvacorerrhi=0.;
  Float_t ph1bdt = 0.;
  Float_t ph1bdtvar = 0.;
  Int_t   ph1dcoridx=0;
  Float_t ph1emvadcor=0.;
  Float_t ph2emvacor=0.;
  Float_t ph2emvacorerr=0.;
  Float_t ph2emvacorerrlo=0.;
  Float_t ph2emvacorerrhi=0.;
  Float_t ph2bdt = 0.;
  Float_t ph2bdtvar = 0.;
  Int_t   ph2dcoridx=0;
  Float_t ph2emvadcor=0.;  
  
  Float_t phemvacor=0.;
  Float_t phemvacorerr=0.;
  Float_t phbdt=0.;
  Float_t phbdtvar=0.;
  Int_t phdcoridx = 0;
  Float_t phemvadcor=0;
  
  Float_t phregtarget = 0.;
 
  for (UInt_t isample=1; isample<3; ++isample) {
    TTree *hmc = 0;
    TTree *hmvacor = 0;
    TTree *hmcsingle = 0;
    TTree *hmvacorsingle = 0;
    if (isample==0) {
      hmc = hmcph;
      hmvacor = hmvacorph;
      //hmcsingle = hmcqcdsingle;
      //hmvacorsingle = hmvacorqcdsingle;
    }
    else if (isample==1) {
      hmc = hmcele;
      hmvacor = hmvacorele;
      hmcsingle = hmcelesingle;
      hmvacorsingle = hmvacorelesingle;
    }    
    else if (isample==2) {
      hmc = hdele;
      hmvacor = hmvacordele;
      
      hmcsingle = hdelesingle;
      hmvacorsingle = hmvacordelesingle;
      
    } 

//     std::vector<TTreeFormula*> forms1;
//     std::vector<TTreeFormula*> forms2;
//     std::vector<TTreeFormula*> formssingle;
    TTreeFormula **formseb1 = new TTreeFormula*[nvarseb];
    TTreeFormula **formseb2 = new TTreeFormula*[nvarseb];
    TTreeFormula **formsebsingle = new TTreeFormula*[nvarseb];
    for (UInt_t ivar=0; ivar<varlisteb->size(); ++ivar) {
      TString expression = varlisteb->at(ivar);      
      expression.ReplaceAll("ph.genz","vtxZ");
      TString expr1(expression);
      expr1.ReplaceAll("ph.","ph1.");
      TString expr2(expression);
      expr2.ReplaceAll("ph.","ph2.");
      printf("expr = %s, expr1 = %s, expr2 = %s\n",expression.Data(),expr1.Data(),expr2.Data());
      formseb1[ivar] = new TTreeFormula(expr1,expr1,hmc);
      formseb2[ivar] = new TTreeFormula(expr2,expr2,hmc);
      if (hmcsingle) formsebsingle[ivar] = new TTreeFormula(expression,expression,hmcsingle);
    }

    TTreeFormula **formsee1 = new TTreeFormula*[nvarsee];
    TTreeFormula **formsee2 = new TTreeFormula*[nvarsee];
    TTreeFormula **formseesingle = new TTreeFormula*[nvarsee];
    for (UInt_t ivar=0; ivar<varlistee->size(); ++ivar) {
      TString expression = varlistee->at(ivar);    
      expression.ReplaceAll("ph.genz","vtxZ");      
      if (expression=="(1.0-(!ismc)*0.072)*ph.scpse/ph.scrawe") expression = "ph.scpse/ph.scrawe";
      TString expr1(expression);
      expr1.ReplaceAll("ph.","ph1.");
      TString expr2(expression);
      expr2.ReplaceAll("ph.","ph2.");
      printf("expr = %s, expr1 = %s, expr2 = %s\n",expression.Data(),expr1.Data(),expr2.Data());
      formsee1[ivar] = new TTreeFormula(expr1,expr1,hmc);
      formsee2[ivar] = new TTreeFormula(expr2,expr2,hmc);
      if (hmcsingle) formseesingle[ivar] = new TTreeFormula(expression,expression,hmcsingle);
    }
    
    TString denebexpr1 = "ph1.scrawe";
    TString denebexpr2 = "ph2.scrawe";
    TString denebexprsingle = "ph.scrawe";
    TTreeFormula *denebform1 = new TTreeFormula(denebexpr1,denebexpr1,hmc);
    TTreeFormula *denebform2 = new TTreeFormula(denebexpr2,denebexpr2,hmc);
    TTreeFormula *denebformsingle = 0;
    if (hmcsingle) denebformsingle = new TTreeFormula(denebexprsingle,denebexprsingle,hmcsingle);

//     TString deneeexpr1 = "ph1.scrawe + (1.0-(!ismc)*0.072)*ph1.scpse";
//     TString deneeexpr2 = "ph2.scrawe + (1.0-(!ismc)*0.072)*ph2.scpse";
   
    TString deneeexpr1 = "ph1.scrawe + ph1.scpse";
    TString deneeexpr2 = "ph2.scrawe + ph2.scpse";   
    
    TString deneeexprsingle = "ph.scrawe + ph.scpse";
    TTreeFormula *deneeform1 = new TTreeFormula(deneeexpr1,deneeexpr1,hmc);
    TTreeFormula *deneeform2 = new TTreeFormula(deneeexpr2,deneeexpr2,hmc);
    TTreeFormula *deneeformsingle = 0;
    if (hmcsingle) deneeformsingle = new TTreeFormula(deneeexprsingle,deneeexprsingle,hmcsingle);    
    
    TTreeFormula *costhetaform = new TTreeFormula("costheta","costheta",hmc);

    TString isbexpr1 = "ph1.isbarrel";
    TString isbexpr2 = "ph2.isbarrel";
    TString isbexprsingle = "ph.isbarrel";
    TTreeFormula *isbform1 = new TTreeFormula(isbexpr1,isbexpr1,hmc);
    TTreeFormula *isbform2 = new TTreeFormula(isbexpr2,isbexpr2,hmc);
    TTreeFormula *isbformsingle = 0;
    if (hmcsingle) isbformsingle = new TTreeFormula(isbexprsingle,isbexprsingle,hmcsingle);    
    
    hmvacor->Branch("massmvacor",&massmvacor,"massmvacor/F");
    hmvacor->Branch("massmvacorerr",&massmvacorerr,"massmvacorerr/F");
    //hmvacor->Branch("massmvacorerrlo",&massmvacorerrlo,"massmvacorerrlo/F");
    //hmvacor->Branch("massmvacorerrhi",&massmvacorerrhi,"massmvacorerrhi/F");
    
    hmvacor->Branch("ph1.emvacor",&ph1emvacor,"ph1.emvacor/F");
    hmvacor->Branch("ph1.emvacorerr",&ph1emvacorerr,"ph1.emvacorerr/F");
    hmvacor->Branch("ph1.bdt",&ph1bdt,"ph1.bdt/F");
    hmvacor->Branch("ph1.bdtvar",&ph1bdtvar,"ph1.bdtvar/F");    
    hmvacor->Branch("ph1.dcoridx",&ph1dcoridx,"ph1.dcoridx/I"); 
    hmvacor->Branch("ph1.emvadcor",&ph1emvadcor,"ph1.emvadcor/F");    
    
    //hmvacor->Branch("ph1.emvacorerrlo",&ph1emvacorerrlo,"ph1.emvacorerrlo/F");
    //hmvacor->Branch("ph1.emvacorerrhi",&ph1emvacorerrhi,"ph1.emvacorerrhi/F");
    hmvacor->Branch("ph2.emvacor",&ph2emvacor,"ph2.emvacor/F");
    hmvacor->Branch("ph2.emvacorerr",&ph2emvacorerr,"ph2.emvacorerr/F");  
    hmvacor->Branch("ph2.bdt",&ph2bdt,"ph2.bdt/F");
    hmvacor->Branch("ph2.bdtvar",&ph2bdtvar,"ph2.bdtvar/F");    
    hmvacor->Branch("ph2.dcoridx",&ph2dcoridx,"ph2.dcoridx/I");    
    hmvacor->Branch("ph2.emvadcor",&ph2emvadcor,"ph2.emvadcor/F");    
    
    
    //hmvacor->Branch("ph2.emvacorerrlo",&ph2emvacorerrlo,"ph2.emvacorerrlo/F");
    //hmvacor->Branch("ph2.emvacorerrhi",&ph2emvacorerrhi,"ph2.emvacorerrhi/F");
    
    if (hmvacorsingle) {
      hmvacorsingle->Branch("ph.emvacor",&phemvacor,"ph.emvacor/F");
      hmvacorsingle->Branch("ph.emvacorerr",&phemvacorerr,"ph.emvacorerr/F");
      hmvacorsingle->Branch("ph.dcoridx",&phdcoridx,"ph.dcoridx/I");    
      hmvacorsingle->Branch("ph.emvadcor",&phemvadcor,"ph.emvadcor/F");            
      //hmvacor->Branch("ph.bdt",&ph1bdt,"ph.bdt/F");
      //hmvacor->Branch("ph.bdtvar",&ph1bdtvar,"ph.bdtvar/F");      
    }
    
    //TString method = "MLP method";
    //TString method = "BDT method";
    TString method = "BDTG method";
    //TString method = "PDEFoam method";
    
    for (Long64_t i=0; i<hmc->GetEntries(); ++i) {
      hmc->LoadTree(i);

      float den1, den2;
      
      bool isb1 = isbform1->EvalInstance();
      bool isb2 = isbform2->EvalInstance();

      if (isb1) {
        gbr = gbreb;
        //gbrvar = gbrvareb;
        //gbrdcor = gbrdcoreb;
        vals = valseb;
        den1 = denebform1->EvalInstance();
        for (UInt_t ivar=0; ivar<nvarseb; ++ivar) {
          valseb[ivar] = formseb1[ivar]->EvalInstance();
        }        
      }
      else {
        gbr = gbree;
        //gbrvar = gbrvaree;
        //gbrdcor = gbrdcoree;
        vals = valsee;
        den1 = deneeform1->EvalInstance();
        for (UInt_t ivar=0; ivar<nvarsee; ++ivar) {
          valsee[ivar] = formsee1[ivar]->EvalInstance();
        }              
      }
      

      phregtarget = gbr->GetResponse(vals);     
      ph1emvacor = phregtarget*den1;

      //printf("phregtarget = %5f, ph1emvacor = %5f\n",phregtarget,ph1emvacor);
      
      
      if (isb2) {
        gbr = gbreb;
        vals = valseb;        
        den2 = denebform2->EvalInstance();
        for (UInt_t ivar=0; ivar<nvarseb; ++ivar) {
          valseb[ivar] = formseb2[ivar]->EvalInstance();
        }        
      }
      else {
        gbr = gbree;
        vals = valsee;        
        den2 = deneeform2->EvalInstance();
        for (UInt_t ivar=0; ivar<nvarsee; ++ivar) {
          valsee[ivar] = formsee2[ivar]->EvalInstance();
        }              
      }

      phregtarget = gbr->GetResponse(vals);      
      ph2emvacor = phregtarget*den2;

      

      
      massmvacor = TMath::Sqrt(2.0*ph1emvacor*ph2emvacor*(1.0-costhetaform->EvalInstance()));
      //massmvacorerr = 0.5*massmvacor*TMath::Sqrt(ph1emvacorerr*ph1emvacorerr/ph1emvacor/ph1emvacor + ph2emvacorerr*ph2emvacorerr/ph2emvacor/ph2emvacor);
      //massmvacorerrlo = 0.5*massmvacor*TMath::Sqrt(ph1emvacorerrlo*ph1emvacorerrlo/ph1emvacor/ph1emvacor + ph2emvacorerrlo*ph2emvacorerrlo/ph2emvacor/ph2emvacor);
      //massmvacorerrhi = 0.5*massmvacor*TMath::Sqrt(ph1emvacorerrhi*ph1emvacorerrhi/ph1emvacor/ph1emvacor + ph2emvacorerrhi*ph2emvacorerrhi/ph2emvacor/ph2emvacor);
        
      hmvacor->Fill();
      
    }
    hmc->AddFriend(hmvacor);
    hmvacor->Write();
    
    if (hmcsingle) {
      for (Long64_t i=0; i<hmcsingle->GetEntries(); ++i) {
        hmcsingle->LoadTree(i);

        float den;
        bool isbsingle = isbformsingle->EvalInstance();

        if (isbsingle) {
          gbr = gbreb;
          vals = valseb;          
          den = denebformsingle->EvalInstance();
          for (UInt_t ivar=0; ivar<nvarseb; ++ivar) {
            valseb[ivar] = formsebsingle[ivar]->EvalInstance();
          }        
        }
        else {
          gbr = gbree;
          vals = valsee;          
          den = deneeformsingle->EvalInstance();
          for (UInt_t ivar=0; ivar<nvarsee; ++ivar) {
            valsee[ivar] = formseesingle[ivar]->EvalInstance();
          }              
        }

        phregtarget = gbr->GetResponse(vals);     
        phemvacor = phregtarget*den;

        
        hmvacorsingle->Fill();
        
      }
      hmcsingle->AddFriend(hmvacorsingle);
      hmvacorsingle->Write();      
      
    }
    
  }
  
  
  
  
  
//   
}
コード例 #24
0
ファイル: GetMuonHistos3.C プロジェクト: mialiu149/OneLepStop
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;
}
コード例 #25
0
void pulseConvert(const char* ifname)
{
   TFile* ifile = TFile::Open(ifname);
   if (!ifile) {
      cout<< "File not found: " << ifname <<endl;
      return;
   }
   TTree* itree = (TTree*) ifile->Get("pulse");
   if (!itree) {
      cout<< "Error: could not find tree \"pulse\"" <<endl;
      return;
   }

   Int_t event, tc1, tc2;
   Float_t b1_t[1024], b1_c[4096], b2_t[1024], b2_c[4096];

   Float_t* b1_c1 = b1_c;
   Float_t* b1_c2 = b1_c + 1024;
   Float_t* b1_c3 = b1_c + 2048;
   Float_t* b1_c4 = b1_c + 3072;
   Float_t* b2_c1 = b2_c;
   Float_t* b2_c2 = b2_c + 1024;
   Float_t* b2_c3 = b2_c + 2048;
   Float_t* b2_c4 = b2_c + 3072;

   itree->SetBranchAddress("event", &event);
   itree->SetBranchAddress("tc1", &tc1);
   itree->SetBranchAddress("tc2", &tc2);
   itree->SetBranchAddress("b1_t", &b1_t);
   itree->SetBranchAddress("b2_t", &b2_t);
   itree->SetBranchAddress("b1_c", &b1_c);
   itree->SetBranchAddress("b2_c", &b2_c);

   TFile* ofile = TFile::Open(Form("%s.pulse.root",ifname), "recreate");

   // TTree* otree = new TTree("pulse", "old pulse tree");
   TTree* otree = new TTree("p", "new pulse tree");
   otree->SetMarkerStyle(6);
   otree->SetMarkerColor(2);
   otree->SetLineColor(2);

   // otree->Branch("event", &event, "event/I");
   // otree->Branch("tc1", &tc1, "tc1/I");
   // otree->Branch("b1_t",  b1_t, "b1_t[1024]/F");
   // otree->Branch("b1_c1", b1_c1, "b1_c1[1024]/F");
   // otree->Branch("b1_c2", b1_c2, "b1_c2[1024]/F");
   // otree->Branch("b1_c3", b1_c3, "b1_c3[1024]/F");
   // otree->Branch("b1_c4", b1_c4, "b1_c4[1024]/F");
   // otree->Branch("tc2", &tc2, "tc2/I");
   // otree->Branch("b2_t",  b2_t, "b2_t[1024]/F");
   // otree->Branch("b2_c1", b2_c1, "b2_c1[1024]/F");
   // otree->Branch("b2_c2", b2_c2, "b2_c2[1024]/F");
   // otree->Branch("b2_c3", b2_c3, "b2_c3[1024]/F");
   // otree->Branch("b2_c4", b2_c4, "b2_c4[1024]/F");

   otree->Branch("event", &event, "event/I");
   otree->Branch("tc1", &tc1, "tc1/I");
   otree->Branch("t1",  b1_t, "t1[1024]/F");
   otree->Branch("c1", b1_c1, "c1[1024]/F");
   otree->Branch("c2", b1_c2, "c2[1024]/F");
   otree->Branch("c3", b1_c3, "c3[1024]/F");
   otree->Branch("c4", b1_c4, "c4[1024]/F");
   otree->Branch("tc2", &tc2, "tc2/I");
   otree->Branch("t2",  b2_t, "t2[1024]/F");
   otree->Branch("c5", b2_c1, "c5[1024]/F");
   otree->Branch("c6", b2_c2, "c6[1024]/F");
   otree->Branch("c7", b2_c3, "c7[1024]/F");
   otree->Branch("c8", b2_c4, "c8[1024]/F");

   for (Long64_t jentry=0; jentry<itree->GetEntries(); jentry++)
   {
      if (jentry % 1000 == 0) cout<< "jentry = " << jentry <<endl;
      itree->LoadTree(jentry);
      itree->GetEntry(jentry);

      otree->Fill();
   }

   cout<< "Write " << otree->GetEntries() << " events into file " << ofile->GetName() <<endl;
   ofile->Write();
}
コード例 #26
0
ファイル: scanchain.C プロジェクト: anilsemizoglu/single_mt2
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;
	}
コード例 #27
0
ファイル: SkimMain.C プロジェクト: Feynman27/HIMuonSkimming
int main() {
	
	//included for grid running
	ROOT::Cintex::Cintex::Enable();
	//if above fails, try the lines below
	/*
	gROOT->SetBatch(1);
	gROOT->ProcessLine("#include <vector>");
	*/


	//flag for making missing momentum histos
	bool doHistos = false;

	//flag for ONLY filling missing momentum histos
	//(i.e. will not fill output tree branches from d3pd)
	bool doHistosQuick = false;


	//get the run list ,set branch addresses and
	TString inputFiles="input.txt";

	BranchBase *t = new BranchBase(inputFiles);

	//get the tree holding the DPD variables
	TTree* itsTree = t->fChain;
	  
	//output file and tree
	TFile *outfile   = new TFile("skimmed.root","recreate");
	TTree *MyTree    = new TTree("data","data");

	//Set the muon branches to be stored
	//in the output tree
	MuonBranch *mu = new MuonBranch;
	mu->Set_Muon_Branches(MyTree);

	//Set the global/trigger branches to be stored
	//in the output tree
	TrigGlobalBranch* glob = new TrigGlobalBranch;
  	glob->Set_Trig_and_Global_Branches(MyTree);

	//set branch status and make sure
	//entries!=0
	int result = t->TurnOnBranches();

	if (result!=0) {

		std::cout << "Exiting program. " << std::endl; 
    		system("rm skimmed.root");

		exit(0);
	}

	int nentries = itsTree->GetEntries();
	if (nentries==0) {

		std::cout << "Zero entries in itsTree. Exiting program. " << std::endl;
		exit(0);
	}

	if(doHistos||doHistosQuick) {
			std::cout << "Will produce missing momentum performance histos." << std::endl;
			if(doHistosQuick) std::cout << "Output tree branches will be empty for fast histo production." << std::endl;
			std::cout << "Initializing histos for missing momentum filling... " << std::endl;
			int init = glob->InitMissMomHistos();
        		if(!init) {std::cout << "WARNING: MUST INITIALIZE HISTOS. " << std::endl; exit(0);}
        		std::cout << "Done! " << std::endl;
	}

	//event loop
	for (Long64_t jentry=0; jentry<nentries;jentry++){
		
		//Long64_t ientry = t->fChain->LoadTree(jentry);
		//if(jentry==1000) break; //temp hack
		Long64_t ientry = itsTree->LoadTree(jentry);
		if (ientry < 0) break;

		itsTree->GetEntry(jentry); //  nbytes += nb;
		//t->fChain->GetEntry(jentry); //  nbytes += nb;
		//std::cout << "muons:" << mu->mu_muid_n <<std::endl;
    		
		if(jentry%1000==0) printf("running event %5dk\n",(int) jentry/1000);

		bool event = t->EventCuts();
		if(!event) continue;

	 	if(!doHistosQuick){	
    			mu->Fill_Muon_Branches();
    			glob->Fill_Trig_and_Global_Branches();
    			//Fill_FCal_Branches           ();
    			//Fill_Track_Branches          (); 
		}

		if(doHistos||doHistosQuick) {
			glob->FillMissMomHistos();

		}

    		MyTree->Fill();

	} //event loop

	outfile->cd();
  	outfile->Write();
  	outfile -> Close();
	
	delete mu;
	delete glob;
	delete t;
  	return 0;

}
コード例 #28
0
Int_t runPrefetchReading(bool caching = false)
{
   //const char *options = 0;
   Int_t freq = 1000; 
   Int_t cachesize = -1;
   Float_t percententries = 1.00;
   Float_t percentbranches = 1.00;
   TStopwatch sw;
   
   //set the reading mode to async prefetching
   gEnv->SetValue("TFile.AsyncPrefetching", 1);

   //enable the local caching of blocks
   TString cachedir="file:/tmp/xcache/";
   // or using xrootd on port 2000
   // TString cachedir="root://localhost:2000//tmp/xrdcache1/";
   if (caching) gEnv->SetValue("Cache.Directory", cachedir.Data());
   
   // open the local if any
   TString filename("atlasFlushed.root");
   if (gSystem->AccessPathName(filename,kReadPermission) && filename.Index(":") == kNPOS) {
      // otherwise open the http file
      filename.Prepend("https://root.cern.ch/files/");
      //filename.Prepend("root://cache01.usatlas.bnl.gov//data/test1/");
      //filename.Prepend( "root://pcitdss1401//tmp/" );
      //filename.Prepend("http://www-root.fnal.gov/files/");
      //filename.Prepend("http://oink.fnal.gov/distro/roottest/");
   }
   
   TString library("atlasFlushed/atlasFlushed");
   fprintf(stderr,"Starting to load the library\n");
   gSystem->Load(library);

   fprintf(stderr,"Starting to open the file\n");
   TFile *file = TFile::Open( filename, "TIMEOUT=30" );
   if (!file || file->IsZombie()) {
      Error("runPrefetchReading","Could not open the file %s within 30s",filename.Data());
      return 1;
   }
   fprintf(stderr,"The file has been opened, setting up the TTree\n");

   // file->MakeProject("atlasFlushed","*","RECREATE+");

   // Try the known names :)
   const char *names [] = { "E","Events","CollectionTree","ntuple","T" };
   TTree *T = NULL;
   for (unsigned int i = 0; i < sizeof(names)/sizeof(names[0]); ++i) {
      file->GetObject(names[i], T);
      if (T) break;
   }
   if (T==0) {
     Error("runPrefetchReading","Could not find a tree which the conventional names in %s.",filename.Data());
     return 2;
   }
   TFile::SetReadaheadSize(0);  // (256*1024);
   Long64_t nentries = T->GetEntries();

   int efirst = 0;
   int elast  = efirst+nentries;
   if (cachesize == -2) {
      gEnv->SetValue("TFile.AsyncReading", 0);
      cachesize = -1;
   }
   T->SetCacheSize(cachesize);

   if (cachesize != 0) {
      T->SetCacheEntryRange(efirst,elast);
      if (percentbranches < 1.00) {
         int nb = T->GetListOfBranches()->GetEntries();
         int incr = nb * percentbranches;
         for(int b=0;b < nb; b += incr) T->AddBranchToCache(((TBranch*)T->GetListOfBranches()->At(b)),kTRUE);
      } else {
         T->AddBranchToCache("*");
      }
      T->StopCacheLearningPhase();
   }

   //...........................................................................
   // First read, with saving the info in cache
   //...........................................................................
   fprintf(stderr,"Setup done. Starting to read the entries\n");
   TRandom r;
   for (Long64_t i = efirst; i < elast; i++) {
     //if (i%100 == 0 || i>2000) fprintf(stderr,"i.debug = %lld\n",i);
     // if (i==2000) gDebug = 7;
     if (i % freq == 0){
       // for (Long64_t i=elast-1;i>=efirst;i--) {
       if (i%freq == 0 || i==(elast-1)) fprintf(stderr,"i = %lld\n",i);
       if (r.Rndm() > percententries) continue; 
       T->LoadTree(i);
       if (percentbranches < 1.00) {
         int nb = T->GetListOfBranches()->GetEntries();
         int incr = nb * percentbranches;
         for(int b=0;b<nb; b += incr) ((TBranch*)T->GetListOfBranches()->At(b))->GetEntry(i);   
         int count = 0;
         int maxcount = 1000 + 100 ;
         for(int x = 0; x < maxcount; ++x ) { /* waste cpu */ count = sin(cos((double)count)); }
       } else {
         T->GetEntry(i);
       }
     }
   }

   fprintf(stderr,"Done reading for the first pass, now closing the file\n");
   file->Close();
   delete file;

   //...........................................................................
   // Second read, actually reading the data from cache
   //...........................................................................
   fprintf(stderr,"Opening the file for the 2nd pass\n");
   file = TFile::Open( filename, "TIMEOUT=30" );
   if (!file || file->IsZombie()) return 1;
 
   fprintf(stderr,"The file has been opened, setting up the TTree\n");
   // Try the known names :)
   for (unsigned int i = 0; i < sizeof(names)/sizeof(names[0]); ++i) {
      file->GetObject(names[i], T);
      if (T) break;
   }
   if (T==0) {
     Error("runPrefetchReading","Could not find a tree which the conventional names in %s.",filename.Data());
     return 2;
   }

   TFile::SetReadaheadSize(0);  // (256*1024);
   nentries = T->GetEntries();

   efirst = 0;
   elast  = efirst+nentries;

   if (cachesize == -2) {
      gEnv->SetValue("TFile.AsyncReading", 0);
      cachesize = -1;
   }
   T->SetCacheSize(cachesize);

   if (cachesize != 0) {
      T->SetCacheEntryRange(efirst,elast);
      if (percentbranches < 1.00) {
         int nb = T->GetListOfBranches()->GetEntries();
         int incr = nb * percentbranches;
         for(int b=0;b < nb; b += incr) T->AddBranchToCache(((TBranch*)T->GetListOfBranches()->At(b)),kTRUE);
      } else {
         T->AddBranchToCache("*");
      }
      T->StopCacheLearningPhase();
   }
      
   fprintf(stderr,"Setup done, starting the 2nd reading.\n");
   for (Long64_t i = efirst; i < elast; i++) {
     if (i % freq == 0){
       // for (Long64_t i=elast-1;i>=efirst;i--) {
       if (i%freq == 0 || i==(elast-1)) fprintf(stderr,"i = %lld\n",i);
       if (r.Rndm() > percententries) continue;
       T->LoadTree(i);
       if (percentbranches < 1.00) {
         int nb = T->GetListOfBranches()->GetEntries();
         int incr = nb * percentbranches;
         
         for(int b=0;b<nb; b += incr) {
           ((TBranch*)T->GetListOfBranches()->At(b))->GetEntry(i);
         }
         
         int count = 0;
         int maxcount = 1000 + 100 ;
         for(int x = 0; x < maxcount; ++x ) {
           /* waste cpu */
           count = sin(cos((double)count));
         }         
       } else {
         T->GetEntry(i);
       }
     }
   }
   fprintf(stderr, "Done with the 2nd reading\n");

   fprintf(stderr, "fPrefetchedBlocks = %lli\n", file->GetCacheRead()->GetPrefetchedBlocks());

   fprintf(stderr, "Delete tmp directory: /tmp/xcache\n" );
   if (caching) system( "rm -r /tmp/xcache" );
   
   file->Close();
   delete file;
   return 0;
}
コード例 #29
0
//===============================
void FitSignalBG(Double_t nSigma, Int_t iRapBin, Int_t iPTBin){	

  gStyle->SetOptFit(kTRUE);
  gStyle->SetOptStat(kFALSE);

  Char_t name[100];
  //1.) perform the fit to the continuum, using the sidebands
  sprintf(name, "c1_rap%d_pT%d", iRapBin, iPTBin);
  TCanvas *c1 = new TCanvas(name);
  sprintf(name, "Counts per %1.0f MeV", 1000.*binWidth);
  c1->SetFillColor(0);
  c1->SetLeftMargin(0.15);
  hMass->SetYTitle(name);
  hMass->SetXTitle("M_{#mu#mu} [GeV]");
  hMass->SetTitleOffset(1.5, "y");
  hMass->SetStats(0);
  hMass->Draw();

  //starting values for fit:
  Double_t a = -2.0e6, b = 5.e5, c = -2.4e4;
  Double_t range_min = 8.6, range_max = 11.4;
  Double_t normY1S = hMass->GetMaximum() / binWidth;
  Double_t normY2S = 0.3*normY1S; 
  Double_t normY3S = 0.15*normY1S;
  Double_t sigma1S = 0.1, mean1S = 9.45;
  Double_t alpha = 1.33, n = 6.6; //CB-tail parameters

  printf("will be fitting the continuum between %1.2f < M < %1.2f\n", range_min, range_max);
  sprintf(name, "fCont");
  TF1* fCONT = new TF1(name, fitContinuum, range_min, range_max, 3);
  fCONT->SetParameters(a, b, c);
  hMass->Fit(fCONT, "0", "", range_min, range_max);
  fCONT = hMass->GetFunction(name);

  Double_t chisqrd = fCONT->GetChisquare();
  Int_t NDF = fCONT->GetNDF();
  Double_t redChi2 = chisqrd/NDF;
  printf("\nChisqrd = %1.3f, NDF = %d, Chisqrd/NDF = %1.3f, Prob = %1.3f\n\n", chisqrd, NDF, redChi2, TMath::Prob(chisqrd,NDF));

  fCONT->GetParameters(fitParBG);
  for(int iPar = 0; iPar < 3; iPar++){
	  fitParBGerr[iPar]=fCONT->GetParError(iPar);
  }

  //2.) fit the peaks on the top of a fixed continuum
  sprintf(name,"fPeaks");
  Int_t const npar = 10;
  fRECO = new TF1(name, fitPolyCrystal3, peak_min, peak_max, npar);
  fRECO->SetParNames("normY1S", "mass_Ups1S", "sigma_Ups1S", "normY2S", "normY3S", "n", "alpha", "a", "b", "c");
  fRECO->SetParameters(normY1S, mean1S, sigma1S, normY2S, normY3S, n, alpha, a, b, c);
  fRECO->FixParameter(7,fitParBG[0]);
  fRECO->FixParameter(8,fitParBG[1]);
  fRECO->FixParameter(9,fitParBG[2]);
  //fix alpha and n from the fit to all bins
  if(iPTBin > 0 && iRapBin > 0){

    Char_t fileName[100];
    if(iRapBin == 0)
      sprintf(fileName, "tmpFiles/CBParameters.root");
    else
      sprintf(fileName, "tmpFiles/CBParameters_rap%d.root", iRapBin);
    TFile *fIn = new TFile(fileName);
    TTree *treeIn = (TTree *) gDirectory->Get("CBPars");
    Double_t alphaAll, nAll;
    TBranch *b_alphaAll, *b_nAll;
    treeIn->SetBranchAddress("alphaAll", &alphaAll, &b_alphaAll);
    treeIn->SetBranchAddress("nAll", &nAll, &b_nAll);
    Long64_t iEntry = treeIn->LoadTree(0);
    treeIn->GetEntry(0);
    printf("alpha and n from File: %1.3f, %1.3f\n", alphaAll, nAll);
    fRECO->FixParameter(5, nAll);
    fRECO->FixParameter(6, alphaAll);
  }

  hMass->Fit(fRECO, "0", "", peak_min, peak_max);

  fRECO = hMass->GetFunction(name);
  fRECO->SetLineWidth(1);

  Double_t fitParTot[npar];
  fRECO->GetParameters(fitParTot);
  normY1S = fitParTot[0];   printf("normY1S = %1.3e\n", normY1S);
  mean1S = fitParTot[1];
  sigma1S = fitParTot[2];
  normY2S = fitParTot[3];
  normY3S = fitParTot[4];
  n = fitParTot[5];  printf("n = %1.3f\n", n);
  alpha = fitParTot[6];  printf("alpha = %1.3f\n", alpha);

  sigma1S_save[iRapBin][iPTBin]=sigma1S;

  chisqrd = fRECO->GetChisquare();
  NDF = fRECO->GetNDF();
  redChi2 = chisqrd/NDF;
  printf("\nChisqrd = %1.3f, NDF = %d, Chisqrd/NDF = %1.3f, Prob = %1.3e\n", chisqrd, NDF, redChi2, TMath::Prob(chisqrd,NDF));

  //save alpha and n parameters if fit is 
  //for integrated bins in y and pT:
  if(iPTBin == 0)
    SaveCBParameters(iRapBin, iPTBin, alpha, n, fRECO->GetParError(6), fRECO->GetParError(5));

  Double_t mean2S = mean1S*(massPDG2S/massPDG1S);
  Double_t mean3S = mean1S*(massPDG3S/massPDG1S);
  Double_t sigma2S = sigma1S*(massPDG2S/massPDG1S);
  Double_t sigma3S = sigma1S*(massPDG3S/massPDG1S);

  printf("=========================================\n");
  printf("Calculate the number of Y's in the sample\n");
  printf("=========================================\n");

  TF1 *CB[kNbSpecies];
  Double_t intCBFit[kNbSpecies]; //integral values of a CB with N=Nfit and fixed alpha, n, sigma, width

  for(int iUps = 0; iUps < kNbSpecies; iUps++){
    sprintf(name, "CB_%d", iUps);
    CB[iUps] = new TF1(name, CBFunction, range_min, range_max, 5);
    CB[iUps]->SetParameter(0, 1.);
    if(iUps == 0){
      CB[iUps]->FixParameter(1, mean1S);
      CB[iUps]->FixParameter(2, sigma1S);
    }
    else if(iUps == 1){
      CB[iUps]->FixParameter(1, mean2S);
      CB[iUps]->FixParameter(2, sigma2S);
    }
    else if(iUps == 2){
      CB[iUps]->FixParameter(1, mean3S);
      CB[iUps]->FixParameter(2, sigma3S);
    }
    CB[iUps]->FixParameter(3, alpha);
    CB[iUps]->FixParameter(4, n);
    intCB[iUps] = CB[iUps]->Integral(range_min, range_max);
  }

  nY[UPS1S] = normY1S * intCB[UPS1S];
  nY[UPS2S] = normY2S * intCB[UPS2S];
  nY[UPS3S] = normY3S * intCB[UPS3S];

  printf("rapidity bin %d, pT bin %d\n", iRapBin, iPTBin);
  printf("the integral of the fitted CB for the %s is: %1.3e --> #%s = %1.3e\n", specName[UPS1S], intCB[UPS1S], specName[UPS1S], nY[UPS1S]);
  printf("the integral of the fitted CB for the %s is: %1.3e --> #%s = %1.3e\n", specName[UPS2S], intCB[UPS2S], specName[UPS2S], nY[UPS2S]);
  printf("the integral of the fitted CB for the %s is: %1.3e --> #%s = %1.3e\n", specName[UPS3S], intCB[UPS3S], specName[UPS3S], nY[UPS3S]);

  //calculate the fraction of BG in a given mass interval
  massMin[UPS1S] = mean1S - nSigma*sigma1S;
  massMin[UPS2S] = mean2S - nSigma*sigma2S;
  massMin[UPS3S] = mean3S - nSigma*sigma3S;
  massMax[UPS1S] = mean1S + nSigma*sigma1S;
  massMax[UPS2S] = mean2S + nSigma*sigma2S;
  massMax[UPS3S] = mean3S + nSigma*sigma3S;
  for(int iSpecies = 0; iSpecies < kNbSpecies; iSpecies++){
    printf("integrating histos between %1.3f and %1.3f GeV (+- %1.1f sigma window)\n",
	   massMin[iSpecies], massMax[iSpecies], nSigma);
  }

  fUps1S =  new TF1("fUps1S", CBFunction, range_min, range_max, 5);
  fUps1S->FixParameter(0, normY1S * binWidth);
  fUps1S->FixParameter(1, mean1S);
  fUps1S->FixParameter(2, sigma1S);
  fUps1S->FixParameter(3, alpha);
  fUps1S->FixParameter(4, n);

  fUps2S = new TF1("fUps2S", CBFunction, range_min, range_max, 5);
  fUps2S->FixParameter(0, normY2S * binWidth);
  fUps2S->FixParameter(1, mean2S);
  fUps2S->FixParameter(2, sigma2S);
  fUps2S->FixParameter(3, alpha);
  fUps2S->FixParameter(4, n);

  fUps3S = new TF1("fUps3S", CBFunction, range_min, range_max, 5);
  fUps3S->FixParameter(0, normY3S * binWidth);
  fUps3S->FixParameter(1, mean3S);
  fUps3S->FixParameter(2, sigma3S);
  fUps3S->FixParameter(3, alpha);
  fUps3S->FixParameter(4, n);


  Double_t nUps[kNbSpecies];
  nUps[UPS1S] = fUps1S->Integral(massMin[UPS1S], massMax[UPS1S]);
  nUps[UPS2S] = fUps2S->Integral(massMin[UPS2S], massMax[UPS2S]);
  nUps[UPS3S] = fUps3S->Integral(massMin[UPS3S], massMax[UPS3S]);


  fBG = new TF1("fBG", DrawContinuum, range_min, range_max, 3);
  for(int iPar = 0; iPar < 3; iPar++){
    fBG->FixParameter(iPar, fitParBG[iPar]);
    fBG->SetParError(iPar, fitParBGerr[iPar]);
//    printf("fBG par %f +- %f\n", fBG->GetParameter(iPar), fBG->GetParError(iPar));

  }
  Double_t nBG[kNbSpecies];
  nBG[UPS1S] = fBG->Integral(massMin[UPS1S], massMax[UPS1S]);
  nBG[UPS2S] = fBG->Integral(massMin[UPS2S], massMax[UPS2S]);
  nBG[UPS3S] = fBG->Integral(massMin[UPS3S], massMax[UPS3S]);


/*  intCB[UPS3S] = CB[UPS3S]->Integral(massMin[UPS3S], massMax[UPS3S]);
  intCB[UPS2S] = CB[UPS2S]->Integral(massMin[UPS3S], massMax[UPS3S]);
  intCB[UPS1S] = CB[UPS1S]->Integral(massMin[UPS3S], massMax[UPS3S]);
  nY[UPS3S] = normY3S * intCB[UPS3S];
  nY[UPS2S] = normY2S * intCB[UPS2S];
  nY[UPS1S] = normY1S * intCB[UPS1S];
  printf("3S region:::1sigma integral CB3S = %1.3f, normY3S = %1.3f, nY3S = %1.3f\n",intCB[UPS3S] ,normY3S,nY[UPS3S]);
  printf("3S region:::1sigma integral CB2S = %1.3f, normY2S = %1.3f, nY2S = %1.3f\n",intCB[UPS2S] ,normY2S,nY[UPS2S]);
  printf("3S region:::1sigma integral CB1S = %1.3f, normY1S = %1.3f, nY1S = %1.3f\n",intCB[UPS1S] ,normY1S,nY[UPS1S]);
  printf("3S region:::1sigma integral BKG  = %1.3f, normBkg = %1.3f, nBkg = %1.3f\n",fBG->Integral(massMin[UPS3S], massMax[UPS3S]) ,1/binWidth,fBG->Integral(massMin[UPS3S], massMax[UPS3S])/binWidth);
  printf("3S region:::1sigma CB3S background fraction = %1.3f\n",fBG->Integral(massMin[UPS3S], massMax[UPS3S])/binWidth/(fBG->Integral(massMin[UPS3S], massMax[UPS3S])/binWidth+nY[UPS1S]+nY[UPS2S]+nY[UPS3S]));
  printf("3S region:::1sigma NumEvents = %1.3f\n",fBG->Integral(massMin[UPS3S], massMax[UPS3S])/binWidth+nY[UPS1S]+nY[UPS2S]+nY[UPS3S]);

  intCB[UPS3S] = CB[UPS3S]->Integral( range_min, range_max);
  intCB[UPS2S] = CB[UPS2S]->Integral( range_min, range_max);
  intCB[UPS1S] = CB[UPS1S]->Integral( range_min, range_max);
  nY[UPS3S] = normY3S * intCB[UPS3S];
  nY[UPS2S] = normY2S * intCB[UPS2S];
  nY[UPS1S] = normY1S * intCB[UPS1S];

  printf("3S region:::FullRegion integral CB3S = %1.3f, normY3S = %1.3f, nY3S = %1.3f\n",intCB[UPS3S] ,normY3S,nY[UPS3S]);
  printf("3S region:::FullRegion integral CB2S = %1.3f, normY2S = %1.3f, nY2S = %1.3f\n",intCB[UPS2S] ,normY2S,nY[UPS2S]);
  printf("3S region:::FullRegion integral CB1S = %1.3f, normY1S = %1.3f, nY1S = %1.3f\n",intCB[UPS1S] ,normY1S,nY[UPS1S]);
  printf("3S region:::FullRegion integral background = %1.3f\n",fBG->Integral(range_min, range_max)/binWidth);
  printf("3S region:::FullRegion NumEvents = %1.3f\n",fBG->Integral(range_min, range_max)/binWidth+nY[UPS1S]+nY[UPS2S]+nY[UPS3S]);

  double tempBfrac=fBG->Integral(massMin[UPS3S], massMax[UPS3S])/(fBG->Integral(massMin[UPS3S], massMax[UPS3S])+fUps1S->Integral(massMin[UPS3S], massMax[UPS3S])+fUps2S->Integral(massMin[UPS3S], massMax[UPS3S])+fUps3S->Integral(massMin[UPS3S], massMax[UPS3S]));
  printf("3S region:::1sigma fUps background fraction = %1.3f\n",tempBfrac);
*/
  if(iRapBin == 0 || iPTBin == 0)
    printf("rapidity bin %d, pTBin %d\n", iRapBin, iPTBin);	   
  else{
    printf("rapidity bin %d (%1.1f - %1.1f), pT bin %d (%1.0f - %1.0f GeV/c)\n", 
	   iRapBin, onia::rapForPTRange[iRapBin-1], onia::rapForPTRange[iRapBin], 
	   iPTBin, onia::pTRange[iRapBin][iPTBin-1], onia::pTRange[iRapBin][iPTBin]);
  }

  FILE *fInfo = fopen("tmpFiles/statistics.txt", "a");
  if(iRapBin == 0 || iPTBin == 0)
    fprintf(fInfo, "rapidity bin %d, pTBin %d\n", iRapBin, iPTBin);	   
  else{
    fprintf(fInfo, "rapidity bin %d (%1.1f - %1.1f), pT bin %d (%1.0f - %1.0f GeV/c)\n", 
	   iRapBin, onia::rapForPTRange[iRapBin-1], onia::rapForPTRange[iRapBin], 
	   iPTBin, onia::pTRange[iRapBin][iPTBin-1], onia::pTRange[iRapBin][iPTBin]);
  }
  for(int iSpecies = 0; iSpecies < kNbSpecies; iSpecies++){
    fracBG[iSpecies] = nBG[iSpecies] / (nBG[iSpecies] + nUps[iSpecies]);
    // printf("nUps = %1.3f\n", nUps[iSpecies]);
    // printf("nBG = %1.3f\n", nBG[iSpecies]);
    printf("%s: fraction of BG in a +- %1.1f sigma window is %1.3f (not correct)\n",specName[iSpecies], nSigma, fracBG[iSpecies]);
    printf("%s: Number of BG events in a +- %1.1f sigma window is %1.3f, number of signal events is %1.3f\n",nSigma, nBG[iSpecies], nUps[iSpecies]);

    fprintf(fInfo, "integral of the fitted CB for the %s is (norm factor= %1.3e): %7.0f\n", specName[iSpecies], intCB[iSpecies], nY[iSpecies]);
  }
  fclose(fInfo);

//  if(iPTBin > 0 && iRapBin > 0)
	if(iPTBin > -1 && iRapBin > -1)
    SaveFitPars(iRapBin, iPTBin);

}
コード例 #30
0
int main(int argc, char* argv[]){
  using namespace muon_pog;


  if (argc < 3) 
    {
      std::cout << "Usage : "
		<< argv[0] << " PATH_TO_INPUT_FILE PAT_TO_CONFIG_FILE(s)\n";
      exit(100);
    }

  // Input root file
  TString fileName = argv[1];

  std::cout << "[" << argv[0] << "] Processing file " << fileName.Data() << std::endl;
  
  std::vector<Plotter> plotters;
  for (int iConfig = 2; iConfig < argc; ++iConfig)
    {
        std::cout << "[" << argv[0] << "] Using config file " << argv[iConfig] << std::endl;
	plotters.push_back(std::string(argv[iConfig]));
    }
  
  // Set it to kTRUE if you do not run interactively
  gROOT->SetBatch(kTRUE); 

  // Initialize Root application
  TRint* app = new TRint("CMS Root Application", &argc, argv);

  //setTDRStyle(); what to do here?
   
  // Initialize pointers to summary and full event structure
 
  muon_pog::Event* ev = new muon_pog::Event();
  TTree* tree;
  TBranch* evBranch;

  // Open file, get tree, set branches

  TFile* inputFile = TFile::Open(fileName,"READONLY");
  tree = (TTree*)inputFile->Get("MUONPOGTREE");
  if (!tree) inputFile->GetObject("MuonPogTree/MUONPOGTREE",tree);

  evBranch = tree->GetBranch("event");
  evBranch->SetAddress(&ev);

  system("mkdir -p results");
  
  TFile* outputFile = TFile::Open("results/results.root","RECREATE"); // CB find a better name for output file  

  for (auto & plotter : plotters)
    plotter.book(outputFile);
      
  // Watch number of entries
  int nEntries = tree->GetEntriesFast();
  std::cout << "[" << argv[0] << "] Number of entries = " << nEntries << std::endl;

  int nFilteredEvents = 0;
  
  for (Long64_t iEvent=0; iEvent<nEntries; ++iEvent) 
    {
      if (tree->LoadTree(iEvent)<0) break;

      evBranch->GetEntry(iEvent);

      for (auto & plotter : plotters)
	plotter.fill(ev->muons, ev->hlt);

    }

  outputFile->Write();
  
  if (!gROOT->IsBatch()) app->Run();

  return 0;
}