Пример #1
0
void parallelMergeClient() 
{
   // Client program which creates and fills 2 histograms and a TTree. 
   // Every 1000000 fills the histograms and TTree is send to the server which displays the histogram.
   //
   // To run this demo do the following:
   //   - Open at least 2 windows
   //   - Start ROOT in the first windows
   //   - Execute in the first window: .x fastMergeServer.C
   //   - Execute in the other windows: root.exe -b -l -q .x treeClient.C
   //     (You can put it in the background if wanted).
   // If you want to run the hserv.C on a different host, just change
   // "localhost" in the TSocket ctor below to the desired hostname.
   //
   //Author: Fons Rademakers, Philippe Canal
   
   gBenchmark->Start("treeClient");

   TParallelMergingFile *file = (TParallelMergingFile*)TFile::Open("mergedClient.root?pmerge=localhost:1095","RECREATE");
   
   file->Write();
   file->UploadAndReset();       // We do this early to get assigned an index.
   UInt_t idx = file->fServerIdx; // This works on in ACLiC.

   TH1 *hpx;
   if (idx == 0) {
      // Create the histogram
      hpx = new TH1F("hpx","This is the px distribution",100,-4,4);
      hpx->SetFillColor(48);  // set nice fillcolor
   } else {
      hpx = new TH2F("hpxpy","py vs px",40,-4,4,40,-4,4);
   }
   Float_t px, py;
   TTree *tree = new TTree("tree","tree");
   tree->SetAutoFlush(4000000);
   tree->Branch("px",&px);
   tree->Branch("py",&py);
 
   // Fill histogram randomly
   gRandom->SetSeed();
   const int kUPDATE = 1000000;
   for (int i = 0; i < 25000000; ) {
      gRandom->Rannor(px,py);
      if (idx%2 == 0)
         hpx->Fill(px);
      else
         hpx->Fill(px,py);
      tree->Fill();
      ++i;
      if (i && (i%kUPDATE) == 0) {
         file->Write();
      }
   }
   file->Write();
   delete file;

   gBenchmark->Show("treeClient");
}
Пример #2
0
// PValue for finding a local p-value as observed in 'bin' or worse 
void ToyExperiments::printGlobalPValueOfLocalFluctuation(unsigned int bin, unsigned int nExperiments) const {
  std::cout << "Determining global p-value for observed fluctuation in bin " << bin << " from " << nExperiments << " toy experiments ...  " << std::flush;

  // Find the predicted yields that correspond
  // to the local p-value 'localPValue'
  std::vector<unsigned int> limitYields = yields(localPValue(bin,observedYields_.at(bin)));

  TH1* hIsAbovePValue = new TH1D("hIsAbovePValue","",2,0,2);

  const double minCorr = findMinValidRandomNumberForCorrelatedUncertainties();

  for(unsigned int p = 0; p < nExperiments; ++p) {
    bool isAbovePValue = false;
    double rCorr = rand_->Gaus(0.,1.);
    while( rCorr <= minCorr ) {
      rCorr = rand_->Gaus(0.,1.);
    }
    for(unsigned int b = 0; b < Parameters::nBins(); ++b) {
      double prediction = -1.;
      bool negativePrediction = true;
      while( negativePrediction ) {
	double rUncorr = rand_->Gaus(0.,1.);
	double uncorrVar = rUncorr * uncorrelatedUncerts_.at(b);
	double corrVar   = rCorr   * correlatedUncerts_.at(b);
	prediction = meanPredictions_.at(b) + uncorrVar + corrVar;
	if( prediction >= 0. ) {
	  negativePrediction = false;
	}
      }
      double predictedYield = rand_->Poisson(prediction);
      if( predictedYield >= limitYields.at(b) ) {
	isAbovePValue = true;
	break;
      }      
    }
    if( isAbovePValue ) {
      hIsAbovePValue->Fill(1);
    } else {
      hIsAbovePValue->Fill(0);
    }
  }
  std::cout << "ok" << std::endl;

  double lpv      = localPValue(bin,observedYields_.at(bin));
  double gpUncorr = 1. - pow(1.-lpv,Parameters::nBins());
  double gpCorr   = hIsAbovePValue->Integral(2,2)/hIsAbovePValue->Integral(1,2);

  std::cout << "\n\n----- Global p-value for observed fluctuation in bin " << bin << " -----" << std::endl;
  std::cout << "  local p-value                           : " << lpv << " (" << TMath::NormQuantile(1.-lpv) << "sig)" << std::endl;
  std::cout << "  global p-value (without correlations)   : " << gpUncorr  << " (" << TMath::NormQuantile(1.-gpUncorr) << "sig)" << std::endl;
  std::cout << "  global p-value (including correlations) : " << gpCorr  << " (" << TMath::NormQuantile(1.-gpCorr) << "sig)" << std::endl;
}
TH1* fillHistogram(TTree* testTree, const std::string& varName, const std::string& selection, const std::string& frWeightName,
		   const std::string& histogramName, unsigned numBinsX, double xMin, double xMax)
{
  std::cout << "<fillHistogram>:" << std::endl;
  std::cout << " testTree = " << testTree << std::endl;
  std::cout << " varName = " << varName << std::endl;
  std::cout << " selection = " << selection << std::endl;
  std::cout << " frWeightName = " << frWeightName << std::endl;
  std::cout << " histogramName = " << histogramName << std::endl;

  TH1* histogram = new TH1F(histogramName.data(), histogramName.data(), numBinsX, xMin, xMax);
  histogram->Sumw2();

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

  TTree* selTree = ( selection != "" ) ? testTree->CopyTree(selection.data()) : testTree;
  std::cout << " selTree = " << selTree << std::endl;

  Float_t eventWeight = 1.;
  selTree->SetBranchAddress("weight", &eventWeight);

  Float_t var = 0.;
  selTree->SetBranchAddress(varName.data(), &var);
  
  Float_t frWeight = 1.;
  if ( frWeightName != "" ) {
    std::cout << "--> setting branch-address of fake-rate weight..." << std::endl;
    selTree->SetBranchAddress(frWeightName.data(), &frWeight);
  }

  int numEntries = selTree->GetEntries();
  std::cout << "--> numEntries = " << numEntries << std::endl;
  //if ( maxEntriesToProcess != -1 ) numEntries = TMath::Min(numEntries, maxEntriesToProcess);
  for ( int iEntry = 0 ; iEntry < numEntries; ++iEntry ) {
    selTree->GetEvent(iEntry);  

    //std::cout << "iEntry = " << iEntry << ": var = " << var << ", frWeight = " << frWeight << std::endl;

    if ( frWeightName != "" ) {
      if ( TMath::Abs(frWeight) < 1. ) // some entries have weight O(-100)
                                       // --> indication of technical problem with k-NearestNeighbour tree ?
	histogram->Fill(var, frWeight*eventWeight);
    } else {
      histogram->Fill(var, eventWeight);
    }
  }

  delete dummyOutputFile;

  return histogram;
}
Пример #4
0
int main (int argc, char *argv[])
{ 
	LineStream ls;
	char *line;
	char *pos;
	Stringa buffer;

	if (argc != 2) {
		usage ("%s <file.intraOffsets>");
	}

	TH1 *his = new TH1D ("","Intra-read distribution",1000,0,1000);
	TCanvas *canv = new TCanvas("","canvas",1200,400);
	ls = ls_createFromFile (argv[1]);
	while (line = ls_nextLine (ls)) {
		his->Fill (atoi (line));
	}
	ls_destroy (ls);
	his->Draw();
	his->GetXaxis()->SetLabelSize (0.04);
	his->GetYaxis()->SetLabelSize (0.04);
	buffer = stringCreate (100);
	pos = strchr (argv[1],'.');
	if (pos == NULL) {
		die ("Expected <file.intraOffsets>: %s",argv[1]);
	}
	*pos = '\0';
	stringPrintf (buffer,"%s_intraDistribution.jpg",argv[1]);
	canv->Print (string (buffer),"jpg");
	stringDestroy (buffer);
	return 0;
}
Пример #5
0
void Kin2Txt() {
  AliRunLoader* rl = AliRunLoader::Open("galice.root");
  rl->LoadKinematics();
  rl->LoadHeader();

  TH1* hM  = new TH1D("hM",  "TreeK;M#(){#pi^{+}#pi^{-}} #(){GeV/#it{c}^{2}}", 100, 0., 2.);
  TH1* hPt = new TH1D("hPt", "TreeK;P_{T}#(){#pi^{+}#pi^{-}} #(){GeV/#it{c}}", 100, 0., 1.);
  TH1* hY  = new TH1D("hY",  "TreeK;Y#(){#pi^{+}#pi^{-}}",                     160,-8., 8.);
  std::ofstream ofs("rho0.txt");
  
  AliStack *stack = NULL;
  TParticle *part = NULL;
  TLorentzVector v[2], vSum;
  for (Int_t i=0, n(rl->GetNumberOfEvents()); i<n; ++i) {
    rl->GetEvent(i);
    stack = rl->Stack();

    Int_t nPrimary(0);
    for (Int_t j(0), m(stack->GetNtrack()); j<m; ++j) {
      part = stack->Particle(j);
      if (part->IsPrimary())
	part->Momentum(v[nPrimary++]);
    }
    if (nPrimary != 2) {
      Printf("Error: nPrimary=%d != 2", nPrimary);
      continue;
    }
    vSum = v[0] + v[1];
    hM->Fill(vSum.M());
    hPt->Fill(vSum.Perp());
    hY->Fill(vSum.Rapidity());
    ofs << std::fixed << std::setprecision(4)
	<< vSum.M() << " " << vSum.Perp() << " " << vSum.Rapidity() << " "
	<< v[0].Eta() << " " << v[0].Px() << " " << v[0].Py() << " " << v[0].Pz() << " "
	<< v[1].Eta() << " " << v[1].Px() << " " << v[1].Py() << " " << v[1].Pz()
	<< std::endl;
  }
  hM->Draw();
  c1->SaveAs("TreeK.pdf(");
  hPt->Draw();
  c1->SaveAs("TreeK.pdf");
  hY->Draw();
  c1->SaveAs("TreeK.pdf)");
}
Пример #6
0
void analyzer()
{

  TString processName = "ZJets";

  TFile* f = TFile::Open(Form("hist_%s.root", processName.Data()), "recreate");

  // Create chain of root trees
  TChain chain("DelphesMA5tune");
  //kisti
  //chain.Add("/cms/home/tjkim/fcnc/sample/ZToLL50-0Jet_sm-no_masses/events_*.root");
  //hep
  chain.Add("/Users/tjkim/Work/fcnc/samples/ZToLL50-0Jet_sm-no_masses/events_*.root");  

  // Create object of class ExRootTreeReader
  ExRootTreeReader *treeReader = new ExRootTreeReader(&chain);
  Long64_t numberOfEntries = treeReader->GetEntries();
  
  // Get pointers to branches used in this analysis
  TClonesArray *branchMuon = treeReader->UseBranch("DelphesMA5tuneMuon");
  
  // Book histograms
  TH1 *histDiMuonMass = new TH1F("dimuon_mass","Di-Muon Invariant Mass (GeV)",100, 50, 150);
 
  // Loop over all events

  for(Int_t entry = 0; entry < numberOfEntries; ++entry)
  {
    // Load selected branches with data from specified event
    treeReader->ReadEntry(entry);
 
    int nmuon = 0; 
    for( int i = 0; i < branchMuon->GetEntries(); i++)
    {
      Muon *muon = (Muon*) branchMuon->At(i);
      if( muon->PT <= 20 || abs(muon->Eta) >= 2.4 ) continue;
      nmuon = nmuon + 1 ;
    }

    if( nmuon >= 2){

      Muon *mu1 = (Muon*) branchMuon->At(0);
      Muon *mu2 = (Muon*) branchMuon->At(1);

      // Plot di-muon invariant mass 
      histDiMuonMass->Fill(((mu1->P4()) + (mu2->P4())).M());
    }
 
  }

  // Show resulting histograms
  histDiMuonMass->Write();

  f->Close();

}
Пример #7
0
void testTDime(Int_t nev = 100) {

  gSystem->Load("libEVGEN");
  gSystem->Load("libTDime");
  gSystem->Load("libdime");

  TDime* dime = new TDime();
  dime->SetEnergyCMS(7000.0);
  dime->SetYRange(-2.0, 2.0);   // Set rapidity range of mesons
  dime->SetMinPt(0.1);          // Minimum pT of mesons
  dime->Initialize();

  // (pi+pi-) histograms
  TH1* hM = new TH1D("hM", "DIME #pi^{+}#pi^{-};M_{#pi^{+}#pi^{-}} #[]{GeV/#it{c}^{2}}", 100,  0.0, 5.0);

  TClonesArray* particles = new TClonesArray("TParticle", 6);
  TParticle* part = NULL;
  TLorentzVector v[2];
  TLorentzVector vSum;

  // Event loop
  for (Int_t i = 0; i < nev; ++i) {

    dime->GenerateEvent();
    Int_t np = dime->ImportParticles(particles, "All");
    printf("\n DIME Event %d: Imported %3d particles \n", i, np);

    Int_t nPrimary = 0;

    // Loop over pion (j = 4,5) tracks
    for (Int_t j = 4; j < 6; ++j) {
      part = (TParticle*) particles->At(j); // Choose the particle
      part->Print();
      part->Momentum(v[nPrimary]);          // Copy content to v
      nPrimary++;
    }
    //particles.Clear();

    // 4-vector sum
    vSum = v[0] + v[1];

    // Fill pi+pi- histograms
    hM->Fill(vSum.M());
  }

  // Save plots as pdf
  hM->Draw();    c1->SaveAs("massTDime.pdf");

}
    void fill(const NTupleReader& tr, const double weight)
        {
            const int& nSearchBin            = tr.getVar<int>("nSearchBin");
            const double& met                = tr.getVar<double>("met");
            const double& best_had_brJet_MT2 = tr.getVar<double>("best_had_brJet_MT2");
            const int& cntCSVS               = tr.getVar<int>("cntCSVS");
            const int& nTopCandSortedCnt     = tr.getVar<int>("nTopCandSortedCnt");
            const bool& passBaseline         = tr.getVar<bool>("passBaseline");

            met_->Fill(met, weight);
            mt2_->Fill(best_had_brJet_MT2, weight);
            nt_->Fill(nTopCandSortedCnt, weight);
            nb_->Fill(cntCSVS, weight);

            if(passBaseline)
            {
                baseline_met_->Fill(met, weight);
                baseline_mt2_->Fill(best_had_brJet_MT2, weight);
                baseline_nt_->Fill(nTopCandSortedCnt, weight);
                baseline_nb_->Fill(cntCSVS, weight);

                baseline_nSearchBin_->Fill(nSearchBin, weight);
            }
        }
Пример #9
0
void TTimeHists::Fill(EHist hist)
{
   for (Long_t n = 0; n < fNum; ++n) {
      NextValues();
      if (fgDebug > 1) {
         printf("%ld: fill %s", n, hist == kHist? (fDim < 4 ? "hist" : "arr") : "sparse");
         for (Int_t d = 0; d < fDim; ++d)
            printf("[%g]", fValue[d]);
         printf("\n");
      }
      if (hist == kHist) {
         switch (fDim) {
         case 1: fHist->Fill(fValue[0]); break;
         case 2: ((TH2F*)fHist)->Fill(fValue[0], fValue[1]); break;
         case 3: ((TH3F*)fHist)->Fill(fValue[0], fValue[1], fValue[2]); break;
         default: fHn->Fill(fValue); break;
         }
      } else {
         fSparse->Fill(fValue);
      }
   }
}
Пример #10
0
void ConnectToServer(const TInetAddress *hostb, Int_t port)
{
   // Called by the Bonjour resolver with the host and port to which
   // we can connect.

   // Connect only once...
   TBonjourResolver *resolver = (TBonjourResolver*) gTQSender;
   TInetAddress host = *hostb; 
   delete resolver;

   printf("ConnectToServer: host = %s, port = %d\n", host.GetHostName(), port);

   //--- Here starts original hclient.C code ---

   // Open connection to server
   TSocket *sock = new TSocket(host.GetHostName(), port);

   // Wait till we get the start message
   char str[32];
   sock->Recv(str, 32);

   // server tells us who we are
   int idx = !strcmp(str, "go 0") ? 0 : 1;

   Float_t messlen  = 0;
   Float_t cmesslen = 0;
   if (idx == 1)
      sock->SetCompressionLevel(1);

   TH1 *hpx;
   if (idx == 0) {
      // Create the histogram
      hpx = new TH1F("hpx","This is the px distribution",100,-4,4);
      hpx->SetFillColor(48);  // set nice fillcolor
   } else {
      hpx = new TH2F("hpxpy","py vs px",40,-4,4,40,-4,4);
   }

   TMessage::EnableSchemaEvolutionForAll(gEvo);
   TMessage mess(kMESS_OBJECT);
   //TMessage mess(kMESS_OBJECT | kMESS_ACK);

   // Fill histogram randomly
   gRandom->SetSeed();
   Float_t px, py;
   const int kUPDATE = 1000;
   for (int i = 0; i < 25000; i++) {
      gRandom->Rannor(px,py);
      if (idx == 0)
         hpx->Fill(px);
      else
         hpx->Fill(px,py);
      if (i && (i%kUPDATE) == 0) {
         mess.Reset();              // re-use TMessage object
         mess.WriteObject(hpx);     // write object in message buffer
         sock->Send(mess);          // send message
         messlen  += mess.Length();
         cmesslen += mess.CompLength();
      }
   }
   sock->Send("Finished");          // tell server we are finished

   if (cmesslen > 0)
      printf("Average compression ratio: %g\n", messlen/cmesslen);

   gBenchmark->Show("hclient");

   // Close the socket
   sock->Close();
}
Пример #11
0
bool TauAnalysisSelector::process(Long64_t entry) {
  double weight = 1.0;
  if(!fPuWeightName.empty()) {
    weight *= fPuWeight->value();
  }
  fEventCounter.setWeight(weight);

  cAll.increment();

  if(fIsEmbedded) {
    weight *= fGeneratorWeight->value();
    fEventCounter.setWeight(weight);
  }
  cGeneratorWeight.increment();

  /*
  std::cout << "FOO Event " << fEventInfo.event() << ":" << fEventInfo.lumi() << ":" << fEventInfo.run()
            << " electronVeto passed? " << fElectronVetoPassed->value()
            << std::endl;

  if( (fEventInfo.event() == 10069461 && fEventInfo.lumi() == 33572) ||
      (fEventInfo.event() == 10086951 && fEventInfo.lumi() == 33630) ||
      (fEventInfo.event() == 101065527 && fEventInfo.lumi() == 336953) ||
      (fEventInfo.event() == 101450418 && fEventInfo.lumi() == 338236) ||
      (fEventInfo.event() == 101460111 && fEventInfo.lumi() == 338268) ) {
    std::cout << "BAR Event " << fEventInfo.event() << ":" << fEventInfo.lumi() << ":" << fEventInfo.run()
              << " electronVeto passed? " << fElectronVetoPassed->value()
              << " Nelectrons " << fElectrons.size()
              << std::endl;
    for(size_t i=0; i<fElectrons.size(); ++i) {
      ElectronCollection::Electron electron = fElectrons.get(i);
      std::cout << "  Electron " << i
                << " pt " << electron.p4().Pt()
                << " eta " << electron.p4().Eta()
                << " hasGsfTrack " << electron.hasGsfTrack()
                << " hasSuperCluster " << electron.hasSuperCluster()
                << " supercluster eta " << electron.superClusterEta()
                << " passIdVeto " << electron.cutBasedIdVeto()
                << std::endl;
    }
  }

  if(!fElectronVetoPassed->value()) return false;
  cElectronVeto.increment();
  */

  // Tau BR
  if(fIsEmbedded && fEmbeddingNormalizationMode == kIDTriggerEfficiencyTauBR) {
    weight *= (1-0.357); // from my thesis, which took the numbers from PDG
    fEventCounter.setWeight(weight);
  }
  cTauBRWeight.increment();

  // MC status
  std::vector<GenParticleCollection::GenParticle> genTaus;
  GenParticleCollection::GenParticle theGenTau;
  if(isMC()) {
    bool canContinue = true;
    if(fIsEmbedded) {
      canContinue = findGenTaus(fGenTausEmbedded, 2212, &genTaus);
      canContinue = canContinue && genTaus.size() != 0;
    }
    else
      canContinue = findGenTaus(fGenTaus, 6, &genTaus);
    if(!canContinue)
      return false;
  }
  cGenTauFound.increment();
  if(isMC() && fMCTauMultiplicity != kMCTauNone) {
    size_t ntaus = genTaus.size();
    if(fIsEmbedded) {
      std::vector<GenParticleCollection::GenParticle> genTausOrig;
      findGenTaus(fGenTaus, 6, &genTausOrig);
      ntaus = genTausOrig.size();
    }

    if(fIsEmbedded) {
      // For embedded the embedded tau is counted as one
      if(fMCTauMultiplicity == kMCTauZeroTaus) return true;
      if(fMCTauMultiplicity == kMCTauOneTau && ntaus != 0) return true;
      if(fMCTauMultiplicity == kMCTauTwoTaus && ntaus != 1) return true;
      if(fMCTauMultiplicity == kMCTauMoreThanTwoTaus && ntaus < 2) return true;
    }
    else {
      if(fMCTauMultiplicity == kMCTauZeroTaus && ntaus != 0) return true;
      if(fMCTauMultiplicity == kMCTauOneTau && ntaus != 1) return true;
      if(fMCTauMultiplicity == kMCTauTwoTaus && ntaus != 2) return true;
      if(fMCTauMultiplicity == kMCTauMoreThanTwoTaus && ntaus < 3) return true;
    }
   
    if(genTaus.size() > 0)
      theGenTau = genTaus[0];
  }
  cTauMCSelection.increment();

  bool originalMuonIsWMu = false;
  EmbeddingMuonCollection::Muon embeddingMuon;
  if(fIsEmbedded) {
    if(fMuons.size() != 1)
      throw std::runtime_error("Embedding muon collection size is not 1");
    embeddingMuon = fMuons.get(0);
    if(embeddingMuon.p4().Pt() < 41) return true;
    //std::cout << "Muon pt " << muon.p4().Pt() << std::endl;

    originalMuonIsWMu = std::abs(embeddingMuon.pdgId()) == 13 && std::abs(embeddingMuon.motherPdgId()) == 24 && std::abs(embeddingMuon.grandMotherPdgId()) == 6;
    if(!originalMuonIsWMu) return true;
  }

  cOnlyWMu.increment();

  // Per-event correction for W->tau->mu
  if(fIsEmbedded && fEmbeddingWTauMuWeights) {
    embeddingMuon.ensureValidity();
    int bin = fEmbeddingWTauMuWeights->FindBin(embeddingMuon.p4().Pt());
    //std::cout << embeddingMuon.p4().Pt() << " " << bin << std::endl;
    weight *= fEmbeddingWTauMuWeights->GetBinContent(bin);
    fEventCounter.setWeight(weight);
  }
  cWTauMuWeight.increment();

  // Muon trigger efficiency weighting
  if(fIsEmbedded && (fEmbeddingNormalizationMode == kIDTriggerEfficiency || fEmbeddingNormalizationMode == kIDTriggerEfficiencyTauBR)) {
    weight *= 1/embeddingMuon.triggerEfficiency();
    fEventCounter.setWeight(weight);
  }
  cTriggerEffWeight.increment();

  // Muon ID efficiency weighting
  if(fIsEmbedded) {
    weight *= 1/embeddingMuon.idEfficiency();
    fEventCounter.setWeight(weight);
  }
  cIdEffWeight.increment();

  // Weighting by arbitrary histogram, given in constructor argument
  if(fIsEmbedded && fEmbeddingMuonWeights) {
    embeddingMuon.ensureValidity();
    int bin = fEmbeddingMuonWeights->FindFixBin(embeddingMuon.p4().Pt());
    weight *= fEmbeddingMuonWeights->GetBinContent(bin);
    fEventCounter.setWeight(weight);
  }
  cMuonWeight.increment();

  // Jet selection
  /*
  size_t njets = fJets.size();
  size_t nselectedjets = 0;
  for(size_t i=0; i<njets; ++i) {
    JetCollection::Jet jet = fJets.get(i);

    // Clean selected muon from jet collection
    bool matches = false;
    double DR = ROOT::Math::VectorUtil::DeltaR(fMuons.get(0).p4(), jet.p4());
    if(DR < 0.1) {
      matches = true;
    }
    if(matches) continue;

    // Count jets
    ++nselectedjets;
  }
  if(nselectedjets < 3) return true;
  */
  cJetSelection.increment();

  if(fSelectedVertexCount->value() <= 0) return true;
  cPrimaryVertex.increment();

  std::vector<TauCollection::Tau> selectedTaus;
  std::vector<TauCollection::Tau> tmp;

  if(fTaus.size() < 1) return true;
  cAllTauCandidates.increment();

  // Pre pT cut (for some reason in the region pT < 10 there is significantly more normal than embedded)
  for(size_t i=0; i<fTaus.size(); ++i) {
    TauCollection::Tau tau = fTaus.get(i);
    if(tau.p4().Pt() < 10) continue;
    if(!TauID::isolation(tau)) continue;
    //if(isMC() && !fIsEmbedded && tau.genMatchP4().Pt() <= 41) continue; // temporary hack
    selectedTaus.push_back(tau);
    if(!fIsEmbedded) break; // select only the first gen tau
  }
  if(selectedTaus.empty()) return true;
  cPrePtCut.increment();

  // Decay mode finding
  bool atLeastOneIsolated = false;
  for(size_t i=0; i<selectedTaus.size(); ++i) {
    TauCollection::Tau& tau = selectedTaus[i];
    if(!TauID::decayModeFinding(tau)) continue;

    if(TauID::isolation(tau)) {
      atLeastOneIsolated = true;
      hTau_AfterDecayModeFindingIsolation.fill(tau.p4(), weight);
    }
    tmp.push_back(tau);
  }
  selectedTaus.swap(tmp);
  tmp.clear();
  if(selectedTaus.empty()) return true;
  cDecayModeFinding.increment();
  if(atLeastOneIsolated) {
    if(theGenTau.isValid()) hGenTau_AfterDecayModeFindingIsolation.fill(theGenTau.p4(), weight);
    hVertexCount_AfterDecayModeFindingIsolation->Fill(fVertexCount->value(), weight);
  }

  // Eta cut
  atLeastOneIsolated = false;
  for(size_t i=0; i<selectedTaus.size(); ++i) {
    TauCollection::Tau& tau = selectedTaus[i];
    if(!TauID::eta(tau)) continue;

    if(TauID::isolation(tau)) {
      atLeastOneIsolated = true;
      hTau_AfterEtaCutIsolation.fill(tau.p4(), weight);
    }
    tmp.push_back(tau);
  }
  selectedTaus.swap(tmp);
  tmp.clear();
  if(selectedTaus.empty()) return true;
  cEtaCut.increment();
  if(atLeastOneIsolated) {
    hGenTau_AfterEtaCutIsolation.fill(theGenTau.p4(), weight);
    hVertexCount_AfterEtaCutIsolation->Fill(fVertexCount->value(), weight);
  }

  // Pt cut
  atLeastOneIsolated = false;
  for(size_t i=0; i<selectedTaus.size(); ++i) {
    TauCollection::Tau& tau = selectedTaus[i];
    if(!TauID::pt(tau)) continue;

    if(TauID::isolation(tau)) {
      atLeastOneIsolated = true;
      hTau_AfterPtCutIsolation.fill(tau.p4(), weight);
      hTauLeadingTrackPt_AfterPtCutIsolation->Fill(tau.leadPFChargedHadrCandP4().Pt(), weight);
    }
    tmp.push_back(tau);
  }
  selectedTaus.swap(tmp);
  tmp.clear();
  if(selectedTaus.empty()) return true;
  cPtCut.increment();
  if(atLeastOneIsolated) {
    hGenTau_AfterPtCutIsolation.fill(theGenTau.p4(), weight);
    hVertexCount_AfterPtCutIsolation->Fill(fVertexCount->value(), weight);
  }

  // Leading track pt
  atLeastOneIsolated = false;
  for(size_t i=0; i<selectedTaus.size(); ++i) {
    TauCollection::Tau& tau = selectedTaus[i];
    if(!TauID::leadingChargedHadrCandPt(tau)) continue;
    tmp.push_back(tau);

    if(TauID::isolation(tau)) {
      atLeastOneIsolated = true;
      hTau_AfterLeadingTrackPtCutIsolation.fill(tau.p4(), weight);
    }
  }
  selectedTaus.swap(tmp);
  tmp.clear();
  if(selectedTaus.empty()) return true;
  cLeadingTrackPtCut.increment();
  if(atLeastOneIsolated) {
    hGenTau_AfterLeadingTrackPtCutIsolation.fill(theGenTau.p4(), weight);
  }

  // ECAL fiducial cuts
  for(size_t i=0; i<selectedTaus.size(); ++i) {
    TauCollection::Tau& tau = selectedTaus[i];
    if(!TauID::ecalCracks(tau)) continue;
    tmp.push_back(tau);
  }
  selectedTaus.swap(tmp);
  tmp.clear();
  if(selectedTaus.empty()) return true;
  cEcalCracks.increment();

  for(size_t i=0; i<selectedTaus.size(); ++i) {
    TauCollection::Tau& tau = selectedTaus[i];
    if(!TauID::ecalGap(tau)) continue;
    tmp.push_back(tau);
  }
  selectedTaus.swap(tmp);
  tmp.clear();
  if(selectedTaus.empty()) return true;
  cEcalGap.increment();
  

  // Against electron
  atLeastOneIsolated = false;
  for(size_t i=0; i<selectedTaus.size(); ++i) {
    TauCollection::Tau& tau = selectedTaus[i];
    if(!TauID::againstElectron(tau)) continue;
    tmp.push_back(tau);

    if(TauID::isolation(tau)) {
      atLeastOneIsolated = true;
      hTau_AfterAgainstElectronIsolation.fill(tau.p4(), weight);
    }
  }
  selectedTaus.swap(tmp);
  tmp.clear();
  if(selectedTaus.empty()) return true;
  cAgainstElectron.increment();
  if(atLeastOneIsolated) {
    hGenTau_AfterAgainstElectronIsolation.fill(theGenTau.p4(), weight);
  }

  // Against muon
  atLeastOneIsolated = false;
  for(size_t i=0; i<selectedTaus.size(); ++i) {
    TauCollection::Tau& tau = selectedTaus[i];
    if(!TauID::againstMuon(tau)) continue;
    tmp.push_back(tau);

    if(TauID::isolation(tau)) {
      atLeastOneIsolated = true;
      hTau_AfterAgainstMuonIsolation.fill(tau.p4(), weight);
    }
  }
  selectedTaus.swap(tmp);
  tmp.clear();
  if(selectedTaus.empty()) return true;
  cAgainstMuon.increment();
  if(atLeastOneIsolated) {
    hGenTau_AfterAgainstMuonIsolation.fill(theGenTau.p4(), weight);
  }

  // Tau candidate selection finished

  // Isolation
  for(size_t i=0; i<selectedTaus.size(); ++i) {
    TauCollection::Tau& tau = selectedTaus[i];

    if(!TauID::isolation(tau)) continue;

    int decayMode = tau.decayMode();
    int fill = -1;
    if     (decayMode <= 2)  fill = decayMode; // 0 = pi+, 1 = pi+pi0, 2 = pi+pi0pi0
    else if(decayMode == 10) fill = 3; // pi+pi-pi+
    else                     fill = 4; // Other

    hTau_AfterIsolation.fill(tau.p4(), weight);
    hTauDecayModeAll_AfterIsolation->Fill(decayMode, weight);
    hTauDecayMode_AfterIsolation->Fill(fill, weight);

    tmp.push_back(tau);
  }
  selectedTaus.swap(tmp);
  tmp.clear();
  if(selectedTaus.empty()) return true;
  cIsolation.increment();
  hVertexCount_AfterIsolation->Fill(fVertexCount->value(), weight);
  if(theGenTau.isValid()) hGenTau_AfterIsolation.fill(theGenTau.p4(), weight);

  // One prong
  for(size_t i=0; i<selectedTaus.size(); ++i) {
    TauCollection::Tau& tau = selectedTaus[i];
    if(!TauID::oneProng(tau)) continue;
    tmp.push_back(tau);

    hTau_AfterOneProng.fill(tau.p4(), weight);
    hTauP_AfterOneProng->Fill(tau.p4().P(), weight);
    hTauLeadingTrackPt_AfterOneProng->Fill(tau.leadPFChargedHadrCandP4().Pt(), weight);
    hTauLeadingTrackP_AfterOneProng->Fill(tau.leadPFChargedHadrCandP4().P(), weight);
    hTauRtau_AfterOneProng->Fill(tau.rtau(), weight);
  }
  selectedTaus.swap(tmp);
  tmp.clear();
  if(selectedTaus.empty()) return true;
  cOneProng.increment();
  hGenTau_AfterOneProng.fill(theGenTau.p4(), weight);
  hVertexCount_AfterOneProng->Fill(fVertexCount->value(), weight);

  // Rtau
  for(size_t i=0; i<selectedTaus.size(); ++i) {
    TauCollection::Tau& tau = selectedTaus[i];
    if(!TauID::rtau(tau)) continue;

    hTau_AfterRtau.fill(tau.p4(), weight);

    tmp.push_back(tau);
  }
  selectedTaus.swap(tmp);
  tmp.clear();
  if(selectedTaus.empty()) return true;
  cRtau.increment();
  hVertexCount_AfterRtau->Fill(fVertexCount->value(), weight);
  if(theGenTau.isValid()) hGenTau_AfterRtau.fill(theGenTau.p4(), weight);

  // Tau ID finished

  // Trigger
  /*
  if(fIsEmbedded) {
    if(!fMuTriggerPassed->value()) return true;
  }
  */
  cMuTrigger.increment();


  if(false) {
    std::cout << "Event " << fEventInfo.event() << ":" << fEventInfo.lumi() << ":" << fEventInfo.run() << std::endl;
    for(size_t i=0; i< selectedTaus.size(); ++i) {
      TauCollection::Tau& tau = selectedTaus[i];
      std::cout << "  selected tau pt " << tau.p4().Pt() << " eta " << tau.p4().Eta() << " phi " << tau.p4().Phi() << std::endl;
      if(fIsEmbedded) {
        embeddingMuon.ensureValidity();
        double DR = ROOT::Math::VectorUtil::DeltaR(tau.p4(), embeddingMuon.p4());
        if(DR < 0.5) {
          std::cout << "    matched to embedding muon, DR " << DR << std::endl;
        }
      }
      for(size_t j=0; j<fGenTaus.size(); ++j) {
        GenParticleCollection::GenParticle gen = fGenTaus.get(j);
        double DR = ROOT::Math::VectorUtil::DeltaR(tau.p4(), gen.p4());
        if(DR < 0.5) {
          std::cout << "    matched to generator tau, DR " << DR
                    << " mother " << gen.motherPdgId()
                    << " grandmother " << gen.grandMotherPdgId()
                    << std::endl;
        }
      }
    }
  }

  return true;
}
Пример #12
0
void MassPlotterSingleTop::singleTopAnalysis(TList* allCuts, Long64_t nevents ,TString myfileName ){

  TopUtilities topUtils ;

  int lumi = 0;

  TIter nextcut(allCuts); 
  TObject *objcut; 

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

  double MT_QCD_Tree , TOPMASS_QCD_Tree , MuIso_QCD_Tree , Weight_QCD_Tree;

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

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

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

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

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


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

    Sample.Print(Weight);

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

    string lastFileName = "";

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

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

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

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

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

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

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

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

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

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

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

      if(! pass)
	continue;

      int cut = 0;

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

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

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

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

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

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

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


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

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

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


      if( nTightMuons != 1 )
	  continue;

      bool isiso = true;

      if( nLooseMuos > 0 )
      	continue;

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

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

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

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

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

      int nJetsPt20_47 = 0;

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

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

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


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

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

	  if ( DR > 0.3 ){

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


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

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

      //weight = 1.0;

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

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

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

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

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

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

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

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

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


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

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

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

      if( IsQCD )
	theQCD_Tree->Fill();



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

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

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

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

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

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

  theTreeFile->Close();
      

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

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

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

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

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

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

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

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

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

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

  theFile->cd();
  hTopMass->Write();
  hTopMassEtaJ->Write();
  //cutflowtable.Print("cutflowtable");
  theFile->Close();
  if( printEventIds )
    for( auto a : EventIdFiles ){
      a->close();
    }
}
Пример #13
0
  int main(int argc, char *argv[]){
    /////////////////////////////////////
    if (argc != 6)
    {
      std::cout << "Please enter something like: ./run \"filelist_WJets_PU20bx25_100_200.txt\" \"WJets_PU20bx25_100_200\" \"Results\" \"00\" \"0\" " << std::endl;
      return EXIT_FAILURE;
    }
    //get the inputs from user
    const string InRootList = argv[1];
    const string subSampleKey = argv[2];
    const string Outdir = argv[3];
    const string inputnumber = argv[4];
    const string verbosity = argv[5];
    //////////////////////////////////////
    int verbose = atoi(verbosity.c_str());

     //some varaibles
    char filenames[500];
    vector<string> filesVec;
    ifstream fin(InRootList.c_str());
    TChain *sample_AUX = new TChain("TreeMaker2/PreSelection");
    char tempname[200];
    char histname[200];
    const double deltaRMax = 0.1;
    const double deltaPtMax = 0.2;

    map<string,int> binMap = utils2::BinMap_NoB();
    int totNbins=binMap.size();
    map<string,int> binMap_mht_nj = utils2::BinMap_mht_nj();
    int totNbins_mht_nj=binMap_mht_nj.size();
    TH1* hAccAll = new TH1D("hAccAll","Acceptance -- All",totNbins_mht_nj,1,totNbins_mht_nj+1);
    TH1* hIsoRecoAll = new TH1D("hIsoRecoAll","Efficiency -- All",totNbins,1,totNbins+1);
    TH1* hAccPass = new TH1D("hAccPass","Acceptance -- Pass",totNbins_mht_nj,1,totNbins_mht_nj+1);
    TH1* hIsoRecoPass = new TH1D("hIsoRecoPass","Efficiency -- Pass",totNbins,1,totNbins+1);
    hAccAll->Sumw2();
    hIsoRecoAll->Sumw2();
    hAccPass->Sumw2();
    hIsoRecoPass->Sumw2();

    int TauResponse_nBins=4;
    vector<TH1*> vec_resp;
        TFile * resp_file = new TFile("TauHad/HadTau_TauResponseTemplates_TTbar_Elog195WithDirectionalTemplates.root","R");
    for(int i=0; i<TauResponse_nBins; i++){
      sprintf(histname,"hTauResp_%d",i);
      vec_resp.push_back( (TH1D*) resp_file->Get( histname )->Clone() );
    }

    ///read the file names from the .txt files and load them to a vector.
    while(fin.getline(filenames, 500) ){filesVec.push_back(filenames);}
    cout<< "\nProcessing " << subSampleKey << " ... " << endl;
    for(unsigned int in=0; in<filesVec.size(); in++){ sample_AUX->Add(filesVec.at(in).c_str()); }


    // --- Analyse the events --------------------------------------------
    Selection * sel = new Selection();
    Utils * utils = new Utils();

    // Interface to the event content
    Events * evt = new Events(sample_AUX, subSampleKey,verbose);

    // Loop over the events (tree entries)
    int eventN=0;
    while( evt->loadNext() ){
//      if(eventN>10000)break;
      eventN++;

      // Through out an event that contains HTjets with bad id
      if(evt->JetId()==0)continue;

//printf("\n@@@@@@@@@@@@@@@@@@@@@@@@@@  \n event: %d \n Njet: %d HT: %g MHT: %g dphi1: %g dphi2: %g dphi3: %g  \n ",eventN-1,evt->nJets(),evt->ht(),evt->mht(),evt->deltaPhi1(),evt->deltaPhi2(),evt->deltaPhi3()); //Ahmad3

      // Apply the NJets baseline-cut
      if( !sel->Njet_4(evt->nJets()) ) continue;
      // Apply the HT and MHT baseline-cuts
      if( !sel->ht_500(evt->ht()) ) continue;
      if( !sel->mht_200(evt->mht()) ) continue;
      // Apply the delta-phi cuts
//      if( !sel->dphi(evt->nJets(),evt->minDeltaPhiN()) ) continue;
      if( !sel->dphi(evt->nJets(),evt->deltaPhi1(),evt->deltaPhi2(),evt->deltaPhi3(),evt->deltaPhi4()) ) continue;

      if(verbose!=0)printf("\n############ \n event: %d \n ",eventN-1);

      double genMuPt=0.;
      double genMuEta=-99.;
      double genMuPhi=-99.;
      int firstMuId=0;
      vector<TVector3> genMuonVec;
      TVector3 temp3vec;
      genMuonVec.clear();
      bool isMuon = false;

      for(int i=0; i< evt->GenMuPtVec_().size(); i++){
        if(evt->GenMuFromTauVec_()[i]==0){
          genMuPt = evt->GenMuPtVec_().at(i);
          genMuEta = evt->GenMuEtaVec_().at(i);
          genMuPhi = evt->GenMuPhiVec_().at(i);
          isMuon=true;
          temp3vec.SetPtEtaPhi(genMuPt,genMuEta,genMuPhi);
          genMuonVec.push_back(temp3vec);
        }
        
        if(verbose!=0){
          printf("Muon # %d, pt: %g, eta: %g, phi: %g \n ",i,genMuPt,genMuEta,genMuPhi);
        }

        break; // if more than one muon exist, pick the energetic one. 
      }

      // ask for exactly one muon
      if( evt->GenMuPtVec_().size() > 1 ) continue;

      if( !( isMuon ) ) continue;

      // recompute ht mht njet
      double scale;
      if(genMuPt >=20.)scale = utils->getRandom(genMuPt,vec_resp );
      else scale = utils->getRandom(20.,vec_resp );
      double simTauJetPt = scale * genMuPt;
      double simTauJetEta = genMuEta;
      double simTauJetPhi = genMuPhi;

        // 3Vec of muon and scaledMu
        TVector3 SimTauJet3Vec,NewTauJet3Vec,Muon3Vec;
        SimTauJet3Vec.SetPtEtaPhi(simTauJetPt,simTauJetEta,simTauJetPhi);
        Muon3Vec.SetPtEtaPhi(genMuPt,genMuEta,genMuPhi);

        // New ht and mht
        vector<TVector3> HT3JetVec,MHT3JetVec;
        HT3JetVec.clear();
        MHT3JetVec.clear();
        TVector3 temp3Vec;
        int slimJetIdx=-1;
        utils->findMatchedObject(slimJetIdx,genMuEta,genMuPhi,evt->slimJetPtVec_(),evt->slimJetEtaVec_(), evt->slimJetPhiVec_(),deltaRMax,verbose);
        // If there is no match, add the tau jet as a new one
        if(slimJetIdx==-1){
          NewTauJet3Vec=SimTauJet3Vec;
          if(NewTauJet3Vec.Pt()>30. && fabs(NewTauJet3Vec.Eta())<2.4)HT3JetVec.push_back(NewTauJet3Vec);
          if(NewTauJet3Vec.Pt()>30. && fabs(NewTauJet3Vec.Eta())<5.)MHT3JetVec.push_back(NewTauJet3Vec);
        }
        for(int i=0;i<evt->slimJetPtVec_().size();i++){
          if(i!=slimJetIdx){
            temp3Vec.SetPtEtaPhi(evt->slimJetPtVec_()[i],evt->slimJetEtaVec_()[i],evt->slimJetPhiVec_()[i]);
            if(evt->slimJetPtVec_()[i]>30. && fabs(evt->slimJetEtaVec_()[i])<2.4)HT3JetVec.push_back(temp3Vec);
            if(evt->slimJetPtVec_()[i]>30. && fabs(evt->slimJetEtaVec_()[i])<5.)MHT3JetVec.push_back(temp3Vec);
          }
          else if(i==slimJetIdx){
            temp3Vec.SetPtEtaPhi(evt->slimJetPtVec_()[i],evt->slimJetEtaVec_()[i],evt->slimJetPhiVec_()[i]);
            NewTauJet3Vec=temp3Vec-Muon3Vec+SimTauJet3Vec;
            if(NewTauJet3Vec.Pt()>30. && fabs(NewTauJet3Vec.Eta())<2.4)HT3JetVec.push_back(NewTauJet3Vec);
            if(NewTauJet3Vec.Pt()>30. && fabs(NewTauJet3Vec.Eta())<5.)MHT3JetVec.push_back(NewTauJet3Vec);
          }

        }

        // Order the HT3JetVec and MHT3JetVec based on their pT
        HT3JetVec = utils->Order_the_Vec(HT3JetVec);
        MHT3JetVec = utils->Order_the_Vec(MHT3JetVec);


        double newHT=0,newMHT=0,newMHTPhi=-1;
        TVector3 newMHT3Vec;
        for(int i=0;i<HT3JetVec.size();i++){
          newHT+=HT3JetVec[i].Pt();
        }
        for(int i=0;i<MHT3JetVec.size();i++){
          newMHT3Vec-=MHT3JetVec[i];
        }
        newMHT=newMHT3Vec.Pt();
        newMHTPhi=newMHT3Vec.Phi();

        //New #Jet
        int newNJet = HT3JetVec.size();
        if(verbose==1)printf("newNJet: %d \n ",newNJet);



      // Acceptance determination 1: Counter for all events
      // with muons at generator level
      hAccAll->Fill( binMap_mht_nj[utils2::findBin_mht_nj(evt->nJets(),evt->mht()).c_str()] );
//      hAccAll->Fill( binMap_mht_nj[utils2::findBin_mht_nj(newNJet,newMHT).c_str()] ); // this doesn't work good

      // Check if generator-level muon is in acceptance
      if( genMuPt > LeptonAcceptance::muonPtMin() && std::abs(genMuEta) < LeptonAcceptance::muonEtaMax() ) {
        if(verbose!=0)printf("Muon is in acceptance \n ");
        // Acceptance determination 2: Counter for only those events
        // with generator-level muons inside acceptance
        // hAccPass->Fill( binMap[utils2::findBin(cntNJetsPt30Eta24,nbtag,HT,template_mht).c_str()] );
        hAccPass->Fill( binMap_mht_nj[utils2::findBin_mht_nj(evt->nJets(),evt->mht()).c_str()] );
//        hAccPass->Fill( binMap_mht_nj[utils2::findBin_mht_nj(newNJet,newMHT).c_str()] );

        // Reconstruction-efficiency determination 1: Counter for all events
        // with generator-level muons inside acceptance, regardless of whether
        // the muon has also been reconstructed or not.
        // hIsoRecoAll->Fill( binMap[utils2::findBin(cntNJetsPt30Eta24,nbtag,HT,template_mht).c_str()]);
        hIsoRecoAll->Fill( binMap[utils2::findBin_NoB(evt->nJets(),evt->ht(),evt->mht()).c_str()]);

        // Check if the muon has been reconstructed: check if a reconstructed
        // muon is present in the event that matches the generator-level muon
        // Isolation-efficiency determination 1: Counter for all events with a
        // reconstructed muon that has a generator-level muon match inside the
        // the acceptance, regardless of whether the reconstructed muon is also
        // isolated or not.

//if( evt->MuPtVec_().size()>0 )printf(" RecoMu--> Pt: %g eta: %g phi: %g deltaRMax: %g ",evt->MuPtVec_()[0],evt->MuEtaVec_()[0],evt->MuPhiVec_()[0],deltaRMax); // Ahmad3
//else cout << " Muon size is 0 \n " ;
        // in R and in pt
        int matchedMuonIdx = -1;
        if(evt->MuPtVec_().size()>0 && utils->findMatchedObject(matchedMuonIdx,genMuEta,genMuPhi,evt->MuPtVec_(),evt->MuEtaVec_(),evt->MuPhiVec_(),deltaRMax,verbose) ) {
          // Muon is reconstructed
          const double relDeltaPtMu = std::abs(genMuPt - evt->MuPtVec_().at(matchedMuonIdx) ) / evt->MuPtVec_().at(matchedMuonIdx) ;
          if(verbose!=0)printf(" relDeltaPtMu: %g \n ",relDeltaPtMu);
          if( relDeltaPtMu < deltaPtMax ) {
            // and matches generated pt
            if(verbose!=0)printf("Muon is reconstructed \n ");
            // Check if the muon is also isolated: check if an isolated muon is present
            // in the event that matches the reconstructed muon in R
            if( /*muonsRelIso->at(matchedMuonIdx) <= Selection::muIso()*/ true ){
                //.................//.................//
                // Currently muons are picked if they are isolated.
                // So we don't need to put a cut here.     
                //.................//.................//
              // Muon is isolated
              if(verbose!=0)printf("Muon is isolated \n ");
              // Reconstruction-efficiency determination 2: Counter for those events
              // with generator-level muons inside acceptance where the muon has also
              // been reconstructed.
              // Isolation-efficiency determination 2: Counter for those events where
              // the muon is also isolated.
              // hIsoRecoPass->Fill( binMap[utils2::findBin(cntNJetsPt30Eta24,nbtag,HT,template_mht).c_str()] );
              hIsoRecoPass->Fill( binMap[utils2::findBin_NoB(evt->nJets(),evt->ht(),evt->mht()).c_str()] );
            } // End of muon is isolated
          } // End of pt matching
        } // End of reconstructed muon
      } // End of muon in acceptance



    } // end of loop over events


     // Compute acceptance
    TH1* hAcc = static_cast<TH1*>(hAccPass->Clone("hAcc"));
    hAcc->Divide(hAccPass,hAccAll,1,1,"B");// we use B option here because the two histograms are correlated. see TH1 page in the root manual.

    // Compute efficiencies
    TH1* hEff = static_cast<TH1*>(hIsoRecoPass->Clone("hEff"));
    hEff->Divide(hIsoRecoPass,hIsoRecoAll,1,1,"B");

    if(verbose!=0){
      for(int j=1; j<= totNbins; j++){
        printf("hAccAll: %g hAccPass: %g hAcc: %g hIsoRecoAll: %g hIsoRecoPass: %g hEff: %g \n ",hAccAll->GetBinContent(j),hAccPass->GetBinContent(j),hAcc->GetBinContent(j),hIsoRecoAll->GetBinContent(j),hIsoRecoPass->GetBinContent(j),hEff->GetBinContent(j));
      }
    }


    // --- Save the Histograms to File -----------------------------------
    sprintf(tempname,"LostLepton/LostLepton2_MuonEfficienciesFrom%s_%s.root",subSampleKey.c_str(),inputnumber.c_str());
    TFile outFile(tempname,"RECREATE");
    hAcc->Write();
    hEff->Write();
    hAccAll->Write();
    hAccPass->Write();
    hIsoRecoAll->Write();
    hIsoRecoPass->Write();
    outFile.Close();




  } // end of main
Пример #14
0
// === Main Function ===================================================
void general1(int sampleId) {
  std::cout << "Analysing the " << sampleLabel(sampleId) << " sample" << std::endl;


  // --- Declare the Output Histograms ---------------------------------
  TH1* hNJets = new TH1F("hNJets",";N(jets);N(events)",12,0,12);
  hNJets->Sumw2();
  TH1* hHt = new TH1F("hHt",";H_{T} [GeV]",30,0,3000);
  hHt->Sumw2();
  hHt->GetXaxis()->SetNdivisions(505);
  TH1* hMht = new TH1F("hMht",";#slash{H}_{T} [GeV]",30,0,1500);
  hMht->Sumw2();
  hMht->GetXaxis()->SetNdivisions(505);
  TH1* hMEff = new TH1F("hMEff",";M_{eff} [GeV]",50,0,5000);
  hMEff->Sumw2();
  hMEff->GetXaxis()->SetNdivisions(505);
  std::vector<TH1*> hJetPt(6);
  std::vector<TH1*> hJetPhi(6);
  std::vector<TH1*> hJetEta(6);
  for(unsigned int i = 0; i < hJetEta.size(); ++i) {
    TString name = "hJetPt_";
    name += i;
    TString title = ";p_{T}(jet ";
    title += i+1;
    title += ") [GeV];N(events)";
    hJetPt.at(i) = new TH1F(name,title,30,0,1500);
    hJetPt.at(i)->Sumw2();

    name = "hJetPhi_";
    name += i;
    title = ";#phi(jet ";
    title += i+1;
    title += ");N(events)";
    hJetPhi.at(i) = new TH1F(name,title,24,-4,4);
    hJetPhi.at(i)->Sumw2();

    name = "hJetEta_";
    name += i;
    title = ";#eta(jet ";
    title += i+1;
    title += ");N(events)";
    hJetEta.at(i) = new TH1F(name,title,25,-5,5);
    hJetEta.at(i)->Sumw2();
  }



  // --- Declare the Variables Read from the Tree ----------------------
  // Reco-level jets
  int nRecoJets = 0;
  float recoJetPt[kRecoJetColSize];
  float recoJetPhi[kRecoJetColSize];
  float recoJetEta[kRecoJetColSize];

  // Number of reco-level muons and electrons
  int nRecoMus = 0;
  int nRecoEle = 0;

  // MC Event weight
  float evtWgt = 1.;



  // --- Set Up the Tree -----------------------------------------------

  // Get the tree from file
  TChain* tr = new TChain("AnaTree");
  tr->Add("/nfs/dust/test/cmsdas/school61/susy/ntuple/2013-v1/"+fileName(sampleId)+"_0.root");

  // Set the branches
  tr->SetBranchAddress("NrecoJet",&nRecoJets);
  tr->SetBranchAddress("recoJetPt",recoJetPt);
  tr->SetBranchAddress("recoJetPhi",recoJetPhi);
  tr->SetBranchAddress("recoJetEta",recoJetEta);
  tr->SetBranchAddress("NrecoMu",&nRecoMus);
  tr->SetBranchAddress("NrecoEle",&nRecoEle);
  if( sampleId > 0 ) tr->SetBranchAddress("EvtWgt",&evtWgt);



  // --- Process the Events in the Tree --------------------------------
  int nEvtsToProcess = tr->GetEntries();
  std::cout << "Processing " << nEvtsToProcess << " events" << std::endl;

  // Loop over the tree entries
  for(int evtIdx = 0; evtIdx < nEvtsToProcess; ++evtIdx) {
    if( evtIdx%100000 == 0 ) std::cout<<"  Event: " << evtIdx << std::endl;

    // Get the variables' values for this event
    tr->GetEntry(evtIdx);
    if( nRecoJets > kRecoJetColSize ) {
      std::cerr << "ERROR: more than " << kRecoJetColSize << " reco jets in event " << evtIdx << std::endl;
      exit(-1);
    }


    // Apply the lepton veto
    if( nRecoEle > 0 ) continue;
    if( nRecoMus > 0 ) continue;


    // Calculate RA2 selection-variables from jets
    float selNJet = 0; // Number of jets with pt > 50 GeV and |eta| < 2.5 (HT jets)
    float selHt   = 0.;
    float selMhtX = 0.;
    float selMhtY = 0.;
    // Loop over reco jets: they are ordered in pt
    for(int jetIdx = 0; jetIdx < nRecoJets; ++jetIdx) {
      // Calculate NJet and HT
      if( recoJetPt[jetIdx] > kHtJetPtMin && TMath::Abs(recoJetEta[jetIdx]) < kHtJetEtaMax ) {
	selNJet++;
	selHt += recoJetPt[jetIdx];
      }
      // Calculate MHT components
      if( recoJetPt[jetIdx] > kMhtJetPtMin && TMath::Abs(recoJetEta[jetIdx]) < kMhtJetEtaMax ) {
	selMhtX -= recoJetPt[jetIdx]*TMath::Cos(recoJetPhi[jetIdx]);
	selMhtY -= recoJetPt[jetIdx]*TMath::Sin(recoJetPhi[jetIdx]);
      }
    } // End of loop over reco jets
    float selMht = sqrt( selMhtX*selMhtX + selMhtY*selMhtY );
    

    // Select only events with at least 2 HT jets
    if( selNJet < 3 ) continue;



    //>>> PLACE OTHER RA2 CUTS HERE




    
    // Event weight in plots
    float weight = 1.;
    if( sampleId == 1 ) weight = evtWgt; // In case of the flat QCD-MC, reweight to physical spectrum

    
    // Fill histogram
    hNJets->Fill(selNJet,weight);
    hHt->Fill(selHt,weight);
    hMht->Fill(selMht,weight);
    hMEff->Fill(selHt+selMht,weight);
    for(int i = 0; i < static_cast<int>(hJetPt.size()); ++i) {
      if( i == nRecoJets ) break;
      hJetPt.at(i)->Fill(recoJetPt[i],weight);
      hJetPhi.at(i)->Fill(recoJetPhi[i],weight);
      hJetEta.at(i)->Fill(recoJetEta[i],weight);
    }
  } // End of loop over events



  // --- Save the Histograms to File -----------------------------------
  TFile outFile("General_"+fileName(sampleId)+".root","RECREATE");
  hNJets->Write();
  hHt->Write();
  hMht->Write();
  hMEff->Write();
  for(unsigned int i = 0; i < hJetPt.size(); ++i) {
    hJetPt[i]->Write();
    hJetEta[i]->Write();
    hJetPhi[i]->Write();
  }  
}
Пример #15
0
void plots() {

  gSystem->Load("libEVGEN"); // Needs to be!

  AliRunLoader* rl = AliRunLoader::Open("galice.root");
  rl->LoadKinematics();
  rl->LoadHeader();

  // 4pi histograms
  TH1* hM    = new TH1D("hM",  "DIME #rho#rho;M_{4#pi} #(){GeV/#it{c}^{2}}", 100,  1.0, 3.0);
  TH1* hPt   = new TH1D("hPt", "DIME #rho#rho;p_{T}#(){4#pi} #(){GeV/#it{c}}", 100,  0.0, 3.0);

  // pi+- histograms
  TH1* hPt1   = new TH1D("hPt1", "DIME #rho#rho;p_{T}#(){#pi^{#pm}} #(){Gev/#it{c}}",  100, 0.0, 3.0);

  AliStack* stack = NULL;
  TParticle* part = NULL;
  TLorentzVector v[4];
  TLorentzVector vSum;

  // Loop over events
  for (Int_t i = 0; i < rl->GetNumberOfEvents(); ++i) {

    rl->GetEvent(i);
    stack = rl->Stack();
    Int_t nPrimary = 0;

    // Loop over all particles
    for (Int_t j = 0; j < stack->GetNtrack(); ++j) {
      part = stack->Particle(j);           // Get particle
      part->Print();                       // Print contents

      if (abs(part->GetPdgCode()) == 211   // Is pi+ or pi-
          & part->GetStatusCode() == 1     // Is stable final state
          & stack->IsPhysicalPrimary(j)) { // Is from generator level

        part->Momentum(v[nPrimary]);       // Set content of v
        ++nPrimary;
      }
    }
    if (nPrimary != 4) {
      printf("Error: nPrimary=%d != 4 \n", nPrimary);
      continue;
    }

    // 4-vector sum
    vSum = v[0] + v[1] + v[2] + v[3];

    // Fill 4pi histograms
    hM->Fill(vSum.M());
    hPt->Fill(vSum.Perp());

    // Fill pi+- histograms
    for (Int_t k = 0; k < 4; ++k) {
      hPt1->Fill(v[k].Perp());
    }
    printf("\n");
  }

  // Save plots as pdf
  hM->Draw();    c1->SaveAs("plotM.pdf");
  hPt->Draw();   c1->SaveAs("plotPt.pdf");
  hPt1->Draw();  c1->SaveAs("plotPt1.pdf");

}
Пример #16
0
void blinding_study() 
{
	gSystem->CompileMacro("MitGPTree.h");
	
// First we define MIT Style for the plots.

	TStyle *MitStyle = gStyle;
	//gStyle = MitStyle;

	// Canvas
	MitStyle->SetCanvasColor     (0);
	MitStyle->SetCanvasBorderSize(10);
	MitStyle->SetCanvasBorderMode(0);
	MitStyle->SetCanvasDefH      (700);
	MitStyle->SetCanvasDefW      (700);
	MitStyle->SetCanvasDefX      (100);
	MitStyle->SetCanvasDefY      (100);

	// Pads
	MitStyle->SetPadColor       (0);
	MitStyle->SetPadBorderSize  (10);
	MitStyle->SetPadBorderMode  (0);
	MitStyle->SetPadBottomMargin(0.13);
	MitStyle->SetPadTopMargin   (0.04);
	MitStyle->SetPadLeftMargin  (0.18);
	MitStyle->SetPadRightMargin (0.04);
	MitStyle->SetPadGridX       (0);
	MitStyle->SetPadGridY       (0);
	MitStyle->SetPadTickX       (0);
	MitStyle->SetPadTickY       (0);

	// Frames
	MitStyle->SetFrameFillStyle ( 0);
	MitStyle->SetFrameFillColor ( 0);
	MitStyle->SetFrameLineColor ( 1);
	MitStyle->SetFrameLineStyle ( 0);
	MitStyle->SetFrameLineWidth ( 1);
	MitStyle->SetFrameBorderSize(10);
	MitStyle->SetFrameBorderMode( 0);

	// Histograms
	MitStyle->SetHistFillColor(2);
	MitStyle->SetHistFillStyle(0);
	MitStyle->SetHistLineColor(1);
	MitStyle->SetHistLineStyle(0);
	MitStyle->SetHistLineWidth(2);
	MitStyle->SetNdivisions(505);

	// Functions
	MitStyle->SetFuncColor(1);
	MitStyle->SetFuncStyle(0);
	MitStyle->SetFuncWidth(2);

	// Various
	MitStyle->SetMarkerStyle(20);
	MitStyle->SetMarkerColor(kBlack);
	MitStyle->SetMarkerSize (1.2);

	MitStyle->SetTitleSize  (0.055,"X");
	MitStyle->SetTitleOffset(1.200,"X");
	MitStyle->SetLabelOffset(0.005,"X");
	MitStyle->SetLabelSize  (0.050,"X");
	MitStyle->SetLabelFont  (42   ,"X");
	MitStyle->SetTickLength (-0.03,"X");

	MitStyle->SetStripDecimals(kFALSE);

	MitStyle->SetTitleSize  (0.055,"Y");
	MitStyle->SetTitleOffset(1.800,"Y");
	MitStyle->SetLabelOffset(0.010,"Y");
	MitStyle->SetLabelSize  (0.050,"Y");
	MitStyle->SetLabelFont  (42   ,"Y");
	MitStyle->SetTickLength (-0.03,"Y");

	MitStyle->SetTextSize   (0.055);
	MitStyle->SetTextFont   (42);

	MitStyle->SetStatFont   (42);
	MitStyle->SetTitleFont  (42);
	MitStyle->SetTitleFont  (42,"X");
	MitStyle->SetTitleFont  (42,"Y");

	MitStyle->SetOptStat    (0);
  
// Here the style section ends and the macro begins.
	
	string sig_samples[] = 
	{
		"s12-dmmpho-v_m1-v7a",
		"s12-dmmpho-av_m1-v7a",
		"s12-dmmpho-v_m10-v7a",
		"s12-dmmpho-av_m10-v7a",
		"s12-dmmpho-v_m100-v7a",
		"s12-dmmpho-av_m100-v7a",
		"s12-dmmpho-v_m200-v7a",
		"s12-dmmpho-av_m200-v7a",
		"s12-dmmpho-av_m300-v7a",	
		"s12-dmmpho-v_m500-v7a",
		"s12-dmmpho-av_m500-v7a",		
		"s12-dmmpho-v_m1000-v7a",
		"s12-dmmpho-av_m1000-v7a",
		"s12-addmpho-md1_d2-v7a",
		"s12-addmpho-md1_d3-v7a",
		"s12-addmpho-md1_d4-v7a",
		"s12-addmpho-md1_d5-v7a",		
		"s12-addmpho-md1_d6-v7a",
		"s12-addmpho-md2_d2-v7a",
		"s12-addmpho-md2_d3-v7a",
		"s12-addmpho-md2_d5-v7a",
		"s12-addmpho-md2_d6-v7a",
		"s12-addmpho-md3_d2-v7a",
		"s12-addmpho-md3_d3-v7a",
		"s12-addmpho-md3_d4-v7a",
		"s12-addmpho-md3_d5-v7a",
		"s12-addmpho-md3_d6-v7a"
	}
	
	Int_t signal_num=0; 
	
// This macro considers only one signal sample at a time, so the variable signal_num defines
// which signal sample to work on (it is the index of the sample in sig_samples).
	
	double sig_weights[] =
	{
		4.81E-07,
		4.79E-07,
		4.80E-07,
		4.81E-07,
		4.77E-07,
		4.26E-07,
		4.23E-07,
		3.18E-07,
		2.19E-07,
		2.01E-07,
		9.52E-08,
		3.00E-08,
		8.22E-09,
		6.48E-02,
		1.73E-01,
		6.93E-02,
		9.17E-02,
		9.63E-01,
		5.87E-03,
		4.91E-03,
		4.37E-03,
		4.26E-03,
		1.45E-03,
		7.93E-04,
		5.53E-04,
		4.26E-04,
		3.24E-04
	};
	
// The signal weights are given by (sigma_MC * lumi)/(N_processed). Background weights are defined similarly below.

	string bg_samples[] = {"s12-zgptg130-v7c", "s12-wjets-ptw100-v7a", "s12-wgptg130-v7a", "s12-qcdht100-250-v7a", "s12-qcdht250-500-v7a", "s12-qcdht500-1000-v7a", 
	"s12-qcdht1000-v7a", "s12-2pibo10_25-v7a", "s12-2pibo25_250-v7a", "s12-2pibo250-v7a", "s12-2pibx10_25-v7a", "s12-2pibx25_250-v7a", "s12-2pibx250-v7a", 
	"s12-pj50_80-v7a", "s12-pj80_120-v7a", "s12-pj120_170-v7a", "s12-pj170_300-v7a", "s12-pj300_470-v7a", "s12-pj470_800-v7a", "s12-pj800_1400-v7a", 
	"s12-pj1400_1800-v7a", "s12-pj1800-v7a", "s12-zgllgptg130-v7a", "s12-zgllg-v7a"};

	double bg_weights[]=
	{
		5.28E-03,
		1.14E-01,
		1.38E-02,
		5.63E+03,
		2.34E+02,
		9.71E+00,
		3.09E-01,
		9.21E+00,
		9.90E-01,
		4.21E-04,
		1.66E+01,
		6.43E-01,
		4.91E-05,
		3.30E+01,
		5.49E+00,
		1.09E+00,
		3.01E-01,
		2.15E-02,
		2.10E-03,
		7.11E-05,
		4.45E-07,
		1.88E-08,
		3.18E-03,
		5.10E-01
	};
	
	string sigLine = sig_samples[signal_num];
	Double_t sigWeight = sig_weights[signal_num];
	
	TH1* sig_hist = new TH1F("sig_hist", TString("Phi Between Met and Photon for Signal Events [") + TString(sigLine) + TString("]"), 70, 0, 3.5); 
	TH1* bg_hist = new TH1F("bg_hist", TString("Phi Between Met and Photon for Background Events [") + TString(sigLine) + TString("]"), 70, 0, 3.5);
	
	TH1* signifhist = new TH1F("signifhist", TString(" "), 24, 2, 3.2);

	cout<<"The selected signal sample is: "<<TString(sigLine)<<" "<<endl;
	
	TString sigFilename = TString("monoph-2013-July9_") + TString(sigLine) + TString("_noskim.root");
	
	MitGPTree sigEvent;
	sigEvent.LoadTree(TString("/scratch/cferko/hist/monoph-2013-July9/merged/")+sigFilename, 0);
	sigEvent.InitTree(0);
	
	int nDataSig=sigEvent.tree_->GetEntries();
	
	for (int evt=0; evt<nDataSig; ++evt) 
	{
		sigEvent.tree_->GetEntry(evt);
		Double_t pho1Pt = sigEvent.pho1_.Pt();
		Double_t jet1Pt = sigEvent.jet1_.Pt();
		Double_t met = sigEvent.met_;
		Double_t metPhi = sigEvent.metPhi_;
		Double_t nphotons = sigEvent.nphotons_;
		Double_t ncosmics = sigEvent.ncosmics_;
		Double_t phoPassEleVeto = sigEvent.phoPassEleVeto_a1_;
		Double_t jet1Pt = sigEvent.jet1_.Pt();
		Double_t nlep = sigEvent.nlep_;
		Double_t pho1Eta = sigEvent.pho1_.Eta();
		Double_t pho1Phi = sigEvent.pho1_.Phi();
		Double_t phoIsTrigger = sigEvent.phoIsTrigger_a1_;
		Double_t phoLeadTimeSpan = sigEvent.phoLeadTimeSpan_a1_;
		Double_t phoCoviEtaiEta = sigEvent.phoCoviEtaiEta_a1_;
		Double_t phoCoviPhiiPhi = sigEvent.phoCoviPhiiPhi_a1_;
		Double_t phoMipIsHalo = sigEvent.phoMipIsHalo_a1_;
		Double_t phoSeedTime = sigEvent.phoSeedTime_a1_;
		
		Double_t deltaPhi = TMath::ACos(TMath::Cos(pho1Phi - metPhi));
		
		if (TMath::Abs(pho1Eta)<1.479 && met>140 && pho1Pt>160 && nphotons>0 && phoPassEleVeto>0 && phoIsTrigger==1 && TMath::Abs(phoLeadTimeSpan) < 8. && phoCoviEtaiEta > 0.001 && phoCoviPhiiPhi > 0.001 && phoMipIsHalo == 0 && phoSeedTime > -1.5 && nlep==0 && ncosmics==0 && jet1Pt<100) sig_hist->Fill(deltaPhi, sigWeight);			
	}

	for (int i=0; i<24; i++)
	{
		string bgLine = bg_samples[i];
		Double_t bgWeight = bg_weights[i];

		TString bgFilename = TString("monoph-2013-July9_") + TString(bgLine) + TString("_noskim.root");

		MitGPTree bgEvent;
		bgEvent.LoadTree(TString("/scratch/cferko/hist/monoph-2013-July9/merged/") + bgFilename, 0);
		bgEvent.InitTree(0);
		
		int nDataBg=bgEvent.tree_->GetEntries();
		
		for (int evt=0; evt<nDataBg; ++evt) 
		{
			bgEvent.tree_->GetEntry(evt);
			Double_t pho1Pt = bgEvent.pho1_.Pt();
			Double_t jet1Pt = bgEvent.jet1_.Pt();
			Double_t met = bgEvent.met_;
			Double_t metPhi = bgEvent.metPhi_;
			Double_t nphotons = bgEvent.nphotons_;
			Double_t ncosmics = bgEvent.ncosmics_;
			Double_t phoPassEleVeto = bgEvent.phoPassEleVeto_a1_;
			Double_t jet1Pt = bgEvent.jet1_.Pt();
			Double_t nlep = bgEvent.nlep_;
			Double_t pho1Eta = bgEvent.pho1_.Eta();
			Double_t pho1Phi = bgEvent.pho1_.Phi();
			Double_t phoIsTrigger = bgEvent.phoIsTrigger_a1_;
			Double_t phoLeadTimeSpan = bgEvent.phoLeadTimeSpan_a1_;
			Double_t phoCoviEtaiEta = bgEvent.phoCoviEtaiEta_a1_;
			Double_t phoCoviPhiiPhi = bgEvent.phoCoviPhiiPhi_a1_;
			Double_t phoMipIsHalo = bgEvent.phoMipIsHalo_a1_;
			Double_t phoSeedTime = bgEvent.phoSeedTime_a1_;
			
			Double_t deltaPhi = TMath::ACos(TMath::Cos(pho1Phi - metPhi));
			
			if (TMath::Abs(pho1Eta)<1.479 && met>140 && pho1Pt>160 && nphotons>0 && phoPassEleVeto>0 && phoIsTrigger==1 && TMath::Abs(phoLeadTimeSpan) < 8. && phoCoviEtaiEta > 0.001 && phoCoviPhiiPhi > 0.001 && phoMipIsHalo == 0 && phoSeedTime > -1.5 && nlep==0 && ncosmics==0 && jet1Pt<100) bg_hist->Fill(deltaPhi, bgWeight);			
		}	
	}
	
	Double_t sigTot = sig_hist->Integral();
	Double_t bgTot = bg_hist->Integral();
	
	Double_t signifTot = sigTot/TMath::Sqrt(bgTot);
	Double_t signifTarget = 0.25*signifTot;
	
	Int_t reduced=0;

// The strange limits in the for loop are a messy hack to get the integral to work out. Since hist->Integral(a,b)
// integrates from BIN a to BIN b (bin numbers instead of values of the x-axis), I choose to work from bin 64
// (an angle cut of 3.2) to bin 40 (an angle cut of 2).

	for (int i=64; i>=40; i--)
	{
		Double_t sigcount = sig_hist->Integral(0, i);
		Double_t bgcount = bg_hist->Integral(0, i);
		if (bgcount>0)
		{
			Double_t significance = sigcount/TMath::Sqrt(bgcount);
//			cout<<"At a phi cut of "<<sig_hist->GetBinCenter(i)+0.025<<" the significance is "<<significance<<", which is a fraction "<<significance/signifTot<<" of max."<<endl;
			if (significance<signifTarget && reduced==0)
			{
				cout<<"The signal significance is reduced to one-fourth of its uncut value at a phi cut of "<<sig_hist->GetBinCenter(i)+0.025<<endl;
				reduced=1;
			}
			signifhist->Fill(sig_hist->GetBinCenter(i), significance);
		}
	}
	
	signifhist->SetStats(kFALSE);
	signifhist->GetXaxis()->SetTitle("Maximum #Delta#phi");
	signifhist->GetYaxis()->SetTitle("Signal Significance");
	signifhist->Draw();
	c1->Print(TString("Blinding_") + TString(sigLine) + TString(".pdf"));
}
Пример #17
0
void plot_ZJetBalance( int index, int bin, TH1& responseHistGen, 
		       TH1& responseHistReco, TH1& genJetpt, 
		       TH1& caloJetpt, TH1& recoZpt ) {

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

  TChain* t = new TChain("ZJet");
  if( useLocalFile == true ) t->Add("analysis_zjet.root");
  else t->Add(basename + TString("*.root"));

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

  Float_t JetRecoPt[20][4];
  Float_t JetCorPt[20][4];
  Float_t JetGenPt[20][4];
  Float_t JetRecoEta[20][4];
  Float_t JetGenEta[20][4];
  Float_t JetRecoPhi[20][4];
  Float_t JetGenPhi[20][4];
  Float_t JetRecoType[20][4];
  Float_t Z_Pt;
  Float_t Z_Phi;
  Float_t Z_Eta;
  Float_t Z_PtGen;
  Float_t Z_PhiGen;
  Float_t ePlusPt;
  Float_t eMinusPt;
  Float_t ePlusPtGen;
  Float_t eMinusPtGen;
  Float_t ePlusEta;
  Float_t eMinusEta;
  Float_t ePlusPhi;
  Float_t eMinusPhi;
  Float_t mZeeGen;
  Float_t mZee;

  Float_t ePlus_ecaliso_20;
  Float_t ePlus_sc_e;
  Float_t eMinus_ecaliso_20;
  Float_t eMinus_sc_e;
  Float_t ePlus_ptisoatecal_15;	   
  Float_t eMinus_ptisoatecal_15;
  

  t->SetBranchAddress("JetGenPt",   JetGenPt);
  t->SetBranchAddress("JetGenEta",  JetGenEta);
  t->SetBranchAddress("JetGenPhi",  JetGenPhi);
  t->SetBranchAddress("JetCorPt",   JetCorPt);
  t->SetBranchAddress("JetRecoPt",  JetRecoPt);
  t->SetBranchAddress("JetRecoEta", JetRecoEta);
  t->SetBranchAddress("JetRecoPhi", JetRecoPhi);

  t->SetBranchAddress("Z_Pt",       &Z_Pt);
  t->SetBranchAddress("Z_Phi",      &Z_Phi);
  t->SetBranchAddress("Z_Eta",      &Z_Eta);
  t->SetBranchAddress("Z_PtGen",    &Z_PtGen);
  t->SetBranchAddress("Z_PhiGen",   &Z_PhiGen);
  t->SetBranchAddress("ePlusPt",    &ePlusPt);
  t->SetBranchAddress("eMinusPt",   &eMinusPt);
  t->SetBranchAddress("ePlusPtGen", &ePlusPtGen);
  t->SetBranchAddress("eMinusPtGen",&eMinusPtGen);
  t->SetBranchAddress("ePlusEta",   &ePlusEta);
  t->SetBranchAddress("eMinusEta",  &eMinusEta);
  t->SetBranchAddress("ePlusPhi",   &ePlusPhi);
  t->SetBranchAddress("eMinusPhi",  &eMinusPhi);
  t->SetBranchAddress("mZeeGen",     &mZeeGen);
  t->SetBranchAddress("mZee",        &mZee);
  t->SetBranchAddress("ePlus_ecaliso_20",      &ePlus_ecaliso_20);
  t->SetBranchAddress("ePlus_sc_e",            &ePlus_sc_e);
  t->SetBranchAddress("eMinus_ecaliso_20",     &eMinus_ecaliso_20);
  t->SetBranchAddress("eMinus_sc_e",           &eMinus_sc_e);
  t->SetBranchAddress("ePlus_ptisoatecal_15",  &ePlus_ptisoatecal_15);	   
  t->SetBranchAddress("eMinus_ptisoatecal_15", &eMinus_ptisoatecal_15);

  t->SetBranchStatus("*",    0);
  t->SetBranchStatus("JetGenPt",    1);
  t->SetBranchStatus("JetGenEta",   1);
  t->SetBranchStatus("JetGenPhi",   1);
  t->SetBranchStatus("JetRecoPt",   1);
  t->SetBranchStatus("JetRecoEta",  1);
  t->SetBranchStatus("JetRecoPhi",  1);
  t->SetBranchStatus("JetCorPt",    1);
  t->SetBranchStatus("JetCorEta",   1);
  t->SetBranchStatus("JetCorPhi",   1);
  t->SetBranchStatus("Z_Pt",        1);
  t->SetBranchStatus("Z_Phi",       1);
  t->SetBranchStatus("Z_Eta",       1);
  t->SetBranchStatus("Z_PtGen",     1);
  t->SetBranchStatus("Z_PhiGen",    1);
  t->SetBranchStatus("ePlusPt",     1);
  t->SetBranchStatus("eMinusPt",    1);
  t->SetBranchStatus("ePlusPtGen",  1);
  t->SetBranchStatus("eMinusPtGen", 1);
  t->SetBranchStatus("ePlusEta",    1);
  t->SetBranchStatus("eMinusEta",   1);
  t->SetBranchStatus("ePlusPhi",    1);
  t->SetBranchStatus("eMinusPhi",   1);
  t->SetBranchStatus("mZeeGen",     1);
  t->SetBranchStatus("mZee",        1);
  t->SetBranchStatus("ePlus_ecaliso_20",      1);
  t->SetBranchStatus("ePlus_sc_e",            1);
  t->SetBranchStatus("eMinus_ecaliso_20",     1);
  t->SetBranchStatus("eMinus_sc_e",           1);
  t->SetBranchStatus("ePlus_ptisoatecal_15",  1);	   
  t->SetBranchStatus("eMinus_ptisoatecal_15", 1);





  for (Long64_t entry =0; entry < t->GetEntries(); entry++) {
    t->GetEntry(entry);
    if(entry%20000==0) std::cout<<"************ Event # "<< entry <<std::endl;


    bool isPtCut  = (ePlusPt>20.0) && (eMinusPt>20.0) && 
      (Z_Pt > GenPt[bin]) && (Z_Pt < GenPt[bin+1]);


    bool isEtaCutP = (fabs(ePlusEta)<1.4442) || 
      (fabs(ePlusEta)>1.560 && fabs(ePlusEta)<2.5);
    bool isEtaCutM = (fabs(eMinusEta)<1.4442) || 
      (fabs(eMinusEta)>1.560 && fabs(eMinusEta)<2.5);
    bool isECALiso = (ePlus_ecaliso_20 > 0.0) && 
      (ePlus_ecaliso_20 < 0.2) && (eMinus_ecaliso_20 > 0.0) && 
      (eMinus_ecaliso_20 < 0.2);    
    bool isTrackiso = (ePlus_ptisoatecal_15 < 0.2) && 
      (eMinus_ptisoatecal_15 < 0.2);


    if( !(isPtCut && isEtaCutP && isEtaCutM && isECALiso && 
	  isTrackiso && fabs(mZee-91.2)<2.5) )  continue;

    float leadGenJetPt=JetGenPt[index][0]; 
    float secondGenJetPt=JetGenPt[index][0]; 


    int leadRecoIndex=-1, secondRecoIndex=-1;
    float leadRecoJetPt   = 0.0;
    float secondRecoJetPt = 0.0;

    leadRecoIndex = 0; 
    secondRecoIndex = 1;
    leadRecoJetPt   =  JetRecoPt[index][0];
    secondRecoJetPt =  JetRecoPt[index][1];


//   FindLeadIndex(JetRecoCorrectedPt[index], leadRecoIndex[index], secondRecoIndex[index]);
//   leadRecoJetPt   = JetRecoCorrectedPt[index][leadRecoIndex];
//   secondRecoJetPt = JetRecoCorrectedPt[index][secondRecoIndex];

//   if(leadRecoIndex==-1) continue;


    // ************ test: apply jet pT cut *****************
    if( JetRecoPt[index][0] < MINPTCUT || 
	JetRecoPt[index][1] < MINPTCUT ) continue;


    float leadRecoJetEta = JetRecoEta[index][leadRecoIndex];
    double dPhiReco = dPhi(JetRecoPhi[index][leadRecoIndex], Z_Phi);


    if( fabs(dPhiReco)<2.94 || fabs(leadRecoJetEta)>1.3 || 
	secondRecoJetPt/leadRecoJetPt>0.2 ) continue;


    double ptRatioGen  = leadGenJetPt/Z_PtGen;
    double ptRatioReco = 0.0;

    if(usingCorrectedCaloJetPt) ptRatioReco = JetCorPt[index][0]/Z_Pt;
    else ptRatioReco = JetRecoPt[index][0]/Z_Pt;


    responseHistGen.Fill( ptRatioGen );
    responseHistReco.Fill( ptRatioReco );

    genJetpt.Fill(leadGenJetPt); 
    caloJetpt.Fill(leadRecoJetPt);
    recoZpt.Fill( Z_Pt );

    
  } // end TTree loop


  if(makeplot_ZptBalance==true) {

    TString plotname = 
      Form("ptBalance-allCuts_%d_%d", (int) GenPt[bin], 
	   (int) GenPt[bin+1] );
    
    PlotOnCanvas( responseHistGen, responseHistReco, 
		  plotname);
  }

}
Пример #18
0
void
GetEccenNpart_new(char* xname = "ile")
{
  gStyle->SetOptStat(0);
  gStyle->SetTitle(0);

  char name[100];

  TChain* ch = new TChain("t");
  int n;

  //you need a file list of root ntuple: fxxxx.lis
  //
  sprintf(name,"f%s.lis",xname);
  cout << "open the filelist : " << name << endl;
  ifstream fin(name);

  string filename;
  while(!fin.eof()){
    fin >> filename;
    if(filename.empty()) continue;
    cout << filename << endl;

    ch->AddFile(filename.c_str());
  }
  fin.close();

  double b;
  int ncoll;
  int npart;
  int nHitBbc_n, nHitBbc_s;
  double qBBC_n, qBBC_s;
  double vertex, ecc_std, ecc_rp, ecc_part,e4;
  double r_oll,r_geo,r_arith;
  ch->SetBranchAddress("b",            &b        );
  ch->SetBranchAddress("vertex",       &vertex   );
  ch->SetBranchAddress("ncoll",        &ncoll    );
  ch->SetBranchAddress("npart",        &npart    );
  ch->SetBranchAddress("ecc_std",      &ecc_std  );
  ch->SetBranchAddress("ecc_rp",       &ecc_rp  );
  ch->SetBranchAddress("ecc_part",     &ecc_part );
  ch->SetBranchAddress("r_ollitra",    &r_oll );
  ch->SetBranchAddress("r_geo",        &r_geo );
  ch->SetBranchAddress("r_arith",      &r_arith );
  ch->SetBranchAddress("e4",           &e4       );
  ch->SetBranchAddress("qBBC_n",       &qBBC_n   );
  ch->SetBranchAddress("qBBC_s",       &qBBC_s   );
  ch->SetBranchAddress("nHitBbc_n",    &nHitBbc_n);
  ch->SetBranchAddress("nHitBbc_s",    &nHitBbc_s);

  char fname[100];
  sprintf(fname,"rootfile/g%s_cent.root",xname);
  TFile* fout = new TFile(fname,"recreate");//rootfile to save distributions

  TH1* hbbcq    = new TH1D("hbbcq","hbbcq",12000,-0.5,2999.5);      hbbcq->Sumw2();
  TH1* hbbcqall = new TH1D("hbbcqall","hbbcqall",12000,-0.5,2999.5);hbbcqall->Sumw2();
  TH1* hbbcqeff = new TH1D("hbbcqeff","hbbcqeff",12000,-0.5,2999.5);hbbcqeff->Sumw2();

  n = ch->GetEntries();
  cout << "events: "<< n << endl;

  //First loop determines the BBC trigger efficiency
  //as function of bbcq;
  for(int i=0; i<n; i++){
    ch->GetEntry(i);

    if(nHitBbc_n>=2&&nHitBbc_s>=2){
      hbbcq->Fill( (qBBC_n+qBBC_s)/100. );//divide by 100 to fit in 0-3000 range
    }

    hbbcqall->Fill( (qBBC_n+qBBC_s)/100. );
  }
  hbbcqeff->Divide(hbbcq,hbbcqall);

  efficiency = hbbcq->Integral()/hbbcqall->Integral();
  cout << "efficiency : " << efficiency << endl;

  //hbin contains the integrated fraction starting from 0 bbc charge, including the BBC trigger efficiency
  TH1* hbin = new TH1D("hbin","hbin",hbbcq->GetNbinsX(),-0.5,2999.5);
  TH1* hbbcqscale = (TH1*)hbbcq->Clone("hbbcqscale");
  hbbcqscale->Scale(1.0/hbbcq->Integral());
  for(int i=1; i<=hbbcqscale->GetNbinsX(); i++){
    hbin->SetBinContent(i,hbbcqscale->Integral(1,i));
  }
  //Following two lines defines the array of cuts and average bbc charge
  //for centrality percentitle in 5%, 10% and 20% steps
  double bbcq5[21],bbcq10[11],bbcq20[6];
  double abbcq5[20],abbcq10[10],abbcq20[5];

  //calculate the various variables for 5% step
  GetCentrality(hbin,20,bbcq5,hbbcq,abbcq5);
  cout << endl << endl;

  //calculate the various variables for 10% step
  GetCentrality(hbin,10,bbcq10,hbbcq,abbcq10);
  cout << endl << endl;

  //calculate the various variables for 20% step
  GetCentrality(hbin,5,bbcq20,hbbcq,abbcq20);
  cout << endl << endl;

  cout << " Find cuts for all the centralities " << endl << endl;

  const int nval=9;//number of variables to fill
  char* centname[3] = {"5pStep","10pStep","20pStep"};
  char* varname[nval] = {"npart","ncoll","b","standard_ecc","reactionplane_ecc","participant_ecc","R_Ollitraut","R_Geo", "R_arith"};
  double vup[nval] = {499.5,2999.5,19.995,1,1,1,4,4,4};
  double vlo[nval] = {-0.5,-0.5,-0.005,-1,-1,-1,0,0,0};
  int vNb[nval] = {500,3000,2000,200,200,200,400,400,400};

  //initialize the histograms which are used to fill the distribution of variables for each centrality
  TH1* hvar[3][nval][20];
  for(int i=0; i<3; i++){
    int NC = 0;
    if(i==0) NC = 20;
    else if(i==1) NC = 10;
    else if(i==2) NC = 5;
    for(int ivar=0; ivar<nval; ivar++){
      for(int icen=0; icen<NC; icen++){
	sprintf(name,"hvar_%s_%s_cent%d",centname[i],varname[ivar],icen);
	hvar[i][ivar][icen] = new TH1D(name,name,vNb[ivar],vlo[ivar],vup[ivar]);
      }
    }
  }

  double qbbcsum;
  for(int i=0; i<n; i++){
    if(i%1000000==0) cout << i << endl;
    ch->GetEntry(i);

    if(!(nHitBbc_n>=2&&nHitBbc_s>=2)) continue;//BBC trigger condition

    qbbcsum = (qBBC_n+qBBC_s)/100.;

    int centbin5  = FindBin(20,bbcq5,qbbcsum);
    int centbin10 = FindBin(10,bbcq10,qbbcsum);
    int centbin20 = FindBin(5,bbcq20,qbbcsum);

    if(centbin5==-1) continue;
    if(centbin10==-1) continue;
    if(centbin20==-1) continue;

    //find the weight according to the corresponding average efficiency.
    double weight = hbbcqeff->GetBinContent(hbbcqeff->FindBin(qbbcsum));
    //5 percent step
    //
    hvar[0][0][centbin5]->Fill(npart,weight);
    hvar[0][1][centbin5]->Fill(ncoll,weight);
    hvar[0][2][centbin5]->Fill(b,weight);
    hvar[0][3][centbin5]->Fill(ecc_std,weight);
    hvar[0][4][centbin5]->Fill(ecc_rp,weight);
    hvar[0][5][centbin5]->Fill(ecc_part,weight);
    hvar[0][6][centbin5]->Fill(r_oll,weight);
    hvar[0][7][centbin5]->Fill(r_geo,weight);
    hvar[0][8][centbin5]->Fill(r_arith,weight);

    //10 percent step
    //
    hvar[1][0][centbin10]->Fill(npart,weight);
    hvar[1][1][centbin10]->Fill(ncoll,weight);
    hvar[1][2][centbin10]->Fill(b,weight);
    hvar[1][3][centbin10]->Fill(ecc_std,weight);
    hvar[1][4][centbin10]->Fill(ecc_rp,weight);
    hvar[1][5][centbin10]->Fill(ecc_part,weight);
    hvar[1][6][centbin10]->Fill(r_oll,weight);
    hvar[1][7][centbin10]->Fill(r_geo,weight);
    hvar[1][8][centbin10]->Fill(r_arith,weight);


    //20 percent step
    //
    hvar[2][0][centbin20]->Fill(npart,weight);
    hvar[2][1][centbin20]->Fill(ncoll,weight);
    hvar[2][2][centbin20]->Fill(b,weight);
    hvar[2][3][centbin20]->Fill(ecc_std,weight);
    hvar[2][4][centbin20]->Fill(ecc_rp,weight);
    hvar[2][5][centbin20]->Fill(ecc_part,weight);
    hvar[2][6][centbin20]->Fill(r_oll,weight);
    hvar[2][7][centbin20]->Fill(r_geo,weight);
    hvar[2][8][centbin20]->Fill(r_arith,weight);
  }

  //get mean and RMS values for the variables
  float var[3][nval+1][20];
  float rms[3][nval+1][20];
  for(int i=0; i<3; i++){
    int NC = 0;
    if(i==0) NC = 20;
    else if(i==1) NC = 10;
    else if(i==2) NC = 5;
    for(int icen=0; icen<NC; icen++){
      for(int ivar=0; ivar<nval; ivar++){
	var[i][ivar][icen] = hvar[i][ivar][icen]->GetMean();
	rms[i][ivar][icen] = hvar[i][ivar][icen]->GetRMS();
      }
      var[i][nval][icen] = var[i][1][icen]/sigmann;
      rms[i][nval][icen] = rms[i][1][icen]/sigmann;
    }
  }
  //save to file
  for(int ivar=0; ivar<4; ivar++){
    for(int icen=0; icen<16; icen++){
      cout<<var[0][ivar][icen]<<",";
    }
    cout<<var[2][ivar][4]<<",";
    cout<<endl;
  }

  cout.precision(4);

  sprintf(name,"5pstepresults/t%s.txt",xname);
  ofstream f5(name);
  cout << " Bin % &  npart &  ncoll &  b & ecc_std & ecc_rp & ecc_part & r_ollitrau & T_{AB}\\\\\\hline" << endl;
  for(int icen=0; icen<19; icen++){
    for(int ivar=0; ivar<7; ivar++){
      f5 << var[0][ivar][icen] << " ";
    }
    f5 << var[0][nval][icen] << " ";
    f5 <<endl<<  " (";
    /* for(int ivar=0; ivar<7; ivar++){
      f5 << rms[0][ivar][icen] << " ";
    }
    f5 << rms[0][nval][icen] << " ";
    f5 <<  ")"<< endl;
    */
    cout << icen*5 << "-" << icen*5+5;
    for(int ivar=0; ivar<7; ivar++){
      cout <<" & " <<var[0][ivar][icen] ;
    }
    cout <<" & " <<var[0][nval][icen] ;
    cout <<"\\\\"<<endl;
    for(int ivar=0; ivar<7; ivar++){
      if(ivar==0)cout <<" & ("<<rms[0][ivar][icen];
      else cout <<" & "<<rms[0][ivar][icen];
    }
    cout <<" & "<<rms[0][nval][icen];
    cout <<  ")\\\\\\hline" << endl;

    // printf(" & %3.1f & %4.1f & %2.2f & %1.3f & %1.3f & %1.3f & %1.3f \\\\\n",
    //	   var[0][0][icen],var[0][1][icen],var[0][2][icen],var[0][3][icen],var[0][4][icen],var[0][5][icen],var[0][6][icen]);
    //printf(" (& %3.1f & %4.1f & %2.2f & %1.3f & %1.3f & %1.3f & %1.3f) \\\\\\hline\n",
    //       rms[0][0][icen],rms[0][1][icen],rms[0][2][icen],rms[0][3][icen],rms[0][4][icen],rms[0][5][icen],rms[0][6][icen]);
  }
  f5.close();

  cout << endl << endl;
  sprintf(name,"10pstepresults/t%s.txt",xname);
  ofstream f10(name);
  cout <<endl<< " Bin % &  npart &  ncoll &  b & ecc_std & ecc_rp & ecc_part & r_ollitrau & T_{AB}\\\\\\hline" << endl;
  for(int icen=0; icen<10; icen++){
    for(int ivar=0; ivar<7; ivar++){
      f10 << var[1][ivar][icen] << " ";
    }
    f10 << var[1][nval][icen] << " ";
    f10 <<endl<<" (";
    /*for(int ivar=0; ivar<7; ivar++){
      f10 << rms[1][ivar][icen] << " ";
    }
    f10 << rms[1][nval][icen] << " ";
    f10 <<  ")" << endl;
    */
    cout << icen*10 << "-" << icen*10+10;
    for(int ivar=0; ivar<7; ivar++){
      cout <<" & " <<var[1][ivar][icen] ;
    }
    cout <<" & " <<var[1][nval][icen] ;
    cout <<"\\\\"<<endl;
    for(int ivar=0; ivar<7; ivar++){
      if(ivar==0)cout <<" & ("<<rms[1][ivar][icen];
      else cout <<" & "<<rms[1][ivar][icen];
    }
    cout <<" & "<<rms[1][nval][icen];
    cout <<  ")\\\\\\hline" << endl;

    //printf(" & %3.1f & %4.1f & %2.2f & %1.3f & %1.3f & %1.3f & %1.3f \\\\\n",
    //       var[1][0][icen],var[1][1][icen],var[1][2][icen],var[1][3][icen],var[1][4][icen],var[1][5][icen],var[1][6][icen]);
    //printf(" (& %3.1f & %4.1f & %2.2f & %1.3f & %1.3f & %1.3f & %1.3f) \\\\\\hline\n",
    //       rms[1][0][icen],rms[1][1][icen],rms[1][2][icen],rms[1][3][icen],rms[1][4][icen],rms[1][5][icen],rms[1][6][icen]);

  }
  f10.close();

  cout << endl << endl;
  sprintf(name,"20pstepresults/t%s.txt",xname);
  ofstream f20(name);
  cout <<endl<< " Bin % &  npart &  ncoll &  b & ecc_std & ecc_rp & ecc_part & r_ollitrau & T_{AB}\\\\\\hline" << endl;
  for(int icen=0; icen<5; icen++){
    for(int ivar=0; ivar<7; ivar++){
      f20 << var[2][ivar][icen] << " ";
    }
    f20 << var[2][nval][icen] << " ";
    f20 << endl<<  " (";

    /*for(int ivar=0; ivar<7; ivar++){
      f20 << rms[2][ivar][icen] << " ";
    }
    f20 << rms[2][nval][icen] << " ";
    f20 <<  ")"<< endl;
    */
    cout << icen*20 << "-" << icen*20+20;
    for(int ivar=0; ivar<7; ivar++){
      cout <<" & " <<var[2][ivar][icen] ;
    }
    cout <<" & " <<var[2][nval][icen] ;
    cout <<"\\\\"<<endl;
    for(int ivar=0; ivar<7; ivar++){
      if(ivar==0)cout <<" & ("<<rms[2][ivar][icen];
      else cout <<" & "<<rms[2][ivar][icen];
    }
    cout <<" & "<<rms[2][nval][icen];
    cout <<  ")\\\\\\hline" << endl;
    //printf(" & %3.1f & %4.1f & %2.2f & %1.3f & %1.3f & %1.3f & %1.3f \\\\\n",
    //       var[2][0][icen],var[2][1][icen],var[2][2][icen],var[2][3][icen],var[2][4][icen],var[2][5][icen],var[2][6][icen]);
    //printf(" (& %3.1f & %4.1f & %2.2f & %1.3f & %1.3f & %1.3f & %1.3f) \\\\\\hline\n",
    //       rms[2][0][icen],rms[2][1][icen],rms[2][2][icen],rms[2][3][icen],rms[2][4][icen],rms[2][5][icen],rms[2][6][icen]);

  }
  f20.close();

  fout->Write();
  fout->Close();

  return;
}
Пример #19
0
void simul(int Nevents = 200000, double Twist_width = 0.04, double Asy_wdith   = 0.06){

    char name[200];

    TFile *OutFile=new TFile("Simu3.root","recreate");
    OutFile->cd();
    TRandom3 ran;

    //20-25% events have ~1092 multiplicity
    const int MEAN_MULT =1092,SIGMA_MULT=86 ;//Mean and rms of total multiplicity (det0+det1+det2)
    int min=MEAN_MULT-5*SIGMA_MULT;
    int max=MEAN_MULT+5*SIGMA_MULT;
    if(min<0) min=0;
    TF1 *Mult_func=new TF1("mult_func","exp(-(x-[0])*(x-[0])/(2*[1]*[1]))",min,max);
    Mult_func->SetParameter(0,MEAN_MULT );
    Mult_func->SetParameter(1,SIGMA_MULT);
    //

    TFile* fout = new TFile("toyout.root","recreate");
    TF1* v2_func=new TF1("v2_func","x*exp(-(x*x+[0]*[0])/(2*[1]))*TMath::BesselI0(x*[0]/[1])",0,0.40);
    v2_func->SetParameter(0,9.13212e-02);
    v2_func->SetParameter(1,1.20361e-03);
    //

    Float_t v2   =0          ;//true v2   at eta=0, this will be the refer
    Float_t Psi2 =0          ;//true Psi2 at eta=0
    
    float vncut[] = {0.00, 0.04, 0.06,0.1, 0.12, 0.14, 0.15};
    
    TProfile* hpr_qn[2];
    for (int iq=0; iq<2; iq++) {
        sprintf(name, "hpr_qn_%d", iq); hpr_qn[iq] = new TProfile(name,"", 7, 0, 7);
    }
    TH1* hebin = new TH1D("hebin","", 7, 0, 7);
    TH1* hmul = new TH1D("hmul","", 2000, 0, 2000);
    TH1* hmuleta = new TH1D("hmuleta","", NETA, -ETAMAX, ETAMAX);
    TH1* hmulphi = new TH1D("hmulphi","", 120 , -PI, PI);
    TH1* hv2 = new TH1D("hv2","",1000, 0, 0.5);
    TH1* hv4 = new TH1D("hv4","",1000, 0, 0.5);
    double q2[2];
    double q4[2];
    float qw;
    for(int iev=0; iev<Nevents; iev++){

        if(iev%10000==0) cout<<iev<<endl;

        v2     = v2_func->GetRandom();//0.05;//True v2
        Psi2   = ((ran.Rndm()-0.5)*2*PI)/2.0; //True Psi_2 angle
       
       // int ntrk =  1092;
        int ntrk =  8000;
        qw = 0;
        std::memset(q2, 0, sizeof(q2) );
        std::memset(q4, 0, sizeof(q4) );
        
        for(int itrk =0; itrk<ntrk; itrk++){

            float phi = (ran.Rndm()-0.5)*2*PI;//random angle for the particle

            float trk_vn   =  v2 ;
            float trk_psin =  Psi2;
            
            phi =add_flow(phi ,trk_vn, trk_psin);
            q2[0] += cos(2*phi); q2[1] += sin(2*phi);
            q4[0] += cos(4*phi); q4[1] += sin(4*phi);
            qw++;

        }//end of itrk
        
        double mv2 = sqrt(q2[0]*q2[0] + q2[1]*q2[1]);
        double mv4 = sqrt(q4[0]*q4[0] + q4[1]*q4[1]);
        
        
        mv2 = mv2/qw;
        mv4 = mv4/qw;
        
        int ebin = 0;

        for (int j=0; j<7; j++) {
            if(mv2>= vncut[7-1-j]){
                ebin = 7-1-j;
                break;
            }
        }
        
        hv2->Fill(  mv2 );
        hv4->Fill(  mv4 );
        
        hpr_qn[0]->Fill(ebin, mv2);
        hpr_qn[1]->Fill(ebin, mv4);
        hebin->Fill( ebin );
        
    }//end of iev
  
    
    float xx[7] = {0};
    float xxE[7] = {0};
    float yy[7] = {0};
    float yyE[7] = {0};
    
    for (int j=0; j<7; j++) {
        xx[j] =hpr_qn[0]->GetBinContent( j+1); xxE[j] =hpr_qn[0]->GetBinError( j+1);
        yy[j] =hpr_qn[1]->GetBinContent( j+1); yyE[j] =hpr_qn[1]->GetBinError( j+1);
    }
    
    TGraphErrors* gr = new TGraphErrors(7,xx, yy, xxE, yyE);
    
    hv2->Write();
    hv4->Write();
    gr->SetName("gr");
    gr->Write();
    hebin->Write();
    hpr_qn[0]->Write();
    hpr_qn[1]->Write();
    v2_func->Write();
    
    cout<<"Task ends"<<endl;
}//end of sim
void plotMarkovChainMonitorTree()
{
  std::string inputFilePath = "/data1/veelken/tmp/svFitStudies/";

  std::vector<std::string> eventsToProcess;
  eventsToProcess.push_back("1:102093:40804761");
  //eventsToProcess.push_back("1:3369:1346645");
  //eventsToProcess.push_back("1:89621:35819785");
  //eventsToProcess.push_back("1:79157:31638382");

  std::string genNtupleFileName = "/data1/veelken/tmp/svFitStudies/testNSVfitTrackLikelihoods3_ntuple_Higgs_mutau_125_2012Nov30.root";

  gROOT->SetBatch(true);

  for ( std::vector<std::string>::const_iterator eventToProcess = eventsToProcess.begin();
	eventToProcess != eventsToProcess.end(); ++eventToProcess ) {
    std::cout << "processing " << (*eventToProcess) << std::endl;
    TObjArray* run_ls_event = TString(eventToProcess->data()).Tokenize(":");
    assert(run_ls_event);
    if ( run_ls_event->GetEntries() != 3 ) {
      std::cerr << "Failed to parse " << (*eventToProcess) << " !!" << std::endl;
      assert(0);
    }

    int run = convertToInt(*run_ls_event, 0);
    int ls = convertToInt(*run_ls_event, 1);
    int event = convertToInt(*run_ls_event, 2);

    std::string inputFileName = Form(
      "%s/nSVfitProducerByIntegration2W%sMaxGenVertex_run%i_ls%i_ev%i_mc.root", 
      inputFilePath.data(), "decayKinePlusMEt", run, ls, event);
    TFile* inputFile = new TFile(inputFileName.data());
    assert(inputFile);

    std::string treeName = "monitorTree";
    TTree* monitorTree = dynamic_cast<TTree*>(inputFile->Get(treeName.data()));
    assert(monitorTree);

    int numEntries = monitorTree->GetEntries();

    TH2* histogramDensity_vs_X1_and_X2           = new TH2D("histogramDensity_vs_X1_and_X2",           "histogramDensity_vs_X1_and_X2",            100, 0., 1., 100, 0., 1.);
    TH2* histogramMass_vs_X1_and_X2              = new TH2D("histogramMass_vs_X1_and_X2",              "histogramMass_vs_X1_and_X2",               100, 0., 1., 100, 0., 1.);

    TH2* histogramDensity_vs_decayDist1_and_phi1 = new TH2D("histogramDensity_vs_decayDist1_and_phi1", "histogramDensity_vs_decayDist1_and_phi1",  200, -0.2, +0.2, 180, -TMath::Pi(), +TMath::Pi());
    TH2* histogramDensity_vs_X1_and_phi1         = new TH2D("histogramDensity_vs_X1_and_phi1",         "histogramDensity_vs_X1_and_phi1",          100,  0.,   1.,  180, -TMath::Pi(), +TMath::Pi());
    TH2* histogramDensity_vs_decayDist2_and_phi2 = new TH2D("histogramDensity_vs_decayDist2_and_phi2", "histogramDensity_vs_decayDist2_and_phi2",  200, -0.2, +0.2, 180, -TMath::Pi(), +TMath::Pi());
    TH2* histogramDensity_vs_X2_and_phi2         = new TH2D("histogramDensity_vs_X2_and_phi2",         "histogramDensity_vs_X2_and_phi2",          100,  0.,   1.,  180, -TMath::Pi(), +TMath::Pi());
        
    TH1* histogramDiTauPtDistribution            = new TH1D("histogramDiTauPtDistribution",            "histogramDiTauPtDistribution",             250, 0., 250.);
    TH1* histogramDiTauEtaDistribution           = new TH1D("histogramDiTauEtaDistribution",           "histogramDiTauEtaDistribution",            198, -9.9, +9.9);
    TH1* histogramDiTauPhiDistribution           = new TH1D("histogramDiTauPhiDistribution",           "histogramDiTauPhiDistribution",            360, -TMath::Pi(), +TMath::Pi());
    TH1* histogramDiTauMassDistribution          = new TH1D("histogramDiTauMassDistribution",          "histogramDiTauMassDistribution",           250, 0., 250.);
    
    TH1* histogramSVfitMass_unweighted                      = bookMassHistogram("histogramSVfitMass_unweighted");
    TH1* histogramSVfitMass_gjAngle_labGt0_00025_unweighted = bookMassHistogram("histogramSVfitMass_gjAngle_labGt0_00025_unweighted");
    TH1* histogramSVfitMass_gjAngle_labLt0_00025_unweighted = bookMassHistogram("histogramSVfitMass_gjAngle_labLt0_00025_unweighted");
    TH1* histogramSVfitMass_weighted                        = bookMassHistogram("histogramSVfitMass_weighted");
    TH1* histogramSVfitMass_gjAngle_labGt0_00025_weighted   = bookMassHistogram("histogramSVfitMass_gjAngle_labGt0_00025_weighted");
    TH1* histogramSVfitMass_gjAngle_labLt0_00025_weighted   = bookMassHistogram("histogramSVfitMass_gjAngle_labLt0_00025_weighted");

    TH1* histogramLeg1PtDistribution             = new TH1D("histogramLeg1PtDistribution",             "histogramLeg1PtDistribution",              250, 0., 250.);
    TH1* histogramLeg1EtaDistribution            = new TH1D("histogramLeg1EtaDistribution",            "histogramLeg1EtaDistribution",             198, -9.9, +9.9);
    TH1* histogramLeg1PhiDistribution            = new TH1D("histogramLeg1PhiDistribution",            "histogramLeg1PhiDistribution",             360, -TMath::Pi(), +TMath::Pi());
    TH1* histogramLeg1dEtaDistribution           = new TH1D("histogramLeg1dEtaDistribution",           "histogramLeg1dPhiDistribution",            400, -0.05, +0.05);
    TH1* histogramLeg1dPhiDistribution           = new TH1D("histogramLeg1dPhiDistribution",           "histogramLeg1dEtaDistribution",            400, -0.05, +0.05);
    TH2* histogramLeg1dPhi_vs_dEtaDistribution   = new TH2D("histogramLeg1dPhi_vs_dEtaDistribution",   "histogramLeg1dPhi_vs_dEtaDistribution",    400, -0.05, +0.05, 400, -0.05, +0.05);

    TH1* histogramLeg2PtDistribution             = new TH1D("histogramLeg2PtDistribution",             "histogramLeg1PtDistribution",              250, 0., 250.);
    TH1* histogramLeg2EtaDistribution            = new TH1D("histogramLeg2EtaDistribution",            "histogramLeg2EtaDistribution",             198, -9.9, +9.9);
    TH1* histogramLeg2PhiDistribution            = new TH1D("histogramLeg2PhiDistribution",            "histogramLeg2PhiDistribution",             360, -TMath::Pi(), +TMath::Pi());
    TH1* histogramLeg2dEtaDistribution           = new TH1D("histogramLeg2dEtaDistribution",           "histogramLeg2dPhiDistribution",            400, -0.05, +0.05);
    TH1* histogramLeg2dPhiDistribution           = new TH1D("histogramLeg2dPhiDistribution",           "histogramLeg2dEtaDistribution",            400, -0.05, +0.05);
    TH2* histogramLeg2dPhi_vs_dEtaDistribution   = new TH2D("histogramLeg2dPhi_vs_dEtaDistribution",   "histogramLeg2dPhi_vs_dEtaDistribution",    400, -0.05, +0.05, 400, -0.05, +0.05);

    TH1* histogramMoveDistribution               = new TH1D("histogramMoveDistribution",               "histogramMoveDistribution",               1000, 0., monitorTree->GetEntries());

    TGraph* graphEvolution_X1                    = new TGraph(numEntries);
    TGraph* graphEvolution_phiLab1               = new TGraph(numEntries);
    TGraph* graphEvolution_decayDist1            = new TGraph(numEntries);
    TGraph* graphEvolution_X2                    = new TGraph(numEntries);
    TGraph* graphEvolution_phiLab2               = new TGraph(numEntries);
    TGraph* graphEvolution_decayDist2            = new TGraph(numEntries);

    Float_t X1, phiLab1, decayDistance1, X2, phiLab2, decayDistance2;
    monitorTree->SetBranchAddress("x0", &X1);
    monitorTree->SetBranchAddress("x1", &phiLab1);
    //monitorTree->SetBranchAddress("x2", &decayDistance1);
    //monitorTree->SetBranchAddress("x3", &X2);
    //monitorTree->SetBranchAddress("x4", &phiLab2);
    //monitorTree->SetBranchAddress("x5", &decayDistance2);
    //monitorTree->SetBranchAddress("x0", &X1);
    //monitorTree->SetBranchAddress("x1", &phiLab1);
    monitorTree->SetBranchAddress("x2", &X2);
    monitorTree->SetBranchAddress("x3", &phiLab2);
    //monitorTree->SetBranchAddress("x1", &X2);
    //monitorTree->SetBranchAddress("x0", &phiLab1);
    //monitorTree->SetBranchAddress("x1", &phiLab2);

    Float_t diTauPt, diTauEta, diTauPhi, diTauMass;
    monitorTree->SetBranchAddress("APt", &diTauPt);
    monitorTree->SetBranchAddress("AEta", &diTauEta);
    monitorTree->SetBranchAddress("APhi", &diTauPhi);
    monitorTree->SetBranchAddress("AMass", &diTauMass);

    Float_t leg1Pt, leg1Eta, leg1Phi, leg1VisPt, leg1VisEta, leg1VisPhi;
    monitorTree->SetBranchAddress("A_leg1Pt", &leg1Pt);
    monitorTree->SetBranchAddress("A_leg1Eta", &leg1Eta);
    monitorTree->SetBranchAddress("A_leg1Phi", &leg1Phi);
    monitorTree->SetBranchAddress("A_leg1VisPt", &leg1VisPt);
    monitorTree->SetBranchAddress("A_leg1VisEta", &leg1VisEta);
    monitorTree->SetBranchAddress("A_leg1VisPhi", &leg1VisPhi);

    Float_t leg2Pt, leg2Eta, leg2Phi, leg2VisPt, leg2VisEta, leg2VisPhi;
    monitorTree->SetBranchAddress("A_leg2Pt", &leg2Pt);
    monitorTree->SetBranchAddress("A_leg2Eta", &leg2Eta);
    monitorTree->SetBranchAddress("A_leg2Phi", &leg2Phi);
    monitorTree->SetBranchAddress("A_leg2VisPt", &leg2VisPt);
    monitorTree->SetBranchAddress("A_leg2VisEta", &leg2VisEta);
    monitorTree->SetBranchAddress("A_leg2VisPhi", &leg2VisPhi);
    
    Int_t move;
    monitorTree->SetBranchAddress("move", &move);

    TF1* pdfWeight_vs_eta_m90 = new TF1("pdfWeight_vs_eta", "[0] + x*([1] + x*([2] + x*([3] + x*([4] + x*([5]  + x*[6])))))", -2., +2.); 
    pdfWeight_vs_eta_m90->SetParameter(0, 0.173744);
    pdfWeight_vs_eta_m90->SetParameter(1, 1.00115e-18);
    pdfWeight_vs_eta_m90->SetParameter(2, -0.0370055);
    pdfWeight_vs_eta_m90->SetParameter(3, 3.40875e-17);
    pdfWeight_vs_eta_m90->SetParameter(4, -0.014232);
    pdfWeight_vs_eta_m90->SetParameter(5, -1.07345e-17);
    pdfWeight_vs_eta_m90->SetParameter(6, 0.00320732);

    for ( int iEntry = 0; iEntry < numEntries; ++iEntry ) {
      monitorTree->GetEntry(iEntry);
      
      if ( (iEntry % 100000) == 0 ) 
      //if ( TMath::Abs(leg1Eta - leg1VisEta) < 0.000250 && TMath::Abs(leg1Phi - leg1VisPhi) < 0.000250 )
	std::cout << "entry #" << iEntry << ":" 
		  << " X1 = " << X1 << ", phiLab1 = " << phiLab1 << ", decayDistance1 = " << decayDistance1 << "," 
		  << " X2 = " << X2 << ", phiLab2 = " << phiLab2 << ", decayDistance2 = " << decayDistance2 << ", Mass = " << diTauMass << std::endl;
      
      //if ( !(leg2Eta > 0.0485 && leg2Eta < 0.0495) ) continue;
      //if ( !(phiLab1 > 1. && phiLab1 < 2.) ) continue;
      //if ( !(phiLab1 > -2. && phiLab1 < -1.) ) continue;

      histogramDensity_vs_X1_and_X2->Fill(X1, X2);
      histogramMass_vs_X1_and_X2->Fill(X1, X2, diTauMass);

      histogramDensity_vs_decayDist1_and_phi1->Fill(decayDistance1, phiLab1);
      histogramDensity_vs_X1_and_phi1->Fill(X1, phiLab1);
      histogramDensity_vs_decayDist2_and_phi2->Fill(decayDistance2, phiLab2);
      histogramDensity_vs_X2_and_phi2->Fill(X2, phiLab2);
    
      histogramDiTauPtDistribution->Fill(diTauPt);
      histogramDiTauEtaDistribution->Fill(diTauEta);
      histogramDiTauPhiDistribution->Fill(diTauPhi);
      histogramDiTauMassDistribution->Fill(diTauMass);

      double gjAngle_lab = TMath::Sqrt(square(leg1Eta - leg1VisEta) + square(leg1Phi - leg1VisPhi));
      double jacobiFactor = 2.*TMath::Pi()*gjAngle_lab;
      //double weight = jacobiFactor;
      //double weight = pdfWeight_vs_eta_m90->Eval(diTauEta);
      double weight = compDeltaFunctionJacobiFactor(X1)*compDeltaFunctionJacobiFactor(X2);
      //double weight = compDeltaFunctionJacobiFactor(X1)*compDeltaFunctionJacobiFactor(X2)*(X1*X2);      
      std::cout << "eta = " << diTauEta << ": weight = " << weight << std::endl;
      histogramSVfitMass_unweighted->Fill(diTauMass);
      histogramSVfitMass_weighted->Fill(diTauMass, weight);
      if ( gjAngle_lab > 0.00025 ) {
	histogramSVfitMass_gjAngle_labGt0_00025_unweighted->Fill(diTauMass);
	histogramSVfitMass_gjAngle_labGt0_00025_weighted->Fill(diTauMass, weight);
      } else {
	histogramSVfitMass_gjAngle_labLt0_00025_unweighted->Fill(diTauMass);
	histogramSVfitMass_gjAngle_labLt0_00025_weighted->Fill(diTauMass, weight);
      }

      histogramLeg1PtDistribution->Fill(leg1Pt);
      histogramLeg1EtaDistribution->Fill(leg1Eta);
      histogramLeg1PhiDistribution->Fill(leg1Phi);
      histogramLeg1dEtaDistribution->Fill(leg1Eta - leg1VisEta);
      histogramLeg1dPhiDistribution->Fill(leg1Phi - leg1VisPhi);
      histogramLeg1dPhi_vs_dEtaDistribution->Fill(leg1Eta - leg1VisEta, leg1Phi - leg1VisPhi);
      //std::cout << "leg1Eta = " << leg1Eta << ", leg1VisEta = " << leg1VisEta << " --> dEta = " << (leg1Eta - leg1VisEta) << ";"
      //	  << " leg1Phi = " << leg1Phi << ", leg1VisPhi = " << leg1VisPhi << " --> dPhi = " << (leg1Phi - leg1VisPhi) << std::endl;

      histogramLeg2PtDistribution->Fill(leg2Pt);
      histogramLeg2EtaDistribution->Fill(leg2Eta);
      histogramLeg2PhiDistribution->Fill(leg2Phi);
      histogramLeg2dEtaDistribution->Fill(leg2Eta - leg2VisEta);
      histogramLeg2dPhiDistribution->Fill(leg2Phi - leg2VisPhi);
      histogramLeg2dPhi_vs_dEtaDistribution->Fill(leg2Eta - leg2VisEta, leg2Phi - leg2VisPhi);
      //std::cout << "leg2Eta = " << leg2Eta << ", leg2VisEta = " << leg2VisEta << " --> dEta = " << (leg2Eta - leg2VisEta) << ";"
      //	  << " leg2Phi = " << leg2Phi << ", leg2VisPhi = " << leg2VisPhi << " --> dPhi = " << (leg2Phi - leg2VisPhi) << std::endl;

      histogramMoveDistribution->Fill(move);

      graphEvolution_X1->SetPoint(iEntry, move, X1);
      graphEvolution_phiLab1->SetPoint(iEntry, move, phiLab1);
      graphEvolution_decayDist1->SetPoint(iEntry, move, decayDistance1);
      graphEvolution_X2->SetPoint(iEntry, move, X2);
      graphEvolution_phiLab2->SetPoint(iEntry, move, phiLab2);
      graphEvolution_decayDist2->SetPoint(iEntry, move, decayDistance2);
    }
    
    histogramMass_vs_X1_and_X2->Divide(histogramDensity_vs_X1_and_X2);
    
    Float_t genX1, genX2;
    Float_t genDiTauPt, genDiTauEta, genDiTauPhi, genDiTauMass;
    //getGen(genNtupleFileName, run, ls, event, genX1, genX2, genDiTauPt, genDiTauEta, genDiTauPhi, genDiTauMass);
/*
    showHistogram2d(
      histogramDensity_vs_X1_and_X2, "X_{1}", "X_{2}", kNormByNegLogMax, 0.,   2., &genX1, &genX2, 
      Form("plots/plotMarkovChainMonitorTree_density_vs_X1andX2_run%i_ls%i_ev%i.root", run, ls, event));
    showHistogram2d(
      histogramMass_vs_X1_and_X2, "X_{1}", "X_{2}", kNormByValue, 0., 250., 0, 0, 
      Form("plots/plotMarkovChainMonitorTree_mass_vs_X1andX2_run%i_ls%i_ev%i.root", run, ls, event));

    showHistogram2d(
      histogramDensity_vs_decayDist1_and_phi1, "D^{decay}_{1}", "#phi^{lab}_{1}", kNormByNegLogMax, 0., 2., 0, 0, 
      Form("plots/plotMarkovChainMonitorTree_density_vs_decayDist1andPhi1_run%i_ls%i_ev%i.root", run, ls, event));
    showHistogram2d(
      histogramDensity_vs_X1_and_phi1, "X_{1}", "#phi^{lab}_{1}", kNormByNegLogMax, 0., 2., 0, 0, 
      Form("plots/plotMarkovChainMonitorTree_density_vs_X1andPhi1_run%i_ls%i_ev%i.root", run, ls, event));
    showHistogram2d(
      histogramDensity_vs_decayDist2_and_phi2, "D^{decay}_{2}", "#phi^{lab}_{2}", kNormByNegLogMax, 0., 2., 0, 0, 
      Form("plots/plotMarkovChainMonitorTree_density_vs_decayDist2andPhi2_run%i_ls%i_ev%i.root", run, ls, event));
    showHistogram2d(
      histogramDensity_vs_X2_and_phi2, "X_{2}", "#phi^{lab}_{2}", kNormByNegLogMax, 0., 2., 0, 0, 
      Form("plots/plotMarkovChainMonitorTree_density_vs_X2andPhi2_run%i_ls%i_ev%i.root", run, ls, event));
    
    showHistogram1d(
      histogramDiTauPtDistribution, "P_{T}^{#tau#tau}", &genDiTauPt, 
      Form("plots/plotMarkovChainMonitorTree_diTauPtDistribution_run%i_ls%i_ev%i.root", run, ls, event));
    showHistogram1d(
      histogramDiTauEtaDistribution, "#eta_{#tau#tau}", &genDiTauEta, 
      Form("plots/plotMarkovChainMonitorTree_diTauEtaDistribution_run%i_ls%i_ev%i.root", run, ls, event));
    showHistogram1d(
      histogramDiTauPhiDistribution, "#phi_{#tau#tau}", &genDiTauPhi, 
      Form("plots/plotMarkovChainMonitorTree_diTauPhiDistribution_run%i_ls%i_ev%i.root", run, ls, event));
    showHistogram1d(
      histogramDiTauMassDistribution, "M_{#tau#tau}", &genDiTauMass, 
      Form("plots/plotMarkovChainMonitorTree_diTauMassDistribution_run%i_ls%i_ev%i.root", run, ls, event));
 */
    divideByBinWidth(histogramSVfitMass_unweighted);
    std::cout << "SVfit mass (unweighted):" << std::endl;
    printMaximum(histogramSVfitMass_unweighted);
    showHistogram1d(
      histogramSVfitMass_unweighted, "M_{#tau#tau}", &genDiTauMass, 
      Form("plots/plotMarkovChainMonitorTree_svFitMass_unweighted_run%i_ls%i_ev%i.root", run, ls, event));
    divideByBinWidth(histogramSVfitMass_gjAngle_labGt0_00025_unweighted);
    showHistogram1d(
      histogramSVfitMass_gjAngle_labGt0_00025_unweighted, "M_{#tau#tau}", &genDiTauMass, 
      Form("plots/plotMarkovChainMonitorTree_svFitMass_gjAngle_labGt0_00025_unweighted_run%i_ls%i_ev%i.root", run, ls, event));
    divideByBinWidth(histogramSVfitMass_gjAngle_labLt0_00025_unweighted);    
    showHistogram1d(
      histogramSVfitMass_gjAngle_labLt0_00025_unweighted, "M_{#tau#tau}", &genDiTauMass, 
      Form("plots/plotMarkovChainMonitorTree_svFitMass_gjAngle_labLt0_00025_unweighted_run%i_ls%i_ev%i.root", run, ls, event));
    divideByBinWidth(histogramSVfitMass_weighted);
    std::cout << "SVfit mass (weighted by Jacobi factor):" << std::endl;
    printMaximum(histogramSVfitMass_weighted);
    showHistogram1d(
      histogramSVfitMass_weighted, "M_{#tau#tau}", &genDiTauMass, 
      Form("plots/plotMarkovChainMonitorTree_svFitMass_weighted_run%i_ls%i_ev%i.root", run, ls, event));
    divideByBinWidth(histogramSVfitMass_gjAngle_labGt0_00025_weighted);
    showHistogram1d(
      histogramSVfitMass_gjAngle_labGt0_00025_weighted, "M_{#tau#tau}", &genDiTauMass, 
      Form("plots/plotMarkovChainMonitorTree_svFitMass_gjAngle_labGt0_00025_weighted_run%i_ls%i_ev%i.root", run, ls, event));
    divideByBinWidth(histogramSVfitMass_gjAngle_labLt0_00025_weighted);    
    showHistogram1d(
      histogramSVfitMass_gjAngle_labLt0_00025_weighted, "M_{#tau#tau}", &genDiTauMass, 
      Form("plots/plotMarkovChainMonitorTree_svFitMass_gjAngle_labLt0_00025_weighted_run%i_ls%i_ev%i.root", run, ls, event));
/*
    showHistogram1d(
      histogramLeg1PtDistribution, "P_{T}^{1}", 0, 
      Form("plots/plotMarkovChainMonitorTree_leg1PtDistribution_run%i_ls%i_ev%i.root", run, ls, event));
    showHistogram1d(
      histogramLeg1EtaDistribution, "#eta_{1}", 0, 
      Form("plots/plotMarkovChainMonitorTree_leg1EtaDistribution_run%i_ls%i_ev%i.root", run, ls, event));
    showHistogram1d(
      histogramLeg1PhiDistribution, "#phi_{1}", 0, 
      Form("plots/plotMarkovChainMonitorTree_leg1PhiDistribution_run%i_ls%i_ev%i.root", run, ls, event));
    showHistogram1d(
      histogramLeg1dEtaDistribution, "#eta_{1} - #eta_{vis}", 0, 
      Form("plots/plotMarkovChainMonitorTree_leg1dEta_run%i_ls%i_ev%i.root", run, ls, event));
    showHistogram1d(
      histogramLeg1dPhiDistribution, "#phi_{1} - #phi_{vis}", 0, 
      Form("plots/plotMarkovChainMonitorTree_leg1dPhi_run%i_ls%i_ev%i.root", run, ls, event));
 */
    showHistogram2d(
      histogramLeg1dPhi_vs_dEtaDistribution, "#eta_{1} - #eta_{vis}", "#phi_{1} - #phi_{vis}", kNormByNegLogMax, 0., 2., 0, 0, 
      Form("plots/plotMarkovChainMonitorTree_leg1dPhi_vs_dEta_run%i_ls%i_ev%i.root", run, ls, event));
/*
    showHistogram1d(
      histogramLeg2PtDistribution, "P_{T}^{2}", 0, 
      Form("plots/plotMarkovChainMonitorTree_leg2PtDistribution_run%i_ls%i_ev%i.root", run, ls, event));
    showHistogram1d(
      histogramLeg2EtaDistribution, "#eta_{2}", 0, 
      Form("plots/plotMarkovChainMonitorTree_leg2EtaDistribution_run%i_ls%i_ev%i.root", run, ls, event));
    showHistogram1d(
      histogramLeg2PhiDistribution, "#phi_{2}", 0, 
      Form("plots/plotMarkovChainMonitorTree_leg2PhiDistribution_run%i_ls%i_ev%i.root", run, ls, event));
    showHistogram1d(
      histogramLeg2dEtaDistribution, "#eta_{2} - #eta_{vis}", 0, 
      Form("plots/plotMarkovChainMonitorTree_leg2dEta_run%i_ls%i_ev%i.root", run, ls, event));
    showHistogram1d(
      histogramLeg2dPhiDistribution, "#phi_{2} - #phi_{vis}", 0, 
      Form("plots/plotMarkovChainMonitorTree_leg2dPhi_run%i_ls%i_ev%i.root", run, ls, event));
    showHistogram2d(
      histogramLeg2dPhi_vs_dEtaDistribution, "#eta_{2} - #eta_{vis}", "#phi_{2} - #phi_{vis}", kNormByNegLogMax, 0., 2., 0, 0, 
      Form("plots/plotMarkovChainMonitorTree_leg2dPhi_vs_dEta_run%i_ls%i_ev%i.root", run, ls, event));

    showHistogram1d(
      histogramMoveDistribution, "Move", 0, 
      Form("plots/plotMarkovChainMonitorTree_moveDistribution_run%i_ls%i_ev%i.root", run, ls, event));
 */
/*    
    showGraph(
      graphEvolution_X1, "Move", &genX1, 0., 1., "X_{1}", 
      Form("plots/plotMarkovChainMonitorTree_evolution_X1_run%i_ls%i_ev%i.root", run, ls, event));
    showGraph(
      graphEvolution_phiLab1, "Move", 0, -TMath::Pi(), +TMath::Pi(), "#phi^{lab}_{1}", 
      Form("plots/plotMarkovChainMonitorTree_evolution_phiLab1_run%i_ls%i_ev%i.root", run, ls, event));
    showGraph(
      graphEvolution_decayDist1, "Move", 0, -1., +1., "D^{decay}_{1}",
      Form("plots/plotMarkovChainMonitorTree_evolution_decayDist1_run%i_ls%i_ev%i.root", run, ls, event));
    showGraph(
      graphEvolution_X2, "Move", &genX2, 0., 1., "X_{2}",   
      Form("plots/plotMarkovChainMonitorTree_evolution_X2_run%i_ls%i_ev%i.root", run, ls, event));
    showGraph(
      graphEvolution_phiLab2, "Move", 0, -TMath::Pi(), +TMath::Pi(), "#phi^{lab}_{2}",   
      Form("plots/plotMarkovChainMonitorTree_evolution_phiLab2_run%i_ls%i_ev%i.root", run, ls, event));
    showGraph(
      graphEvolution_decayDist2, "Move", 0, -1., +1., "D^{decay}_{2}", 
      Form("plots/plotMarkovChainMonitorTree_evolution_decayDist2_run%i_ls%i_ev%i.root", run, ls, event));
 */
    delete histogramDensity_vs_X1_and_X2;
    delete histogramMass_vs_X1_and_X2;

    delete histogramDensity_vs_decayDist1_and_phi1;
    delete histogramDensity_vs_X1_and_phi1;
    delete histogramDensity_vs_decayDist2_and_phi2;
    delete histogramDensity_vs_X2_and_phi2;

    delete histogramDiTauPtDistribution;
    delete histogramDiTauEtaDistribution;
    delete histogramDiTauPhiDistribution;
    delete histogramDiTauMassDistribution;

    delete histogramSVfitMass_unweighted;
    delete histogramSVfitMass_gjAngle_labGt0_00025_unweighted;
    delete histogramSVfitMass_gjAngle_labLt0_00025_unweighted;
    delete histogramSVfitMass_weighted;
    delete histogramSVfitMass_gjAngle_labGt0_00025_weighted;
    delete histogramSVfitMass_gjAngle_labLt0_00025_weighted;

    delete histogramLeg1PtDistribution;
    delete histogramLeg1EtaDistribution;
    delete histogramLeg1PhiDistribution;
    delete histogramLeg1dPhi_vs_dEtaDistribution;

    delete histogramLeg2PtDistribution;
    delete histogramLeg2EtaDistribution;
    delete histogramLeg2PhiDistribution;
    delete histogramLeg2dPhi_vs_dEtaDistribution;

    delete histogramMoveDistribution;

    delete graphEvolution_X1;
    delete graphEvolution_phiLab1;
    delete graphEvolution_decayDist1;
    delete graphEvolution_X2;
    delete graphEvolution_phiLab2;
    delete graphEvolution_decayDist2;

    delete inputFile;
  }
}
Пример #21
0
static PyObject *
fill_hist_with_ndarray(PyObject *self, PyObject *args, PyObject* keywords) {

    using namespace std;
    PyObject *hist_ = NULL;
    PyObject *array_ = NULL;
    PyObject *weights_ = NULL;
    PyArrayObject *array = NULL;
    PyArrayObject *weights = NULL;
    TH1* hist = NULL;
    TH2* hist2d = NULL;
    TH3* hist3d = NULL;
    unsigned int dim = 1;
    unsigned int array_depth = 1;
    unsigned int i, n, k;
    char *array_data;
    char *weights_data = NULL;
    npy_intp array_stride_n;
    npy_intp array_stride_k = 1;
    npy_intp weights_stride = 1;
    static const char* keywordslist[] = {
        "hist",
        "array",
        "weights",
        NULL};

    if(!PyArg_ParseTupleAndKeywords(
                args, keywords, "OO|O",
                const_cast<char **>(keywordslist),
                &hist_, &array_, &weights_)) {
        return NULL;
    }

    if(!PyCObject_Check(hist_)) {
        PyErr_SetString(PyExc_TypeError,"Unable to convert hist to PyCObject");
        return NULL;
    }
    //this is not safe so be sure to know what you are doing type check in python first
    //this is a c++ limitation because void* have no vtable so dynamic cast doesn't work
    hist = static_cast<TH1*>(PyCObject_AsVoidPtr(hist_));
    if (hist == NULL) {
        PyErr_SetString(PyExc_TypeError,"Unable to convert hist to TH1*");
        return NULL;
    }
    dim = hist->GetDimension();

    if (dim == 2) {
        hist2d = static_cast<TH2*>(PyCObject_AsVoidPtr(hist_));
        if (hist2d == NULL) {
            PyErr_SetString(PyExc_TypeError,"Unable to convert hist to TH2*");
            return NULL;
        }
    } else if (dim == 3) {
        hist3d = static_cast<TH3*>(PyCObject_AsVoidPtr(hist_));
        if (hist3d == NULL) {
            PyErr_SetString(PyExc_TypeError,"Unable to convert hist to TH3*");
            return NULL;
        }
    } else if (dim > 3) {
        PyErr_SetString(PyExc_ValueError,"dim must not be greater than 3");
        return NULL;
    }

    if (dim > 1)
        array_depth = 2;

    array = (PyArrayObject *) PyArray_ContiguousFromAny(
            array_, PyArray_DOUBLE, array_depth, array_depth);
    if (array == NULL) {
        PyErr_SetString(PyExc_TypeError,
                "Unable to convert object to array");
        return NULL;
    }

    if (dim > 1) {
        k = array->dimensions[1];
        if (k != dim) {
            PyErr_SetString(PyExc_ValueError,
                "length of the second dimension must equal the dimension of the histogram");
            Py_DECREF(array);
            return NULL;
        }
        array_stride_k = array->strides[1];
    }

    n = array->dimensions[0];
    array_stride_n = array->strides[0];
    array_data = array->data;

    if (weights_) {
        weights = (PyArrayObject *) PyArray_ContiguousFromAny(
                weights_, PyArray_DOUBLE, 1, 1);
        if (weights == NULL) {
            PyErr_SetString(PyExc_TypeError,
                    "Unable to convert object to array");
            Py_DECREF(array);
            return NULL;
        }
        if (n != weights->dimensions[0]) {
            PyErr_SetString(PyExc_ValueError,
                    "array and weights must have the same length");
            Py_DECREF(weights);
            Py_DECREF(array);
            return NULL;
        }
        weights_data = weights->data;
        weights_stride = weights->strides[0];
    }

    if (dim == 1) {
        // weighted fill
        if (weights) {
            for (i = 0; i < n; ++i) {
                hist->Fill(
                        *(double *)(array_data + i * array_stride_n),
                        *(double *)(weights_data + i * weights_stride));
            }
        } else {
            // unweighted fill
            for (i = 0; i < n; ++i) {
                hist->Fill(*(double *)(array_data + i * array_stride_n));
            }
        }
    } else if (dim == 2) {
        // weighted fill
        if (weights) {
            for (i = 0; i < n; ++i) {
                hist2d->Fill(
                        *(double *)(array_data + i * array_stride_n),
                        *(double *)(array_data + i * array_stride_n + array_stride_k),
                        *(double *)(weights_data + i * weights_stride));
            }
        } else {
            // unweighted fill
            for (i = 0; i < n; ++i) {
                hist2d->Fill(
                        *(double *)(array_data + i * array_stride_n),
                        *(double *)(array_data + i * array_stride_n + array_stride_k));
            }
        }
    } else if (dim == 3) {
        // weighted fill
        if (weights) {
            for (i = 0; i < n; ++i) {
                hist3d->Fill(
                        *(double *)(array_data + i * array_stride_n),
                        *(double *)(array_data + i * array_stride_n + array_stride_k),
                        *(double *)(array_data + i * array_stride_n + 2 * array_stride_k),
                        *(double *)(weights_data + i * weights_stride));
            }
        } else {
            // unweighted fill
            for (i = 0; i < n; ++i) {
                hist3d->Fill(
                        *(double *)(array_data + i * array_stride_n),
                        *(double *)(array_data + i * array_stride_n + array_stride_k),
                        *(double *)(array_data + i * array_stride_n + 2 * array_stride_k));
            }
        }
    }
    if (weights)
        Py_DECREF(weights);
    Py_DECREF(array);
    Py_RETURN_NONE;
}
Пример #22
0
//_____________________________
void muIDCutsOptim::Loop()
{
  //  In a ROOT session, you can do:
  //      root> .L muIDCutsOptim.C
  //      root> muIDCutsOptim t
  //      root> t.GetEntry(12); // Fill t data members with entry number 12
  //      root> t.Show();       // Show values of entry 12
  //      root> t.Show(16);     // Read and show values of entry 16
  //      root> t.Loop();       // Loop on all entries
  //
  
  //  This is the loop skeleton where:
  //    jentry is the global entry number in the chain
  //    ientry is the entry number in the current Tree
  //  Note that the argument to GetEntry must be:
  //    jentry for TChain::GetEntry
  //    ientry for TTree::GetEntry and TBranch::GetEntry
  //

  if (fChain == 0) return;
  
  
  //===== Definition of file type, particle and if we want the high purity cut included in the soft muon ID cuts
  const char* fileType = "MC";
  const char* particle = "JPsi";
  fIspp = kFALSE;
  fIncludeHighPurity = kFALSE;
  //=====
  
  
  Long64_t nentries(0);
  if ( !strcmp(fileType,"MC") ) nentries = fChain->GetEntries();
  else nentries = 1500000;
  
  std::cout << "# Events = " << nentries << std::endl;
  
  
  //===== Definition of some cuts
  Double_t leMinvSig = 3.0; // Signal range
  Double_t ueMinvSig = 3.2;
  
  Double_t leMinvBkg1 = 2.7; // Bkg 1 range (sideband)
  Double_t ueMinvBkg1 = 2.9;
  
  Double_t leMinvBkg2 = 3.3; // Bkg 1 range (sideband)
  Double_t ueMinvBkg2 = 3.5;

  Double_t Ptmin = 3.0; // Pt cut (6.5) (3.0)
  Double_t Ptmax = 6.5; // (12.0) (6.5)
  
  Double_t Ymin = 2.0; // Y cut (0.0) (2.0)
  Double_t Ymax = 2.4; // (2.4) (2.4)
  //=====
  
  
  //===== Definition of MuID variables and binning
  const int nvar = 19;
  const char* varname[19] = {"isGoodMuon", "highPurity", "TrkMuArb", "TMOneStaTight", "nPixValHits",
    "nMuValHits", "nTrkHits", "normChi2_inner", "normChi2_global", "nPixWMea",
    "nTrkWMea", "StationsMatched", "dxy", "dxyErr", "dz",
    "dzErr", "ptErr_inner", "ptErr_global","VtxProb"};
  const int nbins[19] = {2, 2, 2, 2, 11,
    56, 36, 100, 100, 6,
    19, 7, 100, 100, 100,
    100, 100, 100, 200};
  const double lowedge[19] = {0, 0, 0, 0, 0,
    0, 0, 0, 0, 0,
    0, 0, 0, 0, 0,
    0, 0, 0, 0};
  const double hiedge[19] = {2, 2, 2, 2, 11,
    56, 36, 10, 50, 6,
    19, 7, 2, 0.25, 20,
    5, 0.15, 0.15, 1.};
  //=====
  
  
  SelectBranches(nvar,varname); // Activates only desired branches (General and MuID ones in this case)
  
  
  //====== Create histograms and arrays to store them ========
  TObjArray* aDistr = new TObjArray();
  TObjArray* aSig = new TObjArray();
  TObjArray* aBkg = new TObjArray();
  TObjArray* aSigC = new TObjArray();
  TObjArray* aBkgC = new TObjArray();
  TObjArray* aGlob = new TObjArray();
  TObjArray* aMinvCuts = new TObjArray();
  TObjArray* aSigSoftMuCutsButOne = new TObjArray();
  TObjArray* aBkgSoftMuCutsButOne = new TObjArray();
  TObjArray* aSigSoftMuCuts = new TObjArray();
  TObjArray* aBkgSoftMuCuts = new TObjArray();
  
  map<TString, TH1F*> hists_sig, hists_bkg, hists_sig_distr, hists_bkg_distr, hists_distr, hists_sig_distr_CutTest, hists_bkg_distr_CutTest, hists_sig_SofMu, hists_bkg_SofMu;
  
  TString sHPName("");
  if ( fIncludeHighPurity ) sHPName += "highPurity"; // This is for the histograms creation
  
  TObjArray* dummyA(0x0);
  TString partType("");
  for (int i=0; i<nvar; i++)
  {
    // Single cuts histos
    hists_sig[Form("%s",varname[i])] = new TH1F(Form("h%s_sig",varname[i]),Form("Signal di-#mu %s cut distribution",varname[i]),nbins[i],lowedge[i],hiedge[i]);
    hists_bkg[Form("%s",varname[i])] = new TH1F(Form("h%s_bkg",varname[i]),Form("Background di-#mu %s cut distribution",varname[i]),nbins[i],lowedge[i],hiedge[i]);
    
    // Variable distributions histos
    hists_sig_distr[Form("%s",varname[i])] = new TH1F(Form("h%s_sig_distr",varname[i]),Form("Signal single-#mu %s distribution",varname[i]),nbins[i],lowedge[i],hiedge[i]);
    hists_bkg_distr[Form("%s",varname[i])] = new TH1F(Form("h%s_bkg_distr",varname[i]),Form("Background single-#mu %s distribution",varname[i]),nbins[i],lowedge[i],hiedge[i]);
    
    partType.Clear();
    if ( !strcmp(varname[i],"VtxProb") ) partType += "di-#mu";
    else partType += "di-#mu";
    hists_distr[Form("%s",varname[i])] = new TH1F(Form("h%s_distr",varname[i]),Form("Sig+Bkg %s %s distribution",partType.Data(),varname[i]),nbins[i],lowedge[i],hiedge[i]);
    
    dummyA = new TObjArray();
    dummyA->SetName(Form("mInv_%s",varname[i]));
    aMinvCuts->Add(dummyA);
    
    if ( !strcmp(varname[i],"isGoodMuon") || !strcmp(varname[i],sHPName.Data()) || !strcmp(varname[i],"nPixWMea") || !strcmp(varname[i],"nTrkWMea") || !strcmp(varname[i],"dxy") || !strcmp(varname[i],"dz") )
    {
      // Histos for all the soft muon cuts applied but the one on the histo
      hists_sig_distr_CutTest[Form("%s",varname[i])] = new TH1F(Form("hSoftMuNoCut_%s_sig",varname[i]),Form("Signal single-#mu %s distribution (w/ rest of soft MuID cuts)",varname[i]),nbins[i],lowedge[i],hiedge[i]);
      hists_bkg_distr_CutTest[Form("%s",varname[i])] = new TH1F(Form("hSoftMuNoCut_%s_bkg",varname[i]),Form("Background single-#mu %s distribution (w/ rest of soft MuID cuts)",varname[i]),nbins[i],lowedge[i],hiedge[i]);
      
      hists_sig_SofMu[Form("%s",varname[i])] = new TH1F(Form("hSoftMuCut_%s_sig",varname[i]),Form("Signal di-#mu %s cut distribution (w/ all Soft MuID cuts except %s)",varname[i],varname[i]),nbins[i],lowedge[i],hiedge[i]);
      hists_bkg_SofMu[Form("%s",varname[i])] = new TH1F(Form("hSoftMuCut_%s_bkg",varname[i]),Form("Background di-#mu %s cut distribution (w/ all Soft MuID cuts except %s)",varname[i],varname[i]),nbins[i],lowedge[i],hiedge[i]);
    }
    else
    {
      // Histos for all the soft muon cuts applied
      hists_sig_distr_CutTest[Form("%s",varname[i])] = new TH1F(Form("hSoftMuFull_%s_sig",varname[i]),Form("Signal %s %s distribution (w/ all Soft MuID cuts)",partType.Data(),varname[i]),nbins[i],lowedge[i],hiedge[i]);
      hists_bkg_distr_CutTest[Form("%s",varname[i])] = new TH1F(Form("hSoftMuFull_%s_bkg",varname[i]),Form("Signal %s %s distribution (w/ all Soft MuID cuts)",partType.Data(),varname[i]),nbins[i],lowedge[i],hiedge[i]);
      
      hists_sig_SofMu[Form("%s",varname[i])] = new TH1F(Form("hSoftMuCut_%s_sig",varname[i]),Form("Signal di-#mu %s cut distribution (w/ all Soft MuID cuts)",varname[i]),nbins[i],lowedge[i],hiedge[i]);
      hists_bkg_SofMu[Form("%s",varname[i])] = new TH1F(Form("hSoftMuCut_%s_bkg",varname[i]),Form("Background di-#mu %s cut distribution (w/ all Soft MuID cuts)",varname[i]),nbins[i],lowedge[i],hiedge[i]);
    }
  }


  // Histos for global distributions
  TH1* hpt = new TH1D("hPtSig",Form("Dimuon p_{T} distribution (%2.1f < m_{#mu^{+}#mu^{-}} < %2.1f)",leMinvSig,ueMinvSig),300,0.0,15.0);
  TH1* hptw = new TH1D("hPtSigW",Form("Dimuon p_{T} distribution weighted (%2.1f < m_{#mu^{+}#mu^{-}} < %2.1f)",leMinvSig,ueMinvSig),300,0.0,15.0);
  
  TH1* hMinvw = new TH1D("hmInv","Dimuon m_{inv} distribution",600,0.,15.0);
  TH1* hRapw = new TH1D("hRap","Dimuon rapidity distribution",180,-4.5,4.5);
  TH1* hPtw = new TH1D("hPt","Dimuon p_{T} distribution",300,0.0,15.0);
  TH1* hCent = new TH1D("hCent","Centrality distribution",200,0.,100);
  TH1* hCentw = new TH1D("hCentw","Weighted centrality distribution",200,0.,100);
  //======================
  
  
  TLorentzVector *tlvmupl(0x0);
  TLorentzVector *tlvmumi(0x0);
  TLorentzVector *tlvqq(0x0);

  Long64_t nbytes = 0, nb = 0;
  //*************** Event loop
  for (Long64_t jentry=0; jentry<nentries;jentry++)
  {
    Long64_t ientry = LoadTree(jentry);
    if (ientry < 0) break;
    nb = fChain->GetEntry(jentry);   nbytes += nb;
    
    if ( jentry % 1000 == 0 ) std::cout << jentry << "/" << nentries << std::endl;
    
    Double_t weight = fChain->GetWeight()*GetNColl(Centrality); // This is the weight for the Pt and centrality. The weight stored in the chain is filterEficiency/nentries

    //Fill centrality histo
    hCentw->Fill(Centrality/2.,weight);
    hCent->Fill(Centrality/2.);
    
    
    //*************** Loop on reco dimuons
//    for (int i=0; i<Reco_QQ_size; i++)
//    {
    Int_t i(0);
    Bool_t kQQfound(kFALSE);
    while ( i < Reco_QQ_size && !kQQfound ) // This is just to take only the first dimuon passing the basic conditions, to not double count single muons
    {
      if ( !isTriggerSelected(i) || Reco_QQ_sign[i]!=0 )
      {
        i++;
        continue; // Checks if the event is selected by the trigger
      }
      
//      if (Reco_QQ_sign[i]!=0) continue;
      tlvmupl = (TLorentzVector*) Reco_QQ_mupl_4mom->At(i);
      tlvmumi = (TLorentzVector*) Reco_QQ_mumi_4mom->At(i);
      
      if (!IsAccept(tlvmupl->Pt(), tlvmupl->Eta()) || !IsAccept(tlvmumi->Pt(), tlvmumi->Eta()))
      {
        i++;
        continue; // Basic single muon kinematic cuts
      }
      
      tlvqq = (TLorentzVector*) Reco_QQ_4mom->At(i);
      Double_t mass = tlvqq->M();
      Double_t QQPt = tlvqq->Pt();
      Double_t QQY = TMath::Abs(tlvqq->Rapidity());
      
      if ( QQPt < Ptmin || QQPt > Ptmax || QQY < Ymin || QQY > Ymax )
      {
        i++;
        continue; // The simulation is restricted to pt in [Ptmin,Ptmax], so this rejects background dmuons outside the range
      }
      
      bool issig = (mass>leMinvSig && mass<ueMinvSig);
      bool isbkg = ((mass>leMinvBkg1 && mass<ueMinvBkg1) || (mass>leMinvBkg2 && mass<ueMinvBkg2));
      
      if ( !issig && ! isbkg )
      {
        i++;
        continue; // We keep only dimuons in the sidebands and signal ranges
      }
      
      kQQfound = kTRUE; // If at this point the dimuon has passed the basic conditions we keep only this dimuon from the event
      
      const double varValP[19] = {Reco_QQ_mupl_isGoodMuon[i],Reco_QQ_mupl_highPurity[i],Reco_QQ_mupl_TrkMuArb[i],Reco_QQ_mupl_TMOneStaTight[i],Reco_QQ_mupl_nPixValHits[i],Reco_QQ_mupl_nMuValHits[i],Reco_QQ_mupl_nTrkHits[i],Reco_QQ_mupl_normChi2_inner[i],Reco_QQ_mupl_normChi2_global[i],Reco_QQ_mupl_nPixWMea[i],Reco_QQ_mupl_nTrkWMea[i],Reco_QQ_mupl_StationsMatched[i],Reco_QQ_mupl_dxy[i],Reco_QQ_mupl_dxyErr[i],Reco_QQ_mupl_dz[i],Reco_QQ_mupl_dzErr[i],Reco_QQ_mupl_ptErr_inner[i],Reco_QQ_mupl_ptErr_global[i],Reco_QQ_VtxProb[i]};
      const double varValM[19] = {Reco_QQ_mumi_isGoodMuon[i],Reco_QQ_mumi_highPurity[i],Reco_QQ_mumi_TrkMuArb[i],Reco_QQ_mumi_TMOneStaTight[i],Reco_QQ_mumi_nPixValHits[i],Reco_QQ_mumi_nMuValHits[i],Reco_QQ_mumi_nTrkHits[i],Reco_QQ_mumi_normChi2_inner[i],Reco_QQ_mumi_normChi2_global[i],Reco_QQ_mumi_nPixWMea[i],Reco_QQ_mumi_nTrkWMea[i],Reco_QQ_mumi_StationsMatched[i],Reco_QQ_mumi_dxy[i],Reco_QQ_mumi_dxyErr[i],Reco_QQ_mumi_dz[i],Reco_QQ_mumi_dzErr[i],Reco_QQ_mumi_ptErr_inner[i],Reco_QQ_mumi_ptErr_global[i],0.}; //Reco_QQ_VtxProb set to 0. since it is a dimuon variable
      

      //**************************************************
      //*************** Fill histos **********************
      //**************************************************
      
      //===== General distributions
      hMinvw->Fill(mass,weight);
      hRapw->Fill(tlvqq->Rapidity(),weight);
      hPtw->Fill(QQPt,weight);
      
      if (issig)
      {
        hpt->Fill(QQPt);
        hptw->Fill(QQPt,weight);
      }
      //=====
      
      
      //===== MuID distributions
      for (int ihist=0; ihist<nvar; ihist++)
      {
        Bool_t isQQVar = kFALSE;
        if ( !strcmp(varname[ihist],"VtxProb") ) isQQVar = kTRUE; // Just to avoid filling the histos twice if testing a variable corresponding to a dimuon
          
        hists_distr[varname[ihist]]->Fill(varValP[ihist],weight); // Signal+ Background variable distribution
        if ( !isQQVar ) hists_distr[varname[ihist]]->Fill(varValM[ihist],weight);
        
        if (issig)
        {
          hists_sig_distr[varname[ihist]]->Fill(varValP[ihist],weight);  // Signal variable distribution
          if ( !isQQVar ) hists_sig_distr[varname[ihist]]->Fill(varValM[ihist],weight);
        }
        if (isbkg)
        {
          hists_bkg_distr[varname[ihist]]->Fill(varValP[ihist],weight);  // Background variable distribution
          if ( !isQQVar ) hists_bkg_distr[varname[ihist]]->Fill(varValM[ihist],weight);
        }

        
        ////_______ Soft muons cut testing MuID distributions
        Int_t nTest = whichMuIDVar(varname[ihist]); // If the variable is not on the soft muon cuts the full cut is applied
        
        if (isSoftMuon(varValP,nTest))
        {
          if (issig) hists_sig_distr_CutTest[varname[ihist]]->Fill(varValP[ihist],weight); // Variable distribution with the rest of soft MuID cuts applied (all the soft muon cuts if the variable does't belong to the soft cut)
          if (isbkg) hists_bkg_distr_CutTest[varname[ihist]]->Fill(varValP[ihist],weight);
        }
        if ( !isQQVar && isSoftMuon(varValM,nTest) )
        {
          if (issig) hists_sig_distr_CutTest[varname[ihist]]->Fill(varValM[ihist],weight);
          if (isbkg) hists_bkg_distr_CutTest[varname[ihist]]->Fill(varValM[ihist],weight);
        }
        ////_______
        
        
        dummyA = static_cast<TObjArray*>(aMinvCuts->FindObject(Form("mInv_%s",varname[ihist])));
        
        TH1* dummyH(0x0);
        Double_t nBins = hists_sig[varname[ihist]]->GetNbinsX();
        for ( Int_t j=1 ; j<=nBins ; j++)
        {
          //// Cuts on MuID variables
          Double_t cutVal = hists_sig[varname[ihist]]->GetBinLowEdge(j);
          if (Cut(varname[ihist],i,cutVal))
          {
            if (issig) hists_sig[varname[ihist]]->Fill(hists_sig[varname[ihist]]->GetBinCenter(j),weight); // Variable cut distribution
            if (isbkg) hists_bkg[varname[ihist]]->Fill(hists_bkg[varname[ihist]]->GetBinCenter(j),weight);
            
            if ( !(dummyH = static_cast<TH1*>(dummyA->FindObject(Form("mInv_%s_Cut%2.4f",varname[ihist],cutVal)))) ) // Creates the minv histogram and store in array (only once)
            {
              dummyH = new TH1D(Form("mInv_%s_Cut%2.4f",varname[ihist],cutVal),Form("Dimuon m_{inv} distribution (cut on %s: %2.4f)",varname[ihist],cutVal),600,0.,15.0);
              dummyA->Add(dummyH);
            }
            
            dummyH->Fill(mass,weight); // Invariant mass histo for each variable cut
            
            if ( isSoftMuon(varValP,nTest) && isSoftMuon(varValM,nTest) ) // If the variable is not in the soft MuID cut, the full soft cut is applied and the variable cut distribution is filled
            {
              if (issig) hists_sig_SofMu[varname[ihist]]->Fill(hists_sig[varname[ihist]]->GetBinCenter(j),weight);
              if (isbkg) hists_bkg_SofMu[varname[ihist]]->Fill(hists_bkg[varname[ihist]]->GetBinCenter(j),weight);
            }
          }
        }
      }
      //=======
      i++;
    }
  }
  
  //====== Save histos ======
  TFile *f = new TFile(Form("histos_%s_%s_%s_Pt%2.1f_%2.1f_Y%2.1f_%2.1f.root",fileType,particle,fIncludeHighPurity ? "HPincl" : "NoHPincl",Ptmin,Ptmax,Ymin,Ymax),"RECREATE");
  
  for (int i=0; i<nvar; i++)
  {
    aSigC->Add(hists_sig[varname[i]]);
    aBkgC->Add(hists_bkg[varname[i]]);
    
    aSig->Add(hists_sig_distr[varname[i]]);
    aBkg->Add(hists_bkg_distr[varname[i]]);
  
    aDistr->Add(hists_distr[varname[i]]);
    
    aSigSoftMuCutsButOne->Add(hists_sig_distr_CutTest[varname[i]]);
    aBkgSoftMuCutsButOne->Add(hists_bkg_distr_CutTest[varname[i]]);
    
    aSigSoftMuCuts->Add(hists_sig_SofMu[varname[i]]);
    aBkgSoftMuCuts->Add(hists_bkg_SofMu[varname[i]]);
  }
  
  aSigC->Write("SigSingleCut", TObject::kOverwrite | TObject::kSingleKey);
  aBkgC->Write("BkgSingleCut", TObject::kOverwrite | TObject::kSingleKey);
  
  aSig->Write("SigDistr", TObject::kOverwrite | TObject::kSingleKey);
  aBkg->Write("BkgDistr", TObject::kOverwrite | TObject::kSingleKey);
  
  aDistr->Write("Distr", TObject::kOverwrite | TObject::kSingleKey);
  
  aSigSoftMuCutsButOne->Write("SigDistrSoftMuCutButOne", TObject::kOverwrite | TObject::kSingleKey);
  aBkgSoftMuCutsButOne->Write("BkgDistrSoftMuCutButOne", TObject::kOverwrite | TObject::kSingleKey);
  
  aSigSoftMuCuts->Write("SigSoftMuCut", TObject::kOverwrite | TObject::kSingleKey);
  aBkgSoftMuCuts->Write("BkgSoftMuCut", TObject::kOverwrite | TObject::kSingleKey);
  
  
  aGlob->Add(hMinvw);
  aGlob->Add(hRapw);
  aGlob->Add(hPtw);
  aGlob->Add(hpt);
  aGlob->Add(hptw);
  aGlob->Add(hCent);
  aGlob->Add(hCentw);

  aGlob->Write("Global", TObject::kOverwrite | TObject::kSingleKey);
  
  
  aMinvCuts->Write("MinvWCuts", TObject::kOverwrite | TObject::kSingleKey);
  
  f->Close();
  //=========
  
}
Пример #23
0
void testsl() {
  gSystem->Load("libStarLight");
  gSystem->Load("libAliStarLight");

  TStarLight* sl = new TStarLight("starlight generator", "title", "");

  sl->SetParameter("baseFileName = slight	#suite of output files will be saved with this base name");
  sl->SetParameter("BEAM_1_Z = 82    #Z of projectile");
  sl->SetParameter("BEAM_1_A = 208   #A of projectile");
  sl->SetParameter("BEAM_2_Z = 82   #Z of target");
  sl->SetParameter("BEAM_2_A = 208   #A of target");
  sl->SetParameter("BEAM_1_GAMMA = 1470.0 #Gamma of the colliding ion 1");
  sl->SetParameter("BEAM_2_GAMMA = 1470.0 #Gamma of the colliding ion 2");
  sl->SetParameter("W_MAX = -1   #Max value of w");
  sl->SetParameter("W_MIN = -1    #Min value of w");
  sl->SetParameter("W_N_BINS = 50    #Bins i w");
  sl->SetParameter("RAP_MAX = 9.    #max y");
  sl->SetParameter("RAP_N_BINS = 200    #Bins i y");
  sl->SetParameter("CUT_PT = 0 #Cut in pT? 0 = (no, 1 = yes)");
  sl->SetParameter("PT_MIN = 1.0 #Minimum pT in GeV");
  sl->SetParameter("PT_MAX = 3.0 #Maximum pT in GeV");
  sl->SetParameter("CUT_ETA = 0 #Cut in pseudorapidity? (0 = no, 1 = yes)");
  sl->SetParameter("ETA_MIN = -10 #Minimum pseudorapidity");
  sl->SetParameter("ETA_MAX = 10 #Maximum pseudorapidity");
  sl->SetParameter("PROD_MODE = 2     #gg or gP switch (1 = 2-photon, 2 = coherent vector meson (narrow), 3 = coherent vector meson (wide), 4 = incoherent vector meson)");
  sl->SetParameter("N_EVENTS = 1000   #Number of events");
  sl->SetParameter("PROD_PID = 443013   #Channel of interest; this is j/psi --> mu+ mu-");
  sl->SetParameter("RND_SEED = 5574533 #Random number seed");
  sl->SetParameter("BREAKUP_MODE = 5     #Controls the nuclear breakup; a 5 here makes no requirement on the breakup of the ions");
  sl->SetParameter("INTERFERENCE = 0     #Interference (0 = off, 1 = on)");
  sl->SetParameter("IF_STRENGTH = 1.    #percent of intefernce (0.0 - 0.1)");
  sl->SetParameter("INT_PT_MAX = 0.24  #Maximum pt considered, when interference is turned on");
  sl->SetParameter("INT_PT_N_BINS =120   #Number of pt bins when interference is turned on");
  sl->SetParameter("XSEC_METHOD = 1 # Set to 0 to use old method for calculating gamma-gamma luminosity");
  sl->SetParameter("PYTHIA_FULL_EVENTRECORD = 0 # Write full pythia information to output (vertex, parents, daughter etc).");

  sl->InitStarLight();
  sl->PrintInputs(std::cout);
  TClonesArray tca("TParticle", 100);

  TLorentzVector v[2], vSum;
  TH1* hM  = new TH1D("hM",  "STARLIGHT;M#(){#pi^{+}#pi^{-}}",    200, 3.0, 3.2);
  TH1* hPt = new TH1D("hPt", "STARLIGHT;P_{T}#(){#pi^{+}#pi^{-}}", 80, 0., 2.);
  TH1* hY  = new TH1D("hY",  "STARLIGHT;Y#(){#pi^{+}#pi^{-}}",    100,-10., 10.);

  std::ofstream ofs("sl.txt");
  TParticle *p;
  for (Int_t counter(0); counter<20000; ) {
    sl->GenerateEvent();
    sl->BoostEvent();
    sl->ImportParticles(&tca, "ALL");
    Bool_t genOK = kTRUE;
    TLorentzVector vSum;
    for (Int_t i=0; i<tca.GetEntries() && genOK; ++i) {
      p = (TParticle*)tca.At(i);
      p->Momentum(v[i]);
      vSum += v[i];
//       genOK = TMath::Abs(v[i].Rapidity()) <= 1.5;
    }
    tca.Clear();
    if (!genOK) continue;
    Printf("%5d %d", counter, genOK);
    ++counter;
    vSum = v[0] + v[1];
    ofs << std::fixed << std::setprecision(4)
	<< vSum.M() << " " << vSum.Perp() << " " << vSum.Rapidity() << " "
	<< v[0].Eta() << " " << v[0].Px() << " " << v[0].Py() << " " << v[0].Pz() << " "
	<< v[1].Eta() << " " << v[1].Px() << " " << v[1].Py() << " " << v[1].Pz()
	<< std::endl;
    hM->Fill(vSum.M());
    hPt->Fill(vSum.Perp());
    hY->Fill(vSum.Rapidity());
  }
  TFile::Open("sl.root", "RECREATE");
  sl->Write();
  gFile->Write();

  hM->Draw();
  c1->SaveAs("SL.pdf(");
  hPt->Draw();
  c1->SaveAs("SL.pdf");
  hY->Draw();
  c1->SaveAs("SL.pdf)");
}
Пример #24
0
void Example1(const char *inputFile)
{
  gSystem->Load("libDelphes");

  // Create chain of root trees
  TChain chain("Delphes");
  chain.Add(inputFile);

  // Create object of class ExRootTreeReader
  ExRootTreeReader *treeReader = new ExRootTreeReader(&chain);
  Long64_t numberOfEntries = treeReader->GetEntries();

  // Get pointers to branches used in this analysis
  TClonesArray *branchJet = treeReader->UseBranch("Jet");
  TClonesArray *branchElectron = treeReader->UseBranch("Electron");
  TClonesArray *branchEvent = treeReader->UseBranch("Event");

  // Book histograms
  TH1 *histJetPT = new TH1F("jet_pt", "jet P_{T}", 100, 0.0, 100.0);
  TH1 *histMass = new TH1F("mass", "M_{inv}(e_{1}, e_{2})", 100, 40.0, 140.0);

  // Loop over all events
  for(Int_t entry = 0; entry < numberOfEntries; ++entry)
  {
    // Load selected branches with data from specified event
    treeReader->ReadEntry(entry);

    
    //HepMCEvent *event = (HepMCEvent*) branchEvent -> At(0);
    //LHEFEvent *event = (LHEFEvent*) branchEvent -> At(0);
    //Float_t weight = event->Weight;

    // If event contains at least 1 jet
    if(branchJet->GetEntries() > 0)
    {
      // Take first jet
      Jet *jet = (Jet*) branchJet->At(0);

      // Plot jet transverse momentum
      histJetPT->Fill(jet->PT);

      // Print jet transverse momentum
      cout << "Jet pt: "<<jet->PT << endl;
    }

    Electron *elec1, *elec2;

    // If event contains at least 2 electrons
    if(branchElectron->GetEntries() > 1)
    {
      // Take first two electrons
      elec1 = (Electron *) branchElectron->At(0);
      elec2 = (Electron *) branchElectron->At(1);

      // Plot their invariant mass
      histMass->Fill(((elec1->P4()) + (elec2->P4())).M());
    }
  }

  // Show resulting histograms
  histJetPT->Draw();
  histMass->Draw();
}
Пример #25
0
// === Main Function ===================================================
void hadTau2(unsigned int id = 11,
	     const TString &effName = "../data/LostLepton_MuonEfficienciesFromWJetMC.root",
	     const TString &respTempl = "../data/HadTau_TauResponseTemplates.root",
	     int nEvts = -1) {

  const bool isMC = ( id >= 10 );


  // --- Declare the Output Histograms ---------------------------------
  const TString title = isMC ? "Hadronic-Tau Closure Test" : "Hadronic-Tau Prediction";

  // Control plot: muon pt in the control sample
  TH1* hMuonPt = new TH1D("hMuonPt",title+";p_{T}(#mu^{gen}) [GeV];N(events)",50,0.,500.);
  hMuonPt->Sumw2();

  // Predicted distributions
  TH1* hPredHt = new TH1D("hPredHt",title+";H_{T} [GeV];N(events)",25,500.,3000.);
  hPredHt->Sumw2();
  TH1* hPredMht = new TH1D("hPredMht",title+";#slash{H}_{T} [GeV];N(events)",20,200.,1200.);   
  hPredMht->Sumw2();
  TH1* hPredNJets = new TH1D("hPredNJets",title+";N(jets);N(events)",9,3,12);   
  hPredNJets->Sumw2();

  // In case of MC: true distributions
  TH1* hTrueHt = static_cast<TH1*>(hPredHt->Clone("hTrueHt"));
  TH1* hTrueMht = static_cast<TH1*>(hPredMht->Clone("hTrueMht"));
  TH1* hTrueNJets = static_cast<TH1*>(hPredNJets->Clone("hTrueNJets"));

  // Event yields in the different RA2 search bins
  // First bin (around 0) is baseline selection
  TH1* hPredYields = new TH1D("hPredYields",title+";;N(events)",37,-0.5,36.5);
  hPredYields->Sumw2();
  hPredYields->GetXaxis()->SetBinLabel(1,"baseline");
  for(int bin = 2; bin <= hPredYields->GetNbinsX(); ++bin) {
    TString label = "Bin ";
    label += bin-1;
    hPredYields->GetXaxis()->SetBinLabel(bin,label);
  }
  TH1* hTrueYields = static_cast<TH1*>(hPredYields->Clone("hTrueYields"));



  // --- Tau Templates and Muon Efficiencies ---------------------------

  // Interface to the tau response templates
  TauResponse tauResp(respTempl);

  // Interfaces to the muon acceptance as well as reconstruction and 
  // isolation efficiencies
  LeptonAcceptance muonAcc(effName,LeptonAcceptance::nameMuonAcc());
  LeptonEfficiency muonRecoEff(effName,LeptonEfficiency::nameMuonRecoEff());
  LeptonEfficiency muonIsoEff(effName,LeptonEfficiency::nameMuonIsoEff());



  // --- Analyse the events --------------------------------------------

  // Interface to the event content
  Event* evt = new Event(Sample::fileNameFullSample(id),nEvts);

  // Loop over the events (tree entries)
  while( evt->loadNext() ) {

    // Select the control sample: 
    // - select events with exactly one well-reconstructed, isolated muon
    // Use the muon to predict the energy deposits of the 
    // hadronically decaying tau:
    // - scale the muon pt by a random factor drawn from the
    //   tau-reponse template to simulate the tau measurement
    // - use the simulated tau-pt to predict HT, MHT, and N(jets)
    if( evt->isoMuonsN() == 1 && evt->isoElectronsN() == 0 ) {

      // The kinematic properties of the well-reconstructed, isolated muon
      const float muPt = evt->isoMuonsPt()[0];
      const float muEta = evt->isoMuonsEta()[0];
      const float muPhi = evt->isoMuonsPhi()[0];
      
      // Use only events where the muon is inside acceptance
      if( muPt < TauResponse::ptMin() ) continue;
      if( std::abs( muEta ) > TauResponse::etaMax() ) continue;

      // "Cross cleaning": find the jet that corresponds to
      // the muon. Associate the jet that is closest in
      // in eta-phi space to the lepton
      int muJetIdx = -1;
      const float deltaRMax = 0.2;
      if( !utils::findMatchedObject(muJetIdx,muEta,muPhi,evt->jetsEta(),evt->jetsPhi(),evt->jetsN(),deltaRMax) ) continue;

      // Calculate RA2 selection-variables from "cleaned" jets
      int selNJet = 0;
      float selHt   = 0.;
      float selMhtX = 0.;
      float selMhtY = 0.;
      for(int jetIdx = 0; jetIdx < evt->jetsN(); ++jetIdx) {	// Loop over reco jets
	// Skip this jet if it is the muon
	if( jetIdx == muJetIdx ) continue;
	
	// Calculate NJet and HT
	if( evt->jetsPt()[jetIdx] > Selection::htJetPtMin() && std::abs(evt->jetsEta()[jetIdx]) < Selection::htJetEtaMax() ) {
	  selNJet++;
	  selHt += evt->jetsPt()[jetIdx];
	}
	// Calculate MHT
	if( evt->jetsPt()[jetIdx] > Selection::mhtJetPtMin() && std::abs(evt->jetsEta()[jetIdx]) < Selection::mhtJetEtaMax() ) {
	  selMhtX -= evt->jetsPt()[jetIdx]*cos(evt->jetsPhi()[jetIdx]);
	  selMhtY -= evt->jetsPt()[jetIdx]*sin(evt->jetsPhi()[jetIdx]);
	}
      } // End of loop over reco jets
      
      // Select only events with at least 2 HT jets
      if( selNJet < 2 ) continue;

      // Plot the muon pt as control plot
      hMuonPt->Fill(muPt);
      
      // Get random number from tau-response template
      // The template is chosen according to the muon pt
      const float scale = tauResp.getRandom(muPt);
      // Scale muon pt with tau response --> simulate tau jet pt
      const float simTauJetPt = scale * muPt;
      const float simTauJetEta = muEta;
      const float simTauJetPhi = muPhi;

      // Taking into account the simulated tau jet, recompute
      // HT, MHT, and N(jets)
      int simNJet = selNJet;
      float simHt = selHt;
      float simMhtX = selMhtX;
      float simMhtY = selMhtY;
      
      // If simulted tau-jet meets same criteria as as HT jets,
      // recompute NJets and HT
      if( simTauJetPt > Selection::htJetPtMin() && std::abs(muEta) < Selection::htJetEtaMax() ) {
	simNJet++;
	simHt += simTauJetPt;
      }
      // If simulated tau-jet meets same criteria as MHT jets,
      // recompute MHT
      if( simTauJetPt > Selection::mhtJetPtMin() && std::abs(muEta) < Selection::mhtJetEtaMax() ) {
	simMhtX -= simTauJetPt*cos(muPhi);
	simMhtY -= simTauJetPt*sin(muPhi);
      }

      const float simMht = sqrt( simMhtX*simMhtX + simMhtY*simMhtY );
      const float simMhtPhi = std::atan2(simMhtY,simMhtX);

      // Apply baseline selection
      if( !Selection::nJets(simNJet) ) continue;
      if( !Selection::ht(simHt) ) continue;
      if( !Selection::mht(simMht) ) continue;
      if( !deltaPhi(simMhtPhi,evt->jetsN(),evt->jetsPt(),evt->jetsEta(),evt->jetsPhi(),muJetIdx,simTauJetPt,simTauJetEta,simTauJetPhi) ) continue;

      // Corrections to control sample
      const double corrBRWToTauHad = 0.65;  // Correction for the BR of hadronic tau decays
      const double corrBRTauToMu = 1./1.15; // Correction for the fact that some muons could come from leptonic decays of taus from W decays
      const double acc = muonAcc(evt->mht(),evt->nJets());
      const double recoEff = muonRecoEff(evt->ht(),evt->mht(),evt->nJets());
      const double isoEff = muonIsoEff(evt->ht(),evt->mht(),evt->nJets());
      if( !( acc > 0. && recoEff > 0. && isoEff > 0. ) ) continue;
      const double corrMuAcc = 1./acc; // Correction for muon acceptance
      const double corrMuRecoEff = 1./recoEff; // Correction for muon reconstruction efficiency
      const double corrMuIsoEff = 1./isoEff; // Correction for muon isolation efficiency

      // The overall correction factor
      const double corr = corrBRTauToMu * corrBRWToTauHad * corrMuAcc * corrMuRecoEff * corrMuIsoEff;

      // Fill the prediction
      hPredHt->Fill(simHt,corr);
      hPredMht->Fill(simMht,corr);
      hPredNJets->Fill(simNJet,corr);

      // Predicted event yields
      hPredYields->Fill(0.,corr);
      const unsigned int searchBin = Selection::searchBin(simHt,simMht,simNJet);
      if( searchBin > 0 ) {
	hPredYields->Fill(searchBin,corr);
      }

    } // End if exactly one muon


    if( isMC ) {
      // Fill the 'truth' for comparison with the prediction
      // Select only events where the W decayed into a hadronically
      // decaying tau
      if( !( evt->flgW() == 15 && evt->flgTau() == 1 ) ) continue;
      
      // Apply baseline selection
      if( !Selection::nJets(evt->nJets()) ) continue;
      if( !Selection::ht(evt->ht()) ) continue;
      if( !Selection::mht(evt->mht()) ) continue;
      if( !Selection::deltaPhi(evt->deltaPhi1(),evt->deltaPhi2(),evt->deltaPhi3()) ) continue;

      hTrueHt->Fill(evt->ht());
      hTrueMht->Fill(evt->mht());
      hTrueNJets->Fill(evt->nJets());

      // True event yields
      hTrueYields->Fill(0.);
      const unsigned int searchBin = Selection::searchBin(evt->ht(),evt->mht(),evt->nJets());
      if( searchBin > 0 ) {
	hTrueYields->Fill(searchBin);
      }

    } // End isMC

  } // End of loop over events
  

  // --- Save the Histograms to File -----------------------------------
  const TString outFileName = isMC ? "HadTau_WJetMC_Closure.root" : "HadTau_Data_Prediction.root";
  TFile outFile(outFileName,"RECREATE");
  hMuonPt->Write();
  hTrueHt->Write();
  hTrueMht->Write();
  hTrueNJets->Write();
  hTrueYields->Write();
  hPredHt->Write();
  hPredMht->Write();
  hPredNJets->Write();
  hPredYields->Write();
  outFile.Close();
}
Пример #26
0
//_________________________________________________________________________________________________
void OccupancyInTimeBins(const char* input, const char* output)
{
  timeResolutions.push_back(1);
  timeResolutions.push_back(10);
  timeResolutions.push_back(100);
  
  AliRawReader* rawReader = AliRawReader::Create(input);
  
  AliMUONRawStreamTrackerHP stream(rawReader);
  
  stream.DisableWarnings();
  stream.TryRecover(kTRUE);
  
  int numberOfUsedEvents(0);
  int numberOfBadEvents(0);
  int numberOfEvents(0);
  int numberOfPhysicsEvent(0);
  int numberOfCalibrationEvent(0);
  int numberOfEventsWithMCH(0);
  int numberOfEventsWithoutCDH(0);
  
  int runNumber(-1);
  
  time_t runStart, runEnd;
  AliMergeableCollection* hc(0x0);
  
  AliCDBManager* cdbm = AliCDBManager::Instance();
  
  if (!cdbm->IsDefaultStorageSet())
  {
    cdbm->SetDefaultStorage("local:///cvmfs/alice-ocdb.cern.ch/calibration/data/2015/OCDB");
  }
  
  cdbm->SetRun(0);
  
  AliMpCDB::LoadAll();


  while (rawReader->NextEvent() ) //&& numberOfEvents < 1000 )
  {
    rawReader->Reset();
    ++numberOfEvents;
    
    if ( !rawReader->GetDataHeader() )
    {
      ++numberOfEventsWithoutCDH;
    }
    
    if (rawReader->GetType() != AliRawEventHeaderBase::kPhysicsEvent)
    {
      if ( rawReader->GetType() == AliRawEventHeaderBase::kCalibrationEvent )
      {
        ++numberOfCalibrationEvent;
      }
      continue;
    }
    
    if (runNumber<0)
    {
      runNumber = rawReader->GetRunNumber();
      GetTimeRange(runNumber,runStart,runEnd);

      hc = new AliMergeableCollection("occ");
      
      for ( std::vector<int>::size_type is = 0; is < timeResolutions.size(); ++is )
      {
        FillCollection(*hc,runStart,runEnd,timeResolutions[is]);
      }
      
      FillNumberOfPads(*hc);
      
    }
    
    ++numberOfPhysicsEvent;
    
    if ( numberOfPhysicsEvent % 5000 == 0 )
      cout << Form("%12d events processed : %12d physics %d used ones %d bad ones [ %d with MCH information ]",
                   numberOfEvents,numberOfPhysicsEvent,numberOfUsedEvents,numberOfBadEvents,numberOfEventsWithMCH) << endl;
    
    Bool_t mchThere(kFALSE);
    
    for ( int iDDL = 0; iDDL < AliDAQ::NumberOfDdls("MUONTRK") && !mchThere; ++iDDL )
    {
      rawReader->Reset();
      rawReader->Select("MUONTRK",iDDL,iDDL);
      if (rawReader->ReadHeader() )
      {
        if (rawReader->GetEquipmentSize() ) mchThere = kTRUE;
      }
    }
    
    if ( mchThere)
    {
      ++numberOfEventsWithMCH;
    }
    else
    {
      continue;
    }
    
    Int_t buspatchId;
    UShort_t  manuId;
    UChar_t manuChannel;
    UShort_t adc;
    
    stream.First();
    
    std::map<int,int> bpValues;
    
    while ( stream.Next(buspatchId,manuId,manuChannel,adc,kTRUE) )
    {
      bpValues[buspatchId]++;
    }
    
    for ( std::map<int,int>::const_iterator it = bpValues.begin(); it != bpValues.end(); ++it )
    {
      const int& buspatchId = it->first;
      const int& bpvalue = it->second;
      
      TString bpName = Form("BP%04d",buspatchId);
      
      for ( std::vector<int>::size_type is = 0; is < timeResolutions.size(); ++is )
      {
        TH1* h = hc->Histo(Form("/BUSPATCH/HITS/%ds/%s",timeResolutions[is],bpName.Data()));
        
        if (!h)
        {
          cout << "histogram not found" << endl;
          continue;
        }
        
        h->Fill(rawReader->GetTimestamp(),bpvalue);
      }
    }
    
    for ( std::vector<int>::size_type is = 0; is < timeResolutions.size(); ++is )
    {
      TH1* h = hc->Histo(Form("Nevents%ds",timeResolutions[is]));
      
      if (!h)
      {
        cout << "histogram not found" << endl;
        continue;
      }
      
      h->Fill(rawReader->GetTimestamp());
    }
    
  }
  
  // Group BP histograms per DE then DDL then Chamber then Station
  
  for ( std::vector<int>::size_type is = 0; is < timeResolutions.size(); ++is )
  {
    GroupByDE(*hc,timeResolutions[is]);
    GroupByDDL(*hc,timeResolutions[is]);
    GroupByChamber(*hc,timeResolutions[is]);
    GroupByStation(*hc,timeResolutions[is]);
  }
  
  // make normalized versions of the histograms
  Normalize(*hc);
  
  TFile* fout = new TFile(output,"RECREATE");
  hc->Write("occ");
  delete fout;
}
Пример #27
0
//______________________________________________________________________________
void CBElemThresholds()
{
    // load CaLib
    gSystem->Load("libCaLib.so");

    // configuration
    const Char_t calibration[]  = "LD2_Mar_13";
    const Int_t set             = 0;
    const Double_t currThr      = 2;
    const Char_t* fADC          = "/home/werthm/src/ROOT/acqu/acqu_user/data/Mar_13/CB/NaI.dat";
    const Char_t* fIn           = "/home/werthm/loc/presort/data/Mar_13/all.root";

    // read gains
    Double_t gain[720];
    TCMySQLManager::GetManager()->ReadParameters("Data.CB.E1", calibration, set, gain, 720);

    // create threshold histogram
    TH1* hThr = new TH1F("Threshold distribution", "Threshold distribution", 200, 0, 20);

    // read the ADC calibration file
    TCReadARCalib c(fADC, kFALSE);

    // get element list and loop over elements
    TList* list = c.GetElements();
    TIter next(list);
    TCARElement* e;
    TH1* h;
    Int_t n = 0;
    Int_t nAbove = 0;
    Double_t thr[720];
    Double_t min, max;
    while ((e = (TCARElement*)next()))
    {
        // load histogram
        TOLoader::LoadObject(fIn, TString::Format("ADC%s", e->GetADC()).Data(), &h, "", "q");

        // find first filled bin
        Double_t x = FindFirstFilledBin(h);

        // calculate threshold in MeV
        thr[n] = x * gain[n];

        // exclude holes
        if (!TCUtils::IsCBHole(n))
        {
            // save min/max
            if (!n)
            {
                min = thr[n];
                max = thr[n];
            }
            else
            {
                min = TMath::Min(min, thr[n]);
                max = TMath::Max(max, thr[n]);
            }

            // fill distribution histo
            hThr->Fill(thr[n]);

            // count elements above currently set threshold
            if (thr[n] > currThr) nAbove++;
        }

        // user info
        printf("%3d  %f\n", n, thr[n]);

        // clean-up
        delete h;

        n++;
    }

    printf("Minimum threshold           : %.2f\n", min);
    printf("Maximum threshold           : %.2f\n", max);
    printf("Above threshold of %.2f MeV : %d (%.1f%%)\n", currThr, nAbove, 100.*nAbove/672.);

    hThr->Draw();
}
Пример #28
0
//_________________________________________________________________________________________________
void FillNumberOfPads(AliMergeableCollection& hc)
{
  // number of pads needed for normalization

  TIter next(AliMpDDLStore::Instance()->CreateBusPatchIterator());
  AliMpBusPatch* bp;

  Int_t total(0);
  
  AliMpDCSNamer dcs("TRACKER");
  
  while ( ( bp = static_cast<AliMpBusPatch*>(next())) )
  {
    TH1* h = new TH1F(Form("BP%04d",bp->GetId()),"number of pads",1,0,1);
    
    Int_t npads(0);
    
    Int_t detElemId = AliMpDDLStore::Instance()->GetDEfromBus(bp->GetId());
    
    AliMpDetElement* de = AliMpDDLStore::Instance()->GetDetElement(detElemId);
    
    for ( Int_t i = 0; i < bp->GetNofManus(); ++i )
    {
      Int_t manuId = bp->GetManuId(i);
      
      npads += de->NofChannelsInManu(manuId);
    }
    
    TH1* hde = hc.Histo(Form("/DE/NPADS/DE%04d",detElemId));
    if (!hde)
    {
        hde = new TH1F(Form("DE%04d",detElemId),"number of pads",1,0,1);
        hc.Adopt("/DE/NPADS/",hde);
    }
    hde->Fill(0.0,1.0*npads);
    
    Int_t ddlId = de->GetDdlId() + AliDAQ::DdlIDOffset("MUONTRK");
    
    TH1* hddl = hc.Histo(Form("/DDL/NPADS/DDL%d",ddlId));
    if (!hddl)
    {
      hddl = new TH1F(Form("DDL%d",ddlId),"number of pads",1,0,1);
      hc.Adopt("/DDL/NPADS/",hddl);
    }
    hddl->Fill(0.0,1.0*npads);
    
    Int_t chamberId = 1+AliMpDEManager::GetChamberId(detElemId);
    Int_t stationId = 1 + AliMpDEManager::GetChamberId(detElemId)/2;
    
    TH1* hchamberSide(0x0);
    TH1* hstationSide(0x0);
    
    if (dcs.DCSAliasName(detElemId).Contains("Left"))
    {
      hchamberSide = hc.Histo(Form("/CHAMBER/NPADS/CHAMBER%dLEFT",chamberId));
      if (!hchamberSide)
      {
        hchamberSide = new TH1F(Form("CHAMBER%dLEFT",chamberId),"number of pads",1,0,1);
        hc.Adopt("/CHAMBER/NPADS/",hchamberSide);
      }
      hstationSide = hc.Histo(Form("/STATION/NPADS/STATION%dLEFT",stationId));
      if (!hstationSide)
      {
        hstationSide = new TH1F(Form("STATION%dLEFT",stationId),"number of pads",1,0,1);
        hc.Adopt("/STATION/NPADS/",hstationSide);
      }
    }
    else
    {
      if (dcs.DCSAliasName(detElemId).Contains("Right"))
      {
        hchamberSide = hc.Histo(Form("/CHAMBER/NPADS/CHAMBER%dRIGHT",chamberId));
        if (!hchamberSide)
        {
          hchamberSide = new TH1F(Form("CHAMBER%dRIGHT",chamberId),"number of pads",1,0,1);
          hc.Adopt("/CHAMBER/NPADS/",hchamberSide);
        }
        hstationSide = hc.Histo(Form("/STATION/NPADS/STATION%dRIGHT",stationId));
        if (!hstationSide)
        {
          hstationSide = new TH1F(Form("STATION%dRIGHT",stationId),"number of pads",1,0,1);
          hc.Adopt("/STATION/NPADS/",hstationSide);
        }
      }
    }

    hchamberSide->Fill(0.0,1.0*npads);
    hstationSide->Fill(0.0,1.0*npads);
    
    TH1* hchamber = hc.Histo(Form("/CHAMBER/NPADS/CHAMBER%d",chamberId));
    if (!hchamber)
    {
      hchamber = new TH1F(Form("CHAMBER%d",chamberId),"number of pads",1,0,1);
      hc.Adopt("/CHAMBER/NPADS/",hchamber);
    }
    hchamber->Fill(0.0,1.0*npads);

    TH1* hstation = hc.Histo(Form("/STATION/NPADS/STATION%d",stationId));
    if (!hstation)
    {
      hstation = new TH1F(Form("STATION%d",stationId),"number of pads",1,0,1);
      hc.Adopt("/STATION/NPADS/",hstation);
    }
    hstation->Fill(0.0,1.0*npads);

    h->Fill(0.0,1.0*npads);
    
    total += npads;
    
    hc.Adopt("/BUSPATCH/NPADS/",h);
  }
  
  std::cout << "Total pads=" << total << std::endl;
  
}
Пример #29
0
// === Main Function ===================================================
void hadTau1(unsigned int id = 11, int nEvts = -1) {

  // --- Declare the Output Histograms ---------------------------------

  // The tau response templates
  // They are filled for different bins in generated tau-lepton pt.
  // The binning is encapsulated in ../Utils/TauResponse.h
  std::vector<TH1*> hTauResp(TauResponse::nBins());
  for(unsigned int i = 0; i < TauResponse::nBins(); ++i) {
    hTauResp.at(i) = new TH1D(TauResponse::name(i),";p_{T}(visible) / p_{T}(generated);Probability",50,0.,2.5);
    hTauResp.at(i)->Sumw2();
  }

  // Control histograms for the jet-tau matching efficiency
  TH1* hNJetAll = new TH1D("hNJetAll",";N(jets)",10,0,10);
  hNJetAll->Sumw2();
  TH1* hNJetPass = static_cast<TH1*>(hNJetAll->Clone("hNJetPass"));

  TH1* hHtAll = new TH1D("hHtAll",";H_{T} [GeV]",30,0,3000);
  hHtAll->Sumw2();
  TH1* hHtPass = static_cast<TH1*>(hHtAll->Clone("hHtPass"));

  TH1* hMhtAll = new TH1D("hMhtAll",";#slash{H}_{T} [GeV]",20,0,2000);
  hMhtAll->Sumw2();
  TH1* hMhtPass = static_cast<TH1*>(hMhtAll->Clone("hMhtPass"));



  // --- Analyse the events --------------------------------------------

  // Interface to the event content
  Event* evt = new Event(Sample::fileNameFullSample(id),nEvts);

  // Loop over the events (tree entries)
  while( evt->loadNext() ) {

    // Select only events where the W decayed into a hadronically
    // decaying tau
    if( !(evt->flgW() == 15 && evt->flgTau() == 1) ) continue;

    // Kinematic variables of generator-level tau
    const float genTauPt = evt->genLeptonPt();
    const float genTauEta = evt->genLeptonEta();
    const float genTauPhi = evt->genLeptonPhi();

    // Use only events where the tau is inside the muon acceptance
    // because lateron we will apply the response to muon+jet events
    if( genTauPt < TauResponse::ptMin() ) continue;
    if( std::abs(genTauEta) > TauResponse::etaMax() ) continue;


    // "Cross cleaning": find the jet that originates in the
    // hadronic tau-decay. Associate the jet that is closest in
    // deltaR to the tau. The distance has to be smaller than deltaRMax.

    // First, fill counters before jet-tau matching
    hNJetAll->Fill(evt->nJets());
    hHtAll->Fill(evt->ht());
    hMhtAll->Fill(evt->mht());

    // Do the matching
    int tauJetIdx = -1;		// Will store the index of the jet matched to the tau
    const float deltaRMax = genTauPt < 50. ? 0.2 : 0.1; // Increase deltaRMax at low pt to maintain high-enought matching efficiency
    if( !utils::findMatchedObject(tauJetIdx,genTauEta,genTauPhi,evt->jetsEta(),evt->jetsPhi(),evt->jetsN(),deltaRMax) ) continue;

    // Then, fill counters after matching
    hNJetPass->Fill(evt->nJets());
    hHtPass->Fill(evt->ht());
    hMhtPass->Fill(evt->mht());


    // Calculate RA2 selection-variables from "cleaned" jets,
    // i.e. jets withouth the tau-jet
    int selNJet = 0; // Number of HT jets (jets pt > 50 GeV and |eta| < 2.5)

    for(int jetIdx = 0; jetIdx < evt->jetsN(); ++jetIdx) {	// Loop over reco jets
      // Skip this jet if it is the tau
      if( jetIdx == tauJetIdx ) continue;

      // Calculate NJet 
      if( evt->jetsPt()[jetIdx] > Selection::htJetPtMin() && std::abs(evt->jetsEta()[jetIdx]) < Selection::htJetEtaMax() ) selNJet++;
    } // End of loop over reco jets
    
    
    // Select only events with at least 2 HT jets
    if( selNJet < 2 ) continue;
    

    // Fill histogram with relative visible energy of the tau
    // ("tau response template") for hadronically decaying taus
    for(int jetIdx = 0; jetIdx < evt->jetsN(); ++jetIdx) {	// Loop over reco jets
      // Select tau jet
      if( jetIdx == tauJetIdx ) {
	// Get the response pt bin for the tau
	const unsigned int ptBin = TauResponse::ptBin(genTauPt);
	// Fill the corresponding response template
	const double tauJetPt = evt->jetsPt()[jetIdx];
	hTauResp.at(ptBin)->Fill( tauJetPt / genTauPt );
	break;		// End the jet loop once the tau jet has been found
      }
    }	// End of loop over reco jets
  } // End of loop over tree entries


  // Normalize the response distributions to get the probability density
  for(unsigned int i = 0; i < hTauResp.size(); ++i) {
    if( hTauResp.at(i)->Integral("width") > 0. ) {
      hTauResp.at(i)->Scale(1./hTauResp.at(i)->Integral("width"));
    }
  }

  // Get the jet-tau matching efficiency
  TH1* hMatchEffNJet = static_cast<TH1*>(hNJetPass->Clone("hMatchEffNJet"));
  hMatchEffNJet->Divide(hNJetAll);
  TH1* hMatchEffHt = static_cast<TH1*>(hHtPass->Clone("hMatchEffHt"));
  hMatchEffHt->Divide(hHtAll);
  TH1* hMatchEffMht = static_cast<TH1*>(hMhtPass->Clone("hMatchEffMht"));
  hMatchEffMht->Divide(hMhtAll);


  // --- Save the Histograms to File -----------------------------------
  TFile outFile("../data/HadTau_TauResponseTemplates.root","RECREATE");
  for(unsigned int i = 0; i < hTauResp.size(); ++i) {
    hTauResp.at(i)->Write();
  }
  hMatchEffNJet->Write();
  hMatchEffHt->Write();
  hMatchEffMht->Write();
  outFile.Close();
}
Пример #30
0
void delphes(const char *inputFile, const char* outputFileName)
{
  gSystem->Load("libDelphes");

  TChain *chain = new TChain("Delphes");
  chain->Add(inputFile);

  ExRootTreeReader *treeReader = new ExRootTreeReader(chain);
  ExRootResult *result = new ExRootResult();
  TH1* hNJet = result->AddHist1D("hNJets", "Jet multiplicity", "Multiplicity", "Events", 20, 0., 20.);
  TH1* hNLeptons = result->AddHist1D("hNLeptons", "Lepton multiplicity", "Multiplicity", "Events", 20, 0., 20.);
  TH1* hJetPt = result->AddHist1D("hJetPt", "Jet pT", "Transverse momentum p_{T} (GeV/c)", "Entries per 10GeV/c", 50, 0., 500.);
  TH1* hNBjets = result->AddHist1D("hNBjets", "B Jet multiplicity", "B jet multiplicity", "Events", 20, 0., 20.);
  TH1* hBjetPt = result->AddHist1D("hBjetPt", "B jet pT", "Transverse momentum p_{T} (GeV/c)", "Entries per 10GeV/c", 50, 0., 500.);
  TH1* hST = result->AddHist1D("hST", "ST", "Scalar sum S_{T} (GeV/c)", "Events per 500GeV/c", 40, 0., 20000.);

  // Analyze
  TClonesArray *branchJet = treeReader->UseBranch("Jet");
  TClonesArray *branchElectron = treeReader->UseBranch("Electron");
  TClonesArray *branchMuon = treeReader->UseBranch("Muon");
  TClonesArray *branchMissingET = treeReader->UseBranch("MissingET");

  int nEventsTotal = 0, nEvents4J = 0, nEvents2B = 0, nEvents3B = 0, nEvents4B = 0;
  int nEvents4J2B = 0, nEvents6J2B = 0, nEvents6J3B = 0;

  // Loop over all events
  for(Long64_t entry = 0, allEntries = treeReader->GetEntries(); entry < allEntries; ++entry)
  {
    double sT = 0;
    int nLeptons = 0, nJets = 0, nBjets = 0;

    treeReader->ReadEntry(entry);

    for ( int i=0, n=branchMuon->GetEntriesFast(); i<n; ++i )
    {
      const Muon* muon = (Muon*)branchMuon->At(i);
      const double muonPt = muon->PT;
      if ( muonPt < 50 || fabs(muon->Eta) > 2.5 ) continue;
      sT += muonPt;
      nLeptons += 1;
    }

    for ( int i=0, n=branchElectron->GetEntriesFast(); i<n; ++i )
    {
      const Electron* electron = (Electron*)branchElectron->At(i);
      const double electronPt = electron->PT;
      if ( electronPt < 50 || fabs(electron->Eta) > 2.5 ) continue;
      sT += electronPt;
      nLeptons += 1;
    }

    for ( int i=0, n=branchJet->GetEntriesFast(); i<n; ++i )
    {
      const Jet* jet = (Jet*)branchJet->At(i);
      const double jetPt = jet->PT;
      if ( jetPt < 50 ) continue;
      if ( fabs(jet->Eta) > 2.5 ) continue;
      ++nJets;
      hJetPt->Fill(jetPt);
      sT += jetPt;
      if ( !jet->BTag ) continue;
      ++nBjets;
      hBjetPt->Fill(jetPt);
    }
    hNLeptons->Fill(nLeptons);
    hNJets->Fill(nJets);
    hNBjets->Fill(nBjets);

    // Analyse missing ET
    if( branchMissingET->GetEntriesFast() > 0 )
    {
      const MissingET* met = (MissingET*)branchMissingET->At(0);
      sT += met->MET;
    }

    hST->Fill(sT);

    ++nEventsTotal;
    if ( nJets >= 4 ) ++nEvents4J;
    if ( nBjets >= 2 ) ++nEvents2B;
    if ( nBjets >= 3 ) ++nEvents3B;
    if ( nBjets >= 4 ) ++nEvents4B;
    if ( nJets >= 4 && nBjets >= 2 ) ++nEvents4J2B;
    if ( nJets >= 6 && nBjets >= 2 ) ++nEvents6J2B;
    if ( nJets >= 6 && nBjets >= 3 ) ++nEvents6J3B;
  }

  cout << inputFile << endl;
  cout << "nJet4 " << 1.*nEvents4J/nEventsTotal << endl;
  cout << "nBjet2 " << 1.*nEvents2B/nEventsTotal << endl;
  cout << "nBjet3 " << 1.*nEvents3B/nEventsTotal << endl;
  cout << "nBjet4 " << 1.*nEvents4B/nEventsTotal << endl;
  cout << "nJet4 nBjet2 " << 1.*nEvents4J2B/nEventsTotal << endl;
  cout << "nJet6 nBjet2 " << 1.*nEvents6J2B/nEventsTotal << endl;
  cout << "nJet6 nBjet3 " << 1.*nEvents6J3B/nEventsTotal << endl;
  //result->Print("png");
  result->Write(outputFileName);

  delete result;
  delete treeReader;
  delete chain;
}