//-------------------------------------------------------------------
void TestReadStuple()
{
	  TChain *myTree = new TChain("Stuple");

 //DATA
 //myTree->Add("/mnt/autofs/misc/nbay03.a/samantha/RESULTS/STUPLES/StupleV2_noMinVtx_noMinJet_TLphoEleRemoved.root");
 myTree->Add("/mnt/autofs/misc/nbay03.a/samantha/RESULTS/STUPLES/Stuple_noMinVtx_noMinJet_TLphoEleRemoved.root");

	Stuple *myStuple = new Stuple; 

	myTree->SetBranchStatus("pho_num", 1);		// number of electrons so we know how much to read from arrays
	myTree->SetBranchStatus("ele_num", 1);
	myTree->SetBranchStatus("jet_num", 1);

	myTree->SetBranchStatus("ele_Index", 1);
	myTree->SetBranchStatus("ele_Etc", 1);
	myTree->SetBranchStatus("ele_Ntight", 1);
	myTree->SetBranchStatus("ele_Nloose", 1);
	myTree->SetBranchStatus("ele_matchJetIndex", 1);	//if a matching jet is found and removed from jet list


	myTree->SetBranchAddress("pho_num", &myStuple->pho_num);		// number of electrons so we know how much to read from arrays
	myTree->SetBranchAddress("ele_num", &myStuple->ele_num);
	myTree->SetBranchAddress("jet_num", &myStuple->jet_num);

	myTree->SetBranchAddress("ele_Ntight", &myStuple->ele_Ntight);
	myTree->SetBranchAddress("ele_Nloose", &myStuple->ele_Nloose);
	myTree->SetBranchAddress("ele_Index", &myStuple->ele_Index);
	myTree->SetBranchAddress("ele_Etc", &myStuple->ele_Etc);
	myTree->SetBranchAddress("ele_matchJetIndex", &myStuple->ele_matchJetIndex);	//if a matching jet is found and removed from jet list


	//for (unsigned i =0 ; i < myTree->GetEntries(); ++i) {
	for (unsigned i =0 ; i < 100; ++i) {
		myTree->GetEntry(i);
		std::cout << myStuple->ele_num << std::endl;
		for (unsigned j = 0 ; j < myStuple->ele_num; ++j) {
			std::cout << myStuple->ele_matchJetIndex[j] << std::endl;

		}
	}
}
int main(int argc, char** argv){//main  

  //Input output and config options
  std::string cfg;
  bool concept;
  //size of signal region to perform Chi2 position fit.
  //in units of 2.5mm cells to accomodate different granularities
  unsigned nSR;
  //maximum value of residuals to use in error matrix: discard positions that are too far away 
  double residualMax;//mm
  unsigned pNevts;
  std::string filePath;
  std::string digifilePath;
  unsigned nRuns;
  std::string simFileName;
  std::string recoFileName;
  std::string outPath;
  unsigned nSiLayers;
  //0:do just the energies, 1:do fit+energies, 2: do zpos+fit+energies
  unsigned redoStep;
  unsigned debug;
  bool applyPuMixFix;

  po::options_description preconfig("Configuration"); 
  preconfig.add_options()("cfg,c",po::value<std::string>(&cfg)->required());
  po::variables_map vm;
  po::store(po::command_line_parser(argc, argv).options(preconfig).allow_unregistered().run(), vm);
  po::notify(vm);
  po::options_description config("Configuration");
  config.add_options()
    //Input output and config options //->required()
    ("concept",        po::value<bool>(&concept)->default_value(true))
    ("nSR",            po::value<unsigned>(&nSR)->default_value(3))
    ("residualMax",    po::value<double>(&residualMax)->default_value(25))
    ("pNevts,n",       po::value<unsigned>(&pNevts)->default_value(0))
    ("filePath,i",     po::value<std::string>(&filePath)->required())
    ("digifilePath", po::value<std::string>(&digifilePath)->default_value(""))
    ("nRuns",        po::value<unsigned>(&nRuns)->default_value(0))
    ("simFileName,s",  po::value<std::string>(&simFileName)->required())
    ("recoFileName,r", po::value<std::string>(&recoFileName)->required())
    ("outPath,o",      po::value<std::string>(&outPath)->required())
    ("nSiLayers",      po::value<unsigned>(&nSiLayers)->default_value(2))
    ("redoStep",       po::value<unsigned>(&redoStep)->default_value(0))
    ("debug,d",        po::value<unsigned>(&debug)->default_value(0))
    ("applyPuMixFix",  po::value<bool>(&applyPuMixFix)->default_value(false))
    ;

  // ("output_name,o",            po::value<std::string>(&outputname)->default_value("tmp.root"))

  po::store(po::command_line_parser(argc, argv).options(config).allow_unregistered().run(), vm);
  po::store(po::parse_config_file<char>(cfg.c_str(), config), vm);
  po::notify(vm);



  std::string inFilePath = filePath+simFileName;

  size_t end=outPath.find_last_of(".");
  std::string outFolder = outPath.substr(0,end);


  std::cout << " -- Input parameters: " << std::endl
	    << " -- Input file path: " << filePath << std::endl
	    << " -- Digi Input file path: " << digifilePath << std::endl
	    << " -- Output file path: " << outPath << std::endl
	    << " -- Output folder: " << outFolder << std::endl
	    << " -- Requiring " << nSiLayers << " si layers." << std::endl
	    << " -- Number cells in signal region for fit: " << nSR << " cells" << std::endl
	    << " -- Residual max considered for filling matrix and fitting: " << residualMax << " mm" << std::endl
	    << " -- Apply PUMix fix? " << applyPuMixFix << std::endl
	    << " -- Processing ";
  if (pNevts == 0) std::cout << "all events." << std::endl;
  else std::cout << pNevts << " events." << std::endl;

  TRandom3 lRndm(1);
  std::cout << " -- Random number seed: " << lRndm.GetSeed() << std::endl;

  /////////////////////////////////////////////////////////////
  //input
  /////////////////////////////////////////////////////////////

  std::ostringstream inputsim;
  inputsim << filePath << "/" << simFileName;
  std::ostringstream inputrec;
  if (digifilePath.size()==0)
    inputrec << filePath << "/" << recoFileName;
  else 
    inputrec << digifilePath << "/" << recoFileName;

  //std::cout << inputsim.str() << " " << inputrec.str() << std::endl;

  HGCSSInfo * info;

  TChain *lSimTree = new TChain("HGCSSTree");
  TChain *lRecTree = 0;
  
  TFile * simFile = 0;
  TFile * recFile = 0;

  if (recoFileName.find("Digi") != recoFileName.npos) 
    lRecTree = new TChain("RecoTree");
  else lRecTree = new TChain("PUTree");

  if (nRuns == 0){
    if (!testInputFile(inputsim.str(),simFile)) return 1;
    lSimTree->AddFile(inputsim.str().c_str());
    if (!testInputFile(inputrec.str(),recFile)) return 1;
    lRecTree->AddFile(inputrec.str().c_str());
  }
  else {
    for (unsigned i(0);i<nRuns;++i){
      std::ostringstream lstr;
      lstr << inputsim.str() << "_run" << i << ".root";
      if (testInputFile(lstr.str(),simFile)){  
	if (simFile) info =(HGCSSInfo*)simFile->Get("Info");
	else {
	  std::cout << " -- Error in getting information from simfile!" << std::endl;
	  return 1;
	}
      }
      else continue;
      lSimTree->AddFile(lstr.str().c_str());
      lstr.str("");
      lstr << inputrec.str() << "_run" << i << ".root";
      if (!testInputFile(lstr.str(),recFile)) continue;
      lRecTree->AddFile(lstr.str().c_str());
    }
  }

  if (!lSimTree){
    std::cout << " -- Error, tree HGCSSTree cannot be opened. Exiting..." << std::endl;
    return 1;
  }

  if (!lRecTree){
    std::cout << " -- Error, tree RecoTree cannot be opened. Exiting..." << std::endl;
    return 1;
  }


  /////////////////////////////////////////////////////////////
  //Info
  /////////////////////////////////////////////////////////////

  const double cellSize = info->cellSize();
  const unsigned versionNumber = info->version();
  const unsigned model = info->model();
  
  //models 0,1 or 3.
  //bool isTBsetup = (model != 2);
  bool isCaliceHcal = versionNumber==23;//inFilePath.find("version23")!=inFilePath.npos || inFilePath.find("version_23")!=inFilePath.npos;

  //extract input energy

  std::cout << " -- Version number is : " << versionNumber 
	    << ", model = " << model
	    << ", cellSize = " << cellSize
	    << std::endl;


  //initialise detector
  HGCSSDetector & myDetector = theDetector();
 
  myDetector.buildDetector(versionNumber,concept,isCaliceHcal);

  const unsigned nLayers = myDetector.nLayers();
  const unsigned nSections = myDetector.nSections();

  std::cout << " -- N layers = " << nLayers << std::endl
	    << " -- N sections = " << nSections << std::endl;


  HGCSSGeometryConversion geomConv(inFilePath,model,cellSize);
  //set granularity to get cellsize for PU subtraction
  std::vector<unsigned> granularity;
  granularity.resize(nLayers,4);
  geomConv.setGranularity(granularity);

  //////////////////////////////////////////////////
  //////////////////////////////////////////////////
  ///////// Output File // /////////////////////////
  //////////////////////////////////////////////////
  //////////////////////////////////////////////////

  TFile *outputFile = TFile::Open(outPath.c_str(),"RECREATE");
  
  if (!outputFile) {
    std::cout << " -- Error, output file " << outPath << " cannot be opened. Please create output directory. Exiting..." << std::endl;
    return 1;
  }
  else {
    std::cout << " -- output file " << outputFile->GetName() << " successfully opened." << std::endl;
  }
  outputFile->cd();


  ///initialise PU density object

  HGCSSPUenergy puDensity("data/EnergyDensity.dat");


    //////////////////////////////////////////////////
    //////////////////////////////////////////////////
    ///////// positionFit /////////////////////////////
    //////////////////////////////////////////////////
    //////////////////////////////////////////////////
  
  const unsigned nEvts = ((pNevts > lSimTree->GetEntries() || pNevts==0) ? static_cast<unsigned>(lSimTree->GetEntries()) : pNevts) ;
  

  PositionFit lChi2Fit(nSR,residualMax,nLayers,nSiLayers,applyPuMixFix,debug);
  lChi2Fit.initialise(outputFile,"PositionFit",outFolder,geomConv,puDensity);

  //try getting z position from input file, if doesn't exit,
  //perform first loop over simhits to find z positions of layers
  if ((redoStep<2 && !lChi2Fit.getZpositions(versionNumber)) || redoStep>1)
    lChi2Fit.getZpositions(versionNumber,lSimTree,nEvts);
  
  //perform second loop over events to find positions to fit and get energies
  SignalRegion SignalEnergy(outFolder, nLayers, nEvts, geomConv, puDensity,applyPuMixFix,versionNumber);
  SignalEnergy.initialise(outputFile,"Energies");

  //initialise
  bool dofit = redoStep>0 || !SignalEnergy.initialiseFitPositions();
  if (!dofit && redoStep==0) std::cout << " -- Info: fit positions taken from file on disk." << std::endl;
  else std::cout << " -- Info: redoing least square fit." << std::endl;

  if (redoStep>0 || (redoStep==0 && dofit)){
    lChi2Fit.getInitialPositions(lSimTree,lRecTree,nEvts);
    lChi2Fit.finaliseErrorMatrix();
    lChi2Fit.initialiseLeastSquareFit();
  }
  
  //loop on events
  HGCSSEvent * event = 0;
  std::vector<HGCSSSamplingSection> * ssvec = 0;
  std::vector<HGCSSSimHit> * simhitvec = 0;
  std::vector<HGCSSRecoHit> * rechitvec = 0;
  std::vector<HGCSSGenParticle> * genvec = 0;
  unsigned nPuVtx = 0;

  lSimTree->SetBranchAddress("HGCSSEvent",&event);
  lSimTree->SetBranchAddress("HGCSSSamplingSectionVec",&ssvec);
  lSimTree->SetBranchAddress("HGCSSSimHitVec",&simhitvec);
  lSimTree->SetBranchAddress("HGCSSGenParticleVec",&genvec);

  lRecTree->SetBranchAddress("HGCSSRecoHitVec",&rechitvec);
  if (lRecTree->GetBranch("nPuVtx")) lRecTree->SetBranchAddress("nPuVtx",&nPuVtx);
  const unsigned nRemove = 12;
  std::vector<unsigned> lToRemove;
  unsigned list[nRemove] = {25,27,15,1,10,3,18,5,12,7,23,20};

  for (unsigned ievt(0); ievt<nEvts; ++ievt){//loop on entries
    if (debug) std::cout << "... Processing entry: " << ievt << std::endl;
    else if (ievt%50 == 0) std::cout << "... Processing entry: " << ievt << std::endl;

    lSimTree->GetEntry(ievt);
    lRecTree->GetEntry(ievt);
    if (dofit) {
      bool found = lChi2Fit.setTruthInfo(genvec,1);
      if (!found) continue;
      //mask layers in turn
      lToRemove.clear();
      for (unsigned r(0); r<nRemove+1;++r){
	FitResult fit;
	if ( lChi2Fit.performLeastSquareFit(ievt,fit,lToRemove)==0 ){
	  //SignalEnergy.fillEnergies(ievt,(*ssvec),(*simhitvec),(*rechitvec),nPuVtx,fit);
	}
	else std::cout << " -- remove " << r << " Fit failed." << std::endl;
	if (r<nRemove) lToRemove.push_back(list[r]);
      }

    }
    else SignalEnergy.fillEnergies(ievt,(*ssvec),(*simhitvec),(*rechitvec),nPuVtx);

  }//loop on entries

  //finalise

  if (dofit) lChi2Fit.finaliseFit();
  SignalEnergy.finalise();

  outputFile->Write();
  //outputFile->Close();
  
  std::cout << " - End of egammaResolution program." << std::endl;

  return 0;
  

}//main
void PDFSystCalculator_Powheg12Bin()
{
  typedef std::pair<double,double> pairOfDouble;
  set<pairOfDouble> uniqueEventsTrue;

  typedef std::pair<int,int> pairOfInt;
  set<pairOfInt> uniqueEventsReco;

  double mLow = 60.; // Z mass
  double mHigh = 120.; // Z mass
  double ptLow = 0.;
  double ptHigh = 4000.;

  //variable related PDF systematic uncertainty
  //double weightedSelectedEvents[18][53];
  //double weighted2SelectedEvents[18][53];
  double weightedSelectedEvents[12][53];
  double weighted2SelectedEvents[12][53];
  
  double events_central[nptBins] = {0.0};
  double events2_central[nptBins] = {0.0};
  double wa[nptBins] = {0.0};
  double wb[nptBins] = {0.0};
  double wplus[nptBins] = {0.0};
  double wminus[nptBins] = {0.0};

  char tmpName[30];


 // std::ofstream Fout;
 // TString FoutName = "Zpt_12BinWeightedSelectedEvents.txt";
 // Fout.open(FoutName);
 // Fout << fixed << setprecision(3);



  // read input root file
  TChain* tree = new TChain("tree");
  for(int i(1);i<95;i++)
  {
    //sprintf(tmpName,"DYJetsToLL_%d.root",i);
    //sprintf(tmpName,"/d1/scratch/sangilpark/Zpt/CMSSW_5_3_14_patch1/src/TerraNova/NtupleMaker/test/ZpT_Powheg_LowPU/DYJetsToLL_%d.root",i);
    sprintf(tmpName,"/d2/scratch/Storage_Area/ZpT8TeV_Powheg_LowPU/DYJetsToLL_%d.root",i);
    tree->AddFile(tmpName);  // Powheg Ntuple
  }

  TH1D* hPtMCTot = new TH1D("hPtMCTot", "", nptBins, xbins_pt); // no cut
  TH1D* hPtMCAcc = new TH1D("hPtMCAcc", "", nptBins, xbins_pt); // acc.cuts
  TH1D* hPtMCEff = new TH1D("hPtMCEff", "", nptBins, xbins_pt); // acc + all selection cuts


  //Hammid MC truth information pre FSR
  _TrackInfo true1PreFSR, true2PreFSR;
  tree->SetBranchAddress("true1PreFSR", &true1PreFSR);
  tree->SetBranchAddress("true2PreFSR", &true2PreFSR);

  float trueMassPreFSR, truePtPreFSR;
  tree->SetBranchAddress("trueMassPreFSR",	&trueMassPreFSR);
  tree->SetBranchAddress("truePtPreFSR",	&truePtPreFSR);

  vector<float> *weights_CT10;
  TBranch *b_weights_CT10;
  weights_CT10 = 0;
  tree->SetBranchAddress("weights_CT10", &weights_CT10, &b_weights_CT10);


  // Initialize variable
  for(int iBin(0); iBin<nptBins; iBin++)
  {
    {
      for(int j=0; j<53; j++)
      {
	weightedSelectedEvents[iBin][j] = 0;
	weighted2SelectedEvents[iBin][j] = 0;
//	cout << "initialized weightedSelectedEvents : " << weightedSelectedEvents[iBin][j] << endl;
      }
    }
  }

  // Print # of events
  cout << "Loop over the " << tree->GetEntries() << " entries ...\n";

  // Fill histogram
  for(int iEvt(0); iEvt<tree->GetEntries(); iEvt++)
  //for(int iEvt(0); iEvt<20; iEvt++)
  {
    if ( (iEvt % 100000)==0 ) cout << "event " << iEvt << endl;
    tree -> GetEntry(iEvt);

    //nocut start
    pairOfDouble trueMassPtPreFSR(trueMassPreFSR,truePtPreFSR);
    if( !uniqueEventsTrue.insert( trueMassPtPreFSR ).second ) continue;

    if (trueMassPreFSR <  mLow) continue;
    if (trueMassPreFSR > mHigh) continue;

    hPtMCTot -> Fill( truePtPreFSR );

    // acc cut start
    if (true1PreFSR.charge == -999) continue;
    if (true2PreFSR.charge == -999) continue;
    if (true1PreFSR.charge*true2PreFSR.charge>0) continue;

    if (trueMassPreFSR <  mLow) continue;
    if (trueMassPreFSR > mHigh) continue;
    if (true1PreFSR.pt < 20         || true2PreFSR.pt < 20        ) continue;
    if (fabs(true1PreFSR.eta) > 2.1 || fabs(true2PreFSR.eta) > 2.1) continue;
    hPtMCAcc -> Fill( truePtPreFSR );

    //cout << "trueMassPreFSR : " << trueMassPreFSR << endl;
    //cout << "true1PreFSR : " << true1PreFSR.pt << endl;
    //cout << "truePtPreFSR : " << truePtPreFSR << endl;
    //cout << "weights size : " << weights_CT10->size() << endl;


    // Check weight numbers are normal. 
    //cout << Form("iEvt : %d ============================= ",iEvt) << endl;
    //for(int i(0); i<weights_CT10->size(); i++)
    //{
    //  cout << "weights_CT10 : " << (*weights_CT10)[i] << endl;
    //}


    // Save weights each bin
    for(int iBin(0); iBin<nptBins; iBin++)
    {
      if(truePtPreFSR >= xbins_pt[iBin] && truePtPreFSR < xbins_pt[iBin+1])
      {
	for(int j=0; j<weights_CT10->size(); j++)
	{
	  weightedSelectedEvents[iBin][j] += (*weights_CT10)[j];
	  weighted2SelectedEvents[iBin][j] += (*weights_CT10)[j] * (*weights_CT10)[j];
	  //cout << Form("weightedSelectedEvents[%d][%d] : %f \t weighted2SelectedEvents[%d][%d] : %f \t weights_CT10[%d] : %f ",iBin,j,weightedSelectedEvents[iBin][j],iBin,j,weighted2SelectedEvents[iBin][j], j, (*weights_CT10)[j]) << endl;
	}
      }
    }
  }

  double weightedSelectedEventsCentTot=0;
  for(int iBin(0);iBin<nptBins;iBin++)
  {
     weightedSelectedEventsCentTot += weightedSelectedEvents[iBin][0];

      for (unsigned int j=0; j<weights_CT10->size(); ++j)
      {
	cout << fixed << setprecision(5);
	cout<<iBin<<"\t"<<j<<"\t"<<weightedSelectedEvents[iBin][j]<<endl;
      }
  }
    // Calculate PDF syst
  for(int iBin(0);iBin<nptBins;iBin++)
  {
    unsigned int nmembers = weights_CT10->size();
    unsigned int npairs = (nmembers-1)/2;
 
    events_central[iBin] = weightedSelectedEvents[iBin][0]/weightedSelectedEventsCentTot/(xbins_pt[iBin+1]-xbins_pt[iBin]);
    events2_central[iBin] = weighted2SelectedEvents[iBin][0];
    if(npairs>0){
      for (unsigned int j=0; j<npairs; ++j)
      {
	
	double weightedSelectedEventsXPlusTot=0;
	double weightedSelectedEventsXMinusTot=0;
	for(int iBin(0);iBin<nptBins;iBin++)
	{
	  weightedSelectedEventsXPlusTot += weightedSelectedEvents[iBin][2*j+1];
	  weightedSelectedEventsXMinusTot += weightedSelectedEvents[iBin][2*j+2];
	}

	cout << "events central : " << events_central[iBin] << endl;
	//wa[iBin] = weightedSelectedEvents[iBin][2*j+1]/events_central[iBin]-1.;
	//wb[iBin] = weightedSelectedEvents[iBin][2*j+2]/events_central[iBin]-1.;
	
	wa[iBin] = (weightedSelectedEvents[iBin][2*j+1]/weightedSelectedEventsXPlusTot/(xbins_pt[iBin+1]-xbins_pt[iBin]))/events_central[iBin]-1.;
	wb[iBin] = (weightedSelectedEvents[iBin][2*j+2]/weightedSelectedEventsXMinusTot/(xbins_pt[iBin+1]-xbins_pt[iBin]))/events_central[iBin]-1.;
	
	if (wa[iBin]>wb[iBin]){
	  if (wa[iBin]<0.) wa[iBin] = 0.;
	  if (wb[iBin]>0.) wb[iBin] = 0.;
	  wplus[iBin] += wa[iBin]*wa[iBin];
	  wminus[iBin] += wb[iBin]*wb[iBin];
	}else{
	  if (wb[iBin]<0.) wb[iBin] = 0.;
	  if (wa[iBin]>0.) wa[iBin] = 0.;
	  wplus[iBin] += wb[iBin]*wb[iBin];
	  wminus[iBin] += wa[iBin]*wa[iBin];
	}
      }
      if (wplus[iBin]>0) wplus[iBin] = sqrt(wplus[iBin]);
      if (wminus[iBin]>0) wminus[iBin] = sqrt(wminus[iBin]);
    }else{
      cout << "\tNO eigenvectors for uncertainty estimation" << endl;
    }
    //cout <<iBin+1<<" Bin: Relative uncertainty with respect to central member: +" << 100.*wplus[iBin] << " / -" <<  100.*wminus[iBin] << " [%]" << endl;
    cout <<iBin+1<<" + " << 100.*wplus[iBin] << " / -" <<  100.*wminus[iBin] << " [%]" << endl;
  }

  for(int i(0); i<nptBins; i++)
  {
    cout << i+1 << " bin Events number : " << hPtMCAcc->GetBinContent(i+1) << endl;
  }

  TFile* Hist_out = new TFile("ZptPreFSR_Powheg12Bin.root","recreate");

  hPtMCTot->Write();
  hPtMCAcc->Write();

  //Fout.close();
}
Exemple #4
0
//---------------------------------------------------------------------------//
//Main Method
//---------------------------------------------------------------------------//
int main(int argc, char** argv)
{	
	TApplication *App = new TApplication("Application",(Int_t*)&argc, argv);
	TCanvas *Canvas = new TCanvas("canvas", "Canvas", 640, 640);

	// Set up ROOT as we require.
	SetupROOT();

	// Get list of files to run over. 
	TString fileName("/storage/epp2/phseaj/exercise/basket_2010b.list");
	std::ifstream inputFile(fileName.Data(), ios::in);

	// Declare a TChain for the TGlobalPID module
	TChain *gRecon = new TChain("ReconDir/Global");
	TChain *gGenVtx = new TChain("TruthDir/Vertices");
	// Check if the file exists.
	if (!inputFile.is_open()){
	std::cout << "ERROR: File prod4 files not found!" << std::endl;
		std::cout << " - This file should contain a list of all data files to be processed." << std::endl;
		return 0;
	}
	else{
		std::string curFileName;

		// Add the input files to the TChains.
		//only doing 10 of the basket files, revert to while to do whole run
	//	while(getline(inputFile,curFileName)){
		for(int l = 0; l<10; l++){
			if(getline(inputFile,curFileName)){
				gRecon->Add(curFileName.c_str());
				gGenVtx->Add(curFileName.c_str());
			}
		}
	}

	std::cout << "Got input file(s)." << std::endl;

	//Setup access to the Recon tree
	int NPIDs(0);  // This variable counts the number of particles per event
	int NVtxFGD1(0), NVtxFGD2(0);
        // Declare a TClonesArray to hold objects of type TGlobalPID
 	TClonesArray *globalPIDs = new TClonesArray("ND::TGlobalReconModule::TGlobalPID",50);
	TClonesArray *VtxFGD1 = new TClonesArray("ND::TTruthVerticesModule::TTruthVertex",50);    
	TClonesArray *VtxFGD2 = new TClonesArray("ND::TTruthVerticesModule::TTruthVertex",50);    
    // Associate the right branch in the TTree to the right local variable
	gRecon->SetBranchAddress("NPIDs",&NPIDs);
    gRecon->SetBranchAddress("PIDs",&globalPIDs);
	gGenVtx->SetBranchAddress("VtxFGD1", &VtxFGD1);
	gGenVtx->SetBranchAddress("NVtxFGD1", &NVtxFGD1);
	gGenVtx->SetBranchAddress("VtxFGD2", &VtxFGD2);
	gGenVtx->SetBranchAddress("NVtxFGD2", &NVtxFGD2);
	//check that truthdir and recon have the same number of entries
	if(gRecon->GetEntries() != gGenVtx->GetEntries()) 
		cout<<"not equal entries, probably wrong"<<endl;
	// Loop over the entries in the TChain.

	//========================================================
	//			Declare Graphs n stuff here
	//========================================================

	//adding tclones arrays for use with detectors
	Int_t NTPCs;
	TClonesArray *TPC;

	Int_t NFDGs;
	TClonesArray *FDG;

	Int_t NECALs;
	TClonesArray *ECAL;

	Int_t NPODs;
	TClonesArray *POD;

	Int_t NSMRDs;
	TClonesArray *SMRD;

	//adding a 2d graph general purpose, change titles each time!
	TH1D *graph1 = new TH1D("graph1","Momenta of TPC PIDs from FDGs", 100, -50.0 , 50.0);
	
	Int_t ninteract(0), nfgd(0),nfgdqes(0),fgdqesneu(0);
	//========================================================
	//	end		Declare Graphs n stuff here
	//========================================================

	// Loop over the entries in the TChain. (only 1/1000 of whole entries atm)
	for(unsigned int i = 0; i < gRecon->GetEntries()/10; ++i) {
		if((i+1)%10000 == 0) std::cout << "Processing event: " << (i+1) << std::endl;
		//display status every 10,000 th entry

	// Get an entry for the Recon tree
		gRecon->GetEntry(i);
		gGenVtx->GetEntry(i);
		ND::TGlobalReconModule::TGlobalPID *gTrack = NULL;

		//added new loop for truth vertex
		gGenVtx->GetEntry(i);
		
		for (int j=0; j<NPIDs; j++) {
			// Get a specific track from the TClonesArray
			gTrack = (ND::TGlobalReconModule::TGlobalPID*)globalPIDs->At(j);
			//get truevertex (in example, also gets trueparticle, can add in later)
			ND::TTrueVertex vtx = gTrack->TrueParticle.Vertex;
			//get position lorrentz vector
			TLorentzVector vec = vtx.Position;
			ninteract++;
			if(ABS(vec.X())<832.2 && ABS(vec.Y()-55)<832.2 && ((vec.Z()>123.45&&vec.Z()<446.95)||(vec.Z()>1481.45&&vec.Z()<1807.95))){	//is it in one of the FGDs?
				nfgd++;
				if(vtx.ReactionCode.find("Weak[NC],QES;",0)!=-1){
					unsigned long det;
					det = gTrack->Detectors;
					string detstr;
					stringstream stream;
					stream << det;
					detstr = stream.str();
					if(detstr.find("1",0)||detstr.find("2",0)||detstr.find("3",0)){
						graph1->Fill((Double_t)gTrack->FrontMomentum);	
					} 	
					nfgdqes++;
				}	
			}
			TClonesArray *TPCObjects = new TClonesArray("ND::TGlobalReconModule::TTPCObject",gTrack->NTPCs);
			ND::TGlobalReconModule::TObject *tpcTrack = NULL;
			for ( int k = 0 ; k < gTrack->NTPCs; k++) {
				tpcTrack = (ND::TGlobalReconModule::TObject*) TPCObjects->At(k);
				//now we can access  variables through tpcTrack->PullEle for example
			}
		}

	} // End loop over events

//plotting bits at the end :D
	graph1->Draw();
	App->Run();
	return 0;
}
Exemple #5
0
void TreeFiller(string inFiles, string outFile, string histName) {

	
	TChain *origFiles = new TChain("treeVars", "treeVars");
	origFiles->Add(inFiles.c_str());
	
	int nEntries = origFiles->GetEntries();
	cout << "The old chain contains " << nEntries << " entries." << endl;
	
	
	float jet1Eta, jet2Eta, deltaY, genTopPt1, genTopPt2, jet1Mass, jet2Mass, jet1MinMass, jet2MinMass, jet1BDisc, jet2BDisc, jet1SubjetMaxBDisc, jet2SubjetMaxBDisc,
			jet1tau32, jet2tau32, jet1Pt, jet2Pt, jetPtForMistag, mttMass, mttMassPred, mistagWt, mistagWtAll, mistagWtNsubAll, mistagWtNsub, index, cutflow, NNoutput, ptReweight;
	int jet1NSubjets, jet2NSubjets;
		
	
	origFiles->SetBranchAddress("jet1Eta", &jet1Eta);
	origFiles->SetBranchAddress("jet2Eta", &jet2Eta);
	origFiles->SetBranchAddress("deltaY", &deltaY);
	origFiles->SetBranchAddress("jet1Mass", &jet1Mass);
	origFiles->SetBranchAddress("jet2Mass", &jet2Mass);
	origFiles->SetBranchAddress("jet1minMass", &jet1MinMass);
	origFiles->SetBranchAddress("jet2minMass", &jet2MinMass);
	origFiles->SetBranchAddress("jet1Nsubj", &jet1NSubjets);
	origFiles->SetBranchAddress("jet2Nsubj", &jet2NSubjets);
	origFiles->SetBranchAddress("jet1BDisc", &jet1BDisc);
	origFiles->SetBranchAddress("jet2BDisc", &jet2BDisc);
	origFiles->SetBranchAddress("jet1SubjetMaxBDisc", &jet1SubjetMaxBDisc);
	origFiles->SetBranchAddress("jet2SubjetMaxBDisc", &jet2SubjetMaxBDisc);
	origFiles->SetBranchAddress("jet1tau32", &jet1tau32);
	origFiles->SetBranchAddress("jet2tau32", &jet2tau32);
	origFiles->SetBranchAddress("jet1Pt", &jet1Pt);
	origFiles->SetBranchAddress("jet2Pt", &jet2Pt);
	origFiles->SetBranchAddress("jetPtForMistag", &jetPtForMistag);
	origFiles->SetBranchAddress("mttMass", &mttMass);
	origFiles->SetBranchAddress("mttMassPred", &mttMassPred);
	origFiles->SetBranchAddress("index", &index);
	origFiles->SetBranchAddress("cutflow", &cutflow);
	origFiles->SetBranchAddress("NNoutput", &NNoutput);
	origFiles->SetBranchAddress("mistagWt", &mistagWt);
	origFiles->SetBranchAddress("genTopPt1", &genTopPt1);	
	origFiles->SetBranchAddress("genTopPt2", &genTopPt2);	

	
	TFile *newFile = new TFile(outFile.c_str(), "RECREATE");
	TTree *newTree = origFiles->CloneTree(0);
	newTree->Branch("mistagWtNsub", &mistagWtNsub, "mistagWtNsub/F");
	newTree->Branch("mistagWtNsubAll", &mistagWtNsubAll, "mistagWtNsubAll/F");
	newTree->Branch("mistagWtAll", &mistagWtAll, "mistagWtAll/F");
	newTree->Branch("ptReweight", &ptReweight, "ptReweight/F");

	newTree->SetBranchAddress("mistagWtNsub", &mistagWtNsub);
	newTree->SetBranchAddress("misagWtNsubAll", &mistagWtNsubAll);
	newTree->SetBranchAddress("mistagWtAll", &mistagWtAll);
	newTree->SetBranchAddress("ptReweight", &ptReweight);
	
/*	
	TMVA::Reader* reader = new TMVA::Reader();
	reader->AddVariable("jet1Eta", &jet1Eta);
	reader->AddVariable("jet2Eta", &jet2Eta);
	reader->AddVariable("deltaY", &deltaY);
	reader->AddVariable("jet1Mass", &jet1Mass);
	reader->AddVariable("jet2Mass", &jet2Mass);
	reader->AddVariable("jet1BDisc", &jet1BDisc);
	reader->AddVariable("jet2BDisc", &jet2BDisc);
	reader->AddVariable("jet1SubjetMaxBDisc", &jet1SubjetMaxBDisc);
	reader->AddVariable("jet2SubjetMaxBDisc", &jet2SubjetMaxBDisc);
	reader->AddVariable("jet1tau32", &jet1tau32);
	reader->AddVariable("jet2tau32", &jet2tau32);
	reader->AddVariable("jet1Pt", &jet1Pt);
	reader->AddVariable("jet2Pt", &jet2Pt);
	reader->AddVariable("mttMass", &mttMass);

	reader->BookMVA("MLP", "weights/TMVA_tt_Zp_MLP.weightsZp10_cut4.xml");
*/	
	//TFile *mistagFileLow = new TFile("notCSVL_notCSVM_mistag.root");
	//TFile *mistagFileMed = new TFile("CSVL_notCSVM_mistag.root");
	//TFile *mistagFileHi = new TFile("CSVM_mistag.root");
	TFile *mistagFileLow = new TFile("Jan21_mistag.root");//data_LowBscore_mistag_Dec16.root");
	TFile *mistagFileMed = new TFile("Jan21_mistag.root");//data_MedBscore_mistag_Dec16.root");
	TFile *mistagFileHi = new TFile("Jan21_mistag.root");//data_HiBscore_mistag_Dec16.root");
	TFile *mistagFile = new TFile("Jan21_mistag.root");//data_AllBscore_mistag_Dec16.root");
	histName = "MISTAG_RATE_SUB_TTBAR_Inclusive";
	TH1F *mistagRateHistAll = (TH1F *) mistagFile->Get( histName.c_str() )->Clone();	
	TH1F *mistagRateHistLow = (TH1F *) mistagFileLow->Get( histName.c_str() )->Clone();	
	TH1F *mistagRateHistMed = (TH1F *) mistagFileMed->Get( histName.c_str() )->Clone();	
	TH1F *mistagRateHistHi = (TH1F *) mistagFileHi->Get( histName.c_str() )->Clone();	
	string histName2 = "MISTAG_RATE_SUB_TTBAR_InclNsub";
	TH1F *mistagRateHistNSAll = (TH1F *) mistagFile->Get( histName2.c_str() )->Clone();	
	TH1F *mistagRateHistNSLow = (TH1F *) mistagFileLow->Get( histName2.c_str() )->Clone();	
	TH1F *mistagRateHistNSMed = (TH1F *) mistagFileMed->Get( histName2.c_str() )->Clone();	
	TH1F *mistagRateHistNSHi = (TH1F *) mistagFileHi->Get( histName2.c_str() )->Clone();	
	cout << histName << endl;
	cout << "Entries " << mistagRateHistAll->Integral() << endl;	
	cout << "Entries2 " << mistagRateHistNSHi->Integral() << endl;
	
	for (int i = 0; i < origFiles->GetEntries(); i++){
	
		origFiles->GetEntry(i);
		if  (i % 1000000 == 0) cout << 100*(float(i) / float(nEntries)) << " Percent Complete." << endl;
		mistagWt = 0.000;
		mistagWtNsub = 30.0000;
	
		if (cutflow == 4 || index == 1){
		
			if (genTopPt1 > 400) genTopPt1 = 400;
			if (genTopPt2 > 400) genTopPt2 = 400;
			//NNoutput =  reader->EvaluateMVA("MLP");
			ptReweight = sqrt( exp(0.156 - 0.00137*genTopPt1)*exp(0.156 - 0.00137*genTopPt2) );			
			
			if (index == 1) {
				
				float bScore = -9.99;
				float tauScore = 9.99;
				int probeJet = 0;
				if (jet1Pt == jetPtForMistag) {
					probeJet = 1;
					bScore = jet1SubjetMaxBDisc;
					tauScore = jet2tau32;
				}
				if (jet2Pt == jetPtForMistag) {
					bScore = jet2SubjetMaxBDisc;
					tauScore = jet1tau32;
					probeJet = 2;
				}


				if (bScore > 0.679) mistagWt = mistagRateHistHi->GetBinContent( mistagRateHistHi->FindBin( jetPtForMistag ) );			
				else if (bScore > 0.244) mistagWt = mistagRateHistMed->GetBinContent( mistagRateHistMed->FindBin( jetPtForMistag ) );			
				else mistagWt = mistagRateHistLow->GetBinContent( mistagRateHistLow->FindBin( jetPtForMistag ) );			
				mistagWtAll = mistagRateHistAll->GetBinContent( mistagRateHistAll->FindBin( jetPtForMistag ) );

				if (tauScore < 0.7){

				if (bScore > 0.679) mistagWtNsub = mistagRateHistNSHi->GetBinContent( mistagRateHistNSHi->FindBin( jetPtForMistag ) );			
				else if (bScore > 0.244) mistagWtNsub = mistagRateHistNSMed->GetBinContent( mistagRateHistNSMed->FindBin( jetPtForMistag ) );			
				else mistagWtNsub = mistagRateHistNSLow->GetBinContent( mistagRateHistNSLow->FindBin( jetPtForMistag ) );			
				mistagWtNsubAll = mistagRateHistNSAll->GetBinContent( mistagRateHistNSAll->FindBin( jetPtForMistag ) );
				}
				else {
				mistagWtNsub = 0.0;
				mistagWtNsubAll = 0.0;
				}
				//mttMass = mttMassPred;
				//NNoutput = reader->EvaluateMVA("MLP");
			}
			
			
			newTree->Fill();
		
		}
		

	}


	
	
	newTree->Draw("mistagWtNsub", "index == 1");	
	


	newFile->cd();
	newTree->Write();
	newFile->Write();
	newFile->Close();
	
}
int main (int argc, char** argv)
{
  gROOT->ProcessLine("#include <vector>");
  
  //TFile* f1 = new TFile(argv[1]);
  TChain *tree =  new TChain("tree");
  for (int i = 1 ; i < argc ; i++)
  {
    std::cout << "Adding file " << argv[i] << std::endl;
    tree->Add(argv[i]);
  }
  
  //play with input names
//   std::string inputFileName = 
  
  // find the number of channels directly from the tchain file
  // before creating the variables
  // first, get the list of leaves
  TObjArray *leavescopy = tree->GetListOfLeaves();
  int nLeaves = leavescopy->GetEntries();
  std::vector<std::string> leavesName;
  // fill a vector with the leaves names
//   std::cout << nLeaves << std::endl;
  for(int i = 0 ; i < nLeaves ; i++)
  {
//     std::cout << i << std::endl;
    leavesName.push_back(leavescopy->At(i)->GetName());
  }
  // count the entries that start with "ch"
  int numOfCh = 0;
  int numOfCry = 0;
  std::string det_prefix("detector");
  std::string cry_prefix("cry");
  for(int i = 0 ; i < nLeaves ; i++)
  {
//     leavesName.push_back(leavescopy->At(i)->GetName());
    if (!leavesName[i].compare(0, det_prefix.size(), det_prefix))
      numOfCh++;
    if (!leavesName[i].compare(0, cry_prefix.size(), cry_prefix))
      numOfCry++;
    
  }
  
  //the string "cry" appears 4 times per crystal..
  numOfCry = numOfCry / 4;
  
  std::cout << numOfCh << std::endl;
  std::cout << numOfCry << std::endl;
  
  
  Long64_t Seed;
  int Run;
  int Event;
  float totalEnergyDeposited;
  int NumOptPhotons;
  int NumCherenkovPhotons;
  
  std::vector<float> *CryEnergyDeposited;
  std::vector<float> **pCryEnergyDeposited;
  std::vector<float> *PosXEnDep; 
  std::vector<float> **pPosXEnDep;
  std::vector<float> *PosYEnDep; 
  std::vector<float> **pPosYEnDep;
  std::vector<float> *PosZEnDep; 
  std::vector<float> **pPosZEnDep;
  
//   DetectorHit         = new Short_t             [numOfCh];
  CryEnergyDeposited  = new std::vector<float>  [numOfCry];
  pCryEnergyDeposited = new std::vector<float>* [numOfCry];
  PosXEnDep           = new std::vector<float>  [numOfCry];
  pPosXEnDep          = new std::vector<float>* [numOfCry];
  PosYEnDep           = new std::vector<float>  [numOfCry];
  pPosYEnDep          = new std::vector<float>* [numOfCry];
  PosZEnDep           = new std::vector<float>  [numOfCry];
  pPosZEnDep          = new std::vector<float>* [numOfCry];
  
//   short RunDetectorHit[16];
  
  
  std::vector<float> **pEdep;
  std::vector<float> **px;
  std::vector<float> **py;
  std::vector<float> **pz;
  
  pEdep = new std::vector<float>* [numOfCry];
  px    = new std::vector<float>* [numOfCry];
  py    = new std::vector<float>* [numOfCry];
  pz    = new std::vector<float>* [numOfCry];
  
  for (int i = 0 ; i < numOfCry ; i++)
  {
    pEdep[i] = 0; 
    px[i] = 0;
    py[i] = 0;
    pz[i] = 0;
  }

  Short_t  *detector;
  detector = new Short_t [numOfCh];
  
  tree->SetBranchAddress("Seed",&Seed);
  tree->SetBranchAddress("Run",&Run);
  tree->SetBranchAddress("Event",&Event);
  tree->SetBranchAddress("totalEnergyDeposited",&totalEnergyDeposited);
  tree->SetBranchAddress("NumOptPhotons",&NumOptPhotons);
  tree->SetBranchAddress("NumCherenkovPhotons",&NumCherenkovPhotons);
  
  for (int i = 0 ; i < numOfCry ; i++)
  {
    std::stringstream snames;
    snames << "cry" << i;
    tree->SetBranchAddress(snames.str().c_str(),&pEdep[i]);
    snames.str("");
    snames<< "cry" << i << "PosXEnDep";    
    tree->SetBranchAddress(snames.str().c_str(),&px[i]);
    snames.str("");
    snames<< "cry" << i << "PosYEnDep";
    tree->SetBranchAddress(snames.str().c_str(),&py[i]);
    snames.str("");
    snames<< "cry" << i << "PosZEnDep";
    tree->SetBranchAddress(snames.str().c_str(),&pz[i]);


  }
  for (int i = 0 ; i < numOfCh ; i++)
  {
    std::stringstream snames;
    snames << "detector" << i;
    tree->SetBranchAddress(snames.str().c_str(),&detector[i]);
  }
  
  
  
  //output ttree
  long long int DeltaTimeTag,ExtendedTimeTag;
  Short_t charge[32]; //adc type is always 32 channels
  Float_t RealX,RealY,RealZ;
  Short_t CrystalsHit;
  Short_t NumbOfInteractions;
  std::vector <float> TotalCryEnergy;	
  std::vector <float>* pTotalCryEnergy; 
  pTotalCryEnergy = &TotalCryEnergy;
  
  TTree* t1 = new TTree("adc","adc");
  
  t1->Branch("ExtendedTimeTag",&ExtendedTimeTag,"ExtendedTimeTag/l"); 	//absolute time tag of the event
  t1->Branch("DeltaTimeTag",&DeltaTimeTag,"DeltaTimeTag/l"); 			//delta time from previous event
  t1->Branch("TotalCryEnergy","std::vector<float>",&pTotalCryEnergy);	
  //branches of the 32 channels data
  for (int i = 0 ; i < 32 ; i++)
  {
    //empty the stringstreams
    std::stringstream snames,stypes;
    charge[i] = 0;
    snames << "ch" << i;
    stypes << "ch" << i << "/S";  
    t1->Branch(snames.str().c_str(),&charge[i],stypes.str().c_str());
  }
  t1->Branch("RealX",&RealX,"RealX/F"); 
  t1->Branch("RealY",&RealY,"RealY/F"); 
  t1->Branch("RealZ",&RealZ,"RealZ/F"); 
  t1->Branch("CrystalsHit",&CrystalsHit,"CrystalsHit/S"); 
  t1->Branch("NumbOfInteractions",&NumbOfInteractions,"NumbOfInteractions/S"); 

  
  long int counter = 0;
  int nEntries = tree->GetEntries();
  std::cout << "nEntries = " << nEntries << std::endl;
  for(int i = 0; i < nEntries ; i++)
  {  
    
    tree->GetEvent(i);
    
    ExtendedTimeTag = 1e-9;
    DeltaTimeTag = 1e-9;
    
    NumbOfInteractions = 0;
    CrystalsHit = 0;

    
    
    for(int i = 0; i < numOfCh ; i++)
    {
      //convert to ADC channels, as if it was data from a digitizer
      //mppc gain = 1.25e6
      //adc channel binning 156e-15 C
      double adcCh = detector[i]*1.25e6*1.6e-19/156e-15;
      charge[i*2] = (Short_t) adcCh; 
    }
    
    RealX = RealY = RealZ = 0;
    
    // calculate a weigthed energy deposition in x,y,z
    for(int i = 0; i < numOfCry ; i++) //first total energy deposited
    {
      Float_t SumEnergy = 0;
      NumbOfInteractions += px[i]->size();
      if(px[i]->size()) CrystalsHit++;
      for(int j = 0; j < px[i]->size(); j++)
      {
		RealX += (px[i]->at(j) * pEdep[i]->at(j))/totalEnergyDeposited;
      }
      for(int j = 0; j < px[i]->size(); j++)
      {
		RealY += (py[i]->at(j) * pEdep[i]->at(j))/totalEnergyDeposited;
      }
      for(int j = 0; j < px[i]->size(); j++)
      {
		RealZ += (pz[i]->at(j) * pEdep[i]->at(j))/totalEnergyDeposited;
      }
      for(int j = 0; j < px[i]->size(); j++)
      {
		SumEnergy += pEdep[i]->at(j);	
      }
      TotalCryEnergy.push_back(SumEnergy);
    }
/*
    //find crystal with max energy deposition
    Float_t MaxEnergyCry = 0;
    Short_t MaxEnergyCryNum = -1;
    MaxEnergyCry = *std::max_element(TotalCryEnergy.begin(), TotalCryEnergy.end());
    MaxEnergyCryNum = std::distance(TotalCryEnergy.begin(), (std::max_element(TotalCryEnergy.begin(), TotalCryEnergy.end())));
*/
    
    if(NumbOfInteractions > 0) // discard events with no energy deposition (they would never trigger the detectors anyway..)
    {
      t1->Fill();
    }
    
    counter++;
    
    int perc = ((100*counter)/nEntries); //should strictly have not decimal part, written like this...
    if( (perc % 10) == 0 )
    {
      std::cout << "\r";
      std::cout << perc << "% done... ";
      //std::cout << counter << std::endl;
    }
    
  TotalCryEnergy.clear();
  
  }
  std::cout << std::endl;
  std::string outFile = "Tree_OUT.root";
  TFile* fOut = new TFile(outFile.c_str(),"recreate");
  
  t1->Write();
  
//   f1->Close();
  
  fOut->Close();
  
  
  
  return 0;
}
Exemple #7
0
void process()
{
   Int_t raw[512];   // buffer for input signal and bkg trees
   // buffers for output trees
   Int_t sig[512];
   Int_t cmsig[512];
   Int_t cm[16];

   // pedestal
   const char* fbkg_name = "Raw_Data_FZ320P_05_MSSD_2_250V_K237_Pedestal.dat-events.root";
   TFile* fbkg = TFile::Open(fbkg_name);
   if (!fbkg) cout<< "File not found: " << fbkg <<endl<<exitl;

   TTree* tree = (TTree*) fbkg->Get("etree");
   tree->SetBranchAddress("raw", &raw);

   TH2* h2d = (TH2*) fbkg->Get("h2d");
   new TCanvas;
   h2d->Draw();

   TProfile* profile = (TProfile*) fbkg->Get("profile"); 
   //new TCanvas;
   //profile->Draw();

   Int_t pedestal[512];
   for (int i=0; i<512; i++) {
      // pedestal[i] = profile->GetBinContent(i+1) - 0.5;
      // pedestal[i] = profile->GetBinContent(i+1) + 0.5;
      pedestal[i] = profile->GetBinContent(i+1);
   }

   // cout << "\nPedestals for every channel\n" << endl;
   // for (int i=0; i<512; i++) {
   //    cout << pedestal[i] << " ";
   //    if (i>0 && (i+1)%128==0)
   //       cout << endl;
   // }

   cout<< "processing bkg" <<endl;

   // output file with tree
   const char* obfname = "FZ320P_05_MSSD_2-bkg.root";
   TFile* obfile = TFile::Open(obfname, "recreate");

   TTree* btree = new TTree("btree", "btree");
   btree->Branch("sig", &sig, "sig[512]/I");
   btree->Branch("cmsig", &cmsig, "cmsig[512]/I");
   btree->Branch("cm", &cm, "cm[16]/I");
   btree->SetMarkerStyle(6);
   btree->SetMarkerColor(2);

   for (int jentry=0; jentry<tree->GetEntries(); ++jentry)
   {
      tree->GetEvent(jentry);
      // sig
      for (int i=0; i<512; ++i) {
         sig[i] = raw[i] - pedestal[i];
      }
      // calc common mode
      Int_t group32[32];
      Int_t index32[32];
      for (int igroup=0; igroup<16; ++igroup) {
         for (int istrip=0; istrip<32; ++istrip)   // istrip is number inside group of 32
         {
            group32[istrip] = sig[igroup*32 + istrip];
         }
         // sort array group32 in ascending order
         TMath::Sort(32, group32, index32, kFALSE);
         Int_t median = group32[index32[14]];
         cm[igroup] = median;
      }
      // subtract common mode
      for (int istrip=0; istrip<512; ++istrip) {
         Int_t igroup = istrip/32;
         cmsig[istrip] = sig[istrip] - cm[igroup];
      }
      // Fill sig, cmsig, cm
      btree->Fill();
   }
   obfile->Write();

   /////////////////////////////////////////////////
   //
   // signal tree
   //
   /////////////////////////////////////////////////

   cout<< "processing signal" <<endl;
   
   TChain* chain = new TChain("etree");
   chain->Add("Raw_Data_FZ320P_05_MSSD_250V_K237_Position_1.dat-events.root");
   chain->Add("Raw_Data_FZ320P_05_MSSD_250V_K237_Position_2.dat-events.root");
   chain->Add("Raw_Data_FZ320P_05_MSSD_2_250V_K237_Position_3.dat-events.root");
   chain->Add("Raw_Data_FZ320P_05_MSSD_2_250V_K237_Position_4.dat-events.root");
   chain->SetBranchAddress("raw", &raw);

   // output file with tree
   const char* osfname = "FZ320P_05_MSSD_2-signal.root";
   TFile* osfile = TFile::Open(osfname, "recreate");

   TTree* stree = new TTree("stree", "stree");
   stree->Branch("sig", &sig, "sig[512]/I");
   stree->Branch("cmsig", &cmsig, "cmsig[512]/I");
   stree->Branch("cm", &cm, "cm[16]/I");
   stree->SetMarkerStyle(6);
   stree->SetMarkerColor(2);

   for (int jentry=0; jentry<chain->GetEntries(); ++jentry)
   {
      chain->GetEvent(jentry);
      // sig
      for (int i=0; i<512; ++i) {
         sig[i] = raw[i] - pedestal[i];
      }
      // calc common mode
      Int_t group32[32];
      Int_t index32[32];
      for (int igroup=0; igroup<16; ++igroup) {
         for (int istrip=0; istrip<32; ++istrip)   // istrip is number inside group of 32
         {
            group32[istrip] = sig[igroup*32 + istrip];
         }
         // sort array group32 in ascending order
         TMath::Sort(32, group32, index32, kFALSE);
         Int_t median = group32[index32[14]];
         cm[igroup] = median;
      }
      // subtract common mode
      for (int istrip=0; istrip<512; ++istrip) {
         Int_t igroup = istrip/32;
         cmsig[istrip] = sig[istrip] - cm[igroup];
      }
      // Fill sig, cmsig, cm
      stree->Fill();
   }
   osfile->Write();

   ////////////////////////////////////////////////////////
   //
   // process trees
   //
   ///////////////////////////////////////////////////////

   cout<< "results" <<endl;

   Double_t a, mean, sigma;

   TH1F* h_sigma_bkg = new TH1F("h_sigma_bkg","CM subtr. noise for groups", 16,0,16);
   TH1F* h_mean_sig = new TH1F("h_mean_sig","CM subtr. signal for groups", 16,0,16);
   TH1F* h_SN = new TH1F("h_SN","Signal to Noise Ratio for groups", 16,0,16);

   new TCanvas;
   btree->Draw("cmsig","Iteration$>=0&&Iteration$<32");
   fitgr(0,0, "Q", "goff", btree->GetHistogram());
   pargaus(a,mean,sigma,"htemp");
   //cout<< "mean = " << mean << " sigma = " << sigma <<endl;
   //-- png("FZ320P_05_MSSD_2-bkg-ex");

   new TCanvas;
   // for (int igroup=0; igroup<16; ++igroup) {
   for (int igroup=0; igroup<15; ++igroup) {
      Int_t ch1 = igroup*32;
      Int_t ch2 = (igroup+1)*32;
      btree->Draw("cmsig",Form("Iteration$>=%d&&Iteration$<%d",ch1,ch2),"");
      fitgr(0,0, "", "", btree->GetHistogram());
      pargaus(a,mean,sigma,"htemp");
      // h_sigma_bkg->Fill(igroup, sigma);
      h_sigma_bkg->SetBinContent(igroup+1, sigma);
   }
   new TCanvas;
   h_sigma_bkg->Draw();
   //-- png("FZ320P_05_MSSD_2-bkg-allgroups");

   // signal
   new TCanvas;
   stree->Draw("cmsig","cmsig>8 &&Iteration$>=0&&Iteration$<32");
   //-- png("FZ320P_05_MSSD_2-sig-ex");

   new TCanvas;
   // for (int igroup=0; igroup<16; ++igroup) {
   for (int igroup=0; igroup<15; ++igroup) {
      Int_t ch1 = igroup*32;
      Int_t ch2 = (igroup+1)*32;
      stree->Draw("cmsig",Form("cmsig>8 &&Iteration$>=%d&&Iteration$<%d",ch1,ch2),"");
      gPad->Update();
      gPad->Modified();
      mean = stree->GetHistogram()->GetMean();
      h_mean_sig->SetBinContent(igroup+1, mean);
   }
   new TCanvas;
   h_mean_sig->Draw();
   //-- png("FZ320P_05_MSSD_2-signal-allgroups");

   for (int igroup=0; igroup<16; ++igroup) {
      Double_t signal32 =  h_mean_sig->GetBinContent(igroup+1);
      Double_t noise32 = h_sigma_bkg->GetBinContent(igroup+1);
      Double_t snr = 0;
      if (noise32 > 0) snr = signal32 / noise32;
      h_SN->SetBinContent(igroup+1, snr);
   }
   new TCanvas;
   h_SN->Draw();
   //-- png("FZ320P_05_MSSD_2-SN-allgroups");
}
Exemple #8
0
//------------------------------------------------------------------------------
// LatinosTreeScript
//------------------------------------------------------------------------------
void LatinosTreeScript(TString rootPath,
		       Float_t luminosity,
		       Int_t   jetChannel,
		       TString flavorChannel,
		       TString theSample,
		       TString systematic,
		       Bool_t  verbose)
{
  TH1::SetDefaultSumw2();

  TString path = Form("rootfiles/%s/%djet/%s/", systematic.Data(), jetChannel, flavorChannel.Data());

  gSystem->mkdir(path, kTRUE);

  TFile* output = new TFile(path + theSample + ".root", "recreate");


  // Counting histograms
  //----------------------------------------------------------------------------
  TH1F* hWTrigger     = new TH1F("hWTrigger",     "", 3, 0, 3);
  TH1F* hWMetCut      = new TH1F("hWMetCut",      "", 3, 0, 3);
  TH1F* hWLowMinv     = new TH1F("hWLowMinv",     "", 3, 0, 3);
  TH1F* hWZVeto       = new TH1F("hWZVeto",       "", 3, 0, 3);
  TH1F* hWpMetCut     = new TH1F("hWpMetCut",     "", 3, 0, 3);
  TH1F* hWJetVeto     = new TH1F("hWJetVeto",     "", 3, 0, 3);
  TH1F* hWDeltaPhiJet = new TH1F("hWDeltaPhiJet", "", 3, 0, 3);
  TH1F* hWSoftMuVeto  = new TH1F("hWSoftMuVeto",  "", 3, 0, 3); 
  TH1F* hWExtraLepton = new TH1F("hWExtraLepton", "", 3, 0, 3);
  TH1F* hWPtll        = new TH1F("hWPtll",        "", 3, 0, 3);
  TH1F* hWTopTagging  = new TH1F("hWTopTagging",  "", 3, 0, 3);

  TH1F* hWeffTrigger     = new TH1F("hWeffTrigger",     "", 3, 0, 3);
  TH1F* hWeffMetCut      = new TH1F("hWeffMetCut",      "", 3, 0, 3);
  TH1F* hWeffLowMinv     = new TH1F("hWeffLowMinv",     "", 3, 0, 3);
  TH1F* hWeffZVeto       = new TH1F("hWeffZVeto",       "", 3, 0, 3);
  TH1F* hWeffpMetCut     = new TH1F("hWeffpMetCut",     "", 3, 0, 3);
  TH1F* hWeffJetVeto     = new TH1F("hWeffJetVeto",     "", 3, 0, 3);
  TH1F* hWeffDeltaPhiJet = new TH1F("hWeffDeltaPhiJet", "", 3, 0, 3);
  TH1F* hWeffSoftMuVeto  = new TH1F("hWeffSoftMuVeto",  "", 3, 0, 3); 
  TH1F* hWeffExtraLepton = new TH1F("hWeffExtraLepton", "", 3, 0, 3);
  TH1F* hWeffPtll        = new TH1F("hWeffPtll",        "", 3, 0, 3);
  TH1F* hWeffTopTagging  = new TH1F("hWeffTopTagging",  "", 3, 0, 3);


  // WW level histograms
  //----------------------------------------------------------------------------
  TH1F* hPtLepton1WWLevel       = new TH1F("hPtLepton1WWLevel",       "", 200, 0, 200);
  TH1F* hPtLepton2WWLevel       = new TH1F("hPtLepton2WWLevel",       "", 200, 0, 200);
  TH1F* hPtDiLeptonWWLevel      = new TH1F("hPtDiLeptonWWLevel",      "", 200, 0, 200);
  TH1F* hMinvWWLevel            = new TH1F("hMinvWWLevel",            "", 200, 0, 200);
  TH1F* hMtWWLevel              = new TH1F("hMtWWLevel",              "", 250, 0, 250);
  TH1F* hNJets30WWLevel         = new TH1F("hNJetsPF30WWLevel",       "",  10, 0,  10);
  TH1F* hpfMetWWLevel           = new TH1F("hpfMetWWLevel",           "", 150, 0, 150);
  TH1F* hppfMetWWLevel          = new TH1F("hppfMetWWLevel",          "", 150, 0, 150);
  TH1F* hchMetWWLevel           = new TH1F("hchMetWWLevel",           "", 150, 0, 150);
  TH1F* hpchMetWWLevel          = new TH1F("hpchMetWWLevel",          "", 150, 0, 150);
  TH1F* hpminMetWWLevel         = new TH1F("hpminMetWWLevel",         "", 150, 0, 150);
  TH1F* hDeltaRLeptonsWWLevel   = new TH1F("hDeltaRLeptonsWWLevel",   "",  50, 0,   5);
  TH1F* hDeltaPhiLeptonsWWLevel = new TH1F("hDeltaPhiLeptonsWWLevel", "",  32, 0, 3.2);
  TH1F* hDPhiPtllJetWWLevel     = new TH1F("hDPhiPtllJetWWLevel",     "",  32, 0, 3.2);

  TH1F* h_WWLevel_TightFailEvents = new TH1F("h_WWLevel_TightFailEvents", "", 3, 0 , 3);
  TH1F* h_WWLevel_TightTightEvents = new TH1F("h_WWLevel_TightTightEvents", "", 3, 0 , 3);
  TH1F* h_WWLevel_TightLooseEvents = new TH1F("h_WWLevel_TightLooseEvents", "", 3, 0 , 3);


  // TwoLeptons level histograms
  //----------------------------------------------------------------------------
  TH1F* hPtLepton1TwoLeptonsLevel       = new TH1F("hPtLepton1TwoLeptonsLevel",       "", 200, 0, 200);
  TH1F* hPtLepton2TwoLeptonsLevel       = new TH1F("hPtLepton2TwoLeptonsLevel",       "", 200, 0, 200);
  TH1F* hPtDiLeptonTwoLeptonsLevel      = new TH1F("hPtDiLeptonTwoLeptonsLevel",      "", 200, 0, 200);
  TH1F* hMinvTwoLeptonsLevel            = new TH1F("hMinvTwoLeptonsLevel",            "", 200, 0, 200);
  TH1F* hMtTwoLeptonsLevel              = new TH1F("hMtTwoLeptonsLevel",              "", 250, 0, 250);
  TH1F* hNJets30TwoLeptonsLevel         = new TH1F("hNJetsPF30TwoLeptonsLevel",       "",  10, 0,  10);
  TH1F* hpfMetTwoLeptonsLevel           = new TH1F("hpfMetTwoLeptonsLevel",           "", 150, 0, 150);
  TH1F* hppfMetTwoLeptonsLevel          = new TH1F("hppfMetTwoLeptonsLevel",          "", 150, 0, 150);
  TH1F* hchMetTwoLeptonsLevel           = new TH1F("hchMetTwoLeptonsLevel",           "", 150, 0, 150);
  TH1F* hpchMetTwoLeptonsLevel          = new TH1F("hpchMetTwoLeptonsLevel",          "", 150, 0, 150);
  TH1F* hpminMetTwoLeptonsLevel         = new TH1F("hpminMetTwoLeptonsLevel",         "", 150, 0, 150);
  TH1F* hDeltaRLeptonsTwoLeptonsLevel   = new TH1F("hDeltaRLeptonsTwoLeptonsLevel",   "",  50, 0,   5);
  TH1F* hDeltaPhiLeptonsTwoLeptonsLevel = new TH1F("hDeltaPhiLeptonsTwoLeptonsLevel", "",  32, 0, 3.2);
  TH1F* hDPhiPtllJetTwoLeptonsLevel     = new TH1F("hDPhiPtllJetTwoLeptonsLevel",     "",  32, 0, 3.2);

  TH1F* h_TwoLeptons_TightFailEvents = new TH1F("h_TwoLeptons_TightFailEvents", "", 3, 0 , 3);
  TH1F* h_TwoLeptons_TightTightEvents = new TH1F("h_TwoLeptons_TightTightEvents", "", 3, 0 , 3);
  TH1F* h_TwoLeptons_TightLooseEvents = new TH1F("h_TwoLeptons_TightLooseEvents", "", 3, 0 , 3);



  // Dilepton level differential histograms 
  //----------------------------------------------------------------------------

  //differential in dilepton (eta, pt, ptll, mll, dphill), jets (jetpt1, njet), transverse mass? 2-jet bin?
  
  Double_t pt1bins[8] = {20,40,60,80,100,125,150,200}; 
  Double_t eta1bins[9] = {-2.4,-1.8,-1.2,-0.6,0,0.6,1.2,1.8,2.4};
  Double_t mllbins[9] = {20,40,60,80,100,125,150,175,200};
  Double_t dphibins[13] = {0,0.25,0.5,0.75,1,1.25,1.5,1.75,2,2.25,2.5,2.75,3};
  Double_t ptllbins[8] = {30,40,50,60,70,85,120,150};

  TH1F* hPtLepton1DilepLevel_Diff  = new TH1F("hPtLepton1DilepLevel_Diff",       "", 7, pt1bins);
  TH1F* hEtaLepton1DilepLevel_Diff  = new TH1F("hEtaLepton1DilepLevel_Diff",       "", 8, eta1bins);
  TH1F* hDileptonDilepLevel_Diff  = new TH1F("hDileptonDilepLevel_Diff",       "", 7, ptllbins);
  TH1F* hMinvDilepLevel_Diff  = new TH1F("hMinvDilepLevel_Diff",       "", 8, mllbins);
  TH1F* hDeltaPhiDilepLevel_Diff  = new TH1F("hDeltaPhiDilepLevel_Diff",       "", 12, dphibins);


  // WW level differential histograms 
  //----------------------------------------------------------------------------

  TH1F* hPtLepton1WWLevel_Diff  = new TH1F("hPtLepton1WWLevel_Diff",       "",7, pt1bins);
  TH1F* hEtaLepton1WWLevel_Diff  = new TH1F("hEtaLepton1WWLevel_Diff",       "", 8, eta1bins);
  TH1F* hDileptonWWLevel_Diff  = new TH1F("hDileptonWWLevel_Diff",       "", 7, ptllbins);
  TH1F* hMinvWWLevel_Diff  = new TH1F("hMinvWWLevel_Diff",       "", 8, mllbins);
  TH1F* hDeltaPhiWWLevel_Diff  = new TH1F("hDeltaPhiWWLevel_Diff",       "", 12, dphibins);




  // Data-driven methods: Z+jets
  //----------------------------------------------------------------------------
  TH1F* hNinZevents     [numberDYMVACuts];
  TH1F* hNoutZevents    [numberDYMVACuts];
  TH1F* hNinLooseZevents[numberDYMVACuts];
  TH1F* hMassInZevents  [numberDYMVACuts];
  TH1F* hMassOutZevents [numberDYMVACuts];

  for (Int_t nC=0; nC<numberDYMVACuts; nC++) {
    hNinZevents     [nC] = new TH1F(Form("hNinZevents%.1i",      nC+1 ), "",   3, 0,   3);
    hNoutZevents    [nC] = new TH1F(Form("hNoutZevents%.1i",     nC+1 ), "",   3, 0,   3);
    hNinLooseZevents[nC] = new TH1F(Form("hNinLooseZevents%.1i", nC+1 ), "",   3, 0,   3);
    hMassInZevents  [nC] = new TH1F(Form("hMassInZevents%.1i",   nC+1 ), "", 200, 0, 200);
    hMassOutZevents [nC] = new TH1F(Form("hMassOutZevents%.1i",  nC+1 ), "", 200, 0, 200);

   


  }


  // Data-driven methods: Top
  //----------------------------------------------------------------------------
  TH1F* hTopTaggedEvents            = new TH1F("hTopTaggedEvents",            "", 3, 0, 3);
  TH1F* hNTopControlRegion          = new TH1F("hNTopControlRegion",          "", 3, 0, 3);
  TH1F* hNTopTaggedTopControlRegion = new TH1F("hNTopTaggedTopControlRegion", "", 3, 0, 3);

  TH1F* hbTagDisTopTaggedEvents            = new TH1F("hbTagDisTopTaggedEvents",            "", 300, -10, 20);
  TH1F* hbTagDisNTopControlRegion          = new TH1F("hbTagDisNTopControlRegion",          "", 300, -10, 20);
  TH1F* hbTagDisNTopTaggedTopControlRegion = new TH1F("hbTagDisNTopTaggedTopControlRegion", "", 300, -10, 20);


  //----------------------------------------------------------------------------
  // Input files
  //----------------------------------------------------------------------------
  TString filesPath;

  if (runAtOviedo) filesPath = " /hadoop/LatinosSkims/ReducedTrees/R53X_S1_V08_S2_V09_S3_V13/";
  if (runAtIfca)   filesPath = "/gpfs/csic_projects/tier3data/LatinosSkims/ReducedTrees/Systematics2013_nominals_fromMaiko/"; 
  if (runEOS)      filesPath = "root://eoscms.cern.ch//eos/cms/store/group/phys_higgs/cmshww/amassiro/RunI/trees/tree_skim_wwmin_09Jan2014/";

  if (rootPath != "") filesPath = rootPath;

  TChain* tree = new TChain("latino", "latino");

  if (theSample == "DataRun2012_Total") {

    tree->Add(filesPath + "/data/" + "latino_RunA_892pbinv.root");
    tree->Add(filesPath + "/data/" + "latino_RunB_4404pbinv.root");
    tree->Add(filesPath + "/data/" + "latino_RunC_7032pbinv.root");
    tree->Add(filesPath + "/data/" + "latino_RunD_7274pbinv.root");
  }

  else if (theSample == "WJetsFakes_Total_old") {
    tree->Add("/gpfs/csic_projects/tier3data/LatinosSkims/ReducedTrees/R53X_S1_V08_S2_V09_S3_V13/Moriond13/latino_LooseLoose_19.5fb.root");

 }
  else if (theSample == "WJetsFakes_Total") {
      
    tree->Add(filesPath + "/wjets/" + "latino_RunA_892pbinv_LooseLoose.root");
    tree->Add(filesPath + "/wjets/" + "latino_RunB_4404pbinv_LooseLoose.root");
    tree->Add(filesPath + "/wjets/" + "latino_RunC_7032pbinv_LooseLoose.root");
    tree->Add(filesPath + "/wjets/" + "latino_RunD_7274pbinv_LooseLoose.root");
    tree->Add(filesPath + "/wjets/" + "latino_082_WGstarToElNuMad.root");
    tree->Add(filesPath + "/wjets/" + "latino_083_WGstarToMuNuMad.root");
    tree->Add(filesPath + "/wjets/" + "latino_084_WGstarToTauNuMad.root");
    tree->Add(filesPath + "/wjets/" + "latino_085_WgammaToLNuG.root");
    tree->Add(filesPath + "/wjets/" + "latino_086_ZgammaToLLuG.root");

  }
  else if (theSample == "ggWWto2L") {
    tree->Add(filesPath + "/" + systematic + "/" + "latino_001_GluGluToWWTo4L.root");
  }
  else if (theSample == "WWTo2L2Nu") {
    tree->Add(filesPath + "/" + systematic + "/" + "latino_000_WWJets2LMad.root");
  }
  else if (theSample == "WWTo2L2Nu_pow") {
    tree->Add(filesPath + "/" + systematic + "/" + "latino_006_WWJets2LPowheg.root");
  }
  else if (theSample == "WWTo2L2Nu_nonSkim_pow") {
    tree->Add("/gpfs/csic_projects/tier3data/LatinosSkims/ReducedTrees/DiferentialXSection/NoSkim_puW_effW_triggW/latino006.root");
  }
  else if (theSample == "WWTo2L2Nu_mcnlo") {
    tree->Add(filesPath + "/" + systematic + "/" + "latino_002_WWto2L2NuMCatNLO.root");
  }
  else if (theSample == "WWTo2L2Nu_mcnlo_nnll") {
    tree->Add("/gpfs/csic_projects/cms/calderon/WWGEN/nnllResummation/latino002_nll_ewk.root");
  }
  else if (theSample == "WWTo2L2Nu_pow_nnll") {
    tree->Add("/gpfs/csic_projects/cms/calderon/WWGEN/nnllResummation/latino006_nll_ewk.root");
  }
  else if (theSample == "WWTo2L2Nu_mad_nnll") {
    tree->Add("/gpfs/csic_projects/cms/calderon/WWGEN/nnllResummation/latino000_nll_ewk.root");
  } else if (theSample == "WZ") {
    tree->Add(filesPath + "/" + systematic + "/" + "latino_074_WZJetsMad.root");
    tree->Add(filesPath + "/" + systematic + "/" + "latino_078_WZTo2L2QMad.root");
  }
  else if (theSample == "ZZ") {
    tree->Add(filesPath + "/" + systematic + "/" + "latino_075_ZZJetsMad.root");
    tree->Add(filesPath + "/" + systematic + "/" + "latino_079_ZZTo2L2QMad.root"); 
  }
  else if (theSample == "TTbar") {
    tree->Add(filesPath + "/" + systematic + "/" + "latino_019_TTTo2L2Nu2B.root");
  }
  else if (theSample == "TW") {
    tree->Add(filesPath + "/" + systematic + "/" + "latino_011_TtWFullDR.root");
    tree->Add(filesPath + "/" + systematic + "/" + "latino_012_TbartWFullDR.root");
  }
  else if (theSample == "Top") {
    tree->Add(filesPath + "/" + systematic + "/" + "latino_019run_TTTo2L2Nu2B.root");
    tree->Add(filesPath + "/" + systematic + "/" + "latino_011_TtWFullDR.root");
    tree->Add(filesPath + "/" + systematic + "/" + "latino_012_TbartWFullDR.root");
  }
  else if (theSample == "DY") {
    tree->Add(filesPath + "/" + systematic + "/" + "latino_036_DY10toLLMad.root");
    tree->Add(filesPath + "/" + systematic + "/" + "latino_037_DY50toLLMad.root");
  }
  else if (theSample == "DYtautau") { // Only for OF channels!!! 
    tree->Add(filesPath + "/templates/" + "latino_DYtt_19.5fb.root"); // CHECK PATH    
  }
  else if (theSample == "Zgamma") { 
    tree->Add(filesPath + "/" + systematic + "/" + "latino_086_ZgammaToLLuG.root");
  }
  else if (theSample == "WgammaNoStar") {
    tree->Add(filesPath + "/" + systematic + "/" + "latino_085_WgammaToLNuG.root");
  }
  else if (theSample == "WgammaStar") {
    tree->Add(filesPath + "/" + systematic + "/" + "latino_082_WGstarToElNuMad.root");
    tree->Add(filesPath + "/" + systematic + "/" + "latino_083_WGstarToMuNuMad.root");
    tree->Add(filesPath + "/" + systematic + "/" + "latino_084_WGstarToTauNuMad.root");
  }
  else if (theSample == "HWW125") { 
    tree->Add(filesPath + "/" + systematic + "/" + "latino_1125_ggToH125toWWTo2LAndTau2Nu.root");
  }
  else if (theSample =="GamGamWW"){
    tree->Add(filesPath + "/" + systematic + "/" + "latino_008_GamGamWW.root");    
  }
  else if (theSample == "WJets") {
    tree->Add(filesPath + "/" + systematic + "/" + "latino_080_WJetsToLNuMad.root");
    //CHECK PATH: tree->Add("/gpfs/csic_projects/tier3data/LatinosSkims/ReducedTrees/R53X_S1_V08_S2_V09_S3_V13/MC_LooseLoose/4L/latino_080_WJetsToLNuMad.root");
  }
  else if (theSample == "VVV") {
    tree->Add(filesPath + "/" + systematic + "/" + "latino_088_WWGJets.root");
    tree->Add(filesPath + "/" + systematic + "/" + "latino_089_WZZJets.root");
    tree->Add(filesPath + "/" + systematic + "/" + "latino_090_ZZZJets.root");
    tree->Add(filesPath + "/" + systematic + "/" + "latino_091_WWZJets.root");
    tree->Add(filesPath + "/" + systematic + "/" + "latino_092_WWWJets.root");
    tree->Add(filesPath + "/" + systematic + "/" + "latino_093_TTWJets.root");
    tree->Add(filesPath + "/" + systematic + "/" + "latino_094_TTZJets.root");
    tree->Add(filesPath + "/" + systematic + "/" + "latino_095_TTWWJets.root");
    tree->Add(filesPath + "/" + systematic + "/" + "latino_096_TTGJets.root");
  }
  else {
    return;
  }


  // Declaration of leaf types
  //----------------------------------------------------------------------------
  Float_t baseW;        tree->SetBranchAddress("baseW"       , &baseW);
  Float_t channel;      tree->SetBranchAddress("channel"     , &channel);
  Float_t chmet;        tree->SetBranchAddress("chmet"       , &chmet);
  Float_t dataset;      tree->SetBranchAddress("dataset"     , &dataset);
  Float_t dphill;       tree->SetBranchAddress("dphill"      , &dphill);
  Float_t dphilljet;    tree->SetBranchAddress("dphilljet"   , &dphilljet);
  Float_t dphilljetjet; tree->SetBranchAddress("dphilljetjet", &dphilljetjet);
  Float_t drll;         tree->SetBranchAddress("drll"        , &drll);
  Float_t effW;         tree->SetBranchAddress("effW"        , &effW);
  Float_t jeteta1;      tree->SetBranchAddress("jeteta1"     , &jeteta1);
  Float_t jeteta2;      tree->SetBranchAddress("jeteta2"     , &jeteta2);
  Float_t jeteta3;      tree->SetBranchAddress("jeteta3"     , &jeteta3);
  Float_t jetpt1;       tree->SetBranchAddress("jetpt1"      , &jetpt1);
  Float_t jetpt2;       tree->SetBranchAddress("jetpt2"      , &jetpt2);
  Float_t jetpt3;       tree->SetBranchAddress("jetpt3"      , &jetpt3);
  Float_t jettche1;     tree->SetBranchAddress("jettche1"    , &jettche1);
  Float_t jettche2;     tree->SetBranchAddress("jettche2"    , &jettche2);
  Float_t mctruth;      tree->SetBranchAddress("mctruth"     , &mctruth);
  Float_t mll;          tree->SetBranchAddress("mll"         , &mll);
  Float_t mpmet;        tree->SetBranchAddress("mpmet"       , &mpmet); 
  Float_t mth;          tree->SetBranchAddress("mth"         , &mth);
  Float_t nbjet;        tree->SetBranchAddress("nbjet"       , &nbjet);
  Float_t nbjettche;    tree->SetBranchAddress("nbjettche"   , &nbjettche);
  Float_t nextra;       tree->SetBranchAddress("nextra"      , &nextra);
  Float_t njet;         tree->SetBranchAddress("njet"        , &njet);
  Float_t nvtx;         tree->SetBranchAddress("nvtx"        , &nvtx);
  Float_t pchmet;       tree->SetBranchAddress("pchmet"      , &pchmet);
  Float_t pfmet;        tree->SetBranchAddress("pfmet"       , &pfmet);
  Float_t ppfmet;       tree->SetBranchAddress("ppfmet"      , &ppfmet);
  Float_t pt1;          tree->SetBranchAddress("pt1"         , &pt1);
  Float_t pt2;          tree->SetBranchAddress("pt2"         , &pt2);
  Float_t eta1;          tree->SetBranchAddress("eta1"         , &eta1);
  Float_t eta2;          tree->SetBranchAddress("eta2"         , &eta2);
  Float_t ch1;          tree->SetBranchAddress("ch1"         , &ch1);
  Float_t ch2;          tree->SetBranchAddress("ch2"         , &ch2);
  Float_t ptll;         tree->SetBranchAddress("ptll"        , &ptll);
  Float_t softtche;     tree->SetBranchAddress("softtche"    , &softtche);
  Float_t trigger;      tree->SetBranchAddress("trigger"     , &trigger);
  Float_t triggW;       tree->SetBranchAddress("triggW"      , &triggW);
  Int_t   bveto;        tree->SetBranchAddress("bveto"       , &bveto);
  Int_t   bveto_ip;     tree->SetBranchAddress("bveto_ip"    , &bveto_ip);
  Int_t   bveto_mu;     tree->SetBranchAddress("bveto_mu"    , &bveto_mu);
  Int_t   bveto_nj30;   tree->SetBranchAddress("bveto_nj30"  , &bveto_nj30);
  Int_t   dphiveto;     tree->SetBranchAddress("dphiveto"    , &dphiveto);
  Int_t   sameflav;     tree->SetBranchAddress("sameflav"    , &sameflav);
  Int_t   zveto;        tree->SetBranchAddress("zveto"       , &zveto);
  UInt_t  event;        tree->SetBranchAddress("event"       , &event);
  UInt_t  lumi;         tree->SetBranchAddress("lumi"        , &lumi);
  UInt_t  run;          tree->SetBranchAddress("run"         , &run);

  Int_t pass2012ICHEP1;  tree->SetBranchAddress("pass2012ICHEP1", &pass2012ICHEP1);
  Int_t pass2012ICHEP2;  tree->SetBranchAddress("pass2012ICHEP2", &pass2012ICHEP2);
  
    Float_t dymva1;          tree->SetBranchAddress("dymva1"         , &dymva1);

  

    Float_t nllW = 1; 
    if ( theSample.Contains("_nnll") && jetChannel == 0)
      tree->SetBranchAddress("nllW", &nllW);

    Float_t fakeW;

  if (theSample.Contains("WJetsFakes"))
    tree->SetBranchAddress("fakeW", &fakeW);

  Float_t puW;
  
  if (!theSample.Contains("WJetsFakes") && !theSample.Contains("Data"))
    tree->SetBranchAddress("puW", &puW);


  // Set the channel
  //----------------------------------------------------------------------------
  Float_t SelectedChannel = -999;

  if      (flavorChannel == "MuMu") SelectedChannel =  0;
  else if (flavorChannel == "EE"  ) SelectedChannel =  1;
  else if (flavorChannel == "EMu" ) SelectedChannel =  2;
  else if (flavorChannel == "MuE" ) SelectedChannel =  3;
  else if (flavorChannel == "OF" )  SelectedChannel =  4;
  else if (flavorChannel == "SF" )  SelectedChannel =  5;
  
  //  else if (flavorChannel == "All" ) SelectedChannel = -1;


  //----------------------------------------------------------------------------
  // Loop
  //----------------------------------------------------------------------------
  for (int ievent=0; ievent<tree->GetEntries(); ievent++) {
    
    tree->GetEntry(ievent);
    
    Double_t efficiencyW = effW * triggW;
    Double_t totalW      = -999;

    
    Double_t mybaseW = 5984.0/999864; 
    //5812.3/539594; // mcnlo 
    //5812.3/1933235; // madgraph (1933232)
    // 5812.3/999864; // powheg (999860)


    if (theSample.Contains("Data"))
      totalW = 1.0;

    else if (theSample.Contains("WJetsFakes")) { 
      totalW = fakeW;
     
      if ( dataset >= 82 && dataset <= 85 ) 
	totalW  = fakeW * (1 + 0.5 * (dataset >= 82 && dataset <= 84)) * baseW * puW * effW * triggW * luminosity;
    
    }

    else if (theSample.Contains("_nnll") ) {
      efficiencyW = puW * effW * triggW *nllW;
      totalW      = (1 + 0.5 * (dataset >= 82 && dataset <= 84)) * mybaseW * efficiencyW * luminosity;
    } 

    else {
      efficiencyW = puW * effW * triggW ;
      totalW      = (1 + 0.5 * (dataset >= 82 && dataset <= 84)) * baseW * efficiencyW * luminosity;
    }

    //cout <<mybaseW << endl;

    //if (theSample.Contains("DYtautau") && dataset != 86) totalW *= (19.4/12.1);


    // Help variables
    //--------------------------------------------------------------------------
    //   Int_t dphiv = ((njet <= 1 && dphiveto) || (njet > 1 && dphilljetjet < 165.*TMath::DegToRad()));

    Int_t dphiv = (njet <= 1 || (njet > 1 && dphilljetjet < 165.*TMath::DegToRad()));

    Float_t metvar = (njet <= 1) ? mpmet : pfmet;

    Float_t jetbin = njet;

    Float_t dyMVA = ( !sameflav || ( (njet!=0 || dymva1>0.88) && (njet!=1 || dymva1>0.84) && ( njet==0 || njet==1 || (pfmet > 45.0)) ) );

	    
    if (njet == 3) jetbin = 2;  


    Int_t vbfsel = ((jetpt3 <= 30 || !(jetpt3 > 30 && ((jeteta1-jeteta3 > 0 && jeteta2-jeteta3 < 0) || (jeteta2-jeteta3 > 0 && jeteta1-jeteta3 < 0)))));


    // The selection begins here
    //--------------------------------------------------------------------------
    if (theSample == "DY" && mctruth == 2 && (flavorChannel == "EMu" || flavorChannel == "MuE")) continue;
    if (run == 201191) continue;
    if (trigger != 1) continue;
    if (pt2 <= 20) continue; // increase the pt of the leptons to further reduce Wjets 
    if (pt1 <= 20) continue; // increase the pt of the leptons to further reduce Wjets 
    if (ch1*ch2 > 0) continue;

    if (dataset == 86 && (flavorChannel == "MuMu" || flavorChannel == "EE")) continue; 

    if ((SelectedChannel == -1) || (channel == SelectedChannel)    || 
	(SelectedChannel == 4 && (channel == 2 || channel == 3) )  || 
	(SelectedChannel == 5 && (channel == 0 || channel == 1) ) ) {



      //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      //
      // Data-driven methods
      //
      //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      // if (pfmet > 20 && mpmet > 20 && mll > 12 && ptll > 45 && nextra == 0 && (dphiv || !sameflav)) { OLD CUTS
	
      // if( pfmet > 20 && mpmet > 20 && mll > 12&& nextra == 0 && (dphiv || !sameflav) && dyMVA && ptll>30 && (!sameflav || ptll>45) ) { 

      if( pfmet > 20 && mpmet > 20 && mll > 12&& nextra == 0 && (dphiv || !sameflav)  && ptll>30 && (!sameflav || ptll>45) ) { 



	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//
	// Z+jets
	//
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

	//if (dphiv && jetbin == jetChannel && bveto_mu && (bveto_ip && (nbjettche == 0 || njet > 3))) { OLD CUTS

	if( jetbin == jetChannel && bveto_mu && bveto_ip==1 && nbjettche==0 && ptll > 45) { 


	  // Loop over the metvar bins
	  //--------------------------------------------------------------------
	  for (size_t mc=0; mc<numberDYMVACuts; mc ++) {
	    
	    if ( jetbin == 0 ) { 

	      if ( dymva1 > DYMVACut_0j[mc] && fabs(mll - ZMASS) < 7.5) {
		hNinLooseZevents[mc]->Fill(1,totalW);
	      }

	      if (dymva1 > DYMVACut_0j[mc] && dymva1 < DYMVACut_0j[mc+1]) {   
		if (fabs(mll - ZMASS) < 7.5) {
		  hNinZevents[mc]   ->Fill(  1, totalW);
		  hMassInZevents[mc]->Fill(mll, totalW);
		}
		else if (fabs(mll - ZMASS) > 15) {  
		  hNoutZevents[mc]   ->Fill(  1, totalW);
		  hMassOutZevents[mc]->Fill(mll, totalW);
		}
	      }
	    }

	    if ( jetbin == 1 ) { 

	      if ( dymva1 > DYMVACut_1j[mc] && fabs(mll - ZMASS) < 7.5) {
		hNinLooseZevents[mc]->Fill(1,totalW);
	      }

	      if (dymva1 > DYMVACut_1j[mc] && dymva1 < DYMVACut_1j[mc+1]) {   
		if (fabs(mll - ZMASS) < 7.5) {
		  hNinZevents[mc]   ->Fill(  1, totalW);
		  hMassInZevents[mc]->Fill(mll, totalW);
		}
		else if (fabs(mll - ZMASS) > 15) {  
		  hNoutZevents[mc]   ->Fill(  1, totalW);
		  hMassOutZevents[mc]->Fill(mll, totalW);
		}
	      }
	    }


	  }
	}
      
      


	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//
	// Top
	//
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

	//   if (zveto  && metvar > (20 + 25*sameflav)) { OLD CUTS

	if ( zveto && dyMVA ) {

	  
	  // btag_eff denominator
	  if ((jetChannel == 0 && njet == 1 && nbjet == 1) || // jetBProbabilityBJetTags discriminator
	      (jetChannel == 1 && njet == 2 && jettche2 > 2.1) ||
	      (jetChannel == 2)) {

	    hNTopControlRegion->Fill(1, totalW);
	    hbTagDisNTopControlRegion->Fill(jettche2, totalW);
	    
	    // btag_eff numerator
	    if ((jetChannel == 0 && !bveto_nj30) || // bveto_nj30 == tche>2.1 && jetPt[10,30] && softMuonVeto for jetPt<30 
		(jetChannel == 1 && jettche1 > 2.1) ||
		(jetChannel == 2)) {
	      
	      hNTopTaggedTopControlRegion->Fill(1, totalW);
	      hbTagDisNTopTaggedTopControlRegion->Fill(jettche2, totalW);
	    }
	  }
	  
	}

	// Top-tagged events for ttbar estimation
	//----------------------------------------------------------------------
	if (zveto && dyMVA) {

	  if ((jetChannel == 0 && njet == 0 && !bveto) ||
	      (jetChannel == 1 && njet == 1 && bveto && jettche1 > 2.1) || // bveto == bveto_nj30 == tche>2.1 && jetPt[10,30] && softMuonVeto (no pt requirement)
	      (jetChannel == 2)) {
	    
	    hTopTaggedEvents->Fill(1, totalW);
	    hbTagDisTopTaggedEvents->Fill(jettche2, totalW);
	  }
	}
      }


      //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      //
      // Main analisis
      //
      //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


  

      hWTrigger   ->Fill(1, totalW); 
      hWeffTrigger->Fill(1, efficiencyW);



	  hPtLepton1TwoLeptonsLevel      ->Fill(pt1,       totalW);
	  hPtLepton2TwoLeptonsLevel      ->Fill(pt2,       totalW);
	  hPtDiLeptonTwoLeptonsLevel     ->Fill(ptll,      totalW);
	  hMinvTwoLeptonsLevel           ->Fill(mll,       totalW);
	  hMtTwoLeptonsLevel             ->Fill(mth,       totalW);
	  hNJets30TwoLeptonsLevel        ->Fill(njet,      totalW);
	  hpfMetTwoLeptonsLevel          ->Fill(pfmet,     totalW);
	  hppfMetTwoLeptonsLevel         ->Fill(ppfmet,    totalW);
	  hchMetTwoLeptonsLevel          ->Fill(chmet,     totalW);
	  hpchMetTwoLeptonsLevel         ->Fill(pchmet,    totalW);
	  hpminMetTwoLeptonsLevel        ->Fill(mpmet,     totalW);
	  hDeltaRLeptonsTwoLeptonsLevel  ->Fill(drll,      totalW);
	  hDeltaPhiLeptonsTwoLeptonsLevel->Fill(dphill,    totalW);
	  hDPhiPtllJetTwoLeptonsLevel    ->Fill(dphilljet, totalW);



	  //if ( (pass2012ICHEP1 && !pass2012ICHEP2) || (!pass2012ICHEP1 && pass2012ICHEP2))    
	    h_TwoLeptons_TightFailEvents ->Fill(1, totalW); 
	  
	  if ( pass2012ICHEP1 && pass2012ICHEP2) 
	    h_TwoLeptons_TightTightEvents ->Fill(1, totalW); 
	  

	  if ( pass2012ICHEP1 || pass2012ICHEP2) 
	    h_TwoLeptons_TightLooseEvents ->Fill(1, totalW); 
	


    if (nextra == 0) {
			
	    hWExtraLepton->Fill(1, totalW);
	    hWeffExtraLepton->Fill(1, efficiencyW);
      
	    if (pfmet > 20 ) { // removed for differential xsec
	   
	      hWMetCut->Fill(1, totalW);
	      hWeffMetCut->Fill(1, efficiencyW);
	
	      if (mll > 12) {
	    
		hWLowMinv->Fill(1, totalW);
		hWeffLowMinv->Fill(1, efficiencyW);

		if (zveto==1 || !sameflav) {
		  
		  hWZVeto->Fill(1, totalW); 
		  hWeffZVeto->Fill(1, efficiencyW); 

		  if (mpmet > 20  && dyMVA ) { 

		
		    hWpMetCut->Fill(1, totalW);
		    hWeffpMetCut->Fill(1, efficiencyW);		  
		    

		    if (dphiv || !sameflav) {


		      hWDeltaPhiJet->Fill(1, totalW);
		      hWeffDeltaPhiJet->Fill(1, efficiencyW);


		      if (bveto_mu) { //--> third soft lepton with pt> 3GeV 
		      
			hWSoftMuVeto->Fill(1, totalW); 
			hWeffSoftMuVeto->Fill(1, efficiencyW);
		     

			 
			if ( ptll>30 && (!sameflav || ptll>45) ) {
			    
			  hWPtll->Fill(1, totalW);
			  hWeffPtll->Fill(1, efficiencyW);
			  

			  if (jetbin == jetChannel) {
			    
			    hWJetVeto->Fill(1, totalW);
			    hWeffJetVeto->Fill(1, efficiencyW);
			    

			    if (bveto_ip==1 &&  nbjettche==0) {
			      
			      hWTopTagging->Fill(1, totalW);
			      hWeffTopTagging->Fill(1, efficiencyW);

		       
			
			  
			  hPtLepton1WWLevel      ->Fill(pt1,       totalW);
			  hPtLepton2WWLevel      ->Fill(pt2,       totalW);
			  hPtDiLeptonWWLevel     ->Fill(ptll,      totalW);
			  hMinvWWLevel           ->Fill(mll,       totalW);
			  hMtWWLevel             ->Fill(mth,       totalW);
			  hNJets30WWLevel        ->Fill(njet,      totalW);
			  hpfMetWWLevel          ->Fill(pfmet,     totalW);
			  hppfMetWWLevel         ->Fill(ppfmet,    totalW);
			  hchMetWWLevel          ->Fill(chmet,     totalW);
			  hpchMetWWLevel         ->Fill(pchmet,    totalW);
			  hpminMetWWLevel        ->Fill(mpmet,     totalW);
			  hDeltaRLeptonsWWLevel  ->Fill(drll,      totalW);
			  hDeltaPhiLeptonsWWLevel->Fill(dphill,    totalW);
			  hDPhiPtllJetWWLevel    ->Fill(dphilljet, totalW);

			  hPtLepton1WWLevel_Diff  ->Fill(pt1,       totalW);
			  hEtaLepton1WWLevel_Diff ->Fill(eta1,      totalW);
			  hDileptonWWLevel_Diff   ->Fill(ptll,      totalW);
			  hMinvWWLevel_Diff       ->Fill(mll,       totalW);
			  hDeltaPhiWWLevel_Diff   ->Fill(dphill,    totalW);


			  //if ( (pass2012ICHEP1 && !pass2012ICHEP2) || (!pass2012ICHEP1 && pass2012ICHEP2))    
			    h_WWLevel_TightFailEvents ->Fill(1, totalW); 
			  
			   if ( (pass2012ICHEP1 && pass2012ICHEP2)) 
			     h_WWLevel_TightTightEvents ->Fill(1, totalW); 
			  
			    if ( pass2012ICHEP1 || pass2012ICHEP2) 
			      h_WWLevel_TightLooseEvents ->Fill(1, totalW); 
	


			}
			  }
		      }		      
		    }
		  }
		}
	      }
	    }
	  }
	}
      
      
  }
  
}
	  
  verbose = true;

  // Print
  //----------------------------------------------------------------------------
  if (verbose) {

    float norm = 1933235;

    /*
    cout << "Dilepton Level TF  " <<  h_TwoLeptons_TightFailEvents   ->GetEntries() << endl;
    cout << "Dilepton Level TT  " <<  h_TwoLeptons_TightTightEvents  ->GetEntries() << endl;
    cout << "Dilepton Level TL  " <<  h_TwoLeptons_TightLooseEvents  ->GetEntries() << endl;

    cout << "Dilepton Level TF  " <<  h_TwoLeptons_TightFailEvents   ->GetSumOfWeights() << endl;
    cout << "Dilepton Level TT  " <<  h_TwoLeptons_TightTightEvents  ->GetSumOfWeights() << endl;
    cout << "Dilepton Level TL  " <<  h_TwoLeptons_TightLooseEvents  ->GetSumOfWeights() << endl;


    cout << "WW Level TF  " <<  h_WWLevel_TightFailEvents   ->GetEntries() << endl;
    cout << "WW Level TT  " <<  h_WWLevel_TightTightEvents  ->GetEntries() << endl;
    cout << "WW Level TL  " <<  h_WWLevel_TightLooseEvents  ->GetEntries() << endl;

    cout << "WW Level TF  " <<  h_WWLevel_TightFailEvents   ->GetSumOfWeights() << endl;
    cout << "WW Level TT  " <<  h_WWLevel_TightTightEvents  ->GetSumOfWeights() << endl;
    cout << "WW Level TL  " <<  h_WWLevel_TightLooseEvents  ->GetSumOfWeights() << endl;

    */

    cout << endl;
    cout << " Expected number of RAW events for " << theSample.Data() << endl;
    cout << " ------------------+-----------" << endl;
    cout << " trigger           | " << hWTrigger    ->GetEntries() << endl;
    cout << " extra lepton veto | " << hWExtraLepton->GetEntries() << endl;
    cout << " MET cut           | " << hWMetCut     ->GetEntries() << endl;
    cout << " low minv cut      | " << hWLowMinv    ->GetEntries() << endl;
    cout << " Z veto            | " << hWZVeto      ->GetEntries() << endl;
    cout << " projected MET cut | " << hWpMetCut    ->GetEntries() << endl;
    cout << " DeltaPhiJet veto  | " << hWDeltaPhiJet->GetEntries() << endl;    
    cout << " soft muon veto    | " << hWSoftMuVeto ->GetEntries() << endl;
    cout << " ptll cut          | " << hWPtll       ->GetEntries() << endl;
    cout << " jet veto          | " << hWJetVeto    ->GetEntries() << endl;
    cout << " top tagging       | " << hWTopTagging ->GetEntries() << endl; 


    /*
   
    cout << hWTrigger    ->GetEntries() << endl;
    cout << hWExtraLepton->GetEntries() << endl;
    cout << hWMetCut     ->GetEntries() << endl;
    cout << hWLowMinv    ->GetEntries() << endl;
    cout << hWZVeto      ->GetEntries() << endl;
    cout << hWpMetCut    ->GetEntries() << endl;
    cout << hWDeltaPhiJet->GetEntries() << endl;    
    cout << hWSoftMuVeto ->GetEntries() << endl;
    cout << hWTopTagging ->GetEntries() << endl;
    cout << hWPtll       ->GetEntries() << endl;
    cout << hWJetVeto    ->GetEntries() << endl;
    


    
    cout << endl;
    */

    /*
    
    if (!theSample.Contains("Data")) {
      cout << endl;
      cout << " Normalized to " << luminosity << " 1/fb" << endl;
      cout << " ------------------+-----------" << endl;
      cout << " trigger           | " << hWTrigger    ->GetSumOfWeights() << endl;
      cout << " extra lepton veto | " << hWExtraLepton->GetSumOfWeights() << endl;
      cout << " MET cut           | " << hWMetCut     ->GetSumOfWeights() << endl;
      cout << " low minv cut      | " << hWLowMinv    ->GetSumOfWeights() << endl;
      cout << " Z veto            | " << hWZVeto      ->GetSumOfWeights() << endl;
      cout << " projected MET cut | " << hWpMetCut    ->GetSumOfWeights() << endl;
      cout << " DeltaPhiJet veto  | " << hWDeltaPhiJet->GetSumOfWeights() << endl;     
      cout << " soft muon veto    | " << hWSoftMuVeto ->GetSumOfWeights() << endl;
      cout << " jet veto          | " << hWJetVeto    ->GetSumOfWeights() << endl;
      cout << " top tagging       | " << hWTopTagging ->GetSumOfWeights() << endl; 

      cout << endl;

          }
 
    */


    //cout << hWTopTagging->GetBinContent(2) << " +- " << hWTopTagging->GetBinError(2) << endl;	 
 }


  // Save the histograms
  //----------------------------------------------------------------------------
  output->cd();
  output->Write("", TObject::kOverwrite);
  output->Close();
  
}
Exemple #9
0
void draw() {

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

  chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_1.root");
  chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_10.root");
  chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_100.root");
  chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_101.root");
  chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_102.root");
  chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_103.root");
  chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_104.root");
  chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_105.root");
  chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_106.root");
  chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_107.root");
  chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_108.root");
  chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_109.root");
  chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_11.root");
  chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_110.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_111.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_112.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_113.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_114.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_115.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_116.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_117.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_118.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_119.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_12.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_120.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_121.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_122.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_123.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_124.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_125.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_126.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_127.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_128.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_129.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_13.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_130.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_131.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_132.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_133.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_134.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_135.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_136.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_137.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_138.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_139.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_14.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_140.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_141.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_142.root");
  //chain->AddFile("/afs/cern.ch/work/j/jlawhorn/HighPtJet80/HCALTree_143.root");
  
  cout << chain->GetEntries() << endl;

  Double_t pulse[10], ped[10];

  chain->SetBranchAddress("pulse", &pulse);
  chain->SetBranchAddress("ped", &ped);

  vector<Double_t> ucut;
  vector<Double_t> lcut;

  const int nbin=11;

  for (int i=0; i<nbin; i++) {
    lcut.push_back(25+i*25);
    ucut.push_back(50+i*25);
  }
  
  Double_t avgPulse[nbin][10], avgPulse2[nbin][10], adcUnc[nbin][10], totUnc[nbin][10]; 
  for (UInt_t i=0; i<nbin; i++) {
    for (UInt_t j=0; j<10; j++) {avgPulse[i][j]=0; avgPulse2[i][j]=0; adcUnc[i][j]=0; totUnc[i][j]=0;}
  }

  Int_t nPulses[nbin]={0};

  TFile *outf = new TFile("test_hist.root", "recreate");
  TH1D *hQ = new TH1D("hq", "hq",50, 0, 400);

  for (UInt_t i=0; i<chain->GetEntries(); i++) {
  //for (UInt_t i=0; i<1000; i++) {
    chain->GetEntry(i);

    Double_t sumQ=0;
    for (UInt_t j=0; j<10; j++) { sumQ+=pulse[j];}

    hQ->Fill(sumQ);

    if (sumQ<25 || sumQ>300) continue;
    Int_t ibin= floor( sumQ/25-1 );
    //cout << sumQ << ", " << ibin << endl;

    nPulses[ibin]++;

    for (UInt_t j=0; j<10; j++) { 
      avgPulse[ibin][j]+=pulse[j]/sumQ;
      avgPulse2[ibin][j]+=pulse[j]*pulse[j]/sumQ;
      adcUnc[ibin][j]+=(sigma(pulse[j])*sigma(pulse[j])+1)/(pulse[j]*pulse[j]);
    }

  }

  //hQ->Draw("hist");

  //TH1D *h = new TH1D("h1", "h1", 10, -0.5, 9.5);
  vector<TGraphErrors*> grs;
  for (UInt_t i=0; i<nbin; i++) {
    char gname[50];
    sprintf(gname,"graph_%i",i);
    grs.push_back(new TGraphErrors(0));
    grs[i]->SetName(gname);

    cout << lcut[i] << " < Q_10 < " << ucut[i] << ": " << nPulses[i] << endl;

    for (UInt_t j=0; j<10; j++) {
      avgPulse[i][j]/=nPulses[i];
      avgPulse2[i][j]/=nPulses[i];
      adcUnc[i][j]=sqrt(adcUnc[i][j])/nPulses[i];
      totUnc[i][j]=sqrt(adcUnc[i][j] + avgPulse2[i][j] - avgPulse[i][j]*avgPulse[i][j])/sqrt(nPulses[i]);

      //cout << "avgPulse[" << j << "] = " << avgPulse[j] << " +/- " << totUnc[j] << endl;

      grs[i]->SetPoint(j, j, avgPulse[i][j]);
      grs[i]->SetPointError(j, 0, totUnc[i][j]);
    }
    
    grs[i]->Write();
  }

  outf->Write();
  outf->Close();


}
Exemple #10
0
void createPlot(std::vector<TString> samples, std::vector<TString> files, std::vector<TString> legend)
{

  TString y_title = "Number of Entries";
  const int nHist = files.size(); // number of files

  // Declare the histograms to be saved 
  TH1F *h_mll[nHist];
  TH1F *h_dilpt[nHist];
  TH1F *h_dphill[nHist];
  TH1F *h_leadleppt[nHist];
  TH1F *h_trailleppt[nHist];
  TH1F *h_met[nHist];
  TH1F *h_mt[nHist];
  
  // Get the histograms from the ntuples
  for (int i=0;i<nHist;i++) {
    TString treeName = "angles";
    TChain *chain = new TChain(treeName);
    chain->Add(files[i]);
    assert(chain);
    
    // declare histograms  to fill
    Color_t color = kBlack;
    TString sampleName = samples[i];
    if ( sampleName.Contains("SMHiggs",TString::kExact )) color = kBlue;
    if ( sampleName.Contains("PSHiggs", TString::kExact)) color = kMagenta;
    if ( sampleName.Contains("T",  TString::kExact)) color = kRed;
    if ( sampleName.Contains("THiggs",  TString::kExact)) color = kRed;


    
    // define the histograms to plot
    
    // dilmass 
    h_mll[i] = new TH1F(TString("HWW_"+sampleName+"_hdilmass"), TString("HWW_"+sampleName+"_hdilmass"), 20, 0, 200);
    h_mll[i]->SetLineColor(color);
    h_mll[i]->SetMarkerColor(color);
    
    // leading lepton pT
    h_leadleppt[i] = new TH1F(TString("HWW_"+sampleName+"_hleadleppt"), TString("HWW_"+sampleName+"_hleadleppt"), 20, 0, 100);
    h_leadleppt[i]->SetLineColor(color);
    h_leadleppt[i]->SetMarkerColor(color);
   
    // trailing lepton pT
    h_trailleppt[i] = new TH1F(TString("HWW_"+sampleName+"_htrailleppt"), TString("HWW_"+sampleName+"_htrailleppt"), 20, 0, 100);
    h_trailleppt[i]->SetLineColor(color);
    h_trailleppt[i]->SetMarkerColor(color);
    
    // MET
    h_met[i] = new TH1F(TString("HWW_"+sampleName+"_hmet"), TString("HWW_"+sampleName+"_hmet"), 20, 0, 100);
    h_met[i]->SetLineColor(color);
    h_met[i]->SetMarkerColor(color);
    
    
    // dilepton pT
    h_dilpt[i] = new TH1F(TString("HWW_"+sampleName+"_hdilpt"), TString("HWW_"+sampleName+"_hdilpt"), 30, 20, 100);
    h_dilpt[i]->SetLineColor(color);
    h_dilpt[i]->SetMarkerColor(color);
    
    // deltaphi (ll)
    h_dphill[i] = new TH1F(TString("HWW_"+sampleName+"_hdphi"), TString("HWW_"+sampleName+"_hdphi"), 18, 0, 180.0);
    h_dphill[i]->SetLineColor(color);
    h_dphill[i]->SetMarkerColor(color);
    
    // transverse mass
    h_mt[i] = new TH1F(TString("HWW_"+sampleName+"_hmt"), TString("HWW_"+sampleName+"_hmt"), 20, 0, 200);
    h_mt[i]->SetLineColor(color);
    h_mt[i]->SetMarkerColor(color);
    

    std::cout  << "Processing " << chain->GetEntries() << " entries. \n";
    int nEntries =  chain->GetEntries() ;
    int nSelected = 0;
    
    // mcfm variables to be used
    double mll_ = 0.0;
    double leadleppt_ = 0.0;
    double trailleppt_ = 0.0;
    double leadlepeta_ = 0.0;
    double traillepeta_ = 0.0;
    double dphill_ = 0.0;
    double met_ = 0.0;
    double mt_ = 0.0;
    double dilpt_ = 0.0;
    double wt_ = 1.0;

    if (chain->GetBranchStatus("mll"))
      chain->SetBranchAddress("mll", &mll_);

    if (chain->GetBranchStatus("leadleppt"))
      chain->SetBranchAddress("leadleppt", &leadleppt_);

    if (chain->GetBranchStatus("trailleppt"))
      chain->SetBranchAddress("trailleppt", &trailleppt_);

    if (chain->GetBranchStatus("dphill"))
      chain->SetBranchAddress("dphill", &dphill_);

    if (chain->GetBranchStatus("met"))
      chain->SetBranchAddress("met", &met_);
    
    if (chain->GetBranchStatus("mt"))
      chain->SetBranchAddress("mt", &mt_);

    if (chain->GetBranchStatus("dilpt"))
      chain->SetBranchAddress("dilpt", &dilpt_);
    
      if (chain->GetBranchStatus("leadlepeta"))
      chain->SetBranchAddress("leadlepeta", &leadlepeta_);

    if (chain->GetBranchStatus("traillepeta"))
      chain->SetBranchAddress("traillepeta", &traillepeta_);

    if (chain->GetBranchStatus("wt"))
      chain->SetBranchAddress("wt", &wt_);
   
    for ( int ievt = 0; ievt < chain->GetEntries(); ievt++) {
      chain->GetEntry(ievt);
      
      //
      // apply WW selections
      // 
      
      if ( ievt == 0 ) 
	std::cout << leadleppt_ << "\t" << trailleppt_ << "\t" << dilpt_ << "\t" << met_ << "\t" << mll_ << "\n";

      float weight = wt_;

      if ( leadleppt_ < 20. ) continue;
      if ( trailleppt_ < 10. ) continue;
      if ( TMath::Abs(leadlepeta_) > 2.5) continue;
      if ( TMath::Abs(traillepeta_) > 2.5) continue;
      
      /*
      if ( dilpt_ < 45.) continue;
      if ( mll_ < 12.) continue;
      if ( met_ < 20.) continue;

      */
      
      h_mll[i]->Fill(mll_, weight);
      h_dilpt[i]->Fill(dilpt_, weight);
      h_dphill[i]->Fill(dphill_ * 180. / TMath::Pi(), weight);
      h_leadleppt[i]->Fill(leadleppt_, weight);
      h_trailleppt[i]->Fill(trailleppt_, weight);
      h_mt[i]->Fill(mt_, weight);
      h_met[i]->Fill(met_, weight);

      // 
      // apply HWW selections for 125 
      // 
      
      if ( higgselection(mH, mt_, mll_, dphill_, leadleppt_, trailleppt_) ) 
	nSelected++;
    } // end of event loop in each sample
    
    std::cout << Form("sample %s: selection effiency is %i / %i = %.2f\n", samples[i].Data(), nSelected, nEntries, float(nSelected)/float(nEntries));
  }
  
  drawsingle("mll", nHist, h_mll, samples, legend, "Dilepton Invariant Mass [GeV]");
  drawsingle("dphill", nHist, h_dphill, samples, legend, "#Delta#phi(leptons) [degrees]");
  drawsingle("mt", nHist, h_mt, samples, legend, "Transverse Higgs Mass [GeV]");
  drawsingle("met", nHist, h_met, samples, legend, "Transverse Missing Energy [GeV]");
  drawsingle("dilpt", nHist, h_dilpt, samples, legend, "Dilepton pT [GeV]");
  
  output_file->cd();
  
  for(int i=0;i<nHist;i++) {
    h_mll[i]->Write();
    h_dphill[i]->Write();
    h_leadleppt[i]->Write();
    h_trailleppt[i]->Write();
    h_met[i]->Write();
    h_mt[i]->Write();
    h_dilpt[i]->Write();
    
  }
  
  // tidy up
  
  for ( int i = 0; i<nHist;i++) {
    delete h_mll[i];
    delete h_dphill[i];
    delete h_leadleppt[i];
    delete h_trailleppt[i];
    delete h_met[i];
    delete h_mt[i];
    delete h_dilpt[i];
  }

}
Exemple #11
0
void _tag()
{
	TCanvas * c1 = new TCanvas("c1", "The 3d view",0,0,1000,500);
	c1->Divide(2,1);
	TChain* T2 = new TChain("Stats");
	T2->Add("TrashMCTest.root");

	TChain* T = new TChain("Primaries");
	T->Add("VertexRestorer.root");
	
	float _primeCostheta[MAXN];
	int _tag = 0;
	int _primariesTotal = 0;

	T2->SetBranchAddress("tag", &_tag);
	T->SetBranchAddress("primariesTotal", &_primariesTotal);
	T->SetBranchAddress("primeCostheta", &_primeCostheta);

	int mTotalNumberOfEvents = T2->GetEntries();
	int nbins = 30;
	int maxd = 1;
	TH1F * probhist = new TH1F("Pw","# of tracks comparison",nbins,-1,maxd);
	TH1F * taghist = new TH1F("Pw","# of tracks comparison",nbins,-1,maxd);
	for (int i = 0; i < mTotalNumberOfEvents; i++) 
	{
		T2->GetEntry(i);
		T->GetEntry(i);
		if (_tag == 0) 
		{
			for (int j = 0; j < _primariesTotal; j++) 
			{
				probhist->Fill(_primeCostheta[j]);
			}
		}
		else 
		{
			for (int j = 0; j < _primariesTotal; j++) 
			{
				taghist->Fill(_primeCostheta[j]);
			}
		}
	
	}
	c1->cd(1);
	THStack * stack = new THStack("d",";cos");
	stack->Add(probhist);
	stack->Add(taghist);
	probhist->SetLineWidth(3);
	//probhist->SetFillColor(kBlue);
	taghist->SetLineWidth(3);
	taghist->SetLineColor(kYellow+1);
	//taghist->SetFillColor(kYellow);
	probhist->Draw();
	taghist->Draw("same");
	stack->Draw();
	c1->cd(2);
	TFile * file = TFile::Open("TrashRecoTest.root");
	file->cd();
	TTree * tree = Jets;
	TH1F * bhist = new TH1F("bhist","# of tracks comparison",nbins,-1,maxd);
	TH1F * bbarhist = new TH1F("bbarhist","# of tracks comparison",nbins,-1,maxd);
	TH1F * whist = new TH1F("whist",";cos#theta",nbins,-1,maxd);
	tree->Project("bhist", "costhetaJetParticles", "costhetaJetParticles > -1 && mcpdg < 0");
	tree->Project("bbarhist", "costhetaJetParticles", "costhetaJetParticles > -1 && mcpdg > 0");
	tree->Project("whist", "costhetaJetParticles", "costhetaJetParticles > -1 && mcpdg == 0");
	whist->SetLineWidth(3);
	whist->SetLineColor(kBlue);
	whist->SetMinimum(0);
	whist->Draw("same");
	bhist->SetLineWidth(3);
	bhist->SetLineColor(kGreen);
	bhist->Draw("same");
	bbarhist->SetLineWidth(3);
	bbarhist->SetLineColor(kRed);
	bbarhist->Draw("same");
	TLegend *legendMean = new TLegend(0.17,0.7,0.5,0.92,NULL,"brNDC");
	legendMean->SetFillColor(kWhite);
	legendMean->SetBorderSize(0);
	legendMean->AddEntry(bhist,"b-jet","fp");
	legendMean->AddEntry(bbarhist,"#bar{b}-jet","fp");
	legendMean->AddEntry(whist,"w-jets","fp");
	legendMean->Draw();
	gPad->Modified();

}
void fitSingleMass( const std::string& basedir, float mass, const std::string&  width, TGraphErrors* gr_mean, TGraphErrors* gr_sigma, TGraphErrors* gr_width, TGraphErrors* gr_alpha1, TGraphErrors* gr_n1, TGraphErrors* gr_alpha2, TGraphErrors* gr_n2 ) {


  std::string outdir = "genSignalShapes";
  system( Form("mkdir -p %s", outdir.c_str()) );


  std::string dataset( Form( "GluGluSpin0ToZGamma_ZToLL_W_%s_M_%.0f_TuneCUEP8M1_13TeV_pythia8", width.c_str(), mass ) );
  std::cout << "-> Starting: " << dataset << std::endl;

  system( Form("ls %s/%s/crab_%s/*/0000/genAna_1.root >> toBeAdded.txt", basedir.c_str(), dataset.c_str(), dataset.c_str() ) );
  TChain* tree = new TChain("mt2");
  ifstream ifs("toBeAdded.txt");
  while( ifs.good() ) {
    std::string fileName;
    ifs >> fileName;
    TString fileName_tstr(fileName);
    if( !fileName_tstr.Contains("pnfs") ) continue;
    tree->Add(Form("$DCAP/%s/mt2", fileName.c_str()) );
  }
  system( "rm toBeAdded.txt" );

  if( tree->GetEntries()==0 ) return;

  int ngenPart;
  tree->SetBranchAddress( "ngenPart", &ngenPart );
  float genPart_pt[100];
  tree->SetBranchAddress( "genPart_pt", genPart_pt );
  float genPart_eta[100];
  tree->SetBranchAddress( "genPart_eta", genPart_eta );
  float genPart_phi[100];
  tree->SetBranchAddress( "genPart_phi", genPart_phi );
  float genPart_mass[100];
  tree->SetBranchAddress( "genPart_mass", genPart_mass );
  int genPart_pdgId[100];
  tree->SetBranchAddress( "genPart_pdgId", genPart_pdgId );
  int genPart_motherId[100];
  tree->SetBranchAddress( "genPart_motherId", genPart_motherId );
  int genPart_status[100];
  tree->SetBranchAddress( "genPart_status", genPart_status );



  RooRealVar* x = new RooRealVar("boss_mass", "boss_mass", mass, 0.5*mass, 1.5*mass );

  RooDataSet* data = new RooDataSet( "data", "data", RooArgSet(*x) );



  int nentries = tree->GetEntries();


  for( int iEntry = 0; iEntry<nentries; ++iEntry ) {

    if( iEntry % 25000 == 0 ) std::cout << "  Entry: " << iEntry << " / " << nentries << std::endl;

    tree->GetEntry(iEntry);

    TLorentzVector leptPlus;
    TLorentzVector leptMinus;
    TLorentzVector photon;
    bool foundLeptPlus = false;
    bool foundLeptMinus = false;
    bool foundPhoton = false;
    bool tauEvent = false;

    for( int iPart=0; iPart<ngenPart; ++iPart ) {

      if( genPart_status[iPart]!=1 ) continue;

      if( abs(genPart_pdgId[iPart])==15 ) {
        tauEvent = true;
        break;
      }

      if( (genPart_pdgId[iPart]==+11 || genPart_pdgId[iPart]==+13) && genPart_motherId[iPart]==23 ) {
        leptMinus.SetPtEtaPhiM( genPart_pt[iPart], genPart_eta[iPart], genPart_phi[iPart], genPart_mass[iPart] );
        foundLeptMinus = true;
      }
      if( (genPart_pdgId[iPart]==-11 || genPart_pdgId[iPart]==-13) && genPart_motherId[iPart]==23 ) {
        leptPlus.SetPtEtaPhiM( genPart_pt[iPart], genPart_eta[iPart], genPart_phi[iPart], genPart_mass[iPart] );
        foundLeptPlus = true;
      }
      if( genPart_pdgId[iPart]==22 && genPart_motherId[iPart]==25 ) {
        photon.SetPtEtaPhiM( genPart_pt[iPart], genPart_eta[iPart], genPart_phi[iPart], genPart_mass[iPart] );
        foundPhoton = true;
      }

    } // for genparts

    if( tauEvent ) continue;
    if( !foundLeptPlus || !foundLeptMinus || !foundPhoton ) continue;


    if( photon.Pt() < 40. ) continue;
    float ptMax = TMath::Max( leptPlus.Pt(), leptMinus.Pt() );
    float ptMin = TMath::Min( leptPlus.Pt(), leptMinus.Pt() );
    if( ptMax<25. ) continue;
    if( ptMin<20. ) continue;
    if( fabs( photon.Eta() ) > 2.5 ) continue;
    if( fabs( photon.Eta())>1.44 && fabs( photon.Eta())<1.57 ) continue;
    if( fabs( leptPlus.Eta() ) > 2.4 ) continue;
    if( fabs( leptMinus.Eta() ) > 2.4 ) continue;
    if( photon.DeltaR( leptPlus  ) < 0.4 ) continue;
    if( photon.DeltaR( leptMinus ) < 0.4 ) continue;

    TLorentzVector zBoson = leptPlus + leptMinus;
    if( zBoson.M() < 50. ) continue;

    TLorentzVector boss = zBoson + photon;
    if( boss.M() < 200. ) continue;

    if( photon.Pt()/boss.M()< 40./150. ) continue;

    x->setVal(boss.M());

    data->add(RooArgSet(*x));

  }


  //RooRealVar* bw_mean  = new RooRealVar( "bw_mean", "Breit-Wigner Mean" , mass, 0.2*mass, 1.8*mass );
  //RooRealVar* bw_gamma = new RooRealVar( "bw_gamma", "Breit-Wigner Width", 0.01*mass, 0., 0.3*mass );
  //RooBreitWigner* model = new RooBreitWigner( "bw", "Breit-Wigner", *x, *bw_mean, *bw_gamma);

  // Crystal-Ball
  RooRealVar mean( "mean", "mean", mass, 0.9*mass, 1.1*mass );
  RooRealVar sigma( "sigma", "sigma", 0.015*mass, 0., 0.07*mass );
  RooRealVar alpha1( "alpha1", "alpha1", 1.2, 0., 2.5 );
  RooRealVar n1( "n1", "n1", 3., 0., 5. );
  RooRealVar alpha2( "alpha2", "alpha2", 1.2, 0., 2.5 );
  RooRealVar n2( "n2", "n2", 3., 0., 10. );
  RooDoubleCBShape* model = new RooDoubleCBShape( "cb", "cb", *x, mean, sigma, alpha1, n1, alpha2, n2 );

  model->fitTo( *data );

  int npoints = gr_mean->GetN();
  gr_mean  ->SetPoint( npoints, mass, mean.getVal() );
  gr_sigma ->SetPoint( npoints, mass, sigma.getVal() );
  gr_width ->SetPoint( npoints, mass, sigma.getVal()/mean.getVal() );
  gr_alpha1->SetPoint( npoints, mass, alpha1.getVal() );
  gr_alpha2->SetPoint( npoints, mass, alpha2.getVal() );
  gr_n1    ->SetPoint( npoints, mass, n1.getVal() );
  gr_n2    ->SetPoint( npoints, mass, n2.getVal() );

  gr_mean  ->SetPointError( npoints, 0., mean.getError() );
  gr_sigma ->SetPointError( npoints, 0., sigma.getError() );
  gr_width ->SetPointError( npoints, 0., sigma.getError()/mean.getVal() );
  gr_alpha1->SetPointError( npoints, 0., alpha1.getError() );
  gr_alpha2->SetPointError( npoints, 0., alpha2.getError() );
  gr_n1    ->SetPointError( npoints, 0., n1.getError() );
  gr_n2    ->SetPointError( npoints, 0., n2.getError() );

  //gr_mean ->SetPoint     ( npoints, mass, bw_mean->getVal() );
  //gr_gamma->SetPoint     ( npoints, mass, bw_gamma->getVal() );
  //gr_width->SetPoint     ( npoints, mass, bw_gamma->getVal()/bw_mean->getVal() );
  //gr_mean ->SetPointError( npoints,   0., bw_mean->getError() );
  //gr_gamma->SetPointError( npoints,   0., bw_gamma->getError()/bw_mean->getVal() );
  //gr_width->SetPointError( npoints,   0., bw_gamma->getError()/bw_mean->getVal() );

  RooPlot* plot = x->frame();
  data->plotOn(plot);
  model->plotOn(plot);

  TCanvas* c1 = new TCanvas( "c1", "", 600, 600 );
  c1->cd();

  plot->Draw();
    
  c1->SaveAs( Form("%s/fit_m%.0f_%s.eps", outdir.c_str(), mass, width.c_str()) );
  c1->SaveAs( Form("%s/fit_m%.0f_%s.pdf", outdir.c_str(), mass, width.c_str()) );

  c1->SetLogy();

  c1->SaveAs( Form("%s/fit_m%.0f_%s_log.eps", outdir.c_str(), mass, width.c_str()) );
  c1->SaveAs( Form("%s/fit_m%.0f_%s_log.pdf", outdir.c_str(), mass, width.c_str()) );


  //delete bw_mean;
  //delete bw_gamma;

  delete c1;
  delete data;
  delete model;
  delete plot;
  delete x;

}
void fit_JVBF(int erg_tev=8, float mSample=0){
  float mPOLE=mSample;
  if (mPOLE<=0) mPOLE=125.6;
  float wPOLE=4.15e-3;
  char TREE_NAME[] = "TestTree";

  TString cinput;
  if (mSample>0) cinput = Form("HZZ4lTree_jvbfMELA_H%.0f_%iTeV.root", mSample, erg_tev);
  else cinput = Form("HZZ4lTree_jvbfMELA_HAll_%iTeV.root", erg_tev);

  TFile* foutput;
  if (mSample>0) foutput = new TFile(Form("jvbfMELA_Fits_H%.0f_%iTeV.root", mSample, erg_tev), "recreate");
  else foutput = new TFile(Form("jvbfMELA_fits_wide_%iTeV.root", erg_tev), "recreate");

  TLorentzVector nullFourVector(0, 0, 0, 0);

  float MC_weight_noxsec;

  float pjvbf_VAJHU;
  float pjvbf_VAJHU_first;
  float pjvbf_VAJHU_second;

  float jet1Pt, jet2Pt;
  float jet1Eta, jet2Eta;
  float jet1Phi, jet2Phi;
  float jet1E, jet2E;
  float jet1Pt_Fake, jet2Pt_Fake;
  float jet1Eta_Fake, jet2Eta_Fake;
  float jet1Phi_Fake, jet2Phi_Fake;
  float jet1E_Fake, jet2E_Fake;
  float jet1px, jet1py, jet1pz;
  float jet2px, jet2py, jet2pz;
  float ZZPx, ZZPy, ZZPz, ZZE, dR;
  short NJets30;

  float ZZMass;

  TChain* tree = new TChain(TREE_NAME);
  tree->Add(cinput);
  tree->SetBranchAddress("MC_weight_noxsec", &MC_weight_noxsec);
  tree->SetBranchAddress("ZZMass", &ZZMass);
  tree->SetBranchAddress("pjvbf_VAJHU", &pjvbf_VAJHU);
  tree->SetBranchAddress("pjvbf_VAJHU_first", &pjvbf_VAJHU_first);
  tree->SetBranchAddress("pjvbf_VAJHU_second", &pjvbf_VAJHU_second);
  tree->SetBranchAddress("NJets30", &NJets30);
  tree->SetBranchAddress("jet1Pt", &jet1Pt);
  tree->SetBranchAddress("jet1Eta", &jet1Eta);
  tree->SetBranchAddress("jet1Phi", &jet1Phi);
  tree->SetBranchAddress("jet1E", &jet1E);
  tree->SetBranchAddress("jet2Pt", &jet2Pt);
  tree->SetBranchAddress("jet2Eta", &jet2Eta);
  tree->SetBranchAddress("jet2Phi", &jet2Phi);
  tree->SetBranchAddress("jet2E", &jet2E);
  tree->SetBranchAddress("jet1_Fake_Pt", &jet1Pt_Fake);
  tree->SetBranchAddress("jet1_Fake_Eta", &jet1Eta_Fake);
  tree->SetBranchAddress("jet1_Fake_Phi", &jet1Phi_Fake);
  tree->SetBranchAddress("jet1_Fake_E", &jet1E_Fake);
  tree->SetBranchAddress("jet2_Fake_Pt", &jet2Pt_Fake);
  tree->SetBranchAddress("jet2_Fake_Eta", &jet2Eta_Fake);
  tree->SetBranchAddress("jet2_Fake_Phi", &jet2Phi_Fake);
  tree->SetBranchAddress("jet2_Fake_E", &jet2E_Fake);


  const int nbinsx=6;
  double bins_mzz[nbinsx+1]={70, 140, 190, 240, 340, 520, 20000};
  double sum_w[nbinsx]={ 0 };
  double sum_mzz[nbinsx][2]={ { 0 } };
  const int nbins_eta = 8;
  double bins_eta[nbins_eta+1]={ 0, 0.75, 1.5, 2.25, 3, 4, 5.5, 10.5, 12 };

  TProfile* hProb[nbinsx];
  TH1D* hProb_all;
  TProfile* hEta[nbinsx+1];
  TH1D* hDist[nbinsx+1];
  for (int bin=0; bin<nbinsx+1; bin++){
    if (bin<nbinsx) hProb[bin] = new TProfile(Form("njets1_pjvbf_bin_%i", bin+1), Form("m_{4l}: [%.0f, %.0f] GeV", bins_mzz[bin], bins_mzz[bin+1]), nbins_eta, bins_eta);
    else hProb_all = new TH1D("njets1_pjvbf_all", Form("m_{4l}: [%.0f, %.0f] GeV", bins_mzz[0], bins_mzz[nbinsx]), nbins_eta, bins_eta);
    if (bin<nbinsx) hEta[bin] = new TProfile(Form("njets1_eta_bin_%i", bin+1), Form("m_{4l}: [%.0f, %.0f] GeV", bins_mzz[bin], bins_mzz[bin+1]), nbins_eta, bins_eta);
    else hEta[bin] = new TProfile("njets1_eta_all", Form("m_{4l}: [%.0f, %.0f] GeV", bins_mzz[0], bins_mzz[nbinsx]), nbins_eta, bins_eta);
    if (bin<nbinsx) hDist[bin] = new TH1D(Form("njets1_dist_bin_%i", bin+1), Form("m_{4l}: [%.0f, %.0f] GeV", bins_mzz[bin], bins_mzz[bin+1]), nbins_eta, bins_eta);
    else hDist[bin] = new TH1D("njets1_dist_all", Form("m_{4l}: [%.0f, %.0f] GeV", bins_mzz[0], bins_mzz[nbinsx]), nbins_eta, bins_eta);
    if (bin<nbinsx) hProb[bin]->Sumw2();
    else hProb_all->Sumw2();
    hEta[bin]->Sumw2();
    hDist[bin]->Sumw2();
  }

  int nEntries = tree->GetEntries();
  cout << nEntries << endl;
  for (int ev = 0; ev < nEntries; ev++){
    tree->GetEntry(ev);

    int massbin=-1;
    for (int bin=0; bin<nbinsx; bin++){
      if (ZZMass>=bins_mzz[bin] && ZZMass<bins_mzz[bin+1]){
        massbin=bin;
      }
    }
    if (NJets30==1){
      hProb[massbin]->Fill(fabs(jet2Eta_Fake), pjvbf_VAJHU_second, MC_weight_noxsec);
      hEta[massbin]->Fill(fabs(jet2Eta_Fake), fabs(jet2Eta_Fake), MC_weight_noxsec);
      hDist[massbin]->Fill(fabs(jet2Eta_Fake), MC_weight_noxsec);

      hEta[nbinsx]->Fill(fabs(jet2Eta_Fake), fabs(jet2Eta_Fake), MC_weight_noxsec);
      hDist[nbinsx]->Fill(fabs(jet2Eta_Fake), MC_weight_noxsec);
    }
  }

  for (int bin=0; bin<nbinsx; bin++){
    hProb[bin]->Scale(1./hProb[bin]->Integral("width"));
  }
  for (int bin=0; bin<nbinsx+1; bin++){
    for (int bineta=1; bineta<=nbins_eta; bineta++){
      double bincontent = hDist[bin]->GetBinContent(bineta);
      double binerror = hDist[bin]->GetBinError(bineta);
      double binwidth = hDist[bin]->GetXaxis()->GetBinWidth(bineta);

      bincontent /= binwidth;
      binerror /= binwidth;

      hDist[bin]->SetBinContent(bineta, bincontent);
      hDist[bin]->SetBinError(bineta, binerror);
    }
    hDist[bin]->Scale(1./hDist[bin]->Integral("width"));
  }
  for (int bineta=1; bineta<=nbins_eta; bineta++){
    double sum_invwsq=0;
    double sum_prob_invwsq=0;
    for (int bin=0; bin<nbinsx; bin++){
      double bincontent = hProb[bin]->GetBinContent(bineta);
      double binerror = hProb[bin]->GetBinError(bineta);

      double invwsq = 0, prob_invwsq = 0;
      if (binerror!=0){
        invwsq = 1./pow(binerror, 2);
        prob_invwsq = bincontent*invwsq;
      }
      sum_invwsq += invwsq;
      sum_prob_invwsq += prob_invwsq;
    }

    if (sum_invwsq>0){
      sum_prob_invwsq /= sum_invwsq;
      sum_invwsq = 1./sqrt(sum_invwsq);
    }
    hProb_all->SetBinContent(bineta, sum_prob_invwsq);
    hProb_all->SetBinError(bineta, sum_invwsq);
  }
  hProb_all->Scale(1./hProb_all->Integral("width"));


  double eta_center_all[nbins_eta];
  double prob_center_all[nbins_eta];
  double eta_center_all_err[nbins_eta];
  double prob_center_all_err[nbins_eta];
  int nNonEmpty_all = 0;
  for (int bineta=1; bineta<=nbins_eta; bineta++){
    if (hProb_all->GetBinError(bineta)>0){
      eta_center_all[nNonEmpty_all] = hEta[nbinsx]->GetBinContent(bineta);
      eta_center_all_err[nNonEmpty_all] = hEta[nbinsx]->GetBinError(bineta);
      prob_center_all[nNonEmpty_all] = hProb_all->GetBinContent(bineta);
      prob_center_all_err[nNonEmpty_all] = hProb_all->GetBinError(bineta);
      cout << nNonEmpty_all << '\t' << prob_center_all[nNonEmpty_all] << '\t' << prob_center_all_err[nNonEmpty_all] << endl;
      nNonEmpty_all++;
    }
  }

  TGraphErrors* tg_all = new TGraphErrors(nNonEmpty_all, eta_center_all, prob_center_all, eta_center_all_err, prob_center_all_err);
  tg_all->SetNameTitle("tg_njets1_pjvbf_all", Form("m_{4l}: [%.0f, %.0f] GeV", bins_mzz[0], bins_mzz[nbinsx]));
  tg_all->GetXaxis()->SetTitle("#eta");
  tg_all->GetYaxis()->SetTitle("<P_{VBF}>");
  
  TF1* fit_tg_all = new TF1("fit_tg_njets1_pjvbf_all", "gaus*(1+gaus(3))", bins_eta[0], bins_eta[nbins_eta]);
  const int npars = 6;
  double mypars[npars]={ 0.155, 5.193, 1.46, 0.362, 3.524, 0.715 };
  fit_tg_all->SetParameters(mypars);
  fit_tg_all->SetParLimits(0, 0, 1);
  fit_tg_all->SetParLimits(3, 0, 1);
  fit_tg_all->SetParLimits(1, 0, 20);
  fit_tg_all->SetParLimits(4, 0, 20);
  fit_tg_all->SetParLimits(2, 0, 20);
  fit_tg_all->SetParLimits(5, 0, 20);
  tg_all->Fit(fit_tg_all);

  double* par_postfit = fit_tg_all->GetParameters();
  double* parerr_postfit = fit_tg_all->GetParErrors();
  double parIndex[npars];
  double parIndexErr[npars]={ 0 };
  for (int ip=0; ip<npars; ip++) parIndex[ip] = (double)ip;

  double integral = 0.5*par_postfit[0]*(1.+TMath::Erf(par_postfit[1]/par_postfit[2]/TMath::Sqrt(2)));
  double integral2 = 1./(2.*TMath::Sqrt(2.*TMath::Pi()*(TMath::Power(par_postfit[2], 2)+TMath::Power(par_postfit[5], 2))));
  integral2 *= par_postfit[0]*par_postfit[3]*TMath::Exp(-0.5*pow(par_postfit[1]-par_postfit[4], 2)/(TMath::Power(par_postfit[2], 2)+TMath::Power(par_postfit[5], 2)))*
    (1.+TMath::Erf((TMath::Power(par_postfit[2], 2)*par_postfit[4]+TMath::Power(par_postfit[5], 2)*par_postfit[1]) / (par_postfit[2]*par_postfit[5]*TMath::Sqrt(2.*(TMath::Power(par_postfit[2], 2)+TMath::Power(par_postfit[5], 2))))));
  integral += integral2;

  cout << integral << endl;
  par_postfit[0] /= integral;
  parerr_postfit[0] /= integral;

  TGraphErrors* tg_pars = new TGraphErrors(npars, parIndex, par_postfit, parIndexErr, parerr_postfit);
  tg_pars->SetNameTitle("njets1_pjvbf_pars", "gaus*(1+gaus(3))");
  tg_pars->GetXaxis()->SetTitle("Parameter index");
  tg_pars->GetYaxis()->SetTitle("Parameter");
  foutput->WriteTObject(tg_pars);
  delete tg_pars;

  foutput->WriteTObject(tg_all);
  delete tg_all;

  for (int bin=0; bin<nbinsx+1; bin++){
    if (bin<nbinsx) foutput->WriteTObject(hProb[bin]);
    else foutput->WriteTObject(hProb_all);
    foutput->WriteTObject(hEta[bin]);
    foutput->WriteTObject(hDist[bin]);
    delete hDist[bin];
    delete hEta[bin];
    if (bin<nbinsx) delete hProb[bin];
    else delete hProb_all;
  }
  delete tree;

  foutput->Close();
}
void test_JVBF(int erg_tev=8, float mSample=0, bool isggH=false){
  float mPOLE=mSample;
  if (mPOLE<=0) mPOLE=125.6;
  float wPOLE=4.15e-3;
  char TREE_NAME[] = "SelectedTree";

  //	TVar::VerbosityLevel verbosity = TVar::INFO;

  Mela mela(erg_tev, mPOLE);

  TFile* foutput;
  if (!isggH){
    if (mSample>0) foutput = new TFile(Form("HZZ4lTree_jvbfMELA_H%.0f_%iTeV.root", mSample, erg_tev), "recreate");
    else foutput = new TFile(Form("HZZ4lTree_jvbfMELA_HAll_%iTeV.root", erg_tev), "recreate");
  }
  else{
    if (mSample>0) foutput = new TFile(Form("HZZ4lTree_jvbfMELA_ggH%.0f_%iTeV.root", mSample, erg_tev), "recreate");
    else foutput = new TFile(Form("HZZ4lTree_jvbfMELA_ggHAll_%iTeV.root", erg_tev), "recreate");
  }
  TLorentzVector nullFourVector(0, 0, 0, 0);

  float MC_weight_noxsec;

  float pjvbf_VAJHU;
  float pjvbf_VAJHU_first;
  float pjvbf_VAJHU_second;
  float phj_VAJHU_first;
  float phj_VAJHU_second;
  float pAux_vbf;
  float pAux_vbf_first;
  float pAux_vbf_second;

  float jet1Pt, jet2Pt;
  float jet1Eta, jet2Eta;
  float jet1Phi, jet2Phi;
  float jet1E, jet2E;
  float jet1Pt_Fake, jet2Pt_Fake;
  float jet1Eta_Fake, jet2Eta_Fake;
  float jet1Phi_Fake, jet2Phi_Fake;
  float jet1E_Fake, jet2E_Fake;
  float jet1px, jet1py, jet1pz;
  float jet2px, jet2py, jet2pz;
  float ZZPx, ZZPy, ZZPz, ZZE, dR;
  short NJets30;
  std::vector<double> * JetPt=0;
  std::vector<double> * JetEta=0;
  std::vector<double> * JetPhi=0;
  std::vector<double> * JetMass=0;
  std::vector<double> myJetPt;
  std::vector<double> myJetCosTheta;
  std::vector<double> myJetEta;
  std::vector<double> myJetPhi;
  std::vector<double> myJetMass;
  TBranch* bJetPt=0;
  TBranch* bJetEta=0;
  TBranch* bJetPhi=0;
  TBranch* bJetMass=0;

  float ZZMass, ZZPt, ZZPhi, ZZEta;

  int GenLep1Id, GenLep2Id, GenLep3Id, GenLep4Id;

  TChain* tree = new TChain(TREE_NAME);
  char* user_folder[3]={ "4mu", "4e", "2mu2e" };
  TString cinput_main = "/scratch0/hep/ianderso/CJLST/140519/PRODFSR";
  if (erg_tev==8) cinput_main.Append("_8TeV");

//  TString cinput_main = "/afs/cern.ch/work/u/usarica/HZZ4l-125p6-FullAnalysis/LHC_";
//  cinput_main.Append(Form("%iTeV", erg_tev));

  for (int ff=0; ff<3; ff++){
    if (!isggH){
      if (mSample>0) tree->Add(Form("%s/%s/HZZ4lTree_VBFH%.0f.root", cinput_main.Data(), user_folder[ff], mSample));
      else tree->Add(Form("%s/%s/HZZ4lTree_VBFH*.root", cinput_main.Data(), user_folder[ff]));
    }
    else{
      if (mSample>0) tree->Add(Form("%s/%s/HZZ4lTree_minloH%.0f.root", cinput_main.Data(), user_folder[ff], mSample));
      else tree->Add(Form("%s/%s/HZZ4lTree_minloH*.root", cinput_main.Data(), user_folder[ff]));
    }
  }
  tree->SetBranchAddress("MC_weight_noxsec", &MC_weight_noxsec);
  tree->SetBranchAddress("NJets30", &NJets30);
  tree->SetBranchAddress("JetPt", &JetPt, &bJetPt);
  tree->SetBranchAddress("JetEta", &JetEta, &bJetEta);
  tree->SetBranchAddress("JetPhi", &JetPhi, &bJetPhi);
  tree->SetBranchAddress("JetMass", &JetMass, &bJetMass);
  tree->SetBranchAddress("ZZMass", &ZZMass);
  tree->SetBranchAddress("ZZPt", &ZZPt);
  tree->SetBranchAddress("ZZEta", &ZZEta);
  tree->SetBranchAddress("ZZPhi", &ZZPhi);

  TTree* newtree = new TTree("TestTree", "");
  newtree->Branch("MC_weight_noxsec", &MC_weight_noxsec);
  newtree->Branch("ZZMass", &ZZMass);
  newtree->Branch("pAux_vbf", &pAux_vbf);
  newtree->Branch("pAux_vbf_first", &pAux_vbf_first);
  newtree->Branch("pAux_vbf_second", &pAux_vbf_second);
  newtree->Branch("pjvbf_VAJHU", &pjvbf_VAJHU);
  newtree->Branch("pjvbf_VAJHU_first", &pjvbf_VAJHU_first);
  newtree->Branch("pjvbf_VAJHU_second", &pjvbf_VAJHU_second);
  newtree->Branch("phj_VAJHU_first", &phj_VAJHU_first);
  newtree->Branch("phj_VAJHU_second", &phj_VAJHU_second);
  newtree->Branch("NJets30", &NJets30);
  newtree->Branch("jet1Pt", &jet1Pt);
  newtree->Branch("jet1Eta", &jet1Eta);
  newtree->Branch("jet1Phi", &jet1Phi);
  newtree->Branch("jet1E", &jet1E);
  newtree->Branch("jet2Pt", &jet2Pt);
  newtree->Branch("jet2Eta", &jet2Eta);
  newtree->Branch("jet2Phi", &jet2Phi);
  newtree->Branch("jet2E", &jet2E);
  newtree->Branch("jet1_Fake_Pt", &jet1Pt_Fake);
  newtree->Branch("jet1_Fake_Eta", &jet1Eta_Fake);
  newtree->Branch("jet1_Fake_Phi", &jet1Phi_Fake);
  newtree->Branch("jet1_Fake_E", &jet1E_Fake);
  newtree->Branch("jet2_Fake_Pt", &jet2Pt_Fake);
  newtree->Branch("jet2_Fake_Eta", &jet2Eta_Fake);
  newtree->Branch("jet2_Fake_Phi", &jet2Phi_Fake);
  newtree->Branch("jet2_Fake_E", &jet2E_Fake);
  newtree->Branch("JetPt", &myJetPt);
//  newtree->Branch("JetCosTheta", &myJetCosTheta);
  newtree->Branch("JetPhi", &myJetPhi);
  newtree->Branch("JetMass", &myJetMass);


  int nEntries = tree->GetEntries();
  double selfDHggcoupl[SIZE_HGG][2] ={ { 0 } };
  double selfDHvvcoupl[SIZE_HVV_VBF][2] ={ { 0 } };
  double selfDHwwcoupl[SIZE_HWW_VBF][2] ={ { 0 } };
  double ggvvcoupl[2]={ 0, 0 };
  mela.setProcess(TVar::SelfDefine_spin0, TVar::JHUGen, TVar::ZZGG);
  int recorded=0;
  for (int ev = 0; ev < nEntries; ev++){
    pjvbf_VAJHU=-1;
    pjvbf_VAJHU_first=-1;
    pjvbf_VAJHU_second=-1;
    jet1Pt=-1;
    jet2Pt=-1;
    jet1Eta=0;
    jet2Eta=0;

    tree->GetEntry(ev);
    GenLep1Id=11;
    GenLep2Id=-11;
    GenLep3Id=11;
    GenLep4Id=-11;

    myJetPt.clear();
    myJetEta.clear();
    myJetPhi.clear();
    myJetMass.clear();
    myJetCosTheta.clear();

    TLorentzVector jet1(0, 0, 1e-3, 1e-3), jet2(0, 0, 1e-3, 1e-3), higgs(0, 0, 0, 0);
    TLorentzVector p4[3], jets[2];
    higgs.SetPtEtaPhiM(ZZPt, ZZEta, ZZPhi, ZZMass);
    for (int i = 0; i < NJets30; i++){
      myJetPt.push_back(JetPt->at(i));
      myJetEta.push_back(JetEta->at(i));
      myJetPhi.push_back(JetPhi->at(i));
      myJetMass.push_back(JetMass->at(i));
      myJetCosTheta.push_back(eta_to_costheta(JetEta->at(i)));
    }

    int filled = 0;
    if (myJetPt.size()>=1){

      jets[0].SetPxPyPzE(0, 0, 0, 1);
      jets[1].SetPxPyPzE(0, 0, 0, 1);
      for (int i = 0; i < myJetPt.size(); i++){
        jets[filled].SetPtEtaPhiM(myJetPt[i], myJetEta[i], myJetPhi[i], myJetMass[i]);

        if (filled==0){
          double jetE = jets[filled].Energy();
          double jetP = jets[filled].P();
          double ratio = (jetP>0 ? jetE/jetP : 1);
          ratio = 1.;
          jet1.SetPxPyPzE(jets[filled].Px()*ratio, jets[filled].Py()*ratio, jets[filled].Pz()*ratio, jetE);
          filled++;
          jet1Pt = jet1.Pt();
          jet1Eta = jet1.Eta();
          jet1Phi = jet1.Phi();
          jet1E = jet1.E();
          jet2.SetXYZT(0, 0, 0, 0);
        }
        else if(filled==1){
          double jetE = jets[filled].Energy();
          double jetP = jets[filled].P();
          double ratio = (jetP>0 ? jetE/jetP : 1);
          ratio = 1.;
          jet2.SetXYZT(jets[filled].Px()*ratio, jets[filled].Py()*ratio, jets[filled].Pz()*ratio, jetE);
          filled++;
          jet2Pt = jet2.Pt();
          jet2Eta = jet2.Eta();
          jet2Phi = jet2.Phi();
          jet2E = jet2.E();
        }
        else continue;

/*
        if (filled == 0){
          if (jets[filled].Pt()>jet1.Pt()){
            jet1.SetPxPyPzE(jets[filled].Px(), jets[filled].Py(), jets[filled].Pz(), jetE);
            jet1Pt = jet1.Pt();
          }
          if (i == myJetPt.size() - 1){
            filled++;
            i = 0;
          }
        }
        else{
          if (jets[filled].Pt()<jet1.Pt() && jets[filled].Pt()>jet2.Pt()){
            jet2.SetPxPyPzE(jets[filled].Px(), jets[filled].Py(), jets[filled].Pz(), jetE);
            jet2Pt = jet2.Pt();
          }
          if (i == myJetPt.size() - 1){
            filled++;
          }
        }
        if (filled == 2) break;
*/
      }
//cos(atan(exp(-jet2Eta))*2)

      if (filled == 2){
        mela.setProcess(TVar::HSMHiggs, TVar::JHUGen, TVar::JJVBF);
        mela.computeProdP(jet1, 2, jet2, 2, higgs, 25, nullFourVector, 0, pjvbf_VAJHU);
        mela.get_PAux(pAux_vbf);

        TLorentzVector pTotal;
        pTotal.SetXYZT(0, 0, 0, 0);
        mela.setProcess(TVar::HSMHiggs, TVar::JHUGen, TVar::JJVBF);
        mela.computeProdP(jet1, 2, pTotal, 2, higgs, 25, nullFourVector, 0, pjvbf_VAJHU_first);
        mela.get_PAux(pAux_vbf_first);
        mela.setProcess(TVar::HSMHiggs, TVar::JHUGen, TVar::JH);
        mela.computeProdP(jet1, 2, pTotal, 2, higgs, 25, nullFourVector, 0, phj_VAJHU_first);
        mela::computeFakeJet(jet1, higgs, pTotal);
        jet2Pt_Fake = pTotal.Pt();
        jet2Eta_Fake = pTotal.Eta();
        jet2Phi_Fake = pTotal.Phi();
        jet2E_Fake = pTotal.E();

        pTotal.SetXYZT(0, 0, 0, 0);
        mela.setProcess(TVar::HSMHiggs, TVar::JHUGen, TVar::JJVBF);
        mela.computeProdP(pTotal, 2, jet2, 2, higgs, 25, nullFourVector, 0, pjvbf_VAJHU_second);
        mela.get_PAux(pAux_vbf_second);
        mela.setProcess(TVar::HSMHiggs, TVar::JHUGen, TVar::JH);
        mela.computeProdP(pTotal, 2, jet2, 2, higgs, 25, nullFourVector, 0, phj_VAJHU_second);
        mela::computeFakeJet(jet2, higgs, pTotal);
        jet1Pt_Fake = pTotal.Pt();
        jet1Eta_Fake = pTotal.Eta();
        jet1Phi_Fake = pTotal.Phi();
        jet1E_Fake = pTotal.E();

        newtree->Fill();
      }
      else if (filled == 1){
/*
        TLorentzVector pTotal = higgs+jet1;
        pTotal.SetVect(-pTotal.Vect());
        pTotal.SetE(pTotal.P());
        jet2 = pTotal;

        jet2Pt = jet2.Pt();
        jet2Eta = jet2.Eta();
        jet2Phi = jet2.Phi();
        jet2E = jet2.E();


        jet1Pt_Fake = jet1.Pt();
        jet1Eta_Fake = jet1.Eta();
        jet1Phi_Fake = jet1.Phi();
        jet1E_Fake = jet1.E();
        jet2Pt_Fake = jet2.Pt();
        jet2Eta_Fake = jet2.Eta();
        jet2Phi_Fake = jet2.Phi();
        jet2E_Fake = jet2.E();

        mela.setProcess(TVar::HSMHiggs, TVar::JHUGen, TVar::JJVBF);
        mela.computeProdP(jet1, 2, jet2, 2, higgs, 25, nullFourVector, 0, pjvbf_VAJHU);
*/
//
        jet2.SetXYZT(0,0,0,0);
        mela.setProcess(TVar::HSMHiggs, TVar::JHUGen, TVar::JJVBF);
        mela.computeProdP(jet1, 2, jet2, 2, higgs, 25, nullFourVector, 0, pjvbf_VAJHU);
        mela.get_PAux(pAux_vbf);
        mela.setProcess(TVar::HSMHiggs, TVar::JHUGen, TVar::JH);
        mela.computeProdP(jet1, 2, jet2, 2, higgs, 25, nullFourVector, 0, phj_VAJHU_first);
        mela::computeFakeJet(jet1, higgs, jet2);
/*
        cout << "TEST:"
          << " Higgs Pz: " <<  higgs.Pz()
          << " Higgs P: " <<  higgs.P()
          << " Higgs E: " <<  higgs.T()
          << " Jet 1 Pz: " <<  jet1.Pz()
          << " Jet 1 P: " <<  jet1.P()
          << " Jet 1 E: " <<  jet1.T()
          << " Jet 2 Pz: " <<  jet2.Pz()
          << " Jet 2 P: " <<  jet2.P()
          << " Jet 2 E: " <<  jet2.T() << '\n' << endl;
*/

        jet2Pt = jet2.Pt();
        jet2Eta = jet2.Eta();
        jet2Phi = jet2.Phi();
        jet2E = jet2.E();

        jet1Pt_Fake = jet1.Pt();
        jet1Eta_Fake = jet1.Eta();
        jet1Phi_Fake = jet1.Phi();
        jet1E_Fake = jet1.E();
        jet2Pt_Fake = jet2.Pt();
        jet2Eta_Fake = jet2.Eta();
        jet2Phi_Fake = jet2.Phi();
        jet2E_Fake = jet2.E();
//
        pjvbf_VAJHU_first = pjvbf_VAJHU;
        pjvbf_VAJHU_second = pjvbf_VAJHU;
        pAux_vbf_first = pAux_vbf;
        pAux_vbf_second = pAux_vbf;
        phj_VAJHU_second = phj_VAJHU_first;

        newtree->Fill();
      }
    }
  }


  foutput->WriteTObject(newtree);
  delete newtree;
  foutput->Close();
  delete tree;
}
Exemple #15
0
int main(int argc, char** argv){//main  

  if (argc < 6) {
    std::cout << " Usage: " 
	      << argv[0] << " <nEvts to process (0=all)>"
	      << " <path to input files>"
	      << " <name of input reco file>"
	      << " <full path to output file>"
	      << " <number of si layers to consider: 1,2 or 3>" 
	      << " <optional: debug (default=0)>"
	      << std::endl;
    return 1;
  }

  //////////////////////////////////////////////////////////
  //// Hardcoded config ////////////////////////////////////
  //////////////////////////////////////////////////////////
  //for HGCAL, true means only 12 FHCAL layers considered (24 are simulated)
  bool concept = true;

  bool selectEarlyDecays = false;

  double minX=-1700,maxX=1700;
  double minY=-1700,maxY=1700;
  double minZ=3170,maxZ=5070;

  unsigned nX=(maxX-minX)/10,nY=(maxY-minY)/10;
  unsigned nZ=maxZ-minZ;

  //// End Hardcoded config ////////////////////////////////////
  //////////////////////////////////////////////////////////

  const unsigned pNevts = atoi(argv[1]);
  std::string filePath = argv[2];
  std::string recoFileName = argv[3];

  std::string outPath = argv[4];
  unsigned nSiLayers = 2;
  nSiLayers = atoi(argv[5]);

  unsigned debug = 0;
  if (argc >7) debug = atoi(argv[7]);

  bool isEM = false;

  if (selectEarlyDecays && isEM) {
    selectEarlyDecays = false;
  }

  std::cout << " -- Input parameters: " << std::endl
	    << " -- Input file path: " << filePath << std::endl
	    << " -- Output file path: " << outPath << std::endl
	    << " -- Requiring " << nSiLayers << " si layers." << std::endl
	    << " -- Processing ";
  if (pNevts == 0) std::cout << "all events." << std::endl;
  else std::cout << pNevts << " events." << std::endl;

  TRandom3 lRndm(1);
  std::cout << " -- Random number seed: " << lRndm.GetSeed() << std::endl;

  /////////////////////////////////////////////////////////////
  //input
  /////////////////////////////////////////////////////////////

  TFile *recFile = new TFile(); 
  TChain *lRecTree = new TChain("RecoTree");
  if(recoFileName.find("*")!=recoFileName.npos){ 
     ofstream myscript;
     myscript.open("eosls.sh");
     myscript<<"#!/bin/bash" << std::endl;
     myscript<<"/afs/cern.ch/project/eos/installation/0.3.15/bin/eos.select ls " << filePath << std::endl; 
     myscript.close();
     FILE *script = popen("bash eosls.sh", "r");
     char eoslsName[100];
     int nF =0;
     while(fgets(eoslsName, 100, script)) {
        std::ostringstream input;
        std::string temp = std::string(eoslsName).substr(0,strlen(eoslsName)-1);
        if(temp.find("HG")!=temp.npos)continue;
        input << filePath << temp;
        lRecTree->AddFile(input.str().c_str());
        if(nF==0)recFile=TFile::Open(input.str().c_str());
        nF+=1;
     }
     pclose(script);  
     system("rm ./eosls.sh");
   }
   else {
     std::ostringstream input;
     input << filePath << recoFileName;
     lRecTree->AddFile(input.str().c_str());
     recFile=TFile::Open(input.str().c_str());
   }
   if (!recFile) {
     std::cout << " -- Error, input file cannot be opened. Exiting..." << std::endl;
     return 1;
   }

  /////////////////////////////////////////////////////////////
  //Info
  /////////////////////////////////////////////////////////////

  HGCSSInfo * info=(HGCSSInfo*)recFile->Get("Info");
  const double cellSize = info->cellSize();
  const unsigned versionNumber = info->version();
  const unsigned model = info->model();
  
  //models 0,1 or 3.
  bool isCaliceHcal = versionNumber==23;//inFilePath.find("version23")!=inFilePath.npos || inFilePath.find("version_23")!=inFilePath.npos;


  std::cout << " -- Version number is : " << versionNumber 
	    << ", model = " << model
	    << ", cellSize = " << cellSize
	    << std::endl;


  //initialise detector
  HGCSSDetector & myDetector = theDetector();

  myDetector.buildDetector(versionNumber,concept,isCaliceHcal);

  //initialise calibration class
  HGCSSDigitisation myDigitiser;
  myDigitiser.setRandomSeed(lRndm.GetSeed());

  const unsigned nLayers = myDetector.nLayers();
  const unsigned nSections = myDetector.nSections();

  std::cout << " -- N layers = " << nLayers << std::endl
	    << " -- N sections = " << nSections << std::endl;

  ofstream EnDensity;
  EnDensity.open("../test/EnergyDensity.dat");

  TFile *outputFile = TFile::Open(outPath.c_str(),"RECREATE");
  
  if (!outputFile) {
    std::cout << " -- Error, output file " << outPath << " cannot be opened. Please create output directory. Exiting..." << std::endl;
    return 1;
  }
  else {
    std::cout << " -- output file " << outputFile->GetName() << " successfully opened." << std::endl;
  }
  
  
  std::cout << " -- 2-D histograms: " << std::endl
	    << " -- X: " << nX << " " << minX << " " << maxX << std::endl
	    << " -- Y: " << nY << " " << minY << " " << maxY << std::endl
	    << " -- Z: " << nZ << " " << minZ << " " << maxZ << std::endl
    ;
  outputFile->cd();

  TH1F *p_nRecHits = new TH1F("p_nRecHits","n(RecHits)",
			      1000,0,500000);
  p_nRecHits->StatOverflows();

  TProfile *p_EvsLayer = new TProfile("p_EvsLayer","Average E vs Layer",30,1,30);

  TProfile *p_AveE[nLayers];
  std::ostringstream p_AveE_Name;
  for(unsigned iL(0); iL<nLayers; iL++){
     p_AveE_Name.str("");
     p_AveE_Name << "p_AveE_layer" <<iL+1;
     p_AveE[iL] = new TProfile(p_AveE_Name.str().c_str(),"Average Energy vs eta",40,1.5,3.5);
  }

  TH2F *p_Occupancy[nLayers];
  for(unsigned iL(0); iL<nLayers; iL++){
     p_AveE_Name.str("");
     p_AveE_Name << "p_Occupancy_Layer" <<iL+1;
     p_Occupancy[iL] = new TH2F(p_AveE_Name.str().c_str(),"RecoHits Occupancy",340,-170,170,340,-170,170);
 }

  std::vector<HGCSSRecoHit> * rechitvec = 0;
  
  lRecTree->SetBranchAddress("HGCSSRecoHitVec",&rechitvec);

  const unsigned nEvts = ((pNevts > lRecTree->GetEntries() || pNevts==0) ? static_cast<unsigned>(lRecTree->GetEntries()) : pNevts) ;
  
  std::cout << "- Processing = " << nEvts  << " events out of " << lRecTree->GetEntries() << std::endl;
  
  //Initialise histos
  //necessary to have overflows ?
  gStyle->SetOptStat(0);

  double Z_layer[nLayers];
  for(unsigned iL(0);iL<nLayers;iL++){
    Z_layer[iL]=0;
  }
  
  double CellNumber[nLayers][40];
  for(unsigned iL(0);iL<nLayers;iL++){
     for(unsigned iEta(0);iEta<40;iEta++){
        CellNumber[iL][iEta] =0;
      }
  }

  std::map<unsigned,bool> channelAlive;

  for (unsigned ievt(0); ievt<nEvts; ++ievt){//loop on entries
    if (debug) std::cout << "... Processing entry: " << ievt << std::endl;
    else if (ievt%50 == 0) std::cout << "... Processing entry: " << ievt << std::endl;
    
    lRecTree->GetEntry(ievt);

    double EvsLayer[nLayers][40];
    double EtotRec[nLayers];
    for(unsigned iL(0);iL<nLayers;iL++){
       EtotRec[iL]=0;
       for(unsigned iEta(0);iEta<40;iEta++){
           EvsLayer[iL][iEta] =0;
       }
    } 
  
    for (unsigned iH(0); iH<(*rechitvec).size(); ++iH){//loop on rechits
      HGCSSRecoHit lHit = (*rechitvec)[iH];
      
      double energy = lHit.energy();//in MIP already...
      unsigned layer = lHit.layer();
      int x = lHit.get_x()/10;
      int y = lHit.get_y()/10;
      double eta = lHit.eta();
      if (layer >= nLayers) {
	//std::cout << " WARNING! RecoHits with layer " << layer << " outside of detector's definition range ! Please fix the digitiser or the detector definition used here. Ignoring..." << std::endl;
	continue;
      }

      p_Occupancy[layer]->Fill(x,y);

      if(ievt==0){
         if(Z_layer[layer] ==0)Z_layer[layer]=lHit.get_z()/10.0;} 
  
      for(unsigned iEta(0);iEta<40;iEta++){
         if(eta>1.5+iEta*0.05 && eta<1.5+(iEta+1)*0.05)EvsLayer[layer][iEta]+=energy;
      }

      if(eta>1.5 && eta<3.5)EtotRec[layer] += energy;
      if (debug>1) std::cout << "-hit" << iH << "-" << layer << " " << energy << " " << EtotRec[layer];
    }//loop on rechits
    
    p_nRecHits->Fill((*rechitvec).size());
    for(unsigned iL(0); iL<nLayers; iL++){
       p_EvsLayer->Fill(iL+1, EtotRec[iL]);
    }

    if(ievt==0){
      for(unsigned iL(0);iL<nLayers;iL++){
         for(int iX(-170); iX < 170; iX++){
            for(int iY(-170);iY < 170; iY++){
              double radius = sqrt(iX*iX + iY*iY);
              if(radius > 170 || radius < 15)continue;
              double R = sqrt(radius*radius + Z_layer[iL]*Z_layer[iL]);
              double theta = acos(Z_layer[iL]/R);
              double eta = -log(tan(theta/2.));
              for(unsigned iEta(0); iEta < 40; iEta++){
                if(eta>1.5+iEta*0.05 && eta<1.5+(iEta+1)*0.05)CellNumber[iL][iEta]+=1;
              }
             }
          }
       }
     }

    for(unsigned iEta(0);iEta<40;iEta++){
       for(unsigned iL(0);iL<nLayers;iL++){
          p_AveE[iL]->Fill(1.5+iEta*0.05,EvsLayer[iL][iEta]/CellNumber[iL][iEta]);
       }
    }
    
  }//loop on entries

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

  // Fit the Energy Density
  EnDensity << "f(x) = exp(p0+p1*x)" << std::endl;
  EnDensity << "layer  p0  p1" << std::endl;
  for(unsigned iL(0);iL<nLayers;iL++){
       TF1 *expofit = new TF1("density","expo",1.5,3.0); 
       p_AveE[iL]->Fit("density","R");
       double p0 = expofit->GetParameter(0);
       double p1 = expofit->GetParameter(1);
       EnDensity << iL << " " << p0 << " " << p1 << std::endl;  
  }
  EnDensity.close();
 
  return 0;


}//main
int process(TChain *trigOnlyChain, MAPJson *jsonMap, MAPTrigOnly mapTo, TString nameChain, TString file, int iFile, int nEntries,
            TString dirIn, TString dirOut, TString usr_hlt, int iJson, 
	    bool GetTrigOnly, bool debug) {

  // TrigOnly MAP //                                                                                          
  MAPTrigOnly::iterator iterMapTo;
  pair<int,int> runevtTo;
  int iEntryTo=-1;

  // OUTPUT FILE //
  if(debug) cout << "--- define output file : " ;
  ostringstream ossi("");
  ossi << iFile ;
  //                                                                                                                                 
  TFile *outfile = new TFile(dirIn+"spikes_"+ossi.str()+".root","RECREATE");
  //ofstream outcheckdata(dirIn+"logcheckdata_"+ossi.str()+".txt",ios::out);
  ofstream outlog(dirOut+"/logs/log_"+ossi.str()+".txt",ios::out);
  ofstream outcheckL1(dirOut+"/checkL1/checkL1_"+ossi.str()+".txt",ios::out);

  //outlog << "TRY TRY TRY" << endl;
  //outcheckL1 << "TRY TRY TRY" << endl;
  //outcheckdata << "TRY TRY TRY" << endl;

  if(debug) cout << "spikes_"+ossi.str()+".root" << endl;
  ossi.str("");

  // INPUT TREE //                                                                                                                   
  if(debug) cout << "--- add data trees to myChain" << endl;
  TChain * myChain = new TChain(nameChain);
  myChain->Add(file);

  // VARIABLES //                                                                                      
  int nEvent, nRun, nLumi ; // data                                                      
  int nEvent_To, nRun_To, nLumi_To; // trigOnly
  // Vertices //
  int vtx_N;
  double _vtx_x[200], _vtx_y[200], _vtx_z[200];
  double _vtx_normalizedChi2[200], _vtx_ndof[200], _vtx_nTracks[200], _vtx_d0[200];

  // Trigger Paths //                                                                           
  int trig_hltInfo[250];
  //int _trig_isEleHLTpath;                                                                                    
  int trig_HLT_path[4]; // unbias, EG5, EG8, EG12
  char trig_fired_names[5000];
  vector<string> m_HLT_pathsV;
  vector<string> m_HLT_triggered;
  vector<int> m_HLT_pathsV_check;

  // Spikes
  int spike_N,spike_TTieta[5000], spike_TTiphi[5000], spike_Rieta[5000], spike_Riphi[5000], spike_severityLevel[5000], 
    spike_outOfTime[5000], spike_TT_sFGVB[5000], spike_TT_adc[5000], spike_TT_sFGVB_E[5000][5], spike_TT_adc_E[5000][5],
    spike_TT_t[5000], spike_TT_tE[5000];
  double  spike_Et[5000], spike_eta[5000], spike_phi[5000], spike_theta[5000];
  int spike_RCTL1iso[5000], spike_RCTL1noniso[5000], spike_RCTL1iso_To[5000], spike_RCTL1noniso_To[5000], 
    spike_RCTL1iso_M_To[5000], spike_RCTL1noniso_M_To[5000],
    spike_maxEGtrig[5000], spike_maxEGtrig_To[5000], spike_maxEGtrig_M_To[5000];
  
  int spike_out_TTieta, spike_out_TTiphi, spike_out_Rieta, spike_out_Riphi, spike_out_severityLevel, 
    spike_out_outOfTime, spike_out_TT_sFGVB, spike_out_TT_adc, spike_out_TT_sFGVB_E[5], spike_out_TT_adc_E[5],
    spike_out_TT_t, spike_out_TT_tE;
  double  spike_out_Et, spike_out_eta, spike_out_phi, spike_out_theta;
  int spike_out_RCTL1iso, spike_out_RCTL1noniso, spike_out_RCTL1iso_To, spike_out_RCTL1noniso_To, 
    spike_out_RCTL1iso_M_To, spike_out_RCTL1noniso_M_To,
    spike_out_maxEGtrig, spike_out_maxEGtrig_To, spike_out_maxEGtrig_M_To;
  
  // TP info
  const int nTow = 4032;
  int trig_tower_N,trig_tower_ieta[nTow],trig_tower_iphi[nTow],trig_tower_adc[nTow],trig_tower_sFGVB[nTow],trig_tower_FG[nTow];
  int trig_tower_N_M,trig_tower_ieta_M[nTow],trig_tower_iphi_M[nTow],trig_tower_adc_M[nTow],trig_tower_sFGVB_M[nTow],
    trig_tower_FG_M[nTow];
  int trig_tower_N_E,trig_tower_ieta_E[nTow],trig_tower_iphi_E[nTow],trig_tower_adc_E[nTow][5],trig_tower_sFGVB_E[nTow][5],
    trig_tower_FG_E[nTow][5];

  // HCAL TP //
  int trig_tower_hcal_N, trig_tower_hcal_ieta[4032], trig_tower_hcal_iphi[4032], trig_tower_hcal_FG[4032],trig_tower_hcal_et[4032];

  // L1 Candidates //                                                                                                             
  int trig_L1emIso_N, trig_L1emNonIso_N; 
  int trig_L1emIso_N_To, trig_L1emNonIso_N_To, trig_L1emIso_N_M_To, trig_L1emNonIso_N_M_To;

  // L1 candidates info //
  int trig_L1emIso_ieta[4], trig_L1emIso_iphi[4], trig_L1emIso_rank[4];
  int trig_L1emNonIso_ieta[4], trig_L1emNonIso_iphi[4], trig_L1emNonIso_rank[4];

  int trig_L1emIso_ieta_To[4], trig_L1emIso_iphi_To[4], trig_L1emIso_rank_To[4];
  int trig_L1emNonIso_ieta_To[4], trig_L1emNonIso_iphi_To[4], trig_L1emNonIso_rank_To[4];
  int trig_L1emIso_ieta_M_To[4], trig_L1emIso_iphi_M_To[4], trig_L1emIso_rank_M_To[4];
  int trig_L1emNonIso_ieta_M_To[4], trig_L1emNonIso_iphi_M_To[4], trig_L1emNonIso_rank_M_To[4];

  // INITIALIZATION //                                                                                                               
  //                                                                                                                                 
  // Global                                                                                                                        
  nEvent = 0;
  nRun = 0;
  nLumi = 0;
  //                                                                                                                          
  // Vertices                                                                                                                   
  vtx_N = 0;
  for(int iv=0;iv<200;iv++) {
    _vtx_normalizedChi2[iv] = 0.;
    _vtx_ndof[iv] = 0.;
    _vtx_nTracks[iv] = 0.;
    _vtx_d0[iv] = 0.;
    _vtx_x[iv] = 0.;
    _vtx_y[iv] = 0.;
    _vtx_z[iv] = 0.;
  }
  //                                                                                                                        
  // L1 candidates                                                                                              
  trig_L1emIso_N    = 0;
  trig_L1emNonIso_N = 0;
  trig_L1emIso_N_M_To  = 0;
  trig_L1emNonIso_N_M_To = 0;

  for(int il1=0 ; il1<4 ; il1++) {
    trig_L1emIso_ieta[il1] = 0;
    trig_L1emIso_iphi[il1] = 0;
    trig_L1emIso_rank[il1] = 0;
    trig_L1emNonIso_ieta[il1] = 0;
    trig_L1emNonIso_iphi[il1] = 0;
    trig_L1emNonIso_rank[il1] = 0;

    trig_L1emIso_ieta_To[il1] = 0;
    trig_L1emIso_iphi_To[il1] = 0;
    trig_L1emIso_rank_To[il1] = 0;
    trig_L1emNonIso_ieta_To[il1] = 0;
    trig_L1emNonIso_iphi_To[il1] = 0;
    trig_L1emNonIso_rank_To[il1] = 0;

    trig_L1emIso_ieta_M_To[il1] = 0;
    trig_L1emIso_iphi_M_To[il1] = 0;
    trig_L1emIso_rank_M_To[il1] = 0;
    trig_L1emNonIso_ieta_M_To[il1] = 0;
    trig_L1emNonIso_iphi_M_To[il1] = 0;
    trig_L1emNonIso_rank_M_To[il1] = 0;
  }

  // Trigger towers              
  trig_tower_N = 0;
  for(int iTow=0 ; iTow<nTow ; iTow++) {
    trig_tower_ieta[iTow] = trig_tower_iphi[iTow]  = -999;
    trig_tower_adc[iTow]  = trig_tower_sFGVB[iTow] = trig_tower_FG[iTow] = -999;
  }
  trig_tower_N_M = 0;
  for(int iTow=0 ; iTow<nTow ; iTow++) {
    trig_tower_ieta_M[iTow] = trig_tower_iphi_M[iTow]  = -999;
    trig_tower_adc_M[iTow]  = trig_tower_sFGVB_M[iTow] = trig_tower_FG_M[iTow] = -999;
  }
  trig_tower_N_E = 0;
  for(int iTow=0 ; iTow<nTow ; iTow++) {
    trig_tower_ieta_E[iTow] = trig_tower_iphi_E[iTow] = -999;
    for(int i=0 ; i<5 ; i++)
      trig_tower_adc_E[iTow][i] = trig_tower_sFGVB_E[iTow][i] = trig_tower_FG_E[iTow][i] = -999;
  }
  trig_tower_hcal_N = 0;
  for(int iTow=0 ; iTow<nTow ; iTow++) {
    trig_tower_hcal_ieta[iTow] = trig_tower_hcal_iphi[iTow]  = -999;
    trig_tower_hcal_FG[iTow]  = trig_tower_hcal_et[iTow] = -999;
  }

  // SPIKES //
  spike_N = 0;  
  for(int isp=0 ; isp<5000 ; isp++) {
    spike_outOfTime[isp] = -999;
    spike_severityLevel[isp] = -999 ;
    //spike_SwissCross[isp] = -999 ;
    spike_Et[isp] = -999 ;
    spike_phi[isp] = -999 ;
    spike_eta[isp] = -999 ;
    spike_theta[isp] = -999 ;
    spike_TTiphi[isp] = -999 ;
    spike_TTieta[isp] = -999 ;
    spike_TT_t[isp] = -999 ;
    spike_TT_tE[isp] = -999 ;
    spike_TT_sFGVB[isp] = -999 ;
    spike_TT_adc[isp] = -999 ;
    spike_Riphi[isp] = -999 ;
    spike_Rieta[isp] = -999 ;

    for(int i=0;i<5;i++) {
      spike_TT_sFGVB_E[isp][i] = -999 ;
      spike_TT_adc_E[isp][i]   = -999 ;
    }
  }

  spike_out_outOfTime = -999;
  spike_out_severityLevel = -999 ;
  //spike_out_SwissCross = -999 ;
  spike_out_Et = -999 ;
  spike_out_phi = -999 ;
  spike_out_eta = -999 ;
  spike_out_theta = -999 ;
  spike_out_TTiphi = -999 ;
  spike_out_TTieta = -999 ;
  spike_out_TT_t = -999 ;
  spike_out_TT_tE = -999 ;
  spike_out_TT_sFGVB = -999 ;
  spike_out_TT_adc = -999 ;
  spike_out_Riphi = -999 ;
  spike_out_Rieta = -999 ;
  
  for(int i=0;i<5;i++) {
    spike_out_TT_sFGVB_E[i] = -999 ;
    spike_out_TT_adc_E[i]   = -999 ;
  }

  myChain->SetBranchAddress("nEvent",&nEvent);
  myChain->SetBranchAddress("nRun",&nRun);
  myChain->SetBranchAddress("nLumi",&nLumi);

  // Vertices
  myChain->SetBranchAddress("vtx_N",&vtx_N);

  //myChain->SetBranchAddress("trig_HLT_path",&trig_HLT_path);
  myChain->SetBranchAddress("trig_fired_names",&trig_fired_names);
  myChain->SetBranchAddress("trig_hltInfo",&trig_hltInfo);

  // L1 candidates                             
  myChain->SetBranchAddress("trig_L1emIso_N", &trig_L1emIso_N);
  myChain->SetBranchAddress("trig_L1emIso_ieta", &trig_L1emIso_ieta);
  myChain->SetBranchAddress("trig_L1emIso_iphi", &trig_L1emIso_iphi);
  myChain->SetBranchAddress("trig_L1emIso_rank", &trig_L1emIso_rank);

  myChain->SetBranchAddress("trig_L1emNonIso_N", &trig_L1emNonIso_N);
  myChain->SetBranchAddress("trig_L1emNonIso_ieta", &trig_L1emNonIso_ieta);
  myChain->SetBranchAddress("trig_L1emNonIso_iphi", &trig_L1emNonIso_iphi);
  myChain->SetBranchAddress("trig_L1emNonIso_rank", &trig_L1emNonIso_rank);

  // Spikes
  myChain->SetBranchAddress("spike_N",&spike_N);
  myChain->SetBranchAddress("spike_TTieta",&spike_TTieta);
  myChain->SetBranchAddress("spike_TTiphi",&spike_TTiphi);
  myChain->SetBranchAddress("spike_Rieta",&spike_Rieta);
  myChain->SetBranchAddress("spike_Riphi",&spike_Riphi);
  myChain->SetBranchAddress("spike_severityLevel",&spike_severityLevel);
  myChain->SetBranchAddress("spike_outOfTime",&spike_outOfTime);
  myChain->SetBranchAddress("spike_Et",&spike_Et);
  myChain->SetBranchAddress("spike_eta",&spike_eta);
  myChain->SetBranchAddress("spike_phi",&spike_phi);
  myChain->SetBranchAddress("spike_theta",&spike_theta);

  // TrigOnly Chain //
  trigOnlyChain->SetBranchAddress("nRun", &nRun_To);
  trigOnlyChain->SetBranchAddress("nLumi", &nLumi_To);
  trigOnlyChain->SetBranchAddress("nEvent", &nEvent_To);

  trigOnlyChain->SetBranchAddress("trig_HLT_path",&trig_HLT_path);

  trigOnlyChain->SetBranchAddress("trig_tower_N", &trig_tower_N);
  trigOnlyChain->SetBranchAddress("trig_tower_ieta",  &trig_tower_ieta);
  trigOnlyChain->SetBranchAddress("trig_tower_iphi",  &trig_tower_iphi);
  trigOnlyChain->SetBranchAddress("trig_tower_adc",  &trig_tower_adc);
  trigOnlyChain->SetBranchAddress("trig_tower_sFGVB",  &trig_tower_sFGVB);
  //trigOnlyChain->SetBranchAddress("trig_tower_FG",  &trig_tower_FG);

  trigOnlyChain->SetBranchAddress("trig_tower_N_E",     &trig_tower_N_E);
  trigOnlyChain->SetBranchAddress("trig_tower_ieta_E",  &trig_tower_ieta_E);
  trigOnlyChain->SetBranchAddress("trig_tower_iphi_E",  &trig_tower_iphi_E);
  trigOnlyChain->SetBranchAddress("trig_tower_adc_E",   &trig_tower_adc_E);
  trigOnlyChain->SetBranchAddress("trig_tower_sFGVB_E", &trig_tower_sFGVB_E);
  //trigOnlyChain->SetBranchAddress("trig_tower_FG_E", &trig_tower_FG_E);

  // HCAL TP                                                        
  trigOnlyChain->SetBranchAddress("trig_tower_hcal_N", &trig_tower_hcal_N);
  trigOnlyChain->SetBranchAddress("trig_tower_hcal_ieta",  &trig_tower_hcal_ieta);
  trigOnlyChain->SetBranchAddress("trig_tower_hcal_iphi",  &trig_tower_hcal_iphi);
  trigOnlyChain->SetBranchAddress("trig_tower_hcal_et",  &trig_tower_hcal_et);
  trigOnlyChain->SetBranchAddress("trig_tower_hcal_FG",  &trig_tower_hcal_FG);

  // L1 candidates collections                        
  trigOnlyChain->SetBranchAddress("trig_L1emIso_N", &trig_L1emIso_N_To);
  trigOnlyChain->SetBranchAddress("trig_L1emIso_ieta", &trig_L1emIso_ieta_To);
  trigOnlyChain->SetBranchAddress("trig_L1emIso_iphi", &trig_L1emIso_iphi_To);
  trigOnlyChain->SetBranchAddress("trig_L1emIso_rank", &trig_L1emIso_rank_To);

  trigOnlyChain->SetBranchAddress("trig_L1emNonIso_N", &trig_L1emNonIso_N_To);
  trigOnlyChain->SetBranchAddress("trig_L1emNonIso_ieta", &trig_L1emNonIso_ieta_To);
  trigOnlyChain->SetBranchAddress("trig_L1emNonIso_iphi", &trig_L1emNonIso_iphi_To);
  trigOnlyChain->SetBranchAddress("trig_L1emNonIso_rank", &trig_L1emNonIso_rank_To);

  trigOnlyChain->SetBranchAddress("trig_L1emIso_N_M", &trig_L1emIso_N_M_To);
  trigOnlyChain->SetBranchAddress("trig_L1emIso_ieta_M", &trig_L1emIso_ieta_M_To);
  trigOnlyChain->SetBranchAddress("trig_L1emIso_iphi_M", &trig_L1emIso_iphi_M_To);
  trigOnlyChain->SetBranchAddress("trig_L1emIso_rank_M", &trig_L1emIso_rank_M_To);

  trigOnlyChain->SetBranchAddress("trig_L1emNonIso_N_M", &trig_L1emNonIso_N_M_To);
  trigOnlyChain->SetBranchAddress("trig_L1emNonIso_ieta_M", &trig_L1emNonIso_ieta_M_To);
  trigOnlyChain->SetBranchAddress("trig_L1emNonIso_iphi_M", &trig_L1emNonIso_iphi_M_To);
  trigOnlyChain->SetBranchAddress("trig_L1emNonIso_rank_M", &trig_L1emNonIso_rank_M_To);


  // OUTPUT TREE //

  TTree * outtree = new TTree("Spikes","Spikes");
  // General informations //
  outtree->Branch("nRun",&nRun,"nRun/I");
  outtree->Branch("nLumi",&nLumi,"nLumi/I");
  outtree->Branch("nEvent",&nEvent,"nEvent/I");

  // Vertices //
  outtree->Branch("vtx_N",&vtx_N,"vtx_N/I");

  outtree->Branch("trig_HLT_path",&trig_HLT_path,"trig_HLT_path[4]/I");
  outtree->Branch("trig_fired_names",&trig_fired_names,"trig_fired_names[5000]/C");
  outtree->Branch("trig_hltInfo",&trig_hltInfo,"trig_hltInfo[250]/I");

  // Trigger towers //
  outtree->Branch("trig_tower_N",&trig_tower_N,"trig_tower_N/I");
  outtree->Branch("trig_tower_ieta",&trig_tower_ieta,"trig_tower_ieta[4032]/I");
  outtree->Branch("trig_tower_iphi",&trig_tower_iphi,"trig_tower_iphi[4032]/I");
  outtree->Branch("trig_tower_adc",&trig_tower_adc,"trig_tower_adc[4032]/I");
  outtree->Branch("trig_tower_sFGVB",&trig_tower_sFGVB,"trig_tower_sFGVB[4032]/I");
  outtree->Branch("trig_tower_FG",&trig_tower_FG,"trig_tower_FG[4032]/I");
  //                                                               
  outtree->Branch("trig_tower_N_E",&trig_tower_N_E,"trig_tower_N_E/I");
  outtree->Branch("trig_tower_ieta_E",&trig_tower_ieta_E,"trig_tower_ieta_E[4032]/I");
  outtree->Branch("trig_tower_iphi_E",&trig_tower_iphi_E,"trig_tower_iphi_E[4032]/I");
  outtree->Branch("trig_tower_adc_E",&trig_tower_adc_E,"trig_tower_adc_E[4032][5]/I");
  outtree->Branch("trig_tower_sFGVB_E",&trig_tower_sFGVB_E,"trig_tower_sFGVB_E[4032][5]/I");
  outtree->Branch("trig_tower_FG_E",&trig_tower_FG_E,"trig_tower_FG_E[4032][5]/I");

  // HCAL TP                                 
  outtree->Branch("trig_tower_hcal_N", &trig_tower_hcal_N, "trig_tower_hcal_N/I");
  outtree->Branch("trig_tower_hcal_ieta",  &trig_tower_hcal_ieta,  "trig_tower_hcal_ieta[trig_tower_N]/I");
  outtree->Branch("trig_tower_hcal_iphi",  &trig_tower_hcal_iphi,  "trig_tower_hcal_iphi[trig_tower_N]/I");
  outtree->Branch("trig_tower_hcal_et",  &trig_tower_hcal_et,  "trig_tower_hcal_et[trig_tower_N]/I");
  outtree->Branch("trig_tower_hcal_FG",  &trig_tower_hcal_FG,  "trig_tower_hcal_FG[trig_tower_N]/I");

  // L1 candidates from Data
  outtree->Branch("trig_L1emIso_N",     &trig_L1emIso_N,     "trig_L1emIso_N/I");
  outtree->Branch("trig_L1emIso_ieta",  &trig_L1emIso_ieta,  "trig_L1emIso_ieta[4]/I");
  outtree->Branch("trig_L1emIso_iphi",  &trig_L1emIso_iphi,  "trig_L1emIso_iphi[4]/I");
  outtree->Branch("trig_L1emIso_rank",  &trig_L1emIso_rank,  "trig_L1emIso_rank[4]/I");

  outtree->Branch("trig_L1emNonIso_N",     &trig_L1emNonIso_N,     "trig_L1emNonIso_N/I");
  outtree->Branch("trig_L1emNonIso_ieta",  &trig_L1emNonIso_ieta,  "trig_L1emNonIso_ieta[4]/I");
  outtree->Branch("trig_L1emNonIso_iphi",  &trig_L1emNonIso_iphi,  "trig_L1emNonIso_iphi[4]/I");
  outtree->Branch("trig_L1emNonIso_rank",  &trig_L1emNonIso_rank,  "trig_L1emNonIso_rank[4]/I");
  
  // L1 candidates from TrigOnly 
  outtree->Branch("trig_L1emIso_N_To",     &trig_L1emIso_N_To,     "trig_L1emIso_N_To/I");
  outtree->Branch("trig_L1emIso_ieta_To",  &trig_L1emIso_ieta_To,  "trig_L1emIso_ieta_To[4]/I");
  outtree->Branch("trig_L1emIso_iphi_To",  &trig_L1emIso_iphi_To,  "trig_L1emIso_iphi_To[4]/I");
  outtree->Branch("trig_L1emIso_rank_To",  &trig_L1emIso_rank_To,  "trig_L1emIso_rank_To[4]/I");
  //                                                                                                   
  outtree->Branch("trig_L1emNonIso_N_To", &trig_L1emNonIso_N_To, "trig_L1emNonIso_N_To/I");
  outtree->Branch("trig_L1emNonIso_ieta_To", &trig_L1emNonIso_ieta_To, "trig_L1emNonIso_ieta_To[4]/I");
  outtree->Branch("trig_L1emNonIso_iphi_To", &trig_L1emNonIso_iphi_To, "trig_L1emNonIso_iphi_To[4]/I");
  outtree->Branch("trig_L1emNonIso_rank_To", &trig_L1emNonIso_rank_To, "trig_L1emNonIso_rank_To[4]/I");

  outtree->Branch("trig_L1emIso_N_M_To",     &trig_L1emIso_N_M_To,     "trig_L1emIso_N_M_To/I");
  outtree->Branch("trig_L1emIso_ieta_M_To",  &trig_L1emIso_ieta_M_To,  "trig_L1emIso_ieta_M_To[4]/I");
  outtree->Branch("trig_L1emIso_iphi_M_To",  &trig_L1emIso_iphi_M_To,  "trig_L1emIso_iphi_M_To[4]/I");
  outtree->Branch("trig_L1emIso_rank_M_To",  &trig_L1emIso_rank_M_To,  "trig_L1emIso_rank_M_To[4]/I");
  //                                                                                
  outtree->Branch("trig_L1emNonIso_N_M_To", &trig_L1emNonIso_N_M_To, "trig_L1emNonIso_N_M_To/I");
  outtree->Branch("trig_L1emNonIso_ieta_M_To", &trig_L1emNonIso_ieta_M_To, "trig_L1emNonIso_ieta_M_To[4]/I");
  outtree->Branch("trig_L1emNonIso_iphi_M_To", &trig_L1emNonIso_iphi_M_To, "trig_L1emNonIso_iphi_M_To[4]/I");
  outtree->Branch("trig_L1emNonIso_rank_M_To", &trig_L1emNonIso_rank_M_To, "trig_L1emNonIso_rank_M_To[4]/I");

  outtree->Branch("spike_TTieta",&spike_out_TTieta,"spike_TTieta/I");
  outtree->Branch("spike_TTiphi",&spike_out_TTiphi,"spike_TTiphi/I");
  //
  outtree->Branch("spike_TT_t",&spike_out_TT_t,"spike_TT_t/I");
  outtree->Branch("spike_TT_sFGVB",&spike_out_TT_sFGVB,"spike_TT_sFGVB/I");
  outtree->Branch("spike_TT_adc",&spike_out_TT_adc,"spike_TT_adc/I");
  outtree->Branch("spike_TT_tE",&spike_out_TT_tE,"spike_TT_tE/I");
  outtree->Branch("spike_TT_sFGVB_E",&spike_out_TT_sFGVB_E,"spike_TT_sFGVB[5]/I");
  outtree->Branch("spike_TT_adc_E",&spike_out_TT_adc_E,"spike_TT_adc[5]/I");
  //
  outtree->Branch("spike_Rieta",&spike_out_Rieta,"spike_Rieta/I");
  outtree->Branch("spike_Riphi",&spike_out_Riphi,"spike_Riphi/I");
  outtree->Branch("spike_severityLevel",&spike_out_severityLevel,"spike_severityLevel/I");
  outtree->Branch("spike_outOfTime",&spike_out_outOfTime,"spike_outOfTime/I");
  outtree->Branch("spike_Et",&spike_out_Et,"spike_Et/D");
  outtree->Branch("spike_eta",&spike_out_eta,"spike_eta/D");
  outtree->Branch("spike_phi",&spike_out_phi,"spike_phi/D");
  outtree->Branch("spike_theta",&spike_out_theta,"spike_theta/D");
  //
  outtree->Branch("spike_maxEGtrig",&spike_out_maxEGtrig,"spike_maxEGtrig/I");
  outtree->Branch("spike_maxEGtrig_To",&spike_out_maxEGtrig_To,"spike_maxEGtrig_To/I");
  outtree->Branch("spike_maxEGtrig_M_To",&spike_out_maxEGtrig_M_To,"spike_maxEGtrig_M_To/I");
  //
  outtree->Branch("spike_RCTL1iso",&spike_out_RCTL1iso,"spike_RCTL1iso/I");
  outtree->Branch("spike_RCTL1noniso",&spike_out_RCTL1noniso,"spike_RCTL1noniso/I");
  outtree->Branch("spike_RCTL1iso_To",&spike_out_RCTL1iso_To,"spike_RCTL1iso_To/I");
  outtree->Branch("spike_RCTL1noniso_To",&spike_out_RCTL1noniso_To,"spike_RCTL1noniso_To/I");
  outtree->Branch("spike_RCTL1iso_M_To",&spike_out_RCTL1iso_M_To,"spike_RCTL1iso_M_To/I");
  outtree->Branch("spike_RCTL1noniso_M_To",&spike_out_RCTL1noniso_M_To,"spike_RCTL1noniso_M_To/I");

  // Variables
  bool isGoodRun, evt_trig_EG12;
  TString filename;

  // Map TT
  MAPTT adcTT;
  MAPTT::iterator iterTT;
  pair<int,int> coords;
  int TT_t, TT_tE;

  int numEntries = myChain->GetEntries () ;
  int nProcess = numEntries;
  if(nEntries>=0 && nEntries<numEntries)
    nProcess = nEntries;

  int nCurrentRun = -999;
  outlog << "will process " << nProcess << "/" << numEntries << "entries" << endl;

  // Loop over entries //
  for (int iEvent = 0 ; iEvent < nProcess ; iEvent++ ) {
    
    // TP Initialization                                                                                                           
    trig_tower_N = 0;
    for(int iTow=0 ; iTow<nTow ; iTow++) {
      trig_tower_ieta[iTow] = trig_tower_iphi[iTow]  = -999;
      trig_tower_adc[iTow]  = trig_tower_sFGVB[iTow] = -999;
    }
    trig_tower_N_M = 0;
    for(int iTow=0 ; iTow<nTow ; iTow++) {
      trig_tower_ieta_M[iTow] = trig_tower_iphi_M[iTow]  = -999;
      trig_tower_adc_M[iTow]  = trig_tower_sFGVB_M[iTow] = -999;
    }
    trig_tower_N_E = 0;
    for(int iTow=0 ; iTow<nTow ; iTow++) {
      trig_tower_ieta_E[iTow] = trig_tower_iphi_E[iTow] = -999;
      for(int i=0 ; i<5 ; i++)
	trig_tower_adc_E[iTow][i] = trig_tower_sFGVB_E[iTow][i] = -999;
    }

    // L1 candidates                                                                                                               
    trig_L1emIso_N    = 0;
    trig_L1emNonIso_N = 0;
    trig_L1emIso_N_M_To  = 0;
    trig_L1emNonIso_N_M_To = 0;
    trig_L1emIso_N_To  = 0;
    trig_L1emNonIso_N_To = 0;

    for(int il1=0 ; il1<4 ; il1++) {
      trig_L1emIso_ieta[il1] = 0;
      trig_L1emIso_iphi[il1] = 0;
      trig_L1emIso_rank[il1] = 0;
      trig_L1emNonIso_ieta[il1] = 0;
      trig_L1emNonIso_iphi[il1] = 0;
      trig_L1emNonIso_rank[il1] = 0;

      trig_L1emIso_ieta_To[il1] = 0;
      trig_L1emIso_iphi_To[il1] = 0;
      trig_L1emIso_rank_To[il1] = 0;
      trig_L1emNonIso_ieta_To[il1] = 0;
      trig_L1emNonIso_iphi_To[il1] = 0;
      trig_L1emNonIso_rank_To[il1] = 0;

      trig_L1emNonIso_ieta_M_To[il1] = 0;
      trig_L1emNonIso_iphi_M_To[il1] = 0;
      trig_L1emNonIso_rank_M_To[il1] = 0;
      trig_L1emIso_ieta_M_To[il1] = 0;
      trig_L1emIso_iphi_M_To[il1] = 0;
      trig_L1emIso_rank_M_To[il1] = 0;
    }

    for(int isp=0 ; isp<5000 ; isp++) {
      spike_outOfTime[isp] = -999;
      spike_severityLevel[isp] = -999 ;
      //spike_SwissCross[isp] = -999 ;
      spike_Et[isp] = -999 ;
      spike_phi[isp] = -999 ;
      spike_eta[isp] = -999 ;
      spike_theta[isp] = -999 ;
      spike_TTiphi[isp] = -999 ;
      spike_TTieta[isp] = -999 ;
      spike_TT_t[isp] = -999 ;
      spike_TT_tE[isp] = -999 ;
      spike_TT_sFGVB[isp] = -999 ;
      spike_TT_adc[isp] = -999 ;
      spike_Riphi[isp] = -999 ;
      spike_Rieta[isp] = -999 ;

      for(int i=0;i<5;i++) {
	spike_TT_sFGVB_E[isp][i] = -999 ;
	spike_TT_adc_E[isp][i]   = -999 ;
      }
    }
    
    myChain->GetEntry (iEvent) ;

    // show processed file                                                                                                         
    if(iEvent==0) {
      filename = myChain->GetFile()->GetName() ;
      outlog << "File : " << filename << endl << endl;
    }
    else if( filename != myChain->GetFile()->GetName() ) {
      filename = myChain->GetFile()->GetName() ;
      outlog << "File : " << myChain->GetFile()->GetName() << endl << endl;
    }

    // show current run/iCat processed                                                                                             
    if(iEvent==0) {
      nCurrentRun = nRun ;
      outlog << "nRun=" << nRun << endl;
    }
    else if(nRun!=nCurrentRun) {
      nCurrentRun=nRun ;
      outlog << "nRun=" << nRun << endl;
    }

    if(debug) cout << "iJson = " << iJson << endl;
    if( iJson>-1 && iJson<5) {
      isGoodRun = AcceptEventByRunAndLumiSection(nRun, nLumi, jsonMap[iJson]);
      if(!isGoodRun) {
	outlog << "failed JSON" << endl;
	continue;
      }
    }

    // JSON selection ////////////////////////////////////////////
    if(debug) cout << "iJson = " << iJson << endl;
    if( iJson>-1 && iJson<5) {
      isGoodRun = false;
      isGoodRun = AcceptEventByRunAndLumiSection(nRun, nLumi, jsonMap[iJson]);
      if(!isGoodRun) {
	outlog << "failed JSON" << endl;
	continue;
      }
    }
    
    // HLT selection //
    if(usr_hlt=="unbias")
      if(trig_HLT_path[0]==0) continue;
    
    // Map the trigger tower //////////////////////////////////////////////////////////////////////
    adcTT.clear();
    for(int t=0 ; t<trig_tower_N ; t++) {
      coords = make_pair( trig_tower_ieta[t] , trig_tower_iphi[t] );
      adcTT[coords].first = t;
    }
    for(int t=0 ; t<trig_tower_N_E ; t++) {
      coords = make_pair( trig_tower_ieta_E[t] , trig_tower_iphi_E[t] );
      iterTT = adcTT.find( coords );

      if( iterTT != adcTT.end() ) {
	adcTT[coords].second = t;
      }
    }
    
    // Load trigOnly information ////////////////////////////////////////////////////////////////////                              
    if( GetTrigOnly ) {

      runevtTo = make_pair(nRun,nEvent);
      iterMapTo = mapTo.find( runevtTo );
      //                                                                                                                           
      if( iterMapTo != mapTo.end() )
	iEntryTo = mapTo[ runevtTo ];
      else iEntryTo = -1;
      //                                                                                                                           
      outlog << "trigOnly info : nRun=" << nRun << " | nEvent=" << nEvent << " | iEntryTo=" << iEntryTo << endl;
      //                                                                                                                           
      if(iEntryTo>=0) {
	trigOnlyChain->GetEntry( iEntryTo );
	if(debug) cout << "----> got entry from trigOnlyChain" << endl;
      }
      else {
	if(debug) cout << "----> entry not mapped" << endl;
	continue;
      }
    }

    // MATCHING SPIKE / L1-CANDIDATE //////////////////////////////////////////////////////////////////                         
    evt_trig_EG12=false;

    outcheckL1 << "ISO_N_data : " ;
    for(int i=0 ; i<4 ; i++) {
      outcheckL1 << "(" << trig_L1emIso_ieta[i] << ";" << trig_L1emIso_iphi[i] << ")=" << trig_L1emIso_rank[i] << " | ";
      if(trig_L1emIso_rank[i] >= 12) evt_trig_EG12=true;
    }

    outcheckL1 << endl
	       << "NONISO_N_data : ";
    for(int i=0 ; i<4 ; i++) {
      outcheckL1 << "(" << trig_L1emNonIso_ieta[i] << ";" << trig_L1emNonIso_iphi[i] << ")=" << trig_L1emNonIso_rank[i] << " | ";
      if(trig_L1emNonIso_rank[i] >= 12) evt_trig_EG12=true;
    }

    if(!evt_trig_EG12) continue;

    outcheckL1 << endl
	       << "ISO_N : " ;
    for(int i=0 ; i<4 ; i++)
      outcheckL1 << "(" << trig_L1emIso_ieta_To[i] << ";" << trig_L1emIso_iphi_To[i] << ")=" << trig_L1emIso_rank_To[i] << " | ";

    outcheckL1 << endl
	       << "NONISO_N : ";
    for(int i=0 ; i<4 ; i++)
      outcheckL1 << "(" << trig_L1emNonIso_ieta_To[i] << ";" << trig_L1emNonIso_iphi_To[i] << ")=" << trig_L1emNonIso_rank_To[i] 
		 << " | ";

    outcheckL1 << endl
	       << "ISO_M : ";
    for(int i=0 ; i<4 ; i++)
      outcheckL1 << "(" << trig_L1emIso_ieta_M_To[i] << ";" << trig_L1emIso_iphi_M_To[i] << ")=" << trig_L1emIso_rank_M_To[i] 
		 << " | ";

    outcheckL1 << endl
	       << "NONISO_M : ";
    for(int i=0 ; i<4 ; i++)
      outcheckL1 << "(" << trig_L1emNonIso_ieta_M_To[i] << ";" << trig_L1emNonIso_iphi_M_To[i] << ")=" 
		 << trig_L1emNonIso_rank_M_To[i] << " | ";

    outcheckL1 << endl << endl;
  

    ///////////////////////////////////////
    // LOOP OVER SPIKES ///////////////////
    ///////////////////////////////////////

    for(int iS=0 ; iS<spike_N ; iS++) {

      if(iS>=5000) break;
      if(spike_Et[iS]<=0) continue;

      // Find spikes'TT informations
      coords = make_pair( spike_TTieta[iS] , spike_TTiphi[iS] );
      iterTT = adcTT.find( coords );
      if( iterTT != adcTT.end() ) {
	TT_t  = (iterTT->second).first ;
	TT_tE = (iterTT->second).second ;
	
	if(TT_t<0  || TT_t  >= 4032) continue;
	spike_TT_t[iS]  = TT_t ;
	spike_TT_sFGVB[iS] = trig_tower_sFGVB[ TT_t ];
	spike_TT_adc[iS] = trig_tower_adc[ TT_t ];
	
	if(TT_tE<0 || TT_tE >= 4032) continue;
	spike_TT_tE[iS] = TT_tE ;
	for(int iSam=0 ; iSam<5 ; iSam++) {
	  spike_TT_sFGVB_E[iS][iSam] = trig_tower_sFGVB_E[ TT_tE ][iSam];
	  spike_TT_adc_E[iS][iSam] = trig_tower_adc_E[ TT_tE ][iSam];
	}
      }

      // Match spike to L1 candidate
      spike_maxEGtrig[iS] = spike_maxEGtrig_To[iS] = spike_maxEGtrig_M_To[iS] = 0;
      
      matchL1toSpike( trig_L1emIso_N, trig_L1emIso_ieta, trig_L1emIso_iphi, trig_L1emIso_rank,
		      spike_Rieta[iS],  spike_Riphi[iS],  spike_RCTL1iso[iS], spike_maxEGtrig[iS], outcheckL1 );
      
      matchL1toSpike( trig_L1emIso_N, trig_L1emIso_ieta, trig_L1emIso_iphi, trig_L1emIso_rank,
		      spike_Rieta[iS],  spike_Riphi[iS],  spike_RCTL1noniso[iS], spike_maxEGtrig[iS], outcheckL1 );
      
      matchL1toSpike( trig_L1emIso_N_To, trig_L1emIso_ieta_To, trig_L1emIso_iphi_To, trig_L1emIso_rank_To,
		      spike_Rieta[iS],  spike_Riphi[iS],  spike_RCTL1iso_To[iS], spike_maxEGtrig_To[iS], outcheckL1 );
      
      matchL1toSpike( trig_L1emIso_N_To, trig_L1emIso_ieta_To, trig_L1emIso_iphi_To, trig_L1emIso_rank_To,
		      spike_Rieta[iS],  spike_Riphi[iS],  spike_RCTL1noniso_To[iS], spike_maxEGtrig_To[iS], outcheckL1 );
      
      matchL1toSpike( trig_L1emIso_N_M_To, trig_L1emIso_ieta_M_To, trig_L1emIso_iphi_M_To, trig_L1emIso_rank_M_To,
		      spike_Rieta[iS],  spike_Riphi[iS],  spike_RCTL1iso_M_To[iS], spike_maxEGtrig_M_To[iS], outcheckL1 );
      
      matchL1toSpike( trig_L1emIso_N_M_To, trig_L1emIso_ieta_M_To, trig_L1emIso_iphi_M_To, trig_L1emIso_rank_M_To,
		      spike_Rieta[iS],  spike_Riphi[iS],  spike_RCTL1noniso_M_To[iS], spike_maxEGtrig_M_To[iS], outcheckL1 );
      

      // Fill the tree //
      spike_out_outOfTime = spike_outOfTime[iS] ;
      spike_out_severityLevel = spike_severityLevel[iS] ;
      spike_out_Et = spike_Et[iS] ;
      spike_out_phi = spike_phi[iS] ;
      spike_out_eta = spike_eta[iS] ;
      spike_out_theta = spike_theta[iS] ;
      spike_out_TTiphi = spike_TTiphi[iS] ;
      spike_out_TTieta = spike_TTieta[iS] ;
      spike_out_TT_t = spike_TT_t[iS] ;
      spike_out_TT_tE = spike_TT_tE[iS] ;
      spike_out_TT_sFGVB = spike_TT_sFGVB[iS] ;
      spike_out_TT_adc = spike_TT_adc[iS] ;
      spike_out_Riphi = spike_Riphi[iS] ;
      spike_out_Rieta = spike_Rieta[iS] ;

      spike_out_maxEGtrig      = spike_maxEGtrig[iS];
      spike_out_maxEGtrig_To   = spike_maxEGtrig_To[iS];
      spike_out_maxEGtrig_M_To = spike_maxEGtrig_M_To[iS];

      spike_out_RCTL1iso = spike_RCTL1iso[iS];
      spike_out_RCTL1noniso = spike_RCTL1noniso[iS];
      spike_out_RCTL1iso_To = spike_RCTL1iso_To[iS];
      spike_out_RCTL1noniso_To = spike_RCTL1noniso_To[iS];
      spike_out_RCTL1iso_M_To = spike_RCTL1iso_M_To[iS];
      spike_out_RCTL1noniso_M_To = spike_RCTL1noniso_M_To[iS];


      for(int i=0;i<5;i++) {
	spike_out_TT_sFGVB_E[i] = spike_TT_sFGVB_E[iS][i] ;
	spike_out_TT_adc_E[i]   = spike_TT_adc_E[iS][i] ;
      }
      
      outtree->Fill();
    }

  }

    // Record tree
  outlog << "recording tree..." << endl;
  outtree->Write();
  outlog << "recorded !" << endl;
  outfile->Close();
  outlog << "file closed." << endl;

  return 1;

}
Exemple #17
0
void StatisticTest(string statTest, double & testEstimator, double & testPvalue, TString cut, TChain * chain, TString variable, TF1 * f, double RangeMin, double RangeMax) //, TH1D * hh, int nbOfBins)
{
	//for Kolmogorov-Smirnov test you have put statTest = "KS"
	//for Anderson-Darling statTest = "AD"


	// ------------------------------------------ //	
	// create a table of our variable (with cuts) //
	// ------------------------------------------ //

	TChain * ReducedChain = (TChain *) chain->CopyTree(cut);
	float value;
        ReducedChain->SetBranchAddress(variable,&value);

	int nEvents = ReducedChain->GetEntries();

	Double_t * sample = new Double_t[nEvents];

	//Double_t * sample2 = new Double_t[nbOfBins];

	for (int ievt = 0 ; ievt < nEvents; ievt++)
        {
                ReducedChain->GetEntry(ievt);
                //sample.push_back(value);
        	sample[ievt] = value;
	}

/*
	for (int ievt = 0 ; ievt < nbOfBins; ievt++)
	{
		sample2[ievt] = hh->GetBinContent(ievt + 1);
		//cout<<endl<<"sample2[ievt] = "<<sample2[ievt]<<endl;
	}
*/


	// -------------------------------------- //        
        // Transform the TF1 and create a GoFTest //
        // -------------------------------------- //	

	ROOT::Math::WrappedTF1 wf1(*f);

	ROOT::Math::GoFTest* goftest_1 = new ROOT::Math::GoFTest(nEvents, sample, wf1, ROOT::Math::GoFTest::kPDF, RangeMin, RangeMax);
	//ROOT::Math::GoFTest* goftest_1 = new ROOT::Math::GoFTest(nbOfBins, sample2, wf1, ROOT::Math::GoFTest::kCDF, RangeMin, RangeMax);

	// ---------------------------------------- //        
        // Return the test statistic and the pvalue //
        // ---------------------------------------- //


	if(statTest == "KS")
	{
		testEstimator = goftest_1-> KolmogorovSmirnovTest("t");
		testPvalue = goftest_1-> KolmogorovSmirnovTest();
	}

	if(statTest == "AD")
        {
                testEstimator = goftest_1-> AndersonDarlingTest("t");
                testPvalue = goftest_1-> AndersonDarlingTest();
        }


	delete sample;
	delete goftest_1;
	sample = 0;
	goftest_1 = 0;

}
int process(TString nameChain, TString file, int iFile, int nEntries, TString dirOut, 
	   ofstream& outlog, int iJson, TString RunPhase, bool debug)  {
  
  // OUTPUT FILE //
  ostringstream ossi("");
  ossi << iFile ;
//  std::cout<<"ossi is what?? "<<ossi<<std::endl;
//  std::cout<<"ossi is what?? "<<ossi<<std::endl;
//  std::cout<<"ossi.str() is what?? "<<ossi.str()<<std::endl;
  TString name=(TString)("elepairs_"+ossi.str()+".root");

  TFile *outfile = new TFile(name,"RECREATE");
  ossi.str("");

  // INPUT TREE //
  TChain * myChain = new TChain(nameChain);
  myChain->Add(file);

  int nEvent, nRun, nLumi ;

  // Vertices //
  int _vtx_N;
  double _vtx_x[200], _vtx_y[200], _vtx_z[200];
  double _vtx_normalizedChi2[200], _vtx_ndof[200], _vtx_nTracks[200], _vtx_d0[200];

  // Trigger Paths //
  int trig_hltInfo[250];
  int _trig_isEleHLTpath;
  int trig_HLT_path[4]; // unbias, EG5, EG8, EG12
  char trig_fired_names[5000];
  //
  vector<string> m_HLT_pathsV;
  vector<string> m_HLT_triggered;
  vector<int> m_HLT_pathsV_check;

//   m_HLT_pathsV.clear();
//   m_HLT_pathsV_check.clear();
//   for(int iP=0 ; iP<(int)HLT_paths_.size() ; iP++) {
//     m_HLT_pathsV.push_back( HLT_paths_[iP]);
//     m_HLT_pathsV_check.push_back(0);
//   }

  // Electrons
  TClonesArray * electrons = new TClonesArray ("TLorentzVector");
  int ele_N, sc_hybrid_N; 
  int ele_outOfTimeSeed[10],ele_severityLevelSeed[10];
  double ele_he[10], ele_sigmaietaieta[10];
  double ele_hcalDepth1TowerSumEt_dr03[10], ele_hcalDepth2TowerSumEt_dr03[10];
  double ele_ecalRecHitSumEt_dr03[10], ele_tkSumPt_dr03[10];
  double ele_sclEta[10], ele_sclEt[10];
  //double ecalIsoRel03,hcalIsoRel03,trackIsoRel03;
  double ele_deltaphiin[10], ele_deltaetain[10];
  double ele_conv_dist[10], ele_conv_dcot[10];
  double ele_fbrem[10];
  int ele_expected_inner_hits[10];
  //int ele_ambiguousGsfTracks[10];
  int ele_isConversion[10];
  int ele_echarge[10];
  //
  int ele_RCTeta[10], ele_RCTphi[10], ele_RCTL1iso[10], ele_RCTL1noniso[10], ele_RCTL1iso_M[10], ele_RCTL1noniso_M[10];
  int ele_TTetaVect[10][50], ele_TTphiVect[10][50];
  double ele_TTetVect[10][50];
  int ele_RCTetaVect[10][10], ele_RCTphiVect[10][10], ele_RCTL1isoVect[10][10], 
    ele_RCTL1nonisoVect[10][10],ele_RCTL1isoVect_M[10][10], ele_RCTL1nonisoVect_M[10][10];
  double ele_RCTetVect[10][10];

  // TP info
  const int nTow = 4032;
  int trig_tower_N,trig_tower_ieta[nTow],trig_tower_iphi[nTow],trig_tower_adc[nTow],trig_tower_sFGVB[nTow]; 
  int trig_tower_N_modif,trig_tower_ieta_modif[nTow],trig_tower_iphi_modif[nTow],trig_tower_adc_modif[nTow],trig_tower_sFGVB_modif[nTow];
  int trig_tower_N_emul,trig_tower_ieta_emul[nTow],trig_tower_iphi_emul[nTow],trig_tower_adc_emul[nTow][5],trig_tower_sFGVB_emul[nTow][5];

  // HCAL TP
  int trig_tower_hcal_N, trig_tower_hcal_ieta[4032], trig_tower_hcal_iphi[4032], trig_tower_hcal_FG[4032],trig_tower_hcal_et[4032];
  int trig_L1emIso_N, trig_L1emNonIso_N, trig_L1emIso_N_M, trig_L1emNonIso_N_M;

  // L1 candidates info
  int trig_L1emIso_ieta[4], trig_L1emIso_iphi[4], trig_L1emIso_rank[4];
  int trig_L1emNonIso_ieta[4], trig_L1emNonIso_iphi[4], trig_L1emNonIso_rank[4];
  int trig_L1emIso_ieta_M[4], trig_L1emIso_iphi_M[4], trig_L1emIso_rank_M[4];
  int trig_L1emNonIso_ieta_M[4], trig_L1emNonIso_iphi_M[4], trig_L1emNonIso_rank_M[4];

  // L1 prefiring
  int trig_preL1emIso_N; 
  int trig_preL1emNonIso_N;
  int trig_preL1emIso_ieta[4], trig_preL1emIso_iphi[4], trig_preL1emIso_rank[4]; 
  int trig_preL1emNonIso_ieta[4], trig_preL1emNonIso_iphi[4],trig_preL1emNonIso_rank[4];
  // L1 postfiring
  int trig_postL1emIso_N; 
  int trig_postL1emNonIso_N;
  int trig_postL1emIso_ieta[4], trig_postL1emIso_iphi[4], trig_postL1emIso_rank[4]; 
  int trig_postL1emNonIso_ieta[4], trig_postL1emNonIso_iphi[4],trig_postL1emNonIso_rank[4];
  
  // Masking
  int trig_nMaskedRCT, trig_nMaskedCh;
  int trig_iMaskedRCTeta[100], trig_iMaskedRCTphi[100], trig_iMaskedRCTcrate[100], trig_iMaskedTTeta[100], trig_iMaskedTTphi[100];

  int trig_strip_mask_N;
  int trig_strip_mask_TTieta[1000], trig_strip_mask_TTiphi[1000], trig_strip_mask_status[1000],
    trig_strip_mask_StripID[1000], trig_strip_mask_PseudoStripID[1000], trig_strip_mask_TccID[1000], trig_strip_mask_CCU[1000],
    trig_strip_mask_xtal_ix[1000][5], trig_strip_mask_xtal_iy[1000][5], trig_strip_mask_xtal_iz[1000][5];

  int trig_xtal_mask_N; // [EB+EE]
  int trig_xtal_mask_ieta[1000],trig_xtal_mask_iphi[1000], // for EE : xtal ieta->ix ; iphi -> iy
    trig_xtal_mask_TTieta[1000],trig_xtal_mask_TTiphi[1000], // but for EE towers, still ieta, iphi...
    trig_xtal_mask_Rieta[1000],trig_xtal_mask_Riphi[1000],
    trig_xtal_mask_status[1000], trig_xtal_mask_EBEE[1000]; // EBEE = {0,1} => 0=EB ; 1=EE
  //double trig_xtal_mask_eT[1000];  

  // INITIALIZATION //
  //
  // Global
  nEvent = 0;
  nRun = 0;
  nLumi = 0;
  //
  // Vertices
  _vtx_N = 0; 
  for(int iv=0;iv<200;iv++) {
    _vtx_normalizedChi2[iv] = 0.;
    _vtx_ndof[iv] = 0.;
    _vtx_nTracks[iv] = 0.;
    _vtx_d0[iv] = 0.;
    _vtx_x[iv] = 0.;
    _vtx_y[iv] = 0.;
    _vtx_z[iv] = 0.;
  }
  //
  // L1 candidates
  trig_L1emIso_N    = 0; 
  trig_L1emNonIso_N = 0;
  trig_preL1emIso_N   = 0; 
  trig_preL1emNonIso_N  = 0;
  trig_postL1emIso_N    = 0; 
  trig_postL1emNonIso_N = 0;
  //
  for(int il1=0 ; il1<4 ; il1++) {
    trig_L1emIso_ieta[il1] = 0; 
    trig_L1emIso_iphi[il1] = 0; 
    trig_L1emIso_rank[il1] = 0; 
    trig_L1emNonIso_ieta[il1] = 0; 
    trig_L1emNonIso_iphi[il1] = 0; 
    trig_L1emNonIso_rank[il1] = 0; 
		
    trig_preL1emIso_ieta[il1] = 0; 
    trig_preL1emIso_iphi[il1] = 0; 
    trig_preL1emIso_rank[il1] = 0;
    trig_preL1emNonIso_ieta[il1] = 0; 
    trig_preL1emNonIso_iphi[il1] = 0; 
    trig_preL1emNonIso_rank[il1] = 0; 
		
    trig_postL1emIso_ieta[il1] = 0; 
    trig_postL1emIso_iphi[il1] = 0; 
    trig_postL1emIso_rank[il1] = 0;
    trig_postL1emNonIso_ieta[il1] = 0; 
    trig_postL1emNonIso_iphi[il1] = 0; 
    trig_postL1emNonIso_rank[il1] = 0;  
  }
  // 
  // Trigger towers
  trig_tower_N = 0;
  for(int iTow=0 ; iTow<nTow ; iTow++) {
    trig_tower_ieta[iTow] = trig_tower_iphi[iTow]  = -999;
    trig_tower_adc[iTow]  = trig_tower_sFGVB[iTow] = -999;
  }
  trig_tower_N_modif = 0;
  for(int iTow=0 ; iTow<nTow ; iTow++) {
    trig_tower_ieta_modif[iTow] = trig_tower_iphi_modif[iTow]  = -999;
    trig_tower_adc_modif[iTow]  = trig_tower_sFGVB_modif[iTow] = -999;
  }
  trig_tower_N_emul = 0;
  for(int iTow=0 ; iTow<nTow ; iTow++) {
    trig_tower_ieta_emul[iTow] = trig_tower_iphi_emul[iTow] = -999;
    for(int i=0 ; i<5 ; i++)
      trig_tower_adc_emul[iTow][i] = trig_tower_sFGVB_emul[iTow][i] = -999;
  }
  trig_tower_hcal_N = 0;
  for(int iTow=0 ; iTow<nTow ; iTow++) {
    trig_tower_hcal_ieta[iTow] = trig_tower_hcal_iphi[iTow]  = -999;
    trig_tower_hcal_FG[iTow]  = trig_tower_hcal_et[iTow] = -999;
  }
  //
  // Masked Towers
  trig_nMaskedRCT=0;
  trig_nMaskedCh=0;
  //
  for (int ii=0;ii<100;ii++) {
    trig_iMaskedRCTeta[ii]   = -999;
    trig_iMaskedRCTphi[ii]   = -999;
    trig_iMaskedRCTcrate[ii] = -999;
    trig_iMaskedTTeta[ii]    = -999;
    trig_iMaskedTTphi[ii]    = -999;
  }
  //
  // Masked strip/xtals
  trig_strip_mask_N = 0;
  trig_xtal_mask_N = 0;
  //
  for(int i=0 ; i<1000 ; i++) {
    trig_strip_mask_TTieta[i] = -999;
    trig_strip_mask_TTiphi[i] = -999;
    trig_strip_mask_status[i] = -999;
    trig_strip_mask_StripID[i] = -999;
    trig_strip_mask_PseudoStripID[i] = -999;
    trig_strip_mask_TccID[i] = -999;
    trig_strip_mask_CCU[i] = -999;
    //
    for(int j=0 ; j<5 ; j++) {
      trig_strip_mask_xtal_ix[i][j] = -999;
      trig_strip_mask_xtal_iy[i][j] = -999;
      trig_strip_mask_xtal_iz[i][j] = -999;
    }
    trig_xtal_mask_ieta[i] = -999;
    trig_xtal_mask_iphi[i] = -999;
    trig_xtal_mask_TTieta[i] = -999;
    trig_xtal_mask_TTiphi[i] = -999;
    trig_xtal_mask_Rieta[i] = -999;
    trig_xtal_mask_Riphi[i] = -999;
    trig_xtal_mask_status[i] = -999;
    trig_xtal_mask_EBEE[i] = -999;
  }

  // Disable useless branches
  //myChain->SetBranchStatus("spike_*",0);
  //myChain->SetBranchStatus("vtx_*",0);
  //myChain->SetBranchStatus("skim_*",0);
  //myChain->SetBranchStatus("trig_pre*",0);
  //myChain->SetBranchStatus("trig_post*",0);
  //myChain->SetBranchStatus("trig_HLT*",0);
  //myChain->SetBranchStatus("BS*",0);
  //myChain->SetBranchStatus("MC_*",0);
  //myChain->SetBranchStatus("ele_MC*",0);
  ////myChain->SetBranchStatus("ele_eid*",0);
  ////myChain->SetBranchStatus("ele_Seed*",0);
  //myChain->SetBranchStatus("ele_charge*",0);
  //myChain->SetBranchStatus("met_*",0);
  //myChain->SetBranchStatus("muons*",0);
  //myChain->SetBranchStatus("jets*",0);
  myChain->SetBranchStatus("sc*",0);
  //myChain->SetBranchStatus("sc_hybrid_N",1);
  //myChain->SetBranchStatus("",0);

  // Global
  myChain->SetBranchAddress("nEvent",&nEvent);
  myChain->SetBranchAddress("nRun",&nRun);
  myChain->SetBranchAddress("nLumi",&nLumi);

  // Trigger
//   myChain->SetBranchAddress ("trig_HLT_triggered", &m_HLT_triggered);
//   myChain->SetBranchAddress ("trig_HLT_pathsV", &m_HLT_pathsV);
//   myChain->SetBranchAddress ("trig_HLT_pathsV_check", &m_HLT_pathsV_check);
  //
  myChain->SetBranchAddress("trig_HLT_path",&trig_HLT_path);
  // unbias, EG5, EG8, EG12
  //
  myChain->SetBranchAddress("trig_fired_names",&trig_fired_names);
  myChain->SetBranchAddress("trig_hltInfo",&trig_hltInfo);

  // SC
  //myChain->SetBranchAddress("sc_hybrid_N",   &sc_hybrid_N);
  
  // Electrons
  myChain->SetBranchAddress("ele_N",   &ele_N);
  myChain->SetBranchAddress("electrons",&electrons);
  myChain->SetBranchAddress("ele_severityLevelSeed", &ele_severityLevelSeed);
  myChain->SetBranchAddress("ele_he",&ele_he);
  myChain->SetBranchAddress("ele_sigmaietaieta",&ele_sigmaietaieta);
  myChain->SetBranchAddress("ele_hcalDepth1TowerSumEt_dr03", &ele_hcalDepth1TowerSumEt_dr03);
  myChain->SetBranchAddress("ele_hcalDepth2TowerSumEt_dr03", &ele_hcalDepth2TowerSumEt_dr03);
  myChain->SetBranchAddress("ele_ecalRecHitSumEt_dr03", &ele_ecalRecHitSumEt_dr03);
  myChain->SetBranchAddress("ele_tkSumPt_dr03",&ele_tkSumPt_dr03);
  myChain->SetBranchAddress("ele_sclEta",&ele_sclEta);
  myChain->SetBranchAddress("ele_sclEt",&ele_sclEt);
  myChain->SetBranchAddress("ele_expected_inner_hits",&ele_expected_inner_hits);
  myChain->SetBranchAddress("ele_deltaphiin",&ele_deltaphiin);
  myChain->SetBranchAddress("ele_deltaetain",&ele_deltaetain);
  myChain->SetBranchAddress("ele_conv_dist",&ele_conv_dist);
  myChain->SetBranchAddress("ele_conv_dcot",&ele_conv_dcot);
  myChain->SetBranchAddress("ele_fbrem",&ele_fbrem);
  //myChain->SetBranchAddress("ele_ambiguousGsfTracks", &ele_ambiguousGsfTracks);
  myChain->SetBranchAddress("ele_isConversion",&ele_isConversion);
  myChain->SetBranchAddress("ele_echarge",&ele_echarge);

  // L1 electron informations
  myChain->SetBranchAddress("ele_TTetaVect", &ele_TTetaVect);
  myChain->SetBranchAddress("ele_TTphiVect", &ele_TTphiVect);
  myChain->SetBranchAddress("ele_TTetVect", &ele_TTetVect);
  //
  myChain->SetBranchAddress("ele_RCTeta", &ele_RCTeta);
  myChain->SetBranchAddress("ele_RCTphi", &ele_RCTphi);
  myChain->SetBranchAddress("ele_RCTL1iso", &ele_RCTL1iso);
  myChain->SetBranchAddress("ele_RCTL1noniso", &ele_RCTL1noniso);
  myChain->SetBranchAddress("ele_RCTL1iso_M", &ele_RCTL1iso_M);
  myChain->SetBranchAddress("ele_RCTL1noniso_M", &ele_RCTL1noniso_M);

  myChain->SetBranchAddress("ele_RCTetaVect", &ele_RCTetaVect);
  myChain->SetBranchAddress("ele_RCTphiVect", &ele_RCTphiVect);
  myChain->SetBranchAddress("ele_RCTetVect", &ele_RCTetVect);
  myChain->SetBranchAddress("ele_RCTL1isoVect", &ele_RCTL1isoVect);
  myChain->SetBranchAddress("ele_RCTL1nonisoVect", &ele_RCTL1nonisoVect);
  myChain->SetBranchAddress("ele_RCTL1isoVect_M", &ele_RCTL1isoVect_M);
  myChain->SetBranchAddress("ele_RCTL1nonisoVect_M", &ele_RCTL1nonisoVect_M);

  // L1 candidates
  myChain->SetBranchAddress("trig_L1emIso_N", &trig_L1emIso_N);
  myChain->SetBranchAddress("trig_L1emIso_ieta", &trig_L1emIso_ieta);
  myChain->SetBranchAddress("trig_L1emIso_iphi", &trig_L1emIso_iphi);
  myChain->SetBranchAddress("trig_L1emIso_rank", &trig_L1emIso_rank);

  myChain->SetBranchAddress("trig_L1emNonIso_N", &trig_L1emNonIso_N);
  myChain->SetBranchAddress("trig_L1emNonIso_ieta", &trig_L1emNonIso_ieta);
  myChain->SetBranchAddress("trig_L1emNonIso_iphi", &trig_L1emNonIso_iphi); 
  myChain->SetBranchAddress("trig_L1emNonIso_rank", &trig_L1emNonIso_rank);

  myChain->SetBranchAddress("trig_L1emIso_N_M", &trig_L1emIso_N_M);
  myChain->SetBranchAddress("trig_L1emIso_ieta_M", &trig_L1emIso_ieta_M);
  myChain->SetBranchAddress("trig_L1emIso_iphi_M", &trig_L1emIso_iphi_M);
  myChain->SetBranchAddress("trig_L1emIso_rank_M", &trig_L1emIso_rank_M);
  
  myChain->SetBranchAddress("trig_L1emNonIso_N_M", &trig_L1emNonIso_N_M);
  myChain->SetBranchAddress("trig_L1emNonIso_ieta_M", &trig_L1emNonIso_ieta_M);
  myChain->SetBranchAddress("trig_L1emNonIso_iphi_M", &trig_L1emNonIso_iphi_M);
  myChain->SetBranchAddress("trig_L1emNonIso_rank_M", &trig_L1emNonIso_rank_M);

  // Pre/post - firing L1 candidates
  myChain->SetBranchAddress("trig_preL1emIso_N",     &trig_preL1emIso_N);
  myChain->SetBranchAddress("trig_preL1emIso_ieta",  &trig_preL1emIso_ieta);
  myChain->SetBranchAddress("trig_preL1emIso_iphi",  &trig_preL1emIso_iphi);
  myChain->SetBranchAddress("trig_preL1emIso_rank",  &trig_preL1emIso_rank);
  //
  myChain->SetBranchAddress("trig_preL1emNonIso_N",     &trig_preL1emNonIso_N);
  myChain->SetBranchAddress("trig_preL1emNonIso_ieta",  &trig_preL1emNonIso_ieta);
  myChain->SetBranchAddress("trig_preL1emNonIso_iphi",  &trig_preL1emNonIso_iphi);
  myChain->SetBranchAddress("trig_preL1emNonIso_rank",  &trig_preL1emNonIso_rank);
  //
  myChain->SetBranchAddress("trig_postL1emIso_N",     &trig_postL1emIso_N);
  myChain->SetBranchAddress("trig_postL1emIso_ieta",  &trig_postL1emIso_ieta);
  myChain->SetBranchAddress("trig_postL1emIso_iphi",  &trig_postL1emIso_iphi);
  myChain->SetBranchAddress("trig_postL1emIso_rank",  &trig_postL1emIso_rank);
  //
  myChain->SetBranchAddress("trig_postL1emNonIso_N",     &trig_postL1emNonIso_N);
  myChain->SetBranchAddress("trig_postL1emNonIso_ieta",  &trig_postL1emNonIso_ieta);
  myChain->SetBranchAddress("trig_postL1emNonIso_iphi",  &trig_postL1emNonIso_iphi);
  myChain->SetBranchAddress("trig_postL1emNonIso_rank",  &trig_postL1emNonIso_rank);

  // Trigger Towers
  // normal collection
  myChain->SetBranchAddress("trig_tower_N", &trig_tower_N);
  myChain->SetBranchAddress("trig_tower_ieta",  &trig_tower_ieta);
  myChain->SetBranchAddress("trig_tower_iphi",  &trig_tower_iphi);
  myChain->SetBranchAddress("trig_tower_adc",  &trig_tower_adc);
  myChain->SetBranchAddress("trig_tower_sFGVB",  &trig_tower_sFGVB);
 
  // modified collection
  myChain->SetBranchAddress("trig_tower_N_modif", &trig_tower_N_modif);
  myChain->SetBranchAddress("trig_tower_ieta_modif",  &trig_tower_ieta_modif);
  myChain->SetBranchAddress("trig_tower_iphi_modif",  &trig_tower_iphi_modif);
  myChain->SetBranchAddress("trig_tower_adc_modif",  &trig_tower_adc_modif);
  myChain->SetBranchAddress("trig_tower_sFGVB_modif",  &trig_tower_sFGVB_modif);

  myChain->SetBranchAddress("trig_tower_N_emul",     &trig_tower_N_emul);
  myChain->SetBranchAddress("trig_tower_ieta_emul",  &trig_tower_ieta_emul);
  myChain->SetBranchAddress("trig_tower_iphi_emul",  &trig_tower_iphi_emul);
  myChain->SetBranchAddress("trig_tower_adc_emul",   &trig_tower_adc_emul);
  myChain->SetBranchAddress("trig_tower_sFGVB_emul", &trig_tower_sFGVB_emul);
  
  // HCAL TP
  myChain->SetBranchAddress("trig_tower_hcal_N", &trig_tower_hcal_N);
  myChain->SetBranchAddress("trig_tower_hcal_ieta",  &trig_tower_hcal_ieta);
  myChain->SetBranchAddress("trig_tower_hcal_iphi",  &trig_tower_hcal_iphi);
  myChain->SetBranchAddress("trig_tower_hcal_et",  &trig_tower_hcal_et);
  myChain->SetBranchAddress("trig_tower_hcal_FG",  &trig_tower_hcal_FG);

  // Strip masking
  myChain->SetBranchAddress("trig_strip_mask_N", &trig_strip_mask_N);
  myChain->SetBranchAddress("trig_strip_mask_TTieta", &trig_strip_mask_TTieta);
  myChain->SetBranchAddress("trig_strip_mask_TTiphi", &trig_strip_mask_TTiphi);
  myChain->SetBranchAddress("trig_strip_mask_StripID", &trig_strip_mask_StripID);
  myChain->SetBranchAddress("trig_strip_mask_PseudoStripID", &trig_strip_mask_PseudoStripID);
  myChain->SetBranchAddress("trig_strip_mask_TccID", &trig_strip_mask_TccID);
  myChain->SetBranchAddress("trig_strip_mask_CCU", &trig_strip_mask_CCU);
  myChain->SetBranchAddress("trig_strip_mask_xtal_ix", &trig_strip_mask_xtal_ix);
  myChain->SetBranchAddress("trig_strip_mask_xtal_iy", &trig_strip_mask_xtal_iy);
  myChain->SetBranchAddress("trig_strip_mask_xtal_iz", &trig_strip_mask_xtal_iz);
  //
  // Crystal masking
  myChain->SetBranchAddress("trig_xtal_mask_N", &trig_xtal_mask_N);
  myChain->SetBranchAddress("trig_xtal_mask_ieta", &trig_xtal_mask_ieta);
  myChain->SetBranchAddress("trig_xtal_mask_iphi", &trig_xtal_mask_iphi);
  myChain->SetBranchAddress("trig_xtal_mask_TTieta", &trig_xtal_mask_TTieta);
  myChain->SetBranchAddress("trig_xtal_mask_TTiphi", &trig_xtal_mask_TTiphi);
  myChain->SetBranchAddress("trig_xtal_mask_Rieta", &trig_xtal_mask_Rieta);
  myChain->SetBranchAddress("trig_xtal_mask_Riphi", &trig_xtal_mask_Riphi);
  myChain->SetBranchAddress("trig_xtal_mask_status", &trig_xtal_mask_status);
  myChain->SetBranchAddress("trig_xtal_mask_EBEE", &trig_xtal_mask_EBEE);

  // Masking
  myChain->SetBranchAddress("trig_nMaskedRCT",      &trig_nMaskedRCT);      
  myChain->SetBranchAddress("trig_iMaskedRCTeta",   &trig_iMaskedRCTeta);                                          
  myChain->SetBranchAddress("trig_iMaskedRCTcrate", &trig_iMaskedRCTcrate);
  myChain->SetBranchAddress("trig_iMaskedRCTphi",   &trig_iMaskedRCTphi);
  myChain->SetBranchAddress("trig_nMaskedCh",       &trig_nMaskedCh);    
  myChain->SetBranchAddress("trig_iMaskedTTeta",    &trig_iMaskedTTeta);   
  myChain->SetBranchAddress("trig_iMaskedTTphi",    &trig_iMaskedTTphi);      	


  if(debug) cout << "got the input tree, start to define output tree" << endl;
  
  // OUTPUT TREE //
  TTree * outtree = new TTree("ElePairs","ElePairs");

  // General informations
  outtree->Branch("nRun",&nRun,"nRun/I");
  outtree->Branch("nLumi",&nLumi,"nLumi/I");
  outtree->Branch("nEvent",&nEvent,"nEvent/I");

  // Vertices
  outtree->Branch("vtx_N",&_vtx_N,"vtx_N/I");
  outtree->Branch("vtx_normalizedChi2",&_vtx_normalizedChi2,"vtx_normalizedChi2[200]/D");
  outtree->Branch("vtx_ndof",&_vtx_ndof,"vtx_ndof[200]/D");
  outtree->Branch("vtx_nTracks",&_vtx_nTracks,"vtx_nTracks[200]/D");
  outtree->Branch("vtx_d0",&_vtx_d0,"vtx_d0[200]/D");
  outtree->Branch("vtx_x",&_vtx_x,"vtx_x[200]/D");
  outtree->Branch("vtx_y",&_vtx_y,"vtx_y[200]/D");
  outtree->Branch("vtx_z",&_vtx_z,"vtx_z[200]/D");

  // HLT informations
//   outtree->Branch ("trig_HLT_triggered", &m_HLT_triggered, 256000,0);
//   outtree->Branch ("trig_HLT_pathsV", &m_HLT_pathsV, 256000,0);
//   outtree->Branch ("trig_HLT_pathsV_check", &m_HLT_pathsV_check, 256000,0);
  //
  outtree->Branch("trig_HLT_path",&trig_HLT_path,"trig_HLT_path[4]/I");
  // unbias, EG5, EG8, EG12
  //
  outtree->Branch("trig_fired_names",&trig_fired_names,"trig_fired_names[5000]/C");
  outtree->Branch("trig_hltInfo",&trig_hltInfo,"trig_hltInfo[250]/I");  

  // Trigger towers
  outtree->Branch("trig_tower_N",&trig_tower_N,"trig_tower_N/I");
  outtree->Branch("trig_tower_ieta",&trig_tower_ieta,"trig_tower_ieta[4032]/I");
  outtree->Branch("trig_tower_iphi",&trig_tower_iphi,"trig_tower_iphi[4032]/I");
  outtree->Branch("trig_tower_adc",&trig_tower_adc,"trig_tower_adc[4032]/I");
  outtree->Branch("trig_tower_sFGVB",&trig_tower_sFGVB,"trig_tower_sFGVB[4032]/I");
  //
  outtree->Branch("trig_tower_N_modif",&trig_tower_N_modif,"trig_tower_N_modif/I");
  outtree->Branch("trig_tower_ieta_modif",&trig_tower_ieta_modif,"trig_tower_ieta_modif[4032]/I");
  outtree->Branch("trig_tower_iphi_modif",&trig_tower_iphi_modif,"trig_tower_iphi_modif[4032]/I");
  outtree->Branch("trig_tower_adc_modif",&trig_tower_adc_modif,"trig_tower_adc_modif[4032]/I");
  outtree->Branch("trig_tower_sFGVB_modif",&trig_tower_sFGVB_modif,"trig_tower_sFGVB_modif[4032]/I");
  //
  outtree->Branch("trig_tower_N_emul",&trig_tower_N_emul,"trig_tower_N_emul/I");
  outtree->Branch("trig_tower_ieta_emul",&trig_tower_ieta_emul,"trig_tower_ieta_emul[4032]/I");
  outtree->Branch("trig_tower_iphi_emul",&trig_tower_iphi_emul,"trig_tower_iphi_emul[4032]/I");
  outtree->Branch("trig_tower_adc_emul",&trig_tower_adc_emul,"trig_tower_adc_emul[4032][5]/I");
  outtree->Branch("trig_tower_sFGVB_emul",&trig_tower_sFGVB_emul,"trig_tower_sFGVB_emul[4032][5]/I");

  // HCAL TP
  outtree->Branch("trig_tower_hcal_N", &trig_tower_hcal_N, "trig_tower_hcal_N/I");
  outtree->Branch("trig_tower_hcal_ieta",  &trig_tower_hcal_ieta,  "trig_tower_hcal_ieta[trig_tower_N]/I");
  outtree->Branch("trig_tower_hcal_iphi",  &trig_tower_hcal_iphi,  "trig_tower_hcal_iphi[trig_tower_N]/I");
  outtree->Branch("trig_tower_hcal_et",  &trig_tower_hcal_et,  "trig_tower_hcal_et[trig_tower_N]/I");
  outtree->Branch("trig_tower_hcal_FG",  &trig_tower_hcal_FG,  "trig_tower_hcal_FG[trig_tower_N]/I");

  // Strip masking
  outtree->Branch("trig_strip_mask_N", &trig_strip_mask_N, "trig_strip_mask_N/I");
  outtree->Branch("trig_strip_mask_TTieta", &trig_strip_mask_TTieta, "trig_strip_mask_TTieta[trig_strip_mask_N]/I");
  outtree->Branch("trig_strip_mask_TTiphi", &trig_strip_mask_TTiphi, "trig_strip_mask_TTiphi[trig_strip_mask_N]/I");
  outtree->Branch("trig_strip_mask_StripID", &trig_strip_mask_StripID, "trig_strip_mask_StripID[trig_strip_mask_N]/I");
  outtree->Branch("trig_strip_mask_PseudoStripID", &trig_strip_mask_PseudoStripID, "trig_strip_mask_PseudoStripID[trig_strip_mask_N]/I");
  outtree->Branch("trig_strip_mask_TccID", &trig_strip_mask_TccID, "trig_strip_mask_TccID[trig_strip_mask_N]/I");
  outtree->Branch("trig_strip_mask_CCU", &trig_strip_mask_CCU, "trig_strip_mask_CCU[trig_strip_mask_N]/I");
  outtree->Branch("trig_strip_mask_xtal_ix", &trig_strip_mask_xtal_ix, "trig_strip_mask_xtal_ix[trig_strip_mask_N][5]/I");
  outtree->Branch("trig_strip_mask_xtal_iy", &trig_strip_mask_xtal_iy, "trig_strip_mask_xtal_iy[trig_strip_mask_N][5]/I");
  outtree->Branch("trig_strip_mask_xtal_iz", &trig_strip_mask_xtal_iz, "trig_strip_mask_xtal_iz[trig_strip_mask_N][5]/I");
  //
  // Crystal masking
  outtree->Branch("trig_xtal_mask_N", &trig_xtal_mask_N, "trig_xtal_mask_N/I");
  outtree->Branch("trig_xtal_mask_ieta", &trig_xtal_mask_ieta, "trig_xtal_mask_ieta[trig_xtal_mask_N]/I");
  outtree->Branch("trig_xtal_mask_iphi", &trig_xtal_mask_iphi, "trig_xtal_mask_iphi[trig_xtal_mask_N]/I");
  outtree->Branch("trig_xtal_mask_TTieta", &trig_xtal_mask_TTieta, "trig_xtal_mask_TTieta[trig_xtal_mask_N]/I");
  outtree->Branch("trig_xtal_mask_TTiphi", &trig_xtal_mask_TTiphi, "trig_xtal_mask_TTiphi[trig_xtal_mask_N]/I");
  outtree->Branch("trig_xtal_mask_Rieta", &trig_xtal_mask_Rieta, "trig_xtal_mask_Rieta[trig_xtal_mask_N]/I");
  outtree->Branch("trig_xtal_mask_Riphi", &trig_xtal_mask_Riphi, "trig_xtal_mask_Riphi[trig_xtal_mask_N]/I");
  outtree->Branch("trig_xtal_mask_status", &trig_xtal_mask_status, "trig_xtal_mask_status[trig_xtal_mask_N]/I");
  outtree->Branch("trig_xtal_mask_EBEE", &trig_xtal_mask_EBEE, "trig_xtal_mask_EBEE[trig_xtal_mask_N]/I");
  // L1 candidates
  outtree->Branch("trig_L1emIso_N",     &trig_L1emIso_N,     "trig_L1emIso_N/I");
  outtree->Branch("trig_L1emIso_ieta",  &trig_L1emIso_ieta,  "trig_L1emIso_ieta[4]/I");
  outtree->Branch("trig_L1emIso_iphi",  &trig_L1emIso_iphi,  "trig_L1emIso_iphi[4]/I");
  outtree->Branch("trig_L1emIso_rank",  &trig_L1emIso_rank,  "trig_L1emIso_rank[4]/I");
  //outtree->Branch("trig_L1emIso_eta",   &trig_L1emIso_eta,   "trig_L1emIso_eta[4]/D");
  //outtree->Branch("trig_L1emIso_phi",   &trig_L1emIso_phi,   "trig_L1emIso_phi[4]/D");
//   outtree->Branch("trig_L1emIso_energy",&trig_L1emIso_energy,"trig_L1emIso_energy[4]/D");
//   outtree->Branch("trig_L1emIso_et",    &trig_L1emIso_et,    "trig_L1emIso_et[4]/D");
  //
  outtree->Branch("trig_L1emNonIso_N",     &trig_L1emNonIso_N,     "trig_L1emNonIso_N/I");
  outtree->Branch("trig_L1emNonIso_ieta",  &trig_L1emNonIso_ieta,  "trig_L1emNonIso_ieta[4]/I");
  outtree->Branch("trig_L1emNonIso_iphi",  &trig_L1emNonIso_iphi,  "trig_L1emNonIso_iphi[4]/I");
  outtree->Branch("trig_L1emNonIso_rank",  &trig_L1emNonIso_rank,  "trig_L1emNonIso_rank[4]/I");
//   outtree->Branch("trig_L1emNonIso_eta",   &trig_L1emNonIso_eta,   "trig_L1emNonIso_eta[4]/D");
//   outtree->Branch("trig_L1emNonIso_phi",   &trig_L1emNonIso_phi,   "trig_L1emNonIso_phi[4]/D");
//   outtree->Branch("trig_L1emNonIso_energy",&trig_L1emNonIso_energy,"trig_L1emNonIso_energy[4]/D");
//   outtree->Branch("trig_L1emNonIso_et",    &trig_L1emNonIso_et,    "trig_L1emNonIso_et[4]/D");
  //
  outtree->Branch("trig_L1emIso_N_M",     &trig_L1emIso_N_M,     "trig_L1emIso_N_M/I");
  outtree->Branch("trig_L1emIso_ieta_M",  &trig_L1emIso_ieta_M,  "trig_L1emIso_ieta_M[4]/I");
  outtree->Branch("trig_L1emIso_iphi_M",  &trig_L1emIso_iphi_M,  "trig_L1emIso_iphi_M[4]/I");
  outtree->Branch("trig_L1emIso_rank_M",  &trig_L1emIso_rank_M,  "trig_L1emIso_rank_M[4]/I");
//   outtree->Branch("trig_L1emIso_eta_M",   &trig_L1emIso_eta_M,   "trig_L1emIso_eta_M[4]/D");
//   outtree->Branch("trig_L1emIso_phi_M",   &trig_L1emIso_phi_M,   "trig_L1emIso_phi_M[4]/D");
//   outtree->Branch("trig_L1emIso_energy_M",&trig_L1emIso_energy_M,"trig_L1emIso_energy_M[4]/D");
//   outtree->Branch("trig_L1emIso_et_M",    &trig_L1emIso_et_M,    "trig_L1emIso_et_M[4]/D");
  //
  outtree->Branch("trig_L1emNonIso_N_M", &trig_L1emNonIso_N_M, "trig_L1emNonIso_N_M/I");
  outtree->Branch("trig_L1emNonIso_ieta_M", &trig_L1emNonIso_ieta_M, "trig_L1emNonIso_ieta_M[4]/I");
  outtree->Branch("trig_L1emNonIso_iphi_M", &trig_L1emNonIso_iphi_M, "trig_L1emNonIso_iphi_M[4]/I");
  outtree->Branch("trig_L1emNonIso_rank_M", &trig_L1emNonIso_rank_M, "trig_L1emNonIso_rank_M[4]/I");
//   outtree->Branch("trig_L1emNonIso_eta_M", &trig_L1emNonIso_eta_M, "trig_L1emNonIso_eta_M[4]/D");
//   outtree->Branch("trig_L1emNonIso_phi_M", &trig_L1emNonIso_phi_M, "trig_L1emNonIso_phi_M[4]/D");
//   outtree->Branch("trig_L1emNonIso_energy_M",&trig_L1emNonIso_energy_M,"trig_L1emNonIso_energy_M[4]/D");
//   outtree->Branch("trig_L1emNonIso_et_M", &trig_L1emNonIso_et_M, "trig_L1emNonIso_et_M[4]/D");

  // pre-post firing L1 candidates
  outtree->Branch("trig_preL1emIso_N",     &trig_preL1emIso_N,     "trig_preL1emIso_N/I");
  outtree->Branch("trig_preL1emIso_ieta",  &trig_preL1emIso_ieta,  "trig_preL1emIso_ieta[4]/I");
  outtree->Branch("trig_preL1emIso_iphi",  &trig_preL1emIso_iphi,  "trig_preL1emIso_iphi[4]/I");
  outtree->Branch("trig_preL1emIso_rank",  &trig_preL1emIso_rank,  "trig_preL1emIso_rank[4]/I");
  //
  outtree->Branch("trig_preL1emNonIso_N",     &trig_preL1emNonIso_N,     "trig_preL1emNonIso_N/I");
  outtree->Branch("trig_preL1emNonIso_ieta",  &trig_preL1emNonIso_ieta,  "trig_preL1emNonIso_ieta[4]/I");
  outtree->Branch("trig_preL1emNonIso_iphi",  &trig_preL1emNonIso_iphi,  "trig_preL1emNonIso_iphi[4]/I");
  outtree->Branch("trig_preL1emNonIso_rank",  &trig_preL1emNonIso_rank,  "trig_preL1emNonIso_rank[4]/I");
  //
  outtree->Branch("trig_postL1emIso_N",     &trig_postL1emIso_N,     "trig_postL1emIso_N/I");
  outtree->Branch("trig_postL1emIso_ieta",  &trig_postL1emIso_ieta,  "trig_postL1emIso_ieta[4]/I");
  outtree->Branch("trig_postL1emIso_iphi",  &trig_postL1emIso_iphi,  "trig_postL1emIso_iphi[4]/I");
  outtree->Branch("trig_postL1emIso_rank",  &trig_postL1emIso_rank,  "trig_postL1emIso_rank[4]/I");
  //
  outtree->Branch("trig_postL1emNonIso_N",     &trig_postL1emNonIso_N,     "trig_postL1emNonIso_N/I");
  outtree->Branch("trig_postL1emNonIso_ieta",  &trig_postL1emNonIso_ieta,  "trig_postL1emNonIso_ieta[4]/I");
  outtree->Branch("trig_postL1emNonIso_iphi",  &trig_postL1emNonIso_iphi,  "trig_postL1emNonIso_iphi[4]/I");
  outtree->Branch("trig_postL1emNonIso_rank",  &trig_postL1emNonIso_rank,  "trig_postL1emNonIso_rank[4]/I");
  //
  outtree->Branch("trig_nMaskedRCT",      &trig_nMaskedRCT,     "trig_nMaskedRCT/I");      
  outtree->Branch("trig_iMaskedRCTeta",   &trig_iMaskedRCTeta,  "trig_iMaskedRCTeta[trig_nMaskedRCT]/I");                                          
  outtree->Branch("trig_iMaskedRCTcrate", &trig_iMaskedRCTcrate,"trig_iMaskedRCTcrate[trig_nMaskedRCT]/I");                                                    
  outtree->Branch("trig_iMaskedRCTphi",   &trig_iMaskedRCTphi,  "trig_iMaskedRCTphi[trig_nMaskedRCT]/I");
  outtree->Branch("trig_nMaskedCh",       &trig_nMaskedCh,      "trig_nMaskedCh/I");    
  outtree->Branch("trig_iMaskedTTeta",    &trig_iMaskedTTeta,   "trig_iMaskedTTeta[trig_nMaskedCh]/I");   
  outtree->Branch("trig_iMaskedTTphi",    &trig_iMaskedTTphi,   "trig_iMaskedTTphi[trig_nMaskedCh]/I");      	


  // Pairs informations
  double pair_M;
  double pair_eta[2], pair_sclEta[2], pair_sclEt[2], pair_phi[2], pair_pT[2], pair_eT[2], pair_E[2];
  int pair_cuts[2], pair_HLT_Ele27_cut[2], pair_fidu[2], pair_charge[2], pair_RCTeta[2], pair_RCTphi[2], 
    pair_L1iso[2], pair_L1noniso[2], pair_L1iso_M[2], pair_L1noniso_M[2];
  int pair_RCTetaVect[2][10], pair_RCTphiVect[2][10], 
    pair_L1isoVect[2][10], pair_L1nonisoVect[2][10],pair_L1isoVect_M[2][10], pair_L1nonisoVect_M[2][10];
  double pair_RCTetVect[2][10];
  int pair_TTetaVect[2][50], pair_TTphiVect[2][50];
  double pair_TTetVect[2][50];

  //
  outtree->Branch("pair_M",&pair_M,"pair_M/D");
  //
  outtree->Branch("pair_cuts",&pair_cuts,"pair_cuts[2]/I");
  // 0 : noCut | 1 : VBTF 95 | 2 : VBTF 80 | 3 : VBTF 60
  outtree->Branch("pair_HLT_Ele27_cut",&pair_HLT_Ele27_cut,"pair_HLT_Ele27_cut[2]/I");
  outtree->Branch("pair_fidu",&pair_fidu,"pair_fidu[2]/I");
  //
  outtree->Branch("pair_eta",&pair_eta,"pair_eta[2]/D");
  outtree->Branch("pair_sclEta",&pair_sclEta,"pair_sclEta[2]/D");
  outtree->Branch("pair_phi",&pair_phi,"pair_phi[2]/D");
  outtree->Branch("pair_RCTeta",&pair_RCTeta,"pair_RCTeta[2]/I");
  outtree->Branch("pair_RCTphi",&pair_RCTphi,"pair_RCTphi[2]/I");
  //
  outtree->Branch("pair_charge",&pair_charge,"pair_charge[2]/I");
  outtree->Branch("pair_pT",&pair_pT,"pair_pT[2]/D");
  outtree->Branch("pair_eT",&pair_eT,"pair_eT[2]/D");
  outtree->Branch("pair_sclEt",&pair_sclEt,"pair_sclEt[2]/D");
  outtree->Branch("pair_E",&pair_E,"pair_E[2]/D");

  outtree->Branch("pair_TTetaVect", &pair_TTetaVect,"pair_TTetaVect[2][50]/I");
  outtree->Branch("pair_TTphiVect", &pair_TTphiVect,"pair_TTphiVect[2][50]/I");
  outtree->Branch("pair_TTetVect", &pair_TTetVect,"pair_TTetVect[2][50]/D");

  outtree->Branch("pair_L1iso",&pair_L1iso,"pair_L1iso[2]/I");
  outtree->Branch("pair_L1noniso",&pair_L1noniso,"pair_L1noniso[2]/I");
  outtree->Branch("pair_L1iso_M",&pair_L1iso_M,"pair_L1iso_M[2]/I");
  outtree->Branch("pair_L1noniso_M",&pair_L1noniso_M,"pair_L1noniso_M[2]/I");
  //
  outtree->Branch("pair_RCTetVect",&pair_RCTetVect,"pair_RCTetVect[2][10]/D");
  outtree->Branch("pair_RCTetaVect",&pair_RCTetaVect,"pair_RCTetaVect[2][10]/I");
  outtree->Branch("pair_RCTphiVect",&pair_RCTphiVect,"pair_RCTphiVect[2][10]/I");
  outtree->Branch("pair_L1isoVect",&pair_L1isoVect,"pair_L1isoVect[2][10]/I");
  outtree->Branch("pair_L1nonisoVect",&pair_L1nonisoVect,"pair_L1nonisoVect[2][10]/I");
  outtree->Branch("pair_L1isoVect_M",&pair_L1isoVect_M,"pair_L1isoVect_M[2][10]/I");
  outtree->Branch("pair_L1nonisoVect_M",&pair_L1nonisoVect_M,"pair_L1nonisoVect_M[2][10]/I");

  if(debug) cout << "output tree defined" << endl;

  // USEFUL VARIABLES //
  vector<int> pairIdx;
  int cutEle[2], fidu[2];
  bool cut_HLT_Ele27[2];
  TLorentzVector * cand[2];
  TLorentzVector total;
  bool isGoodRun;
  TString filename;

//  // JSON FILE READER //
//
//  string jsonDir = "/data_CMS/cms/ndaci/" ;
//  const int nJson = 10;
//  string jsonFile[nJson]; // 2010B, May10, Aug05, Prompt
//  map<int, vector<pair<int, int> > > jsonMap[nJson] ;
//
//  jsonFile[0] = jsonDir + "ndaci_2011A/JSON/goodrunlist_json.txt" ;
//  jsonFile[1] = jsonDir + "ndaci_2011A/JSON/Cert_160404-163869_7TeV_May10ReReco_Collisions11_JSON_v3.txt" ;
//  jsonFile[2] = jsonDir + "ndaci_2011A/JSON/Cert_170249-172619_7TeV_ReReco5Aug_Collisions11_JSON_v3.txt" ;
//  jsonFile[3] = jsonDir + "ndaci_2011A/JSON/Cert_160404-180252_7TeV_PromptReco_Collisions11_JSON.txt" ;
//  jsonFile[4] = jsonDir + "ndaci_2011A/JSON/Cert_160404-180252_7TeV_ReRecoNov08_Collisions11_JSON.txt" ;
//
//  // 2012
//  jsonFile[5] = jsonDir + "ndaci_2012/JSON/Cert_190456-203002_8TeV_PromptReco_Collisions12_JSON.txt";
//  jsonFile[6] = jsonDir + "ndaci_2012/JSON/Cert_190456-196531_8TeV_13Jul2012ReReco_Collisions12_JSON_v2.txt";
//  jsonFile[7] = jsonDir + "ndaci_2012/JSON/Cert_190782-190949_8TeV_06Aug2012ReReco_Collisions12_JSON.txt";
//  jsonFile[8] = jsonDir + "ndaci_2012/JSON/Cert_198022-198523_8TeV_24Aug2012ReReco_Collisions12_JSON.txt";
//  jsonFile[9] = jsonDir + "ndaci_2012/JSON/Cert_190456-208357_8TeV_PromptReco_Collisions12_JSON.txt";
//
//  for(int i=0 ; i<nJson ; i++)
//    jsonMap[i] = readJSONFile(jsonFile[i]);
//
//  if(debug) cout << "JSON defined" << endl;
if(debug) cout << "skipping JSON definition and JSON checks" << endl;


  // -------------------------------------------------------------------------------
  // LOOP OVER EVENTS
  // -------------------------------------------------------------------------------  
  if(debug) cout << "gonna loop over events" << endl;

  int numEntries = myChain->GetEntries () ;
  int nProcess = numEntries;
  if(nEntries>=0 && nEntries<numEntries)
    nProcess = nEntries;

  int nCurrentRun = -999;
  outlog << "will process " << nProcess << "/" << numEntries << "entries" << endl;

  for (int iEvent = 0 ; iEvent < nProcess ; iEvent++ )
    { 

      // HLT information
      for(int i=0 ; i<4 ; i++)
	trig_HLT_path[i]=0;
      
      for(int i=0 ; i<250 ; i++)
	trig_hltInfo[i]=0;

      // TP Initialization
      trig_tower_N = 0;
      for(int iTow=0 ; iTow<nTow ; iTow++) {
	trig_tower_ieta[iTow] = trig_tower_iphi[iTow]  = -999;
	trig_tower_adc[iTow]  = trig_tower_sFGVB[iTow] = -999;
      }
      trig_tower_N_modif = 0;
      for(int iTow=0 ; iTow<nTow ; iTow++) {
	trig_tower_ieta_modif[iTow] = trig_tower_iphi_modif[iTow]  = -999;
	trig_tower_adc_modif[iTow]  = trig_tower_sFGVB_modif[iTow] = -999;
      }
      trig_tower_N_emul = 0;
      for(int iTow=0 ; iTow<nTow ; iTow++) {
	trig_tower_ieta_emul[iTow] = trig_tower_iphi_emul[iTow] = -999;
	for(int i=0 ; i<5 ; i++)
	  trig_tower_adc_emul[iTow][i] = trig_tower_sFGVB_emul[iTow][i] = -999;
      }

      myChain->GetEntry (iEvent) ;
     
      // show processed file
      if(iEvent==0) {
        filename = myChain->GetFile()->GetName() ;
        outlog << "File : " << filename << endl << endl;
      }
      else if( filename != myChain->GetFile()->GetName() ) {
        filename = myChain->GetFile()->GetName() ;
        outlog << "File : " << myChain->GetFile()->GetName() << endl << endl;
      }
     
      // show current run/iCat processed
      if(iEvent==0) {
	nCurrentRun = nRun ;
	outlog << "nRun=" << nRun << endl;
      }
      else if(nRun!=nCurrentRun) {
	nCurrentRun=nRun ;
	outlog << "nRun=" << nRun << endl;
      }

//      // run selection (using both json files)
//      //int iJson = detJson(nRun);
//      //int iJson = 4;
//      if(debug) cout << "iJson = " << iJson << endl;
//      outlog << "iJson = " << iJson << endl;
//      if( iJson>-1 && iJson<9) {
//	isGoodRun = AcceptEventByRunAndLumiSection(nRun, nLumi, jsonMap[iJson]);
//	if(!isGoodRun) {
//	  outlog << "failed JSON" << endl;
//	  continue;
//	}
//      }
//      else {
//	outlog << "no proper JSON file" << endl;
//	//continue;
//      }

      // at least 2 electrons
      if(ele_N<2) continue;
      else outlog << "ele_N=" << ele_N << endl;

      // LOOP OVER ELECTRONS //
      if(debug) cout << "<-- ele_N=" << ele_N << endl
		     << "--- electrons.size=" << electrons->GetSize() << endl;
      for( int iEle1=0 ; iEle1<ele_N ; iEle1++ ) {
	if(debug) cout << "--- get ele #" << iEle1 << endl;
	cand[0] = (TLorentzVector*) (electrons->At (iEle1)) ;
	if(debug) cout << "--- got it" << endl;

	// severity selection
	if( ele_severityLevelSeed[iEle1] >= 3 ) continue;
	
	// check whether electrons of the pair pass HLT_Ele27 Id/Iso cuts
	if(debug) cout << "--- checks VBTF cuts" << endl;
	cut_HLT_Ele27[0] = VBTFcuts( "HLT_Ele27", RunPhase,
				     cand[0]->Pt(), cand[0]->Et(), ele_sclEta[iEle1], cand[0]->Eta(), ele_tkSumPt_dr03[iEle1], ele_ecalRecHitSumEt_dr03[iEle1], 
				     ele_hcalDepth1TowerSumEt_dr03[iEle1], ele_hcalDepth2TowerSumEt_dr03[iEle1], ele_expected_inner_hits[iEle1],
				     ele_deltaphiin[iEle1], ele_deltaetain[iEle1], ele_he[iEle1], ele_sigmaietaieta[iEle1],
				     ele_conv_dist[iEle1], ele_conv_dcot[iEle1], ele_fbrem[iEle1], ele_isConversion[iEle1] ) ;

	// check if ele is a good tag candidate : pass VBTF 95 and has pT>5 GeV
	cutEle[0] = 0;
	cutEle[0] = whichCuts( RunPhase, cand[0]->Pt(), cand[0]->Et(), ele_sclEta[iEle1], cand[0]->Eta(), ele_tkSumPt_dr03[iEle1], ele_ecalRecHitSumEt_dr03[iEle1], 
			       ele_hcalDepth1TowerSumEt_dr03[iEle1], ele_hcalDepth2TowerSumEt_dr03[iEle1], ele_expected_inner_hits[iEle1],
			       ele_deltaphiin[iEle1], ele_deltaetain[iEle1], ele_he[iEle1], ele_sigmaietaieta[iEle1],
			       ele_conv_dist[iEle1], ele_conv_dcot[iEle1], ele_fbrem[iEle1], ele_isConversion[iEle1] ) ;
	fidu[0] = 0;
	if ( fabs(ele_sclEta[iEle1]) < 2.5 && ( fabs(ele_sclEta[iEle1]) > 1.566 || fabs(ele_sclEta[iEle1])<1.4442 ) ) 
	  fidu[0] = 1 ;

	if( cutEle[0]>0 && cand[0]->Et()>=5. ) {
	  if(debug) cout << "--- ele #" << iEle1 << " is a good tag candidate" << endl;
	  
	  // loop to find probe candidates
	  for( int iEle2=0 ; iEle2<ele_N ; iEle2++ ) {
	    if(debug) cout << "----- looks Ele #" << iEle2 << endl;

	    cand[1] = (TLorentzVector*) (electrons->At (iEle2)) ;

	    // severity
	    if( ele_severityLevelSeed[iEle2] >= 3 ) continue;

	    // check HLT_Ele27 cuts
	    cut_HLT_Ele27[1] = VBTFcuts( "HLT_Ele27", RunPhase,
					 cand[1]->Pt(), cand[1]->Et(), ele_sclEta[iEle1], cand[1]->Eta(), ele_tkSumPt_dr03[iEle1], ele_ecalRecHitSumEt_dr03[iEle1], 
					 ele_hcalDepth1TowerSumEt_dr03[iEle1], ele_hcalDepth2TowerSumEt_dr03[iEle1], ele_expected_inner_hits[iEle1],
					 ele_deltaphiin[iEle1], ele_deltaetain[iEle1], ele_he[iEle1], ele_sigmaietaieta[iEle1],
					 ele_conv_dist[iEle1], ele_conv_dcot[iEle1], ele_fbrem[iEle1], ele_isConversion[iEle1] ) ;
	    

	    // check cuts passed by probe candidate
	    cutEle[1] = whichCuts( RunPhase, cand[1]->Pt(), cand[0]->Et(), ele_sclEta[iEle2], cand[1]->Eta(), ele_tkSumPt_dr03[iEle2], ele_ecalRecHitSumEt_dr03[iEle2], 
				   ele_hcalDepth1TowerSumEt_dr03[iEle2], ele_hcalDepth2TowerSumEt_dr03[iEle2], ele_expected_inner_hits[iEle2],
				   ele_deltaphiin[iEle2], ele_deltaetain[iEle2], ele_he[iEle2], ele_sigmaietaieta[iEle2],
				   ele_conv_dist[iEle2], ele_conv_dcot[iEle2], ele_fbrem[iEle2], ele_isConversion[iEle2] ) ;
	    fidu[1] = 0;
	    if ( fabs(ele_sclEta[iEle2]) < 2.5 && ( fabs(ele_sclEta[iEle2]) > 1.566 || fabs(ele_sclEta[iEle2])<1.4442 ) ) 
	      fidu[1] = 1 ;

	    if( cutEle[1]>0 && iEle2<=iEle1 ) continue; // prevents to create several times the same pair

	    if(debug) cout << "---> OK to form a pre-selected pair <--" << endl;

	    // get the pair informations
	    total = (*cand[0]) + (*cand[1]) ;

	    // keep only pairs with Mee > 30 GeV
	    if( total.M() < 30. ) continue; 

	    pair_M = total.M() ;

	    pairIdx.clear();
	    pairIdx.push_back(iEle1);
	    pairIdx.push_back(iEle2);

	    for(int iP=0 ; iP<2 ; iP++) {

	      pair_cuts[iP] = cutEle[iP];
	      pair_fidu[iP] = fidu[iP];
	      pair_HLT_Ele27_cut[iP] = cut_HLT_Ele27[iP];
	      //
	      pair_eta[iP] = cand[iP]->Eta();
	      pair_sclEta[iP] = ele_sclEta[pairIdx[iP]];
	      pair_phi[iP] = cand[iP]->Phi();
	      pair_RCTeta[iP] = ele_RCTeta[pairIdx[iP]];
	      pair_RCTphi[iP] = ele_RCTphi[pairIdx[iP]];
	      //
	      pair_charge[iP] = ele_echarge[pairIdx[iP]];
	      pair_pT[iP] = cand[iP]->Pt();
	      pair_eT[iP] = cand[iP]->Et();
	      pair_sclEt[iP] = ele_sclEt[pairIdx[iP]];
	      pair_E[iP] = cand[iP]->E();
	      //
	      pair_L1iso[iP] = ele_RCTL1iso[pairIdx[iP]];
	      pair_L1noniso[iP] = ele_RCTL1noniso[pairIdx[iP]];
	      pair_L1iso_M[iP] = ele_RCTL1iso_M[pairIdx[iP]];
 	      pair_L1noniso_M[iP] = ele_RCTL1noniso_M[pairIdx[iP]];
	      //
	      for(int iV=0 ; iV<10 ; iV++) {
		pair_RCTetVect[iP][iV] = ele_RCTetVect[pairIdx[iP]][iV];
		pair_RCTetaVect[iP][iV] = ele_RCTetaVect[pairIdx[iP]][iV];
		pair_RCTphiVect[iP][iV] = ele_RCTphiVect[pairIdx[iP]][iV]; 
		pair_L1isoVect[iP][iV] = ele_RCTL1isoVect[pairIdx[iP]][iV]; 
		pair_L1nonisoVect[iP][iV] = ele_RCTL1nonisoVect[pairIdx[iP]][iV];
 		pair_L1isoVect_M[iP][iV] = ele_RCTL1isoVect_M[pairIdx[iP]][iV];
 		pair_L1nonisoVect_M[iP][iV] = ele_RCTL1nonisoVect_M[pairIdx[iP]][iV];
	      } 
	      //
	      for(int iV=0 ; iV<50 ; iV++) {
		pair_TTetaVect[iP][iV] = ele_TTetaVect[pairIdx[iP]][iV];
		pair_TTphiVect[iP][iV] = ele_TTphiVect[pairIdx[iP]][iV];
		pair_TTetVect[iP][iV] = ele_TTetVect[pairIdx[iP]][iV];
	      }
	    }
	    if(debug) cout << "outtree->Fill();" << endl;
	    outtree->Fill();

	  } // loop for probe
	} // endif ele1 is good tag candidate
      } // loop over electrons
     
    }//loop over events

  if(debug) cout << "End loop events" << endl;
  outlog << "End loop events" << endl;

  // Record tree
  if(debug) cout << "recording tree..." << endl;
  outlog << "recording tree..." << endl;

  outtree->Write();

  if(debug) cout << "recorded !" << endl;
  outlog << "recorded !" << endl;

  outfile->Close();

  if(debug) cout << "file closed." << endl;
  outlog << "file closed." << endl;

  return 1;

}
Exemple #19
0
void Campaign4Example()
{
    std::ostringstream os;
    std::string path = "../../data/ds10/data/test_processing/Run";
    std::vector<int> run_id_list;   
    run_id_list.push_back(3007);
    run_id_list.push_back(3008);
    	
    TChain *chain = new TChain("Events");

    if (! USE_DB)
    {
	std::cout<<"WARNING: Database access disabled ! Make sure to check run list manually"<<std::endl;
    }
    //Check runs for validity and add them to the TChain
    for(vector<int>::const_iterator it = run_id_list.begin(); it != run_id_list.end(); it++)
    {
	if (USE_DB)
	{
	    if ( ! DB_does_run_exist("rundb", "daqruns", *it))
	    {
		std::cout<<"Run "<<(*it)<<" does not exist in the database"<<std::endl;
		continue;
	    }
	    
	    if(DB_get_string("rundb", "daqruns", *it, "comment").find("HARDWARE_ISSUE") != string::npos) 
	    {
		std::cout << "Run" << *it << " has HARDWARE ISSUES. Skipping ..." <<std::endl;
		continue;
	    }       
	    
	    if(DB_get_string("rundb", "daqruns", *it, "type").find("laser") == string::npos 
	       && DB_get_string("rundb", "daqruns", *it, "type").find("*junk") == string::npos 
	       && DB_get_string("rundb", "daqruns", *it, "type").find("darkbox") == string::npos 
	       && DB_get_string("rundb", "daqruns", *it, "type").find("other") == string::npos)
		
	    {
		os.str("");
		os << path << setw(6) << setfill('0') << *it << ".root";
		chain->Add(os.str().c_str());
	    }
	}
	else
	{
	    os.str("");
	    os << path << setw(6) << setfill('0') << *it << ".root";
	    chain->Add(os.str().c_str());
	}
    }

    //Create EventData object to store information from ROOT TTree
    EventData* event = NULL;
    chain->SetBranchAddress("event", &event);
    int n_events = chain->GetEntries();

    //Create output histograms
    TFile* f = new TFile ("Run4example.root", "RECREATE");
    TH1F* s1_hist = new TH1F("s1_hist", "S1 Spectrum", 100, 0, 2000);
    TH2F* s2s1_f90_hist = new TH2F("s2s1_f90_hist", "Log(S2/S1) vs F90", 100, 0, 1, 100, -3, 3.2);

    //Loop over all events in TTree
    for(int n = 0; n < n_events; n = n + 1)
    {
		
        if ( n % 10000 == 0)
            std::cout<<"Processing Event: "<<n<<"/"<<n_events<<std::endl;
        
        chain->GetEntry(n);
        
	//Identify S1 and S2 pulses
	Int_t s1_pulse_number;
	std::vector<Int_t> s2_pulse_number;
	s1s2_Identifier(event, s1_pulse_number, s2_pulse_number);
	

	if (s1_pulse_number == -1)
	    continue;
	
	Int_t s2_multiplicity = s2_pulse_number.size();
	if (s2_multiplicity != 1)
	    continue;

	//Calculate energies
	Double_t s1_fixed = -1;
	if (event->sum_of_int[s1_pulse_number].fixed_npe1_valid)
	    s1_fixed = event->sum_of_int[s1_pulse_number].fixed_npe1;

	
	Double_t s2_fixed = -1;
	if (event->sum_of_int[s2_pulse_number[0]].fixed_npe2_valid)
	    s2_fixed = event->sum_of_int[s2_pulse_number[0]].fixed_npe2;
       

	//Calculate drift time
        Double_t t_drift = -1;
	if (s2_multiplicity > 0)
	    t_drift = drift_time_eval (event, s1_pulse_number, s2_pulse_number[0]);
	
	//CUTS
	if ( start_time(event) 
	     && more_one_pulses(event) 
	     && nosat(event) 
	     && nodesync(event) 
	     && s1_fixed > 4. 
	     && s1_fixed < 600. 
	     && s2_multiplicity == 1 
	     && s2_fixed > 10. 
	     && t_drift > 10. 
	     && t_drift < 85.
	     && ! late_peak (event, s1_pulse_number))
	{
	    s1_hist->Fill(s1_fixed);
	    s2s1_f90_hist->Fill(event->sum_of_int[s1_pulse_number].f90, TMath::Log10(s2_fixed/s1_fixed));
	}
    }//Finish loop over events

    s1_hist->Write();
    s2s1_f90_hist->Write();
    f->Close();
}
// The actual job
void backgroundFits_qqzz_1Dw(int channel, int sqrts, int VBFtag)
{
  if(sqrts==7)return;
  TString schannel;
  if      (channel == 1) schannel = "4mu";
  else if (channel == 2) schannel = "4e";
  else if (channel == 3) schannel = "2e2mu";
  else cout << "Not a valid channel: " << schannel << endl;

  TString ssqrts = (long) sqrts + TString("TeV");

  cout << "schannel = " << schannel << "  sqrts = " << sqrts << " VBFtag = " << VBFtag << endl;

  TString outfile;
  if(VBFtag<2) outfile = "CardFragments/qqzzBackgroundFit_" + ssqrts + "_" + schannel + "_" + Form("%d",int(VBFtag)) + ".txt";
  if(VBFtag==2) outfile = "CardFragments/qqzzBackgroundFit_" + ssqrts + "_" + schannel + ".txt";
  ofstream of(outfile,ios_base::out);
  of << "### background functions ###" << endl;


  gSystem->AddIncludePath("-I$ROOFITSYS/include");
  gROOT->ProcessLine(".L ../CreateDatacards/include/tdrstyle.cc");
  setTDRStyle(false);
  gStyle->SetPadLeftMargin(0.16);

  TString filepath;
  if (sqrts==7) {
    filepath = filePath7TeV;
  } else if (sqrts==8) {
    filepath = filePath8TeV;
  }

  TChain* tree = new TChain("SelectedTree");
  tree->Add( filepath+ "/" + (schannel=="2e2mu"?"2mu2e":schannel) + "/HZZ4lTree_ZZTo*.root");


  RooRealVar* MC_weight = new RooRealVar("MC_weight","MC_weight",0.,2.) ; 
  RooRealVar* ZZMass = new RooRealVar("ZZMass","ZZMass",100.,1000.);
  RooRealVar* NJets30 = new RooRealVar("NJets30","NJets30",0.,100.);
  RooArgSet ntupleVarSet(*ZZMass,*NJets30,*MC_weight);
  RooDataSet *set = new RooDataSet("set","set",ntupleVarSet,WeightVar("MC_weight"));

  Float_t myMC,myMass;
  Short_t myNJets;
  int nentries = tree->GetEntries();

  tree->SetBranchAddress("ZZMass",&myMass);
  tree->SetBranchAddress("MC_weight",&myMC);
  tree->SetBranchAddress("NJets30",&myNJets);

  for(int i =0;i<nentries;i++) {
    tree->GetEntry(i);
    if(VBFtag==1 && myNJets<2)continue;
    if(VBFtag==0 && myNJets>1)continue;

    ntupleVarSet.setRealValue("ZZMass",myMass);
    ntupleVarSet.setRealValue("MC_weight",myMC);
    ntupleVarSet.setRealValue("NJets30",(double)myNJets);

    set->add(ntupleVarSet, myMC);
  }

  double totalweight = 0.;
  double totalweight_z = 0.;
  for (int i=0 ; i<set->numEntries() ; i++) { 
    //set->get(i) ; 
    RooArgSet* row = set->get(i) ;
    //row->Print("v");
    totalweight += set->weight();
    if (row->getRealValue("ZZMass") < 200) totalweight_z += set->weight();
  } 
  cout << "nEntries: " << set->numEntries() << ", totalweight: " << totalweight << ", totalweight_z: " << totalweight_z << endl;

  gSystem->Load("libHiggsAnalysisCombinedLimit.so");
	
  //// ---------------------------------------
  //Background
  RooRealVar CMS_qqzzbkg_a0("CMS_qqzzbkg_a0","CMS_qqzzbkg_a0",115.3,0.,200.);
  RooRealVar CMS_qqzzbkg_a1("CMS_qqzzbkg_a1","CMS_qqzzbkg_a1",21.96,0.,200.);
  RooRealVar CMS_qqzzbkg_a2("CMS_qqzzbkg_a2","CMS_qqzzbkg_a2",122.8,0.,200.);
  RooRealVar CMS_qqzzbkg_a3("CMS_qqzzbkg_a3","CMS_qqzzbkg_a3",0.03479,0.,1.);
  RooRealVar CMS_qqzzbkg_a4("CMS_qqzzbkg_a4","CMS_qqzzbkg_a4",185.5,0.,200.);
  RooRealVar CMS_qqzzbkg_a5("CMS_qqzzbkg_a5","CMS_qqzzbkg_a5",12.67,0.,200.);
  RooRealVar CMS_qqzzbkg_a6("CMS_qqzzbkg_a6","CMS_qqzzbkg_a6",34.81,0.,100.);
  RooRealVar CMS_qqzzbkg_a7("CMS_qqzzbkg_a7","CMS_qqzzbkg_a7",0.1393,0.,1.);
  RooRealVar CMS_qqzzbkg_a8("CMS_qqzzbkg_a8","CMS_qqzzbkg_a8",66.,0.,200.);
  RooRealVar CMS_qqzzbkg_a9("CMS_qqzzbkg_a9","CMS_qqzzbkg_a9",0.07191,0.,1.);
  RooRealVar CMS_qqzzbkg_a10("CMS_qqzzbkg_a10","CMS_qqzzbkg_a10",94.11,0.,200.);
  RooRealVar CMS_qqzzbkg_a11("CMS_qqzzbkg_a11","CMS_qqzzbkg_a11",-5.111,-100.,100.);
  RooRealVar CMS_qqzzbkg_a12("CMS_qqzzbkg_a12","CMS_qqzzbkg_a12",4834,0.,10000.);
  RooRealVar CMS_qqzzbkg_a13("CMS_qqzzbkg_a13","CMS_qqzzbkg_a13",0.2543,0.,1.);
	
  if (channel == 1){
    ///* 4mu
    CMS_qqzzbkg_a0.setVal(103.854);
    CMS_qqzzbkg_a1.setVal(10.0718);
    CMS_qqzzbkg_a2.setVal(117.551);
    CMS_qqzzbkg_a3.setVal(0.0450287);
    CMS_qqzzbkg_a4.setVal(185.262);
    CMS_qqzzbkg_a5.setVal(7.99428);
    CMS_qqzzbkg_a6.setVal(39.7813);
    CMS_qqzzbkg_a7.setVal(0.0986891);
    CMS_qqzzbkg_a8.setVal(49.1325);
    CMS_qqzzbkg_a9.setVal(0.0389984);
    CMS_qqzzbkg_a10.setVal(98.6645);
    CMS_qqzzbkg_a11.setVal(-7.02043);
    CMS_qqzzbkg_a12.setVal(5694.66);
    CMS_qqzzbkg_a13.setVal(0.0774525);
    //*/
  }
  else if (channel == 2){
    ///* 4e
    CMS_qqzzbkg_a0.setVal(111.165);
    CMS_qqzzbkg_a1.setVal(19.8178);
    CMS_qqzzbkg_a2.setVal(120.89);
    CMS_qqzzbkg_a3.setVal(0.0546639);
    CMS_qqzzbkg_a4.setVal(184.878);
    CMS_qqzzbkg_a5.setVal(11.7041);
    CMS_qqzzbkg_a6.setVal(33.2659);
    CMS_qqzzbkg_a7.setVal(0.140858);
    CMS_qqzzbkg_a8.setVal(56.1226);
    CMS_qqzzbkg_a9.setVal(0.0957699);
    CMS_qqzzbkg_a10.setVal(98.3662);
    CMS_qqzzbkg_a11.setVal(-6.98701);
    CMS_qqzzbkg_a12.setVal(10.0536);
    CMS_qqzzbkg_a13.setVal(0.110576);
    //*/
  }
  else if (channel == 3){
    ///* 2e2mu
    CMS_qqzzbkg_a0.setVal(110.293);
    CMS_qqzzbkg_a1.setVal(11.8334);
    CMS_qqzzbkg_a2.setVal(116.91);
    CMS_qqzzbkg_a3.setVal(0.0433151);
    CMS_qqzzbkg_a4.setVal(185.817);
    CMS_qqzzbkg_a5.setVal(10.5945);
    CMS_qqzzbkg_a6.setVal(29.6208);
    CMS_qqzzbkg_a7.setVal(0.0826);
    CMS_qqzzbkg_a8.setVal(53.1346);
    CMS_qqzzbkg_a9.setVal(0.0882081);
    CMS_qqzzbkg_a10.setVal(85.3776);
    CMS_qqzzbkg_a11.setVal(-13.3836);
    CMS_qqzzbkg_a12.setVal(7587.95);
    CMS_qqzzbkg_a13.setVal(0.325621);
    //*/
  }
  else {
    cout << "disaster" << endl;
  }
    
  RooqqZZPdf_v2* bkg_qqzz = new RooqqZZPdf_v2("bkg_qqzz","bkg_qqzz",*ZZMass,
					      CMS_qqzzbkg_a0,CMS_qqzzbkg_a1,CMS_qqzzbkg_a2,CMS_qqzzbkg_a3,CMS_qqzzbkg_a4,
					      CMS_qqzzbkg_a5,CMS_qqzzbkg_a6,CMS_qqzzbkg_a7,CMS_qqzzbkg_a8,
					      CMS_qqzzbkg_a9,CMS_qqzzbkg_a10,CMS_qqzzbkg_a11,CMS_qqzzbkg_a12,CMS_qqzzbkg_a13);
  RooArgSet myASet(*ZZMass, CMS_qqzzbkg_a0,CMS_qqzzbkg_a1,CMS_qqzzbkg_a2,CMS_qqzzbkg_a3,CMS_qqzzbkg_a4,
		   CMS_qqzzbkg_a5,CMS_qqzzbkg_a6,CMS_qqzzbkg_a7);
  myASet.add(CMS_qqzzbkg_a8);
  myASet.add(CMS_qqzzbkg_a9);
  myASet.add(CMS_qqzzbkg_a10);
  myASet.add(CMS_qqzzbkg_a11);
  myASet.add(CMS_qqzzbkg_a12);
  myASet.add(CMS_qqzzbkg_a13);
 
  RooFitResult *r1 = bkg_qqzz->fitTo( *set, Save(kTRUE), SumW2Error(kTRUE) );//, Save(kTRUE), SumW2Error(kTRUE)) ;

  cout << endl;
  cout << "------- Parameters for " << schannel << " sqrts=" << sqrts << endl;
  cout << "  a0_bkgd = " << CMS_qqzzbkg_a0.getVal() << endl;
  cout << "  a1_bkgd = " << CMS_qqzzbkg_a1.getVal() << endl;
  cout << "  a2_bkgd = " << CMS_qqzzbkg_a2.getVal() << endl;
  cout << "  a3_bkgd = " << CMS_qqzzbkg_a3.getVal() << endl;
  cout << "  a4_bkgd = " << CMS_qqzzbkg_a4.getVal() << endl;
  cout << "  a5_bkgd = " << CMS_qqzzbkg_a5.getVal() << endl;
  cout << "  a6_bkgd = " << CMS_qqzzbkg_a6.getVal() << endl;
  cout << "  a7_bkgd = " << CMS_qqzzbkg_a7.getVal() << endl;
  cout << "  a8_bkgd = " << CMS_qqzzbkg_a8.getVal() << endl;
  cout << "  a9_bkgd = " << CMS_qqzzbkg_a9.getVal() << endl;
  cout << "  a10_bkgd = " << CMS_qqzzbkg_a10.getVal() << endl;
  cout << "  a11_bkgd = " << CMS_qqzzbkg_a11.getVal() << endl;
  cout << "  a12_bkgd = " << CMS_qqzzbkg_a12.getVal() << endl;
  cout << "  a13_bkgd = " << CMS_qqzzbkg_a13.getVal() << endl;
  cout << "}" << endl;
  cout << "---------------------------" << endl;


  of << "qqZZshape a0_bkgd   " << CMS_qqzzbkg_a0.getVal() << endl;
  of << "qqZZshape a1_bkgd   " << CMS_qqzzbkg_a1.getVal() << endl;
  of << "qqZZshape a2_bkgd   " << CMS_qqzzbkg_a2.getVal() << endl;
  of << "qqZZshape a3_bkgd   " << CMS_qqzzbkg_a3.getVal() << endl;
  of << "qqZZshape a4_bkgd   " << CMS_qqzzbkg_a4.getVal() << endl;
  of << "qqZZshape a5_bkgd   " << CMS_qqzzbkg_a5.getVal() << endl;
  of << "qqZZshape a6_bkgd   " << CMS_qqzzbkg_a6.getVal() << endl;
  of << "qqZZshape a7_bkgd   " << CMS_qqzzbkg_a7.getVal() << endl;
  of << "qqZZshape a8_bkgd   " << CMS_qqzzbkg_a8.getVal() << endl;
  of << "qqZZshape a9_bkgd   " << CMS_qqzzbkg_a9.getVal() << endl;
  of << "qqZZshape a10_bkgd  " << CMS_qqzzbkg_a10.getVal() << endl;
  of << "qqZZshape a11_bkgd  " << CMS_qqzzbkg_a11.getVal() << endl;
  of << "qqZZshape a12_bkgd  " << CMS_qqzzbkg_a12.getVal() << endl;
  of << "qqZZshape a13_bkgd  " << CMS_qqzzbkg_a13.getVal() << endl;
  of << endl << endl;
  of.close();

  cout << endl << "Output written to: " << outfile << endl;
  
    
  double qqzznorm;
  if (channel == 1) qqzznorm = 20.5836;
  else if (channel == 2) qqzznorm = 13.8871;
  else if (channel == 3) qqzznorm = 32.9883;
  else { cout << "disaster!" << endl; }

  ZZMass->setRange("fullrange",100.,1000.);
  ZZMass->setRange("largerange",100.,600.);
  ZZMass->setRange("zoomrange",100.,200.);
    
  double rescale = qqzznorm/totalweight;
  double rescale_z = qqzznorm/totalweight_z;
  cout << "rescale: " << rescale << ", rescale_z: " << rescale_z << endl;


  // Plot m4l and
  RooPlot* frameM4l = ZZMass->frame(Title("M4L"),Range(100,600),Bins(250)) ;
  set->plotOn(frameM4l, MarkerStyle(20), Rescale(rescale)) ;
  
  //set->plotOn(frameM4l) ;
  RooPlot* frameM4lz = ZZMass->frame(Title("M4L"),Range(100,200),Bins(100)) ;
  set->plotOn(frameM4lz, MarkerStyle(20), Rescale(rescale)) ;


  int iLineColor = 1;
  string lab = "blah";
  if (channel == 1) { iLineColor = 2; lab = "4#mu"; }
  if (channel == 3) { iLineColor = 4; lab = "2e2#mu"; }
  if (channel == 2) { iLineColor = 6; lab = "4e"; }

  bkg_qqzz->plotOn(frameM4l,LineColor(iLineColor),NormRange("largerange")) ;
  bkg_qqzz->plotOn(frameM4lz,LineColor(iLineColor),NormRange("zoomrange")) ;
    
//second shape to compare with (if previous comparison code unceommented)
  //bkg_qqzz_bkgd->plotOn(frameM4l,LineColor(1),NormRange("largerange")) ;
  //bkg_qqzz_bkgd->plotOn(frameM4lz,LineColor(1),NormRange("zoomrange")) ;
    
  
  double normalizationBackground_qqzz = bkg_qqzz->createIntegral( RooArgSet(*ZZMass), Range("fullrange") )->getVal();
  cout << "Norm all = " << normalizationBackground_qqzz << endl;
    
  frameM4l->GetXaxis()->SetTitle("m_{4l} [GeV]");
  frameM4l->GetYaxis()->SetTitle("a.u.");
  frameM4lz->GetXaxis()->SetTitle("m_{4l} [GeV]");
  frameM4lz->GetYaxis()->SetTitle("a.u.");

  char lname[192];
  sprintf(lname,"qq #rightarrow ZZ #rightarrow %s", lab.c_str() );
  char lname2[192];
  sprintf(lname2,"Shape Model, %s", lab.c_str() );
  // dummy!
  TF1* dummyF = new TF1("dummyF","1",0.,1.);
  TH1F* dummyH = new TH1F("dummyH","",1, 0.,1.);
  dummyF->SetLineColor( iLineColor );
  dummyF->SetLineWidth( 2 );

  dummyH->SetLineColor( kBlue );
  TLegend * box2 = new TLegend(0.4,0.70,0.80,0.90);
  box2->SetFillColor(0);
  box2->SetBorderSize(0);
  box2->AddEntry(dummyH,"Simulation (POWHEG+Pythia)  ","pe");
  box2->AddEntry(dummyH,lname,"");
  box2->AddEntry(dummyH,"","");
  box2->AddEntry(dummyF,lname2,"l");
    
  TPaveText *pt = new TPaveText(0.15,0.955,0.4,0.99,"NDC");
  pt->SetFillColor(0);
  pt->SetBorderSize(0);
  pt->AddText("CMS Preliminary 2012");
  TPaveText *pt2 = new TPaveText(0.84,0.955,0.99,0.99,"NDC");
  pt2->SetFillColor(0);
  pt2->SetBorderSize(0);
  TString entag;entag.Form("#sqrt{s} = %d TeV",sqrts);
  pt2->AddText(entag.Data());

  TCanvas *c = new TCanvas("c","c",800,600);
  c->cd();
  frameM4l->Draw();
  frameM4l->GetYaxis()->SetRangeUser(0,0.4);
  if(channel == 3)frameM4l->GetYaxis()->SetRangeUser(0,0.7);
  box2->Draw();
  pt->Draw();
  pt2->Draw();
  TString outputPath = "bkgFigs";
  outputPath = outputPath+ (long) sqrts + "TeV/";
  TString outputName;
  if(VBFtag<2) outputName =  outputPath + "bkgqqzz_" + schannel + "_" + Form("%d",int(VBFtag));
  if(VBFtag==2) outputName =  outputPath + "bkgqqzz_" + schannel;
  c->SaveAs(outputName + ".eps");
  c->SaveAs(outputName + ".png");
    
  TCanvas *c2 = new TCanvas("c2","c2",1000,500);
  c2->Divide(2,1);
  c2->cd(1);
  frameM4l->Draw();
  box2->Draw("same");
  c2->cd(2);
  frameM4lz->Draw();
  box2->Draw("same");
  
  if (VBFtag<2) outputName = outputPath + "bkgqqzz_" + schannel + "_z" + "_" + Form("%d",int(VBFtag));
  if (VBFtag==2) outputName = outputPath + "bkgqqzz_" + schannel + "_z";
  c2->SaveAs(outputName + ".eps");
  c2->SaveAs(outputName + ".png");

  /* TO make the ratio btw 2 shapes, if needed for compairson
  TCanvas *c3 = new TCanvas("c3","c3",1000,500);
   if(sqrts==7)
    sprintf(outputName, "bkgFigs7TeV/bkgqqzz_%s_ratio.eps",schannel.c_str());
  else if(sqrts==8)
    sprintf(outputName, "bkgFigs8TeV/bkgqqzz_%s_ratio.eps",schannel.c_str());

   const int nPoints = 501.;
  double masses[nPoints] ;
  int j=0;
  for (int i=100; i<601; i++){
    masses[j] = i;
    j++;
  }
  cout<<j<<endl;
  double effDiff[nPoints];
  for (int i = 0; i < nPoints; i++){
    ZZMass->setVal(masses[i]);
    double eval = (bkg_qqzz_bkgd->getVal(otherASet)-bkg_qqzz->getVal(myASet))/(bkg_qqzz->getVal(myASet));
    //cout<<bkg_qqzz_bkgd->getVal(otherASet)<<" "<<bkg_qqzz->getVal(myASet)<<" "<<eval<<endl;
    effDiff[i]=eval;
  }
  TGraph* grEffDiff = new TGraph( nPoints, masses, effDiff );
  grEffDiff->SetMarkerStyle(20);
  grEffDiff->Draw("AL");

  //c3->SaveAs(outputName);
  */

  if (VBFtag<2) outputName = outputPath + "bkgqqzz_" + schannel + "_z" + "_" + Form("%d",int(VBFtag)) + ".root";
  if (VBFtag==2) outputName = outputPath + "bkgqqzz_" + schannel + "_z" + ".root";
  TFile* outF = new TFile(outputName,"RECREATE");
  outF->cd();
  c2->Write();
  frameM4l->Write();
  frameM4lz->Write();	
  outF->Close();


  delete c;
  delete c2;
}
void rateStudy() {
  const int NRUNS = 25;
  const int NCH = 32;
  const int NBINS = 32;

  TCanvas* c1 = new TCanvas("c1", "c1", 800, 600);

  TMultiGraph *mg = new TMultiGraph();

  TLegend *legend=new TLegend(0.65,0.15,0.88,0.55);
  legend->SetNColumns(4);
  legend->SetFillColor(0);

  TH1F* hRate = new TH1F("hRate", "hist", 32.0, 0, 8.0);

  //Color buffer
  const int NCOLORS = 32;
  int color[NCOLORS] = {73, 2, 3, 4, 99, 6, 7, 8, 9, 12, 28, 32, 34,
                        28, 50, 51, 56, 58, 88, 99, 1, 208, 209,
                        218, 212, 210, 221, 224, 225, 226, 227, 228 };

  ifstream fin;
  //fin.open("runlist.txt");
  fin.open("filter_runlist.txt");

  string line = "";

  TFile* out = new TFile("outtemp.root", "REACREATE");
  TH1F* h = new TH1F("h","hist", NBINS, 0, NBINS);
  TF1* pois = new TF1("pois","[0]*TMath::Poisson(x,[1])",0,50);
  TF1* ppp = new TF1("ppp","[0]*TMath::Power(0.5,x*[1])",0.01,1.0);


  for (int ch = 0; ch < NCH; ++ch) {

    //if ( ch==26 || ch==27 )
    //continue;

    //Graph points and errors
    Double_t x[NRUNS];
    Double_t y[NRUNS];
    Double_t errX[NRUNS] = {0};
    Double_t errY[NRUNS] = {0};

    int fileCounter = 0;
    while(getline(fin, line)) {
      vector<double> data = parse(line);
      stringstream filePath;
      filePath << "pmtratestudy/run" << data[0] << "*.root";
      cout << "opening file at " << filePath.str() << endl;
      cout << "file counter: " << fileCounter << " channel=" << ch << endl;
      //TFile* f = new TFile(filePath.str().c_str());
      //TTree* t = (TTree *)f->Get("eventtree");
      TChain* t = new TChain("eventtree");
      t->Add( filePath.str().c_str() );
      out->cd();

      x[fileCounter] = data[1];

      int nfires[NCH] = {0};
      int samples = 0;
      float chmax = 0.0;
      t->SetBranchAddress("nfires", &nfires);
      t->SetBranchAddress("samples", &samples);
      t->SetBranchAddress("chmax", &chmax);
      
      h->Reset();
      
      int nentries = t->GetEntries();
      for (int entry = 0; entry < nentries; ++entry) {
        t->GetEntry(entry);
        if (chmax < 100.0) {
          h->Fill(nfires[ch]);
        }
      }


      
      pois->SetParameter(0,1);
      pois->SetParameter(1, h->GetMean());

      h->Fit(pois,"RQ","",0,50);
      //TF1 *myfit = (TF1 *)h->GetFunction("pois");
      TF1 *myfit = (TF1 *)pois;
      Double_t lambda = myfit->GetParameter(1);  
      h->Draw();
      stringstream histFileName;
      histFileName << "hist/h" << data[0] << "_ch" << ch << ".png";
      c1->SaveAs(histFileName.str().c_str());
      //Graph with poisson method
#if 1
      y[fileCounter] = lambda / ((samples - 1) * 15.625E-6);
      errY[fileCounter] = myfit->GetParError(1) / ((samples - 1) * 15.625E-6);
#endif
      //Graph with mean method
#if 0
      y[fileCounter] = h->GetMean() / ((samples - 1) * 15.625E-6);
      errY[fileCounter] = h->GetMeanError() / ((samples - 1) * 15.625E-6);
#endif
      cout << x[fileCounter] << ", " << y[fileCounter] 
           << " | " << (samples - 1) << endl;
      delete t;
      //f->Close();
      fileCounter++;
    } 

    ppp->SetParameter(0,1);
    ppp->SetParameter(1,0.4);
     
    TGraphErrors* gr = new TGraphErrors(NRUNS, x, y, errX, errY);
    gr->SetLineColor(color[ch % NCOLORS]);
    cout << "color: " << color[ch % NCOLORS] << endl;
    gr->SetLineWidth(2);
    gr->SetMarkerStyle(7);
    gr->Fit("ppp","R0","Q0",0.045,2.0);
    TF1 *afit = (TF1 *)gr->GetFunction("ppp");
    Double_t aRate = 1/afit->GetParameter(1);  
    if (aRate > 0) {
      hRate->Fill(aRate);
    }
    gr->GetXaxis()->SetTitle("Run Date");
    gr->GetYaxis()->SetTitle("Rate [kHz]");

    stringstream entryName, fileName;
    entryName << "Channel" << ch;
    gr->SetTitle(entryName.str().c_str());
    fileName << "plots/" << ch << ".png";
    legend->AddEntry(gr, entryName.str().c_str());
    gr->Draw("alp");
    c1->SaveAs(fileName.str().c_str());
    mg->Add(gr);
    cout << "added plot to mg\n";
    fin.clear();
    fin.seekg(0, ios::beg);
  } // loop over channel
  hRate->Draw();
  hRate->Fit("gaus");
  c1->SaveAs("hrate.pdf");
  mg->Draw("alp");
  mg->GetXaxis()->SetTitle("Days since first run");
  mg->GetYaxis()->SetTitle("Rate [kHz]");
  mg->SetTitle("All channels: Rate vs. Days since first Run");

  legend->Draw();
  c1->SaveAs("mg.pdf");
  
}
Exemple #22
0
int main(int argc, char* argv[])
{
  TFile* file = new TFile("neutrons.root", "recreate");

  TChain* chain = createChain(argc, argv);
  // Assign addresses
  double target_charge, veto_charge, target_cb, veto_cb;
  unsigned long long time;
  chain->SetBranchAddress("target_total", &target_charge);
  chain->SetBranchAddress("veto_total", &veto_charge);
  chain->SetBranchAddress("target_cb", &target_cb);
  chain->SetBranchAddress("veto_cb", &veto_cb);
  chain->SetBranchAddress("time", &time);

  const int chainEntries = chain->GetEntries();
  const double adc2us = 4/1000.0;
  const int maxCharge = 30000;
  TH1F* histogram = new TH1F("timing", "timing", 2000, 0, 2000);
  TH1F* neutrons = new TH1F("nspec", "neutron spectrum", 200, 0, maxCharge);
  TH1F* hydrogen = new TH1F("nhspec", "capture on hydrogen", 200, 0, maxCharge);
  TH1F* externals = new TH1F("externspec", "externals", 200, 0, maxCharge);
  TH1F* tsa_neutrons = new TH1F("tsa_spec", "neutron spectrum from tsa plot", 200, 0, maxCharge);
  TH1I* multiplicity = new TH1I("mult", "Event multiplicity", 20, 0, 20);

  unsigned long long t1=0;
  unsigned long long t2=0;
  unsigned long long t3=0;

  // cuts
  const double max_target_cb = 0.5;
  const double max_veto_charge = 500;
  const double min_target_charge = 0;
  const double tale_min = 800;
  const double tale_max = 2000;
  const double neutrons_min = 0;
  const double neutrons_time = 50;
  const double hydro_min = 100;
  const double hydro_max = 150;

  double previous_charge = 0;

  // TSA Plots
  const int nbins = 100;
  double logmin = -0.3;
  double logmax = 4.5;
  double binwidth = (logmax-logmin)/double(nbins);
  double bin_array[nbins+1];
  bin_array[0]=std::pow(10, logmin);
  for(int i=1; i<=nbins; i++)
    bin_array[i]=bin_array[0]+std::pow(10,logmin + i*binwidth);
  TH2F* tsa = new TH2F("tsa", "time series analysis", nbins, bin_array, nbins, bin_array);

  // Keep track of timing in order to get multiplicity
  std::vector<unsigned long long> time_vec;
  time_vec.resize(1, 0);

  for(int evt=0; evt<chainEntries; ++evt)
  {
    // Print out progress
    if(!(evt%1000))
      std::cout << std::floor(double(evt)/chainEntries*100) << "%\r";
    previous_charge = target_charge;
    chain->GetEvent(evt);    

    if(veto_charge<max_veto_charge &&
       target_charge>min_target_charge &&
       target_cb < max_target_cb )
    {
      
      t3=t2;
      t2=t1;
      t1=time;
      double d12 = (t1-t2)*adc2us;
      double d23 = (t2-t3)*adc2us;
      tsa->Fill(d23, d12);
      if((time-time_vec[0])*adc2us < 50)
	time_vec.push_back(time);
      else
      {
	multiplicity->Fill(time_vec.size());
	time_vec.clear();
	time_vec.push_back(time);
      }

      histogram->Fill(d12);
      if(d12 < neutrons_time && d12 > neutrons_min)
	neutrons->Fill(target_charge);
      if(d12 < tale_max && d12 > tale_min)
	externals->Fill(target_charge);
      if(d12 < hydro_max && d12 > hydro_min)
	hydrogen->Fill(target_charge);
      if(d12 < neutrons_time && d23 < neutrons_time)
	tsa_neutrons->Fill(previous_charge);
    }
  }
  std::cout << std::endl;
  // Events in tale:
  TF1* fitter_extern = new TF1("fitter_extern", "[0]*TMath::Exp([1]*x)",
			       0, 2000);
  fitter_extern->SetParameters(1000, -4e-4);
  histogram->Fit(fitter_extern, "QO", "", tale_min, tale_max);
  TF1* fitter_h = new TF1("fitter_h", "[0]*TMath::Exp([1]*x)",
			  0, 2000);
  fitter_h->SetParameters(1000, -4e-3);
  histogram->Fit(fitter_h, "QO+", "", hydro_min, hydro_max);

  

  int tale_events = fitter_extern->Integral(tale_min, tale_max);
  int bkg_events = fitter_extern->Integral(neutrons_min, neutrons_time);

  int h_long_events = fitter_h->Integral(hydro_min, hydro_max);
  int h_short_events = fitter_h->Integral(neutrons_min, neutrons_time);

  double talebkgratio = bkg_events / double(tale_events);
  externals->Scale(talebkgratio);
  double h_ratio = h_short_events / h_long_events;
  hydrogen->Scale(h_ratio);

  TH1F* pureNeutrons = new TH1F("pureNeutrons", "pureNeutrons", 200, 0, maxCharge);
  for(int i=0; i<neutrons->GetNbinsX(); i++)
    pureNeutrons->SetBinContent(i, neutrons->GetBinContent(i) - externals->GetBinContent(i) 
				- hydrogen->GetBinContent(i));

  file->Write();
  std::cout << "Wrote histograms to neutrons.root" << std::endl;

  // TRint* app = new TRint("EVIL", &argc, argv);
  // TCanvas* c1 = new TCanvas();
  //c1->Divide(1,2);
  //c1->cd(1);
  //histogram->Draw();
  //fitter_h->Draw("same");
  //fitter_extern->Draw("same");
  //c1->cd(2);
  // externals->SetLineColor(kBlack);
  // neutrons->SetLineColor(kGreen);
  // pureNeutrons->SetLineColor(kRed);
  // hydrogen->SetLineColor(kBlue);
  // neutrons->Draw();
  // externals->Draw("same");
  // hydrogen->Draw("same");
  // pureNeutrons->Draw("same");
  //app->Run();

  delete histogram;
  delete externals;
  delete neutrons;
  delete pureNeutrons;
  //delete c1;
  delete chain;
  delete file;
  return 0;
}
void closure_jetfakepho(){//main  
  
  int channel = 1; // 1 = eg; 2 = mg
	 
  TChain *sigtree = new TChain("signalTree");
  if(channel == 1)sigtree->Add("../../../data/resTree_egsignal_2016.root");
  else if(channel ==2)sigtree->Add("../../../data/resTree_mgsignal_2016.root");

  TChain *controltree = new TChain("jetTree");
  if(channel == 1)controltree->Add("../../../data/resTree_egsignal_2016.root");
  else if(channel == 2)controltree->Add("../../../data/resTree_mgsignal_2016.root");

  std::ostringstream outputname;
  if(channel == 1)outputname << "jet-fake-pho_egpt.root";
  else if(channel == 2)outputname << "jet-fake-pho_mgpt.root";
  TFile *outputfile = TFile::Open(outputname.str().c_str(),"RECREATE");
  outputfile->cd();

//*********** histo list **********************//
//  TH1F *p_controlPhoEt = new TH1F("p_controlPhoEt","#gamma E_{T}; E_{T} (GeV)",300,35,335);
//  TH1F *p_sigPhoEt  = new TH1F("p_sigPhoEt","#gamma E_{T}; E_{T} (GeV)",300,35,335);
//  TH1F *p_fakesPhoEt = new TH1F("p_fakesPhoEt","#gamma E_{T}; E_{T} (GeV)",300,35,335);
//  TH1F *p_elebkgPhoEt = new TH1F("p_elebkgPhoEt","#gamma E_{T}; E_{T} (GeV)",300,35,335);

  TH1F *p_controlPhoEt = new TH1F("p_controlPhoEt",";pt;",115,35,150);
  TH1F *p_sigPhoEt  = new TH1F("p_sigPhoEt",";pt;",115,35,150);
  TH1F *p_fakesPhoEt = new TH1F("p_fakesPhoEt",";pt;",115,35,150);
  TH1F *p_elebkgPhoEt = new TH1F("p_elebkgPhoEt",";pt;",115,35,150);

  sigtree->Draw("phoEt >> p_sigPhoEt", "sigMET < 70");
  controltree->Draw("phoEt >> p_controlPhoEt", "sigMET < 70");

  //p_sigPhoEt->SetBinContent(115, p_sigPhoEt->GetBinContent(115) + p_sigPhoEt->GetBinContent(116));
  //p_controlPhoEt->SetBinContent(115, p_controlPhoEt->GetBinContent(115) + p_controlPhoEt->GetBinContent(116));
  
  p_sigPhoEt->Sumw2();
  p_controlPhoEt->Sumw2();
//************ Proxy Tree **********************//
if(channel == 1){
  TChain *proxytree = new TChain("proxyTree");
  proxytree->Add("../../../data/resTree_egsignal_2016.root");

  float proxyphoEt(0);
  float proxysigMET(0);
  
  proxytree->SetBranchAddress("phoEt",     &proxyphoEt);
  proxytree->SetBranchAddress("sigMET",    &proxysigMET);
 
  for (unsigned ievt(0); ievt<proxytree->GetEntries(); ++ievt){//loop on entries
	proxytree->GetEntry(ievt);

    if(proxysigMET > 70)continue;
	double w_ele = 1; 
    for(unsigned i(0); i<nelePtBins-1; i++){
      if(proxyphoEt > elePtBins[i] && proxyphoEt < elePtBins[i+1])w_ele=elefakepho[i];
    }
    if(proxyphoEt >= 120)w_ele = 0.0124176; 
	p_elebkgPhoEt->Fill(proxyphoEt,w_ele);
  }
  p_elebkgPhoEt->Sumw2();
  p_sigPhoEt->Add(p_elebkgPhoEt, -1);
}
  for(unsigned ibin(1); ibin < p_sigPhoEt->GetSize()-1; ibin++){
    double xvalue = p_sigPhoEt->GetBinCenter(ibin);
    double frac(0),fracerror(0);
    for(unsigned i(0); i<19; i++) 
      if(xvalue >= PtBin[i] && xvalue < PtBin[i+1]){
        frac = fracHad[i];
        fracerror = fracHadError[i];
      }
    if(xvalue >= 140){ frac = (fracHad[18]+fracHad[17])/2; fracerror = fracHadError[18];}
    
    double binvalue = p_sigPhoEt->GetBinContent(ibin)*frac;
    double binerror = p_sigPhoEt->GetBinError(ibin);  
    if(binvalue == 0)continue;
    double totalerror = sqrt(binvalue*binvalue*fracerror*fracerror + binerror*binerror*frac*frac);
    p_fakesPhoEt->SetBinContent(ibin, binvalue);
    p_fakesPhoEt->SetBinError(ibin, binerror);
  }

outputfile->Write();

Double_t plotPtBins[]={35,40,45,50,55,60,65,70,75,80,85,90,100,110,120,130,140,160,200};
gStyle->SetOptStat(0);
TCanvas *c_pt = new TCanvas("Photon_Pt", "Photon P_{T}",800,800);
c_pt->cd();
TPad *pad1 = new TPad("pad1", "pad1", 0, 0.3, 1, 1.0);
pad1->SetBottomMargin(0.1);
pad1->Draw();  
pad1->cd();  
gPad->SetLogy();
TH1 *new_controlPhoEt = p_controlPhoEt->Rebin(5);
TH1 *new_fakesPhoEt = p_fakesPhoEt->Rebin(5);
new_controlPhoEt->GetXaxis()->SetRangeUser(35,150);
new_fakesPhoEt->GetXaxis()->SetRangeUser(35,150);
new_controlPhoEt->Draw("EP");
new_controlPhoEt->SetLineColor(kBlack);
new_controlPhoEt->SetMarkerStyle(20);
new_fakesPhoEt->SetLineColor(kRed);
new_fakesPhoEt->SetMarkerStyle(20);
new_fakesPhoEt->SetMarkerColor(kRed);
new_fakesPhoEt->Draw("EP same");
TLegend *leg =  new TLegend(0.6,0.7,0.9,0.9);
leg->SetFillStyle(0);
gStyle->SetLegendBorderSize(1);
gStyle->SetLegendFillColor(0);
leg->AddEntry(new_controlPhoEt,"hadron proxies");
leg->AddEntry(new_fakesPhoEt,"fake photons");
leg->Draw("same");

TF1 *fitfunc_num = new TF1("fitfunc_num","expo(0)+expo(3)",35,150);
TF1 *fitfunc_den = new TF1("fitfunc_den","expo(0)+expo(3)",35,150);

c_pt->cd();
TPad *pad2 = new TPad("pad2", "pad2", 0, 0.05, 1, 0.25);
pad2->Draw();
pad2->cd();
TH1F *ratio=(TH1F*)new_fakesPhoEt->Clone("transfer factor");
ratio->Divide(new_controlPhoEt);
ratio->SetTitle("");
ratio->GetYaxis()->SetTitle("proxies/fake");
ratio->GetXaxis()->SetLabelFont(63);
ratio->GetXaxis()->SetLabelSize(14);
ratio->GetYaxis()->SetLabelFont(63);
ratio->GetYaxis()->SetLabelSize(14);
ratio->Draw();

RooRealVar pt("pt","",35,150);
//pt.setBins(33);
new_controlPhoEt->SetMaximum(new_controlPhoEt->GetEntries());
new_fakesPhoEt->SetMaximum(new_fakesPhoEt->GetEntries());
RooDataHist* hist_den = new RooDataHist("hist_den","hist_den",pt,new_controlPhoEt);
RooDataHist* hist_num = new RooDataHist("hist_num","hist_num",pt,new_fakesPhoEt);
RooHistPdf*  pdf_den  = new RooHistPdf("pdf_den","pdf_den", pt, *hist_den);
RooHistPdf*  pdf_num  = new RooHistPdf("pdf_num","pdf_num", pt, *hist_num);
RooRealVar coeff1_den("coeff1_den","coeff1", 1, -15, 10*new_controlPhoEt->GetEntries());
RooRealVar coeff2_den("coeff2_den","coeff2", 1, -15, 10*new_controlPhoEt->GetEntries());
RooRealVar lambda1_den("lambda1_den","lambda1", 0.02, -1, 1);
RooRealVar lambda2_den("lambda2_den","lambda2", 0.02, -1, 1);
RooExponential expo1_den("expo1_den", "exponential PDF", pt, lambda1_den);
RooExponential expo2_den("expo2_den", "exponential PDF", pt, lambda2_den);
RooAddPdf model_den("model_den","",RooArgList(expo1_den, expo2_den),RooArgList(coeff1_den, coeff2_den));

RooRealVar coeff1_num("coeff1_num","coeff1", 1, -15, 10*new_fakesPhoEt->GetEntries());
RooRealVar coeff2_num("coeff2_num","coeff2", 1, -15, 10*new_fakesPhoEt->GetEntries());
RooRealVar lambda1_num("lambda1_num","lambda1", 0.02, -1, 1);
RooRealVar lambda2_num("lambda2_num","lambda2", 0.02, -1, 1);
RooExponential expo1_num("expo1_num", "exponential PDF", pt, lambda1_num);
RooExponential expo2_num("expo2_num", "exponential PDF", pt, lambda2_num);
RooAddPdf model_num("model_num","",RooArgList(expo1_num, expo2_num),RooArgList(coeff1_num, coeff2_num));

//RooMCStudy* mcstudy_den = new RooMCStudy(*pdf_den,pt,RooFit::FitModel(model_den),RooFit::Binned(kTRUE),RooFit::Silence(),RooFit::Extended(),
//				       RooFit::FitOptions(RooFit::Save(kTRUE),RooFit::PrintEvalErrors(0)));
//RooMCStudy* mcstudy_num = new RooMCStudy(*pdf_num,pt,RooFit::FitModel(model_num),RooFit::Binned(kTRUE),RooFit::Silence(),RooFit::Extended(),
//				       RooFit::FitOptions(RooFit::Save(kTRUE),RooFit::PrintEvalErrors(0)));
//RooChi2MCSModule chi2mod_den;
//RooChi2MCSModule chi2mod_num;
//mcstudy_den->addModule(chi2mod_den);
//mcstudy_num->addModule(chi2mod_num);
//mcstudy_den->generateAndFit(1000,new_controlPhoEt->GetEntries());
//mcstudy_num->generateAndFit(1000,new_fakesPhoEt->GetEntries());

//TH1* chi2_den = mcstudy_den->fitParDataSet().createHistogram("chi2"); 
//TH1* prob_den = mcstudy_den->fitParDataSet().createHistogram("prob");   
//TH1* chi2_num = mcstudy_num->fitParDataSet().createHistogram("chi2"); 
//TH1* prob_num = mcstudy_num->fitParDataSet().createHistogram("prob");   
//TH1* result_den = mcstudy_den->fitParDataSet().createHistogram("hh");
//TH1* result_den = mcstudy_den->fitResult(0)->correlationHist("c000") ;
//chi2_num->SetLineColor(kRed) ;
//prob_num->SetLineColor(kRed) ;

TCanvas* mccan = new TCanvas("mccan","mccan",800,400) ;
mccan->Divide(2) ;
//mccan->cd(1) ; gPad->SetLeftMargin(0.15) ; chi2_den->GetYaxis()->SetTitleOffset(1.4) ; chi2_den->Draw() ; chi2_num->Draw("esame") ;
//mccan->cd(2) ; gPad->SetLeftMargin(0.15) ; prob_den->GetYaxis()->SetTitleOffset(1.4) ; prob_den->Draw() ; prob_num->Draw("esame") ;
RooPlot* den_frame = pt.frame(RooFit::Title("jet proxies"));
RooPlot* num_frame = pt.frame(RooFit::Title("candidate photon X hadron factor"));

mccan->cd(1);
gPad->SetLogy();
den_frame->SetMaximum(new_controlPhoEt->GetEntries());
RooFitResult* reden = model_den.fitTo(*hist_den,RooFit::SumW2Error(kTRUE),RooFit::Save());
hist_den->plotOn(den_frame);
model_den.plotOn(den_frame,
		 RooFit::FillColor(kBlue-4));
den_frame->Draw();

mccan->cd(2);
gPad->SetLogy();
num_frame->SetMaximum(10000);
num_frame->SetMinimum(10);
RooFitResult* renum = model_num.fitTo(*hist_num,RooFit::SumW2Error(kTRUE),RooFit::Save());
hist_num->plotOn(num_frame);
model_num.plotOn(num_frame,
		 RooFit::FillColor(kBlue-4));
num_frame->Draw();

pt.setRange("signal",35,150);
RooAbsReal* igx_den1 = expo1_den.createIntegral(pt,RooFit::Range("signal"));
RooAbsReal* igx_den2 = expo2_den.createIntegral(pt,RooFit::Range("signal"));
RooAbsReal* igx_num1 = expo1_num.createIntegral(pt,RooFit::Range("signal"));
RooAbsReal* igx_num2 = expo2_num.createIntegral(pt,RooFit::Range("signal"));
std::cout << "inte den1=" << igx_den1->getVal() << " den2=" << igx_den2->getVal() << " num1=" << igx_num1->getVal() << " num2=" << igx_num2->getVal() << std::endl;
std::cout << "totalden=" << new_controlPhoEt->GetEntries() << std::endl;
fitfunc_den->SetParameter(1,lambda1_den.getVal());
fitfunc_den->SetParameter(3,lambda2_den.getVal());
fitfunc_num->SetParameter(1,lambda1_num.getVal());
fitfunc_num->SetParameter(3,lambda2_num.getVal());
new_fakesPhoEt->Fit("fitfunc_num");
new_controlPhoEt->Fit("fitfunc_den");
c_pt->cd();
pad1->cd();
fitfunc_den->Draw("same");
fitfunc_num->Draw("same");
if(channel == 1)c_pt->SaveAs("JetFake_ratio_eg.pdf");
else if(channel == 2)c_pt->SaveAs("JetFake_ratio_mg.pdf");
//  NO.   NAME      VALUE            ERROR          SIZE      DERIVATIVE 
//   1  p0           9.73181e+00   2.26898e-01   2.78046e-05   9.10547e-03
//   2  p1          -3.34186e-02   1.55081e-03   4.43967e-07   7.43686e-01
//  3  p3           9.55643e+00   2.70401e-01   3.31514e-05   7.64064e-03
//  4  p4          -3.34188e-02   1.82847e-03   5.28578e-07   5.89368e-01
//FCN=95.1209 FROM MIGRAD    STATUS=CONVERGED     253 CALLS         254 TOTAL
//                    EDM=2.21358e-08    STRATEGY= 1      ERROR MATRIX ACCURATE 
// EXT PARAMETER                                   STEP         FIRST   
// NO.   NAME      VALUE            ERROR          SIZE      DERIVATIVE 
//  1  p0           2.27259e+00   1.40250e+00   3.06094e-04  -1.34231e-05
//  2  p1           2.05848e-02   9.68368e-03   2.22428e-06  -1.31028e-02
//  3  p3           1.24698e+01   9.85422e-03   9.76944e-06  -3.21533e-02
//   4  p4          -4.47018e-02   2.05076e-04   1.63128e-07  -1.91568e+00

mccan->SaveAs("JetFake_ptfitting.pdf");
for(unsigned i(0); i< 23; i++){
  Double_t bincenter = i*5.0+2.5;
  std::cout << "bin" << i << "  " << ratio->GetBinContent(i) << "  predict = " << fitfunc_num->Eval(bincenter)/fitfunc_den->Eval(bincenter) << std::endl;
}
}
Exemple #24
0
int MC_Ratio(int leptonId, double* par1, int npar1bins, double* par2, int npar2bins, TString sel_den , TString sel_num, double cut_num , TString par_x , TString par_y , TString option ){

  setTDRStyle();

  ///////////////
  //Get the TTree
  ///////////////

  //Location of the .root file
  TString location2 = "/Users/GLP/Desktop/CERN_data/dyjetsnew/postprocessed/";

  //Reading the tree 
  //
  TChain* tree = new TChain("treeProducerSusyMultilepton");

  //DY events
  //tree->Add(location+"DYJetsToLLM50_PU_S14_POSTLS170.root");
  tree->Add(location2+"dyjets_good.root");

  //Plot the result

  Long64_t n = tree->GetEntries();

  //Path for input and output file. Written in FitDataPath.txt
  TString _path = "/Users/GLP/Dropbox/Physique/Master_Thesis/plots_root/MC_eff/";

  //////////////////////
  //Name for the plots//
  //////////////////////

  TString _filetag = "";

  TString pname;
  TString _pname;
  TString _par;
  TString _sel_num;
  TString _sel_den;
  TString _option;

  ////Writing string
  //particle string
  if(abs(leptonId) == 11){pname = "e"; _pname = "e";}
  if(abs(leptonId) == 13){pname = " #mu"; _pname = "mu";}
  //Parameter string
  if(par_x == "Pt"){_par = "P_{t}";}
  else if(par_x == "eta"){_par = "#eta";}
  else if(par_x == "phi"){_par = "#phi";}
  //sel_den string
  if((sel_den == "tightmva")&&(leptonId == 13)){cout<<"ERROR: no tightId MVA defined for the muon !"<<endl;return 1;}
  if(sel_den == "tightcut"){_sel_den = "tightcut";}
  else if(sel_den == "tightmva"){_sel_den = "tightmva";}
  else if(sel_den == "loose"){_sel_den = "loose";}
  else if(sel_den == ""){_sel_den = "";}
  else{cout<<"ERROR: wrong sel_denion !";return 1;}
  //sel_num string
  if((sel_num == "tightmva")&&(leptonId == 13)){cout<<"ERROR: no tightId MVA defined for the muon !"<<endl;return 1;}
  if(sel_num == "tightcut"){_sel_num = "tightcut";}
  else if(sel_num == "tightmva"){_sel_num = "tightmva";}
  else if(sel_num == ""){_sel_num = "";}
  else if(sel_num == "loose"){_sel_num = "loose";}
  else if(sel_num == "reliso3"){_sel_num = Form("reliso3_%0.3lf",cut_num);}
  else if(sel_num == "reliso4"){_sel_num = Form("reliso4_%0.3lf",cut_num);}
  else if(sel_num == "chiso3"){_sel_num = Form("chiso3_%0.3lf",cut_num);}
  else if(sel_num == "chiso4"){_sel_num = Form("chiso4_%0.3lf",cut_num);}
  else if(sel_num == "dxy"){_sel_num = Form("dxy_%0.3lf",cut_num);}
  else if(sel_num == "dz"){_sel_num = Form("dz_%0.3lf",cut_num);}
  else{cout<<"ERROR: wrong numerator name !";return 1;}
  //option string
  option.Append(" ");
  option.Prepend(" ");
  if(option.Contains(" ll ")){_option += "_ll";}
  if(option.Contains(" unmatched ")){_option += "_unmatched";}
  if(option.Contains(" alleta ")){_option += "_alleta";}
  if(option.Contains(" short ")){_option += "_short";}
  _option += "_";
  //parameter range string
  TString _par1range;
  _par1range = Form("%0.3f_"+par_x+"%0.3f",par1[0],par1[npar1bins]);
  TString _par2range;
  _par2range = Form("%0.3f_"+par_y+"%0.3f",par2[0],par2[npar2bins]);

  /////////////////////////////////////
  //Write the name of the output file//
  /////////////////////////////////////

  TString _fname = "MCeff"+_filetag+_option+_pname+_par1range+"_"+_par2range+"_den_"+_sel_den+"_num_"+_sel_num;

  //Output file
  cout<<"going to create the file"<<endl;
  //Check if the file exists
  TFile *fcheck = TFile::Open(_path+_fname+".root", "READ");
  if (fcheck) {
    cout << "File "<<_fname<<" exists ! Please change name" << endl;
    return 1;
  }

  TFile* file_out = new TFile(_path+_fname+".root","recreate");
  cout<<"done ! "<<endl;

  //Declaration of histogram
  TH1D **histo_num = new TH1D*[npar2bins];
  TH1D **histo_den = new TH1D*[npar2bins];
  TH1D **eff = new TH1D*[npar2bins];


  //Par1 distribution histogram
  TH1D** histo_par1 = new TH1D*[npar2bins];

  //Distribution of the cut parameter whose efficiency is studied
  TH1D *histo_other_sel = new TH1D("histo_other_sel","h",5,0,5);
  TH1D *histo_good_sel = new TH1D("histo_good_sel","h",5,0,5);

//Histo separate in Lep_good Lep_other
  //
  TH1D **histo_num_O = new TH1D*[npar2bins];
  TH1D **histo_den_O = new TH1D*[npar2bins];
  TH1D **eff_O = new TH1D*[npar2bins];
  TH1D **histo_num_G = new TH1D*[npar2bins];
  TH1D **histo_den_G = new TH1D*[npar2bins];
  TH1D **eff_G = new TH1D*[npar2bins];

  //Counter LepGood vs LepOther

  TH1D **histo_counter = new TH1D*[npar2bins];
  TH1D **histo_counter_G_par1 = new TH1D*[npar2bins];
  TH1D **histo_counter_O_par1 = new TH1D*[npar2bins];
  TH1D **histo_counter_par1 = new TH1D*[npar2bins];


  for(int _i = 0; _i < npar2bins; ++_i){ 

    histo_num[_i] = new TH1D("histo_num","Pt",npar1bins,par1[0],par1[npar1bins]);
    histo_den[_i] = new TH1D("histo_den","Pt",npar1bins,par1[0],par1[npar1bins]);
    eff[_i] = new TH1D("eff","Pt",npar1bins,par1[0],par1[npar1bins]);

    //
    histo_par1[_i] = new TH1D("histo_par1","par1",npar1bins*25,par1[0],par1[npar1bins]);

    //
    histo_num_O[_i] = new TH1D("histo_num_O","Pt",npar1bins,par1[0],par1[npar1bins]);
    histo_den_O[_i] = new TH1D("histo_den_O","Pt",npar1bins,par1[0],par1[npar1bins]);
    eff_O[_i] = new TH1D("eff_O","Pt",npar1bins,par1[0],par1[npar1bins]);

    histo_num_G[_i] = new TH1D("histo_num_G","Pt",npar1bins,par1[0],par1[npar1bins]);
    histo_den_G[_i] = new TH1D("histo_den_G","Pt",npar1bins,par1[0],par1[npar1bins]);
    eff_G[_i] = new TH1D("eff_G","Pt",npar1bins,par1[0],par1[npar1bins]);

    histo_counter_G_par1[_i] = new TH1D("histo_counter_G_par1","count",npar1bins,par1[0],par1[npar1bins]);
    histo_counter_O_par1[_i] = new TH1D("histo_counter_O_par1","count",npar1bins,par1[0],par1[npar1bins]);
    histo_counter_par1[_i] = new TH1D("histo_counter_par1","count",npar1bins,par1[0],par1[npar1bins]);

    histo_counter[_i] = new TH1D("histo_counter","count",2,0,2); 

  }

  //Event variables
  Int_t evt_id;
  Double_t scale;
  //Generated
  Double_t gen_phi[200];
  Double_t gen_eta[200];
  Double_t Pt[200];
  Double_t m[200];
  Int_t Id[200];
  Int_t Mo[200];
  Double_t charge[200];
  Int_t status[200];
  Int_t GrMa[200];
  Int_t ngenPart;
  Int_t source[200];
  Int_t pile_up;
  //not loose
  Int_t On;
  Int_t Oid[200];
  Double_t Opt[200];
  Double_t Om[200];
  Double_t Oeta[200];
  Double_t Ophi[200];
  Int_t   Oq[200];
  Int_t Otight[200];
  Int_t Otighte[200];
  //Double_t Omvaid[200];
  Int_t Oloose[200];
  Double_t Oiso3[200];
  Double_t Oiso4[200];
  Double_t Ochiso3[200];
  Double_t Ochiso4[200];
  Double_t Odxy[200];
  Double_t Odz[200];
  //loose
  Int_t 	Gn;
  Int_t 	Gid[200];
  Double_t 	Gpt[200];
  Double_t 	Gm[200];
  Double_t 	Geta[200];
  Double_t 	Gphi[200];
  Int_t   	Gq[200];
  Int_t 	Gtight[200];
  Int_t 	Gtighte[200];
  Int_t 	Gloose[200];
  Double_t 	Giso3[200];
  Double_t 	Giso4[200];
  Double_t 	Gchiso3[200];
  Double_t 	Gchiso4[200];
  Double_t 	Gdxy[200];
  Double_t 	Gdz[200];

  //Assigne branches tree->SetBranchAddress("evt_scale1fb", &scale);
  tree->SetBranchAddress("evt_id", &evt_id);
  //generated
  tree->SetBranchAddress("nGenPart", &ngenPart);
  tree->SetBranchAddress("GenPart_pdgId", &Id);
  tree->SetBranchAddress("GenPart_sourceId", &source);
  tree->SetBranchAddress("GenPart_eta", &gen_eta);
  tree->SetBranchAddress("GenPart_phi", &gen_phi);
  tree->SetBranchAddress("GenPart_pt", &Pt);
  tree->SetBranchAddress("GenPart_mass", &m);
  tree->SetBranchAddress("GenPart_charge", &charge);
  tree->SetBranchAddress("GenPart_status", &status);
  //not loose
  tree->SetBranchAddress("nLepOther",&On);
  tree->SetBranchAddress("LepOther_pdgId",&Oid);
  tree->SetBranchAddress("LepOther_pt",&Opt);
  tree->SetBranchAddress("LepOther_mass",&Om);
  tree->SetBranchAddress("LepOther_eta",&Oeta);
  tree->SetBranchAddress("LepOther_phi",&Ophi);
  tree->SetBranchAddress("LepOther_charge",&Oq);
  tree->SetBranchAddress("LepOther_tightId",&Otight);
  tree->SetBranchAddress("LepOther_eleCutIdCSA14_50ns_v1",&Otighte);
  tree->SetBranchAddress("LepOther_relIso03",&Oiso3);
  tree->SetBranchAddress("LepOther_relIso04",&Oiso4);
  tree->SetBranchAddress("LepOther_chargedHadRelIso03",&Ochiso3);
  tree->SetBranchAddress("LepOther_chargedHadRelIso04",&Ochiso4);
  tree->SetBranchAddress("LepOther_dxy",&Odxy);
  tree->SetBranchAddress("LepOther_dz",&Odz);
  //Loose
  tree->SetBranchAddress("nLepGood",&Gn);
  tree->SetBranchAddress("LepGood_pdgId",&Gid);
  tree->SetBranchAddress("LepGood_pt",&Gpt);
  tree->SetBranchAddress("LepGood_mass",&Gm);
  tree->SetBranchAddress("LepGood_eta",&Geta);
  tree->SetBranchAddress("LepGood_phi",&Gphi);
  tree->SetBranchAddress("LepGood_charge",&Gq);
  tree->SetBranchAddress("LepGood_tightId",&Gtight);
  tree->SetBranchAddress("LepGood_eleCutIdCSA14_50ns_v1",&Gtighte);
  tree->SetBranchAddress("LepGood_relIso03",&Giso3);
  tree->SetBranchAddress("LepGood_relIso04",&Giso4);
  tree->SetBranchAddress("LepGood_chargedHadRelIso03",&Gchiso3);
  tree->SetBranchAddress("LepGood_chargedHadRelIso04",&Gchiso4);
  tree->SetBranchAddress("LepGood_dxy",&Gdxy);
  tree->SetBranchAddress("LepGood_dz",&Gdz);

  int count = 0;

  //Count lepgood/other

  int goodcount = 0;
  int othercount = 0;


  if(option.Contains(" short ")){n = 100000;}

  //Start loop over all events
  for (int k = 0; k < n; ++k) {

    //Declaration of event parameters
    Int_t 	evtn;
    Int_t 	evtloose[200];
    Int_t 	evtid[200];
    Double_t 	evtpt[200];
    Double_t 	evtm[200];
    Double_t 	evteta[200];
    Double_t 	evtphi[200];
    Int_t   	evtq[200];
    Int_t 	evttight[200];
    Int_t 	evttighte[200];
    Double_t 	evtiso3[200];
    Double_t 	evtiso4[200];
    Double_t 	evtchiso3[200];
    Double_t 	evtchiso4[200];
    Double_t 	evtdxy[200];
    Double_t 	evtdz[200];

    if( 100*(double)k/n> count){cout<<count<<endl;++count;}

    tree->GetEntry(k);

    //Selection on denominator
    for(int j = 0; j < Gn+On; ++j){

      //Separate here other from loose
      if(j < On){

        evtloose[j]			  = 0;
        evtid[j]                      = Oid[j];
        evtpt[j]                      = Opt[j];
        evtm[j]                       = Om[j];
        evteta[j]                     = Oeta[j];
        evtphi[j]                     = Ophi[j];
        evtq[j]                       = Oq[j];
        evttight[j]                   = Otight[j];
        evttighte[j]                  = Otighte[j];
        evtiso3[j]                    = Oiso3[j];
        evtiso4[j]                    = Oiso4[j];
        evtchiso3[j]                  = Ochiso3[j];
        evtchiso4[j]                  = Ochiso4[j];
        evtdxy[j]                     = Odxy[j];
        evtdz[j]                      = Odz[j];


      }else if((j >=  On)&&(j < Gn+On)){

        evtloose[j]		       = 1;
        evtid[j]                   = Gid[j-On];
        evtpt[j]                   = Gpt[j-On];
        evtm[j]                    = Gm[j-On];
        evteta[j]                  = Geta[j-On];
        evtphi[j]                  = Gphi[j-On];
        evtq[j]                    = Gq[j-On];
        evttight[j]                = Gtight[j-On];
        evttighte[j]               = Gtighte[j-On];
        evtiso3[j]                 = Giso3[j-On];
        evtiso4[j]                 = Giso4[j-On];
        evtchiso3[j]               = Gchiso3[j-On];
        evtchiso4[j]               = Gchiso4[j-On];
        evtdxy[j]                  = Gdxy[j-On];
        evtdz[j]                   = Gdz[j-On];

      }

      if((!option.Contains(" ll "))||((option.Contains(" ll "))&&(Gn+On == 2)&&(evtq[0] == -evtq[1]))){
	if(abs(evtid[j]) == leptonId){
	  //Cut on the denominator
	  //if((sel_den != "loose")||(evtloose[j] == 1)){
	  //if(evtloose[j] == 1){
	    if((sel_den != "tightcut")||(((abs(evtid[j]) == 13)&&(sel_den == "tightcut")&&(evttight[j] == 1 ))||((abs(evtid[j]) == 11)&&(sel_den == "tightcut")&&(evttighte[j] >= 3)))){
	      if((sel_den != "tightmva")||((abs(evtid[j]) == 11)&&(sel_den == "tightmva")&&(evttight[j] == 1))){
		//Veto the EE-EB gape

		//Variable for matching
		double R = 999;
		double delta_P = 999;
		double delta_charge = 999;

		//Parameter on the xaxis

		double par;
		double par_2;


		//loop over all generated particles to do the matching
		for (int i = 0; i < ngenPart; ++i) {
		  if((abs(Id[i]) == leptonId)){ 

		    //Electrons selection
		    double R2 = DeltaR(gen_eta[i],evteta[j],gen_phi[i],evtphi[j] );

		    //Minimise DeltaR and Fill the other variables
		    if (R > R2) {

		      R = R2;
		      delta_P = abs(evtpt[j]-Pt[i])/Pt[i];
		      delta_charge = abs(evtq[j] - charge[i]);
		    }
		  }
		}

		//Choose the parameter to be filled for the eff.
		if(par_x == "Pt"){par = evtpt[j];}
		else if(par_x == "eta"){par = evteta[j];}
		else if(par_x == "phi"){par = evtphi[j];}
		if(par_y == "Pt"){par_2 = evtpt[j];}
		else if(par_y == "eta"){par_2 = abs(evteta[j]);}
		else if(par_y == "phi"){par_2 = abs(evtphi[j]);}

		//Fill Pt only for matched events
		if(((R<0.1)&&(delta_P < 0.2)&&(delta_charge < 0.5))||option.Contains(" unmatched ")){

		  for(int ii = 0; ii < npar2bins; ++ii){
		    if((par_2 > par2[ii])&&(par_2 <= par2[ii+1])){histo_den[ii]->Fill(par);histo_par1[ii]->Fill(par);
		      
		      if(evtloose[j] == 1){histo_good_sel->Fill(evttighte[j]);}
		      else if(evtloose[j] == 0){histo_other_sel->Fill(evttighte[j]);}
		      else{cout<<"Error !"<<endl; return 1;}
			
			
			}
		  }

		  //Additional cut on the numerator
		  int a = 0;

		  if((sel_num == "tightcut")&&(abs(evtid[j]) == 13)&&(evttight[j] == 1)){a = 1;}
		  if((sel_num == "tightcut")&&(abs(evtid[j]) == 11)&&(evttighte[j] >= 3)){a = 1;}
		  if((sel_num == "reliso3")&&(evtiso3[j] <= cut_num)){a = 2;}
		  if((sel_num == "reliso4")&&(evtiso4[j] <= cut_num)){a = 3;}
		  if((sel_num == "chiso3")&&(evtchiso3[j] <= cut_num)){a = 4;}
		  if((sel_num == "chiso4")&&(evtchiso4[j] <= cut_num)){a = 5;}
		  if((sel_num == "dxy")&&(abs(evtdxy[j]) <= cut_num)){a = 6;}
		  if((sel_num == "dz")&&(abs(evtdz[j]) <= cut_num)){a = 7;}
		  if((sel_num == "tightmva")&&(abs(evtid[j]) == 11)&&(evttight[j] == 1)){a = 9;}
		  if((sel_num == "loose")&&(evtloose[j]) == 1){a = 8;}

		  //Find the corresponding histogram for par2
		  TH1D* hist;
		  TH1D* hist_evt;

		  bool found = false;
		  for(int _i = 0; _i < npar2bins; ++_i){
		    if((par_2 > par2[_i])&&(par_2 <= par2[_i+1])){hist = histo_num[_i];found = true;}
		  }
		  if(!found){a = 0;}

		  switch(a){

		    case 0:

		      break;

		    case 1:
		      hist->Fill(par);
		      break;

		    case 2:
		      hist->Fill(par);
		      break;
		    case 3:
		      hist->Fill(par);
		      break;
		    case 4:
		      hist->Fill(par);
		      break;
		    case 5:
		      hist->Fill(par);
		      break;
		    case 6:
		      hist->Fill(par);
		      break;

		    case 7:
		      hist->Fill(par);
		      break;

		    case 8:
		      hist->Fill(par);
		      break;

		    case 9:
		      hist->Fill(par);
		      break;
		  }
		}
	      }
	    }
	  }
	
	//}
	}
      }
    }

    mkdir(_path+_fname+"_PDF/", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);

    ///////////////////
    //Draw histograms//
    ///////////////////

    //Canvas declaration
    for(int i = 0; i < npar2bins; ++i){

      ////////////////////
      //Build histograms//
      ////////////////////

      histo_num[i]->Sumw2();
      histo_den[i]->Sumw2();
      eff[i]->Divide(histo_num[i],histo_den[i],1,1,"B");

      //histo_num_O[i]->Sumw2();
      //histo_den_O[i]->Sumw2();
      //eff_O[i]->Divide(histo_num_O[i],histo_den_O[i],1,1,"B");

      //histo_num_G[i]->Sumw2();
      //histo_den_G[i]->Sumw2();
      //eff_G[i]->Divide(histo_num_G[i],histo_den_G[i],1,1,"B");

      //histo_counter_G_par1[i]->Sumw2();
      //histo_counter_O_par1[i]->Sumw2();
      //histo_counter_par1[i]->Divide(histo_counter_O_par1[i],histo_counter_G_par1[i],1,1,"B");

      //histo_counter[i]->Fill(0.5,goodcount);
      //histo_counter[i]->Fill(1.5,othercount);

      //String for name of the ouput files and histograms titles
      //

      TString _parybin;

      //Parameter string
      if(par_y == "Pt"){_parybin = Form("%0.f_Pt%0.f",par2[i],par2[i+1]);}
      else if(par_y == "eta"){_parybin = Form("%0.3f_eta%0.3f",par2[i],par2[i+1]);cout<<"it works !"<<endl;}
      else if(par_y == "phi"){_parybin = Form("%0.3f_phi%0.3f",par2[i],par2[i+1]);}

      TString _parytitle;

      //Title string
      if(par_y == "Pt"){_parytitle = Form("%0.f #leq P_{t} #leq %0.f",par2[i],par2[i+1]);}
      else if(par_y == "eta"){_parytitle = Form("%0.3f #leq #||{#eta}  #leq %0.3f",par2[i],par2[i+1]);cout<<"it works !"<<endl;}
      else if(par_y == "phi"){_parytitle = Form("%0.3f #leq #||{#phi}  #leq %0.3f",par2[i],par2[i+1]);}

      //Draw histograms
      TCanvas* c1 = new TCanvas("c1","c1");
      c1->cd();
      eff[i]->Draw();
      eff[i]->GetYaxis()->SetTitle("#epsilon");
      eff[i]->GetXaxis()->SetTitle(_par);
      eff[i]->GetYaxis()->SetRangeUser(0,1.1);
      eff[i]->SetMarkerStyle(20);
      eff[i]->SetMarkerSize(1);
      eff[i]->SetMarkerColor(4);
      eff[i]->SetLineColor(4);
      eff[i]->SetTitle(_sel_num+" for "+_sel_den+" "+pname+" "+_parytitle);

      TCanvas* c_par1 = new TCanvas("cpar1","cpar1");
      TString _partitle = _par + (TString)" distribution for "+pname+", "+_parytitle+", "+sel_num;
      c_par1->cd();
      histo_par1[i]->Draw();
      histo_par1[i]->SetTitle(_partitle);
      histo_par1[i]->GetXaxis()->SetTitle(_par);
      histo_par1[i]->SetLineWidth(2);
      histo_par1[i]->SetLineColor(4);
      histo_par1[i]->SetMarkerColor(4);

      histo_good_sel->Add(histo_other_sel);
      TCanvas* csel = new TCanvas("csel","csel");
      csel->cd();
      histo_good_sel->Draw();


      /////////////////////
      //Saving the output//
      /////////////////////

      //Write pdf
      TString cname = "eff"+_filetag+_option+_pname+_par1range+"_"+_parybin+"_den_"+_sel_den+"_num_"+_sel_num;
      c1->SaveAs(_path+_fname+"_PDF/"+cname+".pdf");
      c_par1->SaveAs(_path+_fname+"_PDF/"+cname+"par_distr.pdf");
      csel->SaveAs(_path+_fname+"_PDF/"+cname+"sel.pdf");

      //Write in output file
      file_out->cd();
      eff[i]->Write("eff"+_parybin);
      histo_good_sel->Write("sel"+_parybin);
      //histo_par1[i]->Write("histo_par1_"+_parybin);
      

    }

    file_out->Close();

    return 0;


  }
void Draw_BDiJetImbalance()
{
  gStyle->SetOptStat(0);
  gStyle->SetOptTitle(0);

  //==========================================================================//
  // SET RUNNING CONDITIONS
  //==========================================================================//
  bool print_plots = true;

  bool is_pp = false;

  // const char* inFile = "HFtag_bjet.root";
  // const char* inFile = "HFtag_bjet_pp.root";
  // const char* inFile = "/phenix/plhf/dcm07e/sPHENIX/bjetsims/test.root";
  // if (!is_pp)
  //   const char* inFile = "HFtag_bjet_AuAu0-10.root";

  const char* inDir = "/phenix/plhf/dcm07e/sPHENIX/bjetsims/ana";

  // // desired nn integrated luminosity [pb^{-1}]
  // double lumiDesired = 175;
  // if ( !is_pp )
  //   lumiDesired = 229; // AuAu 0-10% central (10B events)
  // desired nn integrated luminosity [pb^{-1}]
  double lumiDesired = 200;
  TString scol("p + p #sqrt{s_{_{NN}}} = 200 GeV");
  TString slumi(Form("#int L dt = %.0f pb^{-1} |z| < 10 cm", lumiDesired));
  if ( !is_pp )
  {
    // equivelant nn luminosity:
    // N_{evt}^{NN} / sigma_NN = N_{evt}^{AA}*Ncoll / sigma_NN
    // = 10e9 * 962 / 42e9 pb = 229 pb^-1
    double evntDesired = 24e9; // AuAu 0-10% central
    lumiDesired = evntDesired * 962 / 42e9; // AuAu 0-10% central
    scol = "0-10% Au + Au #sqrt{s_{_{NN}}}=200 GeV";
    slumi = Form("%.0fB events |z| < 10 cm", evntDesired / 1.e9);
  }

  // luminosity per file generated [pb^{-1}]
  double lumiPerFile = 99405 / (4.641e-06 * 1e12);
  double lumiRead = 0;

  double pT1min = 20;
  double pT2min = 10;
  // double etamax = 1.0;
  double etamax = 0.7;

  // double bJetEff = 0.5; // b-jet tagging efficiency
  double bJetEff = 0.60; // p+p b-jet tagging efficiency
  if ( !is_pp )
    bJetEff = 0.40;

  double bJetPur = 0.40; // b-jet tagging purity

  double RAA = 1.0;
  if (!is_pp)
    RAA = 0.6;

  const int NETACUT = 3;
  double etacut[] = {1.3, 1.0, 0.7};
  double etaColor[] = {kBlue, kRed, kBlack};

  const int PTCUT = 3;
  double ptcut[] = {10, 20, 40};
  double ptColor[] = {kBlue, kRed, kBlack};

  //==========================================================================//
  // DECLARE VARIABLES
  //==========================================================================//

  //-- tree variables
  TChain *ttree;
  Int_t           event;
  Int_t           truthjet_n;
  Int_t           truthjet_parton_flavor[100];
  Int_t           truthjet_hadron_flavor[100];
  Float_t         truthjet_pt[100];
  Float_t         truthjet_eta[100];
  Float_t         truthjet_phi[100];

  //-- histograms

  TH1D* hjet_pT = new TH1D("hjet_pT", ";p_{T}^{jet} [GeV/c]", 20, 0, 100);
  TH1D* hjet_eta = new TH1D("hjet_eta", ";#eta^{jet}", 40, -2., 2.);
  TH1D* hjet_phi = new TH1D("hjet_phi", ";#phi^{jet}", 40, -4, 4);

  TH1D* hdijet_pT1 = new TH1D("hdijet_pT1", ";p_{T,1}^{jet} [GeV/c]", 20, 0, 100);
  TH1D* hdijet_pT2 = new TH1D("hdijet_pT2", ";p_{T,2}^{jet} [GeV/c]", 20, 0, 100);
  TH1D* hdijet_xj = new TH1D("hdijet_xj", ";x_{j} = p_{T,2} / p_{T,1}; event fraction", 10, 0, 1);
  TH1D* hdijet_dphi = new TH1D("hdijet_dphi", ";|#Delta#phi_{12}|; event fraction", 10, 0, TMath::Pi());

  TH1D* hdijet_sing_pT1 = new TH1D("hdijet_sing_pT1",
                                   ";p_{T,1} [GeV/c];Fraction of Dijet / Single Accepted",
                                   20, 00, 100);
  TH1D* hdijet_sing_eta2 = new TH1D("hdijet_sing_eta2",
                                    ";#eta_{2};Fraction of Dijet / Single Accepted",
                                    15, -1.5, 1.5);
  TH1D* hdijet_eff_pT1[3];
  TH1D* hdijet_eff_eta2[3];
  for (int i = 0; i < NETACUT; i++)
  {
    hdijet_eff_pT1[i] = new TH1D(Form("hdijet_eff_pT1_%i", i),
                                 ";p_{T,1} [GeV/c];Fraction of Dijet / Single Accepted",
                                 20, 00, 100);
    hdijet_eff_pT1[i]->SetLineColor(etaColor[i]);
    hdijet_eff_pT1[i]->SetLineWidth(2);
  } // i
  for (int i = 0; i < PTCUT; i++)
  {
    hdijet_eff_eta2[i] = new TH1D(Form("hdijet_eff_eta2_%i", i),
                                  ";#eta;Fraction of Dijet / Single Accepted",
                                  15, -1.5, 1.5);
    hdijet_eff_eta2[i]->SetLineColor(etaColor[i]);
    hdijet_eff_eta2[i]->SetLineWidth(2);
  } // i

  hjet_pT->Sumw2();
  hjet_eta->Sumw2();
  hjet_phi->Sumw2();

  hdijet_pT1->Sumw2();
  hdijet_pT2->Sumw2();
  hdijet_dphi->Sumw2();
  hdijet_xj->Sumw2();

  // for fixing the uncertainties
  TH1D* hdijet_xj_fix;

  //-- other
  TRandom3 *rand = new TRandom3();

  bool acc[100];

  //==========================================================================//
  // LOAD TTREE
  //==========================================================================//
  // cout << endl;
  // cout << "--> Reading data from " << inFile << endl;

  // TFile *fin = TFile::Open(inFile);
  // if (!fin)
  // {
  //   cout << "ERROR!! Unable to open " << inFile << endl;
  //   return;
  // }

  // ttree = (TTree*) fin->Get("ttree");
  // if (!ttree)
  // {
  //   cout << "ERROR!! Unable to find ttree in " << inFile << endl;
  //   return;
  // }

  cout << endl;
  cout << "--> Reading data from dir: " << inDir << endl;

  // calculate the number of files necessary for the desired luminosity
  int nfiles = (int)(lumiDesired / lumiPerFile);
  cout << "  desired luminosity : " << lumiDesired << endl;
  cout << "  luminosity per file: " << lumiPerFile << endl;
  cout << "  N files needed     : " << nfiles << endl;


  // check the number of files found in the directory
  int nfound = (gSystem->GetFromPipe(Form("ls %s/*.root | wc -l", inDir))).Atoi();
  cout << "  N files found      : " << nfound << endl;

  if (nfound < nfiles)
  {
    cout << "WARNING!! There are not enough files for the desired luminosity." << endl;
    cout << "          Will scale the statistical uncertainties accordingly." << endl;
    // return;
  }

  // chain the desired files
  ttree = new TChain("ttree");
  int nread = 0;

  TString fileList = gSystem->GetFromPipe(Form("ls %s/*.root", inDir));

  int spos = fileList.First("\n");
  while (spos > 0 && nread < nfiles)
  {
    TString tfile = fileList(0, spos);
    // cout << tsub << endl;

    ttree->Add(tfile.Data());


    // chop off the file
    fileList = fileList(spos + 1, fileList.Length());
    spos = fileList.First("\n");
    nread++;
  }

  cout << " successfully read in " << nread << " files" << endl;
  lumiRead = lumiPerFile * nread;


  ttree->SetBranchAddress("event", &event);
  ttree->SetBranchAddress("truthjet_n", &truthjet_n);
  ttree->SetBranchAddress("truthjet_parton_flavor", truthjet_parton_flavor);
  ttree->SetBranchAddress("truthjet_hadron_flavor", truthjet_hadron_flavor);
  ttree->SetBranchAddress("truthjet_pt", truthjet_pt);
  ttree->SetBranchAddress("truthjet_eta", truthjet_eta);
  ttree->SetBranchAddress("truthjet_phi", truthjet_phi);

  Long64_t nentries = ttree->GetEntries();


  //==========================================================================//
  // GET MOMENTUM IMBALANCE
  //==========================================================================//
  cout << endl;
  cout << "--> Running over " << nentries << endl;

  int iprint = 0;
  for (Long64_t ientry = 0; ientry < nentries; ientry++)
  {
    ttree->GetEntry(ientry);

    if (ientry % 100000 == 0) cout << "----> Processing event " << ientry << endl;

    //-- apply acceptance to each jet
    for (int i = 0; i < truthjet_n; i++)
      acc[i] = (rand->Uniform() < bJetEff);
      // acc[i] = (rand->Uniform() < bJetEff) && (rand->Uniform() < RAA);

    //-- get kinematics for all b-jets
    for (int i = 0; i < truthjet_n; i++)
    {
      if (TMath::Abs(truthjet_parton_flavor[i]) != 5)
        continue;

      // single b-jet kinematics
      hjet_pT->Fill(truthjet_pt[i]);
      hjet_eta->Fill(truthjet_eta[i]);
      hjet_phi->Fill(truthjet_phi[i]);

      for (int j = i + 1; j < truthjet_n; j++)
      {
        if (TMath::Abs(truthjet_parton_flavor[j]) != 5)
          continue;


        // find the leading and subleading jets
        int i1, i2;
        double pT1, pT2;
        double phi1, phi2;
        double eta1, eta2;
        bool acc1, acc2;

        if (truthjet_pt[i] > truthjet_pt[j])
        {
          i1 = i;
          i2 = j;
        }
        else
        {
          i1 = j;
          i2 = i;
        }

        pT1 = truthjet_pt[i1];
        phi1 = truthjet_phi[i1];
        eta1 = truthjet_eta[i1];
        acc1 = acc[i1];

        pT2 = truthjet_pt[i2];
        phi2 = truthjet_phi[i2];
        eta2 = truthjet_eta[i2];
        acc2 = acc[i2];



        if (iprint < 20)
        {
          cout << " ientry: " << ientry << endl
               << "        i1:" << i1 << " pT1:" << pT1 << " eta1:" << eta1 << " acc1:" << acc1 << endl
               << "        i2:" << i2 << " pT2:" << pT2 << " eta2:" << eta2 << " acc2:" << acc2 << endl;
          iprint++;
        }



        // check if we accept the leading jet
        // only take RAA hit once
        if ( pT1 < pT1min || TMath::Abs(eta1) > etamax || !acc1  || rand->Uniform() > RAA)
          continue;

        // calculate the delta phi
        double dphi = TMath::Abs(TMath::ATan2(TMath::Sin(phi1 - phi2), TMath::Cos(phi1 - phi2)));
        if (dphi > TMath::Pi())
          cout << " " << truthjet_phi[i] << " " << truthjet_phi[j] << " " << dphi << endl;

        // calculate efficiency for finding the dijet
        hdijet_sing_pT1->Fill(pT1);

        // cut on the subleading jet
        if ( pT2 < pT2min || TMath::Abs(eta2) > etamax || !acc2 )
          continue;

        hdijet_sing_eta2->Fill(eta2);


        // fill efficiency for finding the dijet
        for (int k = 0; k < NETACUT; k++)
        {
          if ( TMath::Abs(eta2) < etacut[k])
            hdijet_eff_pT1[k]->Fill(pT1);
        }
        for (int k = 0; k < PTCUT; k++)
        {
          if (pT2 > ptcut[k])
            hdijet_eff_eta2[k]->Fill(eta2);
        }

        hdijet_dphi->Fill(dphi);

        if ( dphi < 2.*TMath::Pi() / 3)
          continue;


        // fill diagnostic histograms

        hdijet_pT1->Fill(pT1);
        hdijet_pT2->Fill(pT2);
        hdijet_xj->Fill(pT2 / pT1);

      } // j
    } // i

  } // ientry

  // first get some statistics
  cout << " N b dijets: " << hdijet_dphi->Integral() << endl;
  cout << " N b dijets w / dphi cut: " << hdijet_xj->Integral() << endl;

  // calculate efficiencies
  for (int i = 0; i < NETACUT; i++)
  {
    hdijet_eff_pT1[i]->Divide(hdijet_sing_pT1);
    cout << " i: " << hdijet_eff_pT1[i]->GetMaximum() << endl;
  }
  for (int i = 0; i < PTCUT; i++)
  {
    hdijet_eff_eta2[i]->Divide(hdijet_sing_eta2);
  }

  //-- normalize to integral 1
  hdijet_dphi->Scale(1. / hdijet_dphi->Integral());
  hdijet_xj->Scale(1. / hdijet_xj->Integral());

  //-- scale statistical uncertainties if not enough simulated events
  if ( lumiRead < lumiDesired )
  {
    cout << endl;
    cout << "-- Scaling statistical uncertainties by:" << endl;
    cout << "  sqrt(" << lumiRead << "/" << lumiDesired << ") = "
         << TMath::Sqrt(lumiRead / lumiDesired) << endl;
    for (int ix = 1; ix <= hdijet_xj->GetNbinsX(); ix++)
    {
      double be = hdijet_xj->GetBinError(ix);
      be = be * TMath::Sqrt(lumiRead / lumiDesired);
      hdijet_xj->SetBinError(ix, be);
    } // ix
  }

  //-- fix statistical uncertainties for purity
  hdijet_xj_fix = (TH1D*) hdijet_xj->Clone("hdijet_xj_fix");
  hdijet_xj_fix->SetLineColor(kRed);
  hdijet_xj_fix->SetMarkerColor(kRed);
  for (int ix = 1; ix <= hdijet_xj->GetNbinsX(); ix++)
  {
    double bc = hdijet_xj->GetBinContent(ix);
    double be = hdijet_xj->GetBinError(ix);

    // increase the bin error due to the purity
    // need to square it, once for each bjet
    be = be / TMath::Sqrt(bJetPur * bJetPur);
    hdijet_xj_fix->SetBinError(ix, be);
  } // ix



  //==========================================================================//
  // <x_j>
  //==========================================================================//
  cout << endl;
  cout << "--> Calculating <x_j>" << endl;

  double sum = 0;
  double w = 0;
  double err = 0;
  for (int i = 1; i <= hdijet_xj->GetNbinsX(); i++)
  {
    double c = hdijet_xj->GetBinContent(i);
    if (c > 0)
    {
      sum += c * hdijet_xj->GetBinCenter(i);
      w += c;
      err += TMath::Power(c * hdijet_xj->GetBinError(i), 2);
    }
  }
  double mean = sum / w;
  err = TMath::Sqrt(err) / w;

  cout << "  <x_j>=" << mean << " +/- " << err << endl;

  //==========================================================================//
  // PLOT OBJECTS
  //==========================================================================//
  cout << endl;
  cout << "-- > Plotting" << endl;

  hdijet_xj->SetMarkerStyle(kFullCircle);
  hdijet_xj->SetMarkerColor(kBlack);
  hdijet_xj->SetLineColor(kBlack);
  // hdijet_xj->GetYaxis()->SetTitleFont(63);
  // hdijet_xj->GetYaxis()->SetTitleSize(24);
  // hdijet_xj->GetYaxis()->SetTitleOffset(1.4);
  // hdijet_xj->GetYaxis()->SetLabelFont(63);
  // hdijet_xj->GetYaxis()->SetLabelSize(20);
  // hdijet_xj->GetXaxis()->SetTitleFont(63);
  // hdijet_xj->GetXaxis()->SetTitleSize(24);
  // hdijet_xj->GetXaxis()->SetTitleOffset(1.0);
  // hdijet_xj->GetXaxis()->SetLabelFont(63);
  // hdijet_xj->GetXaxis()->SetLabelSize(20);

  hdijet_xj_fix->SetMarkerStyle(kFullCircle);
  hdijet_xj_fix->SetMarkerColor(kBlack);
  hdijet_xj_fix->SetLineColor(kBlack);

  hdijet_dphi->SetMarkerStyle(kFullCircle);
  hdijet_dphi->SetMarkerColor(kBlack);
  hdijet_dphi->SetLineColor(kBlack);
  hdijet_dphi->GetYaxis()->SetTitleFont(63);
  hdijet_dphi->GetYaxis()->SetTitleSize(24);
  hdijet_dphi->GetYaxis()->SetTitleOffset(1.4);
  hdijet_dphi->GetYaxis()->SetLabelFont(63);
  hdijet_dphi->GetYaxis()->SetLabelSize(20);
  hdijet_dphi->GetXaxis()->SetTitleFont(63);
  hdijet_dphi->GetXaxis()->SetTitleSize(24);
  hdijet_dphi->GetXaxis()->SetTitleOffset(1.0);
  hdijet_dphi->GetXaxis()->SetLabelFont(63);
  hdijet_dphi->GetXaxis()->SetLabelSize(20);

  hdijet_pT1->SetLineColor(kBlue);
  hdijet_pT2->SetLineColor(kRed);

  TH1D* heff_axis_pt = new TH1D("heff_axis_pt",
                                "; p_{T, 1} [GeV / c]; Fraction of Dijet / Single Accepted",
                                20, 00, 100);
  heff_axis_pt->SetMinimum(0);
  heff_axis_pt->SetMaximum(1.);
  heff_axis_pt->GetYaxis()->SetTitleFont(63);
  heff_axis_pt->GetYaxis()->SetTitleSize(24);
  heff_axis_pt->GetYaxis()->SetTitleOffset(1.4);
  heff_axis_pt->GetYaxis()->SetLabelFont(63);
  heff_axis_pt->GetYaxis()->SetLabelSize(20);
  heff_axis_pt->GetXaxis()->SetTitleFont(63);
  heff_axis_pt->GetXaxis()->SetTitleSize(24);
  heff_axis_pt->GetXaxis()->SetTitleOffset(1.0);
  heff_axis_pt->GetXaxis()->SetLabelFont(63);
  heff_axis_pt->GetXaxis()->SetLabelSize(20);

  TH1D* heff_axis_eta = new TH1D("heff_axis_eta",
                                 "; #eta_{2}; Fraction of Dijet / Single Accepted",
                                 150, -1.5, 1.5);
  heff_axis_eta->SetMinimum(0);
  heff_axis_eta->SetMaximum(1.);
  heff_axis_eta->GetYaxis()->SetTitleFont(63);
  heff_axis_eta->GetYaxis()->SetTitleSize(24);
  heff_axis_eta->GetYaxis()->SetTitleOffset(1.4);
  heff_axis_eta->GetYaxis()->SetLabelFont(63);
  heff_axis_eta->GetYaxis()->SetLabelSize(20);
  heff_axis_eta->GetXaxis()->SetTitleFont(63);
  heff_axis_eta->GetXaxis()->SetTitleSize(24);
  heff_axis_eta->GetXaxis()->SetTitleOffset(1.0);
  heff_axis_eta->GetXaxis()->SetLabelFont(63);
  heff_axis_eta->GetXaxis()->SetLabelSize(20);

  for (int i = 0; i < NETACUT; i++)
    hdijet_eff_pT1[i]->SetLineColor(etaColor[i]);

//-- legends
  TLegend *leg_jetpt = new TLegend(0.6, 0.5, 0.95, 0.95);
  leg_jetpt->SetFillStyle(0);
  leg_jetpt->SetBorderSize(0);
  leg_jetpt->SetTextFont(63);
  leg_jetpt->SetTextSize(12);
  leg_jetpt->AddEntry(hjet_pT, "Inclusive b - jet", "L");
  leg_jetpt->AddEntry(hdijet_pT1, "leading b - jet", "L");
  leg_jetpt->AddEntry(hdijet_pT2, "subleading b - jet", "L");


//-- other
  TLatex ltxt;
  ltxt.SetNDC();
  ltxt.SetTextFont(63);
  ltxt.SetTextSize(20);

//==========================================================================//
// PLOT
//==========================================================================//

// plot b-jet kinematics
  TCanvas *cjet = new TCanvas("cjet", "b - jet", 1200, 400);
  cjet->SetMargin(0, 0, 0, 0);
  cjet->Divide(3, 1);

  cjet->GetPad(1)->SetMargin(0.12, 0.02, 0.12, 0.02);
  cjet->GetPad(2)->SetMargin(0.12, 0.02, 0.12, 0.02);
  cjet->GetPad(3)->SetMargin(0.12, 0.02, 0.12, 0.02);

  cjet->cd(1);
  gPad->SetLogy();
  hjet_pT->GetYaxis()->SetRangeUser(0.5, 1.5 * hjet_pT->GetMaximum());
  hjet_pT->GetXaxis()->SetRangeUser(0, 50);
  hjet_pT->Draw();
  // hdijet_pT1->Draw("same");
  // hdijet_pT2->Draw("same");

  // leg_jetpt->Draw("same");

  cjet->cd(2);
  hjet_eta->Draw("HIST");

  cjet->cd(3);
  hjet_phi->Draw("HIST");


// plot dijet eff
  TCanvas *ceff = new TCanvas("ceff", "eff", 1200, 600);
  ceff->Divide(2, 1);
  ceff->GetPad(1)->SetMargin(0.12, 0.02, 0.12, 0.02);
  ceff->GetPad(1)->SetTicks(1, 1);
  ceff->GetPad(2)->SetMargin(0.12, 0.02, 0.12, 0.02);
  ceff->GetPad(2)->SetTicks(1, 1);

  ceff->cd(1);

  heff_axis_pt->Draw();

  for (int i = 0; i < NETACUT; i++)
    hdijet_eff_pT1[i]->Draw("L same");

  ceff->cd(2);

  heff_axis_eta->Draw();

  for (int i = 0; i < NETACUT; i++)
    hdijet_eff_eta2[i]->Draw("L same");

// plot dijet checks
  TCanvas *cdijet2 = new TCanvas("cdijet2", "dijet", 1200, 600);
  cdijet2->SetMargin(0, 0, 0, 0);
  cdijet2->Divide(2, 1);

  cdijet2->GetPad(1)->SetMargin(0.12, 0.02, 0.12, 0.02);
  cdijet2->GetPad(2)->SetMargin(0.12, 0.02, 0.12, 0.02);

  cdijet2->cd(1);
  hdijet_xj->Draw();

  ltxt.DrawLatex(0.2, 0.92, "Di b-jets (Pythia8)");
  ltxt.DrawLatex(0.2, 0.86, "p + p #sqrt{s_{_{NN}}}=200 GeV");
  ltxt.DrawLatex(0.2, 0.80, "anti - k_ {T}, R = 0.4");
  ltxt.DrawLatex(0.2, 0.74, Form("p_{T, 1} > % .0f GeV", pT1min));
  ltxt.DrawLatex(0.2, 0.68, Form("p_{T, 2} > % .0f GeV", pT2min));
  ltxt.DrawLatex(0.2, 0.62, Form(" | #Delta#phi_{12}| > 2#pi/3"));

  cdijet2->cd(2);
  hdijet_dphi->Draw();






  // make this one consistent with sPHENIX style
  TCanvas *cdijet = new TCanvas("cdijet", "dijet", 600, 600);
  // cdijet->SetMargin(0.12, 0.02, 0.12, 0.02);
  // cdijet->SetTicks(1, 1);
  cdijet->cd();
  hdijet_xj_fix->GetYaxis()->SetRangeUser(0, 0.3);
  hdijet_xj_fix->Draw();
  // hdijet_xj->Draw("same");


  TLegend *legsphenix = new TLegend(0.15, 0.5, 0.5, 0.9);
  legsphenix->SetFillStyle(0);
  legsphenix->SetBorderSize(0);
  legsphenix->AddEntry("", "#it{#bf{sPHENIX}} Simulation", "");
  legsphenix->AddEntry("", "Di b-jets (Pythia8, CTEQ6L)", "");
  // if (is_pp)
  // {
  //   legsphenix->AddEntry("", "p + p #sqrt{s_{_{NN}}} = 200 GeV", "");
  //   legsphenix->AddEntry("", Form("#int L dt = %.0f pb^{-1} |z| < 10 cm", lumiDesired), "");
  // }
  // else
  // {
  //   legsphenix->AddEntry("", "0-10% Au + Au #sqrt{s_{_{NN}}}=200 GeV", "");
  //   legsphenix->AddEntry("", "10B events |z| < 10 cm", "");
  // }
  legsphenix->AddEntry("", scol.Data(), "");
  legsphenix->AddEntry("", slumi.Data(), "");
  legsphenix->AddEntry("", "anti-k_{T}, R = 0.4", "");
  legsphenix->AddEntry("", Form(" |#eta| < %.1f", etamax), "");
  legsphenix->AddEntry("", Form(" |#Delta#phi_{12}| > 2#pi/3"), "");
  legsphenix->AddEntry("", Form("p_{T, 1} > % .0f GeV", pT1min), "");
  legsphenix->AddEntry("", Form("p_{T, 2} > % .0f GeV", pT2min), "");
  legsphenix->AddEntry("", Form("%.0f%% b-jet Eff, %.0f%% b-jet Pur.", bJetEff * 100., bJetPur * 100.), "");
  legsphenix->Draw("same");

  // ltxt.DrawLatex(0.2, 0.92, "Di b-jets (Pythia8)");
  // if (is_pp)
  // {
  //   ltxt.DrawLatex(0.2, 0.86, "p + p #sqrt{s_{_{NN}}} = 200 GeV");
  //   ltxt.DrawLatex(0.2, 0.80, "#int L dt = 175 pb^{-1} |z| < 10 cm");
  // }
  // else
  // {
  //   ltxt.DrawLatex(0.2, 0.86, "0-10% Au + Au #sqrt{s_{_{NN}}}=200 GeV");
  //   ltxt.DrawLatex(0.2, 0.80, "10B events |z| < 10 cm");
  // }
  // ltxt.DrawLatex(0.2, 0.74, "anti-k_{T}, R = 0.4");
  // ltxt.DrawLatex(0.2, 0.68, Form("p_{T, 1} > % .0f GeV", pT1min));
  // ltxt.DrawLatex(0.2, 0.62, Form("p_{T, 2} > % .0f GeV", pT2min));
  // ltxt.DrawLatex(0.2, 0.56, Form(" |#eta| < %.0f", etamax));
  // ltxt.DrawLatex(0.2, 0.50, Form(" |#Delta#phi_{12}| > 2#pi/3"));


  //==========================================================================//
  // PRINT PLOTS
  //==========================================================================//
  if (print_plots)
  {
    if (is_pp)
    {
      // cjet->Print("bjet_kinematics_pp.pdf");
      // cdijet2->Print("dibjet_2panel_pp.pdf");
      cdijet->Print("dibjet_imbalance_pp.pdf");
      cdijet->Print("dibjet_imbalance_pp.C");
      cdijet->Print("dibjet_imbalance_pp.root");

      TFile *fout = new TFile("dibjet_imbalance_histos_pp.root","RECREATE");
      fout->cd();
      hdijet_xj->Write();
      hdijet_xj_fix->Write();
      fout->Close();
      delete fout;

    }
    else
    {
      cdijet->Print("dibjet_imbalance_AuAu0-10.pdf");
      cdijet->Print("dibjet_imbalance_AuAu0-10.C");
      cdijet->Print("dibjet_imbalance_AuAu0-10.root");

      TFile *fout = new TFile("dibjet_imbalance_histos_AuAu0-10.root","RECREATE");
      fout->cd();
      hdijet_xj->Write();
      hdijet_xj_fix->Write();
      fout->Close();
      delete fout;
    }
  }

}
void GetGen(double sampleweight, TH1D* &h_phistar, vector<TH1D*> &h_cteq, vector<TH1D*> &h_fsr_pileup) {
  gErrorIgnoreLevel = kError;
  cout << "reading signal gen" << endl;
  h_phistar = new TH1D("phistar", "phistar", nbins, 0, nbins);
  h_phistar->Sumw2();
  TChain* t = new TChain(gen_name.c_str(), gen_name.c_str());
  if (doMG) {
    if (elec == 0) t->Add(File_Signal_gen.c_str());
    else if (elec == 1) t->Add(File_Signal_gen_born.c_str());
    else t->Add(File_Signal_gen_bare.c_str());
  } else {
    if (elec == 0) t->Add(File_Powheg_gen.c_str());
    else if (elec == 1) t->Add(File_Powheg_gen_born.c_str());
    else t->Add(File_Powheg_gen_bare.c_str());
  }
  ///t->SetBranchStatus("event_info", 0); //to disable all branches
  //  t->SetBranchStatus("reco", 0); //to disable all branches
  TBranch *b_truth = t->GetBranch("truth");
  TBranch *b_reco = t->GetBranch("reco");
  TLeaf * l_ZY = b_truth->GetLeaf("z_y");
  if (elec == 1) l_ZY = b_reco->GetLeaf("z_yBorn"); //TO BE CHANGED
  if (elec == 2) l_ZY = b_reco->GetLeaf("z_yNaked");
  TLeaf *l_phistar = b_truth->GetLeaf("z_phistar_dressed");
  if (elec == 1) l_phistar = b_truth->GetLeaf("z_phistar_born");
  if (elec == 2) l_phistar = b_truth->GetLeaf("z_phistar_naked");
  int nweights;
  int nwcteq;
  t->SetBranchAddress("weight_size", &nweights);
  t->SetBranchAddress("weight_cteq_size", &nwcteq);
  t->GetEntry(0);
  double weights[nweights];
  int weightid[nweights];
  double weights_cteq[nwcteq];
  t->SetBranchAddress("weights", &weights);
  t->SetBranchAddress("weight_ids", &weightid);
  t->SetBranchAddress("weights_cteq", &weights_cteq);
  double weight_fsr;
  t->SetBranchAddress("weight_fsr", &weight_fsr);
  cout << "Entries: " << t->GetEntries() << endl;
  h_cteq = EmptyHVec(nwcteq);
  h_fsr_pileup = EmptyHVec(3);

  TH1D* h_PDFWeight = new TH1D("h_PDFWeight", "h_PDFWeight", 10000, 0, 100);
  h_PDFWeight->Sumw2();
  // cout << "Nweightcteq=" << nwcteq << endl;

  for (int i = 0; i < t->GetEntries(); i++) {
    // for (int i=0; i<50000;i++){
    t->GetEntry(i);
    double weight = sampleweight;
    double pdfnorm = weights_cteq[0];
    double weightpu_0 = 0;
    double weightpu_p = 0;
    double weightpu_m = 0;
    double phistar = l_phistar->GetValue();
    double Z_Y = l_ZY->GetValue();
    int bin=GetBin(phistar,Z_Y);
    //cout<<pdfnorm<<" "<<weights_cteq[0]<<endl;
    for (int w = 0; w < nweights; w++) {
      if (weightid[w] == 1 || weightid[w] == 2) {
        weight = weight * weights[w];
      }
      //if (weightid[w]==1) {weight=weight*weights[w];}
      if (weightid[w] == 2) weightpu_0 = weights[w];
      if (weightid[w] == 3) weightpu_p = weights[w];
      if (weightid[w] == 4) weightpu_m = weights[w];
    }
    // if (weightpu_0 == 0 || weightpu_p == 0 || weightpu_m == 0) cout << "pile-up weights not there" << endl;
    h_phistar->Fill(bin, weight);
    if (pdfnorm != 0) {
      for (int w = 0; w < nwcteq; w++) {
        h_cteq[w] ->Fill(bin, weight * weights_cteq[w] / pdfnorm);
        if (w != 0) {
          h_PDFWeight->Fill(weights_cteq[w] / pdfnorm, 1);
          // cout<<weights_cteq[w] / pdfnorm<<endl;
        }
      }
    }
    if (doMG) weight_fsr = 1;
    h_fsr_pileup[0]->Fill(bin, weight * weight_fsr);
    if (weightpu_0 != 0) {
      h_fsr_pileup[1]->Fill(bin, weight * weightpu_p / weightpu_0);
      h_fsr_pileup[2]->Fill(bin, weight * weightpu_m / weightpu_0);
    }
  }
  cout << "done reading signal gen" << endl;
  delete t;
  return;
}
void countMuonsPerRunD3PD(){

  //gInterpreter->GenerateDictionary("map<int, double >","map.h;map");
  int cutValue = 11;
  float ptmin = 10.0;
  //float ptmin = 4.;
  //TString fileNameMuonIn = "/afs/cern.ch/user/t/tbalestr/public/16.6.2.5/WorkArea/run/HISingleMuon.root";

///7.3 ub^-1 2010 data
  //TString fileNameMuonIn = "/tmp/tbalestr/HISingleMuon_Aug4_v2.root";
  ///2011 PbPb data
  //TString fileNameMuonIn = "/tmp/tbalestr/HISingleMuon_DPD_HP_merged_26May.root";
  //TString fileNameMuonIn = "/tmp/tbalestr/HISingleMuon_DPD_HP_30May.root";

  TString baseString = "/mnt/Lustre/cgrp/atlas_hi/tbalestri/";
  TString fileNameMuonIn = baseString+"HardProbesFiles/HISingleMuonHardProbesData.04.17.2013.root";  
  TFile* fMuIn = new TFile(fileNameMuonIn, "READ");
  if ( !fMuIn->IsOpen() ) {
    std::cout << fMuIn << " not found!" << std::endl;
  }

  TFile* outFile = new TFile("muonsPerRun.root","recreate");
  
  ///lumi in ub^-1
  std::vector<double> vLumi;
  vLumi.push_back(0.0137422);
  vLumi.push_back(0.126333);
  vLumi.push_back(1.28605451);
  vLumi.push_back(0.08307752);
  vLumi.push_back(3.948807);
  vLumi.push_back(2.766361);
  vLumi.push_back(3.606919);
  vLumi.push_back(3.809249);
  vLumi.push_back(4.11709);
  vLumi.push_back(4.88581);
  vLumi.push_back(2.50513);
  vLumi.push_back(0.0619227);
  vLumi.push_back(0.9694949);
  vLumi.push_back(0.582203);
  vLumi.push_back(5.42834);
  vLumi.push_back(4.20247);
  vLumi.push_back(0.38549);
  vLumi.push_back(5.50425);
  vLumi.push_back(3.15969);
  vLumi.push_back(4.19951);
  vLumi.push_back(5.24396);
  vLumi.push_back(5.30817);
  vLumi.push_back(0.0433861);
  vLumi.push_back(5.29888);
  vLumi.push_back(5.30346);
  vLumi.push_back(0.757212);
  vLumi.push_back(5.985104);
  vLumi.push_back(5.1515);
  vLumi.push_back(6.57761);
  vLumi.push_back(1.75062);
  vLumi.push_back(5.43771);
  vLumi.push_back(3.13928);
  vLumi.push_back(5.14981);
  vLumi.push_back(4.90751);
  vLumi.push_back(2.521785);
  vLumi.push_back(6.45269);
  vLumi.push_back(3.59951);
  vLumi.push_back(5.33795);
  vLumi.push_back(6.16766);
  vLumi.push_back(1.77379);
  vLumi.push_back(0.923454);
  vLumi.push_back(2.07656);

  std::vector<int> vRun;
  vRun.push_back(193211);
  vRun.push_back(193270);
  vRun.push_back(193291);
  vRun.push_back(193295);
  vRun.push_back(193321);
  vRun.push_back(193403);
  vRun.push_back(193412);
  vRun.push_back(193447);
  vRun.push_back(193463);
  vRun.push_back(193481);
  vRun.push_back(193491);
  vRun.push_back(193492);
  vRun.push_back(193493);
  vRun.push_back(193494);
  vRun.push_back(193546);
  vRun.push_back(193558);
  vRun.push_back(193599);
  vRun.push_back(193604);
  vRun.push_back(193641);
  vRun.push_back(193655);
  vRun.push_back(193662);
  vRun.push_back(193679);
  vRun.push_back(193687);
  vRun.push_back(193718);
  vRun.push_back(193795);
  vRun.push_back(193823);
  vRun.push_back(193825);
  vRun.push_back(193826);
  vRun.push_back(193834);
  vRun.push_back(193890);
  vRun.push_back(194017);
  vRun.push_back(194060);
  vRun.push_back(194061);
  vRun.push_back(194121);
  vRun.push_back(194160);
  vRun.push_back(194163);
  vRun.push_back(194179);
  vRun.push_back(194192);
  vRun.push_back(194193);
  vRun.push_back(194370);
  vRun.push_back(194374);
  vRun.push_back(194382);
  const int nRuns = vRun.size(); 

  TGraphErrors* grLumi = new TGraphErrors(nRuns);
  TGraphErrors* grMuPerLumi = new TGraphErrors(nRuns);

  int valNt[30], EF_mu4_MSonly_L1TE50_Matched20[30],EF_mu4_L1VTE50_Matched20[30],runNt, mu_muid_nNt;
  int EF_mu10_MSonly_EFFS_L1ZDC_Matched20[30], EF_mu10_MSonly_EFFS_L1TE10_Matched20[30],EF_mu10_MSonly_EFFS_L1TE20_Matched20[30];
  int EF_mu10_MSonly_EFFS_L1ZDC, EF_mu10_MSonly_EFFS_L1TE10, EF_mu10_MSonly_EFFS_L1TE20, EF_mu4_MSonly_L1TE50, EF_mu4_L1VTE50;
  float ptNt[30], centralityNt,etaNt[30],eLossNt[30],scatNt[30];

  TChain* tree = new TChain("tree","tree");
  std::cout << "Filling the tree for " << fileNameMuonIn << std::endl;
  tree->Add(fileNameMuonIn);
  // --- Set branch adresses ---
  tree->SetBranchAddress("val", &valNt);
  tree->SetBranchAddress("pt", &ptNt);
  tree->SetBranchAddress("eta", &etaNt);
  tree->SetBranchAddress("eLoss",&eLossNt);
  tree->SetBranchAddress("scat",&scatNt);
  tree->SetBranchAddress("mu_muid_n", &mu_muid_nNt);
  tree->SetBranchAddress("run", &runNt);
  tree->SetBranchAddress("centrality", &centralityNt); 
  tree->SetBranchAddress("EF_mu4_MSonly_L1TE50", &EF_mu4_MSonly_L1TE50); 
  tree->SetBranchAddress("EF_mu4_L1VTE50", &EF_mu4_L1VTE50); 
  tree->SetBranchAddress("EF_mu4_MSonly_L1TE50_Matched20", &EF_mu4_MSonly_L1TE50_Matched20); 
  tree->SetBranchAddress("EF_mu4_L1VTE50_Matched20", &EF_mu4_L1VTE50_Matched20); 
  tree->SetBranchAddress("EF_mu10_MSonly_EFFS_L1ZDC", &EF_mu10_MSonly_EFFS_L1ZDC); 
  tree->SetBranchAddress("EF_mu10_MSonly_EFFS_L1TE10", &EF_mu10_MSonly_EFFS_L1TE10); 
  tree->SetBranchAddress("EF_mu10_MSonly_EFFS_L1TE20", &EF_mu10_MSonly_EFFS_L1TE20); 
  tree->SetBranchAddress("EF_mu10_MSonly_EFFS_L1ZDC_Matched20", &EF_mu10_MSonly_EFFS_L1ZDC_Matched20); 
  tree->SetBranchAddress("EF_mu10_MSonly_EFFS_L1TE10_Matched20", &EF_mu10_MSonly_EFFS_L1TE10_Matched20); 
  tree->SetBranchAddress("EF_mu10_MSonly_EFFS_L1TE20_Matched20", &EF_mu10_MSonly_EFFS_L1TE20_Matched20); 

  tree->SetBranchStatus("*",0);
  tree->SetBranchStatus("val", 1);
  tree->SetBranchStatus("pt", 1);
  tree->SetBranchStatus("eta", 1);
  tree->SetBranchStatus("eLoss",1);
  tree->SetBranchStatus("scat",1);
  tree->SetBranchStatus("mu_muid_n", 1);
  tree->SetBranchStatus("run", 1);
  tree->SetBranchStatus("centrality", 1); 
  tree->SetBranchStatus("EF_mu4_MSonly_L1TE50", 1); 
  tree->SetBranchStatus("EF_mu4_L1VTE50", 1); 
  tree->SetBranchStatus("EF_mu4_MSonly_L1TE50_Matched20", 1); 
  tree->SetBranchStatus("EF_mu4_L1VTE50_Matched20", 1); 
  tree->SetBranchStatus("EF_mu10_MSonly_EFFS_L1ZDC", 1); 
  tree->SetBranchStatus("EF_mu10_MSonly_EFFS_L1TE10", 1); 
  tree->SetBranchStatus("EF_mu10_MSonly_EFFS_L1TE20", 1); 
  tree->SetBranchStatus("EF_mu10_MSonly_EFFS_L1ZDC_Matched20", 1); 
  tree->SetBranchStatus("EF_mu10_MSonly_EFFS_L1TE10_Matched20", 1); 
  tree->SetBranchStatus("EF_mu10_MSonly_EFFS_L1TE20_Matched20", 1); 

 std::cout << "Number of entries: " << tree->GetEntries() << std::endl; 
 
 ///map runnumber to #mu
 ///need to used multimap since >1 muon 
 ///value for each run number key
 std::multimap < int, int> runMap;

  ///loop over all events
  for ( int i = 0; i < tree->GetEntries(); ++i ) {
 //   if(i>10000) break;
    tree->LoadTree(i);
    tree->GetEntry(i);

    if(i%10000==0) std::cout << "Event " << i << std::endl;

        for(int imu = 0; imu<mu_muid_nNt; imu++){
            if (
                (valNt[imu]>cutValue) 
                && abs(etaNt[imu])>0.1 
                && abs(etaNt[imu])<2.4 
                && ptNt[imu]>ptmin 
                && centralityNt>=0. 
                && centralityNt<=0.8
                && ( (EF_mu10_MSonly_EFFS_L1ZDC&&EF_mu10_MSonly_EFFS_L1ZDC_Matched20[imu]) ||
                    (EF_mu10_MSonly_EFFS_L1TE10&&EF_mu10_MSonly_EFFS_L1TE10_Matched20[imu])
                    ||(EF_mu10_MSonly_EFFS_L1TE20&&EF_mu10_MSonly_EFFS_L1TE20_Matched20[imu]) )	
		        ){
                ///count number of muons in this run that pass
                runMap.insert(make_pair (runNt,1) );
               }
         } //imu
   } //i
                
   std::cout << std::endl;
   std::cout << "-------------------------  " << std::endl;
   std::cout << " S U M M A R Y " << std::endl;
   std::cout << "-------------------------  " << std::endl;

   TString spreadSheetName = "muonCountingSpreadSheet.csv";
   std::ofstream spreadSheet;
   spreadSheet.open(spreadSheetName);

   double totLumi = 0.0, totalMu = 0;
   for(int iRun = 0; iRun<nRuns; ++iRun){

        int muonsPassed = runMap.count( vRun[iRun] );
        ///Muons per nb^-1
        double muPerLumi = (double)muonsPassed/vLumi[iRun]/1000.0;
        ///Number of muons passed in run iRun
        std::cout << "Index: " << iRun+1 << "\tRun: " << vRun[iRun] << 
            "\tLumi: " << vLumi[iRun]/1000.0 << "\tMuons: " << muonsPassed << "\tMuons/nb^-1: " 
            << muPerLumi << std::endl;

        totLumi += vLumi[iRun]/1000.0;
        totalMu += muonsPassed;

        grMuPerLumi->SetPoint(iRun,vRun[iRun],muPerLumi);
        grMuPerLumi->SetPointError(iRun,0.5, TMath::Sqrt(muonsPassed)/vLumi[iRun]/1000.0);

        grLumi->SetPoint(iRun,totLumi,totalMu);
        grLumi->SetPointError(iRun, 0.0, 0.0);

        writeToSpreadsheet(spreadSheet,iRun+1,vRun[iRun],vLumi[iRun]/1000.,muonsPassed);
   }

   grMuPerLumi->Draw("ape");
   grLumi->Draw("ape");

   outFile->cd();
   grLumi->Write("muonLumiDependence");
   grMuPerLumi->Write("muonPerLumi");

   std::cout << " Total Luminosity: " << totLumi << " nb^-1 " << std::endl;
   std::cout << " Total Muons passed: " << totalMu << std::endl;

   spreadSheet.close();
                
/*
            
  cout << "Number of runs: " << runMap.size() << endl;
  cout << "Run \t" << "Luminosity(ub^-1) \t" << " #muons \t" << "muons/lumi" << endl;
  ///map run lumi to #mu
  //std::map < int, double> lumiMap;
  for (unsigned int j = 0; j<runMap.size(); ++j){
    int runTemp = vRun.at(j);
    double lumiTemp = vLumi.at(j);
    map <int,int>::const_iterator iPairFound = runMap.find(runTemp);
    cout << iPairFound->first << " \t " << lumiTemp << " \t " << " \t " << iPairFound->second << " \t " << " \t " << (double)iPairFound->second/lumiTemp << endl; 
    sum += runMap[runTemp];
  }

  cout << "Total Luminosity = " << totLumi << endl;
  cout << "Total = " << sum << endl;
  */
}
Exemple #28
0
void frameViewer(char* arg) {
	//Take the arguments and save them into respective strings
	std::string infileName;
	std::string inF;
	std::string inPrefix;
	std::string runs, layers;
	std::string runCount;
	std::istringstream stm(arg);

	inPrefix = "/home/p180f/Do_Jo_Ol_Ma/Analysis/MainProcedure/testMain/rawRoot/";

	while (true) {	
		if (std::getline(stm, layers, ' ')) {

			//load the input root files
			TChain *chain = new TChain("fourChamTree");

			for (int i=0; ; i++) {
				runCount = std::to_string(i);
				inF = "run" + runCount + "_" + layers + "layers.root";
				infileName = inPrefix + inF;
				ifstream fin;
				fin.open(infileName.c_str());
				if (!fin.fail()) {
					fin.close();
					chain->Add(infileName.c_str());
					std::cout << "Got " << inF << std::endl;
				} else break;
			}

			const int width=480;	//width of the raw image
			const int height=640;	//height of the raw image


			int x=-10;	//x from file
			int y=-10;	//y from file
			int intensity=-10;	//pixle intensity from file
			int pNum=0;//a counter of the order in which the frame was processed

			//the 2d array which will store each frame of image data.
			int frame[480][640]={0};

			//variables
			int UNIXtime=0;
			float tdc[2]={-10,-10};


			//TTree *T = new TTree("T","TTree of muplus data");
			//add the 'branches' to the tree we will now read in
			chain->SetBranchAddress("pNum",&pNum);	//branch for the frame number
			chain->SetBranchAddress("frame",&frame);	//branch for frame data

			TH2I *frameHisto = new TH2I("Single 4 Spark Event","",width,0,width,height,0,height);	//histogram for the stacked images

			TH1I *chamber1 = new TH1I("chamber1","Chamber 1",width,0,width);//histogram for chamber 1 (the top one)
			TH1I *chamber2 = new TH1I("chamber2","Chamber 2",width,0,width);//histogram for chamber 2
			TH1I *chamber3 = new TH1I("chamber3","Chamber 3",width,0,width);//histogram for chamber 3
			TH1I *chamber4 = new TH1I("chamber4","Chamber 4",width,0,width);//histogram for chamber 4 (the bottom one)
			
			TH1I *chamber1y = new TH1I("chamber1y","Chamber 1",height,0,height);//histogram for chamber 1 (the top one)
			TH1I *chamber2y = new TH1I("chamber2y","Chamber 2",height,0,height);//histogram for chamber 2
			TH1I *chamber3y = new TH1I("chamber3y","Chamber 3",height,0,height);//histogram for chamber 3
			TH1I *chamber4y = new TH1I("chamber4y","Chamber 4",height,0,height);//histogram for chamber 4 (the bottom one)

			//output the plot of the stacked images
		
			TCanvas *fH2 = new TCanvas("fH2", "Single 4 Spark Event", 0, 0, 800, 800);
			fH2->cd();
			frameHisto->Draw();
			frameHisto->GetXaxis()->SetTitle("X position (px)");
			frameHisto->GetXaxis()->CenterTitle();

			frameHisto->GetYaxis()->SetTitle("Intensity");
			frameHisto->GetYaxis()->SetTitleOffset(1.4);
			frameHisto->GetYaxis()->CenterTitle();

			TCanvas *pc2 = new TCanvas("pc2","Frame",0,0,800,800);
			
			pc2->Divide(2,2);
			
			pc2->cd(1);
			chamber1->Draw();
			chamber1->GetXaxis()->SetTitle("X position (px)");
			chamber1->GetXaxis()->CenterTitle();

			chamber1->GetYaxis()->SetTitle("Intensity");
			chamber1->GetYaxis()->SetTitleOffset(1.4);
			chamber1->GetYaxis()->CenterTitle();

			pc2->cd(2);
			chamber2->Draw();
			chamber2->GetXaxis()->SetTitle("X position (px)");
			chamber2->GetXaxis()->CenterTitle();

			chamber2->GetYaxis()->SetTitle("Intensity");
			chamber2->GetYaxis()->SetTitleOffset(1.4);
			chamber2->GetYaxis()->CenterTitle();

			pc2->cd(3);
			chamber3->Draw();
			chamber3->GetXaxis()->SetTitle("X position (px)");
			chamber3->GetXaxis()->CenterTitle();

			chamber3->GetYaxis()->SetTitle("Intensity");
			chamber3->GetYaxis()->SetTitleOffset(1.4);
			chamber3->GetYaxis()->CenterTitle();

			pc2->cd(4);
			chamber4->Draw();
			chamber4->GetXaxis()->SetTitle("X position (px)");
			chamber4->GetXaxis()->CenterTitle();

			chamber4->GetYaxis()->SetTitle("Intensity");
			chamber4->GetYaxis()->SetTitleOffset(1.4);
			chamber4->GetYaxis()->CenterTitle();

			//TFile myF("trackTree.root","RECREATE");
			

			//loop over all data in chain
			Int_t nevent = chain->GetEntries();	//get the number of entries in the TChain
			for (Int_t i=0;i<nevent;i++) {
				chain->GetEntry(i);

				//put the frame data into the histogram for this event
				for(int x=0;x<width;x++){
					for(int y=0;y<height;y++){
						if(frame[x][y]>0){
							frameHisto->Fill(x,y,frame[x][y]);
							if(y>580 && y<610){
								chamber1->Fill(x,frame[x][y]);
								chamber1y->Fill(y,frame[x][y]);
							}
							else if(y>400 && y<440){
								chamber2->Fill(x,frame[x][y]);
								chamber2y->Fill(y,frame[x][y]);
							}
							else if(y>240 && y<280){
								chamber3->Fill(x,frame[x][y]);
								chamber3y->Fill(y,frame[x][y]);
							}
							else if(y>50 && y<100){
								chamber4->Fill(x,frame[x][y]);
								chamber4y->Fill(y,frame[x][y]);
							}
						}	
					}
				}

				double x12[2];
				double y12[2];
				double x34[2];
				double y34[2];

				x12[0] = chamber1->GetMean();
				y12[0] = chamber1y->GetMean();			//593.3;
				x12[1] = chamber2->GetMean();
				y12[1] = chamber2y->GetMean();			//424.7;
				x34[0] = chamber3->GetMean();
				y34[0] = chamber3y->GetMean();			//262.5;
				x34[1] = chamber4->GetMean();
				y34[1] = chamber4y->GetMean();			//69.33;

				cout << "Chamber1x: " << chamber1->GetMean() << endl;
				cout << "Chamber1y: " << chamber1y->GetMean() << endl;
				cout << "Chamber2x: " << chamber2->GetMean() << endl;
				cout << "Chamber2y: " << chamber2y->GetMean() << endl;
				cout << "Chamber3x: " << chamber3->GetMean() << endl;
				cout << "Chamber3y: " << chamber3y->GetMean() << endl;
				cout << "Chamber4x: " << chamber4->GetMean() << endl;
				cout << "Chamber4y: " << chamber4y->GetMean() << endl;

				pc2->cd(1);
				chamber1->Draw();
				gPad->Update();
				
				pc2->cd(2);
				chamber2->Draw();
				gPad->Update();
				
				pc2->cd(3);
				chamber3->Draw();
				gPad->Update();
				
				pc2->cd(4);
				chamber4->Draw();
				gPad->Update();
				
				fH2->cd();
				frameHisto->Draw();
				gPad->Update();

				//wait for user input to advance to next event
				cout << "Frame Number=" << pNum<<endl;
				cout << "Press enter to advance to the next frame" << endl;
				cin.ignore();
				
				//clear the old frame from the histogram
				frameHisto->Reset();
				chamber1->Reset();
				chamber2->Reset();
				chamber3->Reset();
				chamber4->Reset();
			}
		} else break;
	}
}
Exemple #29
0
void getSkimCutflow(TString files) {
  
  TChain *fChain = new TChain("cutFlow");   //!pointer to the analyzed TTree or TChain
   // Declaration of leaf types
   UInt_t          startCount_;
   UInt_t          met200Count_;
   UInt_t          numJetsCount_;
   UInt_t          numCSVMCount_;
   UInt_t          minDeltaPhiCount_;
   UInt_t          muonVetoCount_;
   UInt_t          electronVetoCount_;

   // List of branches
   TBranch        *b_startCount;   //!
   TBranch        *b_met200Count;   //!
   TBranch        *b_numJetsCount;   //!
   TBranch        *b_numCSVMCount;   //!
   TBranch        *b_minDeltaPhiCount;   //!
   TBranch        *b_muonVetoCount;   //!
   TBranch        *b_electronVetoCount;   //!

   fChain->SetBranchAddress("startCount", &startCount_, &b_startCount);
   fChain->SetBranchAddress("met200Count", &met200Count_, &b_met200Count);
   fChain->SetBranchAddress("numJetsCount", &numJetsCount_, &b_numJetsCount);
   fChain->SetBranchAddress("numCSVMCount", &numCSVMCount_, &b_numCSVMCount);
   fChain->SetBranchAddress("minDeltaPhiCount", &minDeltaPhiCount_, &b_minDeltaPhiCount);
   fChain->SetBranchAddress("muonVetoCount", &muonVetoCount_, &b_muonVetoCount);
   fChain->SetBranchAddress("electronVetoCount", &electronVetoCount_, &b_electronVetoCount);

   fChain->Add(files);

   int startCount(0);
   int met200Count(0);
   int numJetsCount(0);
   int numCSVMCount(0);
   int minDeltaPhiCount(0);
   int muonVetoCount(0);
   int electronVetoCount(0);

  for (unsigned int entry=0; entry<fChain->GetEntries(); entry++) {
    fChain->GetEntry(entry);
    startCount+=startCount_;
    met200Count+=met200Count_;
    numJetsCount+=numJetsCount_;
    numCSVMCount+=numCSVMCount_;
    minDeltaPhiCount+=minDeltaPhiCount_;
    muonVetoCount+=muonVetoCount_;
    electronVetoCount+=electronVetoCount_;
  }

  printf("*****Cutflow*****\n");
  printf("startCount\t\t\t%d\n",startCount);
  printf("met200Count\t\t\t%d\n",met200Count);
  printf("numJetsCount\t\t\t%d\n",numJetsCount);
  printf("numCSVMCount\t\t\t%d\n",numCSVMCount);
  printf("minDeltaPhiCount\t\t%d\n",minDeltaPhiCount);
  printf("muonVetoCount\t\t\t%d\n",muonVetoCount);
  printf("electronVetoCount\t\t%d\n",electronVetoCount);

   return;

}
Exemple #30
0
int main(int argc, char * argv[])
{
	// load silly ROOT thing
	gROOT->ProcessLine("#include <vector>");
	gROOT->ProcessLine(".L loader.C+");

	// output
	TFile * output_file = new TFile("output_file.root", "RECREATE");

	TTree * jet_tree = new TTree("jet_tree", "jet_tree");
	float jet_pt = 0;
	float jet_eta = 0;
	float jet_phi = 0;
	float jet_m = 0;
	jet_tree->Branch("jet_pt", &jet_pt);
	jet_tree->Branch("jet_eta", &jet_eta);
	jet_tree->Branch("jet_phi", &jet_phi);
	jet_tree->Branch("jet_m", &jet_m);

	TTree * event_tree = new TTree("event_tree", "event_tree");
	int n = 0;
	int us = 0;
	event_tree->Branch("n", &n);
	event_tree->Branch("us", &us);

	// input tracks
	TChain * tree = new TChain("tree");
	tree->Add("mc15_13TeV.301523.RS_G_hh_bbbb_c20_M2000.track_ntuple.root");
	int number_of_events = tree->GetEntries();

	int track_number = 0;
	vector<float> * track_pt = 0;
	vector<float> * track_eta = 0;
	vector<float> * track_phi = 0;
	tree->SetBranchAddress("track_number", &track_number);
	tree->SetBranchAddress("track_pt", &track_pt);
	tree->SetBranchAddress("track_eta", &track_eta);
	tree->SetBranchAddress("track_phi", &track_phi);

	vector<PseudoJet> particles;

	// variables for timing
	struct timeval start;
	struct timeval end;
	struct timeval duration;
//	TH2F * h_timing = new TH2F("timing", "timing; # Tracks; #mus", 1000, 0, 1000, 100, 1, 10000);
//	TH2F * h_log_timing = new TH2F("log_timing", "log_timing; # Tracks; log_{10}(#mus)", 1000, 0, 1000, 100, log10(1), log10(10000));
//	TH2F * h_timing = new TH2F("timing", "timing; # Tracks; #mus", 1000, 0, 1000, 100, 1, 10000);
//	TH2F * h_log_timing = new TH2F("log_timing", "log_timing; # Tracks; log_{10}(#mus)", 1000, 0, 1000, 100, log10(1), log10(10000));
//	TH2F * h_timing = new TH2F("timing", "timing; # Tracks; #mus", 1000, 0, 1000, 100, 1, 10000);
//	TH2F * h_log_timing = new TH2F("log_timing", "log_timing; # Tracks; log_{10}(#mus)", 1000, 0, 1000, 100, log10(1), log10(10000));
	TH2F * h_timing = new TH2F("timing", "timing; # Tracks; #mus", 1000, 0, 1000, 100, 1, 5000);						// N2Tiled
	TH2F * h_log_timing = new TH2F("log_timing", "log_timing; # Tracks; log_{10}(#mus)", 1000, 0, 1000, 100, log10(1), log10(5000));	// N2Tiled

	for (int event = 0; event < number_of_events; event++)
	{
		// print a sexy load bar
		loadBar(event, number_of_events, 100, 50);

		tree->GetEntry(event);

		for (int track = 0; track < track_number; track++)
		{
			TLorentzVector trackLorentzVector;
			trackLorentzVector.SetPtEtaPhiM(track_pt->at(track) / 1000.0, track_eta->at(track), track_phi->at(track), 0);
			particles.push_back(PseudoJet(trackLorentzVector.Px(), trackLorentzVector.Py(), trackLorentzVector.Pz(), trackLorentzVector.E()));
		}

		// get the start time
		gettimeofday(&start, NULL);

		// not vrplugin
		double R = 0.4;
//		JetDefinition jet_def(antikt_vr, R, N3Dumb, E_scheme, 1, 60);
//		JetDefinition jet_def(antikt_vr, R, N2Plain, E_scheme, 1, 60);
		JetDefinition jet_def(antikt_vr, R, N2Tiled, E_scheme, 1, 60);
		ClusterSequence cs(particles, jet_def);
		vector<PseudoJet> jets = sorted_by_pt(cs.inclusive_jets());

		// vrplugin
//		double rho = 60;
//		double min_r = 0;
//		double max_r = 0.4;
//		VariableRPlugin vrplugin(rho, min_r, max_r, VariableRPlugin::AKTLIKE);
//		JetDefinition jet_def_vrplugin(&vrplugin);
//		ClusterSequence cs_vrplugin(particles, jet_def_vrplugin);
//		vector<fastjet::PseudoJet> jets = sorted_by_pt(cs_vrplugin.inclusive_jets());

		// get the final time
		gettimeofday(&end, NULL);

		// get the duration
		timersub(&end, &start, &duration);
		h_timing->Fill(track_number, (long int) duration.tv_sec * 1000000 + (long int) duration.tv_usec);
		h_log_timing->Fill(track_number, log10((long int) duration.tv_sec * 1000000 + (long int) duration.tv_usec));

		n = track_number;
		us = (long int) duration.tv_sec * 1000000 + (long int) duration.tv_usec;

		event_tree->Fill();

		for (int jet = 0; jet < jets.size(); jet++)
		{
//			printf("jets[jet].pt() = %f\n", jets[jet].pt());
//			printf("jets[jet].eta() = %f\n", jets[jet].eta());
//			printf("jets[jet].phi() = %f\n", jets[jet].phi());
//			printf("jets[jet].m() = %f\n", jets[jet].m());
			jet_pt = jets[jet].pt();
			jet_eta = jets[jet].eta();
			jet_phi = jets[jet].phi();
			jet_m = jets[jet].m();

			jet_tree->Fill();
		}

		particles.clear();
	}

	TProfile * pr_timing = h_timing->ProfileX();
	TF1 * f_timing_n2 = new TF1("f_timing_n2", "pol2", 0, 1000);
	TF1 * f_timing_n3 = new TF1("f_timing_n3", "pol3", 0, 1000);
	pr_timing->Fit(f_timing_n2);
	pr_timing->Fit(f_timing_n3);

	TProfile * pr_log_timing = h_log_timing->ProfileX();
	TF1 * f_log_timing = new TF1("f_log_timing", "pol1", 0, 1000);
	pr_log_timing->Fit(f_log_timing);

	output_file->Write();

	h_timing->Write();
	pr_timing->Write();
	f_timing_n2->Write();
	f_timing_n3->Write();

	h_log_timing->Write();
	pr_log_timing->Write();
	f_log_timing->Write();

	delete(jet_tree);
	delete(event_tree);

	return 0;
}