//------------------------------------------------------------------------------
// getTreeFromFile
//------------------------------------------------------------------------------
TTree* getTreeFromFile(const char* infname, int nsel)
{
  bool verbose = false;

  if (verbose) {
    cout << "--- Open file " << infname << endl;
  }
  
  TFile* inf = new TFile(infname,"read");
  assert(inf);

  //TDirectory *dir = (TDirectory*)inf->FindObjectAny("HwwMakeNtupleMod");
  //assert(dir);

  TTree* t;
  
  if     (nsel==0) t = (TTree*) gROOT->FindObject("HwwTree0");
  else if(nsel==1) t = (TTree*) gROOT->FindObject("HwwTree1");
  else if(nsel==2) t = (TTree*) gROOT->FindObject("HwwTree2");
  else if(nsel==3) t = (TTree*) gROOT->FindObject("HwwTree3");
  else if(nsel==4) t = (TTree*) gROOT->FindObject("HwwTree4");
  else             assert(1);
  t->SetName("tree");
  assert(t);

  if (verbose) {
    cout << "---\tRecovered tree " << t->GetName()
	 << " with "<< t->GetEntries() << " entries" << endl;
  }
  
  return t;
}
//------------------------------------------------------------------------------
// getTreeFromFile
//------------------------------------------------------------------------------
TTree* getTreeFromFile(const char* infname)
{
  bool verbose = true;

  if (verbose) {
    cout << "--- Open file " << infname << endl;
  }
  
  TFile* inf = new TFile(infname,"read");
  assert(inf);

  //TDirectory *dir = (TDirectory*)inf->FindObjectAny("HwwMakeNtupleMod");
  //assert(dir);

  TTree* t;
  t = (TTree*) inf->Get("HwwTree0");
  if(!t) t = (TTree*) inf->Get("HwwTree1");
  if(!t) t = (TTree*) inf->Get("HwwTree2");
  if(!t) t = (TTree*) inf->Get("tree");
  assert(t);
  t->SetName("tree");

  if (verbose) {
    cout << "---\tRecovered tree " << t->GetName()
	 << " with "<< t->GetEntries() << " entries" << endl;
  }
  
  return t;
}
Пример #3
0
TTree* MillePedeTrees::CreateTree(const char *fileName, const TString &treeNameAdd)
{
  TFile *file = TFile::Open(fileName);
  if (!file) return NULL;

  TString *allTreeNames[] = {&fOrgPos, &fPos, &fMisPos, &fMisPar, &fPar, &fMp};
  const unsigned int nTree = sizeof(allTreeNames) / sizeof(allTreeNames[0]);

  unsigned int iTree = 0;
  TTree *mainTree = NULL;
  do {
    file->GetObject(allTreeNames[iTree]->Data(), mainTree);
    if (!mainTree) {
      ::Error("MillePedeTrees::CreateTree",
              "no tree %s in %s", allTreeNames[iTree]->Data(), fileName);
    } 
    *(allTreeNames[iTree]) += treeNameAdd; // Yes, we really change the data members!
    if (mainTree && !treeNameAdd.IsNull()) {
      mainTree->SetName(*(allTreeNames[iTree]));
    }
    ++iTree;
  } while (!mainTree && iTree < nTree);

  if (mainTree) {
    for (unsigned int jTree = iTree; jTree < nTree; ++jTree) {
      const TString newName(*(allTreeNames[jTree]) + treeNameAdd);
// either by really renaming trees: 
//       TTree *tree = NULL;
//       file->GetObject(allTreeNames[jTree]->Data(), tree);
//       if (!tree) {
//         ::Error("MillePedeTrees::CreateTree",
//                 "no tree %s in %s", allTreeNames[jTree]->Data(), fileName);
//       } else {
//         tree->SetName(newName);
//         mainTree->AddFriend(tree, "", true); // no alias, but warn if different lengths
//       }
// or by setting an alias:
      TFriendElement *fEle = mainTree->AddFriend(newName + " = " + *(allTreeNames[jTree]));
      if (!fEle || !fEle->GetTree()) {
        ::Error("MillePedeTrees::CreateTree","no %s as friend tree",allTreeNames[jTree]->Data());
       } 
      *(allTreeNames[jTree]) = newName; // Yes, we really change the data members!
    }
    mainTree->SetEstimate(mainTree->GetEntries()); // for secure use of GetV1() etc.  
  }

  return mainTree;
}
Пример #4
0
void CreateFriendTree() {
   // Open the file created by CreateParentTree
   // Copy a subset of the TTree into a new TTree
   //   (see also tutorials copytree.C, copytree2.C and copytree3.C)
   // Create an index on the new TTree ("Run","Event")
   // Write the new TTree (including its index)
   
   TFile *f = new TFile("treeparent.root");
   TTree *T = (TTree*)f->Get("T");
   TFile *ff = new TFile("treefriend.root","recreate");
   TTree *TF = T->CopyTree("z<10");
   TF->SetName("TF");
   TF->BuildIndex("Run","Event");
   TF->Write();
   TF->Print();
   delete ff;
}
Пример #5
0
TTree * getTree(TFile *m_File, const char *path, const char *name) {
    std::string p = std::string("/") + std::string(path);
    TDirectory *dir = m_File->GetDirectory(p.c_str());
    if(!dir) {
        m_File->mkdir(path);
    }
    m_File->cd(path);
    std::string n = p + std::string("/") + std::string(name);
    TObject *obj = m_File->Get(n.c_str());
    if(!obj) {
        TTree *tree = new TTree();
        tree->SetName(name);
        return tree;
    }
    else {
        return (TTree *)obj;
    }
}
Пример #6
0
void ChangeDataTreeName(std::string suffix){

  // Define names
  TString filename = "", treename = "", histname = "";
  filename.Form("central_%s.root",suffix.c_str());
  treename.Form("id_%s",suffix.c_str());
  histname.Form("sumOfMcWeights_%s",suffix.c_str());

  TString _pathFile(string(getenv("WORKAREA")) + "/histoAna" + "/SusyAna/histos_110312_13fb_n0111_DD_MMtrial9_SYS_HFT/HFTOutputs_merge/");
  filename = _pathFile+filename;
  cout << "open " << filename << endl;

  // Open file
  TFile* file         = new TFile(filename,"UPDATE");
  if(file->IsOpen()==kFALSE){
    cerr << "Cannot open file " << filename << endl;
    abort();
  }
  file->ls();
  TTree* treeOriginal = (TTree*) file->Get(treename);
  TH1D*  histOriginal = (TH1D*)  file->Get(histname);
  TTree* treeNew      = (TTree*) treeOriginal->Clone();
  TH1D*  histNew      = (TH1D*)  histOriginal->Clone();

  // Set-Write-Delete
  histNew->SetName ("sumOfMcWeights_Data" );
  histNew->SetTitle("sumOfMcWeights_Data" );
  histNew->Write   ("",TObject::kOverwrite);
  treeNew->SetName ("id_Data"             );
  treeNew->SetTitle("id_Data"             );
  treeNew->Write   ("",TObject::kOverwrite);
  file->Delete     (histname+";1"         );
  file->Delete     (treename+";1"         );

  // Close file
  file->Close();
}
Пример #7
0
void run(std::string inputFile, int max_iterations, int entries_per_kernel = 100) {
  
  TFile *file2 = new TFile(inputFile.c_str());
  
 
  std::vector<double>* samples = new std::vector<double>;
  double amplitudeTruth;
  TTree *tree = (TTree*)file2->Get("Samples");
  tree->SetBranchAddress("amplitudeTruth",      &amplitudeTruth);
  tree->SetBranchAddress("samples",             &samples);
  int nentries = tree->GetEntries();
  
  float time_shift = 13. ; //---- default is 13
  float pedestal_shift = 0.;
  
  
  float return_chi2 = -99;
  float best_pedestal = 0;
  float best_chi2 = 0;
  
  
  std::vector<TH1F*> v_pulses;
  std::vector<TH1F*> v_amplitudes_reco;
  
  fout->cd();
  TTree* newtree = (TTree*) tree->CloneTree(0); //("RecoAndSim");
  newtree->SetName("RecoAndSim");
  
  std::vector <double> samplesReco;
  std::vector < std::vector<double> > complete_samplesReco;
  std::vector <double> complete_chi2;
  std::vector <double> complete_pedestal;
  
  int ipulseintime = 0;
  newtree->Branch("chi2",   &return_chi2, "chi2/F");
  newtree->Branch("samplesReco",   &samplesReco);
  newtree->Branch("ipulseintime",  ipulseintime,  "ipulseintime/I");
  
  newtree->Branch("complete_samplesReco",   &complete_samplesReco);
  newtree->Branch("complete_chi2",          &complete_chi2);
  newtree->Branch("complete_pedestal",          &complete_pedestal);
  newtree->Branch("best_pedestal",   &best_pedestal, "best_pedestal/F");
  newtree->Branch("best_chi2",   &best_chi2, "best_chi2/F");
  
  
  int totalNumberOfBxActive = 10;
  
  for (unsigned int ibx=0; ibx<totalNumberOfBxActive; ++ibx) {
    samplesReco.push_back(0.);
  }
  
  
  v_amplitudes_reco.clear();
  
  
  struct Args {
      SampleVector samples;
      SampleMatrix samplecor;
      double pederr;
      BXVector bxs;
      FullSampleVector fullpulse;
      FullSampleMatrix fullpulsecov;

      Args(SampleVector const& samples,
           SampleMatrix const& samplecor,
           double pederr,
           BXVector const& bxs,
           FullSampleVector fullpulse,
           FullSampleMatrix fullpulsecov)
        : samples(samples), samplecor(samplecor), pederr(pederr), bxs(bxs), 
          fullpulse(fullpulse), fullpulsecov(fullpulsecov)
      {}
  };

  struct Output {
      double chi2;
      double ampl;
      int status;

      Output(double chi2, double ampl, int status) 
          : chi2{chi2}, ampl{ampl}, status{status}
      {}
  };
  
  std::cout 
            << "max_iterations: " << max_iterations << std::endl
            << "entries_per_kernel: " << entries_per_kernel << std::endl;
  
  for (auto it=0; it<max_iterations; ++it) {
      // vector of input parameters to the kernel
      std::vector<Args> vargs;

      for (int ie=0; ie<entries_per_kernel; ++ie) {
          tree->GetEntry(ie % tree->GetEntries());
          for (int i=0; i<NSAMPLES; ++i)
              amplitudes[i] = samples->at(i);

          double pedval = 0.;
          double pedrms = 1.0;
          vargs.emplace_back(amplitudes, noisecor, pedrms, activeBX, fullpulse, fullpulsecov);
      }

      auto kernel = [](std::vector<Args> const& vargs) -> std::vector<Output> {
          std::vector<Output> vresults;
          for (auto& args : vargs) {
              PulseChiSqSNNLS func;
              func.disableErrorCalculation();
              auto status = func.DoFit(args.samples, args.samplecor, args.pederr,
                                       args.bxs, args.fullpulse, args.fullpulsecov);
              double chi2 = func.ChiSq();
              unsigned int ip_in_time = 0;
              for (unsigned int ip=0; ip<func.BXs().rows(); ++ip) {
                  if (func.BXs().coeff(ip) == 0) {
                      ip_in_time = ip;
                      break;
                  }
              }
              double ampl = status ? func.X()[ip_in_time] : 0.;
              vresults.emplace_back(chi2, ampl, status);
          }

          return vresults;
      };
      std::cout << "iteration: " << it
                 << " wrapper start with vargs.size() = " << vargs.size() << std::endl;
      auto start_time = std::chrono::high_resolution_clock::now();
      auto vresults = kernel(vargs);
      auto end_time = std::chrono::high_resolution_clock::now();
      std::cout << "wrapper end with vresults.size() " << vresults.size() << std::endl;
      auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(
            end_time - start_time).count();
      hDuration->Fill(duration);
      std::cout << "duration = " << duration << std::endl;

      for (auto& results : vresults) {
          h01->Fill(results.ampl - amplitudeTruth);
      }
  }
  
  fout->cd();
  newtree->Write();
  std::cout << "  Mean of REC-MC = " << h01->GetMean() << " GeV" << std::endl;
  std::cout << "  RMS of REC-MC = " << h01->GetRMS() << " GeV" << std::endl;
  std::cout << "  Entries Total = " << h01->GetEntries() << std::endl;
  std::cout << "  Mean Duration = " << hDuration->GetMean() << std::endl;
}
Пример #8
0
int main(int argc, char **argv)
{
	TString analysis = "Lb2Lmumu";
	bool MC = false;
	TString base = "/afs/cern.ch/work/p/pluca/weighted/Lmumu/";

	if(argc > 1)
	{
		string arg = argv[1];
		if(arg == "MC") MC = true;
	}

	vector< string > novar;
	novar.push_back("Lb_MassCons");
	novar.push_back("Lb_MassConsLambda");
	novar.push_back("Lb_MassConsJpsiLambda");
	novar.push_back("cosTheta");
	novar.push_back("cosThetaL");
	novar.push_back("cosThetaB");
	novar.push_back("phiL");
	novar.push_back("phiB");
	novar.push_back("dphi");
	novar.push_back("cosTheta_TRUE");
	novar.push_back("cosThetaL_TRUE");
	novar.push_back("cosThetaB_TRUE");
	novar.push_back("phiL_TRUE");
	novar.push_back("phiB_TRUE");
	novar.push_back("dphi_TRUE");

	TCut cutJpsi = CutsDef::cutJpsi;
	TCut cutMuMu = CutsDef::cutMuMu_veto;

	TreeReader* treeReader = new TreeReader("tree");

	TString namefile = base + "candLb";
	if(MC) namefile += "_MC";
	namefile += ".root";

	TFile * candFile = new TFile(namefile,"recreate");

	if(!MC) treeReader->AddFile(base+analysis+"_CL_NBweighted.root");
	else treeReader->AddFile(base+analysis+"_MC_Pythia8_NBweighted.root");
	treeReader->Initialize(novar,"except");

	Analysis * anaLbMuMu = new Analysis("Lb2Lmumu","Lb",treeReader,&cutMuMu);

	candFile->cd();
	TTree * candLbMuMu = anaLbMuMu->applyCuts(&addVariables);
	candLbMuMu->Write();
	string tnameMuMu = candLbMuMu->GetName();

	candFile->Close();
	candFile = TFile::Open(namefile,"update");
	TTree * singleCand_LbMuMu = anaLbMuMu->checkMultiple("weight",namefile,tnameMuMu,&randomKill);
	singleCand_LbMuMu->Write();



	if(MC)
	{
		treeReader = new TreeReader("tree");
		treeReader->AddFile(base+"Lb2JpsiL_MC_Pythia8_NBweighted.root");
		treeReader->Initialize(novar,"except");
	}
	Analysis * anaLbJpsi = new Analysis("Lb2JpsiL","Lb",treeReader,&cutJpsi);

	candFile->cd();
	TTree * candLbJpsi = anaLbJpsi->applyCuts(&addVariables);
	candLbJpsi->Write();
	string tnameJpsi = candLbJpsi->GetName();

	candFile->Close();
	candFile = TFile::Open(namefile,"update");	
	TTree * singleCand_LbJpsi = anaLbJpsi->checkMultiple("weight",namefile,tnameJpsi,&randomKill);
	singleCand_LbJpsi->Write();

	candFile->cd();
	TTree * candLbJpsi_reduced = anaLbJpsi->applyCuts(&addVariables,300);
	candLbJpsi_reduced->SetName("candLb2JpsiL_reduced");
	candLbJpsi_reduced->Write();



	if(MC)
	{
		candFile->cd();
		TCut jpsiSwap = cutJpsi + CutsDef::jpsiSwapID;
		TCut mumuSwap = cutMuMu + CutsDef::mumuSwapID;
		TTree * mumuSwapTree = anaLbMuMu->applyCuts(&mumuSwap, false,&addVariables);
		mumuSwapTree->SetName("candLmumuSwap");
		mumuSwapTree->Write();
		TTree * jpsiSwapTree = anaLbJpsi->applyCuts(&jpsiSwap, false, &addVariables);
		jpsiSwapTree->SetName("candJpsiLSwap");
		jpsiSwapTree->Write();

		TreeReader * KSReader = new TreeReader("tree");
		KSReader->AddFile(base+"Bd2JpsiKS_MC12_NBweighted.root");
		KSReader->Initialize(novar,"except");
		TCut cutBdLL = cutJpsi + CutsDef::LLcut;
		TCut cutBdDD = cutJpsi + CutsDef::DDcut;
		Analysis * KSAnalysis_LL = new Analysis("BdJpsiKS_LL","B0",KSReader,&cutBdLL);
		TTree *KSTree_LL = KSAnalysis_LL->applyCuts(&addVariables);		
		KSTree_LL->Write();
		Analysis * KSAnalysis_DD = new Analysis("BdJpsiKS_DD","B0",KSReader,&cutBdDD);
		TTree *KSTree_DD = KSAnalysis_DD->applyCuts(&addVariables);		
		KSTree_DD->Write();
		Analysis * KSAnalysis_all = new Analysis("BdJpsiKS","B0",KSReader,&cutJpsi);
		TTree *KSTree = KSAnalysis_all->applyCuts(&addVariables);		
		KSTree->Write();

		candFile->cd();
		TreeReader * KstmumuReader = new TreeReader("tree");
		KstmumuReader->AddFile(base+"Bu2Kstmumu_MC12_NBweighted.root");
		KstmumuReader->Initialize(novar,"except");
		Analysis * KstmumuAnalysis = new Analysis("BuKstmumu","B0",KstmumuReader,&cutMuMu);
		TTree *KstmumuTree = KstmumuAnalysis->applyCuts(&addVariables);
		KstmumuTree->Write();

		candFile->cd();
		TreeReader * KSmumuReader = new TreeReader("tree");
		KSmumuReader->AddFile(base+"Bd2KSmumu_MC12_NBweighted.root");
		KSmumuReader->Initialize(novar,"except");
		Analysis * KSmumuAnalysis = new Analysis("BdKSmumu","B0",KSmumuReader,&cutMuMu);
		TTree *KSmumuTree = KSmumuAnalysis->applyCuts(&addVariables);
		KSmumuTree->Write();

		candFile->cd();
		TreeReader * JpsiGenReader = new TreeReader("tree");
		JpsiGenReader->AddFile("/afs/cern.ch/work/k/kreps/public/LbLMuMuAna/generatorLevel/LbJpsiLGenOnlyDaughInAccForRadiativeTail.root");
		JpsiGenReader->Initialize();
		TCut JpsiTailCut = "TMath::Power(J_psi_1S_MASS/1000,2) < 8 && Lb_MASS > 5300 && Lambda0_MASS > 1105 && Lambda0_MASS < 1125";
		Analysis * JpsiTailAnalysis = new Analysis("JpsiTail","Lb",JpsiGenReader,&JpsiTailCut);
		TTree *JpsiTailTree = JpsiTailAnalysis->applyCuts(&RenameMass, 0.1);
		JpsiTailTree->Write();
	}

	candFile->Close();
	delete candFile;

	return 0;
}
Пример #9
0
int main(int argc, char **argv)
{
	bool printSw = true;
	//TString massModel = "Gauss-m[5622]";
	string massModel = "DCB-m[5622]";
	TString effbase = "/afs/cern.ch/user/p/pluca/work/Lb/Lmumu/results/";
	bool printeff = false;
	TString dodata = "data";
	bool fitsingle = false;
	TString wstr = "physRate_polp006";
	TString decayToDo = "Lb2Lmumu";
	if(dodata=="genMC") wstr += "_noDecay";

	gROOT->ProcessLine(".x lhcbStyle.C");


	RooRealVar * cosThetaL = new RooRealVar("cosThetaL","cosThetaL",0.,-1.,1.);
	RooRealVar * cosThetaB = new RooRealVar("cosThetaB","cosThetaB",0.,-1.,1.);
	RooRealVar * nsig_sw = new RooRealVar("nsig_sw","nsig_sw",1,-1.e6,1.e6);
	RooRealVar * MCweight = new RooRealVar(wstr,wstr,1.,-1.e10,1.e10);
	RooRealVar * MM = new RooRealVar("Lb_MassConsLambda","Lb_MassConsLambda",5620.,5500.,5900.);
	TString datafilename = "/afs/cern.ch/user/p/pluca/work/Lb/Lmumu/candLb.root";
	if(dodata=="MC") datafilename = "/afs/cern.ch/user/p/pluca/work/Lb/Lmumu/candLb_MC.root";
	if(dodata=="genMC") datafilename = "/afs/cern.ch/work/p/pluca/weighted/Lmumu/"+(string)decayToDo+"_geomMC_Pythia8_NBweighted.root";
	TreeReader * data;
	if(dodata!="genMC") data = new TreeReader("cand"+decayToDo);
	else data = new TreeReader("MCtree");
	data->AddFile(datafilename);

	TFile * histFile = new TFile("Afb_hist.root","recreate");

	RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR);

	int nbins = 1;//CutsDef::nq2bins;
	double q2min[] = {15.,11.0,15,16,18};//&CutsDef::q2min_highfirst[0];
	double q2max[] = {20.,12.5,16,18,20};//&CutsDef::q2max_highfirst[0];
	
	//int nbins = CutsDef::nq2bins
	//double *q2min = &CutsDef::q2min[0];
	//double *q2max = &CutsDef::q2max[0];


	TGraphErrors * Afb_vs_q2 = new TGraphErrors();
	TGraphErrors * AfbB_vs_q2 = new TGraphErrors();
	TGraphErrors * fL_vs_q2 = new TGraphErrors();
	TCanvas * ceff = new TCanvas();

	RooCategory * samples = new RooCategory("samples","samples");
	samples->defineType("DD");
	samples->defineType("LL");

	RooRealVar * afb = new RooRealVar("afb","afb",0.,-100,100);
	RooRealVar * fL = new RooRealVar("fL","fL",0.7,-1.,10.);
	//RooRealVar * afb = new RooRealVar("afb","afb",0.,-1.,1.);
	//RooRealVar * fL = new RooRealVar("fL","fL",0.7,0.,1.);
	RooRealVar * origafb = new RooRealVar("afb","afb",0.,-1.,1.);
	RooRealVar * origfL = new RooRealVar("fL","fL",0.7,-1.,10.);
	TString afbLpdf = "((3./8.)*(1.-fL)*(1 + TMath::Power(cosThetaL,2)) + afb*cosThetaL + (3./4.)*fL*(1 - TMath::Power(cosThetaL,2)))";
	RooRealVar * afbB = new RooRealVar("afbB","afbB",0.,-100,100);
	//RooRealVar * afbB = new RooRealVar("afbB","afbB",0.,-1.,1.);
	RooRealVar * origafbB = new RooRealVar("afbB","afbB",0.,-1.,1.);
	TString afbBpdf = "(1 + 2*afbB*cosThetaB)";

	vector< vector< double > > afb_errs, afbB_errs, fL_errs;
	TList * LLlist = new TList, * DDlist = new TList;

	TCanvas * cDD = new TCanvas();
	TCanvas * cLL = new TCanvas();
	TCanvas * cDDB = new TCanvas();
	TCanvas * cLLB = new TCanvas();

	for(int i = 0; i < nbins; i++)
	{
		//if(q2min[i] < 8) continue;
		TString q2name = ((TString)Form("q2_%4.2f_%4.2f",q2min[i],q2max[i])).ReplaceAll(".","");
		TString curq2cut = Form("TMath::Power(J_psi_1S_MM/1000,2) >= %e && TMath::Power(J_psi_1S_MM/1000,2) < %e",q2min[i],q2max[i]);	
		//TString curq2cut = Form("TMath::Power(J_psi_1S_MM/1000,2) >= %e && TMath::Power(J_psi_1S_MM/1000,2) < %e && (Lb_MassConsLambda > 5680 || Lb_MassConsLambda < 5590)",q2min[i],q2max[i]); 
		cout << "------------------- q2 bin: " << q2min[i] << " - " << q2max[i] << " -----------------------" << endl;

		TFile * effFile = NULL;
		TH1F * effDD = NULL, * effLL = NULL, * effLLB = NULL, * effDDB = NULL;
		if(q2min[i] == 15 && q2max[i] == 20)
		{
			effFile = TFile::Open(effbase+"LbeffvscosThetaL_DD.root");
			effDD  = (TH1F *)effFile->Get("htoteff");
			effFile = TFile::Open(effbase+"LbeffvscosThetaL_LL.root");
			effLL  = (TH1F *)effFile->Get("htoteff");
			effFile = TFile::Open(effbase+"LbeffvscosThetaB_DD.root");
			effDDB  = (TH1F *)effFile->Get("htot_nodet_eff");
			effFile = TFile::Open(effbase+"LbeffvscosThetaB_LL.root");
			effLLB  = (TH1F *)effFile->Get("htot_nodet_eff");
		}
		else
		{

			effFile = TFile::Open(effbase+"Lbeff2D_cosThetaL_vs_q2_DD.root");
			TH2F * effDD2D  = (TH2F *)effFile->Get("htot_eff");
			effDD = (TH1F*)GetSliceX(effDD2D,(q2max[i]+q2min[i])/2.);
			effFile = TFile::Open(effbase+"Lbeff2D_cosThetaL_vs_q2_LL.root");
			TH2F * effLL2D  = (TH2F *)effFile->Get("htot_eff");
			effLL = (TH1F*)GetSliceX(effLL2D,(q2max[i]+q2min[i])/2.);
			effFile = TFile::Open(effbase+"Lbeff2D_cosThetaB_vs_q2_DD.root");
			TH2F * effDDB2D  = (TH2F *)effFile->Get("hupper_eff");
			effDDB = (TH1F*)GetSliceX(effDDB2D,(q2max[i]+q2min[i])/2.);
			effFile = TFile::Open(effbase+"Lbeff2D_cosThetaB_vs_q2_LL.root");
			TH2F * effLLB2D  = (TH2F *)effFile->Get("hupper_eff");
			effLLB = (TH1F*)GetSliceX(effLLB2D,(q2max[i]+q2min[i])/2.);
		}

		ceff->cd();

		/**                    FIT EFFICIENCY                  **/

		RooDataHist * hLL = new RooDataHist("hLL","hLL",*cosThetaL,effLL);
		RooDataHist * hDD = new RooDataHist("hDD","hDD",*cosThetaL,effDD);
		RooRealVar * c1LL = new RooRealVar("c1LL","",0.,-1.,1);
		RooRealVar * c1DD = new RooRealVar("c1DD","",0.,-1.,1);
		RooRealVar * c2LL = new RooRealVar("c2LL","",0.,-1.,1);
		RooRealVar * c2DD = new RooRealVar("c2DD","",0.,-1.,1);
		TString effLLstr = "(1 + c1LL*cosThetaL + c2LL*TMath::Power(cosThetaL,2))";
		TString effDDstr = "(1 + c1DD*cosThetaL + c2DD*TMath::Power(cosThetaL,2))";
		RooAbsPdf * effLLpdf = new RooGenericPdf("effLLpdf", "", effLLstr, RooArgSet(*cosThetaL, *c1LL, *c2LL));
		RooAbsPdf * effDDpdf = new RooGenericPdf("effDDpdf", "", effDDstr, RooArgSet(*cosThetaL, *c1DD, *c2DD));
		effLLpdf->fitTo(*hLL,PrintLevel(-1));
		effDDpdf->fitTo(*hDD,PrintLevel(-1));
		fixParams(effLLpdf,cosThetaL);
		fixParams(effDDpdf,cosThetaL);	

		RooDataHist * hLLB = new RooDataHist("hLLB","hLLB",*cosThetaB,effLLB);
		RooDataHist * hDDB = new RooDataHist("hDDB","hDDB",*cosThetaB,effDDB);
		RooRealVar * cB1LL = new RooRealVar("cB1LL","",0,-1.,1);
		RooRealVar * cB1DD = new RooRealVar("cB1DD","",0,-1.,1);
		RooRealVar * cB2LL = new RooRealVar("cB2LL","",0,-1.,1);
		RooRealVar * cB2DD = new RooRealVar("cB2DD","",0,-1.,1);
		TString effLLBstr = "(1 + cB1LL*cosThetaB + cB2LL*TMath::Power(cosThetaB,2))";
		TString effDDBstr = "(1 + cB1DD*cosThetaB + cB2DD*TMath::Power(cosThetaB,2))";
		RooAbsPdf * effLLpdfB = new RooGenericPdf("effLLpdfB", "", effLLBstr, RooArgSet(*cosThetaB, *cB1LL, *cB2LL));
		RooAbsPdf * effDDpdfB = new RooGenericPdf("effDDpdfB", "", effDDBstr, RooArgSet(*cosThetaB, *cB1DD, *cB2DD));
		effLLpdfB->fitTo(*hLLB,PrintLevel(-1));
		effDDpdfB->fitTo(*hDDB,PrintLevel(-1));
		fixParams(effLLpdfB,cosThetaB);
		fixParams(effDDpdfB,cosThetaB);

		//cout << q2min[i] << " - " << q2max[i] << " LL cosThetaL -> " << c1LL->getVal() << "  " << c2LL->getVal() << endl;
		//cout << q2min[i] << " - " << q2max[i] << " DD cosThetaL -> " << c1DD->getVal() << "  " << c2DD->getVal() << endl;
		//cout << q2min[i] << " - " << q2max[i] << " LL cosThetaB -> " << cB1LL->getVal() << "  " << cB2LL->getVal() << endl;
		//cout << q2min[i] << " - " << q2max[i] << " DD cosThetaB -> " << cB1DD->getVal() << "  " << cB2DD->getVal() << endl;


		if(printeff) {
			GetFrame(cosThetaL, hLL,effLLpdf,"-nochi2",0,NULL,0,"cos#theta_{l}","Tot. eff.")->Draw();
			ceff->Print("DDeffFit"+q2name+".pdf");
			GetFrame(cosThetaL, hDD,effDDpdf,"-nochi2",0,NULL,0,"cos#theta_{l}","Tot. eff.")->Draw();
			ceff->Print("LLeffFit"+q2name+".pdf");
			GetFrame(cosThetaB, hLLB,effLLpdfB,"-nochi2",0,NULL,0,"cos#theta_{#Lambda}","Tot. eff.")->Draw();
			ceff->Print("DDeffFitB"+q2name+".pdf");
			GetFrame(cosThetaB, hDDB,effDDpdfB,"-nochi2",0,NULL,0,"cos#theta_{#Lambda}","Tot. eff.")->Draw();
			ceff->Print("LLeffFitB"+q2name+".pdf"); }

			/**                    FIT AFB                  **/


			afb->setVal(0);
			afbB->setVal(0);
			fL->setVal(0.7);

			TString LLnorm = "1./( 1. + (2./3.)*afb*c1LL + (2./5.)*c2LL - (1./5.)*c2LL*fL )*"+effLLstr;
			TString DDnorm = "1./( 1. + (2./3.)*afb*c1DD + (2./5.)*c2DD - (1./5.)*c2DD*fL )*"+effDDstr;
			RooAbsPdf * corrPdfLL = new RooGenericPdf(Form("corrPdfLL_%i",i),LLnorm+"*"+afbLpdf,RooArgSet(*cosThetaL, *afb, *fL, *c1LL, *c2LL) );
			RooAbsPdf * corrPdfDD = new RooGenericPdf(Form("corrPdfDD_%i",i),DDnorm+"*"+afbLpdf,RooArgSet(*cosThetaL, *afb, *fL, *c1DD, *c2DD) );

			TString LLnormB = "1./( (2./3.)*( 2*afbB*cB1LL + cB2LL + 3.) )*"+effLLBstr;
			TString DDnormB = "1./( (2./3.)*( 2*afbB*cB1DD + cB2DD + 3.) )*"+effDDBstr;
			RooAbsPdf * corrPdfLLB = new RooGenericPdf(Form("corrPdfLLB_%i",i),LLnormB+"*"+afbBpdf,RooArgSet(*cosThetaB, *afbB, *cB1LL, *cB2LL) );
			RooAbsPdf * corrPdfDDB = new RooGenericPdf(Form("corrPdfDDB_%i",i),DDnormB+"*"+afbBpdf,RooArgSet(*cosThetaB, *afbB, *cB1DD, *cB2DD) );

			TCut cutLL = CutsDef::LLcut + (TCut)curq2cut;
			TCut cutDD = CutsDef::DDcut + (TCut)curq2cut;

			if(dodata=="genMC")
			{
				corrPdfLLB = new RooGenericPdf("corrPdfLL",afbBpdf,RooArgSet(*cosThetaB, *afbB, *cB1LL, *cB2LL) );
				corrPdfDDB = new RooGenericPdf("corrPdfDD",afbBpdf,RooArgSet(*cosThetaB, *afbB, *cB1DD, *cB2DD) );
				corrPdfLL = new RooGenericPdf("corrPdfLL",afbLpdf,RooArgSet(*cosThetaL, *afb, *fL, *c1LL, *c2LL) );
				corrPdfDD = new RooGenericPdf("corrPdfDD",afbLpdf,RooArgSet(*cosThetaL, *afb, *fL, *c1DD, *c2DD) );
				cutLL = (TCut)curq2cut;
				cutDD = (TCut)curq2cut;
			}

			Analysis * anaLL = new Analysis(Form("LL_mass_%i",i),"Lb",data,&cutLL,MM);
			anaLL->AddVariable(cosThetaL);
			anaLL->AddVariable(cosThetaB);
			anaLL->AddVariable("J_psi_1S_MM");
			if(dodata!="data") anaLL->SetWeight(wstr);
			RooDataSet * dataLL = anaLL->GetDataSet("-recalc-docuts");

			Analysis * anaDD = new Analysis(Form("DD_mass_%i",i),"Lb",data,&cutDD,MM);
			anaDD->AddVariable(cosThetaL);
			anaDD->AddVariable(cosThetaB);
			anaDD->AddVariable("J_psi_1S_MM");
			if(dodata!="data") anaDD->SetWeight(wstr);
			RooDataSet * dataDD = anaDD->GetDataSet("-recalc-docuts");

			RooDataSet * sdataDD, * sdataLL;

			if(dodata=="data")
			{
				sdataLL = anaLL->CalcSweight("",massModel.c_str(),"Exp");

				if(printSw) {
					GetFrame(MM,NULL,sdataLL,"-nochi2",30,NULL,0,"M(#Lambda#mu#mu) (MeV/c^{2})")->Draw();
					ceff->Print("Mass_LL_sWeighted"+q2name+".pdf");
					GetFrame(cosThetaL,NULL,sdataLL,"-nochi2",6,NULL,0,"cos#theta_{l}")->Draw();
					ceff->Print("cosThetaL_LL_sWeighted"+q2name+".pdf");
					GetFrame(cosThetaL,NULL,dataLL,"-nochi2",6,NULL,0,"cos#theta_{l}")->Draw();
					ceff->Print("cosThetaL_LL_"+q2name+".pdf");
				}

				sdataDD = anaDD->CalcSweight("",massModel.c_str(),"Exp");

				if(printSw) {
					GetFrame(MM,NULL,sdataDD,"-nochi2",30,NULL,0,"M(#Lambda#mu#mu) (MeV/c^{2})")->Draw();
					ceff->Print("Mass_DD_sWeighted"+q2name+".pdf");
					GetFrame(cosThetaL,NULL,sdataDD,"-nochi2",10,NULL,0,"cos#theta_{l}")->Draw();
					ceff->Print("cosThetaL_DD_sWeighted"+q2name+".pdf");
					GetFrame(cosThetaL,NULL,dataDD,"-nochi2",10,NULL,0,"cos#theta_{l}")->Draw();
					ceff->Print("cosThetaL_DD_"+q2name+".pdf");
				}
			}		
			else { sdataLL = dataLL; sdataDD = dataDD; }

			histFile->cd();
			TTree * LLTree = (TTree*)sdataLL->tree();
			LLTree->SetName(Form("treeLL_%i",i));
			LLlist->Add(LLTree);
			TTree * DDTree = (TTree*)sdataDD->tree();
			DDTree->SetName(Form("treeDD_%i",i));
			DDlist->Add(DDTree);


			// CREATE COMBINED DATASET
			RooDataSet * combData;
			if(dodata=="data") combData = new RooDataSet(Form("combData_%i",i),"combined data",RooArgSet(*cosThetaL,*cosThetaB,*nsig_sw),Index(*samples),Import("DD",*sdataDD),Import("LL",*sdataLL),WeightVar("nsig_sw"));
			else combData = new RooDataSet(Form("combData_%i",i),"combined data",RooArgSet(*cosThetaL,*cosThetaB,*MCweight),Index(*samples),Import("DD",*sdataDD),Import("LL",*sdataLL),WeightVar(wstr));


			// FIT COS LEPTON
			RooSimultaneous * combModel = new RooSimultaneous(Form("combModel_%i",i),"",*samples);
			combModel->addPdf(*corrPdfLL,"LL");
			combModel->addPdf(*corrPdfDD,"DD");

			combModel->fitTo(*combData,PrintLevel(-1),Verbose(kFALSE),SumW2Error(kTRUE));

			if(fitsingle) corrPdfLL->fitTo(*sdataLL,PrintLevel(-1),Verbose(kFALSE),SumW2Error(kTRUE));
			GetFrame(cosThetaL,corrPdfLL,sdataLL,"-sumW2err-nochi2-noCost",6,NULL,0,"cos#theta_{l}")->Draw();
			ceff->Print("Afb_LL_"+q2name+".pdf");
			if(fitsingle) corrPdfDD->fitTo(*sdataDD,PrintLevel(-1),Verbose(kFALSE),SumW2Error(kTRUE));		
			GetFrame(cosThetaL,corrPdfDD,sdataDD,"-sumW2err-nochi2-noCost",10,NULL,0,"cos#theta_{l}")->Draw();
			ceff->Print("Afb_DD_"+q2name+".pdf");

			Afb_vs_q2->SetPoint(i,(q2max[i] + q2min[i])/2.,afb->getVal());
			Afb_vs_q2->SetPointError(i,(q2max[i] - q2min[i])/2.,afb->getError());
			fL_vs_q2->SetPoint(i,(q2max[i] + q2min[i])/2.,fL->getVal());
			fL_vs_q2->SetPointError(i,(q2max[i] - q2min[i])/2.,fL->getError());
				
			// FIT COS HADRON
			RooSimultaneous * combModelB = new RooSimultaneous(Form("combModelB_%i",i),"",*samples);
			combModelB->addPdf(*corrPdfLLB,"LL");
			combModelB->addPdf(*corrPdfDDB,"DD");

			combModelB->fitTo(*combData,PrintLevel(-1),Verbose(kFALSE),SumW2Error(kTRUE));

			if(fitsingle) corrPdfLLB->fitTo(*sdataLL,PrintLevel(-1),Verbose(kFALSE),SumW2Error(kTRUE));
			GetFrame(cosThetaB,corrPdfLLB,sdataLL,"-sumW2err-nochi2-noCost",6,NULL,0,"cos#theta_{#Lambda}")->Draw();
			ceff->Print("AfbB_LL_"+q2name+".pdf");
			if(fitsingle) corrPdfDDB->fitTo(*sdataDD,PrintLevel(-1),Verbose(kFALSE),SumW2Error(kTRUE));		
			GetFrame(cosThetaB,corrPdfDDB,sdataDD,"-sumW2err-nochi2-noCost",10,NULL,0,"cos#theta_{#Lambda}")->Draw();
			ceff->Print("AfbB_DD_"+q2name+".pdf");

			AfbB_vs_q2->SetPoint(i,(q2max[i] + q2min[i])/2.,afbB->getVal());
			AfbB_vs_q2->SetPointError(i,(q2max[i] - q2min[i])/2.,afbB->getError());
			
			cout << endl << fixed << setprecision(6) << "AfbB = " << afbB->getVal() << " +/- " << afbB->getError() << endl;
			cout << "Afb = " << afb->getVal() << " +/- " << afb->getError() << endl;
			cout << "fL = " << fL->getVal() << " +/- " << fL->getError() << endl;
			cout << endl;
			cout << "------------------------ FELDMAN AND COUSINS ------------------------" << endl;

			vector < RooDataSet * > datas;
			vector < RooAbsPdf * > pdfs, pdfsB;
			vector < TString > cat;
			cat.push_back("LL");
			cat.push_back("DD");
			datas.push_back(sdataLL);
			datas.push_back(sdataDD);

			RooArgSet * origPars = new RooArgSet();
			origPars->add(*origafb);
			origPars->add(*origfL);
			
			pdfs.push_back(corrPdfLL);
			pdfs.push_back(corrPdfDD);

			vector< double > afb_err, afbB_err, fL_err;
/*
			double fLval = fL->getVal(), fLerr = fL->getError();
			FeldmanCousins * FC = new FeldmanCousins(q2name,cat,datas,pdfs,cosThetaL,afb,"nsig_sw");
			//FC->SetNPointsToScan(20);
			//FC->SetNExp(1000);
			if(q2min[i]==18) afb_err = FC->ExtractLimits(origPars,-0.3,0.3);
			else if( (afb->getVal()-1.4*afb->getError()) > -1 && (afb->getVal()+1.4*afb->getError()) < 1 )
		       afb_err = FC->ExtractLimits(origPars,afb->getVal()-1.4*afb->getError(),afb->getVal()+1.4*afb->getError());
		    else afb_err = FC->ExtractLimits(origPars,-0.4,0.4);

			//FeldmanCousins * FCfL = new FeldmanCousins(q2name,cat,datas,pdfs,cosThetaL,fL,"nsig_sw");
			//if(q2min[i]==11) fL_err = FCfL->ExtractLimits(origPars,0.,0.6);
			//else if (q2min[i]==18) fL_err = FCfL->ExtractLimits(origPars,0.75,0.992);
			//( (fLval-1.3*fLerr) > 0 && (fLval+1.3*fLerr) <= 1 )
			//else fL_err = FCfL->ExtractLimits(origPars,fLval-1.3*fLerr,fLval+1.3*fLerr);

			afb_errs.push_back(afb_err);
			//fL_errs.push_back(fL_err);

 			RooArgSet * origParsB = new RooArgSet();
			origParsB->add(*origafbB);
			pdfsB.push_back(corrPdfLLB);
			pdfsB.push_back(corrPdfDDB);

			FeldmanCousins * FCB = new FeldmanCousins(q2name,cat,datas,pdfsB,cosThetaB,afbB,"nsig_sw");
			if( (afbB->getVal()-1.5*afbB->getError()) > -1 && (afbB->getVal()+1.5*afbB->getError()) < 1 )
			   afbB_err = FCB->ExtractLimits(origParsB,afbB->getVal()-1.5*afbB->getError(),afbB->getVal()+1.5*afbB->getError());
			else afbB_err = FCB->ExtractLimits(origParsB,-0.4,0.4);

			afbB_errs.push_back(afbB_err);
*/
			delete effDD;
			delete effLL;
			delete effLLB;
			delete effDDB;
	}

	cDD->Print("DDeff.pdf");
	cLL->Print("LLeff.pdf");
	cDDB->Print("DDBeff.pdf");
	cLLB->Print("LLBeff.pdf");


	Afb_vs_q2->GetXaxis()->SetTitle("q^{2}");
	Afb_vs_q2->GetYaxis()->SetTitle("Afb");
	Afb_vs_q2->SetMaximum(1);
	Afb_vs_q2->SetMinimum(-1);
	Afb_vs_q2->Draw("AP");
	ceff->Print("Afb_vs_q2.pdf");
	AfbB_vs_q2->GetXaxis()->SetTitle("q^{2}");
	AfbB_vs_q2->GetYaxis()->SetTitle("AfbB");
	AfbB_vs_q2->SetMaximum(1);
	AfbB_vs_q2->SetMinimum(-1);
	AfbB_vs_q2->Draw("AP");
	ceff->Print("AfbB_vs_q2.pdf");
	fL_vs_q2->GetXaxis()->SetTitle("q^{2}");
	fL_vs_q2->GetYaxis()->SetTitle("fL");
	fL_vs_q2->Draw("AP");
	ceff->Print("fL_vs_q2.pdf");

	for(int bb = 0; bb < Afb_vs_q2->GetN(); bb++)
	{
		double qq, qqerr, afbv, afbBv, fLv;
		Afb_vs_q2->GetPoint(bb,qq,afbv);
		qqerr = Afb_vs_q2->GetErrorX(bb);
		AfbB_vs_q2->GetPoint(bb,qq,afbBv);
		fL_vs_q2->GetPoint(bb,qq,fLv);
		cout << fixed << setprecision(1) << qq-qqerr << " - " << qq+qqerr;
		cout << fixed << setprecision(4); 
		//cout << " & $" << afbv << "_{-" << TMath::Abs(afb_errs[bb][0] - afbv) << "}^{+" << TMath::Abs(afb_errs[bb][1] - afbv)  << "} \\text{(stat)} \\pm \\text{(sys)}$ ";
		//cout << " & $" << afbBv << "_{-" << TMath::Abs(afbB_errs[bb][0] - afbBv) << "}^{+" << TMath::Abs(afbB_errs[bb][1]-afbBv) << "} \\text{(stat)} \\pm \\text{(sys)}$ " ;
		//cout << " & $" << fLv << "_{-" << TMath::Abs(fL_errs[bb][0] - fLv) << "}^{+" << TMath::Abs(fL_errs[bb][1] - fLv)  << "} \\text{(stat)} \\pm \\text{(sys)}$ ";
		cout << "  \\\\ " << endl;
	}

	histFile->cd();
	TTree * finalLLtree = (TTree*)TTree::MergeTrees(LLlist);
	TTree * finalDDtree = (TTree*)TTree::MergeTrees(DDlist);
	finalLLtree->SetName("LL_data");
	finalDDtree->SetName("DD_data");
	finalLLtree->Write();
	finalDDtree->Write();

	delete ceff;
	histFile->Write();
	delete histFile;

	}
void forest2yskim_jetSkim_forestV3_noEleRejection(TString inputFile_="forestFiles/pA/pA_photonSkimForest_v85_skimPhotonPt50_eta1.5.root",
		std::string MinbiasFname = "skim_trackJet_minbiasTrackJet_mc.root",
		float cutphotonPt  = 35,  // default value dropped to 35GeV  for later photon energy smearing/scaling
		std::string outname = "testPhotonSkim.root",
		sampleType colli=kPADATA,
		bool doMix = false,
		bool doJetResCorrection = 1,  // = L2L3 * MC nonclosure correction  jet energy correction is done by default from Oct 19th (YS)
		int smearingCentBin = -1, //0=0-10%, 1=10-30%, 2=30-50%, 3=50-100%, 4=0-30%, 5=30-100%  : Jet pT and phi smearing!
		float jetEnergyScale = 1.0, 
		float addFlatJetEnergyRes = 0.0, 
		bool useGenJetColl = 0
		)
{
	bool isMC=true;
	if ((colli==kPPDATA)||(colli==kPADATA)||(colli==kHIDATA))
		isMC=false;

	int seconds = time(NULL);         cout << " time = " <<seconds%10000<< endl;
	TRandom3 rand(seconds%10000);
	TString datafname  = "";
	float cutphotonEta = 1.44;
	float preCutPhotonEt = 30;

	const int nMaxPho = 100;


	HiForest *c;
	if((colli==kPADATA)||(colli==kPAMC)) {
		c = new HiForest(inputFile_.Data(), "forest", cPPb, isMC );
	}
	else if  ((colli==kPPDATA)||(colli==kPPMC)) {
		c = new HiForest(inputFile_.Data(), "forest", cPP, isMC );
	}
	else if  ((colli==kHIDATA)||(colli==kHIMC)) {
		c = new HiForest(inputFile_.Data(), "forest", cPbPb, isMC );
		c->GetEnergyScaleTable("../photonEnergyScaleTable_lowPt_v6.root");
	}
	else {
		cout << " Error!  No such collision type" << endl;
		return;
	}

	c->InitTree();


	// vertex and centrality vtxCentWeighting
	TFile* fWeight = new TFile("../vertexReweightingHistogram_pthatweighted.root");

	TH1D* hWeight_vtx_data_pp = (TH1D*)fWeight->Get("vertexHistoData_pp");
	TH1D* hWeight_vtx_mc_pp = (TH1D*)fWeight->Get("vertexHistoMC_pp");

	TH1D* hWeight_vtx_data_ppb = (TH1D*)fWeight->Get("vertexHistoData_ppb");
	TH1D* hWeight_vtx_mc_ppb = (TH1D*)fWeight->Get("vertexHistoMC_ppb");

	TH1D* hWeight_vtx_data_pbpb = (TH1D*)fWeight->Get("vertexHistoData_pbpb");
	TH1D* hWeight_vtx_mc_pbpb = (TH1D*)fWeight->Get("vertexHistoMC_pbpb");
	TH1D* hWeight_cent_data_pbpb = (TH1D*)fWeight->Get("centBinHistoData_pbpb");
	TH1D* hWeight_cent_mc_pbpb = (TH1D*)fWeight->Get("centBinHistoMC_pbpb");




	// L2L3 correction
	TFile* fL2L3pp = new TFile("../corrL2L3/Casym_pp_double_hcalbins_algo_ak3PF_pt100_140_jet80_alphahigh_20_phicut250.root");
	TH1D * c_etapp=(TH1D*)fL2L3pp->Get("C_asym");
	TF1* fptpp = new TF1("fptpp","1-[0]/pow(x,[1])",20,300);
	fptpp->SetParameters(0.06971,0.8167);

	TFile* fL2L3pA = new TFile("../corrL2L3/Casym_pPb_double_hcalbins_algo_akPu3PF_pt100_140_jet80_alphahigh_20_phicut250.root");
	TH1D * c_etapA=(TH1D*)fL2L3pA->Get("C_asym");
	TF1* fptpA = new TF1("fptpA","1-[0]/pow(x,[1])",20,300);
	fptpA->SetParameters(0.3015, 0.8913);

	TFile* fL2L3Ap = new TFile("../corrL2L3/Casym_Pbp_double_hcalbins_algo_akPu3PF_pt100_140_jet80_alphahigh_20_phicut250.root");
	TH1D * c_etaAp=(TH1D*)fL2L3Ap->Get("C_asym");
	TF1* fptAp = new TF1("fptAp","1-[0]/pow(x,[1])",20,300);
	fptAp->SetParameters(0.3015, 0.8913);

	// pA MC
	TF1 * fgaus=new TF1("fgaus_pA","gaus(0)",-20,20);
	fgaus->SetParameters(1,0,1);
	TF1 * fsmear_pA = new TF1("fsmear_pA","[0]/pow(x,[1])",50,300);
	fsmear_pA->SetParameters(1.052,0.5261);


	/*
	   TCanvas* c11 = new TCanvas("c11","",1200,400);   // valiation of smearing factors
	   c11->Divide(3,1);
	   c11->cd(1);
	   c_etapp->Draw();
	   c11->cd(2);
	   c_etaAp->Draw();
	   c11->cd(3);
	   c_etapA->Draw();
	   c11->SaveAs("f1.gif");
	   */


	// Create a new root file
	TFile* newfile_data = new TFile(outname.data(),"recreate");

	TTree* newtreePhoton;
	float newPt[nMaxPho];  // <<= temporary space
	int order[nMaxPho];
	float corrPt[nMaxPho];
	newtreePhoton = c->photonTree->CloneTree(0);
	newtreePhoton->SetName("yPhotonTree");
	newtreePhoton->SetMaxTreeSize(MAXTREESIZE);
	newtreePhoton->Branch("order",  order, "order[nPhotons]/I");
	newtreePhoton->Branch("corrPt", corrPt,"corrPt[nPhotons]/F");

	TTree* treeFullJet;
	if (   (colli==kPPDATA) || (colli==kPPMC) ) {
		//treeFullJet = c->ak3jetTree->CloneTree(0);
		treeFullJet = c->ak3PFJetTree->CloneTree(0);
		cout << "pp collision.  Using ak3PF Jet Algo" << endl<<endl;
	}
	else {
		//treeFullJet = c->akPu3jetTree->CloneTree(0);
		treeFullJet = c->akPu3PFJetTree->CloneTree(0);
		cout << "PbPb or pPb collision. Using akPu3PF Jet Algo" << endl<<endl;
	}
	treeFullJet->SetName("fullJet");
	treeFullJet->SetMaxTreeSize(MAXTREESIZE);
#if 1
	TTree* treeGenp;
	if (   (colli==kHIMC ) || (colli==kPPMC) || (colli==kPAMC) ) {
		treeGenp =  c->genParticleTree->CloneTree(0);
		treeGenp->SetName("genparTree");
		//treeGenp =  c->genpTree->CloneTree(0);
		//treeGenp->SetName("genparTree");
		treeGenp->SetMaxTreeSize(MAXTREESIZE);
	}
#endif


	// jet tree!
	int nJet;
	const int MAXJET = 50000; // to accomodate 100 smeared jets, need to be careful with ram
	float jetPt[MAXJET];
	float jetEta[MAXJET];
	float jetPhi[MAXJET];
	float jetDphi[MAXJET];
	int jetSubid[MAXJET];
	float jetRefPt[MAXJET];
	float jetRefEta[MAXJET];
	float jetRefPhi[MAXJET];
	float jetRefDphi[MAXJET];
	float jetRefPartonPt[MAXJET];
	int  jetRefPartonFlv[MAXJET];

	TTree *newtreeJet = new TTree("yJet","jets");
	newtreeJet->SetMaxTreeSize(MAXTREESIZE);
	newtreeJet->Branch("nJet",&nJet,"nJet/I");
	newtreeJet->Branch("pt",jetPt,"pt[nJet]/F");
	newtreeJet->Branch("eta",jetEta,"eta[nJet]/F");
	newtreeJet->Branch("phi",jetPhi,"phi[nJet]/F");
	newtreeJet->Branch("dphi",jetDphi,"dphi[nJet]/F");
	if ( isMC )  {
		newtreeJet->Branch("subid",jetSubid,"subid[nJet]/I");
		newtreeJet->Branch("refPt",jetRefPt,"refPt[nJet]/F");
		newtreeJet->Branch("refEta",jetRefEta,"refEta[nJet]/F");
		newtreeJet->Branch("refPhi",jetRefPhi,"refPhi[nJet]/F");
		newtreeJet->Branch("refDphi",jetRefDphi,"refDphi[nJet]/F");
		newtreeJet->Branch("refPartonPt",jetRefPartonPt,"refPartonPt[nJet]/F");
		newtreeJet->Branch("refPartonFlv",jetRefPartonFlv,"refPartonFlv[nJet]/I");
	}



	int nMjet;
	float mJetPt[MAXMJET];
	float mJetEta[MAXMJET];
	float mJetPhi[MAXMJET];
	float mJetDphi[MAXMJET];

	TTree * tmixJet = new TTree("mJet","Jet from minbias events");
	tmixJet->SetMaxTreeSize(MAXTREESIZE);
	tmixJet->Branch("nJet",&nMjet,"nJet/I");
	tmixJet->Branch("pt",mJetPt,"pt[nJet]/F");
	tmixJet->Branch("eta",mJetEta,"eta[nJet]/F");
	tmixJet->Branch("phi",mJetPhi,"phi[nJet]/F");
	tmixJet->Branch("dphi", mJetDphi, "dphi[nJet]/F");



	// Imb = Input MinBias events
	EvtSel          evtImb;
	Int_t           nJetImb;
	Float_t         jetPtImb[100];
	Float_t         jetEtaImb[100];
	Float_t         jetPhiImb[100];
	TBranch        *b_evt;
	TBranch        *b_nJetImb;
	TBranch        *b_jetPtImb;
	TBranch        *b_jetEtaImb;
	TBranch        *b_jetPhiImb;


	int nCentBins =  nCentBinSkim;
	if ((colli==kPADATA)||(colli==kPAMC)) {
		nCentBins = nCentBinSkimPA;
	}

	TChain   *tjmb[100][nVtxBin+1];
	int nMB[100][nVtxBin+1] ; //= 199109;
	int mbItr[100][nVtxBin+1];
	if ( doMix ) {
		cout <<"  Tree initialization for MinBias mixing" << endl;
		for( int icent = 0 ; icent< nCentBins ; icent++) {
			for( int ivz = 1 ; ivz<=nVtxBin ; ivz++) {

				tjmb[icent][ivz] = new TChain(Form("trkAndJets_first_cBin2icent%d_ivz%d",icent,ivz));
				tjmb[icent][ivz]->Add(MinbiasFname.data());
				tjmb[icent][ivz]->SetBranchAddress("evt", &evtImb,&b_evt);
				tjmb[icent][ivz]->SetBranchAddress("nJet",   &nJetImb,   &b_nJetImb);
				tjmb[icent][ivz]->SetBranchAddress("jetPt",  &jetPtImb,  &b_jetPtImb);
				tjmb[icent][ivz]->SetBranchAddress("jetEta", &jetEtaImb, &b_jetEtaImb);
				tjmb[icent][ivz]->SetBranchAddress("jetPhi", &jetPhiImb, &b_jetPhiImb);


				nMB[icent][ivz] = tjmb[icent][ivz]->GetEntries();
				cout << "number of evetns in (icent = " << icent << ", ivtxZ = "<< ivz << ")  = " << nMB[icent][ivz] << endl;
				int primeSeed = rand.Integer(37324);
				mbItr[icent][ivz] = primeSeed%(nMB[icent][ivz]);
				cout <<" initial itr = " << mbItr[icent][ivz] << endl;
			}
		}
	}
	else
		cout << endl << endl << "  Mixing process is skipped" << endl << endl << endl ;


	// reweighting factor should go here
	int eTot(0), eSel(0);
	EvtSel evt;
	GammaJet gj;
	Isolation isol;
	TTree *tgj;
	tgj = new TTree("tgj","gamma jet tree");
	tgj->SetMaxTreeSize(MAXTREESIZE);
	tgj->Branch("evt",&evt.run,"run/I:evt:cBin:pBin:trig/O:offlSel:noiseFilt:anaEvtSel:vz/F:vtxCentWeight/F:hf4Pos:hf4Neg:hf4Sum:ptHat:ptHatWeight");
	tgj->Branch("lpho",&gj.photonEt,"photonEt/F:photonRawEt:photonEta:photonPhi:hovere:r9:sigmaIetaIeta:sumIso:genIso:genPhotonEt:genMomId/I:lJetPt/F:lJetEta:lJetPhi:lJetDphi:lJetSubid/I");
	tgj->Branch("isolation",&isol.cc1,"cc1:cc2:cc3:cc4:cc5:cr1:cr2:cr3:cr4:cr5:ct1PtCut20:ct2PtCut20:ct3PtCut20:ct4PtCut20:ct5PtCut20:ecalIso:hcalIso:trackIso");  // ecalIso,hcalIso,trackIso are the pp style isolation


	float vzCut = vtxCutPhotonAna;
	TH1F* hvz = new TH1F("hvz","",nVtxBin,-vzCut,vzCut);
	// event plane hitogram
	TH1F* hEvtPlnBin = new TH1F("hEvtPlnBin", "", nPlnBin, -PI/2., PI/2.);
	// jet algos
	Jets* theJet;
	Jets* genJetTree;
	if (   (colli==kPPDATA) || (colli==kPPMC) ) {
		theJet = &(c->ak3PF) ;
		cout << "pp collision.  Using ak3PF Jet Algo" << endl<<endl;
	}
	else {
		theJet = &(c->akPu3PF) ;
		cout << "PbPb or pPb collision. Using akPu3PF Jet Algo" << endl<<endl;
	}
	genJetTree = &(c->akPu3PF);

	//////// Kaya's modificiation ////////
	EventMatchingCMS* eventMatcher=new EventMatchingCMS();
	bool eventAdded;
	Long64_t duplicateEvents = 0;
	//////// Kaya's modificiation - END ////////

	// Loop starts.
	int nentries = c->GetEntries();
	cout << "number of entries = " << nentries << endl;
	for (Long64_t jentry = 0 ; jentry < nentries; jentry++) {
		eTot++;
		if (jentry% 2000 == 0)  {
			cout <<jentry<<" / "<<nentries<<" "<<setprecision(2)<<(double)jentry/nentries*100<<endl;
		}

		c->GetEntry(jentry);

		//////// Kaya's modificiation ////////
		eventAdded = eventMatcher->addEvent(c->evt.evt, c->evt.lumi, c->evt.run, jentry);
		if(!eventAdded) // this event is duplicate, skip this one.
		{
			duplicateEvents++;
			continue;
		}
		//////// Kaya's modificiation - END ////////

		// Select events with a generated photon in mid-rapidity
		bool genPhotonFlag=false;
		if ( !isMC )   // fixed the most stupid error
			genPhotonFlag = true;
		else {
#if 0 // there is no genp tree, but is higentree
			for ( int g=0 ; g< c->genp.nPar ; g++)
				if ( c->genp.id[g] != 22 )
					continue;
			if ( fabs( c->genp.momId[g] ) > 22 )
				continue;
			if ( fabs( c->genp.status[g] ) != 1 )
				continue;
			if ( fabs( c->genp.eta[g] ) > cutphotonEta )
				continue;
			if ( c->genp.et[g] < 35 )
				continue;
#endif
			for ( int g=0 ; g< c->genparticle.mult ; g++) {
				if ( c->genparticle.pdg[g] != 22 )
					continue;
				//	if ( fabs( c->genparticle.momId[g] ) > 22 )
				//	  continue;
				//	if ( fabs( c->genparticle.status[g] ) != 1 )
				//	  continue;
				if ( fabs( c->genparticle.eta[g] ) > cutphotonEta )
					continue;
				if ( c->genparticle.pt[g] < cutphotonPt )
					continue;
				genPhotonFlag = true;
			}
		}
		if ( !genPhotonFlag)
			continue;

		evt.clear();
		evt.run   = c->evt.run;
		evt.evt = c->evt.evt;
		evt.hf4Pos = c->evt.hiHFplusEta4;
		evt.hf4Neg = c->evt.hiHFminusEta4;
		evt.hf4Sum = evt.hf4Pos + evt.hf4Neg;
		evt.cBin = -99;
		evt.pBin   = -99 ;
		if ((colli==kHIDATA)||(colli==kHIMC))   {
			evt.cBin = c->evt.hiBin;
			evt.pBin   = hEvtPlnBin->FindBin( c->evt.hiEvtPlanes[theEvtPlNumber] ) ;
		}
		else if ((colli==kPADATA)||(colli==kPAMC))   {
			evt.cBin =  getHfBin(evt.hf4Sum);
			// if (  ((evt.cBin) < 0) || (evt.cBin) > 18 )
			//   cout << " Check the pA centrality..  cbin = " << evt.cBin << endl;
		}

		evt.trig = 0;
		evt.offlSel = (c->skim.pcollisionEventSelection > 0);
		evt.noiseFilt = (c->skim.pHBHENoiseFilter > 0);
		evt.anaEvtSel = c->selectEvent() && evt.trig;
		evt.vz = c->evt.vz;

		int cBin = evt.cBin;
		int vzBin = hvz->FindBin(evt.vz)  ;
		hvz->Fill(evt.vz) ;

		// this was the problem!!! all c->selectEvent() are 0
		//if ( ( (colli==kHIDATA)||(colli==kHIMC)||(colli==kPADATA)||(colli==kPAMC) || (colli==kPPMC) ) && ( c->selectEvent() == 0 ))
		if ( ( (colli==kHIDATA)||(colli==kHIMC) ) && ( c->skim.pcollisionEventSelection == 0 ))
			continue;
		if ( ( (colli==kPADATA)||(colli==kPAMC)||(colli==kPPDATA)||(colli==kPPMC)) && ( c->skim.pPAcollisionEventSelectionPA == 0 )) // yeonju included pp data and pp mc
			continue;
	//	if ( ( (colli==kPPMC) ) && ( c->skim.pcollisionEventSelection == 0 ))
	//		continue;
	//	if ( ( (colli==kPADATA)||(colli==kPPDATA) ) && ( c->skim.pVertexFilterCutGplus ==0 ) ) // No Pile up events
	//		continue;
		if ( (vzBin<1) || ( vzBin > nVtxBin) )
			continue;

		eSel++;      // OK.  This event is a collisional and no-noise event.


		// Reweight for vertex and centrality of MC
		evt.vtxCentWeight = 1;
		double wVtx=1;
		double wCent=1;
		if (colli ==kHIMC) {
			int vBin =  hWeight_vtx_data_pbpb->FindBin(evt.vz);
			wVtx =   hWeight_vtx_data_pbpb->GetBinContent(vBin) / hWeight_vtx_mc_pbpb->GetBinContent(vBin) ;
			wCent =  hWeight_cent_data_pbpb->GetBinContent(evt.cBin+1) / hWeight_cent_mc_pbpb->GetBinContent(evt.cBin+1) ;
		}
		else if ( colli ==kPPMC) {
			int vBin =  hWeight_vtx_data_pp->FindBin(evt.vz);
			wVtx =   hWeight_vtx_data_pp->GetBinContent(vBin) / hWeight_vtx_mc_pp->GetBinContent(vBin) ;
		}
		else if ( colli ==kPAMC) {
			int vBin =  hWeight_vtx_data_ppb->FindBin(evt.vz);
			wVtx =   hWeight_vtx_data_ppb->GetBinContent(vBin) / hWeight_vtx_mc_ppb->GetBinContent(vBin) ;
		}
		evt.vtxCentWeight = wVtx * wCent;

		evt.ptHat = -1;
		evt.ptHatWeight = 1;
		evt.ptHat = c->photon.ptHat;

		// if( colli == kPAMC && evt.ptHat > maxpthat ) // pA samples don't use ptHatCutter.C.
		//	continue;
		if (colli ==kHIMC) {
			if ( evt.ptHat < 50  )       evt.ptHatWeight = 9008/16237. ;
			else if ( evt.ptHat < 80  )       evt.ptHatWeight = 3750/85438. ;
			else   evt.ptHatWeight =  1191/140432. ;
		}
        else if ( colli == kPPMC) { // pp has only 4 pthat samples
            if ( evt.ptHat > 30 && evt.ptHat < 50  )       evt.ptHatWeight = 156861/156861. ;
            else if ( evt.ptHat > 50 && evt.ptHat < 80  )       evt.ptHatWeight = 33610/193462. ;
            else if ( evt.ptHat > 80 && evt.ptHat < 120  )       evt.ptHatWeight = 5757/195174. ;
            else   evt.ptHatWeight = 1272/236703. ;
            //  if ( evt.ptHat < 50  )       evt.ptHatWeight = 9008/9008. ;
            //  else if ( evt.ptHat < 80  )       evt.ptHatWeight = 3750/40109. ;
            //  else   evt.ptHatWeight = 1191/66934. ;
    	}
		else if ( colli == kPAMC) { 
			if ( evt.ptHat > 30 && evt.ptHat < 50  )       evt.ptHatWeight = 62744/62744. ;
			else if ( evt.ptHat > 50 && evt.ptHat < 80  )       evt.ptHatWeight = 29499/107309. ;
			else if ( evt.ptHat > 80 && evt.ptHat < 120  )       evt.ptHatWeight = 7640/106817. ;
			else if ( evt.ptHat > 120 && evt.ptHat < 170  )       evt.ptHatWeight = 1868/104443. ;
			else   evt.ptHatWeight = 649/139647. ;
		}



		for (int j=0;j< c->photon.nPhotons;j++) {

			if (  ( c->photon.pt[j] > preCutPhotonEt ) && ( fabs( c->photon.eta[j] ) < cutphotonEta ) ) {
				newPt[j] = c->getCorrEt(j);
			}
			else
				newPt[j] = c->photon.pt[j] - 10000;

		//	if ( (c->isSpike(j)) || (c->photon.hadronicOverEm[j]>0.2) || (c->photon.isEle[j]))  // Electron Rejection should be default.
			if ( (c->isSpike(j)) || (c->photon.hadronicOverEm[j]>0.2) ) //||  (c->photon.isEle[j])  // This is for no Electron Rejection case.
				newPt[j] = newPt[j] - 20000;
			if (c->photon.seedTime[j] ==0 )   // clustering bug
				newPt[j] = newPt[j] - 30000;

			corrPt[j] = newPt[j];
		}

		TMath::Sort(c->photon.nPhotons, newPt, order);


		// Select the leading photon
		gj.clear();
		int leadingIndex=-1;
		for (int j=0;j<c->photon.nPhotons;j++) {
			if ( c->photon.pt[j]  < preCutPhotonEt ) continue;
			if ( fabs(c->photon.eta[j]) > cutphotonEta ) continue;
			if (c->isSpike(j)) continue;
			//   if (!(c->isLoosePhoton(j))) continue;
			if (c->photon.hadronicOverEm[j]>0.1) continue;
			if ((c->photon.rawEnergy[j]/c->photon.energy[j])<0.5) continue;



			// sort using corrected photon pt
			float theCorrPt= corrPt[j];
			if ( theCorrPt > gj.photonEt) {
				gj.photonEt = theCorrPt;
				leadingIndex = j;
			}
		}
		//    if ( (gj.photonEt < cutphotonPt) )    <== This cut ruins the ptHat weighting factor
		//  continue;


		/// Save leading photons
		if (leadingIndex!=-1) {
			gj.photonRawEt=c->photon.pt[leadingIndex];
			gj.photonEta=c->photon.eta[leadingIndex];
			gj.photonPhi=c->photon.phi[leadingIndex];
			gj.hovere=c->photon.hadronicOverEm[leadingIndex];
			gj.r9=c->photon.r9[leadingIndex];
			gj.sigmaIetaIeta=c->photon.sigmaIetaIeta[leadingIndex];
			gj.sumIsol = (c->photon.cr4[leadingIndex]+c->photon.cc4[leadingIndex]+c->photon.ct4PtCut20[leadingIndex]) / 0.9;
			gj.genIso   = c->photon.genCalIsoDR04[leadingIndex];
			gj.genPhotonEt = c->photon.genMatchedPt[leadingIndex];
			gj.genMomId = c->photon.genMomId[leadingIndex];
			isol.Set(c,leadingIndex);
		}
		else {
			gj.clear();
		}
		if ( (colli==kPADATA) && ( evt.run > 211256 ) )  {
			gj.photonEta = - gj.photonEta;
		}



		///////////////////// Skimmed Jet tree ///////////////////////////////////
		nJet = 0 ;

		int jetEntries = 0;
		if (useGenJetColl )    jetEntries = theJet->ngen;
		else                   jetEntries = theJet->nref;

		int nSmear = 1;
		if(smearingCentBin != -1)
			nSmear = 100;

		for(int iSmear =0; iSmear < nSmear; iSmear++){ // iSmear loop have to be here, before Jet loop. mis-ordered for loops ruins jetrefpt values.
			for (int ij=0; ij< jetEntries ; ij++) {
				if ( gj.photonEt < 0 )    continue ;    // If there is no photon in this event
				if (  useGenJetColl )   {
					jetPt[nJet] = theJet->genpt[ij];
					jetEta[nJet] = theJet->geneta[ij];
					jetPhi[nJet] = theJet->genphi[ij];
				}
				else  {
					jetPt[nJet] = theJet->jtpt[ij];
					jetEta[nJet] = theJet->jteta[ij];
					jetPhi[nJet] = theJet->jtphi[ij];
				}

				// Smear phi
				Double_t newPhi = jetPhi[nJet] ;
				if( smearingCentBin != -1 )
				{
					Double_t phiSmear  = TMath::Sqrt((cphi_pbpb[smearingCentBin]*cphi_pbpb[smearingCentBin] - cphi_pp*cphi_pp)
							+ (sphi_pbpb[smearingCentBin]*sphi_pbpb[smearingCentBin] - sphi_pp*sphi_pp)/jetPt[nJet]
							+ (nphi_pbpb[smearingCentBin]*nphi_pbpb[smearingCentBin] - nphi_pp*nphi_pp)/(jetPt[nJet]*jetPt[nJet]));
					newPhi  =  jetPhi[nJet] +   rand.Gaus(0, phiSmear);
					while ( fabs(newPhi) > PI )  {
						if ( newPhi > PI )  newPhi = newPhi - 2*PI;
						if ( newPhi < -PI )  newPhi = newPhi + 2*PI;
					}
				}
				jetPhi[nJet] = newPhi;


				// smear the jet pT
				//float smeared = jetPt[nJet] * rand.Gaus(1,addJetEnergyRes/jetPt[nJet])   *  rand.Gaus(1, addFlatJetEnergyRes) ;
				Double_t smeared = jetPt[nJet] * rand.Gaus(1, addFlatJetEnergyRes);
				if( smearingCentBin != -1 )
				{
					Double_t smearSigma = TMath::Sqrt((c_pbpb[smearingCentBin]*c_pbpb[smearingCentBin] - c_pp*c_pp)
							+ (s_pbpb[smearingCentBin]*s_pbpb[smearingCentBin] - s_pp*s_pp)/jetPt[nJet]
							+ (n_pbpb[smearingCentBin]*n_pbpb[smearingCentBin] - n_pp*n_pp)/(jetPt[nJet]*jetPt[nJet]));
					smeared = jetPt[nJet] * rand.Gaus(1, smearSigma);
				}
				// then multiply jet energy sclae

				// resCorrection
				float resCorrection =1. ;
				float l2l3Corr =1 ;

				if  (doJetResCorrection)   {
					// L2L3 correction!
					if ( colli == kPPDATA)   {
						l2l3Corr = c_etapp->GetBinContent(c_etapp->FindBin(jetEta[nJet])) * fptpp->Eval( jetPt[nJet]);
					}
					else if ( colli == kPADATA)   {
						if ( evt.run > 211256 )
							l2l3Corr = c_etapA->GetBinContent(c_etapA->FindBin(jetEta[nJet]))  * fptpA->Eval( jetPt[nJet]);
						else
							l2l3Corr = c_etaAp->GetBinContent(c_etaAp->FindBin(jetEta[nJet]))  * fptAp->Eval( jetPt[nJet]);
					}
					else if ( colli == kPAMC)
						l2l3Corr = 1 + (fsmear_pA->Eval( jetPt[nJet] )) * fgaus->GetRandom()  ;

					// do the residual correction
					if ((colli==kHIDATA)||(colli==kHIMC))  { 
						if ( evt.cBin  < 12 )   // central
							resCorrection  =  1.04503 -1.6122  /(sqrt(jetPt[nJet])) + 9.27212 / (jetPt[nJet]);  //1.04503    -1.6122    9.27212
						else                  // peripheral
							resCorrection  =  1.00596 -0.653191/(sqrt(jetPt[nJet])) + 4.35373 / (jetPt[nJet]);  //1.00596     -0.653191  4.35373
					}
					else if ((colli==kPPDATA)||(colli==kPPMC)){  // do the residual correction
						resCorrection  = 0.993609  +0.158418/(sqrt(jetPt[nJet])) + 0.335479 / (jetPt[nJet]);//	  0.993609   0.158418   0.335479
					}
					else if ((colli==kPADATA)||(colli==kPAMC)){
						resCorrection = 0.997738 + 0.0221806/(sqrt(jetPt[nJet])) - 0.877999/ (jetPt[nJet]); //C : 0.997738, S : 0.0221806, N : -0.877999 //function derived as a function of gen pt 
						//resCorrection = 0.981365 + 0.342746/(sqrt(jetPt[nJet])) - 2.63018 / (jetPt[nJet]); //C : 0.981365, S : 0.342746, N : -2.63018 //function derived as a function of gen pt //derived from l2l3 corrected sample. 
						//resCorrection = 0.745753 + 6.91646/(sqrt(jetPt[nJet])) - 33.0167 / (jetPt[nJet]); //C : 0.745753, S : 6.91646, N : -33.0167 //function derived as a function of reco pt 
					}

				} // doJetResCorrection

				// reflect eta!
				if ( (colli==kPADATA) && ( evt.run > 211256 ) )  {
					jetEta[nJet] = -jetEta[nJet];
				}

				jetPt[nJet] = smeared * l2l3Corr /resCorrection *jetEnergyScale;



				if ( jetPt[nJet] < cutjetPtSkim)  // double cutjetPtSkim = 15; Oct 19th
					continue;
				if ( fabs( jetEta[nJet] ) > cutjetEtaSkim )     // double cutjetEtaSkim = 3.0; Oct 19th
					continue;
				if ( getDR( jetEta[nJet], jetPhi[nJet], gj.photonEta, gj.photonPhi) < 0.5 )
					continue;


				if (jetPt[nJet] >0)
					jetDphi[nJet] = getAbsDphi( jetPhi[nJet], gj.photonPhi) ;
				else
					jetDphi[nJet] = -1;


				if (  useGenJetColl )   {
					jetSubid[nJet] = -9999;
					jetRefPt[nJet] = -9999;
					jetRefEta[nJet] = -9999;
					jetRefPhi[nJet] = -9999;
					jetRefPt[nJet] =  -9999;
					jetRefPartonPt[nJet] = -9999;
					jetRefPartonFlv[nJet] = -9999;
				}
				else {
					jetRefPt[nJet] = theJet->refpt[ij];
					jetRefEta[nJet] = theJet->refeta[ij];
					jetRefPhi[nJet] = theJet->refphi[ij];
					if (jetRefPt[nJet] >0)
						jetRefDphi[nJet] = getAbsDphi( jetRefPhi[nJet] , gj.photonPhi) ;
					else
						jetRefDphi[nJet] = -1;
					jetRefPartonPt[nJet] = theJet->refparton_pt[ij];
					jetRefPartonFlv[nJet] = theJet->refparton_flavor[ij];

					jetSubid[nJet] = -9999;
					if (jetRefPt[nJet] >0)  {   // Find the collisional subid of this gen jet!!
						for ( int igen=0; igen < genJetTree->ngen ; igen++) {
							if ( jetRefPt[nJet] == genJetTree->genpt[igen] )
								jetSubid[nJet] = genJetTree->gensubid[igen] ;
						}

						if ( jetSubid[nJet] == -9999 ) // No genJet matched!
							cout << " WARNING!  This reco jet was not matched to anyone in the gen jet collection!!! " << endl;

					}
				}

				nJet++ ;
			}// ij for loop
		}// iSmear for loop


		//////// Leading jet kinematics in dphi>7pi/8
		float maxJpt = 0;
		int jetLeadingIndex = -1;

		for (int ij=0; ij< nJet ; ij++) {
			if ( jetDphi[ij] < awayRange )  // const float awayRange= PI * 7./8.;
			continue;
			if ( fabs( jetEta[ij] ) > cutjetEta )  // double cutjetEta = 1.6;
			continue;
			if ( jetPt[ij] > maxJpt) {
				maxJpt = jetPt[ij] ;
				jetLeadingIndex = ij;
			}
		}
		if ( jetLeadingIndex > -1 ) {
			gj.lJetPt = jetPt[jetLeadingIndex];
			gj.lJetEta = jetEta[jetLeadingIndex];
			gj.lJetPhi = jetPhi[jetLeadingIndex];
			gj.lJetDphi =  jetDphi[jetLeadingIndex];
			gj.lJetSubid=  jetSubid[jetLeadingIndex];
		}
		else {
			gj.lJetPt = -1;
			gj.lJetEta = 999;
			gj.lJetPhi = 999;
			gj.lJetDphi = 0;
			gj.lJetSubid=  -99;
		}


		int nMixing = nMixing1;
		nMjet = 0;
		bool noSuchEvent = false;
		int iMix=0;
		int loopCounter=0;

		if ( !doMix )
			iMix = nMixing+1;   // Mixing step will be skipped

		while (iMix<nMixing)  {
			loopCounter++;
			if ( loopCounter > nMB[cBin][vzBin]+1) {
				iMix = 999999 ;
				noSuchEvent = true;
				cout << " no such event!! :  icent = " << cBin << ",  vzBin = " << vzBin << ",  pBin = " << evt.pBin << endl;
				continue;
			}

			mbItr[cBin][vzBin] = mbItr[cBin][vzBin] + 1;
			if ( mbItr[cBin][vzBin] == nMB[cBin][vzBin] )
				mbItr[cBin][vzBin] =  mbItr[cBin][vzBin] - nMB[cBin][vzBin];

			/// Load the minbias tracks!!
			tjmb[cBin][vzBin]->GetEntry(mbItr[cBin][vzBin]);



			// ok found the event!! ///////////
			loopCounter =0;  // Re-initiate loopCounter
			// Jet mixing
			for (int it = 0 ; it < nJetImb ; it++) {
				if ( gj.photonEt < 0 )  continue;
				// Smear phi
				Double_t newPhi = jetPhiImb[it];
				if( smearingCentBin != -1 )
				{
					Double_t phiSmear  = TMath::Sqrt((cphi_pbpb[smearingCentBin]*cphi_pbpb[smearingCentBin] - cphi_pp*cphi_pp)
							+ (sphi_pbpb[smearingCentBin]*sphi_pbpb[smearingCentBin] - sphi_pp*sphi_pp)/jetPtImb[it]
							+ (nphi_pbpb[smearingCentBin]*nphi_pbpb[smearingCentBin] - nphi_pp*nphi_pp)/(jetPtImb[it]*jetPtImb[it]));
					newPhi  =  jetPhiImb[it] +   rand.Gaus(0, phiSmear);
					while ( fabs(newPhi) > PI )  {
						if ( newPhi > PI )  newPhi = newPhi - 2*PI;
						if ( newPhi < -PI )  newPhi = newPhi + 2*PI;
					}
				}
				jetPhiImb[it] = newPhi;


				// smear the jet pT
				//float smeared = jetPtImb[it] * rand.Gaus(1,addJetEnergyRes/jetPtImb[it]) *  rand.Gaus(1, addFlatJetEnergyRes) ;
				Double_t smeared = jetPtImb[it] *  rand.Gaus(1, addFlatJetEnergyRes);
				if( smearingCentBin != -1 )
				{
					Double_t smearSigma = TMath::Sqrt((c_pbpb[smearingCentBin]*c_pbpb[smearingCentBin] - c_pp*c_pp)
							+ (s_pbpb[smearingCentBin]*s_pbpb[smearingCentBin] - s_pp*s_pp)/jetPtImb[it]
							+ (n_pbpb[smearingCentBin]*n_pbpb[smearingCentBin] - n_pp*n_pp)/(jetPtImb[it]*jetPtImb[it]));
					smeared = jetPtImb[it] * rand.Gaus(1, smearSigma);
				}
				float resCorrection =1. ;
				float l2l3Corr =1 ;

				if  (doJetResCorrection)   {
					// L2L3
					if ( colli == kPPDATA)   {
						l2l3Corr = c_etapp->GetBinContent(c_etapp->FindBin(jetEtaImb[it])) * fptpp->Eval( jetPtImb[it]);
					}
					else if ( colli == kPADATA)   {
						if ( evt.run > 211256 )
							l2l3Corr = c_etapA->GetBinContent(c_etapA->FindBin(jetEtaImb[it]))  * fptpA->Eval( jetPtImb[it]);
						else
							l2l3Corr = c_etaAp->GetBinContent(c_etaAp->FindBin(jetEtaImb[it]))  * fptAp->Eval( jetPtImb[it]);
					}
					else if ( colli == kPAMC)
						l2l3Corr = 1 + (fsmear_pA->Eval( jetPtImb[it] )) * fgaus->GetRandom()  ;

					// Correction from MC closure
					if ((colli==kHIDATA)||(colli==kHIMC))  { // do the residual correction
						if ( evt.cBin  < 12 )   // central
							resCorrection  =  1.04503 -1.6122  /(sqrt(jetPtImb[it])) + 9.27212 / (jetPtImb[it]);  //1.04503    -1.6122    9.27212
						else                  // peripheral
							resCorrection  =  1.00596 -0.653191/(sqrt(jetPtImb[it])) + 4.35373 / (jetPtImb[it]);  //1.00596     -0.653191  4.35373
					}
					else if ((colli==kPPDATA)||(colli==kPPMC)){  // do the residual correction
						resCorrection  = 0.993609  +0.158418/(sqrt(jetPtImb[it])) + 0.335479 / (jetPtImb[it]);//          0.993609   0.158418   0.335479
					}
					else if ((colli==kPADATA)||(colli==kPAMC)){
						resCorrection = 0.997738 + 0.0221806/(sqrt(jetPtImb[it])) - 0.877999 / (jetPtImb[it]); //C : 0.997738, S : 0.0221806, N : -0.877999 //function derived as a function of gen pt
						//resCorrection = 0.981365 + 0.342746/(sqrt(jetPtImb[it])) - 2.63018 / (jetPtImb[it]); //C : 0.981365, S : 0.342746, N : -2.63018 //function derived as a function of gen pt//derived from l2l3 corrected sample.
						//resCorrection = 0.745753 + 6.91646/(sqrt(jetPtImb[it])) - 33.0167 / (jetPtImb[it]); //C : 0.745753, S : 6.91646, N : -33.0167//function derived as a function of reco pt
					}

				}


				float smearedCorrected  = smeared *l2l3Corr / resCorrection *jetEnergyScale; // residual correction

				if ( smearedCorrected < cutjetPtSkim )  // double cutjetPtSkim = 15; Oct 19th
					continue;
				if ( fabs( jetEtaImb[it] ) > cutjetEtaSkim )   // double cutjetEtaSkim = 3.0; Oct 19th
					continue;
				if ( getDR( jetEtaImb[it], jetPhiImb[it], gj.photonEta, gj.photonPhi) < 0.5 )  // This cut added for consistency ; Oct 19th
					continue;

				mJetPt[nMjet]    = smearedCorrected;
				mJetEta[nMjet]   = jetEtaImb[it];
				mJetPhi[nMjet]   = jetPhiImb[it];
				if  ( mJetPt[nMjet]>0 )
					mJetDphi[nMjet]  =   getAbsDphi(mJetPhi[nMjet], gj.photonPhi) ;
				else
					mJetDphi[nMjet]=-1;

				nMjet++; // < == Important!
			}

			iMix++;
		}
		if ( noSuchEvent )
			continue;

		tgj->Fill();
		newtreeJet->Fill();
		tmixJet->Fill();
		newtreePhoton->Fill();
		treeFullJet->Fill();
		if (   (colli==kHIMC ) || (colli==kPPMC) || (colli==kPAMC) )
			treeGenp->Fill();
	}

	newfile_data->Write();
	//   newfile_data->Close();   // <<=== If there is close() function. writing stucks in the middle of looping.. I don't know why!!
	cout << " Done! "<< endl;
	cout << "    " << eSel<<" out of total "<<eTot<<" events were analyzed."<<endl;
	cout << "Duplicate events  = " << duplicateEvents << endl;
}
Пример #11
0
/*#include "TTree.h"
#include "TCanvas.h"
#include "TGraph.h"
#include "TMultiGraph.h"
#include "TRint.h"
#include <time.h>
#include <stdio.h>

const short MaxNN = 6;
*/
void make_scatterplot(TString data_file, TString plot_name, TString header)
{
	//TApplication program = new TRInt(); 
	//pull in data
	TTree *t = new TTree(); 
	t->ReadFile(data_file);
	t->SetName("t");
	
	//TString name = "run2.png";
	TCanvas *BG = new TCanvas("c1", "Read Velocity on Local Disk for CMS3 Files", 1920, 1080);
	BG->cd();
	TPad *c = new TPad("MainPad", "My main pad", 0, 0, 1, 0.9);
	c->Draw();
	c->Divide(2,2);

	//In first slot have Time vs. Buffer for 1 Concurrent Read
	c->cd(1);
	int n1 = t->Draw("VelocityMBps:BufferSize", "ConcurrentReads==1", "goff");
	TGraph *ghist1 = new TGraph(n1, t->GetV2(), t->GetV1());
	ghist1->SetName("ghist1");
	ghist1->SetMarkerStyle(3);
	ghist1->SetMarkerColor(1);
	ghist1->SetTitle("Single File Read");
	ghist1->GetXaxis()->SetTitle("Buffer Size (Bytes)");
	ghist1->GetYaxis()->SetTitle("Read Velocity (MB/s)");
	ghist1->Draw("ap");
	
	//In second slot have Time vs. Buffer for 3 Concurrent Reads
	c->cd(2);
	int n2 = t->Draw("VelocityMBps:BufferSize", "ConcurrentReads==3", "goff");
	TGraph *ghist2 = new TGraph(n2, t->GetV2(), t->GetV1());
	Double_t DP2x[n2], DP2y[n2];
	ghist2->SetName("ghist2");
	ghist2->SetMarkerStyle(3);
	ghist2->SetMarkerColor(1);
	ghist2->SetTitle("3 Concurrent Reads");
	ghist2->GetXaxis()->SetTitle("Buffer Size (Bytes)");
	ghist2->GetYaxis()->SetTitle("Read Velocity (MB/s)");
	ghist2->Draw("ap");
	
	//In third slot have Time vs. Buffer for 3 Concurrent Reads
	c->cd(3);
	int n3 = t->Draw("VelocityMBps:BufferSize", "ConcurrentReads==6", "goff");
	TGraph *ghist3 = new TGraph(n3, t->GetV2(), t->GetV1());
	Double_t DP3x[n3], DP3y[n3];
	ghist3->SetName("ghist3");
	ghist3->SetMarkerStyle(3);
	ghist3->SetMarkerColor(1);
	ghist3->SetTitle("6 Concurrent Reads");
	ghist3->GetXaxis()->SetTitle("Buffer Size (Bytes)");
	ghist3->GetYaxis()->SetTitle("Read Velocity (MB/s)");
	ghist3->Draw("ap");
	
	//In fourth slot have Time vs. Buffer for 10 Concurrent Reads
	c->cd(4);
	int n4 = t->Draw("VelocityMBps:BufferSize", "ConcurrentReads==10", "goff");
	TGraph *ghist4 = new TGraph(n4, t->GetV2(), t->GetV1());
	ghist4->SetMarkerStyle(3);
	ghist4->SetName("ghist4");
	ghist4->SetMarkerColor(1);
	ghist4->SetTitle("10 Concurrent Reads");
	ghist4->GetXaxis()->SetTitle("Buffer Size (Bytes)");
	ghist4->GetYaxis()->SetTitle("Read Velocity (MB/s)");
	ghist4->Draw("ap");
	
	//Draw to screen
	//Initialize Canvas
	
	c->cd(0);
	c->Draw();
	
	BG->cd();
	TText *title = new TText(.5,.95, header);
	title->SetTextAlign(22);
	title->Draw();
	
	gDirectory->Add(ghist1);
	gDirectory->Add(ghist2);
	gDirectory->Add(ghist3);
	gDirectory->Add(ghist4);
	gDirectory->Add(t);
	gPad->SaveAs(plot_name);
}
Пример #12
0
//std::mutex mtx;
void ProcessFilePar(TString fileIn, TString fileOut, TString treename,  vector<TString> friends, vector<TString> branches, vector<TString> newbranches, unsigned jobid = 0, unsigned NPAR = 1)
{
  //mtx.lock(); //for threads
  TFile *fin = new TFile(fileIn);
  TTree *tjet = (TTree*)fin->Get(treename);
  //mtx.unlock();

  vector<TTree *> friendTrees;
  vector<bool> sameFileFriend;
  for (auto f:friends) {
    auto fr = tokenize(f,":");
    if (fr.size()==1) {tjet->AddFriend(fr[0]); sameFileFriend.push_back(true);}
    else if (fr.size()==2) {tjet->AddFriend(fr[1],fr[0]); sameFileFriend.push_back(false);}

    TTree *tfriend = (TTree*)fin->Get(f);
    friendTrees.push_back(tfriend);
  }

  AddBranchesByCounter(tjet, branches);
  for (unsigned i=0;i<friendTrees.size();i++) AddBranchesByCounter(friendTrees[i],branches);

  //sort branches into categories
  for (auto bName:branches) {
    TBranch *b=tjet->GetBranch(bName);
    if (b==0) cout <<"Branch "<<bName<<" doesn't exist!"<<endl;

    //parse in case there is a tree name in the branch
    auto branchtoken = tokenize(bName,".");
    auto leafname = branchtoken[branchtoken.size()-1];

    TObjArray *bl = b->GetListOfLeaves();
    if (bl->GetEntries()>1)
      cout <<" Branch "<<b->GetTitle()<<" has more than 1 leave. Taking first..."<<endl;
    if (bl->GetEntries()==0) {
      cout <<" Branch "<<b->GetTitle()<<" has no leaves! Skipping..."<<endl;
      continue;
    }

    TLeaf * l = (TLeaf *)(*bl)[0];
    //what's the type?
    TString type = l->GetTypeName();
    if (VERBOSE) cout<<l->GetTitle()<<endl;

    //array?
    bool array = l->GetLeafCount()!=0;
    TString counter;
    if (array) counter = l->GetLeafCount()->GetBranch()->GetName();

    if (type=="Float_t")
      {  if (array) {brVFloat.push_back(bName); brVFloatCounter.push_back(counter); }else brFloat.push_back(bName);}
    else if (type=="Int_t")
      {  if (array) {brVInt.push_back(bName); brVIntCounter.push_back(counter); }else brInt.push_back(bName);}
    else cout << "Unsupported branch type "<<type<<" for branch "<<bName<<". Skipping..."<<endl;
  }


  //treat counters as ints only
  AppendToListUniquely(brVIntCounter, brInt);
  AppendToListUniquely(brVFloatCounter, brInt);

  //too keep track of old branches, which cannot be read (todo: just check it...)
  int noldbrInt = brInt.size(), noldbrFloat = brFloat.size(), noldbrVInt = brVInt.size(), noldbrVIntCounter = brVIntCounter.size(), noldbrVFloat = brVFloat.size(), noldbrVFloatCounter = brVFloatCounter.size();
  //add new branches
  ParseNewBranches(newbranches, brInt, brFloat, brVInt, brVIntCounter, brVFloat, brVFloatCounter);

  //print for debugging
  if (VERBOSE) {
    cout<<"int       : "; for (auto s:brInt) cout <<s<<", "; cout<<endl;
    cout<<"float     : "; for (auto s:brFloat) cout <<s<<", "; cout<<endl;
    cout<<"Vint      : "; for (auto s:brVInt) cout <<s<<", "; cout<<endl;
    cout<<"Vfloat    : "; for (auto s:brVFloat) cout <<s<<", "; cout<<endl;
    cout<<"Vintcnt   : "; for (auto s:brVIntCounter) cout <<s<<", "; cout<<endl;
    cout<<"Vfloatcnt : "; for (auto s:brVFloatCounter) cout <<s<<", "; cout<<endl;
  }

  tjet->SetBranchStatus("*",1);
  for (auto b:brVFloat) if (tjet->GetBranch(b)!=0) tjet->SetBranchStatus(b,0);
  for (auto b:brFloat)  if (tjet->GetBranch(b)!=0) tjet->SetBranchStatus(b,0);
  for (auto b:brVInt)   if (tjet->GetBranch(b)!=0) tjet->SetBranchStatus(b,0);
  for (auto b:brInt)    if (tjet->GetBranch(b)!=0) {unsigned f=0; tjet->SetBranchStatus(b,0,&f); if (VERBOSE) cout<<"turning off "<<b<<", found = "<<f<<endl;}


  TFile *fout = new TFile(fileOut,"recreate");
  TTree *tjetout;


  //in case of one-to-many event - do not copy branches automatically!
  if (useOneToOne) tjetout = tjet->CloneTree(0);
  else tjetout = new TTree(tjet->GetName(),tjet->GetTitle());


  //think about memory tree
  // tjetout->SetDirectory(0);
  tjetout->SetName(tjet->GetName());
  //TTree *tjetout = new TTree("t","t");

  //to see what is copied...
  //tjetout->Print();

  for (auto b:brVFloat) if (tjet->GetBranch(b)!=0) tjet->SetBranchStatus(b,1);
  for (auto b:brFloat)  if (tjet->GetBranch(b)!=0) tjet->SetBranchStatus(b,1);
  for (auto b:brVInt)   if (tjet->GetBranch(b)!=0) tjet->SetBranchStatus(b,1);
  for (auto b:brInt)    if (tjet->GetBranch(b)!=0) tjet->SetBranchStatus(b,1);

  vector<int> valIntIn(brInt.size()), valIntOut(brInt.size());
  vector<float> valFloatIn(brFloat.size()), valFloatOut(brFloat.size());
  vector<vector<int> >valVIntIn (brVInt.size());  vector<vector<int> >valVIntOut (brVInt.size());
  vector<vector<float> >valVFloatIn (brVFloat.size());  vector<vector<float> >valVFloatOut (brVFloat.size());

  for (unsigned i=0;i<brInt.size();i++) {
    if (tjet->GetBranch(brInt[i])!=0)
      tjet->SetBranchAddress(brInt[i],&valIntIn[i]);

    if (tjetout->GetBranch(brInt[i])!=0) {//why would it?
      tjetout->SetBranchAddress(brInt[i],&valIntOut[i]); 
      cout<<"branch "<<brInt[i]<<" already exist for some reason..."<<endl; 
    }
    else //logical...
      if (NonFriendBranch(tjet, brInt[i])) 
	tjetout->Branch(brInt[i],&valIntOut[i],Form("%s/I",brInt[i].Data()));
  }

  for (unsigned i=0;i<brFloat.size();i++) {
    if (tjet->GetBranch(brFloat[i])!=0) 
      tjet->SetBranchAddress(brFloat[i],&valFloatIn[i]);
    
    if (NonFriendBranch(tjet, brFloat[i]))
      tjetout->Branch(brFloat[i],&valFloatOut[i],Form("%s/F",brFloat[i].Data()));
  }

  for (unsigned i=0;i<brVFloat.size();i++) {
    if (tjet->GetBranch(brVFloat[i])!=0) {
      valVFloatIn[i] = vector<float>(NMAX);
      tjet->SetBranchAddress(brVFloat[i],&valVFloatIn[i][0]);
    }
    

    valVFloatOut[i] = vector<float>(NMAX);
    if (NonFriendBranch(tjet, brVFloat[i]))
      tjetout->Branch(brVFloat[i],&valVFloatOut[i][0],Form("%s[%s]/F",brVFloat[i].Data(),brVFloatCounter[i].Data()));
  }

  for (unsigned i=0;i<brVInt.size();i++) {
    if (tjet->GetBranch(brVInt[i])) {
      valVIntIn[i] = vector<int>(NMAX);
      tjet->SetBranchAddress(brVInt[i],&valVIntIn[i][0]);
    }
    valVIntOut[i] = vector<int>(NMAX);
    if (NonFriendBranch(tjet, brVInt[i]))
      tjetout->Branch(brVInt[i],&valVIntOut[i][0],Form("%s[%s]/I",brVInt[i].Data(),brVIntCounter[i].Data()));
  }

  Long64_t nentries = tjet->GetEntries();
  int nentries1 = nentries/NPAR*jobid;
  int nentries2 = nentries/NPAR*(jobid+1);
  
  nentries = nentries2-nentries1; 
  int oneperc = nentries/100; if (oneperc==0) oneperc = 1;

  cout<<"Start processing..."<<endl;
  TStopwatch s;
  s.Start();
  TTimeStamp t0;
  double readTime = 0, processingTime = 0, copyToTime = 0, cloneTime=0, copyFromTime=0, fillTime = 0;
  

  for (Long64_t i=0; i<nentries;i++) {
    if (jobid==0 && i % oneperc == 0 && i>0) {
      std::cout << std::fixed;
      TTimeStamp t1; cout<<" \r"<<i/oneperc<<"%   "<<" est. time "<<setprecision(2) <<(t1-t0)*nentries/(i+.1)<<" s ";
      cout<<";Processing:"<<setprecision(2)<<processingTime/(t1-t0)*100<<" %";
      cout<<";Copy1:"<<setprecision(2) <<copyToTime/(t1-t0)*100<<" %";
      cout<<";Clone:"<<setprecision(2) <<cloneTime/(t1-t0)*100<<" %";
      cout<<";Copy2:"<<setprecision(2) <<copyFromTime/(t1-t0)*100<<" %";
      cout<<";Fill:"<<setprecision(2) <<fillTime/(t1-t0)*100<<" %";
      cout<<";Read:"<<setprecision(2) <<readTime/(t1-t0)*100<<" %";
      cout<<flush; 
    }
    
    TTimeStamp tsRead0;
    tjet->GetEntry(i+nentries1);
    TTimeStamp tsRead1;
    readTime+=tsRead1-tsRead0;

    Everything ev;
    TTimeStamp tsCpTo0;
    for (unsigned j=0;j<brInt.size();j++) ev.PutInt(brInt[j],valIntIn[j]);
    for (unsigned j=0;j<brFloat.size();j++) ev.PutFloat(brFloat[j],valFloatIn[j]);
    for (unsigned j=0;j<brVFloat.size();j++) ev.PutVFloat(brVFloat[j],brVFloatCounter[j],valVFloatIn[j]);
    for (unsigned j=0;j<brVInt.size();j++) ev.PutVInt(brVInt[j],brVIntCounter[j],valVIntIn[j]);
    TTimeStamp tsCpTo1;
    copyToTime+=tsCpTo1-tsCpTo0;
    

    TTimeStamp tsCl0;
    //think about: copy object (timing 10% ->3%) 
    //but it copies vectors, so push_back will add in the end...
    //    Everything evout = ev;
    //or even reference(in place?) (->0.2%)
    //Everything &evout = ev;
    Everything evout = ev.CloneStructure();
    TTimeStamp tsCl1;
    cloneTime+=tsCl1-tsCl0;

    bool exitEvent = false;
    int counter = 0;

    while (!exitEvent) {
    
    TTimeStamp tsPr0;
    if (useOneToOne) {
      fProcessOneToOne(ev, evout);
      evout.UpdateCounters();
      exitEvent = true;
    } else {
      exitEvent = fProcessOneToMany(ev, evout, counter); 
      //      if (!exitEvent) cout<<"event to write "<<counter<<endl;
      counter++;
    }

    TTimeStamp tsPr1;  
    processingTime+=tsPr1-tsPr0;
    
    
    //Everything evout = ev;
    TTimeStamp tsCpFrom0;
    for (unsigned j=0;j<brInt.size();j++) valIntOut[j] = evout.GetInt(brInt[j]);
    for (unsigned j=0;j<brFloat.size();j++) {valFloatOut[j] = evout.GetFloat(brFloat[j]); 
      //  cout<<brFloat[j]<<" "<<evout.GetFloat(brFloat[j])<<endl;
    }
    for (unsigned j=0;j<brVFloat.size();j++) valVFloatOut[j] = evout[brVFloat[j]];
    for (unsigned j=0;j<brVInt.size();j++) valVIntOut[j] = evout.GetVInt(brVInt[j]);
    TTimeStamp tsCpFrom1;
    copyFromTime+=tsCpFrom1-tsCpFrom0;

    TTimeStamp tsFill0;
    tjetout->Fill();
    TTimeStamp tsFill1;
    fillTime+=tsFill1-tsFill0;
  }

  }
  cout<<endl;
  s.Stop();
  cout<<"Done in ";s.Print();
  
  tjetout->FlushBaskets();
  tjetout->Write();
  
  cout<<"Copying other trees..."<<endl;

  for (unsigned i=0;i<friendTrees.size();i++) {
    TTree *t = friendTrees[i];
    if (sameFileFriend[i]) {
      //TTree *triendout = t->CloneTree(-1,"fast");
      TTree *triendout = t->CopyTree("","",nentries,nentries1);
      triendout->Write();
    }
  }
  


  fout->Close();
  friendTrees.clear();
}
Пример #13
0
int merging() 
{
   Long_t NUMBER_OF_ENTRIES = 100;
   
   TTree* newResult = new TTree("xxx", "Argument");
   static Double_t x, y;
   newResult->Branch("x", &x, "x/D");
   newResult->Branch("y", &y, "y/D");
   for(Long_t i=0; i<NUMBER_OF_ENTRIES; ++i)
   {
      x = i;
      y = i*i;
      //fprintf(stderr,"res %lf %lf %d\n",x,y,i<NUMBER_OF_ENTRIES);
      newResult->Fill();
   }// end of for
   //  newResult->Scan("x:y");
   
   // ======================================
   
   TMessage message(kMESS_OBJECT);
   
   message.Reset();
   message.SetWriteMode();
   message.WriteObject(newResult);
   
   message.Reset();
   message.SetReadMode();
   TTree* readResult = 0;
   readResult = ((TTree*)message.ReadObject(message.GetClass()));
   readResult->SetName("yyy");
   
   // ======================================
   
   TTree* result = 0;
   
   result = readResult->CloneTree(0);
   result->SetName("zzz");
   result->Print();
   result->Show(19);
   readResult->Print();
   readResult->Show(29);
   
   cout<< "Result has " << result->GetEntries()<< " entries." << endl;
   
   TList newResultCollection;
   newResultCollection.SetOwner(kFALSE);
   newResultCollection.Add(readResult);
   
   cerr<<"Hello 1\n";
   
   result->Merge(&newResultCollection);
   
   cerr<<"Hello 2\n";
   
   cout<<result->GetEntries()<<endl;
   printf("result entries = %lld\n",result->GetEntries());
   
   // ======================================
   
   newResultCollection.Clear();
   delete newResult;
   delete readResult;
   
   return 0;
   
} // end of main
void dimuonSkim(const TString configFile, const TString inputFile, const TString outputFile)
{
       std::cout<<"running dimuonSkim()"   <<std::endl;
       std::cout<<"configFile  = "<< configFile.Data() <<std::endl;
       std::cout<<"inputFile   = "<< inputFile.Data() <<std::endl;
       std::cout<<"outputFile  = "<< outputFile.Data() <<std::endl;

       InputConfiguration configInput = InputConfigurationParser::Parse(configFile.Data());
       CutConfiguration configCuts = CutConfigurationParser::Parse(configFile.Data());

       if (!configInput.isValid) {
           std::cout << "Input configuration is invalid." << std::endl;
           std::cout << "exiting" << std::endl;
           return;
       }
       if (!configCuts.isValid) {
           std::cout << "Cut configuration is invalid." << std::endl;
           std::cout << "exiting" << std::endl;
           return;
       }

       // input configuration
       int collisionType = configInput.proc[INPUT::kSKIM].i[INPUT::k_collisionType];
       std::string treePath = configInput.proc[INPUT::kSKIM].s[INPUT::k_treePath];

       // set default values
       if (treePath.size() == 0)  treePath = "ggHiNtuplizer/EventTree";

       // verbose about input configuration
       std::cout<<"Input Configuration :"<<std::endl;
       std::cout << "collisionType = " << collisionType << std::endl;
       const char* collisionName =  getCollisionTypeName((COLL::TYPE)collisionType).c_str();
       std::cout << "collision = " << collisionName << std::endl;
       std::cout << "treePath = " << treePath.c_str() << std::endl;

       // cut configuration
       float cut_vz = configCuts.proc[CUTS::kSKIM].obj[CUTS::kEVENT].f[CUTS::EVT::k_vz];
       int cut_pcollisionEventSelection = configCuts.proc[CUTS::kSKIM].obj[CUTS::kEVENT].i[CUTS::EVT::k_pcollisionEventSelection];
       int cut_pPAprimaryVertexFilter = configCuts.proc[CUTS::kSKIM].obj[CUTS::kEVENT].i[CUTS::EVT::k_pPAprimaryVertexFilter];
       int cut_pBeamScrapingFilter = configCuts.proc[CUTS::kSKIM].obj[CUTS::kEVENT].i[CUTS::EVT::k_pBeamScrapingFilter];

       int cut_nMu = configCuts.proc[CUTS::kSKIM].obj[CUTS::kMUON].i[CUTS::MUO::k_nMu];

       // bool isMC = collisionIsMC((COLL::TYPE)collisionType);
       bool isHI = collisionIsHI((COLL::TYPE)collisionType);
       bool isPP = collisionIsPP((COLL::TYPE)collisionType);

       // verbose about cut configuration
       std::cout<<"Cut Configuration :"<<std::endl;
       std::cout<<"cut_vz = "<< cut_vz <<std::endl;
       if (isHI) {
           std::cout<<"cut_pcollisionEventSelection = "<< cut_pcollisionEventSelection <<std::endl;
       }
       else {   // PP
           std::cout<<"cut_pPAprimaryVertexFilter = "<< cut_pPAprimaryVertexFilter <<std::endl;
           std::cout<<"cut_pBeamScrapingFilter = "<< cut_pBeamScrapingFilter <<std::endl;
       }

       std::cout<<"cut_nMu = "<<cut_nMu<<std::endl;

       std::vector<std::string> inputFiles = InputConfigurationParser::ParseFiles(inputFile.Data());

       std::cout<<"input ROOT files : num = "<<inputFiles.size()<< std::endl;
       std::cout<<"#####"<< std::endl;
       for (std::vector<std::string>::iterator it = inputFiles.begin() ; it != inputFiles.end(); ++it) {
           std::cout<<(*it).c_str()<< std::endl;
       }
       std::cout<<"##### END #####"<< std::endl;

       TChain* treeHLT   = new TChain("hltanalysis/HltTree");
       TChain* treeggHiNtuplizer  = new TChain("ggHiNtuplizer/EventTree");
       TChain* treeHiEvt = new TChain("hiEvtAnalyzer/HiTree");
       TChain* treeSkim  = new TChain("skimanalysis/HltTree");
       TChain* treeHiForestInfo = new TChain("HiForest/HiForestInfo");

       for (std::vector<std::string>::iterator it = inputFiles.begin() ; it != inputFiles.end(); ++it) {
          treeHLT->Add((*it).c_str());
          treeggHiNtuplizer->Add((*it).c_str());
          treeHiEvt->Add((*it).c_str());
          treeSkim->Add((*it).c_str());
          treeHiForestInfo->Add((*it).c_str());
       }

       HiForestInfoController hfic(treeHiForestInfo);
       std::cout<<"### HiForestInfo Tree ###"<< std::endl;
       hfic.printHiForestInfo();
       std::cout<<"###"<< std::endl;

       treeHLT->SetBranchStatus("*",0);     // disable all branches
       treeHLT->SetBranchStatus("HLT_HI*SinglePhoton*Eta*",1);     // enable photon branches
       treeHLT->SetBranchStatus("HLT_HI*DoublePhoton*Eta*",1);     // enable photon branches
       treeHLT->SetBranchStatus("*DoubleMu*",1);                      // enable muon branches
       treeHLT->SetBranchStatus("HLT_HIL1Mu*",1);                     // enable muon branches
       treeHLT->SetBranchStatus("HLT_HIL2Mu*",1);                     // enable muon branches
       treeHLT->SetBranchStatus("HLT_HIL3Mu*",1);                     // enable muon branches
       
       // specify explicitly which branches to store, do not use wildcard
       treeHiEvt->SetBranchStatus("*",1);

       // specify explicitly which branches to store, do not use wildcard
       treeSkim->SetBranchStatus("*",0);

       Int_t pcollisionEventSelection;  // this filter is used for HI.
       if (isHI) {
           treeSkim->SetBranchStatus("pcollisionEventSelection",1);
           if (treeSkim->GetBranch("pcollisionEventSelection")) {
               treeSkim->SetBranchAddress("pcollisionEventSelection",&pcollisionEventSelection);
           }
           else {   // overwrite to default
               pcollisionEventSelection = 1;
               std::cout<<"could not get branch : pcollisionEventSelection"<<std::endl;
               std::cout<<"set to default value : pcollisionEventSelection = "<<pcollisionEventSelection<<std::endl;
           }
       }
       else {
           pcollisionEventSelection = 0;    // default value if the collision is not HI, will not be used anyway.
       }
       Int_t pPAprimaryVertexFilter;    // this filter is used for PP.
       if (isPP) {
           treeSkim->SetBranchStatus("pPAprimaryVertexFilter",1);
           if (treeSkim->GetBranch("pPAprimaryVertexFilter")) {
               treeSkim->SetBranchAddress("pPAprimaryVertexFilter",&pPAprimaryVertexFilter);
           }
           else {   // overwrite to default
               pPAprimaryVertexFilter = 1;
               std::cout<<"could not get branch : pPAprimaryVertexFilter"<<std::endl;
               std::cout<<"set to default value : pPAprimaryVertexFilter = "<<pPAprimaryVertexFilter<<std::endl;
           }
       }
       else {
           pPAprimaryVertexFilter = 0;      // default value if the collision is not PP, will not be used anyway.
       }
       Int_t pBeamScrapingFilter;   // this filter is used for PP.
       if (isPP) {
           treeSkim->SetBranchStatus("pBeamScrapingFilter",1);
           if (treeSkim->GetBranch("pBeamScrapingFilter")) {
               treeSkim->SetBranchAddress("pBeamScrapingFilter",&pBeamScrapingFilter);
           }
           else {   // overwrite to default
               pBeamScrapingFilter = 1;
               std::cout<<"could not get branch : pBeamScrapingFilter"<<std::endl;
               std::cout<<"set to default value : pBeamScrapingFilter = "<<pBeamScrapingFilter<<std::endl;
           }
       }
       else {
           pBeamScrapingFilter = 0;     // default value if the collision is not PP, will not be used anyway.
       }

       ggHiNtuplizer ggHi;
       ggHi.setupTreeForReading(treeggHiNtuplizer);
       
       hiEvt hiEvt;
       hiEvt.setupTreeForReading(treeHiEvt);

       TFile* output = new TFile(outputFile,"RECREATE");
       TTree *configTree = setupConfigurationTreeForWriting(configCuts);

       // output tree variables
       TTree *outputTreeHLT           = treeHLT->CloneTree(0);
       outputTreeHLT->SetName("hltTree");
       outputTreeHLT->SetTitle("subbranches of hltanalysis/HltTree");
       TTree *outputTreeggHiNtuplizer = treeggHiNtuplizer->CloneTree(0);
       TTree *outputTreeHiEvt = treeHiEvt->CloneTree(0);
       outputTreeHiEvt->SetName("HiEvt");
       outputTreeHiEvt->SetTitle("subbranches of hiEvtAnalyzer/HiTree");
       TTree* outputTreeSkim  = treeSkim->CloneTree(0);
       outputTreeSkim->SetName("skim");
       outputTreeSkim->SetTitle("subbranches of skimanalysis/HltTree");
       TTree* outputTreeHiForestInfo = treeHiForestInfo->CloneTree(0);
       outputTreeHiForestInfo->SetName("HiForestInfo");
       outputTreeHiForestInfo->SetTitle("first entry of HiForest/HiForestInfo");
       
       outputTreeHLT->SetMaxTreeSize(MAXTREESIZE);
       outputTreeggHiNtuplizer->SetMaxTreeSize(MAXTREESIZE);
       outputTreeHiEvt->SetMaxTreeSize(MAXTREESIZE);
       outputTreeHiForestInfo->SetMaxTreeSize(MAXTREESIZE);

       // write HiForestInfo
       treeHiForestInfo->GetEntry(0);
       outputTreeHiForestInfo->Fill();

       TTree *diMuonTree = new TTree("dimuon","muon pairs");
       diMuonTree->SetMaxTreeSize(MAXTREESIZE);

       dimuon diMu;
       diMu.branchDiMuonTree(diMuonTree);

       EventMatcher* em = new EventMatcher();
       Long64_t duplicateEntries = 0;

       Long64_t entries = treeggHiNtuplizer->GetEntries();
       Long64_t entriesPassedEventSelection = 0;
       Long64_t entriesAnalyzed = 0;
       std::cout << "entries = " << entries << std::endl;
       std::cout<< "Loop : " << treePath.c_str() <<std::endl;
       for (Long64_t j_entry=0; j_entry<entries; ++j_entry)
       {
           if (j_entry % 20000 == 0)  {
             std::cout << "current entry = " <<j_entry<<" out of "<<entries<<" : "<<std::setprecision(2)<<(double)j_entry/entries*100<<" %"<<std::endl;
           }

           treeHLT->GetEntry(j_entry);
           treeggHiNtuplizer->GetEntry(j_entry);
           treeHiEvt->GetEntry(j_entry);
           treeSkim->GetEntry(j_entry);

           bool eventAdded = em->addEvent(ggHi.run,ggHi.lumis,ggHi.event,j_entry);
           if(!eventAdded) // this event is duplicate, skip this one.
           {
               duplicateEntries++;
               continue;
           }

           // event selection
           if (!(TMath::Abs(hiEvt.vz) < cut_vz))  continue;
           if (isHI) {
               if ((pcollisionEventSelection < cut_pcollisionEventSelection))  continue;
           }
           else {
               if (pPAprimaryVertexFilter < cut_pPAprimaryVertexFilter || pBeamScrapingFilter < cut_pBeamScrapingFilter)  continue;
           }
           entriesPassedEventSelection++;

           // skip if there are no muon pairs to study
           if(ggHi.nMu < cut_nMu)  continue;
           entriesAnalyzed++;

           diMu.makeDiMuonPairs(ggHi);

           outputTreeHLT->Fill();
           outputTreeggHiNtuplizer->Fill();
           outputTreeHiEvt->Fill();
           outputTreeSkim->Fill();
           diMuonTree->Fill();
       }
       std::cout<< "Loop ENDED : " << treePath.c_str() <<std::endl;
       std::cout << "entries            = " << entries << std::endl;
       std::cout << "duplicateEntries   = " << duplicateEntries << std::endl;
       std::cout << "entriesPassedEventSelection   = " << entriesPassedEventSelection << std::endl;
       std::cout << "entriesAnalyzed    = " << entriesAnalyzed << std::endl;
       std::cout << "outputTreeHLT->GetEntries()           = " << outputTreeHLT->GetEntries() << std::endl;
       std::cout << "outputTreeggHiNtuplizer->GetEntries() = " << outputTreeggHiNtuplizer->GetEntries() << std::endl;
       std::cout << "outputTreeHiEvt->GetEntries() = " << outputTreeHiEvt->GetEntries() << std::endl;
       std::cout << "outputTreeSkim->GetEntries()  = " << outputTreeSkim->GetEntries() << std::endl;
       std::cout << "diMuonTree->GetEntries()          = " << diMuonTree->GetEntries() << std::endl;

       // overwrite existing trees
       outputTreeHLT->Write("", TObject::kOverwrite);
       outputTreeggHiNtuplizer->Write("", TObject::kOverwrite);
       outputTreeHiEvt->Write("", TObject::kOverwrite);
       diMuonTree->Write("", TObject::kOverwrite);

       configTree->Write("", TObject::kOverwrite);

       output->Write("", TObject::kOverwrite);
       output->Close();

       std::cout<<"dimuonSkim() - END"   <<std::endl;
}
Пример #15
0
TTree * TreeReader::CopyTree(TCut cut, double frac, string name)
{
	if(!init)
	{
	        cout << "*** WARNING: tree " << fChain->GetName() << " not initialized" << endl;
		return NULL;
	}

	if (cut == "1") cut = "";

	if (pmode == "v") cout << endl << "CopyTree" << endl;

	Long64_t nTot = fChain->GetEntries();

	if (pmode == "v") cout << "N Tot = " << nTot << endl;

	if ((nTot != 0) && (frac != 0.) && (cut != ""))
	{
		if (pmode == "v") 
		{
			cout << "TCut " << endl;
			cut.Print();
		}
		/*
		Long64_t nPas = fChain->GetEntries(cut);
		
		if (pmode == "v") cout << "N Pas = "******" (" << (double) nPas / (double) nTot * 100 << "%)" << endl;

		if (nTot == nPas) cut = "";
		*/
	}

	if (frac == -1)
	{
	       if (cut == "")
	       {
		        cout << "Frac  = " << frac << endl;
			if (name != "") fChain->SetName(name.c_str());
		        return (TTree*) fChain;
	       }
	}

	Long64_t nTot_ = nTot;
	if (frac == 0)
	{
		cut == "";
		nTot = 0;
	}
	if ((frac > 0) && (frac < 1))    nTot *= frac;
	if ((frac > 1) && (frac < nTot)) nTot = frac;

	if (pmode == "v")
	{
		if (frac != 0)
		{
		       cout << "Frac  = " << frac << endl;
		       if (frac >= 0) cout << "Copying entries..." << endl;
		}
		else cout << "Cloning tree structure..." << endl;
	}

	TTree *tTree = NULL;
	if (cut == "") tTree = (TTree*) fChain->CloneTree(nTot);
	else           tTree = (TTree*) fChain->CopyTree(cut, "", nTot);

	if (name != "") tTree->SetName(name.c_str());

	if (nTot != 0) if (pmode == "v")
			 {
			       Long64_t nPas = tTree->GetEntries();
			       cout << "N Pas = "******" (" << (double) nPas / (double) nTot_ * 100 << "%)" << endl;
			       cout << endl;
			 }

	return tTree;

}
Пример #16
0
void drawPhotonSpec(){
  


  TH1::SetDefaultSumw2();
  
  TFile* f1 = new TFile("/mnt/hadoop/cms/store/user/luck/2014-photon-forests/pPb_DATA_photon30trig_localJEC_v1.root");
  TTree* photon = (TTree*)f1->Get("multiPhotonAnalyzer/photon");
  TTree* hlt    = (TTree*)f1->Get("hltanalysis/HltTree");
  hlt->SetName("hlt");
  photon->AddFriend(hlt);
  
  TH1D* h1 = new TH1D("h1",";p_{T} of photon;Entries (Arb. Norm.)",200,0,200);
  // TCut ccut = "abs(eta)<1.44 && hlt.HLT_PAPhoton20_NoCaloIdVL_v1 && hadronicOverEm<0.1";
  TCut ccut = "abs(eta)<1.44 && hadronicOverEm<0.1";
  photon->Draw("pt>>h1",ccut);
  TH1D* h2 = (TH1D*)h1->Clone("h2");
  photon->Draw("pt>>h2",ccut && "!isEle");

  TCut isocut = "sigmaIetaIeta<0.011 && ecalRecHitSumEtConeDR04<4.2 && hcalTowerSumEtConeDR04< 2.2 && trkSumPtHollowConeDR04 <2";

  TH1D* h3 = (TH1D*)h1->Clone("h3");
  photon->Draw("pt>>h3",ccut && isocut);
  
  TH1D* h4 = (TH1D*)h1->Clone("h4");
  photon->Draw("pt>>h4",ccut && isocut && "!isEle");

  
  handsomeTH1(h1,1);
  handsomeTH1(h2,2);
  handsomeTH1(h3,1);
  handsomeTH1(h4,2);
  

  TCanvas* c1 = new TCanvas("c1","",1000,500);
  c1->Divide(2,1);
  c1->cd(1);
  //h1->SetAxisRange(0.5, 80000,"Y");
  h1->Draw("hist" );
  h2->Draw("same hist");

  TLegend *l1 = new TLegend(0.6365615,0.6445304,0.9577623,0.846736,NULL,"brNDC");
  easyLeg(l1,"5.02TeV pA Data");
  l1->SetTextFont(43);
  l1->SetTextSize(16);
  l1->Draw();
  TLegend *l2 = new TLegend(0.6365615,0.4445304,0.9577623,0.646736,NULL,"brNDC");
  easyLeg(l2,"Barrel photons H/E<0.1");
  l2->SetTextFont(43);
  l2->SetTextSize(16);
  l2->AddEntry(h1, "All");
  l2->AddEntry(h2, "Electrons excluded");
  l2->Draw();

  
  c1->cd(2);
  //h3->SetAxisRange(0.5, 2500,"Y");
  h3->Draw("hist");
  h4->Draw("same hist");
  TLegend *l3 = new TLegend(0.6365615,0.4445304,0.9577623,0.646736,NULL,"brNDC");
  easyLeg(l3,"Isolated photons");
  l3->SetTextFont(43);
  l3->SetTextSize(16);
  l3->AddEntry(h3, "All");
  l3->AddEntry(h4, "Electrons excluded");
  l3->Draw();

  
}
Пример #17
0
void plotMETVsJetPhi(int num=-1)
{
   char *title="";
   if (num!=-1) {
      title = Form("%d",num);
   }
   TFile *inf = new TFile("nt_dj_mix100_Gen.root");
   TTree *tGen = (TTree*) inf->FindObjectAny("ntjt");
   tGen->SetName("gen");
   TFile *inf2 = new TFile("nt_dj_mix100.root");
   TTree *tReco = (TTree*) inf2->FindObjectAny("ntjt");
   tReco->SetName("reco");
   TFile *inf3 = new TFile("nt_dj_HyUQ80v4_djcalo_genp_100_50.root");
   TTree *tGen2 = (TTree*) inf3->FindObjectAny("ntjt");
   tGen2->SetName("gen2");
   TFile *inf4 = new TFile("dj_HyUQ80v4_djcalo_genp_100_50.root");
   TTree *tDj = (TTree*) inf4->FindObjectAny("djTree");
   tDj->SetName("dj");

   TFile *inf5 = new TFile("nt_dj_data100_cor.root");
   TTree *tRecoData = (TTree*) inf5->FindObjectAny("ntjt");
   tRecoData->SetName("data");
   TFile *inf6 = new TFile("dj_HCPR-J50U-hiGoodMergedTracks_OfficialSelv2_Final0_djcalo_100_50.root");
   TTree *tDjData = (TTree*) inf6->FindObjectAny("djTree");
   tDjData->SetName("djdata");
   tGen->AddFriend(tReco); 
   tGen->AddFriend(tGen2);
   tGen->AddFriend(tDj);
   tRecoData->AddFriend(tDjData);
   setupAlias(tGen);
   setupAlias(tReco);
   
   const int nBin = 10;
   double delta = 0.0; //shift
//   double Bins[nBin+1] = {0,1,2,2.2,2.4,2.6,2.8,3,PI};
//   double BinsMC[nBin+1] = {0+delta,1+delta,2+delta,2.2+delta,2.4+delta,2.6+delta,2.8+delta,3+delta,PI+delta};
   double Bins[nBin+1];
   double BinsMC[nBin+1];
   for (int i=0;i<nBin+1;i++)
   {
      Bins[i]=-PI+2*PI/(double)nBin*i;
      BinsMC[i]=-PI+2*PI/(double)nBin*i+delta;
      cout <<Bins[i]<<endl;
   }


   const int nPtBin = 6;
   double ptBins[nPtBin+1] = {0.5,1.0,1.5,4,8,20,1000};

   TCanvas *c = new TCanvas("c","",600,600);

   TProfile *p = new TProfile("p","",nBin,BinsMC);
   TProfile *p2 = new TProfile("p2","",nBin,BinsMC);
   TProfile *p3 = new TProfile("p3","",nBin,BinsMC);
   TProfile *p4 = new TProfile("p4","",nBin,Bins);

   TCut evtCut = "nljet>120&&abs(nljetacorr)<1.6&&aljet>50&&abs(aljetacorr)<1.6&&!maskEvt&&cent<30&&abs(jdphi)>2./3.*3.14159";

   tGen->Draw(Form("-gen.metOutOfConex%s:nljphi+0.0>>p",title),"weight"*evtCut);
   tGen->Draw(Form("-gen2.metOutOfConex%s:nljphi+0.0>>p2",title),"weight"*evtCut);
   tGen->Draw(Form("-reco.metOutOfConex%s:nljphi+0.0>>p3",title),"weight"*evtCut);
   tRecoData->Draw(Form("-metOutOfConex%s:nljphi>>p4",title),"1"*evtCut);
   p->SetMarkerStyle(24);
   p2->SetMarkerStyle(25);
   p3->SetMarkerStyle(26);
   p4->SetMarkerStyle(20);

   p->SetAxisRange(-80,120,"Y");
   p->Draw();
   p2->SetMarkerColor(2);
   p2->SetLineColor(2);
   p3->SetMarkerColor(4);
   p3->SetLineColor(4);
   p2->Draw("same");
   p3->Draw("same");
   p4->Draw("same");

   TLine *l = new TLine(Bins[0],0,PI,0);
   l->Draw();
   p->SetXTitle("#phi_{Leading Jet}");
   p->SetYTitle("<#slash{p}_{T}^{#parallel}> (GeV/c)");

// ====================
   TLegend *leg = new TLegend(0.45,0.68,0.92,0.9);
   leg->SetFillStyle(0);
   leg->SetBorderSize(0);
   leg->SetTextFont(63);
   leg->SetTextSize(16);
   leg->AddEntry("p","Jets with |#eta|<1.6","");
   if (num!=-1) {
      leg->AddEntry("p",Form("Tracks with %.1f<p_{T}<%.1f GeV/c",ptBins[num],ptBins[num+1]),"");
   } else {
      leg->AddEntry("p",Form("Tracks with %.1f<p_{T}<%.1f GeV/c",ptBins[0],ptBins[nPtBin]),"");
   }
   leg->AddEntry("p","#slash{p}_{T}^{#parallel} PYTHIA+HYDJET GEN Signal","pl");
   leg->AddEntry("p2","#slash{p}_{T}^{#parallel} PYTHIA+HYDJET GEN S+B","pl");
   leg->AddEntry("p3","#slash{p}_{T}^{#parallel} PYTHIA+HYDJET RECO","pl");
   leg->AddEntry("p4","#slash{p}_{T}^{#parallel} Data RECO","pl");
   leg->Draw();

   c->SaveAs(Form("metOutOfCone%sVsJetPhi.gif",title));
   c->SaveAs(Form("metOutOfCone%sVsJetPhi.eps",title));
}