예제 #1
0
  /** 
   * End of job processing 
   */
  void Terminate(Option_t*)
  {
    fList = dynamic_cast<TList*>(GetOutputData(1));
    if (!fList) {
      AliError(Form("No output list defined (%p)", GetOutputData(1)));
      if (GetOutputData(1)) GetOutputData(1)->Print();
      return;
    }


    TList* output = new TList;
    output->SetName("triggerResults");
    output->SetOwner();

    fVertexMC = static_cast<TH1D*>(fList->FindObject("vertexMC"));
    fVertexESD = static_cast<TH1D*>(fList->FindObject("vertexESD"));
    fM         = static_cast<TH1D*>(fList->FindObject("m"));
    if (fVertexMC) { 
      TH1D* vtxMC = static_cast<TH1D*>(fVertexMC->Clone("vertexMC"));
      vtxMC->SetDirectory(0);
      if (vtxMC->GetEntries() > 0)
	vtxMC->Scale(1. / vtxMC->GetEntries());
      else 
	vtxMC->Scale(0);
      output->Add(vtxMC);
    }
    if (fVertexESD) { 
      TH1D* vtxESD = static_cast<TH1D*>(fVertexESD->Clone("vertexESD"));
      vtxESD->SetDirectory(0);
      if (vtxESD->GetEntries() > 0)
	vtxESD->Scale(1. / vtxESD->GetEntries());
      else 
	vtxESD->Scale(0);
      output->Add(vtxESD);
    }
    if (fM) { 
      TH1D* m = static_cast<TH1D*>(fM->Clone("m"));
      m->SetDirectory(0);
      m->SetYTitle("P(N_{ch}|_{|#eta|<1} < X)");
      if (m->GetBinContent(1) > 0)
	m->Scale(1. / m->GetBinContent(1));
      else 
	m->Scale(0);
      output->Add(m);
    }      

    TString vtxReq;
    if (fVertexRequirement & kMC)  vtxReq.Append("MC ");
    if (fVertexRequirement & kESD) vtxReq.Append("ESD ");
    output->Add(new TNamed("vtxReq", vtxReq.Data()));
    output->Add(new TNamed("trkReq",
			   fTrackletRequirement == kMC ? "MC" : "ESD"));

    fInel.Finish(fList, output);
    fInelGt0.Finish(fList, output);
    fNSD.Finish(fList, output);
    fNClusterGt0.Finish(fList, output);

    PostData(2, output);
  }
예제 #2
0
void RunTest(const char* name, int numentries, int BufferSize) {
   char title[200];
   sprintf(title, "%d events, 10 branches, 10 floats in brunch, Basket size = %d", numentries, BufferSize*sizeof(Float_t)*10);

   TH1D* histoRes = new TH1D(name, title, 10, 0.5, 10.5);
   histoRes->GetXaxis()->SetTitle("Number of active branches");
   histoRes->GetYaxis()->SetTitle("Real time (s)");
   histoRes->SetDirectory(0);
   histoRes->SetStats(kFALSE);
   ProduceTree("TreeFile.root","TestTree", numentries, 0, 10, 10, BufferSize);

   Float_t RealTime, CpuTime;
    
   for(int ActiveBranches=1;ActiveBranches<=10;ActiveBranches++) {
      ReadDummyTree();
      cout << "Buffer size = " << BufferSize*sizeof(Float_t)*10 << " ActiveBranches = " << ActiveBranches << endl;
      MakeDelay(10);
      TestTree("TreeFile.root","TestTree", 10, 10, ActiveBranches, &RealTime, &CpuTime);
      histoRes->SetBinContent(ActiveBranches, RealTime);
   } 
   
   TCanvas* c1 = new TCanvas(TString(name)+"_canvas", title);
   histoRes->Draw();
   c1->SaveAs(TString(name)+".gif");
}
예제 #3
0
void RunTest(const char* name, const char* uselesstitle, int numentries, int BufferSize) {
   TString title;
   title += numentries;
   title.Append(" events, 10 branches, 10 floats in brunch, Basket size = ");
   title += ( BufferSize*10*10*4 );
   TH1D* histoRes = new TH1D(name, title, 10, 0.5, 10.5);
   histoRes->GetXaxis()->SetTitle("Number of active branches");
   histoRes->GetYaxis()->SetTitle("Real time (s)");
   histoRes->SetDirectory(0);
   histoRes->SetStats(kFALSE);
   ProduceTree("TreeFile.root","TestTree", numentries, 0, 10, 10, BufferSize);

   Float_t RealTime, CpuTime;
    
   for(int ActiveBranches=1;ActiveBranches<=10;ActiveBranches++) {
      PurgeMemory();  
      cout << "Buffer size = " << BufferSize*sizeof(Float_t)*10 << " ActiveBranches = " << ActiveBranches << endl;
      MakeDelay(5);
      TestTree("TreeFile.root","TestTree", 10, 10, ActiveBranches, RealTime, CpuTime);
      histoRes->SetBinContent(ActiveBranches, RealTime);
   } 
    
   TCanvas* c1 = new TCanvas(TString(name)+"_canvas",title);
   histoRes->Draw();
   c1->SaveAs(TString(name)+".gif");
}
예제 #4
0
void Plot1DimFoams(TList& foam_list, TMVA::ECellValue cell_value,
                   const TString& cell_value_description,
                   TMVA::PDEFoamKernelBase* kernel)
{
   // visualize a 1 dimensional PDEFoam via a histogram
   TCanvas* canvas = NULL;
   TH1D* projection = NULL;

   // loop over all foams and draw the histogram
   TListIter it(&foam_list);
   TPair* fm_pair = NULL;    // the (foam, caption) pair
   while (fm_pair = (TPair*) it()) {
      TMVA::PDEFoam* foam = (TMVA::PDEFoam*) fm_pair->Key();
      if (!foam) continue;
      TString foam_caption(((TObjString*) fm_pair->Value())->String());
      TString variable_name(foam->GetVariableName(0)->String());

      canvas = new TCanvas(Form("canvas_%u",foam),
                           "1-dimensional PDEFoam", 400, 400);

      projection = foam->Draw1Dim(cell_value, 100, kernel);
      projection->SetTitle(cell_value_description + " of " + foam_caption
                           + ";" + variable_name);
      projection->Draw();
      projection->SetDirectory(0);

      canvas->Update();
   }
}
예제 #5
0
파일: fft.C 프로젝트: svn2github/Go4
///////////////////////////////////////////////////////////////////
//////// Go4 GUI example script fft.C
//          J.Adamczewski, gsi, 30 May 2012
// NOTE: to be run in Go4 GUI local command line only!
//       NEVER call this script in remote analysis process!!!
/////// Functionality:
// perfroms fft on histogram of name1 using the option as explained in root TVirtualFFT:FFT
/////// Usage:
// The draw flag switches if the results are displayed each time this macro is called
// if display is switched off, the result histogram is just updated in browser and existing displays
///////
Bool_t fft(const char* name1, Option_t*  opt = "R2C M", Bool_t draw=kTRUE)
{
   if(TGo4AbstractInterface::Instance()==0 || go4!=TGo4AbstractInterface::Instance()) {
      std::cout <<"FATAL: Go4 gui macro executed outside Go4 GUI!! returning." << std::endl;
      return kFALSE;
   }
   TString newname;
   TString fullname1 = go4->FindItem(name1);
   TObject* ob1 = go4->GetObject(fullname1,1000); // 1000=timeout to get object from analysis in ms

   if ((ob1==0) || !ob1->InheritsFrom("TH1")) {
     std::cout <<"fft could not get histogram "<<fullname1 << std::endl;
     return kFALSE;
   }

   if(ob1->InheritsFrom("TH2") || ob1->InheritsFrom("TH3")){  // 2d
      std::cout <<"fft does not support 2d/3d histogram "<<fullname1 << std::endl;
      return kFALSE;
   }

   TH1* his1=(TH1*)ob1;
   TString n1=his1->GetName();
   TString t1=his1->GetTitle();
   newname.Form("_fft_%s",opt);
   TString finalname = n1+newname;
   TString finaltitle = t1+newname;


   // do fft here:
   Int_t N = his1->GetNbinsX();
   TH1D* result = new TH1D(finalname, finaltitle,N,0,N);
   result->SetName(finalname);
   result->SetTitle(finaltitle);
   result->Reset("");
   Double_t *in = new Double_t[N];
   // since we do not know type of input histo, we copy contents to Double array:
   for(Int_t ix=0; ix<N;++ix)
   {
      in[ix]=his1->GetBinContent(ix+1);
   }
   TVirtualFFT *thefft = TVirtualFFT::FFT(1, &N, opt);
   thefft->SetPoints(in);
   thefft->Transform();
   Double_t re, im;
   for (Int_t i=0; i<N; i++) {
      thefft->GetPointComplex(i, re, im);
      result->SetBinContent(i+1,TMath::Sqrt(re*re + im*im));
   }
   result->SetDirectory(0);

   TString rname = go4->SaveToMemory("FFT", result, kTRUE);
   std::cout<< "Saved result histogram to " << rname.Data() <<std::endl;
   if(draw){
      ViewPanelHandle vpanel = go4->StartViewPanel();
      go4->DrawItem(rname, vpanel);
   }
   return kTRUE;
}
예제 #6
0
int
main (int argc, char *argv[])
{
  map<string, string> opt;
  vector<string> argVector;
  parseOptions (argc, argv, opt, argVector);
  if (argVector.size () != 1 || opt.count ("help"))
    {
      printHelp (argv[0]);
      return 0;
    }
  TFile *fin;
  if (!(fin = TFile::Open (argVector.at (0).c_str (), "update")))
    {
      cout << "Failed to open " << argVector.at (0) << "!" << endl;
      return 0;
    }
  TIter next0 (fin->GetListOfKeys ());
  TObject *obj0;
  TH1D *cutFlow = 0;
  TDirectoryFile *dir = 0;
  while ((obj0 = next0 ()))
    {
      string obj0Class = ((TKey *) obj0)->GetClassName (),
             obj0Name = obj0->GetName ();

      if (obj0Class == "TDirectoryFile")
        {
          dir = (TDirectoryFile *) fin->Get (obj0Name.c_str ());
          TIter next1 (dir->GetListOfKeys ());
          TObject *obj1;
          while ((obj1 = next1 ()))
            {
              string obj1Class = ((TKey *) obj1)->GetClassName (),
                     obj1Name = obj1->GetName ();

              if (obj1Class == "TH1D" && obj1Name.length () >= 7 && ((obj1Name.substr (obj1Name.length () - 7, 7) == "CutFlow" || obj1Name.substr (obj1Name.length () - 7, 7) == "cutFlow")
               || (obj1Name.length () >= 9 && (obj1Name.substr (obj1Name.length () - 9, 9) == "Selection" || obj1Name.substr (obj1Name.length () - 9, 9) == "selection"))
               || (obj1Name.length () >= 8 && (obj1Name.substr (obj1Name.length () - 8, 8) == "MinusOne" || obj1Name.substr (obj1Name.length () - 8, 8) == "minusOne")))
               && !dir->Get ((obj1Name + "LowerLimit").c_str ()) && !dir->Get ((obj1Name + "UpperLimit").c_str ()))
                {
                  cutFlow = (TH1D *) dir->Get (obj1Name.c_str ());
                  cutFlow->SetDirectory (0);
                  getLimits (cutFlow, dir);
                }
            }
        }
    }
  fin->Close ();

  return 0;
}
void ManuallyRebin(TH1D* h1, TFile *out)
{
  cout<<"Taking weighted average"<<endl;
  Int_t nCombine = 40; // Merge 100 bins into 1

  Int_t totalBins = h1->GetNbinsX();
  Int_t finalBins = totalBins/nCombine;
  cout<<"Final N bins:\t"<<finalBins<<endl;
  TString newName = h1->GetName();
  newName += "WgtAvg";
  TH1D *newH = new TH1D(newName, newName, finalBins,
			h1->GetXaxis()->GetXmin(),
			h1->GetXaxis()->GetXmax());
  newH->SetLineColor(kGreen);

  for(Int_t iNewBin = 0; iNewBin < finalBins; iNewBin++)
  {
    Double_t weightedSum = 0.;
    Double_t weights = 0.;
    
    for(Int_t iOldBin = 1; iOldBin < nCombine+1; iOldBin++)
    {
      Int_t binNum = iNewBin * nCombine + iOldBin;
      Double_t errorSq = pow(h1->GetBinError(binNum), 2.);
      Double_t content = h1->GetBinContent(binNum);

      weights += 1./errorSq;
      weightedSum += (1./errorSq) * content;
    }

    Double_t avg = weightedSum/weights;
    Double_t newErr = 1./sqrt(weights);

    newH->SetBinContent(iNewBin + 1, avg);
    newH->SetBinError(iNewBin + 1, newErr);
  }

  TDirectory *dir = out->GetDirectory("WeightedAvg");
  if(!dir) {
    dir = out->mkdir("WeightedAvg");
  }
  dir->cd();
  newH->SetDirectory(0);
  newH->Write(newH->GetName(), TObject::kOverwrite);
  
  // dir->Close();
  
}
예제 #8
0
TH1D* readTH1(const TString &fileName, const TString &histName, const TString &newHistName, bool useCurrentStyle) {
 
  TFile f(fileName,"READ");
  TH1D *h = 0;
  f.GetObject(histName,h);
  if( h ) {
    h->SetDirectory(0);
    if( useCurrentStyle ) h->UseCurrentStyle();
    if( newHistName.Length() ) h->SetName(newHistName);
  } else {
    std::cerr << "ERROR in FileOps::readTH1: Histogram with name '" << histName << "' does not exist in file '" << fileName << "'\n.";
    f.Close();
    exit(-1);
  }
  f.Close();
  
  return h;
}
예제 #9
0
//always data
TH1D* getQCD(TString Obj, TString Variable, int rebinFact){
	TString dir = "rootFilesV4/central/";
	TFile* file = new TFile(dir + "SingleMu_19584pb_PFElectron_PFMuon_PF2PATJets_PFMET.root");
	//TDirectoryFile* folder = (TDirectoryFile*) file->Get("TTbarPlusMetAnalysis/QCD No Iso/Muon/");

	TH1D* plot = (TH1D*) file->Get("TTbar_plus_X_analysis/MuPlusJets/QCD non iso mu+jets ge4j/"+Obj+Variable+"0btag");

	plot->SetFillColor(kYellow);
	plot->SetLineColor(kYellow);
    	
	plot->Scale(1/plot->Integral());
	plot->Rebin(rebinFact);

	plot->SetDirectory(gROOT);
	file->Close();

	return plot;

}
void make(TDirectory & out, TObject * o) {
  TDirectory * dir;
  TH1F * th1f;
  TH1D * th1d;
  TH2F * th2f;
  TH2D * th2d;
  out.cd();
  if((dir = dynamic_cast<TDirectory*>(o)) != 0) {
    TDirectory * outDir = out.mkdir(dir->GetName(), dir->GetTitle());
    TIter next(dir->GetListOfKeys());
    TKey *key;
    while( (key = dynamic_cast<TKey*>(next())) ) {
      string className(key->GetClassName());
      string name(key->GetName());
      TObject * obj = dir->Get(name.c_str());
      if(obj == 0) {
	cerr <<"error: key " << name << " not found in directory " << dir->GetName() << endl;
	exit(-1);
      }
      make(*outDir, obj);
    }
  } else if((th1f = dynamic_cast<TH1F*>(o)) != 0) {
    TH1F *h = (TH1F*) th1f->Clone();
    h->Reset();
    h->Sumw2();
    h->SetDirectory(&out);
  } else if((th1d = dynamic_cast<TH1D*>(o)) != 0) {
    TH1D *h = (TH1D*) th1d->Clone();
    h->Reset();
    h->Sumw2();
    h->SetDirectory(&out);
  } else if((th2f = dynamic_cast<TH2F*>(o)) != 0) {
    TH2F *h = (TH2F*) th2f->Clone();
    h->Reset();   
    h->Sumw2();
    h->SetDirectory(&out);
  } else if((th2d = dynamic_cast<TH2D*>(o)) != 0) {
    TH2D *h = (TH2D*) th2d->Clone();
    h->Reset();   
    h->Sumw2();
    h->SetDirectory(&out);
  }
}
void RebinHist(TH1D* h1, TFile *out)
{
  // This rebinning method doesn't work
  // It needs to divide by the entries to make an average
  // Also, it doesn't include error weighting.
  cout<<"Rebinning histogram"<<endl;
  Int_t nBins = h1->GetNbinsX();
  TH1D *rebinHist = (TH1D*) h1->Clone();
  rebinHist->Rebin(nBins/2);

  // TFile out("Compare.root","update");
  TDirectory *dir = out->GetDirectory("Rebin");
  if(!dir) dir = out->mkdir("Rebin");
  dir->cd();

  TString histName = h1->GetName();
  histName += "Rebin";
  rebinHist->SetName(histName);
  rebinHist->SetTitle(histName);
  rebinHist->SetDirectory(0);
  rebinHist->Write(rebinHist->GetName(), TObject::kOverwrite);
  // out->Close();

}
예제 #12
0
HitInfo::HitInfo(const Mechanics::Device* device,
                 TDirectory* dir,
                 const char* suffix,
                 unsigned int lvl1Bins,
                 unsigned int totBins) :
  // Base class is initialized here and manages directory / device
  SingleAnalyzer(device, dir, suffix),
  _lvl1Bins(lvl1Bins),
  _totBins(totBins)
{
  assert(device && "Analyzer: can't initialize with null device");

  // Makes or gets a directory called from inside _dir with this name
  TDirectory* plotDir = makeGetDirectory("HitInfo");

  std::stringstream name; // Build name strings for each histo
  std::stringstream title; // Build title strings for each histo

  // Generate a histogram for each sensor in the device
  for (unsigned int nsens = 0; nsens < _device->getNumSensors(); nsens++)
  {
    Mechanics::Sensor* sensor = _device->getSensor(nsens);

    name.str(""); title.str("");
    name << sensor->getDevice()->getName() << sensor->getName()
         <<  "Timing" << _nameSuffix;
    title << sensor->getDevice()->getName() << " " << sensor->getName()
          << " Level 1 Accept"
          << ";Level 1 bin number"
          << ";Hits";
    TH1D* lvl1 = new TH1D(name.str().c_str(), title.str().c_str(),
                          _lvl1Bins, 0 - 0.5, _lvl1Bins - 0.5);
    lvl1->SetDirectory(plotDir);
    _lvl1.push_back(lvl1);

    name.str(""); title.str("");
    name << sensor->getDevice()->getName() << sensor->getName()
         <<  "ToT" << _nameSuffix;
    title << sensor->getDevice()->getName() << " " << sensor->getName()
          << " ToT Distribution"
          << ";ToT bin number"
          << ";Hits";
    TH1D* tot = new TH1D(name.str().c_str(), title.str().c_str(),
                         _totBins, 0 - 0.5, _totBins - 0.5);
    tot->SetDirectory(plotDir);
    _tot.push_back(tot);

    name.str(""); title.str("");
    name << sensor->getName() << "ToTMap" << _nameSuffix;
    title << sensor->getName() << " ToT Map"
          << ";X pixel"
          << ";Y pixel"
          << ";Average ToT";
    TH2D* totMap = new TH2D(name.str().c_str(), title.str().c_str(),
                            sensor->getNumX(), 0 - 0.5, sensor->getNumX() - 0.5,
                            sensor->getNumY(), 0 - 0.5, sensor->getNumY() - 0.5);
    totMap->SetDirectory(plotDir);
    _totMap.push_back(totMap);

    name.str(""); title.str("");
    name << sensor->getName() << "ToTMapCnt" << _nameSuffix;
    title << sensor->getName() << " ToT Map Counter";
    TH2D* totMapCnt = new TH2D(name.str().c_str(), title.str().c_str(),
                               sensor->getNumX(), 0 - 0.5, sensor->getNumX() - 0.5,
                               sensor->getNumY(), 0 - 0.5, sensor->getNumY() - 0.5);
    totMapCnt->SetDirectory(0);
    _totMapCnt.push_back(totMapCnt);
  }
}
예제 #13
0
int main(int argc, char* argv[])
{
  TApplication theApp(srcName.Data(), &argc, argv);
//=============================================================================

  if (argc<5) return -1;
  TString sPath = argv[1]; if (sPath.IsNull()) return -1;
  TString sFile = argv[2]; if (sFile.IsNull()) return -1;
  TString sJetR = argv[3]; if (sJetR.IsNull()) return -1;
  TString sSjeR = argv[4]; if (sSjeR.IsNull()) return -1;
//=============================================================================

  sPath.ReplaceAll("#", "/");
//=============================================================================

  double dJetR = -1.;
  if (sJetR=="JetR02") dJetR = 0.2;
  if (sJetR=="JetR03") dJetR = 0.3;
  if (sJetR=="JetR04") dJetR = 0.4;
  if (sJetR=="JetR05") dJetR = 0.5;

  if (dJetR<0.) return -1;
  cout << "Jet R = " << dJetR << endl;
//=============================================================================

  double dSjeR = -1.;
  if (sSjeR=="SjeR01") dSjeR = 0.1;
  if (sSjeR=="SjeR02") dSjeR = 0.2;
  if (sSjeR=="SjeR03") dSjeR = 0.3;
  if (sSjeR=="SjeR04") dSjeR = 0.4;

  if (dSjeR<0.) return -1;
  cout << "Sub-jet R = " << dSjeR << endl;
//=============================================================================

  const double dJetsPtMin  = 0.001;
  const double dCutEtaMax  = 1.6;
  const double dJetEtaMax  = 1.;
  const double dJetAreaRef = TMath::Pi() * dJetR * dJetR;

  fastjet::GhostedAreaSpec areaSpc(dCutEtaMax);
  fastjet::JetDefinition   jetsDef(fastjet::antikt_algorithm, dJetR, fastjet::E_scheme, fastjet::Best);

//fastjet::AreaDefinition  areaDef(fastjet::active_area,areaSpc);
  fastjet::AreaDefinition  areaDef(fastjet::active_area_explicit_ghosts,areaSpc);

//fastjet::JetDefinition   bkgsDef(fastjet::kt_algorithm, 0.2, fastjet::BIpt_scheme, fastjet::Best);
//fastjet::AreaDefinition  aBkgDef(fastjet::active_area_explicit_ghosts, areaSpc);

  fastjet::Selector selectJet = fastjet::SelectorAbsEtaMax(dJetEtaMax);
//fastjet::Selector selectRho = fastjet::SelectorAbsEtaMax(dCutEtaMax-0.2);
//fastjet::Selector selecHard = fastjet::SelectorNHardest(2);
//fastjet::Selector selectBkg = selectRho * (!(selecHard));
//fastjet::JetMedianBackgroundEstimator bkgsEstimator(selectBkg, bkgsDef, aBkgDef);
//fastjet::Subtractor                   bkgSubtractor(&bkgsEstimator);

  fastjet::JetDefinition subjDef(fastjet::kt_algorithm, dSjeR, fastjet::E_scheme, fastjet::Best);
//=============================================================================

  std::vector<fastjet::PseudoJet> fjInput;
  const double dMass = TDatabasePDG::Instance()->GetParticle(211)->Mass();
//=============================================================================

  TList *list = new TList();
  TH1D *hJet = new TH1D("hJet", "", 1000, 0., 1000.); hJet->Sumw2(); list->Add(hJet);

  enum                    {  kJet,   kMje,   kDsz,   kIsm,   kZsm,   kDsr, kVar };
  const TString sHist[] = { "aJet", "aMje", "aDsz", "aIsm", "aZsm", "aDsr" };
  const Int_t      nv[] = {   1000,    150,  120,      150,    150,    500 };
  const Double_t dMin[] = {     0.,     0.,   0.,       0.,     0.,     0. };
  const Double_t dMax[] = {  1000.,   150.,  1.2,     150.,    1.5,     5. };

  THnSparseD *hs = new THnSparseD("hs", "", kVar, nv, dMin, dMax); hs->Sumw2();
  for (Int_t i=0; i<kVar; i++) hs->GetAxis(i)->SetName(sHist[i].Data()); list->Add(hs);
//=============================================================================

  HepMC::IO_GenEvent ascii_in(Form("%s/%s.hepmc",sPath.Data(),sFile.Data()), std::ios::in);
  HepMC::GenEvent *evt = ascii_in.read_next_event();

  while (evt) {
    fjInput.resize(0);

    TLorentzVector vPar;
    for (HepMC::GenEvent::particle_const_iterator p=evt->particles_begin(); p!=evt->particles_end(); ++p) if ((*p)->status()==1) {
      vPar.SetPtEtaPhiM((*p)->momentum().perp(), (*p)->momentum().eta(), (*p)->momentum().phi(), dMass);

      if ((TMath::Abs(vPar.Eta())<dCutEtaMax)) {
        fjInput.push_back(fastjet::PseudoJet(vPar.Px(), vPar.Py(), vPar.Pz(), vPar.E()));
      }
    }
//=============================================================================

    fastjet::ClusterSequenceArea clustSeq(fjInput, jetsDef, areaDef);
    std::vector<fastjet::PseudoJet> includJets = clustSeq.inclusive_jets(dJetsPtMin);
//  std::vector<fastjet::PseudoJet> subtedJets = bkgSubtractor(includJets);
    std::vector<fastjet::PseudoJet> selectJets = selectJet(includJets);
//  std::vector<fastjet::PseudoJet> sortedJets = fastjet::sorted_by_pt(selectJets);

    for (int j=0; j<selectJets.size(); j++) {
      double dJet = selectJets[j].pt();

      hJet->Fill(dJet);
//=============================================================================

      fastjet::Filter trimmer(subjDef, fastjet::SelectorPtFractionMin(0.));
      fastjet::PseudoJet trimmdJet = trimmer(selectJets[j]);
      std::vector<fastjet::PseudoJet> trimmdSj = trimmdJet.pieces();

      double d1sj = -1.; int k1sj = -1;
      double d2sj = -1.; int k2sj = -1;
      for (int i=0; i<trimmdSj.size(); i++) {
        double dIsj = trimmdSj[i].pt(); if (dIsj<0.001) continue;

        if (dIsj>d1sj) {
          d2sj = d1sj; k2sj = k1sj;
          d1sj = dIsj; k1sj = i;
        } else if (dIsj>d2sj) {
          d2sj = dIsj; k2sj = i;
        }
      }

      if ((d1sj>0.) && (d2sj>0.)) {
        TLorentzVector v1sj; v1sj.SetPtEtaPhiM(d1sj, trimmdSj[k1sj].eta(), trimmdSj[k1sj].phi(), trimmdSj[k1sj].m());
        TLorentzVector v2sj; v2sj.SetPtEtaPhiM(d2sj, trimmdSj[k2sj].eta(), trimmdSj[k2sj].phi(), trimmdSj[k2sj].m());
        TLorentzVector vIsj = v1sj + v2sj;

        Double_t dIsm = vIsj.M();
        Double_t dMje = selectJets[j].m();
        Double_t dVar[] = { dJet, dMje, (d1sj-d2sj)/dJet, dIsm, dIsm/dMje, v1sj.DeltaR(v2sj)/2./dJetR };

        hs->Fill(dVar);
      }
    }
//=============================================================================

    delete evt;
    ascii_in >> evt;
  }
//=============================================================================

  TString sXsec = sFile; sXsec.ReplaceAll("out", "xsecs");
  TFile *file = TFile::Open(Form("%s/xsecs/%s.root",sPath.Data(),sXsec.Data()), "READ");
  TH1D *hPtHat        = (TH1D*)file->Get("hPtHat");        hPtHat->SetDirectory(0);
  TH1D *hWeightSum    = (TH1D*)file->Get("hWeightSum");    hWeightSum->SetDirectory(0);
  TProfile *hSigmaGen = (TProfile*)file->Get("hSigmaGen"); hSigmaGen->SetDirectory(0);
  file->Close();
//=============================================================================

  file = TFile::Open(Form("%s.root",sFile.Data()), "NEW");
  hPtHat->Write();
  hWeightSum->Write();
  hSigmaGen->Write();
  list->Write();
  file->Close();
//=============================================================================

  cout << "DONE" << endl;
  return 0;
}
예제 #14
0
//_______________________________________
void FitMCshape(AliDielectronSignalBase *sig)
{
  TFile mcFile(mcLineShapeFile);
  if (!mcFile.IsOpen()) {
    printf("mcMinv_LHC10e2 not found!!!\n");
    return;
  }
  TH1D *hMmc = (TH1D*)mcFile.Get("mcMinv");
  if (!hMmc) {
    printf("mcMinv not found!!\n");
    return;
  }
  hMmc->SetDirectory(0);
  hMmc->SetName("mcMinv");
  mcFile.Close();
  
  TH1* hMsub=sig->GetSignalHistogram();
  Double_t mb1=sig->GetIntegralMin();
  Double_t mb2=sig->GetIntegralMax();
  
  Double_t effInt = 0.;
  for(Int_t iBin=hMmc->FindBin(mb1); iBin<hMmc->FindBin(mb2); iBin++) {
    effInt += hMmc->GetBinContent(iBin);
  }
  effInt/=hMmc->Integral();
  printf("MC signal fraction in range %4.2f-%4.2f GeV: %5.3f \n",hMmc->GetBinLowEdge(hMmc->FindBin(mb1)),hMmc->GetBinLowEdge(hMmc->FindBin(mb2)+1),effInt);
 
  Float_t mcScale1=(hMsub->GetXaxis()->GetBinWidth(1)/hMmc->GetXaxis()->GetBinWidth(1))*
    hMsub->Integral(hMsub->FindBin(mb1),hMsub->FindBin(mb2))/
    hMmc->Integral(hMmc->FindBin(mb1),hMmc->FindBin(mb2));
  
  printf("1st guess of MC scale factor: %6.3f\n",mcScale1);
  
  Float_t mcScale=0.;
  Float_t chi2_min=100000.;
  Int_t iMin=0;
  Int_t ndf=0;
  
  for(Int_t i=0; i<20; i++){
    Float_t chi2=0.;
    Float_t scale=(0.4+0.05*(Float_t)i)*mcScale1;
    ndf=0;
    for(Int_t ib=1; ib<=hMsub->GetXaxis()->GetNbins(); ib++){
      Float_t data=(Float_t)hMsub->GetBinContent(ib);
      Float_t err=(Float_t)hMsub->GetBinError(ib);
      Float_t mc=scale*((Float_t)hMmc->GetBinContent(hMmc->FindBin(hMsub->GetBinCenter(ib))));
      if (err>0) {
        chi2 += ((data-mc)*(data-mc))/(err*err);
        ndf++;
      } else {
        //printf("bin %d Err: %6.3f, chi2: %6.1f\n",ib,err,chi2);
      }
    }
      //printf("%d scale factor: %6.3f, chi2: %6.1f\n",i,scale,chi2);
    if(chi2 < chi2_min){
      chi2_min = chi2;
      mcScale = scale;
      iMin=i;
    }
  }
  //Float_t chi2dof=chi2_min/(Float_t)(hMinv->GetXaxis()->GetNbins()-1);
  Float_t chi2dof=chi2_min/((Float_t)(ndf-1));
  printf("MC fit (i=%d): chi2/dof: %6.3f/%d, Scale: %7.4f \n",iMin,chi2_min,(ndf-1),mcScale);
  hMmc->SetTitle(Form("%f",chi2dof));
  
  //mcScale=IntData/IntMC;printf("Int Data, MC: %10.1f %10.1f, MC scale: %6.3f\n",IntData,IntMC,mcScale);
  
  hMmc->Scale(mcScale);
  hMmc->SetOption("sameHISTC");
  hMsub->GetListOfFunctions()->Add(hMmc);
}
예제 #15
0
/** 
 * 
 * 
 * @param o 
 * @param useWeights 
 * @param correct
 *
 * @ingroup pwglf_forward_scripts_tests
 */
void
TestPoisson(Double_t o=.3, bool useWeights=false, bool correct=true)
{
  const char* load = "$ALICE_PHYSICS/PWGLF/FORWARD/analysis2/scripts/LoadLibs.C";
  if (!gROOT->GetClass("AliAODForwardMult")) {
    gROOT->Macro(load);
    gROOT->GetInterpreter()->UnloadFile(gSystem->ExpandPathName(load));
  }
  
  // --- Parameters of this script -----------------------------------
  Int_t      nBin =  5;  // Our detector matrix size 
  Int_t      nMax = TMath::Max(Int_t(nBin * nBin * o + .5)+nBin/2,nBin);  
  Int_t      nEv  = 10000; // Number of events
  Double_t   mp   = o;   // The 'hit' probability 


  TH2D* base = new TH2D("base", "Basic histogram", 
			nBin,-.5, nBin-.5, nBin, -.5, nBin-.5);
  base->SetXTitle("#eta");
  base->SetYTitle("#varphi");
  base->SetDirectory(0);
  base->SetOption("colz");

  Int_t tN1=nMax;    Double_t tMin1; Double_t tMax1;
  Int_t tN2=nMax*10; Double_t tMin2; Double_t tMax2=nMax;
  MakeIntegerAxis(tN1, tMin1, tMax1);
  MakeIntegerAxis(tN2, tMin2, tMax2);
  TH2D* corr = new TH2D("comp", "Comparison", 
			tN1, tMin1, tMax1, tN2, tMin2, tMax2);
  corr->SetXTitle("Input");
  corr->SetYTitle("Poisson");
  corr->SetDirectory(0);
  corr->SetOption("colz");
  corr->SetStats(0);
  TLine* lcorr = new TLine(0, 0, tMax2, tMax2);

  Int_t mm = TMath::Max(Int_t(nBin * o + .5),nBin/2);
  tN2=mm*10; tMax2 = mm;
  MakeIntegerAxis(tN2, tMin2, tMax2);
  Info("", "Making mean w/nbins=%d,range=[%f,%f]", tN2, tMin2, tMax2);
  TH2D* mean = new TH2D("mean", "Mean comparison", 
			tN2, tMin2, tMax2, tN2, tMin2, tMax2);
  mean->SetXTitle("Input");
  mean->SetYTitle("Poisson");
  mean->SetDirectory(0);
  mean->SetOption("colz");
  mean->SetStats(0);
  TLine* lmean = new TLine(tMin2, tMin2, tMax2, tMax2);

  TH1D* dist = new TH1D("dist", "Distribution of hits", tN1, tMin1, tMax1);
  dist->SetXTitle("s");
  dist->SetYTitle("P(s)");
  dist->SetFillColor(kRed+1);
  dist->SetFillStyle(3001);
  dist->SetDirectory(0);

  TH1D* diff = new TH1D("diff", "P-T", 100, -25, 25);
  diff->SetXTitle("Difference");
  diff->SetFillColor(kRed+1);
  diff->SetFillStyle(3001);
  diff->SetYTitle("Prob");

  AliPoissonCalculator* c = new AliPoissonCalculator("ignored");
  c->Init(nBin ,nBin);

  for (Int_t i = 0; i < nEv; i++) { 
    c->Reset(base);
    base->Reset();

    for (Int_t iEta = 0; iEta < nBin; iEta++) { 
      for (Int_t iPhi = 0; iPhi < nBin; iPhi++) { 
	// Throw a die 
	Int_t m = gRandom->Poisson(mp);
	dist->Fill(m);

	// Fill into our base histogram 
	base->Fill(iEta, iPhi, m);

	// Fill into poisson calculator 
	c->Fill(iEta, iPhi, m > 0, (useWeights ? m : 1));
      }
    }
    // Calculate the result 
    TH2D* res = c->Result(correct);
    
    // Now loop and compare 
    Double_t mBase = 0;
    Double_t mPois = 0;
    for (Int_t iEta = 0; iEta < nBin; iEta++) { 
      for (Int_t iPhi = 0; iPhi < nBin; iPhi++) { 
	Double_t p = res->GetBinContent(iEta, iPhi);
	Double_t t = base->GetBinContent(iEta, iPhi);

	mBase += t;
	mPois += p;
	corr->Fill(t, p);
	diff->Fill(p-t);
      }
    }
    Int_t nn = nBin * nBin;
    mean->Fill(mBase / nn, mPois / nn);
  }

  TCanvas* cc = new TCanvas("c", "c", 900, 900);
  cc->SetFillColor(0);
  cc->SetFillStyle(0);
  cc->SetBorderMode(0);
  cc->SetRightMargin(0.02);
  cc->SetTopMargin(0.02);
  cc->Divide(2,2);
  
  TVirtualPad* pp = cc->cd(1);
  pp->SetFillColor(0);
  pp->SetFillStyle(0);
  pp->SetBorderMode(0);
  pp->SetRightMargin(0.15);
  pp->SetTopMargin(0.02);
  pp->SetLogz();
  pp->SetGridx();
  pp->SetGridy();
  corr->Draw();
  lcorr->Draw();

  pp = cc->cd(2);
  pp->SetFillColor(0);
  pp->SetFillStyle(0);
  pp->SetBorderMode(0);
  pp->SetRightMargin(0.02);
  pp->SetTopMargin(0.02);
#if 0
  c->GetMean()->Draw();
#elif 1 
  pp->SetLogy();
  diff->Draw();
#elif 1
  c->GetOccupancy()->Draw();
#else
  pp->SetLogy();
  dist->SetStats(0);
  dist->Scale(1. / dist->Integral());
  dist->Draw();
  TH1D* m1 = c->GetMean();
  m1->Scale(1. / m1->Integral());
  m1->Draw("same");
  Double_t eI;
  Double_t ii = 100 * dist->Integral(2, 0);
  TLatex* ll = new TLatex(.97, .85, 
			  Form("Input #bar{m}: %5.3f", mp));
  ll->SetNDC();
  ll->SetTextFont(132);
  ll->SetTextAlign(31);
  ll->Draw();
  ll->DrawLatex(.97, .75, Form("Result #bar{m}: %5.3f", dist->GetMean()));
  ll->DrawLatex(.97, .65, Form("Occupancy: #int_{1}^{#infty}P(s)ds = %6.2f%%",
			       ii));
			 
#endif

  pp = cc->cd(3);
  pp->SetFillColor(0);
  pp->SetFillStyle(0);
  pp->SetBorderMode(0);
  pp->SetRightMargin(0.15);
  pp->SetTopMargin(0.02);
  pp->SetGridx();
  pp->SetGridy();
  c->GetCorrection()->Draw();

  pp = cc->cd(4);
  pp->SetFillColor(0);
  pp->SetFillStyle(0);
  pp->SetBorderMode(0);
  pp->SetRightMargin(0.15);
  pp->SetTopMargin(0.02);
  pp->SetLogz();
  pp->SetGridx();
  pp->SetGridy();
  mean->Draw();
  lmean->Draw();

  cc->cd();
}
예제 #16
0
void CombineCFsInDataDir(TDirectory *f, vector<TString> dataSetNames)
{
  TString cfDirName = "CF";
  TString countDirName = "Count";
  vector<TDirectory*> cfDirs = GetDirectories(f, dataSetNames, cfDirName);
  vector<TDirectory*> countDirs = GetDirectories(f, dataSetNames, countDirName);
  TDirectory *mergeDir = (TDirectory*)f->GetDirectory("Merged");
  if(!mergeDir) {
    mergeDir = f->mkdir("Merged");
  }

  UInt_t nDirs = cfDirs.size();
  // Merge each centrality one at a time
  // Load the cfs and counts into vectors for that centrality
  // Find all the cfs and counts that match the name of the CF
  // in the first directory
  TIter iter(cfDirs[0]->GetListOfKeys());
  TObject *obj = NULL;

  while ( (obj = iter()) ) {
    TKey *key = dynamic_cast<TKey*>(obj);
    TH1D *cf = dynamic_cast<TH1D*>(key->ReadObj());
    if(!cf) {
      cout<<"Could not find a CF hist"<<endl;
      return;
    }
    //Figure out which CF we are trying to grab
    TString cfName = cf->GetName();
    TString countName = cfName;
    countName.ReplaceAll("CF","Count");

    //Grab the corresponding CFs and counts
    vector<TH1D*> cfs;
    vector<Double_t> counts;
    Double_t totalCounts = 0;
    for(UInt_t iDir = 0; iDir < nDirs; iDir++) {
      TH1D *thisCF = (TH1D*) cfDirs[iDir]->Get(cfName);
      if(!thisCF) {
	cout<<"Could not find CF matching "<<cfName
	    <<" in "<<cfDirs[iDir]->GetName()<<endl;
      }
      // TVectorD *count = dynamic_cast<TVectorD*>(countDirs[iDir]->Get(countName));
      TVectorD *count = (TVectorD*)countDirs[iDir]->Get(countName);
      // cout<<count->ClassName()<<endl;
      Double_t myCount = count[0](0);
      
      cfs.push_back(thisCF);
      counts.push_back(myCount);
      totalCounts += myCount;
    }
    // Finally, combine the CFs
    TH1D *combinedCF = CombineCFs(cfs, counts);
    if (!combinedCF) {
      cout << "Combine CF returned nothing. Continuing loop."
	   <<endl;
      continue;
    }
    TVectorD finalCount(1);
    finalCount[0] = totalCounts;

    cout<<"Writing combined CF "<<combinedCF->GetName()
    	<<" to "<<mergeDir->GetName()<<endl;
    combinedCF->SetDirectory(0);
    mergeDir->cd();
    combinedCF->Write(combinedCF->GetName(), TObject::kOverwrite);
    finalCount.Write(countName, TObject::kOverwrite);
  }
}
예제 #17
0
void CombineLLAAForDirectory(TDirectory *dataDir)
{
  // Run after merging centralities
  vector<TString> centBins = {"010", "1030", "3050"};
  vector<TString> pairTypes = {"LamLam", "ALamALam"};
  TString finalPairType = "LLAA";


  // Get merge dir
  TDirectory *mergeDir = dataDir->GetDirectory("Merged");
  if(!mergeDir) {
    cout<<"Merge directory does not exist. Cannot merge."<<endl;
    return;
  }

  for(UInt_t iCent = 0; iCent < centBins.size(); iCent++) {
    vector<TH1D*> cfs;
    vector<Double_t> counts;
    Double_t totalCounts = 0;
    for(UInt_t iType = 0; iType < pairTypes.size(); iType++) {
      TString cfName = "CF" + pairTypes[iType] + centBins[iCent];
      TH1D *cf = (TH1D*)mergeDir->Get(cfName);
      if(!cf) {
	cout<<"Could not find CF named "<<cfName<<" in "<<mergeDir->GetName()<<endl;
	return;
      }
      cfs.push_back(cf);
      TString countName = "Count" + pairTypes[iType] + centBins[iCent];
      TVectorD *count = (TVectorD*) mergeDir->Get(countName);
      totalCounts += count[0](0);
      counts.push_back(count[0](0));
    }

    // Finally, combine the CFs
    TH1D *combinedCF = CombineCFs(cfs, counts);
    if (!combinedCF) {
      cout << "Combine CF returned nothing. Continuing loop."
	   <<endl;
      continue;
    }
    TVectorD finalCount(1);
    finalCount[0] = totalCounts;

    // Set names
    TString combinedCFName = "CF" + finalPairType + centBins[iCent];
    TString combinedCountName = "Count" + finalPairType + centBins[iCent];
    combinedCF->SetName(combinedCFName);
    combinedCF->SetTitle(combinedCFName);

    // Set axis ranges
    combinedCF->SetAxisRange(0.9, 1.1, "Y");
    combinedCF->SetAxisRange(0., 1., "X");

    cout<<"Writing combined CF "<<combinedCF->GetName()
    	<<" to "<<mergeDir->GetName()<<endl;
    combinedCF->SetDirectory(0);
    mergeDir->cd();
    combinedCF->Write(combinedCF->GetName(), TObject::kOverwrite);
    finalCount.Write(combinedCountName, TObject::kOverwrite);
  
  }
}
예제 #18
0
void QCDAnalysis(
 Int_t nsel = 0,
 Int_t typeSel = 4,
 Int_t applyPrescale = 1,
 TString typeLepSel = "medium"
 ){

  Int_t period = 1;
  TString filesPath  = "/scratch5/ceballos/ntuples_weights/qcd_";
  Double_t lumi = 0.0715;
  if(period == 1) lumi = 2.2;

  Double_t prescale[5];

  double denFRDA[5][5] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
  double numFRDA[5][5] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
  double denFRBG[5][5] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
  double numFRBG[5][5] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

  //*******************************************************
  //Input Files
  //*******************************************************
  vector<TString> infilenamev;  
  vector<Int_t> infilecatv;  

  TString puPath = "";
  if     (period==0){
  }
  else if(period==1){
  if     (typeSel == 11) {prescale[0]=0.00000;prescale[1]=0.00859;prescale[2]=0.00520;prescale[3]=0.00750;prescale[4]=0.00956;}
  else if(typeSel == 13) {prescale[0]=0.00250;prescale[1]=0.07087;prescale[2]=0.09861;prescale[3]=0.09744;prescale[4]=0.09616;}
  puPath = "/home/ceballos/cms/cmssw/042/CMSSW_7_4_6/src/MitAnalysisRunII/data/puWeights_13TeV_25ns.root";
  infilenamev.push_back(Form("%sdata_AOD_Run2015C1_25ns.root",filesPath.Data())); 												  infilecatv.push_back(0);
  infilenamev.push_back(Form("%sdata_AOD_Run2015D3_25ns.root",filesPath.Data())); 												  infilecatv.push_back(0);
  infilenamev.push_back(Form("%sdata_AOD_Run2015D4_25ns.root",filesPath.Data())); 												  infilecatv.push_back(0);
  infilenamev.push_back(Form("%sWWTo2L2Nu_13TeV-powheg+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));					          infilecatv.push_back(1);
  infilenamev.push_back(Form("%sGluGluWWTo2L2Nu_MCFM_13TeV+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));                                          infilecatv.push_back(1);
  infilenamev.push_back(Form("%sDYJetsToLL_M-10to50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));         infilecatv.push_back(2);
  infilenamev.push_back(Form("%sDYJetsToLL_M-50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v3+AODSIM.root",filesPath.Data()));	          infilecatv.push_back(2);
  infilenamev.push_back(Form("%sTT_TuneCUETP8M1_13TeV-powheg-pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v2+AODSIM.root",filesPath.Data()));				  infilecatv.push_back(3); // tt->X (not tt->2l)
  infilenamev.push_back(Form("%sST_tW_top_5f_inclusiveDecays_13TeV-powheg-pythia8_TuneCUETP8M1+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));      infilecatv.push_back(3);
  infilenamev.push_back(Form("%sST_tW_antitop_5f_inclusiveDecays_13TeV-powheg-pythia8_TuneCUETP8M1+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));  infilecatv.push_back(3);
  infilenamev.push_back(Form("%sZZTo2L2Nu_13TeV_powheg_pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));				          infilecatv.push_back(4);
  infilenamev.push_back(Form("%sZZTo2L2Q_13TeV_amcatnloFXFX_madspin_pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));		          infilecatv.push_back(4);
  infilenamev.push_back(Form("%sZZTo4L_13TeV_powheg_pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));				          infilecatv.push_back(4);
  infilenamev.push_back(Form("%sGluGluToZZTo2e2mu_BackgroundOnly_13TeV_MCFM+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));			  infilecatv.push_back(4);
  infilenamev.push_back(Form("%sGluGluToZZTo2e2tau_BackgroundOnly_13TeV_MCFM+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));			  infilecatv.push_back(4);
  infilenamev.push_back(Form("%sGluGluToZZTo2mu2tau_BackgroundOnly_13TeV_MCFM+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));			  infilecatv.push_back(4);
  infilenamev.push_back(Form("%sGluGluToZZTo4e_BackgroundOnly_13TeV_MCFM+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));  			  infilecatv.push_back(4);
  infilenamev.push_back(Form("%sGluGluToZZTo4mu_BackgroundOnly_13TeV_MCFM+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data())); 			  infilecatv.push_back(4);
  infilenamev.push_back(Form("%sGluGluToZZTo4tau_BackgroundOnly_13TeV_MCFM+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));			  infilecatv.push_back(4);
  infilenamev.push_back(Form("%sWZTo1L1Nu2Q_13TeV_amcatnloFXFX_madspin_pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));		          infilecatv.push_back(4);
  infilenamev.push_back(Form("%sWZTo2L2Q_13TeV_amcatnloFXFX_madspin_pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v2+AODSIM.root",filesPath.Data()));		          infilecatv.push_back(4);
  infilenamev.push_back(Form("%sWZTo3LNu_TuneCUETP8M1_13TeV-powheg-pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));                          infilecatv.push_back(4);
  infilenamev.push_back(Form("%sWWZ_TuneCUETP8M1_13TeV-amcatnlo-pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));			          infilecatv.push_back(4);
  infilenamev.push_back(Form("%sWZZ_TuneCUETP8M1_13TeV-amcatnlo-pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));			          infilecatv.push_back(4);
  infilenamev.push_back(Form("%sZZZ_TuneCUETP8M1_13TeV-amcatnlo-pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v2+AODSIM.root",filesPath.Data()));			          infilecatv.push_back(4);
  infilenamev.push_back(Form("%sTTWJetsToLNu_TuneCUETP8M1_13TeV-amcatnloFXFX-madspin-pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));        infilecatv.push_back(4);
  infilenamev.push_back(Form("%sTTWJetsToQQ_TuneCUETP8M1_13TeV-amcatnloFXFX-madspin-pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));         infilecatv.push_back(4);
  infilenamev.push_back(Form("%sTTZToLLNuNu_M-10_TuneCUETP8M1_13TeV-amcatnlo-pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));	          infilecatv.push_back(4);
  infilenamev.push_back(Form("%sTTZToQQ_TuneCUETP8M1_13TeV-amcatnlo-pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));		          infilecatv.push_back(4);
  infilenamev.push_back(Form("%sTTGJets_TuneCUETP8M1_13TeV-amcatnloFXFX-madspin-pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));	          infilecatv.push_back(4);
  infilenamev.push_back(Form("%sWJetsToLNu_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));	          infilecatv.push_back(5);
  infilenamev.push_back(Form("%sWGToLNuG_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));  		  infilecatv.push_back(6);
  //infilenamev.push_back(Form("%sZGTo2LG_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));		          infilecatv.push_back(6);
  infilenamev.push_back(Form("%sGluGluHToWWTo2L2Nu_M125_13TeV_powheg_JHUgen_pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v3+AODSIM.root",filesPath.Data()));	          infilecatv.push_back(7);
  infilenamev.push_back(Form("%sVBFHToWWTo2L2Nu_M125_13TeV_powheg_JHUgen_pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));  	          infilecatv.push_back(7);
  infilenamev.push_back(Form("%sGluGluHToTauTau_M125_13TeV_powheg_pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data())); 		          infilecatv.push_back(7);
  infilenamev.push_back(Form("%sVBFHToTauTau_M125_13TeV_powheg_pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));			          infilecatv.push_back(7);
  /////infilenamev.push_back(Form("%sVHToNonbb_M125_13TeV_amcatnloFXFX_madspin_pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data())); 		  infilecatv.push_back(7);
  /////infilenamev.push_back(Form("%sttHJetToNonbb_M125_13TeV_amcatnloFXFX_madspin_pythia8_mWCutfix+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data())); infilecatv.push_back(7);
  }

  //infilenamev.push_back(Form("nero.root"));     infilecatv.push_back(0);

  if(infilenamev.size() != infilecatv.size()) assert(0);

  Float_t fMVACut[4][4];
  InitializeJetIdCuts(fMVACut);
 
  TFile *fPUFile = TFile::Open(Form("%s",puPath.Data()));
  TH1D *fhDPU = (TH1D*)(fPUFile->Get("puWeights"));
  assert(fhDPU);
  fhDPU->SetDirectory(0);
  delete fPUFile;

  double xmin = 0.0;
  double xmax = 1.0;
  int nBinPlot      = 200;
  double xminPlot   = 0.0;
  double xmaxPlot   = 200.0;
  const int allPlots = 11;
  const int histBins = 8;
  TH1D* histo[allPlots][histBins];

  for(int thePlot=0; thePlot<allPlots; thePlot++){
    if     (thePlot >=  0 && thePlot <=  5) {nBinPlot = 200; xminPlot = 0.0; xmaxPlot = 200.0;}
    else if(thePlot >=  6 && thePlot <=  6) {nBinPlot =   7; xminPlot =-0.5; xmaxPlot =   6.5;}
    else if(thePlot >=  7 && thePlot <=  7) {nBinPlot =  40; xminPlot = 0.0; xmaxPlot =  40.0;}
    else if(thePlot >=  8 && thePlot <=  8) {nBinPlot =  40; xminPlot =-0.5; xmaxPlot =  39.5;}
    else if(thePlot >=  9 && thePlot <=  9) {nBinPlot =  50; xminPlot = 0.0; xmaxPlot =  50.0;}
    else if(thePlot >= 10 && thePlot <= 10) {nBinPlot =  50; xminPlot = 0.0; xmaxPlot =   2.5;}
    TH1D* histos = new TH1D("histos", "histos", nBinPlot, xminPlot, xmaxPlot);
    histos->Sumw2();
    for(int i=0; i<histBins; i++) histo[thePlot][i] = (TH1D*) histos->Clone(Form("histo%d",i));
    histos->Clear();
  }

  //*******************************************************
  // Chain Loop
  //*******************************************************
  for(UInt_t ifile=0; ifile<infilenamev.size(); ifile++) {

    TFile the_input_file(infilenamev[ifile]);
    TTree *the_input_tree = (TTree*)the_input_file.FindObjectAny("events");
    //TTree *the_input_all  = (TTree*)the_input_file.FindObjectAny("all");

    BareMonteCarlo eventMonteCarlo;
    eventMonteCarlo.setBranchAddresses(the_input_tree);

    BareEvent eventEvent;
    eventEvent.setBranchAddresses(the_input_tree);

    BareJets eventJets;
    eventJets.setBranchAddresses(the_input_tree);

    BareLeptons eventLeptons;
    eventLeptons.setBranchAddresses(the_input_tree);

    BareTaus eventTaus;
    eventTaus.setBranchAddresses(the_input_tree);

    BareMet eventMet;
    eventMet.SetExtend();
    eventMet.setBranchAddresses(the_input_tree);

    BareTrigger eventTrigger;
    eventTrigger.setBranchAddresses(the_input_tree);

    BareVertex eventVertex;
    eventVertex.setBranchAddresses(the_input_tree);

    TNamed *triggerNames = (TNamed*)the_input_file.FindObjectAny("triggerNames");
    char **tokens;
    size_t numtokens;
    tokens = strsplit(triggerNames->GetTitle(), ",", &numtokens);
    if(infilecatv[ifile] == 0){
      for (int i = 0; i < (int)numtokens; i++) {
        printf("triggerNames(%2d): \"%s\"\n",(int)i,tokens[i]);
      }
    }
    else {
      printf("sampleNames(%d): %s\n",ifile,infilenamev[ifile].Data());
    }

    Int_t nPassTrigger[12] = {0,0,0,0,0,0,0,0,0,0,0,0};

    Int_t nPassCuts[10] = {0,0,0,0,0,0,0,0,0,0};
    double theMCPrescale = mcPrescale;
    if(infilecatv[ifile] == 0) theMCPrescale = 1.0;
    for (int i=0; i<int(the_input_tree->GetEntries()/theMCPrescale); ++i) {
      the_input_tree->GetEntry(i);
      if(i%100000==0) printf("event %d out of %d\n",i,(int)the_input_tree->GetEntries());

      if(typeSel != 11 && typeSel != 13) assert(0);

      Bool_t passFilter = kFALSE;
      Bool_t passTrigger = kFALSE;
      for (int nt = 0; nt < (int)numtokens; nt++) {
	if(typeSel == 11 &&
          (strcmp(tokens[nt],"HLT_Ele12_CaloIdL_TrackIdL_IsoVL_PFJet30_v*") == 0 ||
           strcmp(tokens[nt],"HLT_Ele18_CaloIdL_TrackIdL_IsoVL_PFJet30_v*") == 0 ||
           strcmp(tokens[nt],"HLT_Ele23_CaloIdL_TrackIdL_IsoVL_PFJet30_v*") == 0 ||
           strcmp(tokens[nt],"HLT_Ele33_CaloIdL_TrackIdL_IsoVL_PFJet30_v*") == 0) &&
	  (*eventTrigger.triggerFired)[nt] == 1) passTrigger = kTRUE;
	if(typeSel == 13 &&
	  (strcmp(tokens[nt],"HLT_Mu8_TrkIsoVVL_v*")  == 0 ||              
	   strcmp(tokens[nt],"HLT_Mu17_TrkIsoVVL_v*") == 0 ||              
	   strcmp(tokens[nt],"HLT_Mu24_TrkIsoVVL_v*") == 0 ||              
	   strcmp(tokens[nt],"HLT_Mu34_TrkIsoVVL_v*") == 0) &&           
	  (*eventTrigger.triggerFired)[nt] == 1) passTrigger = kTRUE;
      }
      if(passTrigger == kTRUE &&
         eventLeptons.p4->GetEntriesFast() >= 1 &&
         ((TLorentzVector*)(*eventLeptons.p4)[0])->Pt() > 10 && 
	 (double)((TLorentzVector*)(*eventMet.p4)[0])->Pt() < 30.0) passFilter = kTRUE;

      if(passTrigger == kTRUE) nPassCuts[0]++;
      if(passFilter  == kTRUE) nPassCuts[1]++;
      if(passFilter == kFALSE) continue;

      Bool_t passSel = kFALSE;
      TLorentzVector dilep;double deltaPhiDileptonMet = -999.0; double mtW = -999.0;
      vector<int> idLep; vector<int> idTight;
      for(int nlep=0; nlep<eventLeptons.p4->GetEntriesFast(); nlep++) {
        if(selectIdIsoCut(typeLepSel.Data(),TMath::Abs((int)(*eventLeptons.pdgId)[nlep]),TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[nlep])->Pt()),
	   TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[nlep])->Eta()),(double)(*eventLeptons.iso)[nlep],(int)(*eventLeptons.selBits)[nlep]))
	                                                                                               {idTight.push_back(1); idLep.push_back(nlep);}
        else if(((int)(*eventLeptons.selBits)[nlep] & BareLeptons::LepFake)  == BareLeptons::LepFake ) {idTight.push_back(0); idLep.push_back(nlep);}
      }

      vector<int> isGenLep;
      for(unsigned nl=0; nl<idLep.size(); nl++){
        bool isGenLepton = false;
        for(int ngen=0; ngen<eventMonteCarlo.p4->GetEntriesFast(); ngen++) {
          if(TMath::Abs((int)(*eventLeptons.pdgId)[idLep[nl]]) == TMath::Abs((int)(*eventMonteCarlo.pdgId)[ngen]) &&
	    ((TLorentzVector*)(*eventLeptons.p4)[idLep[nl]])->DeltaR(*((TLorentzVector*)(*eventMonteCarlo.p4)[ngen])) < 0.1) {
	    isGenLepton = true;
	    break;
	  }
	}
	if(isGenLepton == true) isGenLep.push_back(nl);
      }
      
      vector<int> idJet20,idJet30;
      for(int nj=0; nj<eventJets.p4->GetEntriesFast(); nj++){
        if(((TLorentzVector*)(*eventJets.p4)[nj])->Pt() < 10) continue;
        bool passId = passJetId(fMVACut, (float)(*eventJets.puId)[nj], ((TLorentzVector*)(*eventJets.p4)[nj])->Pt(), TMath::Abs(((TLorentzVector*)(*eventJets.p4)[nj])->Eta()));
        //if(passId == false) continue;        

        Bool_t isLepton = kFALSE;
        for(unsigned int nl=0; nl<idLep.size(); nl++){
          if(((TLorentzVector*)(*eventJets.p4)[nj])->DeltaR(*((TLorentzVector*)(*eventLeptons.p4)[idLep[nl]])) < 0.3) isLepton = kTRUE;
	}
	if(isLepton == kTRUE) continue;

        if(((TLorentzVector*)(*eventJets.p4)[nj])->Pt() > 20)  idJet20.push_back(nj);
        if(((TLorentzVector*)(*eventJets.p4)[nj])->Pt() > 30)  idJet30.push_back(nj);
      }

      if     (nsel == 0){ // Z->ll
        if(idLep.size() == 2) nPassCuts[2]++;
	if(idLep.size() == 2 &&
     	  ((TLorentzVector*)(*eventLeptons.p4)[idLep[0]])->Pt() > 10 && 
     	  ((TLorentzVector*)(*eventLeptons.p4)[idLep[1]])->Pt() > 10) nPassCuts[3]++;
        if(idLep.size() == 2 &&
     	  ((TLorentzVector*)(*eventLeptons.p4)[idLep[0]])->Pt() > 10 && 
     	  ((TLorentzVector*)(*eventLeptons.p4)[idLep[1]])->Pt() > 10 &&
          (int)(*eventLeptons.pdgId)[idLep[0]]*(int)(*eventLeptons.pdgId)[idLep[1]] < 0 &&
	  TMath::Abs((int)(*eventLeptons.pdgId)[idLep[0]]) == TMath::Abs((int)(*eventLeptons.pdgId)[idLep[1]]) &&
	  TMath::Abs((int)(*eventLeptons.pdgId)[idLep[0]]) == typeSel &&
	 (infilecatv[ifile] == 0 || isGenLep.size() == 2)) {
          nPassCuts[4]++;
          dilep = ( ( *(TLorentzVector*)(eventLeptons.p4->At(idLep[0])) ) + ( *(TLorentzVector*)(eventLeptons.p4->At(idLep[1])) ) ); 
          if(TMath::Abs(dilep.M()-91.1876)<15.0) passSel = kTRUE;	
	}
      }
      else if(nsel == 1){ // fake
        if(idLep.size() == 1) nPassCuts[2]++;
	if(idLep.size() == 1 &&
     	  ((TLorentzVector*)(*eventLeptons.p4)[idLep[0]])->Pt() > 10) nPassCuts[3]++;
        if(idLep.size() == 1 &&
     	  ((TLorentzVector*)(*eventLeptons.p4)[idLep[0]])->Pt() > 10 &&
	  ((typeSel == 11 && idJet30.size() >= 1) ||(typeSel == 13 && idJet20.size() >= 1)) &&
	  TMath::Abs((int)(*eventLeptons.pdgId)[idLep[0]]) == typeSel &&
	 (infilecatv[ifile] == 0 || isGenLep.size() == 1)) {
          dilep = ( *(TLorentzVector*)(eventLeptons.p4->At(idLep[0])) );
          nPassCuts[4]++;
          deltaPhiDileptonMet = TMath::Abs(dilep.DeltaPhi(*((TLorentzVector*)(*eventMet.p4)[0])));
          mtW = TMath::Sqrt(2.0*dilep.Pt()*((TLorentzVector*)(*eventMet.p4)[0])->Pt()*(1.0 - cos(deltaPhiDileptonMet)));
	  if(mtW < 20) passSel = kTRUE;
	}
      }
      else if(nsel == 2){ // W->ln
        if(idLep.size() == 1 && idTight[0] == 1) nPassCuts[2]++;
	if(idLep.size() == 1 && idTight[0] == 1 &&
     	  ((TLorentzVector*)(*eventLeptons.p4)[idLep[0]])->Pt() > 10) nPassCuts[3]++;
        if(idLep.size() == 1 && idTight[0] == 1 &&
     	  ((TLorentzVector*)(*eventLeptons.p4)[idLep[0]])->Pt() > 10 &&
	  TMath::Abs((int)(*eventLeptons.pdgId)[idLep[0]]) == typeSel &&
	 (infilecatv[ifile] == 0 || isGenLep.size() == 1)) {
          dilep = ( *(TLorentzVector*)(eventLeptons.p4->At(idLep[0])) );
          nPassCuts[4]++;
          deltaPhiDileptonMet = TMath::Abs(dilep.DeltaPhi(*((TLorentzVector*)(*eventMet.p4)[0])));
          mtW = TMath::Sqrt(2.0*dilep.Pt()*((TLorentzVector*)(*eventMet.p4)[0])->Pt()*(1.0 - cos(deltaPhiDileptonMet)));
	  if(mtW > 50) passSel = kTRUE;
	}
      }

      if(passSel == kTRUE) nPassCuts[5]++;
      if(passSel == kFALSE) continue;

      if(mtW < 0){
        deltaPhiDileptonMet = TMath::Abs(dilep.DeltaPhi(*((TLorentzVector*)(*eventMet.p4)[0])));
        mtW = TMath::Sqrt(2.0*dilep.Pt()*((TLorentzVector*)(*eventMet.p4)[0])->Pt()*(1.0 - cos(deltaPhiDileptonMet)));
      }

      double mcWeight = eventMonteCarlo.mcWeight;
      if(infilecatv[ifile] == 0) mcWeight = 1.0;
      double theLumi = lumi; if(infilecatv[ifile] == 0) theLumi = 1.0;
      double puWeight = nPUScaleFactor(fhDPU, (double)eventVertex.npv); if(infilecatv[ifile] == 0) puWeight = 1.0;
      double effSF = 1.0;
      if(infilecatv[ifile] != 0){
        for(unsigned int nl=0; nl<idLep.size(); nl++){
          effSF = effSF * effScaleFactor(((TLorentzVector*)(*eventLeptons.p4)[idLep[nl]])->Pt(),TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[idLep[nl]])->Eta()),TMath::Abs((int)(*eventLeptons.pdgId)[idLep[nl]]),period,typeLepSel);
        }
      }
      
      int iPt = -1;
      if     (((TLorentzVector*)(*eventLeptons.p4)[idLep[0]])->Pt() < 15){
        iPt = 0;
      }
      else if(((TLorentzVector*)(*eventLeptons.p4)[idLep[0]])->Pt() < 20){
        iPt = 1;
      }
      else if(((TLorentzVector*)(*eventLeptons.p4)[idLep[0]])->Pt() < 25){
        iPt = 2;
      }
      else if(((TLorentzVector*)(*eventLeptons.p4)[idLep[0]])->Pt() < 30){
        iPt = 3;
      }
      else {
        iPt = 4;
      }
      int iEta = -1;
      if     (TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[idLep[0]])->Eta()) < 0.5){
         iEta = 0;
      }
      else if(TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[idLep[0]])->Eta()) < 1.0){
         iEta = 1;
      }
      else if(TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[idLep[0]])->Eta()) < 1.5){
         iEta = 2;
      }
      else if(TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[idLep[0]])->Eta()) < 2.0){
         iEta = 3;
      }
      else {
         iEta = 4;
      }
      if(nsel == 0) iEta = 0;

      double thePrescale = 1.0;
      if(infilecatv[ifile] != 0 && applyPrescale == 1) thePrescale = prescale[iPt];

      double totalWeight = mcWeight*theLumi*puWeight*effSF*thePrescale*theMCPrescale;

      if(infilecatv[ifile] == 0) {
                            denFRDA[iPt][iEta] = denFRDA[iPt][iEta] + totalWeight;
        if(idTight[0] == 1) numFRDA[iPt][iEta] = numFRDA[iPt][iEta] + totalWeight;
      }
      else {
                            denFRBG[iPt][iEta] = denFRBG[iPt][iEta] + totalWeight;
        if(idTight[0] == 1) numFRBG[iPt][iEta] = numFRBG[iPt][iEta] + totalWeight;
      }

      for(int thePlot=0; thePlot<allPlots; thePlot++){
        double theVar = 0.0;
        if     (thePlot ==  0) theVar = TMath::Min(dilep.M(),199.999);
        else if(thePlot ==  1) theVar = TMath::Min((double)((TLorentzVector*)(*eventMet.p4)[0])->Pt(),199.999);
        else if(thePlot ==  2) theVar = TMath::Min((double)eventMet.metNoMu->Pt(),199.999);
        else if(thePlot ==  3) theVar = TMath::Min((double)((TLorentzVector*)(*eventMet.p4)[0])->Pt(),199.999);
        else if(thePlot ==  4) theVar = TMath::Min(dilep.Pt(),199.999);
        else if(thePlot ==  5) theVar = TMath::Min(mtW,199.999);
        else if(thePlot ==  6) theVar = TMath::Min((double)0.0,6.499);
        else if(thePlot ==  7) theVar = TMath::Min((double)eventEvent.rho,39.999);
        else if(thePlot ==  8) theVar = TMath::Min((double)eventVertex.npv,39.499);
        else if(thePlot ==  9) theVar = TMath::Min(((TLorentzVector*)(*eventLeptons.p4)[idLep[0]])->Pt(),49.999);
        else if(thePlot == 10) theVar = TMath::Min(TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[idLep[0]])->Eta()),2.499);
        histo[thePlot][infilecatv[ifile]]->Fill(theVar,totalWeight);
      }

    }

    printf("eff_cuts: ");
    for(int nc=0; nc<6; nc++){
      double nminusone = the_input_tree->GetEntries();
      if(nc>0) nminusone = nPassCuts[nc-1];
      printf("(%d): %8.5f(%8.5f) | ",nc,100*(double)nPassCuts[nc]/the_input_tree->GetEntries(),100*(double)nPassCuts[nc]/nminusone);
    }
    printf("\n");
  } // end of chain

  for(int nc=0; nc<8; nc++){
    printf("(%d): %5.2f | ",nc,histo[0][nc]->GetSumOfWeights());
  }
  double sumTot[2] = {0.,0.};
  printf("totalMC: %5.2f\n",histo[0][1]->GetSumOfWeights()+histo[0][2]->GetSumOfWeights()+histo[0][3]->GetSumOfWeights()+
                            histo[0][4]->GetSumOfWeights()+histo[0][5]->GetSumOfWeights()+histo[0][6]->GetSumOfWeights()+histo[0][7]->GetSumOfWeights());
  for(int iEta=0; iEta<5; iEta++){
    for(int iPt=0; iPt<5; iPt++){
      sumTot[0] = sumTot[0] + denFRDA[iPt][iEta];
      sumTot[1] = sumTot[1] + denFRBG[iPt][iEta];
      printf("(%d,%d): (%6.1f-%6.1f)/(%6.1f-%6.1f)=%4.3f | ",iPt,iEta,numFRDA[iPt][iEta],numFRBG[iPt][iEta] , denFRDA[iPt][iEta],denFRBG[iPt][iEta],
                                                                     (numFRDA[iPt][iEta]-numFRBG[iPt][iEta])/(denFRDA[iPt][iEta]-denFRBG[iPt][iEta]));
      if(iPt==4) printf("\n");
    }
  }
  printf("sumTot(da/bg) = %f / %f = %f\n",sumTot[0],sumTot[1],sumTot[0]/sumTot[1]);
  if(nsel == 0){
    for(int iEta=0; iEta<5; iEta++){
      for(int iPt=0; iPt<5; iPt++){
        printf("(%d,%d): (%6.1f)/(%6.1f)=%7.5f | ",iPt,iEta,denFRDA[iPt][iEta],denFRBG[iPt][iEta],denFRDA[iPt][iEta]/denFRBG[iPt][iEta]);
        if(iPt==4) printf("\n");
      }
    }
  }
  else {
    for(int iEta=0; iEta<5; iEta++){
      for(int iPt=0; iPt<5; iPt++){
        printf("(%d,%d): (%6.1f)/(%6.1f)=%4.3f | ",iPt,iEta,numFRDA[iPt][iEta] , denFRDA[iPt][iEta],
                                                           (numFRDA[iPt][iEta])/(denFRDA[iPt][iEta]));
        if(iPt==4) printf("\n");
      }
    }
  }

  if(typeSel == 11) printf("double fake_rate_e[%d][%d] = {\n",5,5);
  else              printf("double fake_rate_m[%d][%d] = {\n",5,5);
  for(int iEta=0; iEta<5; iEta++){
    for(int iPt=0; iPt<5; iPt++){
      printf("%4.3f",TMath::Abs((numFRDA[iPt][iEta]-numFRBG[iPt][iEta])/(denFRDA[iPt][iEta]-denFRBG[iPt][iEta])));
      if(iPt!=4||iEta!=4) printf(",");
      if(iPt==4) printf("\n");
    }
  }
  printf("};\n");
  
  for(int thePlot=0; thePlot<allPlots; thePlot++){
    char output[200];
    sprintf(output,"histo_fake_%d_%d_%d.root",thePlot,nsel,typeSel);	  
    TFile* outFilePlotsNote = new TFile(output,"recreate");
    outFilePlotsNote->cd();
    for(int np=0; np<histBins; np++) histo[thePlot][np]->Write();
    outFilePlotsNote->Close();
  }

}
예제 #19
0
void getGlu(const char * mode = "pp2")
{
  TH1::SetDefaultSumw2();

  int nbinsFine = 28;
  TH1D * recoGlu = new TH1D("recoGlu","",nbinsFine,60,200);
  TH1D * recoTot = new TH1D("recoTot","",nbinsFine,60,200);
  TH1D * genGlu = new TH1D("genGlu","",nbinsFine,60,200);
  TH1D * genTot = new TH1D("genTot","",nbinsFine,60,200);
 
//setting up files 
  std::vector<std::string> fileList;
  if(strcmp("pp2",mode)==0) fileList = readInputFileList("pp2MCFiles.txt");
  if(strcmp("pPb5",mode)==0) fileList = readInputFileList("pPbMCFiles.txt");
  if(strcmp("pp7",mode)==0) fileList = readInputFileList("pp7MCFiles.txt");
  int nFiles = fileList.size();

  //pp7 MC reweighting
  int totalEntriesForWeighting[7] = {0};
  if(strcmp(mode, "pp7")==0)
  {
    for(int f=0; f<nFiles; f++)
    { 
      if(f%100 == 0) std::cout << "tabulating entries; file " << f << "/" << nFiles <<std::endl;
      int isGoodFile = openInFileFast(fileList[f].data(),mode,1);
      if( isGoodFile == 0)
      { 
        closeInFileFast(0);
        continue;
      }

      for(int i = 0; i<7; i++)
      {
        if(fileList[f].find(Form("%dto%d",(int)pp7PthatBounds[i],(int)pp7PthatBounds[i+1])) != std::string::npos) totalEntriesForWeighting[i] += trackIn->GetEntries();
      }
      closeInFileFast();
    }
    for(int i = 0 ; i<7; i++) std::cout << pp7PthatBounds[i] << " has " << totalEntriesForWeighting[i] << " entries." <<std::endl;
  }

//start of skim here 
  //looping over forests to skim out of
  //change f= at 2 spots to change starting point, as well as skim outFileNum
  for(int f = 0; f<nFiles; f++)
  {   
    int isGoodFile = openInFile(fileList[f].data(),mode,1);
    if( isGoodFile == 0)
    {
      closeInFile(0);
      continue;
    }

    int nEntries = ak3PFIn->GetEntries();
    //nEntries = 50;
    for(int i = 0; i<nEntries; i++)
    {
      if(i%10000==0) std::cout <<"file: " << f << " event: " << i << "/" << nEntries << std::endl;
      skimIn->GetEntry(i);
      if(pPAcollisionEventSelectionPA == 0 && pcollisionEventSelection == 0) continue; 
   
      ak3PFIn->GetEntry(i);
      float boost = 0;
      if(strcmp("pp2",mode)==0)
      {
        if(pthat > pp2PthatBounds[f+2]) continue;
        weight = crossSection2[f]/(float)nEntries;
      }
      if(strcmp("pPb5",mode)==0 || strcmp("Pbp5",mode)==0)
      {
        boost = pPbRapidity;
        if(pthat > pPb5PthatBounds[f+2]) continue; 
        weight = crossSection5[f]/(float)nEntries;
      }
      if(strcmp("pp7",mode)==0)
      {
        for(int k = 0; k<7; k++)
        {
          if(fileList[f].find(Form("%dto%d",(int)pp7PthatBounds[k],(int)pp7PthatBounds[k+1])) != std::string::npos) weight = crossSection7[k]/(float)totalEntriesForWeighting[k];
        }    
      }
       
      for(int j =0; j < nref; j++)
      {  
        if(TMath::Abs(jteta[j]+boost)>1.5) continue;
        if(TMath::Abs(refparton_flavor[j]) < 901)
        {
          recoTot->Fill(jtpt[j],weight);
          if(refparton_flavor[j] == 21) recoGlu->Fill(jtpt[j],weight);
          genTot->Fill(refpt[j],weight);
          if(refparton_flavor[j] == 21) genGlu->Fill(refpt[j],weight);
        }
      } 
    }
    //cleanup so we can open another
    closeInFile();  
  }
  recoGlu->Divide(recoTot);
  genGlu->Divide(genTot);
  recoGlu->SetDirectory(0);
  genGlu->SetDirectory(0);
  TFile * outputFile = new TFile("gluonFracs.root","update");
  recoGlu->SetName(Form("%s_gFrac_recoMC",mode));
  genGlu->SetName(Form("%s_gFrac_genMC",mode));
  recoGlu->Write();
  genGlu->Write();
  outputFile->Close();
  delete recoGlu;
  delete genGlu;
  delete recoTot;
  delete genTot; 
}
예제 #20
0
void residualAlignment(TH2D* residualX, TH2D* residualY, double& offsetX,
                       double& offsetY, double& rotation,
                       double relaxation, bool display)
{
  assert(residualX && residualY && "Processors: can't perform residual alignment without histograms");

  rotation = 0;
  offsetX = 0;
  offsetY = 0;
  double angleWeights = 0;
  double fitChi2 = 0;

  for (int axis = 0; axis < 2; axis++)
  {
    TH2D* hist = 0;
    if (axis) hist = residualX;
    else      hist = residualY;

    // Project the histogram and fit with a gaussian to center the sensor
    TH1D* project = hist->ProjectionX("ResidualProjetion", 1, hist->GetNbinsY());
    project->SetDirectory(0);

    double sigma = project->GetBinWidth(1);
    double mean = 0;
    fitGaussian(project, mean, sigma, false);

    if (axis) offsetX = mean;
    else      offsetY = mean;

    delete project;

    std::vector<double> ptsX;
    std::vector<double> ptsY;
    std::vector<double> ptsErr;

    const unsigned int numSlices = hist->GetNbinsY();

    for (Int_t row = 1; row <= (int)numSlices; row++)
    {
      TH1D* slice = hist->ProjectionX("ResidualSlice", row, row);
      slice->SetDirectory(0);

      double mean = 0;
      double sigma = 0;
      double factor = 0;
      double background = 0;

      if (slice->Integral() < 1) { delete slice; continue; }
      fitGaussian(slice, mean, sigma, factor, background, false);

      const double sliceMin = slice->GetBinCenter(1);
      const double sliceMax = slice->GetBinCenter(slice->GetNbinsX());
      delete slice;

      // Quality assurance

      // Sigma is contained in the slice's range
      if (sigma > (sliceMax - sliceMin)) continue;
      // Mean is contained in the slice's range
      if (mean > sliceMax || mean < sliceMin) continue;
      // Peak is contains sufficient events
      if (factor < 100) continue;
      // Sufficient signal to noise ratio
      if (factor / background < 10) continue;

      // Get the total number of events in the gaussian 1 sigma
      Int_t sigRangeLow = hist->FindBin(mean - sigma);
      Int_t sigRangeHigh = hist->FindBin(mean + sigma);

      double sigRangeTotal = 0;
      for (Int_t bin = sigRangeLow; bin <= sigRangeHigh; bin++)
        sigRangeTotal += hist->GetBinContent(bin);

      // 2 * 1 sigma integral shoudl give ~ area under gaussian
      sigma /= sqrt(2 * sigRangeTotal);

      ptsX.push_back(hist->GetYaxis()->GetBinCenter(row));
      ptsY.push_back(mean);
      ptsErr.push_back(sigma);
    }

    if (ptsX.size() < 3) continue;

    std::vector<double> yvals = ptsY;
    std::sort(yvals.begin(), yvals.end());
    const double median = yvals[yvals.size()/2];
    double avgDeviation = 0;
    for (unsigned int i = 0; i < yvals.size(); i++)
      avgDeviation += fabs(yvals[i] - median);
    avgDeviation /= (double)yvals.size();

    std::vector<double> ptsXGood;
    std::vector<double> ptsYGood;
    std::vector<double> ptsErrGood;

    for (unsigned int i = 0; i < ptsX.size(); i++)
    {
      if (fabs(ptsY[i] - median) > 1.5*avgDeviation) continue;
      ptsXGood.push_back(ptsX[i]);
      ptsYGood.push_back(ptsY[i]);
      ptsErrGood.push_back(ptsErr[i]);
    }

    if (ptsXGood.size() < 3) continue;

    TGraphErrors* graph = new TGraphErrors(ptsXGood.size(),
                                           &(ptsXGood.at(0)),
                                           &(ptsYGood.at(0)), 0,
                                           &(ptsErrGood.at(0)));

    TF1* fitFunc = new TF1("f1", "1 ++ x");
    TF1* result = 0;

    graph->Fit(fitFunc, "Q0E").Get();
    result = graph->GetFunction(fitFunc->GetName());

    // Weight the angle by the slope uncertainty and the inverse of the chi2 normalized
    double weight = result->GetParError(1);
    const double chi2 = result->GetChisquare() / (double)result->GetNDF();
    fitChi2 += chi2;
    weight *= chi2;
    if (weight > 10 * DBL_MIN) weight = 1.0 / weight;
    else weight = 1.0;

    if (axis)
    {
      rotation -= weight * atan(result->GetParameter(1));
      offsetX = result->GetParameter(0);
    }
    else
    {
      rotation += weight * atan(result->GetParameter(1));
      offsetY = result->GetParameter(0);
    }

    angleWeights += weight;

    if (display)
    {
      TCanvas* can = new TCanvas("ResidualAlignment", "Residual Alignment", 900, 600);
      can->Divide(2);
      can->cd(1);
      hist->Draw("COLZ");
      can->cd(2);
      result->SetLineColor(46);
      result->SetLineWidth(2);
      graph->Draw("ap");
      result->Draw("SAME");
      can->Update();
      can->WaitPrimitive();
    }

    delete fitFunc;
    delete graph;
  }

  if (angleWeights > 10 * DBL_MIN)
    rotation /= angleWeights;
  std::cout << "relaxation: " << relaxation << std::endl;
  rotation *= relaxation;
  offsetX *= relaxation;
  offsetY *= relaxation;
}
void Channel::GetShapes(TString SelectionName, TString xtitle, const int nbins, const double *bins){ 
	MT2Shapes *tA;
	if(fWriteToFile) tA = new MT2Shapes(fOutDir, fRootFile, fLogStream);
	else             tA = new MT2Shapes(fOutDir, fRootFile);
	tA->setVerbose(fVerbose);
	tA->init(fSamples);
	tA->SetPrintSummary(true);
	tA->SetDraw(false);
	tA->SetWrite(false);
  
//                    variable,      cuts,  njet, nlep,  selection_name,      HLT,   xtitle   nbins  bins   
        tA->GetShapes(fVariable,  fCuts,    -1,  -10  , SelectionName,    fTrigger , xtitle , nbins, bins);

	// retrieve shapes
	for(int i=0; i<tA->GetNShapes(); ++i){
		TString name =tA->fh_shapes[i]->GetName();
		if      (name.Contains("QCD_"))        {hQCD         = (TH1D*) tA->fh_shapes[i]->Clone(tA->fh_shapes[i]->GetName()); hQCD->SetDirectory(fDir);}
		else if (name.Contains("PhotonsJets_")){hPhotons     = (TH1D*) tA->fh_shapes[i]->Clone(tA->fh_shapes[i]->GetName()); hPhotons->SetDirectory(fDir);}
		else if (name.Contains("Data_"))       {hData        = (TH1D*) tA->fh_shapes[i]->Clone(tA->fh_shapes[i]->GetName()); hData->SetDirectory(fDir);}
		else if (name.Contains("WJets_"))      {hWJets       = (TH1D*) tA->fh_shapes[i]->Clone(tA->fh_shapes[i]->GetName()); hWJets->SetDirectory(fDir);}
		else if (name.Contains("ZJetsToLL_"))  {hZJetsToLL   = (TH1D*) tA->fh_shapes[i]->Clone(tA->fh_shapes[i]->GetName()); hZJetsToLL->SetDirectory(fDir);}
		else if (name.Contains("ZJetsToNuNu_")){hZJetsToNuNu = (TH1D*) tA->fh_shapes[i]->Clone(tA->fh_shapes[i]->GetName()); hZJetsToNuNu->SetDirectory(fDir);}
		else if (name.Contains("Top_"))        {hTop         = (TH1D*) tA->fh_shapes[i]->Clone(tA->fh_shapes[i]->GetName()); hTop->SetDirectory(fDir);}
		else if (name.Contains("Signal_"))     {hSignal      = (TH1D*) tA->fh_shapes[i]->Clone(tA->fh_shapes[i]->GetName()); hSignal->SetDirectory(fDir);}
		else if (name.Contains("Other_"))      {hOther       = (TH1D*) tA->fh_shapes[i]->Clone(tA->fh_shapes[i]->GetName()); hOther->SetDirectory(fDir);}
	}
	delete tA;
	fGotShapes=true;

	fDir->cd();

	// fix colors
	if(hQCD!=0)        {hQCD    ->SetLineColor(kYellow+1);    hQCD    ->SetFillColor(kYellow+1);      hQCD    ->SetFillStyle(3001);}
	if(hPhotons!=0)    {hPhotons->SetLineColor(kViolet-3);    hPhotons->SetFillColor(kViolet-3);      hPhotons->SetFillStyle(3001);}
	if(hOther!=0)      {hOther  ->SetLineColor(kCyan+2);      hOther  ->SetFillColor(kCyan+2);        hOther  ->SetFillStyle(3001);}
	if(hZJetsToNuNu!=0){hZJetsToNuNu->SetLineColor(kGreen+1); hZJetsToNuNu->SetFillColor(kGreen+1);   hZJetsToNuNu  ->SetFillStyle(3001);}
	if(hSignal!=0)     {hSignal ->SetLineColor(kBlack);       hSignal  ->SetFillColor(kBlack);        hSignal  ->SetFillStyle(3001);}
	if(hZJetsToLL!=0)  {hZJetsToLL->SetLineColor(kOrange);    hZJetsToLL->SetFillColor(kOrange);      hZJetsToLL->SetFillStyle(3001);}
	if(hTop!=0)        {hTop    ->SetLineColor(600);          hTop     ->SetFillColor(600);           hTop->SetFillStyle(3001);}

	if(fSaveResults){
		if(hQCD!=0)         {hQCD->Write();}
		if(hPhotons!=0)     {hPhotons->Write();}
		if(hOther!=0)       {hOther->Write();}
		if(hData!=0)        {hData->Write();}
		if(hTop!=0)         {hTop->Write();}
		if(hZJetsToLL!=0)   {hZJetsToLL->Write();}
		if(hZJetsToNuNu!=0) {hZJetsToNuNu->Write();}
		if(hSignal!=0)      {hSignal->Write();}
	}
	if(fDraw){
		if(hQCD!=0)        DrawHisto(hQCD,           hQCD->GetName(),            "hist", this);
		if(hPhotons!=0)    DrawHisto(hPhotons,       hPhotons->GetName(),        "hist", this);
		if(hOther!=0)      DrawHisto(hOther,         hOther->GetName(),          "hist", this);
		if(hData!=0)       DrawHisto(hData,          hData->GetName(),           "EXO",  this);
		if(hTop!=0)        DrawHisto(hTop,           hTop ->GetName(),           "hist", this);
		if(hZJetsToNuNu!=0)DrawHisto(hZJetsToNuNu,   hZJetsToNuNu->GetName(),    "hist", this);
		if(hSignal!=0)     DrawHisto(hSignal,        hSignal->GetName(),         "hist", this);
		if(hZJetsToLL!=0)  DrawHisto(hZJetsToLL,     hZJetsToLL->GetName(),      "hist", this);
	}
}
예제 #22
0
void AxEffSyst(TString modOCDBOutputPath, TString stdOCDBOutputPath){

  gStyle->SetOptStat(0);

  TFile *axEffModOCDBFile = new TFile(modOCDBOutputPath.Data(),"READONLY");
  TFile *axEffStdOCDBFile = new TFile(stdOCDBOutputPath.Data(),"READONLY");

  TH1D *axEffModOCDBHisto = 0x0;
  axEffModOCDBFile->GetObject("ratio1", axEffModOCDBHisto);
  axEffModOCDBHisto->SetLineColor(kBlue);
  axEffModOCDBHisto->SetLineWidth(2);
  axEffModOCDBHisto->SetTitle("A#times#epsilon");
  axEffModOCDBHisto->GetXaxis()->SetTitle("Rapidity");
  axEffModOCDBHisto->GetYaxis()->SetTitle("A#times#epsilon");

  TH1D *axEffStdOCDBHisto = 0x0;
  axEffStdOCDBFile->GetObject("ratio1", axEffStdOCDBHisto);
  axEffStdOCDBHisto->SetLineColor(kRed);
  axEffStdOCDBHisto->SetTitle("A#times#epsilon Std OCDB");
  axEffStdOCDBHisto->GetXaxis()->SetTitle("Rapidity");
  axEffStdOCDBHisto->GetYaxis()->SetTitle("A#times#epsilon");

  axEffModOCDBHisto->Sumw2(kTRUE);
  axEffStdOCDBHisto->Sumw2(kTRUE);

  TH1D *ratio = (TH1D*)axEffStdOCDBHisto->Clone();
  ratio->Sumw2(kTRUE);
  ratio->SetLineWidth(1);
  ratio->Add(axEffModOCDBHisto, -1.);
  ratio->Divide(axEffStdOCDBHisto);
  ratio->SetLineColor(kBlack);
  ratio->SetTitle("#frac{A#times#epsilon_{Std OCDB}-A#times#epsilon_{Mod OCDB}}{A#times#epsilon_{Std OCDB}}");
  ratio->GetXaxis()->SetTitle("Rapidity");
  ratio->GetYaxis()->SetTitle("Ratio (%)");

  for (Int_t iBinsRatio = 0; iBinsRatio <= ratio->GetNbinsX()+1; iBinsRatio++) {
    Double_t binContent = ratio->GetBinContent(iBinsRatio);
    cout<<binContent<<"->";
    if ( binContent<0. ) ratio->SetBinContent(iBinsRatio, -binContent*100.);
    else ratio->SetBinContent(iBinsRatio, binContent*100.);
    binContent = ratio->GetBinContent(iBinsRatio);
    cout<<binContent<<endl;
  }

  TCanvas *canv = new TCanvas("canv");
  canv->Divide(2,1);

  canv->cd(1);
  axEffModOCDBHisto->SetDirectory(0);
  axEffModOCDBHisto->Draw("E");
  axEffStdOCDBHisto->SetDirectory(0);
  axEffStdOCDBHisto->Draw("SAME E");

  canv->cd(2);
  ratio->GetYaxis()->SetRangeUser(-0.5,ratio->GetMaximum()*2);
  ratio->SetDirectory(0);
  ratio->Draw("E");

  axEffModOCDBFile->Close();
  axEffStdOCDBFile->Close();
}
void NormalizeVGammaSample(TString  InputFilename0 = "/data/smurf/data/Run2012_Summer12_SmurfV9_53X/mitf-alljets/wgamma.root",
                           TString  InputFilename1 = "/data/smurf/data/Run2012_Summer12_SmurfV9_53X/mitf-alljets/wgammafo.root",
			   bool applyCorrection = true
  ) {

  Double_t eventCount0 = 0;

  TH1D *hDRatioPhotonElectron = new TH1D("hDRatioPhotonElectron","hDRatioPhotonElectron",10,0.0,2.5); hDRatioPhotonElectron->Sumw2();

  TH1D *hDLepSel[10];
  hDLepSel[0] = new TH1D("hDLepSel_0","hDLepSel_0",20,0.0,100.0);
  hDLepSel[1] = new TH1D("hDLepSel_1","hDLepSel_1",20,0.0,100.0);
  hDLepSel[2] = new TH1D("hDLepSel_2","hDLepSel_2",10,0.0,2.5);
  hDLepSel[3] = new TH1D("hDLepSel_3","hDLepSel_3",10,0.0,2.5);
  hDLepSel[4] = new TH1D("hDLepSel_4","hDLepSel_4",20,0.0,100.0);
  hDLepSel[5] = new TH1D("hDLepSel_5","hDLepSel_5",20,0.0,100.0);
  hDLepSel[6] = new TH1D("hDLepSel_6","hDLepSel_6",10,0.0,2.5);
  hDLepSel[7] = new TH1D("hDLepSel_7","hDLepSel_7",10,0.0,2.5);
  for(int i=0; i<8; i++) hDLepSel[i]->Sumw2();

  TH1D *hDpSel[20];
  hDpSel[0]  = new TH1D("hDpSel_0" ,"hDpSel_0" ,20,0.0,100.0);
  hDpSel[1]  = new TH1D("hDpSel_1" ,"hDpSel_1" ,20,0.0,100.0);
  hDpSel[2]  = new TH1D("hDpSel_2" ,"hDpSel_2" ,10,0.0,2.5);
  hDpSel[3]  = new TH1D("hDpSel_3" ,"hDpSel_3" ,10,0.0,2.5);
  hDpSel[4]  = new TH1D("hDpSel_4" ,"hDpSel_4" ,40,0.0,200.0);
  hDpSel[5]  = new TH1D("hDpSel_5" ,"hDpSel_5" ,40,0.0,200.0);
  hDpSel[6]  = new TH1D("hDpSel_6" ,"hDpSel_6" ,40,0.0,200.0);
  hDpSel[7]  = new TH1D("hDpSel_7" ,"hDpSel_7" ,36,0.0,160.0);
  hDpSel[8]  = new TH1D("hDpSel_8" ,"hDpSel_8" ,40,0.0,200.0);
  hDpSel[9]  = new TH1D("hDpSel_9" ,"hDpSel_9" ,40,0.0,200.0);
  hDpSel[10] = new TH1D("hDpSel_10","hDpSel_10",20,0.0,100.0);
  hDpSel[11] = new TH1D("hDpSel_11","hDpSel_11",20,0.0,100.0);
  hDpSel[12] = new TH1D("hDpSel_12","hDpSel_12",10,0.0,2.5);
  hDpSel[13] = new TH1D("hDpSel_13","hDpSel_13",10,0.0,2.5);
  hDpSel[14] = new TH1D("hDpSel_14","hDpSel_14",40,0.0,200.0);
  hDpSel[15] = new TH1D("hDpSel_15","hDpSel_15",40,0.0,200.0);
  hDpSel[16] = new TH1D("hDpSel_16","hDpSel_16",40,0.0,200.0);
  hDpSel[17] = new TH1D("hDpSel_17","hDpSel_17",36,0.0,160.0);
  hDpSel[18] = new TH1D("hDpSel_18","hDpSel_18",40,0.0,200.0);
  hDpSel[19] = new TH1D("hDpSel_19","hDpSel_19",40,0.0,200.0);
  for(int i=0; i<20; i++) hDpSel[i]->Sumw2();

  SmurfTree vgammaEvent;
  vgammaEvent.LoadTree(InputFilename0.Data());
  vgammaEvent.InitTree(0);
  vgammaEvent.tree_->SetName("tree");

  TFile *fRatioPhotonElectron = TFile::Open("/data/smurf/data/Run2012_Summer12_SmurfV9_53X/auxiliar/ratio_photon_electron.root");
  TH1D *fhDRatioPhotonElectron = (TH1D*)(fRatioPhotonElectron->Get("hDRatioPhotonElectron"));
  assert(fhDRatioPhotonElectron);
  fhDRatioPhotonElectron->SetDirectory(0);
  fRatioPhotonElectron->Close();
  delete fRatioPhotonElectron;

  for (int n=0;n<vgammaEvent.tree_->GetEntries();n++) { 
    vgammaEvent.tree_->GetEntry(n);

    bool lid = (vgammaEvent.cuts_ & SmurfTree::Lep1FullSelection) == SmurfTree::Lep1FullSelection 
           &&  (vgammaEvent.cuts_ & SmurfTree::Lep2FullSelection) == SmurfTree::Lep2FullSelection;
    if (!lid) continue;

    if( vgammaEvent.lep1_.pt() <= 20	    	     ) continue; // cut on leading lepton pt
    if( vgammaEvent.lep2_.pt() <= 10	    	     ) continue; // cut on trailing lepton pt
    if( vgammaEvent.dilep_.M() <= 12                 ) continue; // cut on minimum dilepton mass

    Double_t add = vgammaEvent.sfWeightPU_*vgammaEvent.sfWeightEff_*vgammaEvent.sfWeightTrig_;
    Double_t myWeight = vgammaEvent.scale1fb_*add;    

    if(!(TMath::Abs(vgammaEvent.lep1McId_) == 11 || TMath::Abs(vgammaEvent.lep1McId_) == 13)) hDLepSel[0]->Fill(TMath::Min(vgammaEvent.lep1_.pt(),99.999),myWeight);
    if(!(TMath::Abs(vgammaEvent.lep2McId_) == 11 || TMath::Abs(vgammaEvent.lep2McId_) == 13)) hDLepSel[0]->Fill(TMath::Min(vgammaEvent.lep2_.pt(),99.999),myWeight);
    if(!(TMath::Abs(vgammaEvent.lep1McId_) == 11 || TMath::Abs(vgammaEvent.lep1McId_) == 13)) hDLepSel[2]->Fill(TMath::Min(TMath::Abs(vgammaEvent.lep1_.eta()),2.499),myWeight);
    if(!(TMath::Abs(vgammaEvent.lep2McId_) == 11 || TMath::Abs(vgammaEvent.lep2McId_) == 13)) hDLepSel[2]->Fill(TMath::Min(TMath::Abs(vgammaEvent.lep2_.eta()),2.499),myWeight);
    if((TMath::Abs(vgammaEvent.lep1McId_) == 11 || TMath::Abs(vgammaEvent.lep1McId_) == 13)) hDLepSel[4]->Fill(TMath::Min(vgammaEvent.lep1_.pt(),99.999),myWeight);
    if((TMath::Abs(vgammaEvent.lep2McId_) == 11 || TMath::Abs(vgammaEvent.lep2McId_) == 13)) hDLepSel[4]->Fill(TMath::Min(vgammaEvent.lep2_.pt(),99.999),myWeight);
    if((TMath::Abs(vgammaEvent.lep1McId_) == 11 || TMath::Abs(vgammaEvent.lep1McId_) == 13)) hDLepSel[6]->Fill(TMath::Min(TMath::Abs(vgammaEvent.lep1_.eta()),2.499),myWeight);
    if((TMath::Abs(vgammaEvent.lep2McId_) == 11 || TMath::Abs(vgammaEvent.lep2McId_) == 13)) hDLepSel[6]->Fill(TMath::Min(TMath::Abs(vgammaEvent.lep2_.eta()),2.499),myWeight);

    eventCount0 += myWeight;

  }

  cout << "eventCount0 Event Count 1fb^-1 : " << eventCount0 << endl;
 
  Double_t eventCount1 = 0;

  SmurfTree vgammafoEvent;
  vgammafoEvent.LoadTree(InputFilename1.Data());
  vgammafoEvent.InitTree(0);
  vgammafoEvent.tree_->SetName("tree");

  for (int n=0;n<vgammafoEvent.tree_->GetEntries();n++) { 
    vgammafoEvent.tree_->GetEntry(n);

    bool lid = ((vgammafoEvent.cuts_ & SmurfTree::Lep1FullSelection) == SmurfTree::Lep1FullSelection 
            &&  (vgammafoEvent.cuts_ & SmurfTree::Lep2LooseEleV2) == SmurfTree::Lep2LooseEleV2) ||
	       ((vgammafoEvent.cuts_ & SmurfTree::Lep1LooseEleV2) == SmurfTree::Lep1LooseEleV2 
           &&   (vgammafoEvent.cuts_ & SmurfTree::Lep2FullSelection) == SmurfTree::Lep2FullSelection);
    if (!lid) continue;

    if( vgammafoEvent.lep1_.pt() <= 20	    	     ) continue; // cut on leading lepton pt
    if( vgammafoEvent.lep2_.pt() <= 10	    	     ) continue; // cut on trailing lepton pt
    if( TMath::Abs(vgammafoEvent.lep1_.eta()) >= 2.5 ) continue; // cut on leading lepton pt
    if( TMath::Abs(vgammafoEvent.lep2_.eta()) >= 2.5 ) continue; // cut on trailing lepton pt
    if( vgammafoEvent.dilep_.M() <= 12               ) continue; // cut on minimum dilepton mass

    Double_t add = vgammafoEvent.sfWeightPU_*vgammafoEvent.sfWeightEff_*vgammafoEvent.sfWeightTrig_;
    Double_t myWeight = vgammafoEvent.scale1fb_*add;    

    hDpSel[0]->Fill(TMath::Min(vgammafoEvent.lep1_.pt(),99.999),myWeight);
    hDpSel[1]->Fill(TMath::Min(vgammafoEvent.lep2_.pt(),99.999),myWeight);
    hDpSel[2]->Fill(TMath::Min(TMath::Abs(vgammafoEvent.lep1_.eta()),2.499),myWeight);
    hDpSel[3]->Fill(TMath::Min(TMath::Abs(vgammafoEvent.lep2_.eta()),2.499),myWeight);
    hDpSel[4]->Fill(TMath::Min((double)vgammafoEvent.mt_,199.999),myWeight);
    hDpSel[5]->Fill(TMath::Min((double)vgammafoEvent.dilep_.M(),199.999),myWeight);
    hDpSel[6]->Fill(TMath::Min((double)vgammafoEvent.met_,199.999),myWeight);
    hDpSel[7]->Fill(TMath::Min((double)vgammafoEvent.dPhi_*180/TMath::Pi(),179.999),myWeight);
    hDpSel[8]->Fill(TMath::Min((double)vgammafoEvent.mt1_,199.999),myWeight);
    hDpSel[9]->Fill(TMath::Min((double)vgammafoEvent.mt2_,199.999),myWeight);
    if(!(TMath::Abs(vgammafoEvent.lep1McId_) == 11 || TMath::Abs(vgammafoEvent.lep1McId_) == 13) && applyCorrection == true) myWeight = myWeight * ratioPhotonElectron(fhDRatioPhotonElectron,TMath::Abs(vgammafoEvent.lep1_.eta()));
    if(!(TMath::Abs(vgammafoEvent.lep2McId_) == 11 || TMath::Abs(vgammafoEvent.lep2McId_) == 13) && applyCorrection == true) myWeight = myWeight * ratioPhotonElectron(fhDRatioPhotonElectron,TMath::Abs(vgammafoEvent.lep2_.eta()));
    hDpSel[10]->Fill(TMath::Min(vgammafoEvent.lep1_.pt(),99.999),myWeight);
    hDpSel[11]->Fill(TMath::Min(vgammafoEvent.lep2_.pt(),99.999),myWeight);
    hDpSel[12]->Fill(TMath::Min(TMath::Abs(vgammafoEvent.lep1_.eta()),2.499),myWeight);
    hDpSel[13]->Fill(TMath::Min(TMath::Abs(vgammafoEvent.lep2_.eta()),2.499),myWeight);
    hDpSel[14]->Fill(TMath::Min((double)vgammafoEvent.mt_,199.999),myWeight);
    hDpSel[15]->Fill(TMath::Min((double)vgammafoEvent.dilep_.M(),199.999),myWeight);
    hDpSel[16]->Fill(TMath::Min((double)vgammafoEvent.met_,199.999),myWeight);
    hDpSel[17]->Fill(TMath::Min((double)vgammafoEvent.dPhi_*180/TMath::Pi(),179.999),myWeight);
    hDpSel[18]->Fill(TMath::Min((double)vgammafoEvent.mt1_,199.999),myWeight);
    hDpSel[19]->Fill(TMath::Min((double)vgammafoEvent.mt2_,199.999),myWeight);

    if(!(TMath::Abs(vgammafoEvent.lep1McId_) == 11 || TMath::Abs(vgammafoEvent.lep1McId_) == 13)) hDLepSel[1]->Fill(TMath::Min(vgammafoEvent.lep1_.pt(),99.999),myWeight);
    if(!(TMath::Abs(vgammafoEvent.lep2McId_) == 11 || TMath::Abs(vgammafoEvent.lep2McId_) == 13)) hDLepSel[1]->Fill(TMath::Min(vgammafoEvent.lep2_.pt(),99.999),myWeight);
    if(!(TMath::Abs(vgammafoEvent.lep1McId_) == 11 || TMath::Abs(vgammafoEvent.lep1McId_) == 13)) hDLepSel[3]->Fill(TMath::Min(TMath::Abs(vgammafoEvent.lep1_.eta()),2.499),myWeight);
    if(!(TMath::Abs(vgammafoEvent.lep2McId_) == 11 || TMath::Abs(vgammafoEvent.lep2McId_) == 13)) hDLepSel[3]->Fill(TMath::Min(TMath::Abs(vgammafoEvent.lep2_.eta()),2.499),myWeight);
    if((TMath::Abs(vgammafoEvent.lep1McId_) == 11 || TMath::Abs(vgammafoEvent.lep1McId_) == 13)) hDLepSel[5]->Fill(TMath::Min(vgammafoEvent.lep1_.pt(),99.999),myWeight);
    if((TMath::Abs(vgammafoEvent.lep2McId_) == 11 || TMath::Abs(vgammafoEvent.lep2McId_) == 13)) hDLepSel[5]->Fill(TMath::Min(vgammafoEvent.lep2_.pt(),99.999),myWeight);
    if((TMath::Abs(vgammafoEvent.lep1McId_) == 11 || TMath::Abs(vgammafoEvent.lep1McId_) == 13)) hDLepSel[7]->Fill(TMath::Min(TMath::Abs(vgammafoEvent.lep1_.eta()),2.499),myWeight);
    if((TMath::Abs(vgammafoEvent.lep2McId_) == 11 || TMath::Abs(vgammafoEvent.lep2McId_) == 13)) hDLepSel[7]->Fill(TMath::Min(TMath::Abs(vgammafoEvent.lep2_.eta()),2.499),myWeight);

    eventCount1 += myWeight;

  }

  cout << "eventCount1 Event Count 1fb^-1 : " << eventCount1 << endl;
 
  double NormalizationWeight = eventCount0/eventCount1;
  cout << "Normalized  Event Count 1fb^-1 : " << NormalizationWeight << endl;

  hDLepSel[0]->Divide(hDLepSel[1]);
  hDLepSel[2]->Divide(hDLepSel[3]);
  hDLepSel[4]->Divide(hDLepSel[5]);
  hDLepSel[6]->Divide(hDLepSel[7]);

  hDRatioPhotonElectron->Add(hDLepSel[2]);
  TFile *weightPE = new TFile("ratio_photon_electron.root", "RECREATE");
  weightPE->cd();
  hDRatioPhotonElectron->Write();
  weightPE->Close();

  //*************************************************************************************************
  // Create new normalized tree
  //*************************************************************************************************
  SmurfTree newEvent;
  newEvent.LoadTree(InputFilename1.Data());
  newEvent.InitTree(0);
  newEvent.tree_->SetName("tree");

  TString OutputFilename = InputFilename1;
  OutputFilename.ReplaceAll(".root","_newweight.root");
  cout << "creating new root file: " << OutputFilename << endl;
  TFile *outputFile = new TFile(OutputFilename.Data(), "RECREATE");
  outputFile->cd();

  for(int i=0; i<8; i++) hDLepSel[i]->Write();
  for(int i=0; i<20; i++) hDpSel[i]->Scale(1./hDpSel[i]->GetSumOfWeights());
  for(int i=0; i<20; i++) hDpSel[i]->Write();

  TTree *normalizedTree = newEvent.tree_->CloneTree(0);  
  for (int n=0;n<newEvent.tree_->GetEntries();n++) { 
    newEvent.tree_->GetEntry(n);
    
    newEvent.scale1fb_ = newEvent.scale1fb_*NormalizationWeight;
    if((vgammafoEvent.cuts_ & SmurfTree::Lep1LooseEleV2) == SmurfTree::Lep1LooseEleV2) newEvent.cuts_ |= SmurfTree::Lep1FullSelection;
    if((vgammafoEvent.cuts_ & SmurfTree::Lep2LooseEleV2) == SmurfTree::Lep2LooseEleV2) newEvent.cuts_ |= SmurfTree::Lep2FullSelection;
    if((vgammafoEvent.cuts_ & SmurfTree::Lep3LooseEleV2) == SmurfTree::Lep3LooseEleV2) newEvent.cuts_ |= SmurfTree::Lep3FullSelection;
    normalizedTree->Fill(); 
  }

  normalizedTree->Write();
  outputFile->Close();

}
예제 #24
0
void plot(char* h, bool norm2data, TString prefix, TString RR) {

    TFile f1(prefix+"DATA"+RR+"CP.root", "read");
    TH1D* hdata = (TH1D*)f1.Get(h);
    hdata->SetDirectory(0);
    
    TFile f2(prefix+"DYM_CP.root", "read");
    TH1D* hsignal = (TH1D*)f2.Get(TString(h));
    hsignal->SetDirectory(0);
    
    TFile f3(prefix+"QCD_CP_dd.root", "read");
    TH1D* hqcd = (TH1D*)f3.Get("hqcd");
    hqcd->SetDirectory(0);

    TFile f3_mc(prefix+"QCD_CP.root", "read");
    TH1D* hqcd_mc = (TH1D*)f3_mc.Get(h);
    hqcd_mc->SetDirectory(0);

    //FIXME    
    cout << "See the implementation in 2D case!" << endl;
    TFile f4(prefix+"TT_CP.root", "read");
    TH1D* httbar = (TH1D*)f4.Get(h); //"httbar");
    httbar->SetDirectory(0);

    TFile f4_mc(prefix+"TT_CP.root", "read");
    TH1D* httbar_mc = (TH1D*)f4_mc.Get(h);
    httbar_mc->SetDirectory(0);

    TFile f5(prefix+"TAU_CP.root", "read");
    TH1D* hZtautau = (TH1D*)f5.Get(h);
    hZtautau->SetDirectory(0);
    
    TFile f6(prefix+"EWK_CP.root", "read");
    TH1D* hWleptonnu = (TH1D*)f6.Get(h);
    hWleptonnu->SetDirectory(0);
    
    TFile f7(prefix+"DIBOSON_CP.root", "read");
    TH1D* hDibosons = (TH1D*)f7.Get(h);
    hDibosons->SetDirectory(0);
    
    gStyle->SetOptStat(0);
    gStyle->SetPalette(1);
    gROOT->ProcessLine(".L ../tools/setTDRStyle.C");
    setTDRStyle();
    gROOT->SetStyle("tdrStyle");
    gROOT->ForceStyle(true);
    
    // signal
    hsignal->SetLineColor(kOrange);
    hsignal->SetFillColor(kOrange);
    
    // qcd
    hqcd->SetLineColor(9);
    hqcd->SetFillColor(9);

    // tt
    httbar->SetLineColor(kRed+2);
    httbar->SetFillColor(kRed+2);

    // tau
    hZtautau->SetLineColor(kGreen);
    hZtautau->SetFillColor(kGreen);

    // EWK
    hWleptonnu->SetLineColor(38);
    hWleptonnu->SetFillColor(38);

    //hupsilon->SetLineColor(51);
    //hupsilon->SetFillColor(51);

    // diboson
    hDibosons->SetLineColor(40);
    hDibosons->SetFillColor(40);

    //
    //The histograms come properly weighted with priors
    //This would normalize to number of events in data
    //

    if (norm2data) {
	    const double ttbarNorm = httbar->Integral();
	    const double WleptonnuNorm = hWleptonnu->Integral();
	    const double ZtautauNorm = hZtautau->Integral();
	    const double qcdNorm = hqcd_mc->Integral();
 	    const double dibosonNorm = hDibosons->Integral();
	    const double signalNorm = hsignal->Integral();
 	    const double fullMCintegral = ttbarNorm+WleptonnuNorm+ZtautauNorm+qcdNorm+dibosonNorm+signalNorm;

	    httbar->Scale(hdata->Integral()/fullMCintegral);
	    hWleptonnu->Scale(hdata->Integral()/fullMCintegral);
	    hZtautau->Scale(hdata->Integral()/fullMCintegral);
	    hqcd_mc->Scale(hdata->Integral()/fullMCintegral);
	    hsignal->Scale(hdata->Integral()/fullMCintegral);
	    hDibosons->Scale(hdata->Integral()/fullMCintegral);
            normalizeToPeak(httbar, hWleptonnu, hqcd_mc, hZtautau, hsignal, hDibosons, hdata);

    } else {
           //Just do not normalize, for utility purposes, not for the analysis 
    }

    // mc
    TH1D* hmc = (TH1D*)hsignal->Clone();
    hmc->Add(hqcd_mc);
    //hmc->Add(hupsilon);
    hmc->Add(httbar);
    hmc->Add(hZtautau);
    hmc->Add(hWleptonnu);
    hmc->Add(hDibosons);

    //set up ratio check
    TH1D* hratio = (TH1D*)httbar->Clone();
    FindRatio(hratio,hdata,hmc);

    THStack* hstack = new THStack("hstack", "hstack");
    //hstack->Add(hupsilon);
    hstack->Add(hWleptonnu);
    hstack->Add(hDibosons);
    hstack->Add(httbar);
    hstack->Add(hZtautau);
    hstack->Add(hqcd_mc);
    hstack->Add(hsignal);

    std::ostringstream pprint;

    //add to stack
    TH1D* hstack4fit = (TH1D*)hsignal->Clone();
    //hstack->Add(hupsilon);
    hstack4fit->Add(hWleptonnu);
    hstack4fit->Add(hDibosons);
    hstack4fit->Add(httbar);
    hstack4fit->Add(hZtautau);
    hstack4fit->Add(hqcd_mc);

//save important histograms
    TFile* f = new TFile(prefix+"stack4fit_analyse"+TString(h)+RR+"CP.root","recreate");
    f->cd();
    //resetHisto(hstack4fit);
    hmc->SetName("hmc");
    hmc->Write();
    hstack4fit->SetName("stack4fit");
    hstack4fit->Write();
    //resetHisto(hsignal);
    hsignal->SetName("hsig_fewz");
    hsignal->SetTitle("hsig_fewz");
    hsignal->Write();
    //resetHisto(hqcd);
    hqcd->SetName("hqcd");
    hqcd->SetTitle("hqcd_dd");
    hqcd->Write();
    //resetHisto(hqcd_mc);
    hqcd_mc->SetName("hqcd_mc");
    hqcd_mc->SetTitle("hqcd_mc");
    hqcd_mc->Write();
    //resetHisto(hZtautau);
    hZtautau->SetName("hDYtautau");
    hZtautau->SetTitle("hDYtautau");
    hZtautau->Write();
    //resetHisto(hWleptonnu);
    cout << "hWleptonnu norm " << hWleptonnu->Integral() << endl;
    hWleptonnu->SetName("hWlepton");
    hWleptonnu->SetTitle("hWlepton");
    hWleptonnu->Write();
    //resetHisto(hDibosons);
    hDibosons->SetName("hdiboson");
    hDibosons->SetTitle("hdiboson");
    hDibosons->Write();
    //resetHisto(httbar);
    httbar->SetName("httbar");
    httbar->SetTitle("httbar_dd");
    httbar->Write();
    //resetHisto(httbar_mc);
    httbar_mc->SetName("httbar_mc");
    httbar_mc->SetTitle("httbar_mc");
    httbar_mc->Write();
    //resetHisto(hdata);
    hdata->SetName("hdata");
    hdata->SetTitle("hdata");
    hdata->Write();
    f->Close();
}
예제 #25
0
int main(int argc, char* argv[])
{
  TApplication theApp(srcName.Data(), &argc, argv);
//=============================================================================

  if (argc<5) return -1;
  TString sPath = argv[1]; if (sPath.IsNull()) return -1;
  TString sFile = argv[2]; if (sFile.IsNull()) return -1;
  TString sJetR = argv[3]; if (sJetR.IsNull()) return -1;
  TString sSjeR = argv[4]; if (sSjeR.IsNull()) return -1;
//=============================================================================

  sPath.ReplaceAll("#", "/");
//=============================================================================

  double dJetR = -1.;
  if (sJetR=="JetR02") dJetR = 0.2;
  if (sJetR=="JetR03") dJetR = 0.3;
  if (sJetR=="JetR04") dJetR = 0.4;
  if (sJetR=="JetR05") dJetR = 0.5;

  if (dJetR<0.) return -1;
  cout << "Jet R = " << dJetR << endl;
//=============================================================================

  double dSjeR = -1.;
  if (sSjeR=="SjeR01") dSjeR = 0.1;
  if (sSjeR=="SjeR02") dSjeR = 0.2;
  if (sSjeR=="SjeR03") dSjeR = 0.3;
  if (sSjeR=="SjeR04") dSjeR = 0.4;

  if (dSjeR<0.) return -1;
  cout << "Sub-jet R = " << dSjeR << endl;
//=============================================================================

  const double dJetsPtMin  = 0.001;
  const double dCutEtaMax  = 1.6;
  const double dJetEtaMax  = 1.;
  const double dJetAreaRef = TMath::Pi() * dJetR * dJetR;

  fastjet::GhostedAreaSpec areaSpc(dCutEtaMax);
  fastjet::JetDefinition   jetsDef(fastjet::antikt_algorithm, dJetR, fastjet::BIpt_scheme, fastjet::Best);
  fastjet::AreaDefinition  areaDef(fastjet::active_area_explicit_ghosts,areaSpc);

  fastjet::Selector selectJet = fastjet::SelectorAbsEtaMax(dJetEtaMax);
  fastjet::JetDefinition subjDef(fastjet::kt_algorithm, dSjeR, fastjet::BIpt_scheme, fastjet::Best);
//=============================================================================

  std::vector<fastjet::PseudoJet> fjInput;
  const Double_t dCut = TMath::TwoPi() / 3.;
//=============================================================================

  enum { kWgt, kXsc, kLje, kLjr, kLtk, kLtr, kJet, kAje, kMje, k1sz, k1sA, k1sm, k1sr, k2sz, k2sA, k2sm, k2sr, kDsm, kDsr, kVar };

  TFile *file = TFile::Open(Form("%s.root",sFile.Data()), "NEW");
  TNtuple *nt = new TNtuple("nt", "", "fWgt:fXsc:fLje:fLjr:fLtk:fLtr:fJet:fAje:fMje:f1sj:f1sA:f1sm:f1sr:f2sj:f2sA:f2sm:f2sr:fDsm:fDsr");
//=============================================================================

  HepMC::IO_GenEvent ascii_in(Form("%s/%s.hepmc",sPath.Data(),sFile.Data()), std::ios::in);
  HepMC::GenEvent *evt = ascii_in.read_next_event();

  while (evt) {
    fjInput.resize(0);

    double dLtk = -1.;
    TVector3 vPar, vLtk;
    for (HepMC::GenEvent::particle_const_iterator p=evt->particles_begin(); p!=evt->particles_end(); ++p) if ((*p)->status()==1) {
      double dEta = (*p)->momentum().eta(); if (TMath::Abs(dEta)>dCutEtaMax) continue;

      double dTrk = (*p)->momentum().perp();
      double dPhi = (*p)->momentum().phi();
      vPar.SetPtEtaPhi(dTrk, dEta, dPhi);
      fjInput.push_back(fastjet::PseudoJet(vPar.Px(), vPar.Py(), vPar.Pz(), vPar.Mag()));
      if (dTrk>dLtk) { dLtk = dTrk; vLtk.SetPtEtaPhi(dTrk, dEta, dPhi); }
    }
//=============================================================================

    fastjet::ClusterSequenceArea clustSeq(fjInput, jetsDef, areaDef);
    std::vector<fastjet::PseudoJet> includJets = clustSeq.inclusive_jets(dJetsPtMin);
    std::vector<fastjet::PseudoJet> selectJets = selectJet(includJets);
//=============================================================================

    if (selectJets.size()>0) {
      std::vector<fastjet::PseudoJet> sortedJets = fastjet::sorted_by_pt(selectJets);
      TVector3 vLje; vLje.SetPtEtaPhi(sortedJets[0].pt(), sortedJets[0].eta(), sortedJets[0].phi());

      TVector3 vJet;
      int kJrl = -1; double dJrl = -1.;
      int kTrl = -1; double dTrl = -1.;
      for (int j=0; j<sortedJets.size(); j++) {
        double dJet = sortedJets[j].pt();
        sortedJets[j].set_user_index(-1);
        vJet.SetPtEtaPhi(dJet, sortedJets[j].eta(), sortedJets[j].phi());
        if (TMath::Abs(vJet.DeltaPhi(vLje))>dCut) { sortedJets[j].set_user_index(1); if (dJet>dJrl) { dJrl = dJet; kJrl = j; } }
        if (TMath::Abs(vJet.DeltaPhi(vLtk))>dCut) { sortedJets[j].set_user_index(2); if (dJet>dTrl) { dTrl = dJet; kTrl = j; } }
      }
//=============================================================================

      TVector3 v1sj, v2sj;
      for (int j=0; j<sortedJets.size(); j++) {
        Float_t dVar[kVar]; for (Int_t i=0; i<kVar; i++) dVar[i] = -1.;
        dVar[kWgt] = 1.; dVar[kXsc] = 1.;
        vJet.SetPtEtaPhi(sortedJets[j].pt(), sortedJets[j].eta(), sortedJets[j].phi());
//=============================================================================

        dVar[kLje] = vLje.Pt(); if (sortedJets[j].user_index()==1) { dVar[kLjr] = ((kJrl==j) ? 1.5 : 0.5); }
        dVar[kLtk] = vLtk.Pt(); if (sortedJets[j].user_index()==2) { dVar[kLtr] = ((kTrl==j) ? 1.5 : 0.5); }
//=============================================================================

        dVar[kJet] = sortedJets[j].pt();
        dVar[kAje] = sortedJets[j].area();
        dVar[kMje] = sortedJets[j].m();
//=============================================================================

        fastjet::Filter trimmer(subjDef, fastjet::SelectorPtFractionMin(0.));
        fastjet::PseudoJet trimmdJet = trimmer(sortedJets[j]);
        std::vector<fastjet::PseudoJet> trimmdSj = trimmdJet.pieces();

        double d1sj = -1.; int k1sj = -1;
        double d2sj = -1.; int k2sj = -1;
        for (int i=0; i<trimmdSj.size(); i++) {
          double dIsj = trimmdSj[i].pt(); if (dIsj<0.001) continue;

          if (dIsj>d1sj) {
            d2sj = d1sj; k2sj = k1sj;
            d1sj = dIsj; k1sj = i;
          } else if (dIsj>d2sj) {
            d2sj = dIsj; k2sj = i;
          }
        }
//=============================================================================

        if (d1sj>0.) {
          v1sj.SetPtEtaPhi(d1sj, trimmdSj[k1sj].eta(), trimmdSj[k1sj].phi());
          dVar[k1sz] = d1sj;
          dVar[k1sA] = trimmdSj[k1sj].area();
          dVar[k1sm] = trimmdSj[k1sj].m();
          dVar[k1sr] = v1sj.DeltaR(vJet);
        }

        if (d2sj>0.) {
          v2sj.SetPtEtaPhi(d2sj, trimmdSj[k2sj].eta(), trimmdSj[k2sj].phi());
          dVar[k2sz] = d2sj;
          dVar[k2sA] = trimmdSj[k2sj].area();
          dVar[k2sm] = trimmdSj[k2sj].m();
          dVar[k2sr] = v2sj.DeltaR(vJet);
        }

        if ((d1sj>0.) && (d2sj>0.)) dVar[kDsr] = v2sj.DeltaR(v1sj);

        nt->Fill(dVar);
      }
    }
//=============================================================================

    delete evt;
    ascii_in >> evt;
  }
//=============================================================================

  file->cd(); nt->Write(); file->Close();
//=============================================================================

  TString sXsec = sFile; sXsec.ReplaceAll("out", "xsecs");
  file = TFile::Open(Form("%s/xsecs/%s.root",sPath.Data(),sXsec.Data()), "READ");
  TH1D *hPtHat        = (TH1D*)file->Get("hPtHat");        hPtHat->SetDirectory(0);
  TH1D *hWeightSum    = (TH1D*)file->Get("hWeightSum");    hWeightSum->SetDirectory(0);
  TProfile *hSigmaGen = (TProfile*)file->Get("hSigmaGen"); hSigmaGen->SetDirectory(0);
  file->Close();
//=============================================================================

  sFile.ReplaceAll("out", "wgt");
  file = TFile::Open(Form("%s.root",sFile.Data()), "NEW");
  hPtHat->Write();
  hWeightSum->Write();
  hSigmaGen->Write();
  file->Close();
//=============================================================================

  cout << "DONE" << endl;
//=============================================================================

  return 0;
}
예제 #26
0
void CombineCentralitiesForDirectory(TString pairType, TDirectory *dataDir)
{
  // Gather the cfs and counts to combine centrality bins


  vector<TString> centBins010 = {"05", "510"};
  vector<TString> centBins1030 = {"1015", "1520", "2025", "2530"};
  vector<TString> centBins3050 = {"3035", "3540", "4045", "4550"};
  vector<TString> finalCentBins = {"010", "1030", "3050"};
  vector<vector<TString> > centBins;
  centBins.push_back(centBins010);
  centBins.push_back(centBins1030);
  centBins.push_back(centBins3050);

  TDirectory *mergeDir = dataDir->GetDirectory("Merged");
  if(!mergeDir) {
    cout<<"Merge directory does not exist. Cannot merge."<<endl;
    return;
  }

  //For each merge group, get the necessary CFs and counts
  for(UInt_t iMerge = 0; iMerge < centBins.size(); iMerge++) {
    vector<TH1D*> cfs;
    vector<Double_t> counts;
    Double_t totalCounts = 0;
    for(UInt_t iCF = 0; iCF < centBins[iMerge].size(); iCF++) {
      TString cfName = "CF" + pairType + centBins[iMerge][iCF];
      TH1D *cf = (TH1D*)mergeDir->Get(cfName);
      if(!cf) {
	cout<<"Could not find CF named "<<cfName<<" in "<<mergeDir->GetName()<<endl;
	return;
      }
      cfs.push_back(cf);
      TString countName = "Count" + pairType + centBins[iMerge][iCF];
      TVectorD *count = (TVectorD*) mergeDir->Get(countName);
      totalCounts += count[0](0);
      counts.push_back(count[0](0));
    }

    // Finally, combine the CFs
    TH1D *combinedCF = CombineCFs(cfs, counts);
    if (!combinedCF) {
      cout << "Combine CF returned nothing. Continuing loop."
	   <<endl;
      continue;
    }
    TVectorD finalCount(1);
    finalCount[0] = totalCounts;

    // Set names
    TString combinedCFName = "CF" + pairType + finalCentBins[iMerge];
    TString combinedCountName = "Count" + pairType + finalCentBins[iMerge];
    combinedCF->SetName(combinedCFName);
    combinedCF->SetTitle(combinedCFName);

    // Set axis ranges
    combinedCF->SetAxisRange(0.9, 1.1, "Y");
    combinedCF->SetAxisRange(0., .5, "X");
    combinedCF->SetLabelSize(0.05, "X");
    combinedCF->SetLabelSize(0.05, "Y");
    combinedCF->SetTitleSize(0.05, "X");
    combinedCF->SetNdivisions(505, "X");
    combinedCF->SetNdivisions(505, "Y");
    
    cout<<"Writing combined CF "<<combinedCF->GetName()
    	<<" to "<<mergeDir->GetName()<<endl;
    combinedCF->SetDirectory(0);
    mergeDir->cd();
    combinedCF->Write(combinedCF->GetName(), TObject::kOverwrite);
    finalCount.Write(combinedCountName, TObject::kOverwrite);
  }
}
void computeDYBkgScaleFactor(Int_t period = 1, Double_t MassZCut = 15){

  TString filesPath  = "/scratch5/ceballos/ntuples_weights/met_";
  Double_t lumi = 0.0715;
  if(period == 1) lumi = 2.2;

  float dymva_= -999.;
  unsigned int nlep_= -1;
  unsigned int njets_= -1;

  //*******************************************************
  //Input Files
  //*******************************************************
  vector<TString> infilenamev;  
  vector<Int_t> infilecatv;  

  TString puPath = "";
  if      (period==0){
  puPath = "/home/ceballos/cms/cmssw/042/CMSSW_7_4_6/src/MitAnalysisRunII/data/puWeights_13TeV_50ns.root";
  infilenamev.push_back(Form("%sdata_AOD_50ns.root",filesPath.Data()));														  infilecatv.push_back(0);
  infilenamev.push_back(Form("%sDYJetsToLL_M-10to50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8+RunIISpring15DR74-Asympt50ns_MCRUN2_74_V9A-v1+AODSIM.root",filesPath.Data()));	  infilecatv.push_back(1);
  infilenamev.push_back(Form("%sDYJetsToLL_M-50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8+RunIISpring15DR74-Asympt50ns_MCRUN2_74_V9A-v2+AODSIM.root",filesPath.Data()));  	  infilecatv.push_back(1);
  infilenamev.push_back(Form("%sWZ_TuneCUETP8M1_13TeV-pythia8+RunIISpring15DR74-Asympt50ns_MCRUN2_74_V9A-v2+AODSIM.root",filesPath.Data()));					  infilecatv.push_back(2);
  infilenamev.push_back(Form("%sZZ_TuneCUETP8M1_13TeV-pythia8+RunIISpring15DR74-Asympt50ns_MCRUN2_74_V9A-v2+AODSIM.root",filesPath.Data()));					  infilecatv.push_back(2);
  assert(0);
  }
  else if(period==1){
  puPath = "/home/ceballos/cms/cmssw/042/CMSSW_7_4_6/src/MitAnalysisRunII/data/puWeights_13TeV_25ns.root";
  infilenamev.push_back(Form("%sdata_AOD_Run2015C1_25ns.root",filesPath.Data()));												  infilecatv.push_back(0);
  infilenamev.push_back(Form("%sdata_AOD_Run2015D3_25ns.root",filesPath.Data()));												infilecatv.push_back(0);
  infilenamev.push_back(Form("%sdata_AOD_Run2015D4_25ns.root",filesPath.Data()));												infilecatv.push_back(0);
  infilenamev.push_back(Form("%sDYJetsToLL_M-10to50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));	infilecatv.push_back(1);
  infilenamev.push_back(Form("%sDYJetsToLL_M-50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v3+AODSIM.root",filesPath.Data()));		  infilecatv.push_back(1);
  infilenamev.push_back(Form("%sZZTo2L2Nu_13TeV_powheg_pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));					infilecatv.push_back(2);
  infilenamev.push_back(Form("%sZZTo2L2Q_13TeV_amcatnloFXFX_madspin_pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));			infilecatv.push_back(2);
  infilenamev.push_back(Form("%sZZTo4L_13TeV_powheg_pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));					infilecatv.push_back(2);
  infilenamev.push_back(Form("%sGluGluToZZTo2e2mu_BackgroundOnly_13TeV_MCFM+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));			infilecatv.push_back(2);
  infilenamev.push_back(Form("%sGluGluToZZTo2e2tau_BackgroundOnly_13TeV_MCFM+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));			infilecatv.push_back(2);
  infilenamev.push_back(Form("%sGluGluToZZTo2mu2tau_BackgroundOnly_13TeV_MCFM+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));			infilecatv.push_back(2);
  infilenamev.push_back(Form("%sGluGluToZZTo4e_BackgroundOnly_13TeV_MCFM+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));  			infilecatv.push_back(2);
  infilenamev.push_back(Form("%sGluGluToZZTo4mu_BackgroundOnly_13TeV_MCFM+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data())); 			infilecatv.push_back(2);
  infilenamev.push_back(Form("%sGluGluToZZTo4tau_BackgroundOnly_13TeV_MCFM+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));			infilecatv.push_back(2);
  infilenamev.push_back(Form("%sWZTo1L1Nu2Q_13TeV_amcatnloFXFX_madspin_pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));			infilecatv.push_back(2);
  infilenamev.push_back(Form("%sWZTo2L2Q_13TeV_amcatnloFXFX_madspin_pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v2+AODSIM.root",filesPath.Data()));			infilecatv.push_back(2);
  infilenamev.push_back(Form("%sWZTo3LNu_TuneCUETP8M1_13TeV-powheg-pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));			infilecatv.push_back(2);
  }
  else {assert(0);}

  if(infilenamev.size() != infilecatv.size()) assert(0);

  const Double_t mZ = 91.1876;
  
  const Int_t nbins = 4;  
  Float_t bins[nbins+1];

  const Int_t nmass = 3;
  const Double_t mH[nmass]     = {0, 125, 200};  
  bool useRFromData[3] = {1, 1, 1};

  //*******************************************************
  //Yields and  histograms
  //*******************************************************
  vector<Double_t> nin_kee_data, nin_kmm_data;
  
  vector<vector<TH1D*> > hNin_ree_mc,   hNout_ree_mc,   hNin_rmm_mc,   hNout_rmm_mc;
  vector<vector<TH1D*> > hNin_ree_da,   hNout_ree_da,   hNin_rmm_da,   hNout_rmm_da;

  vector<vector<Double_t> > nin_ee_dy, nout_ee_dy, nin_ee_vz, nout_ee_vz, nin_ee_data;  
  vector<vector<Double_t> > nin_mm_dy, nout_mm_dy, nin_mm_vz, nout_mm_vz, nin_mm_data;
  vector<vector<Double_t> > varin_ee_dy, varout_ee_dy, varin_ee_vz, varout_ee_vz;
  vector<vector<Double_t> > varin_mm_dy, varout_mm_dy, varin_mm_vz, varout_mm_vz;
  vector<vector<Double_t> > nin_em_data;

  
  for(UInt_t jetIndex = 0; jetIndex < 3; ++jetIndex) {
    Double_t tmp_nin_kee_data=0, tmp_nin_kmm_data=0;
    vector<TH1D*> tmp_hNin_ree_mc,   tmp_hNout_ree_mc,   tmp_hNin_rmm_mc,   tmp_hNout_rmm_mc;
    vector<TH1D*> tmp_hNin_ree_da,   tmp_hNout_ree_da,   tmp_hNin_rmm_da,   tmp_hNout_rmm_da;
    
    vector<Double_t> tmp_nin_ee_dy, tmp_nout_ee_dy, tmp_nin_ee_vz, tmp_nout_ee_vz, tmp_nin_ee_data;  
    vector<Double_t> tmp_nin_mm_dy, tmp_nout_mm_dy, tmp_nin_mm_vz, tmp_nout_mm_vz, tmp_nin_mm_data;
    vector<Double_t> tmp_varin_ee_dy, tmp_varout_ee_dy, tmp_varin_ee_vz, tmp_varout_ee_vz;
    vector<Double_t> tmp_varin_mm_dy, tmp_varout_mm_dy, tmp_varin_mm_vz, tmp_varout_mm_vz;
    vector<Double_t> tmp_nin_em_data;

    char hname[50];
    for(Int_t imass=0; imass<nmass; imass++) {
      if     (useDYMVA == kTRUE){
        if     (jetIndex == 0){
	  bins[0] = -0.20; bins[1] =  0.10; bins[2] = +0.20; bins[3] =  0.30; bins[4] = 1.0; 
	}
	else if(jetIndex == 1){
	  bins[0] = -0.20; bins[1] = +0.10; bins[2] = +0.20; bins[3] =  0.30; bins[4] = 1.0; 
	}
	else if(jetIndex == 2){
	  bins[0] = -0.20; bins[1] = +0.10; bins[2] = +0.20; bins[3] =  0.30; bins[4] = 1.0; 
	}
      } else {
	bins[0] = 20; bins[1] = 25; bins[2] = 35; bins[3] =  45; bins[4] = 70; 
      }

      sprintf(hname,"hNin_%iJet_ree_mc_m%i",Int_t(jetIndex),(Int_t)mH[imass]);  tmp_hNin_ree_mc.push_back(new TH1D(hname,"",nbins,bins));  tmp_hNin_ree_mc[imass]->Sumw2();
      sprintf(hname,"hNout_%iJet_ree_mc_m%i",Int_t(jetIndex),(Int_t)mH[imass]); tmp_hNout_ree_mc.push_back(new TH1D(hname,"",nbins,bins)); tmp_hNout_ree_mc[imass]->Sumw2();
      sprintf(hname,"hNin_%iJet_rmm_mc_m%i",Int_t(jetIndex),(Int_t)mH[imass]);  tmp_hNin_rmm_mc.push_back(new TH1D(hname,"",nbins,bins));  tmp_hNin_rmm_mc[imass]->Sumw2();
      sprintf(hname,"hNout_%iJet_rmm_mc_m%i",Int_t(jetIndex),(Int_t)mH[imass]); tmp_hNout_rmm_mc.push_back(new TH1D(hname,"",nbins,bins)); tmp_hNout_rmm_mc[imass]->Sumw2();
      
      sprintf(hname,"hNin_%iJet_ree_da_m%i",Int_t(jetIndex),(Int_t)mH[imass]);  tmp_hNin_ree_da.push_back(new TH1D(hname,"",nbins,bins));  tmp_hNin_ree_da[imass]->Sumw2();
      sprintf(hname,"hNout_%iJet_ree_da_m%i",Int_t(jetIndex),(Int_t)mH[imass]); tmp_hNout_ree_da.push_back(new TH1D(hname,"",nbins,bins)); tmp_hNout_ree_da[imass]->Sumw2();
      sprintf(hname,"hNin_%iJet_rmm_da_m%i",Int_t(jetIndex),(Int_t)mH[imass]);  tmp_hNin_rmm_da.push_back(new TH1D(hname,"",nbins,bins));  tmp_hNin_rmm_da[imass]->Sumw2();
      sprintf(hname,"hNout_%iJet_rmm_da_m%i",Int_t(jetIndex),(Int_t)mH[imass]); tmp_hNout_rmm_da.push_back(new TH1D(hname,"",nbins,bins)); tmp_hNout_rmm_da[imass]->Sumw2();
      
      tmp_nin_ee_dy.push_back(0), tmp_nout_ee_dy.push_back(0), tmp_nin_ee_vz.push_back(0), tmp_nout_ee_vz.push_back(0), tmp_nin_ee_data.push_back(0);
      tmp_nin_mm_dy.push_back(0), tmp_nout_mm_dy.push_back(0), tmp_nin_mm_vz.push_back(0), tmp_nout_mm_vz.push_back(0), tmp_nin_mm_data.push_back(0);
      tmp_varin_ee_dy.push_back(0), tmp_varout_ee_dy.push_back(0), tmp_varin_ee_vz.push_back(0), tmp_varout_ee_vz.push_back(0);    
      tmp_varin_mm_dy.push_back(0), tmp_varout_mm_dy.push_back(0), tmp_varin_mm_vz.push_back(0), tmp_varout_mm_vz.push_back(0);
      tmp_nin_em_data.push_back(0);
     }

    nin_kee_data.push_back(tmp_nin_kee_data);
    nin_kmm_data.push_back(tmp_nin_kmm_data);

    hNin_ree_mc.push_back(tmp_hNin_ree_mc); 
    hNout_ree_mc.push_back(tmp_hNout_ree_mc); 
    hNin_rmm_mc.push_back(tmp_hNin_rmm_mc); 
    hNout_rmm_mc.push_back(tmp_hNout_rmm_mc);

    hNin_ree_da.push_back(tmp_hNin_ree_da); 
    hNout_ree_da.push_back(tmp_hNout_ree_da); 
    hNin_rmm_da.push_back(tmp_hNin_rmm_da); 
    hNout_rmm_da.push_back(tmp_hNout_rmm_da);

    nin_ee_dy.push_back(tmp_nin_ee_dy);
    nout_ee_dy.push_back(tmp_nout_ee_dy);
    nin_ee_vz.push_back(tmp_nin_ee_vz);
    nout_ee_vz.push_back(tmp_nout_ee_vz);
    nin_ee_data.push_back(tmp_nin_ee_data);
    nin_mm_dy.push_back(tmp_nin_mm_dy);
    nout_mm_dy.push_back(tmp_nout_mm_dy);
    nin_mm_vz.push_back(tmp_nin_mm_vz);
    nout_mm_vz.push_back(tmp_nout_mm_vz);
    nin_mm_data.push_back(tmp_nin_mm_data);
    varin_ee_dy.push_back(tmp_varin_ee_dy);
    varout_ee_dy.push_back(tmp_varout_ee_dy);
    varin_ee_vz.push_back(tmp_varin_ee_vz);
    varout_ee_vz.push_back(tmp_varout_ee_vz);
    varin_mm_dy.push_back(tmp_varin_mm_dy);
    varout_mm_dy.push_back(tmp_varout_mm_dy);
    varin_mm_vz.push_back(tmp_varin_mm_vz);
    varout_mm_vz.push_back(tmp_varout_mm_vz);
    nin_em_data.push_back(tmp_nin_em_data);
  }
  //*******************************************************
  //Systematic Error on VZ Normalization
  //*******************************************************
  const Double_t vzNormSystematic = 0.10;

  Float_t fMVACut[4][4];
  InitializeJetIdCuts(fMVACut);
 
  TFile *fPUFile = TFile::Open(Form("%s",puPath.Data()));
  TH1D *fhDPU = (TH1D*)(fPUFile->Get("puWeights"));
  assert(fhDPU);
  fhDPU->SetDirectory(0);
  delete fPUFile;

  //*******************************************************
  // Chain Loop
  //*******************************************************
  for(UInt_t ifile=0; ifile<infilenamev.size(); ifile++) {

    TFile the_input_file(infilenamev[ifile]);
    TTree *the_input_tree = (TTree*)the_input_file.FindObjectAny("events");
    //TTree *the_input_all  = (TTree*)the_input_file.FindObjectAny("all");

    BareMonteCarlo eventMonteCarlo;
    eventMonteCarlo.setBranchAddresses(the_input_tree);

    BareEvent eventEvent;
    eventEvent.setBranchAddresses(the_input_tree);

    BareJets eventJets;
    eventJets.setBranchAddresses(the_input_tree);

    BareLeptons eventLeptons;
    eventLeptons.setBranchAddresses(the_input_tree);

    BareTaus eventTaus;
    eventTaus.setBranchAddresses(the_input_tree);

    BareMet eventMet;
    eventMet.SetExtend();
    eventMet.setBranchAddresses(the_input_tree);

    BareTrigger eventTrigger;
    eventTrigger.setBranchAddresses(the_input_tree);

    BareVertex eventVertex;
    eventVertex.setBranchAddresses(the_input_tree);

    if(useDYMVA == true){
      the_input_tree->SetBranchAddress("dymva", &dymva_);
      the_input_tree->SetBranchAddress("nlep", &nlep_ );
      the_input_tree->SetBranchAddress("njets", &njets_);
    }

    TNamed *triggerNames = (TNamed*)the_input_file.FindObjectAny("triggerNames");
    char **tokens;
    size_t numtokens;
    tokens = strsplit(triggerNames->GetTitle(), ",", &numtokens);
    if(infilecatv[ifile] == 0){
      for (int i = 0; i < (int)numtokens; i++) {
        printf("triggerNames(%2d): \"%s\"\n",(int)i,tokens[i]);
      }
    }

    double theMCPrescale = mcPrescale;
    if(infilecatv[ifile] == 0) theMCPrescale = 1.0;
    for (int i=0; i<int(the_input_tree->GetEntries()/theMCPrescale); ++i) {
      the_input_tree->GetEntry(i);
      if(i%100000==0) printf("event %d out of %d\n",i,(int)the_input_tree->GetEntries());

      Bool_t passFilter[6] = {kFALSE,kFALSE,kFALSE,kFALSE,kFALSE,kFALSE};
      vector<int> idLep; vector<int> idTight; vector<int> idSoft; unsigned int goodIsTight = 0;
      for(int nlep=0; nlep<eventLeptons.p4->GetEntriesFast(); nlep++) {
        if(selectIdIsoCut(typeLepSel.Data(),TMath::Abs((int)(*eventLeptons.pdgId)[nlep]),TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[nlep])->Pt()),
	   TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[nlep])->Eta()),(double)(*eventLeptons.iso)[nlep],(int)(*eventLeptons.selBits)[nlep]))
	                                                                                               {idTight.push_back(1); idLep.push_back(nlep); goodIsTight++;}
        else if(((int)(*eventLeptons.selBits)[nlep] & BareLeptons::LepFake)  == BareLeptons::LepFake ) {idTight.push_back(0); idLep.push_back(nlep);}
        else if(((int)(*eventLeptons.selBits)[nlep] & BareLeptons::LepSoftIP)== BareLeptons::LepSoftIP){idSoft.push_back(nlep);}
      }
      if(idLep.size()!=idTight.size()) assert(0);
      if(idLep.size()==2) passFilter[0] = kTRUE;
      if(passFilter[0] == kFALSE) continue;

      if(idLep.size() >= 2 &&
     	 ((TLorentzVector*)(*eventLeptons.p4)[idLep[0]])->Pt() > 20 && 
     	 ((TLorentzVector*)(*eventLeptons.p4)[idLep[1]])->Pt() > 20) passFilter[1] = kTRUE;
      for (int nt = 0; nt <(int)numtokens; nt++) {
        if((*eventTrigger.triggerFired)[nt] == 0) continue;
        if((strcmp(tokens[nt],"HLT_Mu8_TrkIsoVVL_Ele17_CaloIdL_TrackIdL_IsoVL_v*")  == 0) ||
           (strcmp(tokens[nt],"HLT_Mu8_TrkIsoVVL_Ele23_CaloIdL_TrackIdL_IsoVL_v*")  == 0) ||
           (strcmp(tokens[nt],"HLT_Mu17_TrkIsoVVL_Ele12_CaloIdL_TrackIdL_IsoVL_v*") == 0) ||
           (strcmp(tokens[nt],"HLT_Mu23_TrkIsoVVL_Ele12_CaloIdL_TrackIdL_IsoVL_v*") == 0) ||
           (strcmp(tokens[nt],"HLT_Mu17_TrkIsoVVL_Mu8_TrkIsoVVL_DZ_v*") 	    == 0) ||
           (strcmp(tokens[nt],"HLT_Mu17_TrkIsoVVL_TkMu8_TrkIsoVVL_DZ_v*")	    == 0) ||
           (strcmp(tokens[nt],"HLT_IsoMu27_v*") 				    == 0) ||
           (strcmp(tokens[nt],"HLT_IsoMu20_v*") 				    == 0) ||
           (strcmp(tokens[nt],"HLT_IsoTkMu20_v*")				    == 0) ||
           (strcmp(tokens[nt],"HLT_Ele17_Ele12_CaloIdL_TrackIdL_IsoVL_DZ_v*")	    == 0) ||
           (strcmp(tokens[nt],"HLT_Ele23_WPLoose_Gsf_v*")			    == 0) ||
           (strcmp(tokens[nt],"HLT_Ele22_eta2p1_WP75_Gsf_v*")			    == 0) ||
           (strcmp(tokens[nt],"HLT_Ele27_WPLoose_Gsf_v*")			    == 0) ||
           (strcmp(tokens[nt],"HLT_Ele27_WP85_Gsf_v*")  			    == 0)
           ) passFilter[2] = kTRUE;
      }

      if(passFilter[1] == kFALSE) continue;
      if(passFilter[2] == kFALSE) continue;

      if(goodIsTight == idTight.size()) passFilter[3] = kTRUE;
      if(passFilter[3] == kFALSE) continue;

      passFilter[4] = ((int)(*eventLeptons.pdgId)[idLep[0]]*(int)(*eventLeptons.pdgId)[idLep[1]] < 0);
      if(passFilter[4] == kFALSE) continue;

      TLorentzVector dilep(( ( *(TLorentzVector*)(eventLeptons.p4->At(idLep[0])) ) + ( *(TLorentzVector*)(eventLeptons.p4->At(idLep[1])) ) )); 

      double dPhiLepMETMin = 999.;
      for(unsigned nl=0; nl<idLep.size(); nl++){
        if(dPhiLepMETMin > TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[idLep[nl]])->DeltaPhi(*((TLorentzVector*)(*eventMet.p4)[0]))))
           dPhiLepMETMin = TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[idLep[nl]])->DeltaPhi(*((TLorentzVector*)(*eventMet.p4)[0])));      
      }
      double minMET  = TMath::Min(((TLorentzVector*)(*eventMet.p4)[0])->Pt(),(double)eventMet.trackMet->Pt());
      double minPMET = TMath::Min(((TLorentzVector*)(*eventMet.p4)[0])->Pt(),(double)eventMet.trackMet->Pt());
      if(dPhiLepMETMin < TMath::Pi()/2) minPMET = minPMET * sin(dPhiLepMETMin);

      unsigned int nJets = 0;
      bool isBtag = kFALSE;
      double bDiscrMax = 0.0;
      double dPhiJetMET = -1.0;
      double dPhiJetDiLep = -1.0;
      for(int nj=0; nj<eventJets.p4->GetEntriesFast(); nj++){
        if(((TLorentzVector*)(*eventJets.p4)[nj])->Pt() < 10) continue;
        bool passId = passJetId(fMVACut, (float)(*eventJets.puId)[nj], ((TLorentzVector*)(*eventJets.p4)[nj])->Pt(), TMath::Abs(((TLorentzVector*)(*eventJets.p4)[nj])->Eta()));
        //if(passId == false) continue;        

        Bool_t isLepton = kFALSE;
        for(unsigned int nl=0; nl<idLep.size(); nl++){
          if(((TLorentzVector*)(*eventJets.p4)[nj])->DeltaR(*((TLorentzVector*)(*eventLeptons.p4)[idLep[nl]])) < 0.3) isLepton = kTRUE;
	}
	if(isLepton == kTRUE) continue;

        if(dPhiJetMET   == -1) dPhiJetMET   = TMath::Abs(((TLorentzVector*)(*eventJets.p4)[nj])->DeltaPhi(*((TLorentzVector*)(*eventMet.p4)[0])))*180./TMath::Pi();
        if(dPhiJetDiLep == -1) dPhiJetDiLep = TMath::Abs(dilep.DeltaPhi(*((TLorentzVector*)(*eventJets.p4)[nj])))*180./TMath::Pi();

	if(((TLorentzVector*)(*eventJets.p4)[nj])->Pt() > 15 && 
	   (float)(*eventJets.bDiscr)[nj] > bDiscrMax) bDiscrMax = (float)(*eventJets.bDiscr)[nj];

        if(((TLorentzVector*)(*eventJets.p4)[nj])->Pt() < 30) continue;

        nJets++;
      }

      if(useDYMVA == true){
        if(nlep_ != idLep.size()) {printf("PROBLEM nlep %d != %d\n",(int)nlep_,(int)idLep.size()); assert(1); return;}
        if(njets_ != nJets) {printf("PROBLEM njet %d != %d\n",(int)njets_,nJets); assert(1); return;}
      }

      if(nJets <= 2) passFilter[5] = kTRUE;  	    
      if(passFilter[5] == kFALSE) continue;

      Int_t typeLep = 2;
      if     (TMath::Abs((int)(*eventLeptons.pdgId)[idLep[0]])==13&&TMath::Abs((int)(*eventLeptons.pdgId)[idLep[1]])==13) typeLep = 0;
      else if(TMath::Abs((int)(*eventLeptons.pdgId)[idLep[0]])==11&&TMath::Abs((int)(*eventLeptons.pdgId)[idLep[1]])==11) typeLep = 1;

      if(infilecatv[ifile] == 0 && TMath::Abs(dilep.M()-mZ)<MassZCut) {
        if(typeLep == 0) nin_kmm_data[nJets]++;
        if(typeLep == 1) nin_kee_data[nJets]++;
      }

      if(minPMET <= 20) continue;
      double varMet = minPMET;
      if(varMet>=70) varMet=69;
      if(useDYMVA == kTRUE) {
        varMet = dymva_;
      }

      double theLumi = lumi; if(infilecatv[ifile] == 0) theLumi = 1.0;
      double puWeight = nPUScaleFactor(fhDPU, (double)eventVertex.npv); if(infilecatv[ifile] == 0) puWeight = 1.0;
      double effSF = 1.0;

      if(infilecatv[ifile] != 0){
        effSF = effScaleFactor(((TLorentzVector*)(*eventLeptons.p4)[idLep[0]])->Pt(),TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[idLep[0]])->Eta()),TMath::Abs((int)(*eventLeptons.pdgId)[idLep[0]]),period,typeLepSel.Data())*
                effScaleFactor(((TLorentzVector*)(*eventLeptons.p4)[idLep[1]])->Pt(),TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[idLep[1]])->Eta()),TMath::Abs((int)(*eventLeptons.pdgId)[idLep[1]]),period,typeLepSel.Data());
      }

      double totalWeight = eventMonteCarlo.mcWeight*theLumi*puWeight*effSF*theMCPrescale;

      vector<bool> isGenDupl;
      for(int ngen0=0; ngen0<eventMonteCarlo.p4->GetEntriesFast(); ngen0++) {
        isGenDupl.push_back(0);
	if(TMath::Abs((int)(*eventMonteCarlo.pdgId)[ngen0]) != 11 &&
	   TMath::Abs((int)(*eventMonteCarlo.pdgId)[ngen0]) != 13) isGenDupl[ngen0] = 1;
	if(TMath::Abs((int)(*eventMonteCarlo.pdgId)[ngen0]) != 11 &&
	   TMath::Abs((int)(*eventMonteCarlo.pdgId)[ngen0]) != 13) continue;
        for(int ngen1=ngen0+1; ngen1<eventMonteCarlo.p4->GetEntriesFast(); ngen1++) {
          if(((TLorentzVector*)(*eventMonteCarlo.p4)[ngen0])->DeltaR(*((TLorentzVector*)(*eventMonteCarlo.p4)[ngen1])) < 0.02) {
	    isGenDupl[ngen0] = 1;
	    break;
	  }
        }
      }
      vector<int> isGenLep; unsigned int goodIsGenLep = 0;
      for(unsigned nl=0; nl<idLep.size(); nl++){
        bool isGenLepton = false;
        for(int ngen=0; ngen<eventMonteCarlo.p4->GetEntriesFast(); ngen++) {
	  if(isGenDupl[ngen] == 1) continue;
          if(TMath::Abs((int)(*eventLeptons.pdgId)[idLep[nl]]) == TMath::Abs((int)(*eventMonteCarlo.pdgId)[ngen]) &&
	    ((TLorentzVector*)(*eventLeptons.p4)[idLep[nl]])->DeltaR(*((TLorentzVector*)(*eventMonteCarlo.p4)[ngen])) < 0.1) {
	    isGenLepton = true;
	    break;
	  }
	}
	if(isGenLepton == true) {isGenLep.push_back(1); goodIsGenLep++;}
	else                    {isGenLep.push_back(0);}
      }
      if(infilecatv[ifile] != 0 && goodIsGenLep != isGenLep.size()) totalWeight = 0.0;

      //loop over analyses
      for(Int_t imass=0; imass<nmass; imass++) {
        // MET related cuts need to be applied after the Rout/in computation
        double theCutMassHigh = 1000.;
	if(dilep.Pt() <= 45.0) continue;
        if(bDiscrMax > 0.605 || idSoft.size() != 0) continue;
	if(dilep.M() <= 12.0) continue;

        if(infilecatv[ifile] == 1){ // Z MC
	  if     (TMath::Abs(dilep.M()-mZ)<MassZCut) {
	    if     (typeLep == 1) {
              hNin_ree_mc[nJets][imass]->Fill(varMet,totalWeight);		 
            }
	    else if(typeLep == 0) {
              hNin_rmm_mc[nJets][imass]->Fill(varMet,totalWeight);		     
            }
          } 
	  else if(TMath::Abs(dilep.M()-mZ) >= 15 && dilep.M() < theCutMassHigh) {
	    if     (typeLep == 1) {
              hNout_ree_mc[nJets][imass]->Fill(varMet,totalWeight);  
            }
	    else if(typeLep == 0) {
              hNout_rmm_mc[nJets][imass]->Fill(varMet,totalWeight);
            }
          }
        }
 
        double theDataWeight = 0.0;
        if     (infilecatv[ifile] == 0 && (typeLep == 0 || typeLep == 1)) theDataWeight =  1.0;
	else if(infilecatv[ifile] == 0					) theDataWeight = -1.0;

	// In reality ee == ee+mm for data
	if(theDataWeight != 0.0){
	  if     (TMath::Abs(dilep.M()-mZ)<MassZCut) {
            hNin_ree_da[nJets][imass]->Fill(varMet,theDataWeight);		
          } 
	  else if(TMath::Abs(dilep.M()-mZ) >= 15 && dilep.M() < theCutMassHigh) {
            hNout_ree_da[nJets][imass]->Fill(varMet,theDataWeight);     
          }
        }

	bool passMET = varMet > 45;
	if(useDYMVA == kTRUE) passMET = dymva_ > 0.3;
	if(passMET == kFALSE) continue;

        if(infilecatv[ifile] == 1){ // Z MC
	  if     (TMath::Abs(dilep.M()-mZ)<MassZCut) {
	    if     (typeLep == 1) { 
	      nin_ee_dy[nJets][imass]+=totalWeight; 
	      varin_ee_dy[nJets][imass]+=totalWeight*totalWeight; 
	    }	
	    else if(typeLep == 0) { 
	      nin_mm_dy[nJets][imass]+=totalWeight; 
	      varin_mm_dy[nJets][imass]+=totalWeight*totalWeight;
	    }

           } 
	   else if(TMath::Abs(dilep.M()-mZ) >= 15 && dilep.M() < theCutMassHigh) {
	    if     (typeLep == 1) {
	      nout_ee_dy[nJets][imass]+=totalWeight; 
	      varout_ee_dy[nJets][imass]+=totalWeight*totalWeight;
	    }  
	    else if(typeLep == 0) {
	      nout_mm_dy[nJets][imass]+=totalWeight;
	      varout_mm_dy[nJets][imass]+=totalWeight*totalWeight;
	    }
          }
        }

        //In Z peak region
	if(TMath::Abs(dilep.M()-mZ)<MassZCut) {

          if(typeLep == 1) {
            if(infilecatv[ifile] == 0) { 
              nin_ee_data[nJets][imass]++; 
            }
            if(infilecatv[ifile] == 2)  {
              nin_ee_vz[nJets][imass]+=totalWeight;
              varin_ee_vz[nJets][imass]+=totalWeight*totalWeight;
            }
          }
	
          if(typeLep == 0) {
            if(infilecatv[ifile] == 0) { 
              nin_mm_data[nJets][imass]++;
            }	
            if(infilecatv[ifile] == 2) {
              nin_mm_vz[nJets][imass]+=totalWeight;
              varin_mm_vz[nJets][imass]+=totalWeight*totalWeight;
            }		   
          }

	  if(infilecatv[ifile] == 0 && typeLep == 2) {
            nin_em_data[nJets][imass]++; 
          }

        } 
        // Out of Z peak region
        else if(TMath::Abs(dilep.M()-mZ) >= 15 && dilep.M() < theCutMassHigh) {

	  if(typeLep == 0) {
            if (infilecatv[ifile] == 2) {
              nout_ee_vz[nJets][imass]+=totalWeight;
              varout_ee_vz[nJets][imass]+=totalWeight*totalWeight;
            }
	  }
	
	  if(typeLep == 1) {
            if (infilecatv[ifile] == 2) {
              nout_mm_vz[nJets][imass]+=totalWeight;
              varout_mm_vz[nJets][imass]+=totalWeight*totalWeight;
            }
	  }
        }

      }
    }
  } // end of chain

  //--------------------------------------------------------------------------------------------------------------
  // Summary print out
  //============================================================================================================== 
  char DYEstimateTableName[200];
  sprintf(DYEstimateTableName,"DYEstimateTable.txt");
  ofstream fout(DYEstimateTableName);

  vector<vector<Double_t> > DYBkgScaleFactorHiggsSelection;
  vector<vector<Double_t> > DYBkgScaleFactorHiggsSelectionErr;
  vector<Double_t> DYBkgScaleFactorWWPreselection;
  vector<Double_t> DYBkgScaleFactorWWPreselectionErr;

  for(UInt_t jetIndex = 0; jetIndex < 3; ++jetIndex) {
    
    vector<Double_t> tmpDYBkgScaleFactorHiggsSelection;
    vector<Double_t> tmpDYBkgScaleFactorHiggsSelectionErr;
    Double_t tmpDYBkgScaleFactorWWPreselection;
    Double_t tmpDYBkgScaleFactorWWPreselectionErr;

    fout << "************************************************************************\n";
    fout << jetIndex << "-Jet Bin DY Bkg Scale Factor Computation\n";
    fout << "************************************************************************\n";

    Double_t k    = sqrt(nin_kee_data[jetIndex]/nin_kmm_data[jetIndex]);
    Double_t kerr = 0.5*k*sqrt(1.0/nin_kee_data[jetIndex] + 1.0/nin_kmm_data[jetIndex]);
    char buffer[200];
  
    fout << "Electron to muon efficiency ratio is " << k << " +/- " << kerr << endl;

    fout << endl;
    fout << jetIndex << "-jet bin summary:" << endl;
    fout << setw(4) << "sel" << "   ";
    fout << setw(25) << "R_out/in       ";
    fout << setw(15) << "mm/em/ee";
    fout << setw(20) << "N_in (OF,VZ sub)";
    fout << setw(20) << "N_in (data/MC)";
    fout << setw(20) << "   N_out data   ";
    fout << setw(20) << "N_out MC  ";
    fout << setw(20) << "N_out (data/MC)" << endl;


    for(Int_t imass=0; imass<nmass; imass++) {
      fout << setw(4) << mH[imass] << "   ";
    
      //
      // compute Routin from MC
      //

      Int_t MetBinToComputeRoutin = nbins-1;

      Double_t nout_ee   = 0;
      Double_t errout_ee = 0;
      Double_t nout_mm   = 0;
      Double_t errout_mm = 0;
      Double_t nout_ll   = 0;
      Double_t errout_ll = 0;      
      Double_t nin_ee   = 0;
      Double_t errin_ee = 0;
      Double_t nin_mm   = 0;
      Double_t errin_mm = 0;
      Double_t nin_ll   = 0;
      Double_t errin_ll = 0;      
      Double_t Ree        = 0;
      Double_t ReeErrStat = 0;
      Double_t ReeErrSyst = 0;      
      Double_t Rmm        = 0;
      Double_t RmmErrStat = 0;
      Double_t RmmErrSyst = 0;
      Double_t Rll = 0;
      Double_t RllErrStat = 0;
      Double_t RllErrSyst = 0;

      if(useRFromData[jetIndex] == false){
	nout_ee   = hNout_ree_mc[jetIndex][imass]->GetBinContent(MetBinToComputeRoutin);
	errout_ee = hNout_ree_mc[jetIndex][imass]->GetBinError(MetBinToComputeRoutin);
	nout_mm   = hNout_rmm_mc[jetIndex][imass]->GetBinContent(MetBinToComputeRoutin);
	errout_mm = hNout_rmm_mc[jetIndex][imass]->GetBinError(MetBinToComputeRoutin);
	nout_ll   = nout_ee+nout_mm;
	errout_ll = sqrt(errout_ee*errout_ee + errout_mm*errout_mm);

	nin_ee   = hNin_ree_mc[jetIndex][imass]->GetBinContent(MetBinToComputeRoutin);
	errin_ee = hNin_ree_mc[jetIndex][imass]->GetBinError(MetBinToComputeRoutin);
	nin_mm   = hNin_rmm_mc[jetIndex][imass]->GetBinContent(MetBinToComputeRoutin);
	errin_mm = hNin_rmm_mc[jetIndex][imass]->GetBinError(MetBinToComputeRoutin);
	nin_ll   = nin_ee+nin_mm;
	errin_ll = sqrt(errin_ee*errin_ee + errin_mm*errin_mm);

	Ree        = nout_ee/nin_ee;
	ReeErrStat = Ree*sqrt(errin_ee*errin_ee/nin_ee/nin_ee + errout_ee*errout_ee/nout_ee/nout_ee);
	ReeErrSyst = computeSyst(hNout_ree_mc[jetIndex][imass],hNin_ree_mc[jetIndex][imass], MetBinToComputeRoutin, 0.4);    

	Rmm        = nout_mm/nin_mm;
	RmmErrStat = Rmm*sqrt(errin_mm*errin_mm/nin_mm/nin_mm + errout_mm*errout_mm/nout_mm/nout_mm);
	RmmErrSyst = computeSyst(hNout_rmm_mc[jetIndex][imass],hNin_rmm_mc[jetIndex][imass], MetBinToComputeRoutin, 0.4);

	TH1D *hout = (TH1D*)hNout_ree_mc[jetIndex][imass]->Clone("hout");
	hout->Add(hNout_rmm_mc[jetIndex][imass]);
	TH1D *hin = (TH1D*)hNin_ree_mc[jetIndex][imass]->Clone("hin");
	hin->Add(hNin_rmm_mc[jetIndex][imass]);
	Rll        = nout_ll/nin_ll;
	RllErrStat = Rll*sqrt(errin_ll*errin_ll/nin_ll/nin_ll + errout_ll*errout_ll/nout_ll/nout_ll);
	RllErrSyst = computeSyst(hout,hin, MetBinToComputeRoutin, 0.4);

	delete hout;
	delete hin;
      } else {
	nout_ll   = hNout_ree_da[jetIndex][imass]->GetBinContent(MetBinToComputeRoutin);
	errout_ll = hNout_ree_da[jetIndex][imass]->GetBinError(MetBinToComputeRoutin);

	nin_ll   = hNin_ree_da[jetIndex][imass]->GetBinContent(MetBinToComputeRoutin);
	errin_ll = hNin_ree_da[jetIndex][imass]->GetBinError(MetBinToComputeRoutin);

	TH1D *hout = (TH1D*)hNout_ree_da[jetIndex][imass]->Clone("hout");
	TH1D *hin = (TH1D*)hNin_ree_da[jetIndex][imass]->Clone("hin");

	Rll        = nout_ll/nin_ll;
	RllErrStat = Rll*sqrt(errin_ll*errin_ll/nin_ll/nin_ll + errout_ll*errout_ll/nout_ll/nout_ll);
	Double_t rErrorMax = 100000.4;
	cout << "M: " << mH[imass] << endl;
	RllErrSyst = computeSyst(hout,hin,MetBinToComputeRoutin,rErrorMax,true,true);
	delete hout;
	delete hin;
      }

      if(Rll <= 0) {Rll = 0.10; RllErrStat = 0.10; RllErrSyst = 0.10;}
      // DO NOT ALLOW FOR MORE THAN 100% uncertainty
      if(RllErrSyst > 1.0*Rll) RllErrSyst = 1.0*Rll;
      // DO NOT ALLOW FOR LESS THAN 30% uncertainty
      if(RllErrSyst < 0.3*Rll) RllErrSyst = 0.3*Rll;

      sprintf(buffer,"%.2f +/- %.2f +/- %.2f",Rll,RllErrStat,RllErrSyst);
//     sprintf(buffer,"%.3f +/- %.3f +/- %.3f",Ree,ReeErrStat,ReeErrSyst);
//     sprintf(buffer,"%.3f +/- %.3f +/- %.3f",Rmm,RmmErrStat,RmmErrSyst);
      fout << setw(25) << buffer; 

      //
      // raw in-yields in data
      //
      sprintf(buffer,"%i/%i/%i",Int_t(nin_mm_data[jetIndex][imass]), Int_t(nin_em_data[jetIndex][imass]), Int_t(nin_ee_data[jetIndex][imass]));
      fout << setw(15) << buffer;

      //
      // in-yields in data after OF and VZ subtraction
      //
      Double_t nof = nin_em_data[jetIndex][imass];
      Double_t nin_ee_sub, err_ee_sub,nin_mm_sub,err_mm_sub,nin_ll_sub,err_ll_sub;

      //use Opposite Flavor data for bkg subtraction
      nin_ee_sub = nin_ee_data[jetIndex][imass] - 0.5*k*nof - nin_ee_vz[jetIndex][imass];
      err_ee_sub = sqrt(nin_ee_data[jetIndex][imass] + 0.5*0.5*k*k*nof*nof*(kerr*kerr/k/k + 1.0/nof) + varin_ee_vz[jetIndex][imass] + pow(nin_ee_vz[jetIndex][imass]*vzNormSystematic,2) );
      nin_mm_sub = nin_mm_data[jetIndex][imass] - 0.5/k*nof - nin_mm_vz[jetIndex][imass];
      err_mm_sub = sqrt(nin_mm_data[jetIndex][imass] + 0.5*0.5/k/k*nof*nof*(kerr*kerr/k/k + 1.0/nof) + varin_mm_vz[jetIndex][imass] + pow(nin_mm_vz[jetIndex][imass]*vzNormSystematic,2));
      nin_ll_sub = nin_ee_sub + nin_mm_sub;
      err_ll_sub = sqrt(nin_mm_data[jetIndex][imass] + nin_ee_data[jetIndex][imass] 
        			 + 0.5*0.5*( (k+1.0/k)*(k+1.0/k)*nof*nof*kerr*kerr + (k+1.0/k)*(k+1.0/k)*nof ) 
        			 + varin_mm_vz[jetIndex][imass] + varin_ee_vz[jetIndex][imass] + pow((nin_ee_vz[jetIndex][imass]+nin_mm_vz[jetIndex][imass])*vzNormSystematic,2));
      if(nin_ee_sub <= 0) nin_ee_sub = 1;
      if(nin_mm_sub <= 0) nin_mm_sub = 1;
      if(nin_ll_sub <= 0) nin_ll_sub = 1;

      sprintf(buffer,"  %.2f +/- %.2f : %.2f : %.2f + %.2f  ",nin_ll_sub,err_ll_sub, 0.5*k*nof + 0.5/k*nof, nin_ee_vz[jetIndex][imass], nin_mm_vz[jetIndex][imass]);
      fout << setw(20) << buffer;
    
      //
      // in-yield data/MC scale factor
      //

      Double_t sfin_ee     = nin_ee_sub/nin_ee_dy[jetIndex][imass];
      Double_t sfin_ee_err = sfin_ee*sqrt(err_ee_sub*err_ee_sub/nin_ee_sub/nin_ee_sub + (varin_ee_dy[jetIndex][imass])*(varin_ee_dy[jetIndex][imass])/(nin_ee_dy[jetIndex][imass])/(nin_ee_dy[jetIndex][imass]));
      Double_t sfin_mm     = nin_mm_sub/nin_mm_dy[jetIndex][imass];
      Double_t sfin_mm_err = sfin_mm*sqrt(err_mm_sub*err_mm_sub/nin_mm_sub/nin_mm_sub + (varin_mm_dy[jetIndex][imass])*(varin_mm_dy[jetIndex][imass])/(nin_mm_dy[jetIndex][imass])/(nin_mm_dy[jetIndex][imass]));
      Double_t sfin_ll     = nin_ll_sub/(nin_ee_dy[jetIndex][imass]+nin_mm_dy[jetIndex][imass]);
//       Double_t sfin_ll_err = sfin_ll*sqrt(err_ll_sub*err_ll_sub/nin_ll_sub/nin_ll_sub 
//                                           + (varin_ee_dy[jetIndex][imass]+varin_mm_dy[jetIndex][imass])*(varin_ee_dy[jetIndex][imass]+varin_mm_dy[jetIndex][imass])/(nin_ee_dy[jetIndex][imass]+nin_mm_dy[jetIndex][imass])/(nin_ee_dy[jetIndex][imass]+nin_mm_dy[jetIndex][imass]));
      Double_t sfin_ll_err = sfin_ll*sqrt(err_ll_sub*err_ll_sub/nin_ll_sub/nin_ll_sub 
                                          + (varin_ee_dy[jetIndex][imass]+varin_mm_dy[jetIndex][imass])/(nin_ee_dy[jetIndex][imass]+nin_mm_dy[jetIndex][imass])/(nin_ee_dy[jetIndex][imass]+nin_mm_dy[jetIndex][imass]));
   
      sprintf(buffer,"%.2f +/- %.2f",sfin_ll,sfin_ll_err);
//    sprintf(buffer,"%.2f +/- %.2f",sfin_ee,sfin_ee_err);
//    sprintf(buffer,"%.2f +/- %.2f",sfin_mm,sfin_mm_err);
      fout << setw(20) << buffer;
    
      //
      // out-yield prediction
      //
      Double_t nout_ee_pre = Ree*nin_ee_sub;
      Double_t nout_ee_sta = nout_ee_pre*sqrt(ReeErrStat*ReeErrStat/Ree/Ree + err_ee_sub*err_ee_sub/nin_ee_sub/nin_ee_sub);
      Double_t nout_ee_sys = nout_ee_pre*ReeErrSyst/Ree;
      Double_t nout_ee_err = sqrt(nout_ee_sys*nout_ee_sys + nout_ee_sta*nout_ee_sta);
      Double_t nout_mm_pre = Rmm*nin_mm_sub;
      Double_t nout_mm_sta = nout_mm_pre*sqrt(RmmErrStat*RmmErrStat/Rmm/Rmm + err_mm_sub*err_mm_sub/nin_mm_sub/nin_mm_sub);
      Double_t nout_mm_sys = nout_mm_pre*RmmErrSyst/Rmm;
      Double_t nout_mm_err = sqrt(nout_mm_sys*nout_mm_sys + nout_mm_sta*nout_mm_sta);
      Double_t nout_ll_pre = Rll*nin_ll_sub;
      Double_t nout_ll_sta = nout_ll_pre*sqrt((RllErrStat*RllErrStat)/Rll/Rll + err_ll_sub*err_ll_sub/nin_ll_sub/nin_ll_sub);
      Double_t nout_ll_sys = nout_ll_pre*RllErrSyst/Rll;
      Double_t nout_ll_err = sqrt(nout_ll_sys*nout_ll_sys + nout_ll_sta*nout_ll_sta);

      sprintf(buffer,"%.2f +/- %.2f +/- %.2f",nout_ll_pre,nout_ll_sta,nout_ll_sys);
//    sprintf(buffer,"%.2f +/- %.2f +/- %.2f",nout_ee_pre,nout_ee_sta,nout_ee_sys);
//    sprintf(buffer,"%.2f +/- %.2f +/- %.2f",nout_mm_pre,nout_mm_sta,nout_mm_sys);
      fout << "   " << setw(20) << buffer;
    
      //
      // out-yield in MC
      //
      printf("SSS %f %f %f\n",nout_ee_dy[jetIndex][imass]+nout_mm_dy[jetIndex][imass],nout_ee_dy[jetIndex][imass],nout_mm_dy[jetIndex][imass]);
      sprintf(buffer,"%.2f +/- %.2f",nout_ee_dy[jetIndex][imass]+nout_mm_dy[jetIndex][imass],sqrt(varout_ee_dy[jetIndex][imass] + varout_mm_dy[jetIndex][imass]));
//    sprintf(buffer,"%.2f +/- %.2f",nout_ee_dy[jetIndex][imass],sqrt(varout_ee_dy[jetIndex][imass]));
//    sprintf(buffer,"%.2f +/- %.2f",nout_mm_dy[jetIndex][imass],sqrt(varout_mm_dy[jetIndex][imass]));
      fout << setw(20) << buffer;
    
      //
      // out-yield data/MC scale factor
      //
      Double_t sfout_ee     = nout_ee_pre/nout_ee_dy[jetIndex][imass];
      Double_t sfout_ee_err = sfout_ee*sqrt(nout_ee_err*nout_ee_err/nout_ee_pre/nout_ee_pre );
      Double_t sfout_mm     = nout_mm_pre/nout_mm_dy[jetIndex][imass];
      Double_t sfout_mm_err = sfout_mm*sqrt(nout_mm_err*nout_mm_err/nout_mm_pre/nout_mm_pre );
      Double_t sfout_ll     = nout_ll_pre/(nout_ee_dy[jetIndex][imass]+nout_mm_dy[jetIndex][imass]);
      Double_t sfout_ll_err = sfout_ll*sqrt(nout_ll_err*nout_ll_err/nout_ll_pre/nout_ll_pre);
    
      sprintf(buffer,"%.2f +/- %.2f",sfout_ll,sfout_ll_err);
//    sprintf(buffer,"%.2f +/- %.2f",sfout_ee,sfout_ee_err);
//    sprintf(buffer,"%.2f +/- %.2f",sfout_mm,sfout_mm_err);
      fout << setw(20) << buffer;        
      fout << endl;
      if (imass == 0) {
        tmpDYBkgScaleFactorWWPreselection    = sfout_ll;
        tmpDYBkgScaleFactorWWPreselectionErr = sfout_ll_err;
      } else {
        // BIG CHANGE, we quote
        //tmpDYBkgScaleFactorHiggsSelection.push_back(sfout_ll);
        //tmpDYBkgScaleFactorHiggsSelectionErr.push_back(sfout_ll_err);
        tmpDYBkgScaleFactorHiggsSelection.push_back(nout_ll_pre);
        tmpDYBkgScaleFactorHiggsSelectionErr.push_back(sqrt(nout_ll_sta*nout_ll_sta+nout_ll_sys*nout_ll_sys));
      }
    }

    DYBkgScaleFactorHiggsSelection.push_back(tmpDYBkgScaleFactorHiggsSelection);
    DYBkgScaleFactorHiggsSelectionErr.push_back(tmpDYBkgScaleFactorHiggsSelectionErr);
    DYBkgScaleFactorWWPreselection.push_back(tmpDYBkgScaleFactorWWPreselection);
    DYBkgScaleFactorWWPreselectionErr.push_back(tmpDYBkgScaleFactorWWPreselectionErr);
  }

  fout.close();


  //***************************************************************************
  // Generate DY Scale Factor and Systematics Code for card creation
  //***************************************************************************
  char DYBkgScaleFactorsName[200];
  sprintf(DYBkgScaleFactorsName,"DYBkgScaleFactors.h");
  ofstream outf(DYBkgScaleFactorsName);

  outf << "static Double_t DYBkgScaleFactor(Int_t mH, Int_t jetBin) {" << endl;
  
  outf << "  Int_t mHiggs[" << nmass-1 << "] = {";
  for (UInt_t i = 0; i < nmass-1 ; ++i) {
    outf << mH[i+1];
    if (i < nmass-1-1) outf << ",";    
  }
  outf << "};" << endl;

  outf << "  Double_t DYBkgScaleFactorWWPreselection[3] = { " 
       << DYBkgScaleFactorWWPreselection[0] << ", "
       << DYBkgScaleFactorWWPreselection[1] << ", "
       << DYBkgScaleFactorWWPreselection[2] << " "
       << " };" << endl;

  outf << "  Double_t DYBkgScaleFactorHiggsSelection[3][" << nmass-1 << "] = { " << endl;
  outf << "    { ";
  for (UInt_t i = 0; i < nmass-1 ; ++i) {
    outf << DYBkgScaleFactorHiggsSelection[0][i];    
    if (i < nmass-1-1) outf << ",";
  }
  outf << "}," << endl;
  outf << "    { ";
  for (UInt_t i = 0; i < nmass-1 ; ++i) {
    outf << DYBkgScaleFactorHiggsSelection[1][i];    
    if (i < nmass-1-1) outf << ",";
  }
  outf << "}," << endl;
  outf << "    { ";
  for (UInt_t i = 0; i < nmass-1 ; ++i) {
    outf << DYBkgScaleFactorHiggsSelection[2][i];    
    if (i < nmass-1-1) outf << ",";
  }
  outf << "} };" << endl;

  outf << "  if(mH == 0) return DYBkgScaleFactorWWPreselection[jetBin];" << endl;
  
  outf << "  Int_t massIndex = -1;" << endl;
  outf << "  for (UInt_t m=0; m < " << nmass-1 << " ; ++m) {" << endl;
  outf << "    if (mH == mHiggs[m]) massIndex = m;" << endl;
  outf << "  }" << endl;
  outf << "  if (massIndex >= 0) {" << endl;  
  outf << "    return DYBkgScaleFactorHiggsSelection[jetBin][massIndex];" << endl;
  outf << "  } else {" << endl;
  outf << "    return DYBkgScaleFactorWWPreselection[jetBin];" << endl;
  
  outf << "  }" << endl;
  outf << "}" << endl;
  outf << endl;


  outf << "static Double_t DYBkgScaleFactorKappa(Int_t mH, Int_t jetBin) {" << endl;
  
  outf << "  Int_t mHiggs[" << nmass-1 << "] = {";
  for (UInt_t i = 0; i < nmass-1 ; ++i) {
    outf << mH[i+1];
    if (i < nmass-1-1) outf << ",";    
  }
  outf << "};" << endl;

  outf << "  Double_t DYBkgScaleFactorWWPreselectionKappa[3] = { " 
       << (1.0 + DYBkgScaleFactorWWPreselectionErr[0]/DYBkgScaleFactorWWPreselection[0]) << ", "
       << (1.0 + DYBkgScaleFactorWWPreselectionErr[1]/DYBkgScaleFactorWWPreselection[1]) << ", "
       << (1.0 + DYBkgScaleFactorWWPreselectionErr[2]/DYBkgScaleFactorWWPreselection[2]) << " "
       << " };" << endl;

  outf << "  Double_t DYBkgScaleFactorHiggsSelectionKappa[3][" << nmass-1 << "] = { " << endl;
  outf << "    { ";
  for (UInt_t i = 0; i < nmass-1 ; ++i) {
    outf << (1.0 + DYBkgScaleFactorHiggsSelectionErr[0][i] / DYBkgScaleFactorHiggsSelection[0][i]);
    if (i < nmass-1-1) outf << ",";
  }
  outf << "}," << endl;
  outf << "    { ";
  for (UInt_t i = 0; i < nmass-1 ; ++i) {
    outf << (1.0 + DYBkgScaleFactorHiggsSelectionErr[1][i] / DYBkgScaleFactorHiggsSelection[1][i]);
    if (i < nmass-1-1) outf << ",";
  }
  outf << "}," << endl;
  outf << "    { ";
  for (UInt_t i = 0; i < nmass-1 ; ++i) {
    outf << (1.0 + DYBkgScaleFactorHiggsSelectionErr[2][i] / DYBkgScaleFactorHiggsSelection[2][i]);
    if (i < nmass-1-1) outf << ",";
  }
  outf << "} };" << endl;

  outf << "  if(mH == 0) return DYBkgScaleFactorWWPreselectionKappa[jetBin];" << endl;
  
  outf << "  Int_t massIndex = -1;" << endl;
  outf << "  for (UInt_t m=0; m < " << nmass-1 << " ; ++m) {" << endl;
  outf << "    if (mH == mHiggs[m]) massIndex = m;" << endl;
  outf << "  }" << endl;
  outf << "  if (massIndex >= 0) {" << endl;  
  outf << "    return DYBkgScaleFactorHiggsSelectionKappa[jetBin][massIndex];" << endl;
  outf << "  } else {" << endl;
  outf << "    return DYBkgScaleFactorWWPreselectionKappa[jetBin];" << endl;
  
  outf << "  }" << endl;
  outf << "}" << endl;
  outf << endl;

  outf.close();
}
예제 #28
0
파일: Eff3Liq.C 프로젝트: soam5515/Scripts
void Eff3Liq(TH1F * hN=0){

  Double_t x[71]={0.0075000,
		  0.0250000,
		  0.0450000,
		  0.0650000,
		  0.0850000,
		  0.1050000,
		  0.1250000,
		  0.1500000,
		  0.1800000,
		  0.2100000,
		  0.2400000,
		  0.2800000,
		  0.3300000,
		  0.3800000,
		  0.4300000,
		  0.4800000,
		  0.5300000,
		  0.5800000,
		  0.6300000,
		  0.6800000,
		  0.7300000,
		  0.7800000,
		  0.8300000,
		  0.8800000,
		  0.9300000,
		  1.0025000,
		  1.1000000,
		  1.2000000,
		  1.3000000,
		  1.4000000,
		  1.5000000,
		  1.6000000,
		  1.7000000,
		  1.8000000,
		  1.9000000,
		  2.0500000,
		  2.2500000,
		  2.4500000,
		  2.6500000,
		  2.8500000,
		  3.1000000,
		  3.4000000,
		  3.7000000,
		  4.0000000,
		  4.3000000,
		  4.6000000,
		  4.9000000,
		  5.3000000,
		  5.8000000,
		  6.3000000,
		  6.8000000,
		  7.3000000,
		  7.8000000,
		  8.3000000,
		  8.8000000,
		  9.3000000,
		  9.8000000,
		  10.3000000,
		  10.8000000,
		  11.3000000,
		  11.8000000,
		  12.3000000,
		  12.8000000,
		  13.3000000,
		  13.8000000,
		  14.3250000,
		  15.2500000,
		  16.4000000,
		  17.4000000,
		  18.5000000,
		  19.5500000};
  Double_t ex[71] = {0.0075000,
		     0.0100000,
		     0.0100000,
		     0.0100000,
		     0.0100000,
		     0.0100000,
		     0.0100000,
		     0.0150000,
		     0.0150000,
		     0.0150000,
		     0.0150000,
		     0.0250000,
		     0.0250000,
		     0.0250000,
		     0.0250000,
		     0.0250000,
		     0.0250000,
		     0.0250000,
		     0.0250000,
		     0.0250000,
		     0.0250000,
		     0.0250000,
		     0.0250000,
		     0.0250000,
		     0.0250000,
		     0.0475000,
		     0.0500000,
		     0.0500000,
		     0.0500000,
		     0.0500000,
		     0.0500000,
		     0.0500000,
		     0.0500000,
		     0.0500000,
		     0.0500000,
		     0.1000000,
		     0.1000000,
		     0.1000000,
		     0.1000000,
		     0.1000000,
		     0.1500000,
		     0.1500000,
		     0.1500000,
		     0.1500000,
		     0.1500000,
		     0.1500000,
		     0.1500000,
		     0.2500000,
		     0.2500000,
		     0.2500000,
		     0.2500000,
		     0.2500000,
		     0.2500000,
		     0.2500000,
		     0.2500000,
		     0.2500000,
		     0.2500000,
		     0.2500000,
		     0.2500000,
		     0.2500000,
		     0.2500000,
		     0.2500000,
		     0.2500000,
		     0.2500000,
		     0.2500000,
		     0.2750000,
		     0.6500000,
		     0.5000000,
		     0.5000000,
		     0.6000000,
		     0.4500000};
  Double_t y[71] ={5.1405333e-02,
		   9.8349500e-02,
		   1.3175000e-01,
		   1.5643750e-01,
		   1.7663350e-01,
		   1.9363550e-01,
		   2.0850400e-01,
		   2.2458900e-01,
		   2.4100000e-01,
		   2.5523733e-01,
		   2.6748400e-01,
		   2.8124000e-01,
		   2.9507200e-01,
		   3.0641600e-01,
		   3.1503400e-01,
		   3.2242800e-01,
		   3.2723000e-01,
		   3.3126800e-01,
		   3.3392000e-01,
		   3.3561000e-01,
		   3.3608000e-01,
		   3.3571400e-01,
		   3.3533800e-01,
		   3.3394000e-01,
		   3.3184000e-01,
		   3.2844632e-01,
		   3.2205000e-01,
		   3.1490200e-01,
		   3.0596700e-01,
		   2.9673300e-01,
		   2.8734700e-01,
		   2.7704000e-01,
		   2.6658000e-01,
		   2.5612000e-01,
		   2.4566000e-01,
		   2.3020050e-01,
		   2.1007500e-01,
		   1.9050950e-01,
		   1.7230650e-01,
		   1.5540000e-01,
		   1.3587233e-01,
		   1.1480600e-01,
		   9.6560667e-02,
		   8.0777667e-02,
		   6.7334333e-02,
		   5.5928667e-02,
		   4.6381333e-02,
		   3.6111800e-02,
		   2.6234400e-02,
		   1.8971620e-02,
		   1.3666760e-02,
		   9.8124400e-03,
		   7.0360200e-03,
		   5.0407600e-03,
		   3.6132800e-03,
		   2.5885200e-03,
		   1.8538120e-03,
		   1.3248120e-03,
		   9.4736800e-04,
		   6.7701400e-04,
		   4.8375800e-04,
		   3.4512600e-04,
		   2.4605200e-04,
		   1.7495000e-04,
		   1.2437880e-04,
		   8.6900727e-05,
		   4.8199615e-05,
		   2.1518400e-05,
		   1.0859600e-05,
		   5.0966000e-06,
		   2.4220667e-06};
  
  Float_t bins[71];

  bins[0]=x[0]-ex[0];//first bin is left side of bin
  for (int i=1;i<70;i++){
    bins[i] = x[i]-ex[i];
  }
  bins[70]=x[70]+ex[70];//last bin to the right side of last bin

  
  TH1F * Yield=new TH1F("Yield","",70,bins);
  TH1F * eff=new TH1F("eff","",70,bins);
  eff->SetDirectory(0);
  Yield->SetDirectory(0);


  TH1D * N2=new TH1D("N2","",200,0,20);
  for(int i=0;i<71;i++){
    //    cout<<h->GetBinLowEdge(i+1)<<" "<<h->GetBinWidth(i+1)+h->GetBinLowEdge(i+1)<<endl;
    Yield->SetBinContent(i+1,y[i]*Yield->GetBinWidth(i+1));
   }
  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  //  Doule_t thresh =53.73; // 26.3 KeV 
  double fudge =10.0;
  Double_t thresh=0;
  stringstream ss112;
  ss112<<"softwareCFDs[0]>0 &&softwareCFDs[1]>0&&NumOfChannelsInEvent==2 && channels[0]==8 && channels[1]==9 &&longGates[1]/shortGates[1]<1.12&&shortGates[1]>200&&ShiftTOFInternal>1.5&&ShiftTOFInternal<100&&sqrt(energies[0]*energies[1])>"<<thresh;

  
  
  //  flt->Draw("TOFEnergy","channels[0]==0&&softwareCFDs[0]>0&&softwareCFDs[1]>0&&softwareCFDs[2]>0&&NumOfChannelsInEvent==3&&channels[2]==9&&longGates[2]/shortGates[2]<1.12&&ShiftTOF>2")


  cout<<gDirectory->GetName()<<endl;
  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  TFile frun354("~/analysis/run354/CoRFL3FG0d3w0run-0354-tw100-softwareCFD.root");
  TH1D * NWithCubicTimes=new TH1D("NWithCubicTimes","",70,bins);
  TH1D * NWithInternalTimes=new TH1D("NWithInternalTimes","",70,bins);


  //  flt->Project("N","TOFEnergy","ErrorBit==0 && NumOfChannelsInEvent==3 && channels[0]==0 && channels[2]==9 &&PulseShape<1.12&&sqrt(energies[0]*energies[1])>53.73");
  flt->Project("NWithCubicTimes","TOFEnergy",ss112.str().c_str());
  flt->Project("NWithInternalTimes","TOFEnergyInternal",ss112.str().c_str());
  NWithCubicTimes->SetDirectory(0);
  NWithInternalTimes->SetDirectory(0);
  /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  TFile frun354bkg("~/analysis/run354/CoRFL3FG0d3w0run-0354-twrandom1000-softwareCFD.root");
  TH1D * RandomBackGround354WithInternalTimes = new TH1D("RandomBackGround354WithInternalTimes","",70,bins);
  flt->Project("RandomBackGround354WithInternalTimes","TOFEnergyInternal",ss112.str().c_str());

  TH1D * RandomBackGround354WithCubicTimes = new TH1D("RandomBackGround354WithCubicTimes","",70,bins);
  flt->Project("RandomBackGround354WithCubicTimes","TOFEnergy",ss112.str().c_str());

  RandomBackGround354WithInternalTimes->SetDirectory(0);
  RandomBackGround354WithCubicTimes->SetDirectory(0);


  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  TFile frun355("~/analysis/run358/CoRrun-0358-LG17-SG7.root");
  TH1D * ShadowBarRun=new TH1D("ShadowBarRun","",70,bins);
  TH1D * ShadowBarRunInternalTimes=new TH1D("ShadowBarRunInternalTimes","",70,bins);
  
  flt->Project("ShadowBarRun","TOFEnergy",ss112.str().c_str());
  flt->Project("ShadowBarRunInternalTimes","TOFEnergyInternal",ss112.str().c_str());

  ShadowBarRun->SetDirectory(0);
  ShadowBarRunInternalTimes->SetDirectory(0);
  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  TFile frun355bkg("~/analysis/run999/CoRrun-0999-tw1000random-softwareCFD-output.root");
  TH1D * ShadowBarRandomBackGround = new TH1D("ShadowBarRandomBackGround","",70,bins);
  flt->Project("ShadowBarRandomBackGround","TOFEnergy",ss112.str().c_str());
  ShadowBarRandomBackGround->SetDirectory(0);

  TH1D * ShadowBarRandomBackGroundInternal = new TH1D("ShadowBarRandomBackGroundInternal","",70,bins);
  flt->Project("ShadowBarRandomBackGroundInternal","TOFEnergyInternal",ss112.str().c_str());
  ShadowBarRandomBackGroundInternal->SetDirectory(0);

  TH1F * hresult= new TH1F ("hresult","",70,bins);
  TH1F * shadowBarSubtracted= new TH1F ("shadowBarSubtracted","",70,bins);
  TH1F * NSubtracted= new TH1F ("NSubtracted","",70,bins);

  Double_t errors[71];
  Double_t errorsNB[71];
  Double_t errorNsub[71];
  Double_t errorShadowSub[71];

  errors[0]=0;
  errorsNB[0]=0;
  errorNsub[0]=0;
  errorShadowSub[0]=0;

  for (int i=1;i<=70;i++){
    Double_t nV, bkgV, bkg355V, bkg354V;
    //cubicTimes
    /*  
    nV= NWithCubicTimes->GetBinContent(i); //data run
    bkgV=ShadowBarRun->GetBinContent( i);//shadow bar run
    bkg355V =ShadowBarRandomBackGround->GetBinContent(i);//random coin build shadow bar
    bkg354V = RandomBackGround354WithCubicTimes->GetBinContent(i);//random coin build normal run
    
*/
    
    //Internal times
    nV= NWithInternalTimes->GetBinContent(i); //data run
    bkgV=ShadowBarRunInternalTimes->GetBinContent( i);//shadow bar run
    bkg355V =ShadowBarRandomBackGroundInternal->GetBinContent(i);//random coin build shadow bar
    bkg354V = RandomBackGround354WithInternalTimes->GetBinContent(i);//random coin build normal run
    



    hresult->SetBinContent(i,nV -(bkgV-(bkg355V/fudge))-(bkg354V/fudge));
    shadowBarSubtracted->SetBinContent(i,bkgV-(bkg355V/fudge));
    NSubtracted->SetBinContent(i,nV-(bkg354V/fudge));


    errorNsub[i]=sqrt( pow(sqrt(nV),2) + pow(sqrt(bkg354V)/fudge,2));
    errorShadowSub[i]=sqrt( pow(sqrt(bkgV),2)+pow(sqrt(bkg355V)/fudge,2) );
    //    errors[i]=sqrt (pow(sqrt(nV),2) + pow(sqrt(bkg354V),2)+pow(sqrt(bkgV),2) + pow(sqrt(bkg355V),2));
    errors[i]=sqrt( pow(errorNsub[i],2)+pow(errorShadowSub[i],2));
  }

  hresult->SetError(errors);
  NSubtracted->SetError(errorNsub);
  shadowBarSubtracted->SetError(errorShadowSub);
  hresult->SetDirectory(0);

  TH1F * hresultNB= new TH1F ("hresultNB","",70,bins);
  TH1F * shadowBarSubtractedNB= new TH1F ("shadowBarSubtractedNB","",70,bins);
  TH1F * NSubtractedNB= new TH1F ("NSubtractedNB","",70,bins);

  TH1D * NWithCubicTimesNB=new TH1D("NWithCubicTimesNB","",70,bins);
  TH1D * NWithInternalTimesNB=new TH1D("NWithInternalTimesNB","",70,bins);

  TH1D * RandomBackGround354WithInternalTimesNB = new TH1D("RandomBackGround354WithInternalTimesNB","",70,bins);
  TH1D * RandomBackGround354WithCubicTimesNB = new TH1D("RandomBackGround354WithCubicTimesNB","",70,bins);
  
  for (int i=1;i<=70;i++){
    hresultNB->SetBinContent(i,hresult->GetBinContent(i)/(hresult->GetBinWidth(i)));
    errorsNB[i]=errors[i]/(hresult->GetBinWidth(i));

    shadowBarSubtractedNB->SetBinContent(i,shadowBarSubtracted->GetBinContent(i)/(shadowBarSubtracted->GetBinWidth(i)));
    errorShadowSub[i]=errorShadowSub[i]/(shadowBarSubtracted->GetBinWidth(i));

    NSubtractedNB->SetBinContent(i,NSubtracted->GetBinContent(i)/(NSubtracted->GetBinWidth(i)));
    errorNsub[i]=errorNsub[i]/(NSubtracted->GetBinWidth(i));
    
    NWithInternalTimesNB->SetBinContent(i,NWithInternalTimes->GetBinContent(i)/NWithInternalTimes->GetBinWidth(i));
    NWithCubicTimesNB->SetBinContent(i,NWithCubicTimes->GetBinContent(i)/NWithCubicTimes->GetBinWidth(i));

    //    RandomBackGround354WithInternalTimesNB->

  }
  hresultNB->SetError(errorsNB);
  NSubtractedNB->SetError(errorNsub);
  shadowBarSubtractedNB->SetError(errorShadowSub);


  /*
  Int_t numEntries = hN->GetNbinsX();
  
  cout<<"NNNNNN "<<numEntries<<endl;

  Double_t time=0;

  Double_t c= 2.99 * TMath::Power(10,8);

  for (int i=1;i<=numEntries;i++){
    
    time = hN->GetBinCenter(i);
    double shiftTime = time*10.0 -(40.6651-3.3444);
    if (time >3){

      time = shiftTime*(1.0/(TMath::Power(10,9)));// put time in secs

      Double_t beta = (1.0/c)*(1.0/time);
      Double_t gamma = 1.0/(TMath::Sqrt(1-beta*beta));
      Double_t KE = (gamma-1)*939.5650; // MEV
      

      // cout<<"time is "<<time<<endl;
      //	    cout<<"Ke is "<<KE<<endl;
      
      //      int bin= N->GetXaxis()->FindBin((Double_t)KE);
      // N->SetBinContent(bin,);
      int bin =N->FindBin((Double_t)KE);
      N->SetBinContent(bin,hN->GetBinContent(i)+N->GetBinContent(bin));
    }
  }*/

 
  
  for (int i=0;i<71;i++){
    eff->SetBinContent(i+1,Double_t((hresult->GetBinContent(i+1)))/(Yield->GetBinContent(i+1)));
    if (i!=70)
      errors[i+1]=errors[i+1]/Yield->GetBinContent(i+1);

  }
  eff->SetError(errors);
  TCanvas * cC = new TCanvas("c");
  cC->cd(1);
  eff->Draw();

  TFile f("EffoutLiq.root","recreate");
  eff->Write();
  hresult->Write();
  NWithCubicTimes->Write();
  NWithInternalTimes->Write();

  NWithCubicTimesNB->Write();
  NWithInternalTimesNB->Write();

  ShadowBarRun->Write();
  ShadowBarRunInternalTimes->Write();
  ShadowBarRandomBackGround->Write();

  RandomBackGround354WithCubicTimes->Write();
  RandomBackGround354WithInternalTimes->Write();

  shadowBarSubtractedNB->Write();
  NSubtractedNB->Write();
  hresultNB->Write();

  Yield->Write();
  shadowBarSubtracted->Write();
  NSubtracted->Write();

  f.Close();

}
예제 #29
0
void calculateTriggerRates(
			   TString inFile0Name = "root://eoscms//eos/cms/store/caf/user/velicanu/PA2013_merged_HiForest/pPb_hiForest2_pilotRun_200kHz_v3.root",
//         TString inFile0Name = "/castor/cern.ch/user/m/miheejo/openHLT/cms442/r181530_reco_v1_2/HIExpressPhysics_hiexp-hirun2011-r181530-reco-v1_2.root",
//         "/castor/cern.ch/user/k/kimy/openHLT//openhlt_run181531.root",
//         "/castor/cern.ch/user/v/velicanu/HIHLT_Validation_Test_GRIF_v10.root",
			   Int_t runNum        = 202792,
			   TString outdir      = "output",
			   char *projectTitle  = "HIpARun2013",
			   string source       = "data"
			   )
{
  char szBuf[256];
  int scale = 23;


  // event selectoin
  //Form("&&Run==%d&&LumiBlock>%d",runNum,goodLumiStart)
  // trigger under investigation
 //  const int ntrigs = 8;
//   const char* triggerPath[ntrigs] = {"","HLT_HIMinBiasHfOrBSC",
// 				     "L1_SingleMu3_BptxAND","HLT_HIL1SingleMu3","HLT_HIL2Mu3",
// 				     "L1_DoubleMuOpen_BptxAND","HLT_HIL1DoubleMuOpen","HLT_HIL2DoubleMu3"};

  /* const int ntrigs = 9;
  const char* triggerPath[ntrigs] = {
    "",
    "HLT_PAL1SingleMuOpen_v1",
    "HLT_PAL1SingleMu3_v1",
    "HLT_PAL1SingleMu7_v1",
    "HLT_PAL1SingleMu12_v1",
    "HLT_PAL1DoubleMu0_v1",
    "HLT_PADimuon0_NoVertexing_v1",
    "HLT_PAMu5_v1",
    "HLT_PAMu8_v1"
    }; */
  //trigger list for singleMu rate plot
  const int ntrigs = 4 ;
  const char* triggerPath[ntrigs] = {
    "",
    "HLT_PAMu3_v1",
    "HLT_PAMu7_v1",
    "HLT_PAMu12_v1"
  };
  /*
  //trigger list for DoubleMu rate plot
  const int ntrigs = 4 ;
  const char* triggerPath[ntrigs] = {
    "",
    "HLT_PAL1DoubleMuOpen_v1",
    "HLT_PAL1DoubleMu0_HighQ_v1",
    "HLT_PAL2DoubleMu3_v1"
  };
  
  //trigger list fo bJet+Mu rate plot
  const int ntrigs =5;
  const char* triggerPath[ntrigs] = {
    "",
    "HLT_PAMu3PFJet20_v1",
    "HLT_PAMu3PFJet40_v1",
    "HLT_PAMu7PFJet20_v1",
    "HLT_PABTagMu_Jet20_Mu4_v1"    
    };*/
  
  TString str;
  TH1D *ahTemp[ntrigs];
  double ahTempRate[ntrigs];  //Rates (Integrated over lumisections)
  // Load input
  TChain * HltTree = new TChain("hltanalysis/HltTree","HI OpenHLT Tree");
  HltTree->Add(inFile0Name);
  cout << inFile0Name << endl;
  cout << " # entries: " << HltTree->GetEntries() << endl;
  int nEvents = HltTree->GetEntries();
  for(int it=1; it<ntrigs; it++)
  {
    
    TH1D *ph  = new TH1D("ph",";Lumi Section; Counts ",1100,0,1100);
    HltTree->Draw("LumiBlock>>ph",str.Format("%s",triggerPath[it]));
    TLegend *lTemp= new TLegend(0.2,0.8,0.8,0.9);
    lTemp->SetHeader(str.Format("Run : %d",runNum));
    lTemp->SetMargin(0.05);
    lTemp->SetFillStyle(0);
    lTemp->SetLineColor(0);
    lTemp->SetLineWidth(5.0);
    lTemp->SetTextSize(0.03); 
    lTemp->AddEntry(ph,str.Format("%s",triggerPath[it],"l")); 
    lTemp->Draw("same");
    c1->SaveAs(str.Format("%d_%s.pdf",runNum,triggerPath[it]));
    TH1D *phLumi = (TH1D*)gDirectory->Get("ph");
    phLumi->SetDirectory(0);
    phLumi->Scale(1./(phLumi->GetBinWidth(1)*23));// 1lumi unit=23 sec
    ahTempRate[it] = phLumi->Integral()/phLumi->GetNbinsX();
    ahTemp[it] = phLumi;

    cout<< triggerPath[it]<<"\t"<<phLumi->GetEntries()<< "\t" << ahTempRate[it] << endl;
   
  }
     
  //----------------------------
  // drawing part
  // axis
  //  TH1D * phLumiAxis = new TH1D("phLumiAxis",";Lumi Section;dEvt/dLumiSec",1100,0,1100);
  TH1D * phLumiAxis = new TH1D("phLumiAxis",";Lumi Section;Rate [Hz]",1,0,1200);
  phLumiAxis->SetMinimum(0.01);
  phLumiAxis->SetMaximum(1e+3);
  gStyle->SetOptStat(kFALSE);

  // legend
  TLegend *l0= new TLegend(0.2,0.7,0.8,0.9);
  l0->SetHeader(str.Format("Run : %d",runNum));
  l0->SetMargin(0.03);
  l0->SetFillStyle(0);
  l0->SetLineColor(0);
  l0->SetLineWidth(1.0);
  l0->SetTextSize(0.03); 
  
  // canvas
  TCanvas *pcLumi = new TCanvas("pcLumi","pcLumi");
  pcLumi->cd();
  phLumiAxis->Draw();
  pcLumi->SetLogy();
 
  for(int it=1; it<ntrigs; it++)
    {
      TH1 *phLocal = (TH1 *)(ahTemp[it]->Clone("phLocal"));
      phLocal->SetDirectory(0); 
      phLocal->SetLineColor(it);
      if (it >= 10) phLocal->SetLineColor(it+20);
      if(it==5)	phLocal->SetLineColor(kOrange+2);
      phLocal->Draw("same");
      l0->AddEntry(phLocal,str.Format("%s: %.2f Hz",triggerPath[it],ahTempRate[it]),"l");
      pcLumi->Update();
     
    }
  l0->Draw("same");
  pcLumi->SaveAs(str.Format("%d_ratedMu.png",runNum));
}
예제 #30
0
void genAnalysis(
 Int_t period = 1
 ){

  TString filesPath  = "/scratch5/ceballos/ntuples_noweights/";
  Double_t lumi = 0.0715;
  if(period == 1) lumi = 2.2;

  //*******************************************************
  //Input Files
  //*******************************************************
  vector<TString> infilenamev;  
  vector<Int_t> infilecatv;  

  TString puPath = "";
  if      (period==0){
  puPath = "/home/ceballos/cms/cmssw/042/CMSSW_7_4_6/src/MitAnalysisRunII/data/puWeights_13TeV_50ns.root";
  //infilenamev.push_back(Form("%sdata_AOD_50ns.root",filesPath.Data()));														  infilecatv.push_back(0);
  infilenamev.push_back(Form("%sWWTo2L2Nu_13TeV-powheg+RunIISpring15DR74-Asympt50ns_MCRUN2_74_V9A-v2+AODSIM.root",filesPath.Data()));						  infilecatv.push_back(1);
  //infilenamev.push_back(Form("%sDYJetsToLL_M-10to50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8+RunIISpring15DR74-Asympt50ns_MCRUN2_74_V9A-v1+AODSIM.root",filesPath.Data()));	  infilecatv.push_back(2);
  //infilenamev.push_back(Form("%sDYJetsToLL_M-50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8+RunIISpring15DR74-Asympt50ns_MCRUN2_74_V9A-v2+AODSIM.root",filesPath.Data()));  	  infilecatv.push_back(2);
  //infilenamev.push_back(Form("%sTTTo2L2Nu_13TeV-powheg+RunIISpring15DR74-Asympt50ns_MCRUN2_74_V9A-v2+AODSIM.root",filesPath.Data()));						  infilecatv.push_back(3);
  //infilenamev.push_back(Form("%sST_tW_antitop_5f_inclusiveDecays_13TeV-powheg-pythia8_TuneCUETP8M1+RunIISpring15DR74-Asympt50ns_MCRUN2_74_V9A-v2+AODSIM.root",filesPath.Data())); infilecatv.push_back(3);
  //infilenamev.push_back(Form("%sWZ_TuneCUETP8M1_13TeV-pythia8+RunIISpring15DR74-Asympt50ns_MCRUN2_74_V9A-v2+AODSIM.root",filesPath.Data()));					  infilecatv.push_back(4);
  //infilenamev.push_back(Form("%sZZ_TuneCUETP8M1_13TeV-pythia8+RunIISpring15DR74-Asympt50ns_MCRUN2_74_V9A-v2+AODSIM.root",filesPath.Data()));					  infilecatv.push_back(4);
  //infilenamev.push_back(Form("%sWJetsToLNu_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8+RunIISpring15DR74-Asympt50ns_MCRUN2_74_V9A-v1+AODSIM.root",filesPath.Data()));		  infilecatv.push_back(5);
  }
  else if(period==1){
  puPath = "/home/ceballos/cms/cmssw/042/CMSSW_7_4_6/src/MitAnalysisRunII/data/puWeights_13TeV_25ns.root";
  //infilenamev.push_back(Form("%sdata_AOD_25ns.root",filesPath.Data()));														  infilecatv.push_back(0);
  infilenamev.push_back(Form("%sWWTo2L2Nu_13TeV-powheg+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));						  infilecatv.push_back(1);
  //infilenamev.push_back(Form("%sDYJetsToLL_M-10to50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));	  //infilecatv.push_back(2);
  //infilenamev.push_back(Form("%sDYJetsToLL_M-50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v3+AODSIM.root",filesPath.Data()));  	          //infilecatv.push_back(2);
  //infilenamev.push_back(Form("%sTTTo2L2Nu_13TeV-powheg+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));						  infilecatv.push_back(3);
  //infilenamev.push_back(Form("%sST_tW_top_5f_//inclusiveDecays_13TeV-powheg-pythia8_TuneCUETP8M1+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));      //infilecatv.push_back(3);
  //infilenamev.push_back(Form("%sST_tW_antitop_5f_//inclusiveDecays_13TeV-powheg-pythia8_TuneCUETP8M1+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));  //infilecatv.push_back(3);
  //infilenamev.push_back(Form("%sZZTo2L2Nu_13TeV_powheg_pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));					  //infilecatv.push_back(4);
  //infilenamev.push_back(Form("%sZZTo2L2Q_13TeV_amcatnloFXFX_madsp//in_pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));		          //infilecatv.push_back(4);
  //infilenamev.push_back(Form("%sZZTo4L_13TeV_powheg_pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));					  //infilecatv.push_back(4);
  //infilenamev.push_back(Form("%sWZTo1L1Nu2Q_13TeV_amcatnloFXFX_madsp//in_pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));			  //infilecatv.push_back(4);
  //infilenamev.push_back(Form("%sWZTo2L2Q_13TeV_amcatnloFXFX_madsp//in_pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v2+AODSIM.root",filesPath.Data()));			  //infilecatv.push_back(4);
  //infilenamev.push_back(Form("%sWZTo3LNu_TuneCUETP8M1_13TeV-powheg-pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));			  //infilecatv.push_back(4);
  //infilenamev.push_back(Form("%sWZZ_TuneCUETP8M1_13TeV-amcatnlo-pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));				  //infilecatv.push_back(4);
  //infilenamev.push_back(Form("%sTTWJetsToLNu_TuneCUETP8M1_13TeV-amcatnloFXFX-madsp//in-pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));	  //infilecatv.push_back(4);
  //infilenamev.push_back(Form("%sTTWJetsToQQ_TuneCUETP8M1_13TeV-amcatnloFXFX-madsp//in-pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));	  //infilecatv.push_back(4);
  //infilenamev.push_back(Form("%sTTZToLLNuNu_M-10_TuneCUETP8M1_13TeV-amcatnlo-pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));		  //infilecatv.push_back(4);
  //infilenamev.push_back(Form("%sTTZToQQ_TuneCUETP8M1_13TeV-amcatnlo-pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));		          //infilecatv.push_back(4);
  //infilenamev.push_back(Form("%sTTGJets_TuneCUETP8M1_13TeV-amcatnloFXFX-madsp//in-pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));		  //infilecatv.push_back(4);
  //infilenamev.push_back(Form("%sWJetsToLNu_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));		  //infilecatv.push_back(5);
  //infilenamev.push_back(Form("%sWGToLNuG_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));                     //infilecatv.push_back(6);
  //infilenamev.push_back(Form("%sGluGluHToWWTo2L2Nu_M125_13TeV_amcatnloFXFX_pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));		  //infilecatv.push_back(7);
  //infilenamev.push_back(Form("%sVBFHToWWTo2L2Nu_M125_13TeV_powheg_JHUgen_pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));		          //infilecatv.push_back(7);
  //infilenamev.push_back(Form("%sHWm//inusJ_HToWW_M125_13TeV_powheg_pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));		                  //infilecatv.push_back(7);
  //infilenamev.push_back(Form("%sHWplusJ_HToWW_M125_13TeV_powheg_pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));		                  //infilecatv.push_back(7);
  //infilenamev.push_back(Form("%sHZJ_HToWW_M125_13TeV_powheg_pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));		                  //infilecatv.push_back(7);
  //infilenamev.push_back(Form("%sGluGluZH_HToWW_M125_13TeV_powheg_pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));		                  //infilecatv.push_back(7);
  //infilenamev.push_back(Form("%sGluGluHToTauTau_M125_13TeV_powheg_pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));		                  //infilecatv.push_back(7);
  //infilenamev.push_back(Form("%sVBFHToTauTau_M125_13TeV_powheg_pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));		                  //infilecatv.push_back(7);
  //infilenamev.push_back(Form("%sWplusHToTauTau_M125_13TeV_powheg_pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));		                  //infilecatv.push_back(7);
  //infilenamev.push_back(Form("%sWm//inusHToTauTau_M125_13TeV_powheg_pythia8+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));		                  //infilecatv.push_back(7);
  //infilenamev.push_back(Form("%sttHJetToNonbb_M125_13TeV_amcatnloFXFX_madsp//in_pythia8_mWCutfix+RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1+AODSIM.root",filesPath.Data()));      //infilecatv.push_back(7);
  }
  else {assert(0);}
  
  //infilenamev.clear();infilecatv.clear();
  //infilenamev.push_back(Form("/scratch5/ceballos/test/test.root"));   infilecatv.push_back(1);

  if(infilenamev.size() != infilecatv.size()) assert(0);

  Float_t fMVACut[4][4];
  InitializeJetIdCuts(fMVACut);
 
  TFile *fPUFile = TFile::Open(Form("%s",puPath.Data()));
  TH1D *fhDPU = (TH1D*)(fPUFile->Get("puWeights"));
  assert(fhDPU);
  fhDPU->SetDirectory(0);
  delete fPUFile;

  double xmin = 0.0;
  double xmax = 1.0;
  int nBinPlot      = 200;
  double xminPlot   = 0.0;
  double xmaxPlot   = 200.0;
  const int allPlots = 160;
  TH1D* histo[allPlots];

  for(int thePlot=0; thePlot<allPlots; thePlot++){
    if     (thePlot >=  0 && thePlot <= 39) {nBinPlot =  20; xminPlot = 0.0; xmaxPlot = 100.0;}
    else if(thePlot >= 40 && thePlot <= 79) {nBinPlot =   5; xminPlot = 0.0; xmaxPlot =   2.5;}
    else if(thePlot >= 80 && thePlot <= 80) {nBinPlot =   5; xminPlot =-0.5; xmaxPlot =   4.5;}
    else if(thePlot >= 81 && thePlot <= 90) {nBinPlot = 100; xminPlot = 0.0; xmaxPlot =   1.0;}
    else if(thePlot >=100 && thePlot <=109) {nBinPlot =  50; xminPlot = 0.0; xmaxPlot = 100.0;}
    else if(thePlot >=110 && thePlot <=119) {nBinPlot =  50; xminPlot = 0.0; xmaxPlot =   5.0;}
    else if(thePlot >=120 && thePlot <=129) {nBinPlot =  50; xminPlot = 0.0; xmaxPlot = 100.0;}
    else if(thePlot >=130 && thePlot <=139) {nBinPlot =  50; xminPlot = 0.0; xmaxPlot =   5.0;}
    else if(thePlot >=140 && thePlot <=149) {nBinPlot =  50; xminPlot = 0.0; xmaxPlot = 100.0;}
    else if(thePlot >=150 && thePlot <=159) {nBinPlot =  50; xminPlot = 0.0; xmaxPlot =   5.0;}
    TH1D* histos = new TH1D("histos", "histos", nBinPlot, xminPlot, xmaxPlot);
    histos->Sumw2();
    histo[thePlot] = (TH1D*) histos->Clone(Form("histo%d",thePlot));
    histos->Clear();
  }

  //*******************************************************
  // Chain Loop
  //*******************************************************
  for(UInt_t ifile=0; ifile<infilenamev.size(); ifile++) {

    TFile the_input_file(infilenamev[ifile]);
    TTree *the_input_tree = (TTree*)the_input_file.FindObjectAny("events");
    //TTree *the_input_all  = (TTree*)the_input_file.FindObjectAny("all");

    BareEvent eventEvent;
    eventEvent.setBranchAddresses(the_input_tree);

    BareJets eventJets;
    eventJets.setBranchAddresses(the_input_tree);

    BareLeptons eventLeptons;
    eventLeptons.setBranchAddresses(the_input_tree);

    BareTaus eventTaus;
    eventTaus.setBranchAddresses(the_input_tree);

    BareMet eventMet;
    eventMet.SetExtend();
    eventMet.setBranchAddresses(the_input_tree);

    BareTrigger eventTrigger;
    eventTrigger.setBranchAddresses(the_input_tree);

    BareVertex eventVertex;
    eventVertex.setBranchAddresses(the_input_tree);

    BareMonteCarlo eventMonteCarlo;
    eventMonteCarlo.setBranchAddresses(the_input_tree);

    TNamed *triggerNames = (TNamed*)the_input_file.FindObjectAny("triggerNames");
    char **tokens;
    size_t numtokens;
    tokens = strsplit(triggerNames->GetTitle(), ",", &numtokens);
    if(infilecatv[ifile] == 0){
      for (int i = 0; i < (int)numtokens; i++) {
        printf("triggerNames(%2d): \"%s\"\n",(int)i,tokens[i]);
      }
    }
    else {
      printf("sampleNames(%d): %s\n",ifile,infilenamev[ifile].Data());
    }

    double isoCut;
    for (int i=0; i<int(the_input_tree->GetEntries()/1.); ++i) {
      the_input_tree->GetEntry(i);
      if(i%100000==0) printf("event %d out of %d\n",i,(int)the_input_tree->GetEntries());

      double totalWeight = 1;//eventMonteCarlo.mcWeight*lumi;

      vector<bool> isGenDupl; int nGoodGenLeptons = 0;
      for(int ngen0=0; ngen0<eventMonteCarlo.p4->GetEntriesFast(); ngen0++) {
        isGenDupl.push_back(0);
	if(TMath::Abs((int)(*eventMonteCarlo.pdgId)[ngen0]) != 11 &&
	   TMath::Abs((int)(*eventMonteCarlo.pdgId)[ngen0]) != 13) isGenDupl[ngen0] = 1;
	if(TMath::Abs((int)(*eventMonteCarlo.pdgId)[ngen0]) != 11 &&
	   TMath::Abs((int)(*eventMonteCarlo.pdgId)[ngen0]) != 13) continue;
        for(int ngen1=ngen0+1; ngen1<eventMonteCarlo.p4->GetEntriesFast(); ngen1++) {
          if(((TLorentzVector*)(*eventMonteCarlo.p4)[ngen0])->DeltaR(*((TLorentzVector*)(*eventMonteCarlo.p4)[ngen1])) < 0.02) {
	    isGenDupl[ngen0] = 1;
	    break;
	  }
        }
	if(isGenDupl[ngen0] == 0) nGoodGenLeptons++;
      }
      histo[80]->Fill((double)nGoodGenLeptons,totalWeight);
      
      for(int ngen=0; ngen<eventMonteCarlo.p4->GetEntriesFast(); ngen++) {
	if(isGenDupl[ngen] == 1) continue;
        if(((TLorentzVector*)(*eventMonteCarlo.p4)[ngen])->Pt() <= 10) continue;
	if(TMath::Abs(((TLorentzVector*)(*eventMonteCarlo.p4)[ngen])->Eta()) >= 2.5) continue;

	int nCount = 0;
	if(TMath::Abs((int)(*eventMonteCarlo.pdgId)[ngen])==11) nCount = 10;
	histo[nCount+ 0]->Fill(TMath::Min(((TLorentzVector*)(*eventMonteCarlo.p4)[ngen])->Pt(),99.999),totalWeight);
	histo[nCount+40]->Fill(TMath::Abs(((TLorentzVector*)(*eventMonteCarlo.p4)[ngen])->Eta()),totalWeight);

        int whichRecoLepton = -1;
        for(int nlep=0; nlep<eventLeptons.p4->GetEntriesFast(); nlep++) {
          if(TMath::Abs((int)(*eventLeptons.pdgId)[nlep]) == TMath::Abs((int)(*eventMonteCarlo.pdgId)[ngen]) &&
	    ((TLorentzVector*)(*eventLeptons.p4)[nlep])->DeltaR(*((TLorentzVector*)(*eventMonteCarlo.p4)[ngen])) < 0.1) {
	    whichRecoLepton = nlep;
	    break;
	  }
	}
	if(whichRecoLepton >= 0) {
	  if(TMath::Abs((int)(*eventMonteCarlo.pdgId)[ngen])==13) histo[81]->Fill(TMath::Min((double)(*eventLeptons.iso)   [whichRecoLepton]/((TLorentzVector*)(*eventLeptons.p4)[whichRecoLepton])->Pt(),0.999),totalWeight);
	  if(TMath::Abs((int)(*eventMonteCarlo.pdgId)[ngen])==11) histo[82]->Fill(TMath::Min((double)(*eventLeptons.iso)   [whichRecoLepton]/((TLorentzVector*)(*eventLeptons.p4)[whichRecoLepton])->Pt(),0.999),totalWeight);
	  if(TMath::Abs((int)(*eventMonteCarlo.pdgId)[ngen])==13) histo[83]->Fill(TMath::Min((double)(*eventLeptons.chIso) [whichRecoLepton]/((TLorentzVector*)(*eventLeptons.p4)[whichRecoLepton])->Pt(),0.999),totalWeight);
	  if(TMath::Abs((int)(*eventMonteCarlo.pdgId)[ngen])==11) histo[84]->Fill(TMath::Min((double)(*eventLeptons.chIso) [whichRecoLepton]/((TLorentzVector*)(*eventLeptons.p4)[whichRecoLepton])->Pt(),0.999),totalWeight);
	  if(TMath::Abs((int)(*eventMonteCarlo.pdgId)[ngen])==13) histo[85]->Fill(TMath::Min((double)(*eventLeptons.nhIso) [whichRecoLepton]/((TLorentzVector*)(*eventLeptons.p4)[whichRecoLepton])->Pt(),0.999),totalWeight);
	  if(TMath::Abs((int)(*eventMonteCarlo.pdgId)[ngen])==11) histo[86]->Fill(TMath::Min((double)(*eventLeptons.nhIso) [whichRecoLepton]/((TLorentzVector*)(*eventLeptons.p4)[whichRecoLepton])->Pt(),0.999),totalWeight);
	  if(TMath::Abs((int)(*eventMonteCarlo.pdgId)[ngen])==13) histo[87]->Fill(TMath::Min((double)(*eventLeptons.phoIso)[whichRecoLepton]/((TLorentzVector*)(*eventLeptons.p4)[whichRecoLepton])->Pt(),0.999),totalWeight);
	  if(TMath::Abs((int)(*eventMonteCarlo.pdgId)[ngen])==11) histo[88]->Fill(TMath::Min((double)(*eventLeptons.phoIso)[whichRecoLepton]/((TLorentzVector*)(*eventLeptons.p4)[whichRecoLepton])->Pt(),0.999),totalWeight);
	  if(TMath::Abs((int)(*eventMonteCarlo.pdgId)[ngen])==13) histo[89]->Fill(TMath::Min((double)(*eventLeptons.puIso) [whichRecoLepton]/((TLorentzVector*)(*eventLeptons.p4)[whichRecoLepton])->Pt(),0.999),totalWeight);
	  if(TMath::Abs((int)(*eventMonteCarlo.pdgId)[ngen])==11) histo[90]->Fill(TMath::Min((double)(*eventLeptons.puIso) [whichRecoLepton]/((TLorentzVector*)(*eventLeptons.p4)[whichRecoLepton])->Pt(),0.999),totalWeight);

	  if(((int)(*eventLeptons.selBits)[whichRecoLepton] & BareLeptons::LepBaseline) == BareLeptons::LepBaseline) { 
	    histo[nCount+ 1]->Fill(TMath::Min(((TLorentzVector*)(*eventMonteCarlo.p4)[ngen])->Pt(),99.999),totalWeight);
   	    histo[nCount+41]->Fill(TMath::Abs(((TLorentzVector*)(*eventMonteCarlo.p4)[ngen])->Eta()),totalWeight);
	  }

          isoCut = 0.12;
	  if(TMath::Abs((int)(*eventLeptons.pdgId)[whichRecoLepton]) == 11) isoCut = (TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[whichRecoLepton])->Eta()) ? 0.1260 : 0.1440);
	  if(((int)(*eventLeptons.selBits)[whichRecoLepton] & BareLeptons::LepVeto) == BareLeptons::LepVeto 
	  && (double)(*eventLeptons.iso)[whichRecoLepton]/((TLorentzVector*)(*eventLeptons.p4)[whichRecoLepton])->Pt() < isoCut) {
	    histo[nCount+ 2]->Fill(TMath::Min(((TLorentzVector*)(*eventMonteCarlo.p4)[ngen])->Pt(),99.999),totalWeight);
   	    histo[nCount+42]->Fill(TMath::Abs(((TLorentzVector*)(*eventMonteCarlo.p4)[ngen])->Eta()),totalWeight);
	  }

	  if(((int)(*eventLeptons.selBits)[whichRecoLepton] & BareLeptons::LepFake) == BareLeptons::LepFake) {
	    histo[nCount+ 3]->Fill(TMath::Min(((TLorentzVector*)(*eventMonteCarlo.p4)[ngen])->Pt(),99.999),totalWeight);
   	    histo[nCount+43]->Fill(TMath::Abs(((TLorentzVector*)(*eventMonteCarlo.p4)[ngen])->Eta()),totalWeight);
	  }

          isoCut = 0.12;
	  if(TMath::Abs((int)(*eventLeptons.pdgId)[whichRecoLepton]) == 11) isoCut = (TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[whichRecoLepton])->Eta()) ? 0.0893 : 0.1210);
	  if(((int)(*eventLeptons.selBits)[whichRecoLepton] & BareLeptons::LepLoose) == BareLeptons::LepLoose 
	  && (double)(*eventLeptons.iso)[whichRecoLepton]/((TLorentzVector*)(*eventLeptons.p4)[whichRecoLepton])->Pt() < isoCut) {
	    histo[nCount+ 4]->Fill(TMath::Min(((TLorentzVector*)(*eventMonteCarlo.p4)[ngen])->Pt(),99.999),totalWeight);
   	    histo[nCount+44]->Fill(TMath::Abs(((TLorentzVector*)(*eventMonteCarlo.p4)[ngen])->Eta()),totalWeight);
	  }

          isoCut = 0.12;
	  if(TMath::Abs((int)(*eventLeptons.pdgId)[whichRecoLepton]) == 11) isoCut = (TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[whichRecoLepton])->Eta()) ? 0.0766 : 0.0678);
	  if(((int)(*eventLeptons.selBits)[whichRecoLepton] & BareLeptons::LepMedium) == BareLeptons::LepMedium 
	  && (double)(*eventLeptons.iso)[whichRecoLepton]/((TLorentzVector*)(*eventLeptons.p4)[whichRecoLepton])->Pt() < isoCut) {
	    histo[nCount+ 5]->Fill(TMath::Min(((TLorentzVector*)(*eventMonteCarlo.p4)[ngen])->Pt(),99.999),totalWeight);
   	    histo[nCount+45]->Fill(TMath::Abs(((TLorentzVector*)(*eventMonteCarlo.p4)[ngen])->Eta()),totalWeight);
	  }

          isoCut = 0.12;
	  if(TMath::Abs((int)(*eventLeptons.pdgId)[whichRecoLepton]) == 11) isoCut = (TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[whichRecoLepton])->Eta()) ? 0.0354 : 0.0646);
	  if(((int)(*eventLeptons.selBits)[whichRecoLepton] & BareLeptons::LepTight) == BareLeptons::LepTight 
	  && (double)(*eventLeptons.iso)[whichRecoLepton]/((TLorentzVector*)(*eventLeptons.p4)[whichRecoLepton])->Pt() < isoCut) {
	    histo[nCount+ 6]->Fill(TMath::Min(((TLorentzVector*)(*eventMonteCarlo.p4)[ngen])->Pt(),99.999),totalWeight);
   	    histo[nCount+46]->Fill(TMath::Abs(((TLorentzVector*)(*eventMonteCarlo.p4)[ngen])->Eta()),totalWeight);
	  }

	  if(((int)(*eventLeptons.selBits)[whichRecoLepton] & BareLeptons::LepSoftIP) == BareLeptons::LepSoftIP) {
	    histo[nCount+ 7]->Fill(TMath::Min(((TLorentzVector*)(*eventMonteCarlo.p4)[ngen])->Pt(),99.999),totalWeight);
   	    histo[nCount+47]->Fill(TMath::Abs(((TLorentzVector*)(*eventMonteCarlo.p4)[ngen])->Eta()),totalWeight);
	  }

          isoCut = 0.12;
	  if(TMath::Abs((int)(*eventLeptons.pdgId)[whichRecoLepton]) == 11) isoCut = (TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[whichRecoLepton])->Eta()) ? 0.0766 : 0.0678);
	  if(((int)(*eventLeptons.selBits)[whichRecoLepton] & BareLeptons::LepMediumIP) == BareLeptons::LepMediumIP 
	  && (double)(*eventLeptons.iso)[whichRecoLepton]/((TLorentzVector*)(*eventLeptons.p4)[whichRecoLepton])->Pt() < isoCut) {
	    histo[nCount+ 8]->Fill(TMath::Min(((TLorentzVector*)(*eventMonteCarlo.p4)[ngen])->Pt(),99.999),totalWeight);
   	    histo[nCount+48]->Fill(TMath::Abs(((TLorentzVector*)(*eventMonteCarlo.p4)[ngen])->Eta()),totalWeight);
	  }

          isoCut = 0.12;
	  if(TMath::Abs((int)(*eventLeptons.pdgId)[whichRecoLepton]) == 11) isoCut = (TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[whichRecoLepton])->Eta()) ? 0.0354 : 0.0646);
	  if(((int)(*eventLeptons.selBits)[whichRecoLepton] & BareLeptons::LepTightIP) == BareLeptons::LepTightIP 
	  && (double)(*eventLeptons.iso)[whichRecoLepton]/((TLorentzVector*)(*eventLeptons.p4)[whichRecoLepton])->Pt() < isoCut) {
	    histo[nCount+ 9]->Fill(TMath::Min(((TLorentzVector*)(*eventMonteCarlo.p4)[ngen])->Pt(),99.999),totalWeight);
   	    histo[nCount+49]->Fill(TMath::Abs(((TLorentzVector*)(*eventMonteCarlo.p4)[ngen])->Eta()),totalWeight);
	  }
	}
      } // end loop over gen leptons


      for(int nlep=0; nlep<eventLeptons.p4->GetEntriesFast(); nlep++) {
	int nCount = 20;
	if(TMath::Abs((int)(*eventLeptons.pdgId)[nlep])==11) nCount = 30;
        int whichGenLepton = -1;
        for(int ngen=0; ngen<eventMonteCarlo.p4->GetEntriesFast(); ngen++) {
	  if(isGenDupl[ngen] == 1) continue;
          if(((TLorentzVector*)(*eventMonteCarlo.p4)[ngen])->Pt() <= 10) continue;
	  if(TMath::Abs(((TLorentzVector*)(*eventMonteCarlo.p4)[ngen])->Eta()) >= 2.5) continue;
          if(TMath::Abs((int)(*eventLeptons.pdgId)[nlep]) == TMath::Abs((int)(*eventMonteCarlo.pdgId)[ngen]) &&
	    ((TLorentzVector*)(*eventLeptons.p4)[nlep])->DeltaR(*((TLorentzVector*)(*eventMonteCarlo.p4)[ngen])) < 0.1) {
	    whichGenLepton = nlep;
	    break;
	  }
	}

	if(whichGenLepton == -1) {
	  histo[nCount+ 0]->Fill(TMath::Min(((TLorentzVector*)(*eventLeptons.p4)[nlep])->Pt(),99.999),totalWeight);
   	  histo[nCount+40]->Fill(TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[nlep])->Eta()),totalWeight);

	  if(((int)(*eventLeptons.selBits)[nlep] & BareLeptons::LepBaseline) == BareLeptons::LepBaseline) { 
	    histo[nCount+ 1]->Fill(TMath::Min(((TLorentzVector*)(*eventLeptons.p4)[nlep])->Pt(),99.999),totalWeight);
   	    histo[nCount+41]->Fill(TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[nlep])->Eta()),totalWeight);
	  }

          isoCut = 0.12;
	  if(TMath::Abs((int)(*eventLeptons.pdgId)[nlep]) == 11) isoCut = (TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[nlep])->Eta()) ? 0.1260 : 0.1440);
	  if(((int)(*eventLeptons.selBits)[nlep] & BareLeptons::LepVeto) == BareLeptons::LepVeto 
	  && (double)(*eventLeptons.iso)[nlep]/((TLorentzVector*)(*eventLeptons.p4)[nlep])->Pt() < isoCut) {
	    histo[nCount+ 2]->Fill(TMath::Min(((TLorentzVector*)(*eventLeptons.p4)[nlep])->Pt(),99.999),totalWeight);
   	    histo[nCount+42]->Fill(TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[nlep])->Eta()),totalWeight);
	  }

	  if(((int)(*eventLeptons.selBits)[nlep] & BareLeptons::LepFake) == BareLeptons::LepFake) {
	    histo[nCount+ 3]->Fill(TMath::Min(((TLorentzVector*)(*eventLeptons.p4)[nlep])->Pt(),99.999),totalWeight);
   	    histo[nCount+43]->Fill(TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[nlep])->Eta()),totalWeight);
	  }

          isoCut = 0.12;
	  if(TMath::Abs((int)(*eventLeptons.pdgId)[nlep]) == 11) isoCut = (TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[nlep])->Eta()) ? 0.0893 : 0.1210);
	  if(((int)(*eventLeptons.selBits)[nlep] & BareLeptons::LepLoose) == BareLeptons::LepLoose 
	  && (double)(*eventLeptons.iso)[nlep]/((TLorentzVector*)(*eventLeptons.p4)[nlep])->Pt() < isoCut) {
	    histo[nCount+ 4]->Fill(TMath::Min(((TLorentzVector*)(*eventLeptons.p4)[nlep])->Pt(),99.999),totalWeight);
   	    histo[nCount+44]->Fill(TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[nlep])->Eta()),totalWeight);
	  }

          isoCut = 0.12;
	  if(TMath::Abs((int)(*eventLeptons.pdgId)[nlep]) == 11) isoCut = (TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[nlep])->Eta()) ? 0.0766 : 0.0678);
	  if(((int)(*eventLeptons.selBits)[nlep] & BareLeptons::LepMedium) == BareLeptons::LepMedium 
	  && (double)(*eventLeptons.iso)[nlep]/((TLorentzVector*)(*eventLeptons.p4)[nlep])->Pt() < isoCut) {
	    histo[nCount+ 5]->Fill(TMath::Min(((TLorentzVector*)(*eventLeptons.p4)[nlep])->Pt(),99.999),totalWeight);
   	    histo[nCount+45]->Fill(TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[nlep])->Eta()),totalWeight);
	  }

          isoCut = 0.12;
	  if(TMath::Abs((int)(*eventLeptons.pdgId)[nlep]) == 11) isoCut = (TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[nlep])->Eta()) ? 0.0354 : 0.0646);
	  if(((int)(*eventLeptons.selBits)[nlep] & BareLeptons::LepTight) == BareLeptons::LepTight 
	  && (double)(*eventLeptons.iso)[nlep]/((TLorentzVector*)(*eventLeptons.p4)[nlep])->Pt() < isoCut) {
	    histo[nCount+ 6]->Fill(TMath::Min(((TLorentzVector*)(*eventLeptons.p4)[nlep])->Pt(),99.999),totalWeight);
   	    histo[nCount+46]->Fill(TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[nlep])->Eta()),totalWeight);
	  }

	  if(((int)(*eventLeptons.selBits)[nlep] & BareLeptons::LepSoftIP) == BareLeptons::LepSoftIP) {
	    histo[nCount+ 7]->Fill(TMath::Min(((TLorentzVector*)(*eventLeptons.p4)[nlep])->Pt(),99.999),totalWeight);
   	    histo[nCount+47]->Fill(TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[nlep])->Eta()),totalWeight);
	  }

          isoCut = 0.12;
	  if(TMath::Abs((int)(*eventLeptons.pdgId)[nlep]) == 11) isoCut = (TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[nlep])->Eta()) ? 0.0766 : 0.0678);
	  if(((int)(*eventLeptons.selBits)[nlep] & BareLeptons::LepMediumIP) == BareLeptons::LepMediumIP 
	  && (double)(*eventLeptons.iso)[nlep]/((TLorentzVector*)(*eventLeptons.p4)[nlep])->Pt() < isoCut) {
	    histo[nCount+ 8]->Fill(TMath::Min(((TLorentzVector*)(*eventLeptons.p4)[nlep])->Pt(),99.999),totalWeight);
   	    histo[nCount+48]->Fill(TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[nlep])->Eta()),totalWeight);
	  }

          isoCut = 0.12;
	  if(TMath::Abs((int)(*eventLeptons.pdgId)[nlep]) == 11) isoCut = (TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[nlep])->Eta()) ? 0.0354 : 0.0646);
	  if(((int)(*eventLeptons.selBits)[nlep] & BareLeptons::LepTightIP) == BareLeptons::LepTightIP 
	  && (double)(*eventLeptons.iso)[nlep]/((TLorentzVector*)(*eventLeptons.p4)[nlep])->Pt() < isoCut) {
	    histo[nCount+ 9]->Fill(TMath::Min(((TLorentzVector*)(*eventLeptons.p4)[nlep])->Pt(),99.999),totalWeight);
   	    histo[nCount+49]->Fill(TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[nlep])->Eta()),totalWeight);
	  }
	}

      } // end loop over reco leptons

      vector<int> idLep;
      for(int nlep=0; nlep<eventLeptons.p4->GetEntriesFast(); nlep++) {
        if(selectIdIsoCut("medium",TMath::Abs((int)(*eventLeptons.pdgId)[nlep]),TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[nlep])->Pt()),
	   TMath::Abs(((TLorentzVector*)(*eventLeptons.p4)[nlep])->Eta()),(double)(*eventLeptons.iso)[nlep],(int)(*eventLeptons.selBits)[nlep]))
	                                                                                               {idLep.push_back(nlep);}
        else if(((int)(*eventLeptons.selBits)[nlep] & BareLeptons::LepFake)  == BareLeptons::LepFake ) {idLep.push_back(nlep);}
      }

      vector<int> idGenJet;
      for(int ngenj=0; ngenj<eventMonteCarlo.jetP4->GetEntriesFast(); ngenj++) {
        Bool_t isGenLepton = kFALSE;
        for(int ngenl=0; ngenl<eventMonteCarlo.p4->GetEntriesFast(); ngenl++) {
	if(TMath::Abs((int)(*eventMonteCarlo.pdgId)[ngenl]) != 12 &&
	   TMath::Abs((int)(*eventMonteCarlo.pdgId)[ngenl]) != 14 &&
	   TMath::Abs((int)(*eventMonteCarlo.pdgId)[ngenl]) != 16 &&
	   TMath::Abs((int)(*eventMonteCarlo.pdgId)[ngenl]) != 11 &&
	   TMath::Abs((int)(*eventMonteCarlo.pdgId)[ngenl]) != 13) continue;
          if(((TLorentzVector*)(*eventMonteCarlo.jetP4)[ngenj])->DeltaR(*((TLorentzVector*)(*eventMonteCarlo.p4)[ngenl])) < 0.3) isGenLepton = kTRUE;
        }
        if(isGenLepton == kTRUE) continue;
        if(TMath::Abs(((TLorentzVector*)(*eventMonteCarlo.jetP4)[ngenj])->Eta()) >= 5) continue;
        idGenJet.push_back(ngenj);
      }

      vector<int> idJet;
      vector<int> idMVAJet;
      for(int nj=0; nj<eventJets.p4->GetEntriesFast(); nj++){
        if(((TLorentzVector*)(*eventJets.p4)[nj])->Pt() < 10) continue;
        Bool_t isLepton = kFALSE;
        for(unsigned int nl=0; nl<idLep.size(); nl++){
          if(((TLorentzVector*)(*eventJets.p4)[nj])->DeltaR(*((TLorentzVector*)(*eventLeptons.p4)[idLep[nl]])) < 0.3) isLepton = kTRUE;
	}
	if(isLepton == kTRUE) continue;

        if(((TLorentzVector*)(*eventJets.p4)[nj])->Pt() < 30) continue;        
	idJet.push_back(nj);

        bool passId = passJetId(fMVACut, (float)(*eventJets.puId)[nj], ((TLorentzVector*)(*eventJets.p4)[nj])->Pt(), TMath::Abs(((TLorentzVector*)(*eventJets.p4)[nj])->Eta()));
        if(passId == false) continue;        
	idMVAJet.push_back(nj);
      }

      for(unsigned int ngenj=0; ngenj<idGenJet.size(); ngenj++) {
	int nCount = 100;
	if(TMath::Abs(((TLorentzVector*)(*eventMonteCarlo.jetP4)[idGenJet[ngenj]])->Eta()) < 2.5)
	histo[nCount+ 0]->Fill(TMath::Min(((TLorentzVector*)(*eventMonteCarlo.jetP4)[idGenJet[ngenj]])->Pt(),99.999),totalWeight);
	if(((TLorentzVector*)(*eventMonteCarlo.jetP4)[idGenJet[ngenj]])->Pt() > 30)
	histo[nCount+10]->Fill(TMath::Abs(((TLorentzVector*)(*eventMonteCarlo.jetP4)[idGenJet[ngenj]])->Eta()),totalWeight);
	
	bool isRecoJet = kFALSE;
        for(unsigned int nj=0; nj<idJet.size(); nj++){
          if(((TLorentzVector*)(*eventMonteCarlo.jetP4)[idGenJet[ngenj]])->DeltaR(*((TLorentzVector*)(*eventJets.p4)[idJet[nj]])) < 0.4) isRecoJet = kTRUE;
        }
        if(isRecoJet == kTRUE) {
	  if(TMath::Abs(((TLorentzVector*)(*eventMonteCarlo.jetP4)[idGenJet[ngenj]])->Eta()) < 2.5)
	  histo[nCount+ 1]->Fill(TMath::Min(((TLorentzVector*)(*eventMonteCarlo.jetP4)[idGenJet[ngenj]])->Pt(),99.999),totalWeight);
	  if(((TLorentzVector*)(*eventMonteCarlo.jetP4)[idGenJet[ngenj]])->Pt() > 30)
	  histo[nCount+11]->Fill(TMath::Abs(((TLorentzVector*)(*eventMonteCarlo.jetP4)[idGenJet[ngenj]])->Eta()),totalWeight);
	}

        isRecoJet = kFALSE;
        for(unsigned int nj=0; nj<idMVAJet.size(); nj++){
          if(((TLorentzVector*)(*eventMonteCarlo.jetP4)[idGenJet[ngenj]])->DeltaR(*((TLorentzVector*)(*eventJets.p4)[idMVAJet[nj]])) < 0.4) isRecoJet = kTRUE;
        }
        if(isRecoJet == kTRUE) {
	  if(TMath::Abs(((TLorentzVector*)(*eventMonteCarlo.jetP4)[idGenJet[ngenj]])->Eta()) < 2.5)
	  histo[nCount+ 2]->Fill(TMath::Min(((TLorentzVector*)(*eventMonteCarlo.jetP4)[idGenJet[ngenj]])->Pt(),99.999),totalWeight);
	  if(((TLorentzVector*)(*eventMonteCarlo.jetP4)[idGenJet[ngenj]])->Pt() > 30)
	  histo[nCount+12]->Fill(TMath::Abs(((TLorentzVector*)(*eventMonteCarlo.jetP4)[idGenJet[ngenj]])->Eta()),totalWeight);
	}
      }

      for(unsigned int nj=0; nj<idJet.size(); nj++) {
	int nCount = 120;
	if(TMath::Abs(((TLorentzVector*)(*eventJets.p4)[idJet[nj]])->Eta()) < 2.5)
	histo[nCount+ 0]->Fill(TMath::Min(((TLorentzVector*)(*eventJets.p4)[idJet[nj]])->Pt(),99.999),totalWeight);
	if(((TLorentzVector*)(*eventJets.p4)[idJet[nj]])->Pt() > 30)
	histo[nCount+10]->Fill(TMath::Abs(((TLorentzVector*)(*eventJets.p4)[idJet[nj]])->Eta()),totalWeight);
	
	bool isGenJet = kFALSE;
        for(unsigned int ngenj=0; ngenj<idGenJet.size(); ngenj++){
          if(((TLorentzVector*)(*eventJets.p4)[idJet[nj]])->DeltaR(*((TLorentzVector*)(*eventMonteCarlo.jetP4)[idGenJet[ngenj]])) < 0.4) isGenJet = kTRUE;
        }
        if(isGenJet == kFALSE) {
  	  if(TMath::Abs(((TLorentzVector*)(*eventJets.p4)[idJet[nj]])->Eta()) < 2.5)
  	  histo[nCount+ 1]->Fill(TMath::Min(((TLorentzVector*)(*eventJets.p4)[idJet[nj]])->Pt(),99.999),totalWeight);
	  if(((TLorentzVector*)(*eventJets.p4)[idJet[nj]])->Pt() > 30)
	  histo[nCount+11]->Fill(TMath::Abs(((TLorentzVector*)(*eventJets.p4)[idJet[nj]])->Eta()),totalWeight);
	}
      }

      for(unsigned int nj=0; nj<idMVAJet.size(); nj++) {
	int nCount = 140;
        if(TMath::Abs(((TLorentzVector*)(*eventJets.p4)[idMVAJet[nj]])->Eta()) < 2.5)
	histo[nCount+ 0]->Fill(TMath::Min(((TLorentzVector*)(*eventJets.p4)[idMVAJet[nj]])->Pt(),99.999),totalWeight);
	if(((TLorentzVector*)(*eventJets.p4)[idMVAJet[nj]])->Pt() > 30)
	histo[nCount+10]->Fill(TMath::Abs(((TLorentzVector*)(*eventJets.p4)[idMVAJet[nj]])->Eta()),totalWeight);
	
	bool isGenJet = kFALSE;
        for(unsigned int ngenj=0; ngenj<idGenJet.size(); ngenj++){
          if(((TLorentzVector*)(*eventJets.p4)[idMVAJet[nj]])->DeltaR(*((TLorentzVector*)(*eventMonteCarlo.jetP4)[idGenJet[ngenj]])) < 0.4) isGenJet = kTRUE;
        }
        if(isGenJet == kFALSE) {
  	  if(TMath::Abs(((TLorentzVector*)(*eventJets.p4)[idMVAJet[nj]])->Eta()) < 2.5)
  	  histo[nCount+ 1]->Fill(TMath::Min(((TLorentzVector*)(*eventJets.p4)[idMVAJet[nj]])->Pt(),99.999),totalWeight);
	  if(((TLorentzVector*)(*eventJets.p4)[idMVAJet[nj]])->Pt() > 30)
	  histo[nCount+11]->Fill(TMath::Abs(((TLorentzVector*)(*eventJets.p4)[idMVAJet[nj]])->Eta()),totalWeight);
	}
      }
    } // end of loop
  } // end of chain

  for(int np= 1; np<10; np++) histo[np]->Divide(histo[ 0]);
  for(int np=11; np<20; np++) histo[np]->Divide(histo[10]);
  for(int np=21; np<30; np++) histo[np]->Divide(histo[20]);
  for(int np=31; np<40; np++) histo[np]->Divide(histo[30]);
  for(int np=41; np<50; np++) histo[np]->Divide(histo[40]);
  for(int np=51; np<60; np++) histo[np]->Divide(histo[50]);
  for(int np=61; np<70; np++) histo[np]->Divide(histo[60]);
  for(int np=71; np<80; np++) histo[np]->Divide(histo[70]);
  for(int np=80; np<=90; np++) histo[np]->Scale(1./histo[np]->GetSumOfWeights());
  for(int np=101; np<110; np++) histo[np]->Divide(histo[100]);
  for(int np=111; np<120; np++) histo[np]->Divide(histo[110]);
  for(int np=121; np<130; np++) histo[np]->Divide(histo[120]);
  for(int np=131; np<140; np++) histo[np]->Divide(histo[130]);
  for(int np=141; np<150; np++) histo[np]->Divide(histo[140]);
  for(int np=151; np<160; np++) histo[np]->Divide(histo[150]);
  char output[200];
  sprintf(output,"histo_geneff.root");	  
  TFile* outFilePlotsNote = new TFile(output,"recreate");
  outFilePlotsNote->cd();
  for(int np=0; np<160; np++) histo[np]->Write();
  outFilePlotsNote->Close();
}