예제 #1
0
void GetBinM(RooUnfoldResponse* &BinM, TH1D* &h_gen, TH1D* &h_reco, RooUnfoldResponse* &BinM_1, TH1D* &h_gen_1, TH1D* &h_reco_1, RooUnfoldResponse* &BinM_2, TH1D* &h_gen_2, TH1D* &h_reco_2, bool madgraph=1, int elec=0){

  TH2D* BinMigration=new TH2D("BinMigration","BinMigration",nbins,0,nbins,nbins,0,nbins);
  BinMigration->Sumw2();
  TH1D* Dphistar=new TH1D("Dphistar","Dphistar",2000,-1,1);
  Dphistar->Sumw2();
  TH1D* Dy=new TH1D("Dy","Dy",2000,-1,1);
  Dy->Sumw2();
  TChain* t = new TChain(reco_name.c_str(),reco_name.c_str());
  int nfiles;
  if (madgraph){
    if (elec==0) nfiles=t->Add(File_Signal_reco_d.c_str());
    if (elec==1) nfiles=t->Add(File_Signal_reco_b.c_str());
    if (elec==2) nfiles=t->Add(File_Signal_reco_n.c_str());
  }
  else {
    if (elec==0) nfiles=t->Add(File_Powheg_reco_d.c_str());
    if (elec==1) nfiles=t->Add(File_Powheg_reco_b.c_str());
    if (elec==2) nfiles=t->Add(File_Powheg_reco_n.c_str());
  }

  TBranch *b_reco=t->GetBranch("reco");
  TBranch *b_truth=t->GetBranch("truth");
  TLeaf *l_phistar=b_reco->GetLeaf("z_phistar_dressed");
  TLeaf *l_phistar_true=b_truth->GetLeaf("z_phistar_dressed");
  if (elec==1) l_phistar_true=b_truth->GetLeaf("z_phistar_born");
  if (elec==2) l_phistar_true=b_truth->GetLeaf("z_phistar_naked");
  TLeaf *l_y=b_reco->GetLeaf("z_y");
  TLeaf *l_y_true=b_truth->GetLeaf("z_y");
  if (elec==1) l_y_true=b_reco->GetLeaf("z_yBorn");
  if (elec==2) l_y_true=b_reco->GetLeaf("z_yNaked");
  int nweights;
  t->SetBranchAddress("weight_size",&nweights);
  t->GetEntry(0);
  cout<<"The sample has nweights: "<<nweights<<endl;
  double weights[nweights];
  int weightid[nweights];
  t->SetBranchAddress("weights",&weights);
  t->SetBranchAddress("weight_ids",&weightid);

  cout<<"Entries: "<<t->GetEntries()<<endl;
  h_gen   = new TH1D("phistar","phistar",nbins,0,nbins);
  h_gen->Sumw2();
  h_reco  = new TH1D("phistar","phistar",nbins,0,nbins);
  h_reco->Sumw2();
  h_gen_1 = new TH1D("phistar","phistar",nbins,0,nbins);
  h_gen_1->Sumw2();
  h_reco_1= new TH1D("phistar","phistar",nbins,0,nbins);
  h_reco_1->Sumw2();
  h_gen_2 = new TH1D("phistar","phistar",nbins,0,nbins);
  h_gen_2->Sumw2();
  h_reco_2= new TH1D("phistar","phistar",nbins,0,nbins);
  h_reco_2->Sumw2();
  BinM  =new RooUnfoldResponse (h_reco,h_gen);
  BinM_1=new RooUnfoldResponse (h_reco,h_gen);
  BinM_2=new RooUnfoldResponse (h_reco,h_gen);

  cout<<"reading signal reco "<<endl;
  for (int i=0; i<t->GetEntries();i++){
    // if (i>20000) continue;
    //for (int i=0; i<50000;i++){
    t->GetEntry(i);
    double weight =1;
    for (int w=0; w<nweights;w++){
      if (weightid[w]==1 || weightid[w]==2 || weightid[w]==12 || weightid[w]==13 || weightid[w]==20 || weightid[w]==30) {weight=weight*weights[w];}
    }
    double phistar=l_phistar->GetValue();
    double phistar_true=l_phistar_true->GetValue();
    Dphistar->Fill((phistar_true-phistar)/phistar_true,weight);
    double y=l_y->GetValue();
    double y_true=l_y_true->GetValue();
    Dy->Fill((y_true-y)/y_true,weight);

    int bin=GetBin(phistar,y);
    int bin_true=GetBin(phistar_true,y_true);

    h_gen ->Fill(bin_true,weight);
    h_reco->Fill(bin,weight);
    if (N_MC==-1 || i<N_MC) BinM  ->Fill(bin,bin_true,weight); 
    BinMigration->Fill(bin,bin_true,weight);
    if (i%2==0){
      h_gen_1 ->Fill(bin_true,weight);
      h_reco_1->Fill(bin,weight);
      if (N_MC==-1 || i<N_MC) BinM_1  ->Fill(bin,bin_true,weight); 
    }
    else{
      h_gen_2 ->Fill(bin_true,weight);
      h_reco_2->Fill(bin,weight);
      if (N_MC==-1 || i<N_MC) BinM_2  ->Fill(bin,bin_true,weight); 
    }
  }
////////////////////////////here is where I left.
  TLatex mark;
  mark.SetTextSize(0.04);
  mark.SetTextFont(42);
  mark.SetNDC(true);

//  BinMigration->GetXaxis()->SetRangeUser(0.001,3.2);
  BinMigration->GetXaxis()->SetTitle("(#phi*,y) bin (reconstructed)");
  BinMigration->GetXaxis()->SetTitleOffset(0.8);
  BinMigration->GetXaxis()->SetTitleSize(0.04);
  BinMigration->GetXaxis()->SetLabelOffset(0);
  BinMigration->GetXaxis()->SetLabelSize(0.03);
  BinMigration->GetYaxis()->SetTitleOffset(1.05);
  BinMigration->GetYaxis()->SetTitleSize(0.04);
  BinMigration->GetYaxis()->SetLabelSize(0.03);
//  BinMigration->GetYaxis()->SetRangeUser(0.001,3.2);
  BinMigration->GetYaxis()->SetTitle("(#phi*,y) bin (generated)");
  BinMigration->GetZaxis()->SetTitleOffset(-0.004);
  BinMigration->SetStats(0);
  BinMigration->SetBit( TH2::kNoTitle, true );

  Dphistar->GetXaxis()->SetTitle("(#phi*(generated) - #phi*(reconstructed)/#phi*(generated)");
  Dphistar->GetXaxis()->SetTitleOffset(1.0);
  Dphistar->GetXaxis()->SetTitleSize(0.04);
  Dphistar->GetXaxis()->SetLabelOffset(0.0);
  Dphistar->GetXaxis()->SetLabelSize(0.04);
  Dphistar->GetYaxis()->SetTitleOffset(1.05);
  Dphistar->GetYaxis()->SetTitleSize(0.04);
  Dphistar->GetYaxis()->SetLabelSize(0.04);
  Dphistar->GetYaxis()->SetTitle("a.u.");
  Dphistar->SetMarkerStyle(20);
  Dphistar->SetMarkerColor(1);
  Dphistar->SetLineColor(1);
  Dphistar->SetStats(0);
  Dphistar->SetBit( TH2::kNoTitle, true );

  Dy->GetXaxis()->SetTitle("(Z(y)(generated) - Z(y)(reconstructed)/Z(y) (generated)");
  Dy->GetXaxis()->SetTitleOffset(1.0);
  Dy->GetXaxis()->SetTitleSize(0.04);
  Dy->GetXaxis()->SetLabelOffset(0.0);
  Dy->GetXaxis()->SetLabelSize(0.04);
  Dy->GetYaxis()->SetTitleOffset(1.05);
  Dy->GetYaxis()->SetTitleSize(0.04);
  Dy->GetYaxis()->SetLabelSize(0.04);
  Dy->GetYaxis()->SetTitle("a.u.");
  Dy->SetMarkerStyle(20);
  Dy->SetMarkerColor(1);
  Dy->SetLineColor(1);
  Dy->SetStats(0);
  Dy->SetBit( TH2::kNoTitle, true );
   
  std::string plotname = "Plots/BinM_";
  if (elec==0) plotname+="Dressed_";
  if (elec==1) plotname+="Born_";
  if (elec==2) plotname+="Naked_";
  if (madgraph)plotname+="MG_";
  else         plotname+="PH_";

  if (madgraph){
    TCanvas* BinM_M = new TCanvas("BinM_M","BinM_M",800,900);
    BinM_M->cd();
    // BinM_M->SetLogx();
    // BinM_M->SetLogy();
    BinM_M->SetLogz();
    BinMigration->Draw("COLZ");
    mark.DrawLatex(0.19,0.80,"MadGraph");
    BinM_M->SaveAs((plotname+"res"+FileType).c_str());
    TCanvas* Dp_M = new TCanvas("Dp_M","Dp_M",800,900);
    Dp_M->cd();
    Dp_M->SetLogy();
    Dphistar->Draw();
    mark.DrawLatex(0.19,0.80,"MadGraph");
    Dp_M->SaveAs((plotname+"Dphistar"+FileType).c_str());
    TCanvas* Dy_M = new TCanvas("Dy_M","Dy_M",800,900);
    Dy_M->cd();
    Dy_M->SetLogy();
    Dy->Draw();
    mark.DrawLatex(0.19,0.80,"MadGraph");
    Dy_M->SaveAs((plotname+"Dy"+FileType).c_str());
  }
  else{
    TCanvas* BinM_P = new TCanvas("BinM_P","BinM_P",800,900);
    BinM_P->cd();
    // BinM_P->SetLogx();
    // BinM_P->SetLogy();
    BinM_P->SetLogz();
    BinMigration->Draw("COLZ");
    mark.DrawLatex(0.19,0.80,"Powheg");
    BinM_P->SaveAs((plotname+"res"+FileType).c_str());
    TCanvas* Dp_P = new TCanvas("Dp_P","Dp_P",800,900);
    Dp_P->cd();
    Dp_P->SetLogy();
    Dphistar->Draw();
    mark.DrawLatex(0.19,0.80,"Powheg");
    Dp_P->SaveAs((plotname+"Dphistar"+FileType).c_str());
    TCanvas* Dy_P = new TCanvas("Dy_P","Dy_P",800,900);
    Dy_P->cd();
    Dy_P->SetLogy();
    Dy->Draw();
    mark.DrawLatex(0.19,0.80,"Powheg");
    Dy_P->SaveAs((plotname+"Dy"+FileType).c_str());
  }

  double weighted_events= BinMigration->GetSumOfWeights();  
  double diagonal=0;
  for (uint i=0; i<nbins; i++){
    diagonal+=BinMigration->GetBinContent(i+1,i+1);
  }
  cout<<weighted_events<<" of which diagonal "<<diagonal<<" non diagonal faction:"<<(weighted_events-diagonal)/weighted_events<<endl;
  //Find amount of bin migration of Y
  double InTheY=0;//Gets values in the Same Y region 
  for (uint i=1; i<=nphistar; i++){
      for (uint j=1; j<=nphistar; j++){
          InTheY+=BinMigration->GetBinContent(i,j);
          InTheY+=BinMigration->GetBinContent(i+nphistar,j+nphistar);
          InTheY+=BinMigration->GetBinContent(i+nphistar*2,j+nphistar*2);
          InTheY+=BinMigration->GetBinContent(i+nphistar*3,j+nphistar*3);
          InTheY+=BinMigration->GetBinContent(i+nphistar*4,j+nphistar*4);
          InTheY+=BinMigration->GetBinContent(i+nphistar*5,j+nphistar*5);
      }
      
  }
  cout<<"Percent mig Y axis: "<<100*(weighted_events-InTheY)/weighted_events<<std::endl<<std::endl;
  
  cout<<"done reading data "<<endl;

  for (uint i=0; i<nbins;i++){
    h_gen->SetBinError(i+1,0);
    h_gen_1->SetBinError(i+1,0);
    h_gen_2->SetBinError(i+1,0);
  }
  return;
}
예제 #2
0
void ana_MC_BTagEff(TString ds="relval", TString physics="ttbar") {
{
  gSystem->Load("libSusyEvent.so");

  // Look ../jec/JetMETObjects/README
  gSystem->Load("../jec/lib/libJetMETObjects.so");

  // Printing utility for ntuple variables
  gROOT->LoadMacro("SusyEventPrinter.cc+");

  // Main analysis code
  gROOT->LoadMacro("SusyAna_MC_BTagEff.cc+"); //this line causes everything to segfault at the end.

  // chain of inputs
  TChain* chain = new TChain("susyTree");

//////////////// MC files /////////////////
  MCpoint* thisMCpoint = setupMCpoint(which_MC_to_use2); 
cout<<"try to add "<<thisMCpoint->filepath.c_str()<<endl;
  chain->Add(thisMCpoint->filepath.c_str()); 
//int which_MC_to_use=0; //already set
/*if(which_MC_to_use==0){
   chain->Add("MC/susyEvents_MC_AB_1M_st350_ho200.root");
}
else if(which_MC_to_use==1){
   chain->Add("MC/susyEvents_MC_AB_1M_st250_ho200.root");
}
else if(which_MC_to_use==2){
   chain->Add("MC/susyEvents_MC_AB_1M_st250_ho150.root");
}
else if(which_MC_to_use==3){
   chain->Add("MC/susyEvents_MC_AB_1M_ho140.root");
}
else if(which_MC_to_use==4){
   chain->Add("MC/susyEvents_MC_AB_1M_ho200.root");
}
*/


   //chain->Add("../susyEvents_AB_1M_ho200_v2.root");
   //chain->Add("../susyEvents_newNatural.root");
   //chain->Add("/eos/uscms/store/user/abarker/MC/newNat350_225/MC_AB_2500k_NEWnaturalHiggsinoNLSPout_mst_350_M3_5025_mu_225.root");//same thing as ../susyEvents_newNatural.root
   //chain->Add("/eos/uscms/store/user/abarker/MC/st_250_ho_150/MC_AB_2500k_st_250_ho_150.root");
   //chain->Add("/eos/uscms/store/user/abarker/MC/st_250_ho_200/MC_AB_2500k_st_250_ho_200.root");
   //chain->Add("/eos/uscms/store/user/abarker/MC/st_350_ho_200/MC_AB_2500k_mst_350_mu_200.root");
   //chain->Add("/eos/uscms/store/user/abarker/MC/ho_140/MC_AB_2500k_ho_140.root");
   //chain->Add("/eos/uscms/store/user/abarker/MC/ho_200/MC_AB_2500k_ho_200.root");


   //chain->Add("../susyEvents_newNatural.root");
    //chain->Add("dcache:/pnfs/cms/WAX/resilient/abarker/MC/MC_AB_2500k_NEWnaturalHiggsinoNLSPout_mst_350_M3_5025_mu_225.root");

   //chain->Add("dcache:/pnfs/cms/WAX/resilient/abarker/MC/MC_AB_2500k_st_250_ho_150.root");
   //chain->Add("dcache:/pnfs/cms/WAX/resilient/abarker/MC/MC_AB_2500k_st_250_ho_200.root");
   //chain->Add("dcache:/pnfs/cms/WAX/resilient/abarker/MC/MC_AB_2500k_mst_350_mu_200.root");
   //chain->Add("dcache:/pnfs/cms/WAX/resilient/abarker/MC/MC_AB_2500k_ho_140.root");
   //chain->Add("dcache:/pnfs/cms/WAX/resilient/abarker/MC/MC_AB_2500k_ho_200.root");


  SusyAna_MC_BTagEff* sea = new SusyAna_MC_BTagEff(chain);

  // configuration parameters
  // any values given here will replace the default values
  sea->SetDataset(physics+"_"+ds);        // dataset name
  sea->SetPrintInterval(1e4);             // print frequency
  sea->SetPrintLevel(0);                  // print level for event contents
  sea->SetUseTrigger(false);
/*
  sea->AddHltName("HLT_Photon36_CaloIdL_Photon22_CaloIdL");  // add HLT trigger path name 
  sea->AddHltName("HLT_Photon32_CaloIdL_Photon26_CaloIdL");  // add HLT trigger path name
  sea->AddHltName("HLT_Photon26_R9Id85_Photon18_R9Id85_Mass60");
  sea->AddHltName("HLT_Photon26_R9Id85_Photon18_CaloId10_Iso50_Mass60");
  sea->AddHltName("HLT_Photon26_CaloId10_Iso50_Photon18_R9Id85_Mass60");
  sea->AddHltName("HLT_Photon26_CaloId10_Iso50_Photon18_CaloId10_Iso50_Mass60");
  sea->AddHltName("HLT_Photon26_R9Id85_OR_CaloId10_Iso50_Photon18_R9Id85_OR_CaloId10_Iso50_Mass60");
  sea->AddHltName("HLT_Photon26_R9Id85_OR_CaloId10_Iso50_Photon18_R9Id85_OR_CaloId10_Iso50_Mass70");
  sea->AddHltName("HLT_Photon36_R9Id85_Photon22_R9Id85");
  sea->AddHltName("HLT_Photon36_R9Id85_Photon22_CaloId10_Iso50");
  sea->AddHltName("HLT_Photon36_CaloId10_Iso50_Photon22_R9Id85");
  sea->AddHltName("HLT_Photon36_CaloId10_Iso50_Photon22_CaloId10_Iso50");
  sea->AddHltName("HLT_Photon36_R9Id85_OR_CaloId10_Iso50_Photon22_R9Id85_OR_CaloId10_Iso50");
*/
  sea->SetFilter(true);                  // filter events passing final cuts
  sea->SetProcessNEvents(-1);             // number of events to be processed

  // as an example -- add your favorite Json here.  More than one can be "Include"ed
  //  sea->IncludeAJson("Cert_161079-161352_7TeV_PromptReco_Collisions11_JSON_noESpbl_v2.txt");
  //sea->IncludeAJson("anotherJSON.txt");

  TStopwatch ts;

  ts.Start();

  sea->Loop();

  ts.Stop();

  std::cout << "RealTime : " << ts.RealTime()/60.0 << " minutes" << std::endl;
  std::cout << "CPUTime  : " << ts.CpuTime()/60.0 << " minutes" << std::endl;
	}
  std::cout << "super end"<<std::endl;
	

}
예제 #3
0
void plotter(const char* datafilename, const char* mcfilename, const char *idmvaCorrectionFile = NULL) {

  // READ Transformations
  std::vector<TGraph*> graphs;
  if (idmvaCorrectionFile != NULL) readTransformations(graphs);
    //readTransformations(graphs, idmvaCorrectionFile);

  //std::vector<TGraph*> graphs;
  //readTransformations(graphs);
  
  // READ SAMPLES
  ifstream myReadFile;
  myReadFile.open("inputfiles.dat");
  char output[100];
  int itype = -1;
  if (myReadFile.is_open()) {
    while (!myReadFile.eof()) {
      float xsec;
      myReadFile >> output >> xsec >> itype;
      std::string init(output);
      if (init.substr(0,1) != "#") {
	samples.push_back(std::pair<std::string, int>(output, itype));
	//std::cout << output << " " << itype << std::endl;
      }
    }
  }
  myReadFile.close();
  std::cout<< "Debug level 1" << std::endl; 
  
  //std::string weight = "weight";
  
  for (int sampletype=0; sampletype<2; sampletype++) {
    
    TChain* chain = new TChain("PhotonToRECO/fitter_tree");
    if (sampletype == 0)
      chain->Add(datafilename);
    else
      chain->Add(mcfilename);
    
    TBranchesI branchesI;
    TBranchesF branchesF;
    TBranchesD branchesD;
    TBranchesUI branchesUI;
    TBranchesUC branchesUC;

    auto leafList = chain->GetListOfLeaves();
    for (auto leaf : *leafList) {
      std::string name =((TLeaf*)leaf)->GetName();
      std::string type = ((TLeaf*)leaf)->GetTypeName();
      
      std::cout << name << type << endl;
            if (type == "Int_t") {
	Int_t a = 0;
	branchesI[name] = a;
	chain->SetBranchAddress(name.c_str(), &(branchesI[name]));
      } else if (type == "Float_t") {
	Float_t a = 0;
	branchesF[name] = a;
	chain->SetBranchAddress(name.c_str(), &(branchesF[name]));
      } else if (type == "Double_t") {
	Double_t a = 0;
	branchesD[name] = a;
	chain->SetBranchAddress(name.c_str(), &(branchesD[name]));
      } else if (type == "UInt_t") {
	UInt_t a = 0;
	branchesUI[name] = a;
	chain->SetBranchAddress(name.c_str(), &(branchesUI[name]));
      } else if (type == "UChar_t") {
	UChar_t a = 0;
	branchesUC[name] = a;
	chain->SetBranchAddress(name.c_str(), &(branchesUC[name]));
	}
	    //std::cout<< "Debug level 1.1" << std::endl; 
    }
    //std::cout<< "Debug level 2" << std::endl; 
    
    std::map<int, std::vector<TTreeFormula*> > categories;
    std::cout << "Reading categories...." << std::endl;
    myReadFile.open("probeCategories.dat");
    std::string line;
    int cat;
    while(!myReadFile.eof()) {
      myReadFile >> cat >> line;
      char a[100];
      if (categories.find(cat) == categories.end() ) {
	sprintf(a, "cat%d_%d", cat, 0);
	std::cout << a << " " << line << std::endl;
	categories[cat].push_back(new TTreeFormula(a, line.c_str(), chain));
      } else {
	sprintf(a, "cat%d_%zu", cat, categories[cat].size());
	std::cout << a << " " << line << std::endl;
	categories[cat].push_back(new TTreeFormula(a, line.c_str(), chain));
      }
    }
    myReadFile.close();
    //std::cout<< "Debug level 3" << std::endl; 

    
    std::vector<HistoDefinition> histoDef;
    // READING PLOT DEFINITION
    std::cout << "Reading plots..." << std::endl;
    myReadFile.open("probesvar.dat");
    std::map<int, HistoContainer> histos;
    histos[samples[sampletype].second] = HistoContainer();
    
    while(!myReadFile.eof()) {
      // type ncat==1 xbin ybins xmin xmax ymin ymax name xaxis yaxis var cat????
      HistoDefinition temp;
      myReadFile >> temp.type >> temp.log >> temp.ncat >> temp.xbins >> temp.ybins >> temp.xmin >> temp.xmax
		 >> temp.ymin >> temp.ymax >> temp.name >> temp.xaxis >> temp.yaxis >> temp.var;
      histoDef.push_back(temp);
      
      TH1F* h = new TH1F("h", "", temp.xbins, temp.xmin, temp.xmax);
      h->GetXaxis()->SetTitle(temp.xaxis.c_str());
      h->GetYaxis()->SetTitle(temp.yaxis.c_str());
      
      int ncats = categories[temp.ncat].size();
      for (int c=0; c<ncats; c++) {
	
	std::ostringstream convert; 
	convert << c;
	std::string name = temp.name + "_cat"+ convert.str() + "_" + samples[sampletype].first;  
	std::cout << c << " " << name << std::endl;
	histos[samples[sampletype].second].histoF[temp.name].push_back(*((TH1F*)h->Clone(name.c_str())));
      }
      delete h;
    }
    myReadFile.close();
    // std::cout<< "Debug level 4 " << chain->GetEntries() << std::endl; 

    for (int z=0; z<chain->GetEntries(); z++) {
      if (z%10000 == 0)
	std::cout << z << std::endl;
      
      chain->GetEntry(z);

      float mass = branchesF["mass"];
      if ((mass > 70 && mass < 110) && ((abs(branchesF["probe_sc_eta"]) < 1.5 && branchesF["probe_Pho_sieie"] < 0.0105) || (abs(branchesF["probe_sc_eta"]) > 1.5 && branchesF["probe_Pho_sieie"] < 0.028))) {
	double weight = 1.0; 
	if (sampletype == 1 && isfinite(branchesF["totWeight"])) {
	  weight = branchesF["totWeight"];
	  // std::cout << "weight in the loop: " << weight << "and:  " << branchesD["totWeight"] << std::endl; 
	}  
	// cout << "mass: " << mass << " - " << "tag_Pho_mva" << branchesF["tag_Pho_mva"] << " - " << "probe_Pho_mva" << branchesF["probe_Pho_mva"] << endl;
	for (unsigned int s=0; s<samples.size(); s++) {
	  for (unsigned int h=0; h<histoDef.size(); h++) {
	    // std::cout << histoDef[h].name << " " << histoDef[h].var << " " << histoDef[h].ncat << std::endl;
	    std::string name = histoDef[h].name;
	    std::string var = histoDef[h].var;
	    int category = histoDef[h].ncat;
	    
	    double final_weight = weight;
	    // std::cout << "final_weight: " << final_weight << std::endl;
	    for (unsigned int cat=0; cat<categories[category].size(); cat++) {
	      categories[category][cat]->UpdateFormulaLeaves();
	      // std::cout<< "Going to draw histogram " << name <<std::endl;
	      
	      if (categories[category][cat]->EvalInstance()) {
		if (name == "idmvaup1" || name == "idmvaup2")
 		  histos[samples[sampletype].second].histoF[name][cat].Fill(branchesF[var]+idmvaShift, final_weight);
		else if (name == "idmvadown1" || name == "idmvadown2")  
 		  histos[samples[sampletype].second].histoF[name][cat].Fill(branchesF[var]-idmvaShift, final_weight);
		else if (name == "idmvatop1" || name == "idmvatop2")
		  {
		  if (idmvaCorrectionFile != NULL)
		    {

		      if(cat == 0 || cat == 1){ histos[samples[sampletype].second].histoF[name][cat].Fill(graphs[cat+2]->Eval(branchesF[var]), final_weight*graphs[cat+2]->Eval(9999));}
		    }
		  }
		else if (name == "idmvabottom1" || name == "idmvabottom2")
		  {
		    if (idmvaCorrectionFile != NULL)
		      {
			if(cat == 0 || cat == 1){ histos[samples[sampletype].second].histoF[name][cat].Fill(graphs[cat]->Eval(branchesF[var]), final_weight*graphs[cat]->Eval(9999));}
		      }

		  }
		else if (name == "sigmaEoEup1" || name == "sigmaEoEup2")
 		  histos[samples[sampletype].second].histoF[name][cat].Fill(branchesF[var]*(1+sigmaEScale), final_weight);
		else if (name == "sigmaEoEdown1" || name == "sigmaEoEdown2")  
 		  histos[samples[sampletype].second].histoF[name][cat].Fill(branchesF[var]*(1-sigmaEScale), final_weight);
		else if (branchesF.find(var) != branchesF.end())
		  histos[samples[sampletype].second].histoF[name][cat].Fill(branchesF[var], final_weight);
		else if (branchesI.find(var) != branchesI.end())
		  histos[samples[sampletype].second].histoF[name][cat].Fill(branchesI[var], final_weight);
	      }	    
	      // std::cout<< "histo " << name << " drawn" << std::endl;
	      // std::cout<< "Debug level 5 " << z << " " << s << " " << h << " " << " " << cat << std::endl; 
	    }
	    // std::cout << "Debug level 6" << std::endl;
	  }
	  // std::cout << "Debug level 7" << std::endl;
	  break;
	}
	// std::cout << "Debug level 8" << std::endl;	
      }
      // std::cout << "Debug level 9" << std::endl;
      // if(sampletype==0 && z>=10000) break ;
      if(sampletype==1 && z>0) break ;
    }
    
    std::cout << sampletype << std::endl;
    std::string rootOutputFile = "tnp_data_2017.root";  
    if (sampletype == 1)
      rootOutputFile = "tnp_tmp.root";
    
    TFile* out = new TFile(rootOutputFile.c_str(), "recreate");
    
    for (unsigned int h=0; h<histoDef.size(); h++) {
      std::string var = histoDef[h].name;
      int cat = categories[histoDef[h].ncat].size();
      for (int c=0; c<cat; c++) {
	histos[samples[sampletype].second].histoF[var][c].Write();
      }
      //std::cout << "Wrote histo successfully" << var << std::endl; 
    }
    out->Close();
  }
}
예제 #4
0
void hbbNN(Int_t ntrain=15) {
// Example of a Multi Layer Perceptron
// For a Tevatron search for SUSY Higgs in bh->bbb, a neural network 
// was used to separate the signal from the background passing 
// some selection cuts. Here is a simplified version of this network, 
// taking into account only bbb events.
//Author: P. Jonsson

//Part 1, preparing the inputs

//Booking some histograms for signal and background, 
//Add histograms yourself for the dijet mass (MH[0]) of the leading pT 
//(=transverse momenta) jets for background and signal  

   TH1F *detas = new TH1F("detas", "detas", 50, .0, 4.);
   TH1F *detab = new TH1F("detab", "detab", 50, .0, 4.);   
   TH1F *dphis = new TH1F("dphis", "dphis", 50, .0, 3.15);
   TH1F *dphib = new TH1F("dphib", "dphib", 50, .0, 3.15);  
   TH1F *angles = new TH1F("angles", "angles", 50, .0, 2.);
   TH1F *angleb = new TH1F("angleb", "angleb", 50, .0, 2.);  
   TH1F *pbalances = new TH1F("pbalances", "pbalances", 50, .0, 1.);
   TH1F *pbalanceb = new TH1F("pbalanceb", "pbalanceb", 50, .0, 1.); 
   TH1F *etahs = new TH1F("etahs", "etahs", 50, -2.5, 2.5);
   TH1F *etahb = new TH1F("etahb", "etahb", 50, -2.5, 2.5);  
   TH1F *sphericitys = new TH1F("sphericitys", "sphericitys", 50, .0, 1.);
   TH1F *sphericityb = new TH1F("sphericityb", "sphericityb", 50, .0, 1.); 

   if (!gROOT->GetClass("TMultiLayerPerceptron")) {
      gSystem->Load("libMLP");
   }

   // Prepare inputs
   // The 2 trees are merged into one, and a "type" branch, 
   // equal to 1 for the signal and 0 for the background is added.

   TChain * signal = new TChain("higgsSearch","");

   //Use a Higgs signal at a mass of  110 GeV   
    signal->Add("LHinput-cut_2b25_1j15-Tight-MC_higgs110GeV.root/higgsSearch");

    //Use a background of multijet bbb events
   TChain *background = new TChain("higgsSearch","");
   background->Add("LHinput-cut_2b25_1j15-Tight-MC_bbb.root/higgsSearch");

   //book combined tree of selected events top use for training
   TFile *f = new TFile("training.root","recreate");
   TTree *simu = new TTree("MonteCarlo", "Filtered Monte Carlo Events");

   Double_t nnoutxlm[4], MH[6], dEta[6], dPhi[6], Angle[6], EtaH[6], pBalance[6], Sphericity;
   Double_t dphi, deta, angle, etah, pbalance, sphericity; 
   Int_t Njets, typeH[6], typeO, nsignal, nbkg;

   //counters for signal and background events
   nsignal=0;
   nbkg=0;

   // 
   //Set branch addresses to use from signal and background trees
   //Description of variables inline below. 
   //Draw histograms of these  variables for signal and background on top 
   //of eachother in different colors. 
   //Save these plots (you can look up how to save plots to files at root.cern.ch)
 
   //Invariant di-jet mass
   signal->SetBranchAddress("MH",  &MH);

   //Delta eta, difference in pseudorapidity (spatial coodinate used to 
   //describe angle with the beam axis = -ln(tan(theta/2))
   signal->SetBranchAddress("dEta",    &dEta);

   //Delta phi, azimuthal angle (going from 0 to 2pi around the beampipe)
   signal->SetBranchAddress("dPhi",  &dPhi);

   //Angle between the leading jet and the combined jet-pair
   signal->SetBranchAddress("Eta1mEtaH", &Angle);

   //Pseudorapidity of the combined jet-pair
   signal->SetBranchAddress("EtaH",  &EtaH);

   //Which jet-pair comes from the true Higgs decay
   signal->SetBranchAddress("type", &typeH);

   //Momentum balance of the jet-pair: p1-p2/p1+p2 
   signal->SetBranchAddress("pBalance",  &pBalance);

   //Number of jets in the event 
   signal->SetBranchAddress("Njets", &Njets);

   //Event sphericity (measure of how spherical, round, the event is)
   signal->SetBranchAddress("FW_H2", &Sphericity);

   //same for background
   background->SetBranchAddress("MH",  &MH);
   background->SetBranchAddress("dEta",    &dEta);
   background->SetBranchAddress("dPhi",  &dPhi);
   background->SetBranchAddress("Eta1mEtaH", &Angle);
   background->SetBranchAddress("EtaH",  &EtaH);
   background->SetBranchAddress("pBalance",  &pBalance);
   background->SetBranchAddress("Njets", &Njets);
   background->SetBranchAddress("FW_H2", &Sphericity);

   //Make input branches of variables to use for the training
   simu->Branch("dEta", &deta, "dEta/D");
   simu->Branch("dPhi",  &dphi,  "dPhi/D");
   simu->Branch("Angle",    &angle,    "Angle/D");
   simu->Branch("pBalance",  &pbalance,  "pBalance/D");
   simu->Branch("EtaH", &etah, "EtaH/D");
   simu->Branch("Sphericity",  &sphericity,  "Sphericity/D");
   simu->Branch("type",   &typeO,   "type/I");
  
   //loop over signal and select events to use for training 
   Int_t i;
   for (i = 0; i < signal->GetEntries(); i++) {
     signal->GetEntry(i);
     //only consider events with 3 jets
      if (Njets==3){
          typeO=0; 
          //select only events where the two leading pT jets come from the 
	  //Higgs decay (typeH[0]==1), and these two jets are separated by 
	  //sqrt(dEta[0]*dEta[0]+dPhi[0]*dPhi[0]) > 1, and the invariant 
          //di-jet mass is greater than 50 GeV
          if (typeH[0]==1 && sqrt(dEta[0]*dEta[0]+dPhi[0]*dPhi[0]) > 1. && MH[0]>50.){          
	    deta = dEta[0];
	    dphi =2*acos(0)- dPhi[0]; 
            angle = Angle[0];
            pbalance = pBalance[0];
            etah = EtaH[0];
            sphericity = Sphericity;
            typeO=1; 
	   }
	  //fill selected signal events (type0==1)
          if (typeO==1){
	    //fill the histograms like this:
	      detas->Fill(deta); 	      
	      dphis->Fill(dphi);
	      angles->Fill(angle);
	      pbalances->Fill(pbalance);
	      etahs->Fill(etah);
	      sphericitys->Fill(sphericity);


	      //fill the training tree   
              simu->Fill();
              nsignal++; 
	  }
      }
   }

   cout << nsignal <<endl; 
   //now loop over background events
   for (i = 0; i < background->GetEntries(); i++) {
      background->GetEntry(i);
      if (Njets==3){
          typeO=1;
	  //similar for background events
          if (sqrt(dEta[0]*dEta[0]+dPhi[0]*dPhi[0]) > 1. && MH[0]>50.){
	    deta = dEta[0];
	    dphi =2*acos(0)- dPhi[0]; 
            angle = Angle[0];
            pbalance = pBalance[0];
            etah = EtaH[0];
            sphericity = Sphericity;
            typeO=0; 
          }
	  //fill the selected background events until you have the same 
          //number as signal
          if (typeO==0 && nbkg<nsignal){
	    //fill the background histograms here:
    	      detab->Fill(deta); 	      
    	      dphib->Fill(dphi);
    	      angleb->Fill(angle);
    	      pbalanceb->Fill(pbalance);
    	      etahb->Fill(etah);
    	      sphericityb->Fill(sphericity);
            
	    
	    
	    nbkg++;
            simu->Fill();
	  } 
      }

   }
   cout << nbkg << endl;   


   	/*Plot the simulated and background variable distributions */
	TCanvas *c1 = new TCanvas("c2", "Signal and Background Distributions");
	c1->Divide(2,3);
	c1->cd(1);  dphis->Draw();       dphib->	SetLineColor(kRed);   dphib->Draw("same");	
	c1->cd(2);  detas->Draw();       detab->	SetLineColor(kRed);   detab->Draw("same");	
	c1->cd(3);  angles->Draw();      angleb->	SetLineColor(kRed);   angleb->Draw("same");	
	c1->cd(4);  pbalances ->Draw();  pbalanceb->	SetLineColor(kRed);   pbalanceb ->Draw("same");	
	c1->cd(5);  etahs->Draw();       etahb->	SetLineColor(kRed);   etahb->Draw("same");	
	c1->cd(6);  sphericitys->Draw(); sphericityb->	SetLineColor(kRed);   sphericityb->Draw("same");	
	c1->SaveAs("sig_background_distr.pdf");	
	


	for(Int_t i = 1; i++; i < 5)
	{ 
		stringstream ss;
		ss << i*5;
		TString structure = "@dEta, @dPhi, @EtaH, @pBalance, @Sphericity, @Angle:" + ss.str() + ":1:type";;
		trainNetwork(simu, structure, 100);

	}
}
예제 #5
0
/// Main function that runs the analysis algorithm on the
/// specified input files
int main(int argc, char* argv[]) {

  /// Gets the list of input files and chains
  /// them into a single TChain
  char inputFileName[150];
  char outFileName[150];
  char skimFileName[150];
  char json[150]="none";

  if ( argc < 3 ){
    cout << "Error at Input: please specify an input file including the list of input ROOT files" << endl; 
    cout << "Example:        ./VecbosApp list.txt output.root" << endl;
    cout << "Available options: " <<endl;
    cout << "-weight=w  weight of the MC" << endl;  
    cout << "-start=N start from event N in the chain" << endl; 
    cout << "-stop=N stop at event N in the chain" << endl; 
    cout << "-signal=N 0=W(prompt),1=Z(prompt),2=W(other),3=Z(other), 4= no mctruth" << endl; 
    cout << "--isData to run on good runs on data" << endl; 
    cout << "-json=file path of the json file" << endl;
    return 1;
  }

  // rad running options
  strcpy(inputFileName,argv[1]);
  strcpy(outFileName,argv[2]);
  strcpy(skimFileName,argv[2]);

  TChain *theChain = new TChain("ntp1");
  char Buffer[500];
  char MyRootFile[2000];  
  ifstream *inputFile = new ifstream(inputFileName);
  // get the tree with the conditions from the first file
  //  TTree *treeCond = new TTree();
  //  int nfiles=1;
  char tmpFileName[256];
  vector<string> filesToRemove;
  while( !(inputFile->eof()) ){
    inputFile->getline(Buffer,500);
    if (!strstr(Buffer,"#") && !(strspn(Buffer," ") == strlen(Buffer)))
      {
	sscanf(Buffer,"%s",MyRootFile);
	if(string(MyRootFile).find("eos") != std::string::npos) {
	  theChain->Add("root:/"+TString(MyRootFile));
        } else {
	  theChain->Add("rfio:"+TString(MyRootFile));
	}
        // theChain->Add("root://castorcms/"+TString(MyRootFile));
	//        theChain->Add(TString(MyRootFile));
	std::cout << "chaining " << MyRootFile << std::endl;
	//	if ( nfiles==1 ) {
	//	  TFile *firstfile = TFile::Open("root://castorcms/"+TString(MyRootFile));
	//	  treeCond = (TTree*)firstfile->Get("Conditions");
	//	}
	//        nfiles++;
      }
  }
 

  //  theChain->MakeClass("thisiswhyitcrashed");

  inputFile->close();
  delete inputFile;
  // get additional input options
  int signal = 0;
  int start = 0;
  int stop  = theChain->GetEntries();
  bool isData = false;
  float lumi = -999.;
  float xsec = -999.;
  float weight = 1.;
  for (int i=1;i<argc;i++){
    if (strncmp(argv[i],"-start",6)==0) sscanf(argv[i],"-start=%i",&start);
    if (strncmp(argv[i],"-stop",5)==0)  sscanf(argv[i],"-stop=%i",&stop);
    if (strncmp(argv[i],"-signal",7)==0)  sscanf(argv[i],"-signal=%i",&signal);
    if (strncmp(argv[i],"-weight",7)==0)  sscanf(argv[i],"-weight=%f",&weight);
    if (strncmp(argv[i],"--isData",8)==0)  isData = true;
    if (strncmp(argv[i],"-lumi",5)==0)  sscanf(argv[i],"-lumi=%f",&lumi);
    if (strncmp(argv[i],"-xsec",5)==0)  sscanf(argv[i],"-xsec=%f",&xsec);
    if (strncmp(argv[i],"-json",5)==0)  sscanf(argv[i],"-json=%s",&json);
  }

  

#if Application == 1
  std::cout << " initialising " << std::endl;
  VecbosEESelection vecbos(theChain);
  std::cout << " setup trigger selection " << std::endl;
  std::vector<string> mask;
  mask.push_back("HLT_Photon10_L1R");
  mask.push_back("HLT_Photon15_L1R");
  for(std::vector<string>::iterator it=mask.begin(); it!= mask.end();it++)
    std::cout << *it <<std::endl;
  vecbos.setRequiredTriggers(mask);
  std::cout << " setup analysis parameters" <<std::endl;
  vecbos.doBestElectronStudy(false);
  std::cout << "  skimname" <<std::endl;
  vecbos.setPrefix(skimFileName);
  std::cout << "  signal" <<std::endl;
  vecbos.setSignal(signal);
  std::cout << " starting event loop"<< std::endl;
  vecbos.Loop();
  std::cout << " preparing plots" <<std::endl;
  vecbos.displayEfficiencies();
#endif

#if Application == 2
  CandleCalib vecbos(theChain);
  //  TriggerMask mask(treeCond);
  //  mask.requireTrigger("HLT_Mu9");
  //  mask.requireTrigger("HLT_Mu11");
  //  mask.requireTrigger("HLT_Mu15");
  //  mask.requireTrigger("HLT_DoubleMu3");
  //  std::vector<int> requiredTriggers = mask.getBits();
  //  vecbos.requireTrigger(requiredTriggers);
  vecbos.Loop(string(outFileName), start, stop);  
#endif

#if Application == 3

  // for electron analysis:
  VecbosEESelection vecbos(theChain);
  std::vector<std::string> mask;
  if(!isData) { // for Winter10 MC only
    mask.push_back("HLT_Ele10_SW_L1R_v2");
    mask.push_back("HLT_Ele17_SW_L1R_v2");
    mask.push_back("HLT_Ele17_SW_L1R_v2");
    mask.push_back("HLT_Ele17_SW_Isol_L1R_v2");
    mask.push_back("HLT_Ele17_SW_TighterEleIdIsol_L1R_v3");
    mask.push_back("HLT_Ele17_SW_TightCaloEleId_Ele8HE_L1R_v2");
  } else { // 2010 Run data
    std::cout << "Applying triggers for data" << std::endl;
    mask.push_back("HLT_Photon10_L1R");
    mask.push_back("HLT_Photon15_L1R");
    mask.push_back("HLT_Photon15_Cleaned_L1R");
    mask.push_back("HLT_Ele10_LW_L1R");
    mask.push_back("HLT_Ele15_SW_L1R");
    mask.push_back("HLT_Ele15_SW_CaloEleId_L1R");
    mask.push_back("HLT_Ele17_SW_CaloEleId_L1R");
    mask.push_back("HLT_Ele17_SW_TightEleId_L1R");
    mask.push_back("HLT_Ele17_SW_TighterEleIdIsol_L1R_v2");
    mask.push_back("HLT_Ele17_SW_TighterEleIdIsol_L1R_v3");
  }
  vecbos.setRequiredTriggers(mask);
  vecbos.doBestElectronStudy(false);
  vecbos.doBTagEfficiencyStudy(false);
  vecbos.setPrefix(skimFileName);
  vecbos.setSignal(signal);
  vecbos.Loop();
  vecbos.displayEfficiencies();

  return 0;

#endif

#if Application == 4  
  // for muon analysis:
  VecbosMuMuSelection vecbos(theChain);
  std::vector<std::string> mask;
  mask.push_back("HLT_Mu9");
  mask.push_back("HLT_Mu15_v1");
  vecbos.setRequiredTriggers(mask);
  vecbos.setPrefix(skimFileName);
  vecbos.setSignal(signal);
  vecbos.Loop();
  vecbos.displayEfficiencies();
  return 0;
#endif

#if Application == 5
#endif

#if Application == 6
  
#endif

#if Application == 7
  if(isData) {
    DiJet vecbos(theChain, true, true);
    vecbos.Loop(string(outFileName), start, stop);  
  } else {
    DiJet vecbos(theChain, false, false);
    vecbos.Loop(string(outFileName), start, stop);  
  }
#endif

#if Application == 8  
  if(isData) {
    vecbos.Loop(string(outFileName), start, stop);  
  } else {
    Razor vecbos(theChain, string(json), false, false);
    vecbos.Loop(string(outFileName), start, stop);  
  }
#endif

#if Application == 9

  VecbosPFEESelection vecbos(theChain);
  std::vector<std::string> mask;
  mask.push_back("HLT_Photon10_L1R");
  vecbos.setRequiredTriggers(mask);
  vecbos.setPrefix(skimFileName);
  vecbos.setSignal(signal);
  vecbos.Loop();
  vecbos.displayEfficiencies();

#endif

#if Application == 10

  // for electron analysis:
  SuperClustersEESelection vecbos(theChain);
  std::vector<std::string> mask;
  mask.push_back("HLT_Photon10_L1R");
  vecbos.setRequiredTriggers(mask);
  vecbos.requireTrigger(requiredTriggers);
  vecbos.setPrefix(skimFileName);
  vecbos.setSignal(signal);
  vecbos.Loop();
  vecbos.displayEfficiencies();
#endif
 //  **********NATASHA MODIFIED 6/21/2010*****************

#if Application == 12
  if(isData) {
    GammaPlusJet vecbos(theChain, true, true);
    vecbos.SetConditions(treeCond);
    vecbos.Loop(string(outFileName), start, stop);  
  } else {
    GammaPlusJet vecbos(theChain, false, false);
    if(lumi > 0. && xsec > 0.) {
      vecbos.SetLuminosity(lumi);
      vecbos.SetXsection(xsec);
    }
    vecbos.SetConditions(treeCond);
    vecbos.Loop(string(outFileName), start, stop);  
  }
#endif

#if Application == 13  
  std::vector<std::string> mask;
  // if(!isData) {
  //   mask.push_back("HLT_HT200");
  // } else {
  if (isData) {
    mask.push_back("HLT_R014_MR150");
    mask.push_back("HLT_R020_MR150");
    mask.push_back("HLT_R025_MR150");
    mask.push_back("HLT_R020_MR500");
    mask.push_back("HLT_R020_MR550");
    mask.push_back("HLT_R025_MR400");
    mask.push_back("HLT_R025_MR450");
    mask.push_back("HLT_R033_MR300");
    mask.push_back("HLT_R033_MR350");
    mask.push_back("HLT_R038_MR200");
    mask.push_back("HLT_R038_MR250");
    mask.push_back("HLT_Mu8_R005_MR200");
    mask.push_back("HLT_Mu8_R020_MR200");
    mask.push_back("HLT_Mu8_R025_MR200");
    mask.push_back("HLT_Ele10_CaloIdL_TrkIdVL_CaloIsoVL_TrkIsoVL_R005_MR200");
    mask.push_back("HLT_Ele10_CaloIdL_TrkIdVL_CaloIsoVL_TrkIsoVL_R020_MR200");
    mask.push_back("HLT_Ele10_CaloIdL_TrkIdVL_CaloIsoVL_TrkIsoVL_R025_MR200");
  }
  if(isData) {
    SUSYInclusive vecbos(theChain, true, true);
    vecbos.setRequiredTriggers(mask);
    vecbos.Loop(string(outFileName), start, stop);  
  } else {
    SUSYTau vecbos(theChain, false, false);
    // vecbos.setRequiredTriggers(mask);
    vecbos.Loop(string(outFileName), start, stop);  
  }
#endif

#if Application == 14

  // top control sample
  TopControlSample vecbos(theChain);
  std::vector<std::string> mask;
  mask.push_back("HLT_Photon10_L1R");
  mask.push_back("HLT_Photon15_L1R");
  mask.push_back("HLT_Photon15_Cleaned_L1R");
  mask.push_back("HLT_Ele10_LW_L1R");
  mask.push_back("HLT_Ele15_SW_L1R");
  mask.push_back("HLT_Ele15_SW_CaloEleId_L1R");
  mask.push_back("HLT_Ele17_SW_CaloEleId_L1R");
  mask.push_back("HLT_Ele17_SW_TightEleId_L1R");
  mask.push_back("HLT_Ele17_SW_TighterEleIdIsol_L1R_v2");
  mask.push_back("HLT_Ele17_SW_TighterEleIdIsol_L1R_v3");

  mask.push_back("HLT_Mu9");
  mask.push_back("HLT_Mu15_v1");

  // MC triggers
//   mask.push_back("HLT_Ele15_LW_L1R");
//   mask.push_back("HLT_Mu9");
  vecbos.setRequiredTriggers(mask);
  vecbos.setPrefix(skimFileName);
  vecbos.setSignal(signal);
  vecbos.Loop();
  vecbos.displayEfficiencies();

#endif


#if Application == 15
  std::vector<std::string> mask;
  if(isData) {
    if(AnalysisSelector == 1 || AnalysisSelector == 2){

      //      mask.push_back("HLT_Mu9");
      //      mask.push_back("HLT_Mu11");
      //      mask.push_back("HLT_Mu15");                                                                        

      //Single Mu
      // mask.push_back("1-163261:HLT_Mu15_v2");
//       mask.push_back("163262-164237:HLT_Mu24_v");
//       mask.push_back("165085-999999:HLT_Mu30_v");
      //Iso Mu
           mask.push_back("1-163261:HLT_Mu15_v2");
           mask.push_back("163262-167043:HLT_IsoMu17_v");
           mask.push_back("167044-167913:HLT_IsoMu17_eta2p1_v");
           mask.push_back("170053-172949:HLT_IsoMu20_v");
      
    }else if(AnalysisSelector == 3 || AnalysisSelector == 4){
      mask.push_back("HLT_Ele10_LW_L1R");                                                                                   
      mask.push_back("HLT_Ele15_SW_L1R");
      mask.push_back("HLT_Ele15_SW_CaloEleId_L1R");
      mask.push_back("HLT_Ele17_SW_CaloEleId_L1R");
      mask.push_back("HLT_Ele17_SW_TightEleId_L1R");
      mask.push_back("HLT_Ele17_SW_TighterEleIdIsol_L1R_v2");                                                               
      mask.push_back("HLT_Ele17_SW_TighterEleIdIsol_L1R_v3");
    }
    SUSYMultiTop vecbos(theChain, true, true);
    vecbos.setRequiredTriggers(mask);
    vecbos.Loop(string(outFileName), start, stop);  
  } else {
    SUSYMultiTop vecbos(theChain, false, false);
    vecbos.SetWeight(double(weight));
    vecbos.Loop(string(outFileName), start, stop);  
  }
#endif

#if Application == 23
  std::vector<std::string> mask;
  if(isData) {
    if(AnalysisSelector == 1 || AnalysisSelector == 2){
      mask.push_back("1-163261:HLT_Mu15_v2");                                                                                                      
      mask.push_back("163262-164237:HLT_Mu24_v"); 
      mask.push_back("165085-999999:HLT_Mu30_v"); 
      
    }else if(AnalysisSelector == 3 || AnalysisSelector == 4){
      mask.push_back("HLT_Ele10_LW_L1R");
      mask.push_back("HLT_Ele15_SW_L1R");
      mask.push_back("HLT_Ele15_SW_CaloEleId_L1R");
      mask.push_back("HLT_Ele17_SW_CaloEleId_L1R");
      mask.push_back("HLT_Ele17_SW_TightEleId_L1R");
      mask.push_back("HLT_Ele17_SW_TighterEleIdIsol_L1R_v2");
      mask.push_back("HLT_Ele17_SW_TighterEleIdIsol_L1R_v3");
    }
    SUSYMultiB vecbos(theChain, true, true);
    vecbos.setRequiredTriggers(mask);
    vecbos.Loop(string(outFileName), start, stop);
  } else {
    SUSYMultiB vecbos(theChain, false, false);
    vecbos.SetWeight(double(weight));
    vecbos.Loop(string(outFileName), start, stop);
  }
#endif


#if Application == 16
  if(isData == true)
    {
      CreateWJetDataset vecbos(theChain, true, true, -1);
      std::vector<std::string> mask;
      mask.push_back("HLT_Mu15");
      mask.push_back("HLT_Mu15_v1");
      vecbos.setRequiredTriggers(mask);
      vecbos.Loop(string(outFileName), start, stop); 
    }
  else
    {
      int SelectZMuMu = -1;
      if(signal == 1)   // Z(prompt)
	SelectZMuMu = 1;
      if(signal == 3)   // Z(other)
	SelectZMuMu = 0;
      
      CreateWJetDataset vecbos(theChain, false, false, SelectZMuMu);
      std::vector<std::string> mask;
      mask.push_back("HLT_Mu15");
      mask.push_back("HLT_Mu15_v1");
      vecbos.setRequiredTriggers(mask);
      vecbos.Loop(string(outFileName), start, stop);
    }
#endif

#if Application == 17
  if(isData) {
    RazorDiPhoton vecbos(theChain, string(json), true, true);
    vecbos.Loop(string(outFileName), start, stop);
  } else {
    RazorDiPhoton vecbos(theChain,  string(json), false, false);
    vecbos.SetWeight(double(weight));
    vecbos.Loop(string(outFileName), start, stop);
  }
#endif

#if Application == 18
  std::vector<std::string> mask;
  if(isData) {
    if(RA4Selector == 1){
      mask.push_back("HLT_Mu11");
      mask.push_back("HLT_Mu5_HT70U_v3");
    }else if(RA4Selector == 2){
      mask.push_back("HLT_Ele15_SW_L1R");
      mask.push_back("HLT_Ele15_SW_CaloEleId_L1R");
      mask.push_back("HLT_Ele17_SW_CaloEleId_L1R");
      mask.push_back("HLT_Ele17_SW_TightEleId_L1R");
      mask.push_back("HLT_Ele10_SW_HT70U_L1R_v1");
      mask.push_back("HLT_Ele10_SW_HT70U_L1R_v2");
    }
    SUSYRA vecbos(theChain, true, true);
    vecbos.setRequiredTriggers(mask);
    vecbos.Loop(string(outFileName), start, stop);
  } else {
    SUSYRA vecbos(theChain, false, false);
    vecbos.Loop(string(outFileName), start, stop);
  }
#endif

#if Application == 19
  std::vector<std::string> mask;
  if(isData) {
    mask.push_back("HLT_Mu9");
    mask.push_back("HLT_Mu11");
    mask.push_back("HLT_Mu15");
    mask.push_back("HLT_Mu17");
    ZMuMu vecbos(theChain, true, true);
    vecbos.setRequiredTriggers(mask);
    vecbos.Loop(string(outFileName), start, stop);
  } else {
    ZMuMu vecbos(theChain, false, false);
    vecbos.Loop(string(outFileName), start, stop);
  }

#endif

#if Application == 20   // LQ3 Analysis
  std::vector<std::string> mask;
  if(isData == true)
  {
     LQ3Analysis Analysis(theChain, true, true);
     Analysis.setRequiredTriggers(mask);
     Analysis.Loop(string(outFileName), start, stop);
  }
  else
  {
     LQ3Analysis Analysis(theChain, false, true);
     Analysis.Loop(string(outFileName), start, stop);
  }
#endif

#if Application == 21   // VBTF Lepton Efficiencies                                                                                                                     
  std::vector<std::string> mask;
  if(isData) {
    if(AnalysisSelector == 1 || AnalysisSelector == 2){
      mask.push_back("HLT_Mu9");
      mask.push_back("HLT_Mu11");
      mask.push_back("HLT_Mu15");
    }else if(AnalysisSelector == 3 || AnalysisSelector == 4){
      mask.push_back("HLT_Ele10_LW_L1R");
      mask.push_back("HLT_Ele15_SW_L1R");
      mask.push_back("HLT_Ele15_SW_CaloEleId_L1R");
      mask.push_back("HLT_Ele17_SW_CaloEleId_L1R");
      mask.push_back("HLT_Ele17_SW_TightEleId_L1R");
      mask.push_back("HLT_Ele17_SW_TighterEleIdIsol_L1R_v2");
      mask.push_back("HLT_Ele17_SW_TighterEleIdIsol_L1R_v3");
    }
    VBTFLeptEff vecbos(theChain, true, true);
    vecbos.setRequiredTriggers(mask);
    vecbos.Loop(string(outFileName), start, stop);
  } else {
    VBTFLeptEff vecbos(theChain, false, false);
    vecbos.Loop(string(outFileName), start, stop);
  }

#endif

#if Application == 22
  if(isData) {
    RazorLeptons vecbos(theChain, string(json), true, true);
    vecbos.Loop(string(outFileName), start, stop);
  } else {
    RazorLeptons vecbos(theChain, string(json), false, false);
    vecbos.Loop(string(outFileName), start, stop);
  }
#endif

#if Application == 24
  if(isData) {
    RazorHiggsBB vecbos(theChain, string(json), true, true);
    vecbos.Loop(string(outFileName), start, stop);
  } else {
    RazorHiggsBB vecbos(theChain, string(json), false, false);
    vecbos.Loop(string(outFileName), start, stop);
  }
#endif

#if Application == 25
  if(isData) {
    RazorBoostedTop vecbos(theChain, string(json), true, true);
    vecbos.Loop(string(outFileName), start, stop);
  } else {
    int model=-1;
    const int nModels=7;
    const char *models[nModels] = {"mSUGRA","T1bbbb","T2bb","T2tt","T1tttt","T2","T1"};
    int modNameLen[nModels] = {6,6,4,4,6,2,2};
    
    for(int i=0;i<nModels;i++){
      if(strstr(inputFileName,models[i])){
	model=i; break;
      }
    }
    RazorBoostedTop vecbos(theChain, string(json), false, false,model);
    vecbos.Loop(string(outFileName), start, stop);
  }
#endif

#if Application == 26
  std::vector<std::string> mask;
  if(isData) {
    if(AnalysisSelector == 1 || AnalysisSelector == 2){
      mask.push_back("1-163261:HLT_Mu15_v2");
      mask.push_back("163262-164237:HLT_Mu24_v");
      mask.push_back("165085-999999:HLT_Mu30_v");

    }else if(AnalysisSelector == 3 || AnalysisSelector == 4){
      mask.push_back("HLT_Ele10_LW_L1R");
      mask.push_back("HLT_Ele15_SW_L1R");
      mask.push_back("HLT_Ele15_SW_CaloEleId_L1R");
      mask.push_back("HLT_Ele17_SW_CaloEleId_L1R");
      mask.push_back("HLT_Ele17_SW_TightEleId_L1R");
      mask.push_back("HLT_Ele17_SW_TighterEleIdIsol_L1R_v2");
      mask.push_back("HLT_Ele17_SW_TighterEleIdIsol_L1R_v3");
    }
    SF_Filler vecbos(theChain, true, true);
    vecbos.setRequiredTriggers(mask);
    vecbos.Loop(string(outFileName), start, stop);
  } else {
    SF_Filler vecbos(theChain, false, false);
    vecbos.SetWeight(double(weight));
    vecbos.Loop(string(outFileName), start, stop);
  }
#endif

#if Application == 27
  std::vector<std::string> mask;
  if(isData) {
    if(AnalysisSelector == 1 || AnalysisSelector == 2){
      mask.push_back("1-163261:HLT_Mu15_v2");
      mask.push_back("163262-164237:HLT_Mu24_v");
      mask.push_back("165085-999999:HLT_Mu30_v");

    }else if(AnalysisSelector == 3 || AnalysisSelector == 4){
      mask.push_back("HLT_Ele10_LW_L1R");
      mask.push_back("HLT_Ele15_SW_L1R");
      mask.push_back("HLT_Ele15_SW_CaloEleId_L1R");
      mask.push_back("HLT_Ele17_SW_CaloEleId_L1R");
      mask.push_back("HLT_Ele17_SW_TightEleId_L1R");
      mask.push_back("HLT_Ele17_SW_TighterEleIdIsol_L1R_v2");
      mask.push_back("HLT_Ele17_SW_TighterEleIdIsol_L1R_v3");
    }
    H4b vecbos(theChain, true, true);
    vecbos.setRequiredTriggers(mask);
    vecbos.Loop(string(outFileName), start, stop);
  } else {
    H4b vecbos(theChain, false, false);
    vecbos.SetWeight(double(weight));
    vecbos.Loop(string(outFileName), start, stop);
  }
#endif


  system("rm thisiswhyitcrashed*");

  return 0;

}
예제 #6
0
int
Fitfraction(){
   ofstream myfile;
   myfile.open("JetFakeRate-mg-2016.txt");
   std::ostringstream hadfrac;
   hadfrac.str("");

  double IsoCutLower[]={3.32,3.42,3.52,3.62,3.72,3.82,3.92,4.02,4.12,4.22,4.32,4.42,4.52,4.62,4.72,4.82,4.92};
  double IsoCutUpper[]={12,12.5,13,13.5,14,14.5,15,15.5,16,16.5,17,17.5,18};
  unsigned nUpper = sizeof(IsoCutUpper)/sizeof(double);
  unsigned nLower = sizeof(IsoCutLower)/sizeof(double);
  //int PtBins[]=  {25,30,35,45,55,70,90};
  int PtBins[]=  {25,28,30,34,38,42,46,50,54,58,62,66,70,75,80,90,100,120,140};
  unsigned nSet = sizeof(PtBins)/sizeof(int);
  TH1F* h_data[nSet][nLower][nUpper]; 
  TH1F* h_bg[nSet][nLower][nUpper];
  TH1F* h_target[nSet][nLower][nUpper];
  TObjArray *templatelist[nSet][nLower][nUpper];
  TFractionFitter* fitter[nSet][nLower][nUpper];
  TH1F* result[nSet][nLower][nUpper];
  TCanvas *can[nSet][nLower][nUpper];
  std::ostringstream hname;

  TFile *outputfile = TFile::Open("hadfraction.root","NEW");
  outputfile->cd();
  TH2F* fracHad2D[nSet];
  TH1F* fracHad1D[nSet];
  for(unsigned iF(0); iF<nSet; iF++){
	hname.str("");
	hname << "fracHad2D_" << iF;
	fracHad2D[iF]=new TH2F(hname.str().c_str(),hname.str().c_str(),17,3.3,5,13,12,18);
	hname.str("");
    hname << "fracHad1D_" << iF;
    fracHad1D[iF]=new TH1F(hname.str().c_str(),hname.str().c_str(),100,0,0.4);
  } 
//************ Signal Tree **********************//
  TChain *egtree = new TChain("egTree");
  egtree->Add("../data/plot_hadron_2016.root");
  float eg_phoEt(0);
  float eg_phoSigma(0);
  float eg_phoChIso(0);
  
  egtree->SetBranchAddress("phoEt",     &eg_phoEt);
  egtree->SetBranchAddress("phoSigma",  &eg_phoSigma);
  egtree->SetBranchAddress("phoChIso",  &eg_phoChIso);

  TChain *mgtree = new TChain("mgTree","mgTree");
  mgtree->Add("../data/plot_hadron_2016.root");
  float mg_phoEt(0);
  float mg_phoSigma(0);
  float mg_phoChIso(0);
  
  mgtree->SetBranchAddress("phoEt",     &mg_phoEt);
  mgtree->SetBranchAddress("phoSigma",  &mg_phoSigma);
  mgtree->SetBranchAddress("phoChIso",  &mg_phoChIso);

  TChain *hadtree = new TChain("hadTree","hadTree");
  hadtree->Add("../data/plot_hadron_2016.root");
  float had_phoEt(0);
  float had_phoSigma(0);
  float had_phoChIso(0);
  
  hadtree->SetBranchAddress("phoEt",     &had_phoEt);
  hadtree->SetBranchAddress("phoSigma",  &had_phoSigma);
  hadtree->SetBranchAddress("phoChIso",  &had_phoChIso);

  TChain *Zeetree = new TChain("ZeeTree");
  Zeetree->Add("../data/plotZ_DoubleMu2016.root");
  float phoEt(0);
  float phoSigma(0);
  float invmass(0);
  bool  ismg(0); 
 
  Zeetree->SetBranchAddress("phoEt",     &phoEt);
  Zeetree->SetBranchAddress("phoSigma",  &phoSigma);
  Zeetree->SetBranchAddress("invmass",   &invmass);
  Zeetree->SetBranchAddress("ismg",      &ismg);

  double fittingError[nSet];
  double systematicError[nSet];
  for(unsigned iF(0); iF<nSet; iF++){ fittingError[iF] = 0; systematicError[iF] = 0;}

  for(unsigned iUpper(0); iUpper<nUpper; iUpper++){
    for(unsigned iLower(0); iLower<nLower; iLower++){
	  for(unsigned iF(0); iF<nSet; iF++){
		templatelist[iF][iLower][iUpper] = new TObjArray(2);
		hname.str("");
		hname << "can" << iF << "_" << IsoCutLower[iLower] << "_" << IsoCutUpper[iUpper] ;
		can[iF][iLower][iUpper]=new TCanvas(hname.str().c_str(),hname.str().c_str(),600,600);
		hname.str("");
        if(iF==nSet-1)hname << "p_SigmaZ-pt-140-inf" << "_" << IsoCutLower[iLower] << "_" << IsoCutUpper[iUpper];
        else hname <<"p_SigmaZ-pt-" << PtBins[iF] << "-" << PtBins[iF+1] << "_" << IsoCutLower[iLower] << "_" << IsoCutUpper[iUpper];
		h_data[iF][iLower][iUpper] = new TH1F(hname.str().c_str(), hname.str().c_str(), 40, 0.0, 0.02); 
		hname.str("");
		if(iF==nSet-1)hname<< "SigmaHadEB-pt-140-inf" << "_" << IsoCutLower[iLower] << "_" << IsoCutUpper[iUpper];
		else hname <<"SigmaHadEB-pt-" <<  PtBins[iF] << "-" << PtBins[iF+1] << "_" << IsoCutLower[iLower] << "_" << IsoCutUpper[iUpper];
		h_bg[iF][iLower][iUpper] = new TH1F(hname.str().c_str(), hname.str().c_str(), 40, 0.0, 0.02);
		hname.str("");
		if(iF==nSet-1)hname<< "p_SigmaTarEB-pt-140-inf" << "_" << IsoCutLower[iLower] << "_" << IsoCutUpper[iUpper];
		else hname <<"p_SigmaTarEB-pt-" <<  PtBins[iF] << "-" << PtBins[iF+1]<< "_" << IsoCutLower[iLower] << "_" << IsoCutUpper[iUpper];
		h_target[iF][iLower][iUpper] = new TH1F(hname.str().c_str(), hname.str().c_str(),40, 0.0, 0.02);    

        for(unsigned ievt(0); ievt < Zeetree->GetEntries(); ievt++){
          Zeetree->GetEntry(ievt);
          if(invmass > 70 && invmass < 110 && ismg){
			if(PtBins[iF] < 50){
			  if(phoEt >= PtBins[iF] && phoEt < PtBins[iF+1])h_data[iF][iLower][iUpper]->Fill(phoSigma);
			}else{
              if(phoEt >= 50)h_data[iF][iLower][iUpper]->Fill(phoSigma);
			}
          }
        }
 
		double nden(0), totalden(0);
		double nnum(0), totalnum(0);
		for(unsigned ievt(0); ievt < mgtree->GetEntries(); ievt++){
		  mgtree->GetEntry(ievt);
		  if(iF!= nSet-1){
			if(mg_phoEt >= PtBins[iF] && mg_phoEt < PtBins[iF+1]){
			  if(mg_phoChIso <= 3.32){
                h_target[iF][iLower][iUpper]->Fill(mg_phoSigma);
                totalden+=1;
                if(mg_phoSigma < 0.0103)nden+=1;
              }
			}
		  }else{
			if(mg_phoEt >= PtBins[iF]){
			  if(mg_phoChIso <= 3.32){
                h_target[iF][iLower][iUpper]->Fill(mg_phoSigma);
                totalden+=1;
                if(mg_phoSigma < 0.0103)nden+=1;
              }
			}
		  }
		}

		for(unsigned ievt(0); ievt < mgtree->GetEntries(); ievt++){
		  mgtree->GetEntry(ievt);
		  if(iF!= nSet-1){
			if(mg_phoEt >= PtBins[iF] && mg_phoEt < PtBins[iF+1]){
			  if(mg_phoChIso > IsoCutLower[iLower] && mg_phoChIso < IsoCutUpper[iUpper]){
                h_bg[iF][iLower][iUpper]->Fill(mg_phoSigma);
                totalnum+=1;
                if(mg_phoSigma < 0.0103)nnum+=1;
              }
			}
		  }else{
			if(mg_phoEt >= PtBins[iF]){
			  if(mg_phoChIso > IsoCutLower[iLower] && mg_phoChIso < IsoCutUpper[iUpper]){
                h_bg[iF][iLower][iUpper]->Fill(mg_phoSigma);
                totalnum+=1;
                if(mg_phoSigma < 0.0103)nnum+=1;
              }
			}
		  }
		}
		double den = nden/totalden; 
		double denerror = (1.0/sqrt(nden)+ 1.0/sqrt(totalden))*den;
		double num = nnum/totalnum; 
		double numerror = (1.0/sqrt(nnum) + 1.0/sqrt(totalnum))*num;
		myfile << "pt=" << PtBins[iF] << " " <<  IsoCutLower[iLower] << " < Iso < " << IsoCutUpper[iUpper] <<  " numIntegral/entries = " << num << std::endl; 

		templatelist[iF][iLower][iUpper]->Add(h_data[iF][iLower][iUpper]);
		templatelist[iF][iLower][iUpper]->Add(h_bg[iF][iLower][iUpper]);
		fitter[iF][iLower][iUpper]= new TFractionFitter(h_target[iF][iLower][iUpper], templatelist[iF][iLower][iUpper], "V");
		fitter[iF][iLower][iUpper]->SetRangeX(3,32);
		fitter[iF][iLower][iUpper]->Constrain(1,0.0,1.0);
		Int_t status = fitter[iF][iLower][iUpper]->Fit();
		if(status == 0){
		  result[iF][iLower][iUpper] = (TH1F*)fitter[iF][iLower][iUpper]->GetPlot();
          result[iF][iLower][iUpper]->SetMinimum(0);
		  double fracBkg, errorBkg;
		  double fracSig, errorSig;
		  fitter[iF][iLower][iUpper]->GetResult(0, fracSig, errorSig);
		  fitter[iF][iLower][iUpper]->GetResult(1, fracBkg, errorBkg);
		  can[iF][iLower][iUpper]->cd();
		  h_target[iF][iLower][iUpper]->GetXaxis()->SetRangeUser(0.006,0.02);
		  h_target[iF][iLower][iUpper]->SetMarkerStyle(20);
		  h_target[iF][iLower][iUpper]->Draw("Ep");
		  result[iF][iLower][iUpper]->SetLineColor(kBlue);
		  result[iF][iLower][iUpper]->SetFillStyle(1001);
		  result[iF][iLower][iUpper]->SetFillColor(kBlue);
		  result[iF][iLower][iUpper]->Draw("same");
		  h_bg[iF][iLower][iUpper]->Scale(1.0/h_bg[iF][iLower][iUpper]->GetEntries()*h_target[iF][iLower][iUpper]->GetEntries()*fracBkg);
		  h_bg[iF][iLower][iUpper]->SetLineColor(kGreen);
		  h_bg[iF][iLower][iUpper]->SetFillStyle(1001);
		  h_bg[iF][iLower][iUpper]->SetFillColor(kGreen);
		  h_bg[iF][iLower][iUpper]->Draw("same");
		  h_target[iF][iLower][iUpper]->Draw("Ep same");
		  TLatex* latex = new TLatex();
		  hname.str("");
		  hname << "Bkg% = " << fracBkg << " #pm " << errorBkg << std::endl;
		  latex->DrawLatex(0.01,0.9*h_target[iF][iLower][iUpper]->GetMaximum(),hname.str().c_str()); 
		  hname.str("");
		  hname << "#chi^{2}/ndof = " << fitter[iF][iLower][iUpper]->GetChisquare() << "/" << fitter[iF][iLower][iUpper]->GetNDF(); 
		  latex->DrawLatex(0.01,0.8*h_target[iF][iLower][iUpper]->GetMaximum(),hname.str().c_str());
		  hname.str("");
		  hname << "frac=" << num << "*" << fracBkg << "/" << den << std::endl;
		  latex->DrawLatex(0.01,0.7*h_target[iF][iLower][iUpper]->GetMaximum(),hname.str().c_str());
		  hname.str("");
		  hname << " =" << num*fracBkg/den << " #pm " << (numerror/num + denerror/den + errorBkg/fracBkg)*num*fracBkg/den;
		  latex->DrawLatex(0.01,0.6*h_target[iF][iLower][iUpper]->GetMaximum(),hname.str().c_str());
		 
		  if(IsoCutLower[iLower] == 3.32 && IsoCutUpper[iUpper]==15.0){
            hadfrac << num*fracBkg/den << ",";
		    fittingError[iF] = (numerror/num + denerror/den + errorBkg/fracBkg)*num*fracBkg/den ;
          }
		  myfile << "frac = " << fracBkg << std::endl;
          fracHad2D[iF]->Fill(IsoCutLower[iLower], IsoCutUpper[iUpper], num*fracBkg/den);
          fracHad1D[iF]->Fill(num*fracBkg/den); 
		} 
		 
		hname.str("");
		hname << "frac" << iF << "_" << IsoCutLower[iLower] << "_" << IsoCutUpper[iUpper] << ".pdf";
		if(IsoCutLower[iLower] == 3.32 && IsoCutUpper[iUpper]==15.0)can[iF][iLower][iUpper]->SaveAs(hname.str().c_str());

	  }
    }
  }
  myfile << hadfrac.str().c_str() << std::endl;
  for(unsigned iF(0); iF < nSet; iF++)systematicError[iF] =  fracHad1D[iF]->GetMeanError();
  for(unsigned iF(0); iF < nSet; iF++)myfile << sqrt(fittingError[iF]*fittingError[iF] + systematicError[iF]*systematicError[iF]) << ",";
  myfile.close();
  outputfile->Write();
  return 1;
}
예제 #7
0
파일: drawE.C 프로젝트: phuo/Glauber
void drawE(){
    TChain* t = new TChain("t");
    char dfilelist[100];
    char name[100];
    sprintf(dfilelist,"outlist.txt");
    ifstream lis(dfilelist);
    int cnt=0;
    int dnt=0;
    while(!lis.eof())
    {
        string filename;
        lis >> filename;
        if(cnt>=0&&cnt<100)
        {
            cout << filename << endl;
            if(!filename.empty()) t->Add(filename.c_str());
            dnt++;
        }
        cnt++;
    }

    double fAngGl[ETOT],feGl[ETOT];
    double frAngGl[ETOT],freGl[ETOT];

    double pfAngGl[ETOT],pfeGl[ETOT];
    double pfrAngGl[ETOT],pfreGl[ETOT];

    double b;
    int ncoll;
    int npart,npartproj,nparttarg;
    int nHitBbc_n, nHitBbc_s, BBCTrig;
    int Centbin;
    double qBBC_n, qBBC_s, pTrigBBC;
    double vertex, ecc_std,ecc_rp, ecc_part,ecc_partr,r_ollitra,r_geo,r_arith,r_ollitrar,r_geor,r_arithr,e4;


    float nux[600] ;
    float nuy[600] ;
    int  st_part[600] ;

    t->SetBranchAddress("b",            &b);
    t->SetBranchAddress("Centbin",   &Centbin);
    t->SetBranchAddress("ncoll",        &ncoll);
    t->SetBranchAddress("npart",        &npart);
    /*    t->SetBranchAddress("npartproj",    &npartproj);
          t->SetBranchAddress("nparttarg",    &nparttarg);
          t->SetBranchAddress("ecc_std",      &ecc_std);
          t->SetBranchAddress("ecc_rp",       &ecc_rp);
          t->SetBranchAddress("ecc_part",     &ecc_part);

          t->SetBranchAddress("e_gl",         feGl);
          t->SetBranchAddress("ang_gl",    fAngGl);
          t->SetBranchAddress("re_gl",       freGl);
          t->SetBranchAddress("rang_gl", frAngGl);

          t->SetBranchAddress("nux", &nux);
          t->SetBranchAddress("nuy", &nuy);
          t->SetBranchAddress("st_part",&st_part);

          t->SetBranchAddress("pe_gl",        pfeGl);
          t->SetBranchAddress("pang_gl",      pfAngGl);
          */
    t->SetBranchAddress("pre_gl",       pfreGl);
    t->SetBranchAddress("prang_gl",     pfrAngGl);

    cout<<t->GetEntries()/1000000<<endl;

    TH1* hevent[7];
    for(int ic=0;ic<7; ic++){
   sprintf(name, "hevent%d", ic); 
    hevent[ic]= new TH1D(name, name,10, 0-0.5, 50-0.5);
    }


    for(int iev=0; iev<t->GetEntries(); iev++){
        t->GetEntry(iev);
        if(iev%10000000==0) cout<<iev<<endl;
        if(Centbin!=0) continue;
        int Ebin[6] = {-1,-1,-1,-1,-1,-1};
        int cutID[7] = {0,0,0,0,0,0,0};
        for(int ih=0;ih<6; ih++){ //iHar bin
            Ebin[ih] = findEbin(Centbin, pfreGl[ih], ih);
        }
        if(Ebin[5]<10 && Ebin[1]<10 && Ebin[2]<10 && Ebin[3]<10 && Ebin[4]<10) cutID[0] = 1;
        if(Ebin[0]<10 && Ebin[5]<10 && Ebin[2]<10 && Ebin[3]<10 && Ebin[4]<10) cutID[1] = 1;
        if(Ebin[0]<10 && Ebin[1]<10 && Ebin[5]<10 && Ebin[3]<10 && Ebin[4]<10) cutID[2] = 1;
        if(Ebin[0]<10 && Ebin[1]<10 && Ebin[2]<10 && Ebin[5]<10 && Ebin[4]<10) cutID[3] = 1;
        if(Ebin[0]<10 && Ebin[1]<10 && Ebin[2]<10 && Ebin[3]<10 && Ebin[5]<10) cutID[4] = 1;
        if(Ebin[0]<10 && Ebin[1]<10 && Ebin[2]<10 && Ebin[3]<10 && Ebin[4]<10) cutID[5] = 1;
        cutID[6] = 1;

        for(int i=0; i<6; i++){
            if(cutID[i] == 1) hevent[i]->Fill(Ebin[i]);
        }
    }
    //hevent->DrawClone();
    for(int i=0;i<6; i++){
    hevent[i]->Scale(1.0/hevent[i]->GetEntries());

        for(int ib=0; ib<10; ib++){
        cout<<hevent[i]->GetBinContent(ib+1)<<"  ";
        }
        cout<<endl;
    }
    /*  gStyle->SetOptStat(0);

        TLatex ptext;

        ptext.SetNDC(1);
        ptext.SetTextFont(43);
        ptext.SetTextSize(15.5);
        ptext.SetTextColor(2);


        gStyle->SetOptTitle(0);
        TH2* hist = new TH2D("hist", "hist", 104, -13, 13, 104, -13, 13);
        TCanvas* c1 = new TCanvas("c1","c1", 400*3, 400*2);
        c1->Divide(3,2);
        int ccnt=0;
        double rg[] = {0.12,0.2,0.2,0.2,0.2,0.3,0.3};
        double rg2[] = {0.05, 0.05, 0.05, 0.05,0.05, 0.05};

        for(int iev=0; iev<t->GetEntries(); iev++){
        t->GetEntry(iev);
        if(iev%100000==0) cout<<iev<<endl;

        if(ccnt==6) break;
        if(b>6) continue;
        if(fabs(pfreGl[ccnt] - rg[ccnt]) >0.02) continue;
        int badd=0;
        for(int ij=0;ij<6; ij++){
        if(ij==ccnt) continue;
        if(pfreGl[ij] > rg2[ij]) badd=1;
        }
        if(badd==1) continue;
        cout<<b<<"  "<<pfreGl[ccnt]<<"  "<<fabs(pfreGl[ccnt] - rg[ccnt])<<"  "<< rg[ccnt]<<"  "<<ccnt<<endl;
        c1->cd(ccnt+1);
        hist->Draw();
        Double_t r = 0.5*sqrt(64/TMath::Pi()/10.);
        TEllipse e;

// cout<<nux->size()<<endl;
for(int in=0; in<600; in++){
e.SetLineColor(kBlack);
e.SetFillColor(0);
e.SetLineWidth(1);
e.SetFillStyle(0);
if(abs(st_part[in])!=1) continue;
e.DrawEllipse(nux[in],nuy[in],r,r,0,360,0,"same");
    //   cout<<nux[in]<<endl;
    }

    TEllipse e1;
    for(int in=0; in<600; in++){
    e1.SetLineColor(kBlack);
    if(st_part[in]==0) continue;
    if(abs(st_part[in])==2)  {
    e1.SetLineStyle(1);
    e1.SetFillStyle(0);
    //      e1.SetFillColor(kGreen);
    if(st_part[in]==2)  e1.SetLineColor(kBlue);
    if(st_part[in]==-2)  e1.SetLineColor(kRed);
    e1.DrawEllipse(nux[in],nuy[in],r,r,0,360,0,"same");
    }
    //   cout<<nux[in]<<endl;
    }
    sprintf(name, "b = %4.2f", b);
    ptext.DrawLatex(0.8, 0.67,name);
    for(int i=0; i<6; i++){
    sprintf(name, "#epsilon_{%d}=%4.2f", i+1, pfreGl[i]);
    ptext.DrawLatex(0.8, 0.7+i*0.04,name);
    }
    e.SetFillColor(0);
    e.SetFillStyle(0);
    e.SetLineColor(1);
e.SetLineStyle(2);
e.SetLineWidth(1);
e.DrawEllipse(b/2,0,6.62,6.62,0,360,0,"same");
e.DrawEllipse(-b/2,0,6.62,6.62,0,360,0,"same");

ccnt++;
}
*/

}
예제 #8
0
void CPVanalysis(const TString dataset="")
{
    
  gSystem->Load("libTree");
  gSystem->Load("libGeom");
  gSystem->Load("libVMC");
  gSystem->Load("libPhysics");
  
  //load analysis framework
  gSystem->Load("libANALYSIS");
  gSystem->Load("libANALYSISalice"); //AliAnalysisTaskSE
  
  gSystem->AddIncludePath("-I$ALICE_ROOT/include -I$ALICE_ROOT/PHOS");

  // A task can be compiled dynamically with AClic
  gROOT->LoadMacro("AliAnalysisTaskCPV.cxx+g");
  
  // Connect to alien
  TString token = gSystem->Getenv("GRID_TOKEN") ;
  token="OK";
  if ( token == "OK" ) 
    TGrid::Connect("alien://");
  else 
    Printf("You are not connected to the GRID") ; 
    // AliInfo("You are not connected to the GRID") ; 

  cout << "CPVanalysis: processing collection " << dataset << endl;
  
  // Create the chain
    TChain* chain;

  if (dataset.Contains(".txt")) {
    gROOT->LoadMacro("$ALICE_PHYSICS/PWG/EMCAL/macros/CreateESDChain.C");
    chain = CreateESDChain(dataset.Data(), 1000);
  }
  else if (dataset.Contains(".xml")) {
    chain = new TChain("esdTree");
    TGridCollection * collection = dynamic_cast<TGridCollection*>(TAlienCollection::Open(dataset));
  
    TAlienResult* result = collection->GetGridResult("",0 ,0);
    TList* rawFileList = result->GetFileInfoList();
    
    for (Int_t counter=0 ; counter < rawFileList->GetEntries() ; counter++) {
      TFileInfo * fi =  static_cast<TFileInfo*>(rawFileList->At(counter)) ; 
      const char * rawFile = fi->GetCurrentUrl()->GetUrl() ;  
      printf("Processing %s\n", rawFile) ;
      chain->Add(rawFile);
      printf("Chain: %d entries.\n",chain->GetEntries()); 
    }
  }
  
  // Make the analysis manager
  AliAnalysisManager *mgr = new AliAnalysisManager("CPVanalysis");
  
  // ESD input handler
  AliESDInputHandler* esdH = new AliESDInputHandler();
  esdH->SetReadFriends(kFALSE);
  mgr->SetInputEventHandler(esdH);
  
  // Debug level
  mgr->SetDebugLevel(0);
  
  //PID task
  gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPIDResponse.C");
  AliAnalysisTask *taskPID =  AddTaskPIDResponse(/*Bool_t isMC=*/ kFALSE, /*Bool_t autoMCesd=*/kTRUE,
						 /*Bool_t tuneOnData=*/kTRUE);

  // // Add physics selection
  gROOT->LoadMacro("$ALICE_PHYSICS/OADB/macros/AddTaskPhysicsSelection.C");
  AliPhysicsSelectionTask* physSelTask = AddTaskPhysicsSelection();
  physSelTask->GetPhysicsSelection()->SetUseBXNumbers(kFALSE);// ---> ???

  // Add my task
  AliAnalysisTaskCPV *task1 = new AliAnalysisTaskCPV("CPVanalysis");

  // task1->SelectCollisionCandidates(AliVEvent::kMB);
  mgr->AddTask(task1);
  
  // Create containers for input/output
  AliAnalysisDataContainer *cinput   = mgr->GetCommonInputContainer(); 
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("histCPV1",TList::Class(),AliAnalysisManager::kOutputContainer,"CPVanalysis.root");
  AliAnalysisDataContainer *coutput2 = mgr->CreateContainer("histCPV2",TList::Class(),AliAnalysisManager::kOutputContainer,"CPVanalysis.root");

  ((AliInputEventHandler*)mgr->GetInputEventHandler())->SetNeedField(1);


  // Connect input/output
  mgr->ConnectInput(task1 , 0, cinput);
  mgr->ConnectOutput(task1, 1, coutput1);
  mgr->ConnectOutput(task1, 2, coutput2);
  
  if (mgr->InitAnalysis()) {
    mgr->PrintStatus();
    mgr->StartAnalysis("local", chain);
  }
  
}
예제 #9
0
파일: hadd.C 프로젝트: Y--/root
void MergeRootfile( TDirectory *target, TList *sourcelist ) {

   //  cout << "Target path: " << target->GetPath() << endl;
   TString path( (char*)strstr( target->GetPath(), ":" ) );
   path.Remove( 0, 2 );

   TFile *first_source = (TFile*)sourcelist->First();
   first_source->cd( path );
   TDirectory *current_sourcedir = gDirectory;
   //gain time, do not add the objects in the list in memory
   Bool_t status = TH1::AddDirectoryStatus();
   TH1::AddDirectory(kFALSE);

   // loop over all keys in this directory
   TChain *globChain = 0;
   TIter nextkey( current_sourcedir->GetListOfKeys() );
   TKey *key, *oldkey=0;
   while ( (key = (TKey*)nextkey())) {

      //keep only the highest cycle number for each key
      if (oldkey && !strcmp(oldkey->GetName(),key->GetName())) continue;

      // read object from first source file
      first_source->cd( path );
      TObject *obj = key->ReadObj();

      if ( obj->IsA()->InheritsFrom( TH1::Class() ) ) {
         // descendant of TH1 -> merge it

         //      cout << "Merging histogram " << obj->GetName() << endl;
         TH1 *h1 = (TH1*)obj;

         // loop over all source files and add the content of the
         // correspondant histogram to the one pointed to by "h1"
         TFile *nextsource = (TFile*)sourcelist->After( first_source );
         while ( nextsource ) {

            // make sure we are at the correct directory level by cd'ing to path
            nextsource->cd( path );
            TKey *key2 = (TKey*)gDirectory->GetListOfKeys()->FindObject(h1->GetName());
            if (key2) {
               TH1 *h2 = (TH1*)key2->ReadObj();
               h1->Add( h2 );
               delete h2;
            }

            nextsource = (TFile*)sourcelist->After( nextsource );
         }
      }
      else if ( obj->IsA()->InheritsFrom( TTree::Class() ) ) {

         // loop over all source files create a chain of Trees "globChain"
         const char* obj_name= obj->GetName();

         globChain = new TChain(obj_name);
         globChain->Add(first_source->GetName());
         TFile *nextsource = (TFile*)sourcelist->After( first_source );
         //      const char* file_name = nextsource->GetName();
         // cout << "file name  " << file_name << endl;
         while ( nextsource ) {

            globChain->Add(nextsource->GetName());
            nextsource = (TFile*)sourcelist->After( nextsource );
         }

      } else if ( obj->IsA()->InheritsFrom( TDirectory::Class() ) ) {
         // it's a subdirectory

         cout << "Found subdirectory " << obj->GetName() << endl;

         // create a new subdir of same name and title in the target file
         target->cd();
         TDirectory *newdir = target->mkdir( obj->GetName(), obj->GetTitle() );

         // newdir is now the starting point of another round of merging
         // newdir still knows its depth within the target file via
         // GetPath(), so we can still figure out where we are in the recursion
         MergeRootfile( newdir, sourcelist );

      } else {

         // object is of no type that we know or can handle
         cout << "Unknown object type, name: "
         << obj->GetName() << " title: " << obj->GetTitle() << endl;
      }

      // now write the merged histogram (which is "in" obj) to the target file
      // note that this will just store obj in the current directory level,
      // which is not persistent until the complete directory itself is stored
      // by "target->Write()" below
      if ( obj ) {
         target->cd();

         //!!if the object is a tree, it is stored in globChain...
         if(obj->IsA()->InheritsFrom( TTree::Class() ))
            globChain->Merge(target->GetFile(),0,"keep");
         else
            obj->Write( key->GetName() );
      }

   } // while ( ( TKey *key = (TKey*)nextkey() ) )

   // save modifications to target file
   target->SaveSelf(kTRUE);
   TH1::AddDirectory(status);
}
예제 #10
0
int main( int argc, char* argv[] ) {


  std::string runName = "precalib_BGO_pedestal_noSource";
  if( argc>1 ) {
    std::string runName_str(argv[1]);
    runName = runName_str;
  }

  std::string tag = "V00";
  if( argc>2 ) {
    std::string tag_str(argv[2]);
    tag = tag_str;
  }

  TString runName_tstr(runName);
  bool isOnlyRunNumber = !(runName_tstr.BeginsWith("BTF_"));


  TChain* tree = new TChain("recoTree");
  if( isOnlyRunNumber ) {
    std::cout << "-> We believe you are passing the program only the run number!" << std::endl;
    std::cout << "-> So for instance you are passing '246' for run 'BTF_246_20140501-212512_beam'" << std::endl;
    std::cout << "(if this is not the case this means TROUBLE)" << std::endl;
    std::cout << "-> Will look for runs matching run number: " << runName << std::endl;
    tree->Add(Form("analysisTrees_%s/Reco_BTF_%s_*beam.root/recoTree", tag.c_str(), runName.c_str()) );
    if( tree->GetEntries()==0 ) {
      std::cout << "WARNING! Didn't find any events matching run: " << runName << std::endl;
      std::cout << "Exiting" << std::endl;
      exit(1913);
    }
  } else {
    std::string fileName = "analysisTrees_"+tag+"/Reco_" + runName + ".root";
    TFile* file = TFile::Open(fileName.c_str());
    if( file==0 ) {
      std::cout << "ERROR! Din't find file " << fileName << std::endl;
      std::cout << "Exiting." << std::endl;
      exit(11);
    }
    tree = (TChain*)file->Get("recoTree");
  }





  UInt_t evtNumber;
  tree->SetBranchAddress( "evtNumber", &evtNumber );
  UInt_t adcData[40];
  tree->SetBranchAddress( "adcData", adcData );
  UInt_t adcBoard[40];
  tree->SetBranchAddress( "adcBoard", adcBoard );
  UInt_t adcChannel[40];
  tree->SetBranchAddress( "adcChannel", adcChannel );


  unsigned int runNumber;
  int nHodoFibersX;
  int nHodoFibersY;
  int nHodoClustersX;
  int nHodoClustersY;
  float cef3_corr[CEF3_CHANNELS];
  float bgo_corr[BGO_CHANNELS];
  float scintFront;
  float pos_hodoClustX[HODOX_CHANNELS];
  float pos_hodoClustY[HODOY_CHANNELS];
  int nFibres_hodoClustX[HODOX_CHANNELS];
  int nFibres_hodoClustY[HODOY_CHANNELS];
  float xBeam, yBeam;
  bool isSingleEle_scintFront;
  bool cef3_ok;
  bool cef3_corr_ok;
  bool bgo_ok;
  bool bgo_corr_ok;

  tree->SetBranchAddress( "runNumber", &runNumber );

  tree->SetBranchAddress( "scintFront", &scintFront );
  tree->SetBranchAddress( "cef3_corr", cef3_corr );
  tree->SetBranchAddress( "bgo_corr", bgo_corr );

  tree->SetBranchAddress( "nHodoFibersX", &nHodoFibersX );
  tree->SetBranchAddress( "nHodoFibersY", &nHodoFibersY );
  tree->SetBranchAddress( "nHodoClustersX", &nHodoClustersX );
  tree->SetBranchAddress( "pos_hodoClustX", pos_hodoClustX );
  tree->SetBranchAddress( "nFibres_hodoClustX", nFibres_hodoClustX );
  tree->SetBranchAddress( "nHodoClustersY", &nHodoClustersY );
  tree->SetBranchAddress( "pos_hodoClustY", pos_hodoClustY );
  tree->SetBranchAddress( "nFibres_hodoClustY", nFibres_hodoClustY );
  tree->SetBranchAddress( "scintFront", &scintFront );
  tree->SetBranchAddress( "isSingleEle_scintFront", &isSingleEle_scintFront );
  tree->SetBranchAddress( "xBeam", &xBeam );
  tree->SetBranchAddress( "yBeam", &yBeam );

  tree->SetBranchAddress( "cef3_ok", &cef3_ok );
  tree->SetBranchAddress( "cef3_corr_ok", &cef3_corr_ok );
  tree->SetBranchAddress( "bgo_ok", &bgo_ok );
  tree->SetBranchAddress( "bgo_corr_ok", &bgo_corr_ok );




  int nBins = 500;
  float xMax = 25.*3./2.;


  TH1D* h1_xPos = new TH1D("xPos", "", nBins, -xMax, xMax);
  TH1D* h1_yPos = new TH1D("yPos", "", nBins, -xMax, xMax);
  TH2D* h2_xyPos = new TH2D("xyPos", "", nBins, -xMax, xMax, nBins, -xMax, xMax);

  TH1D* h1_xPos_singleEle = new TH1D("xPos_singleEle", "", nBins, -xMax, xMax);
  TH1D* h1_yPos_singleEle = new TH1D("yPos_singleEle", "", nBins, -xMax, xMax);
  TH2D* h2_xyPos_singleEle = new TH2D("xyPos_singleEle", "", nBins, -xMax, xMax, nBins, -xMax, xMax);

  TH1D* h1_xPos_new = new TH1D("xPos_new", "", nBins, -xMax, xMax);
  TH1D* h1_yPos_new = new TH1D("yPos_new", "", nBins, -xMax, xMax);
  TH2D* h2_xyPos_new = new TH2D("xyPos_new", "", nBins, -xMax, xMax, nBins, -xMax, xMax);

  TH1D* h1_xPos_new_singleEle = new TH1D("xPos_new_singleEle", "", nBins, -xMax, xMax);
  TH1D* h1_yPos_new_singleEle = new TH1D("yPos_new_singleEle", "", nBins, -xMax, xMax);
  TH2D* h2_xyPos_new_singleEle = new TH2D("xyPos_new_singleEle", "", nBins, -xMax, xMax, nBins, -xMax, xMax);


  TH1D* h1_xPos_bgo = new TH1D("xPos_bgo", "", nBins, -xMax, xMax);
  TH1D* h1_yPos_bgo = new TH1D("yPos_bgo", "", nBins, -xMax, xMax);
  TH2D* h2_xyPos_bgo = new TH2D("xyPos_bgo", "", nBins, -xMax, xMax, nBins, -xMax, xMax);

  TH1D* h1_xPos_singleEle_bgo = new TH1D("xPos_singleEle_bgo", "", nBins, -xMax, xMax);
  TH1D* h1_yPos_singleEle_bgo = new TH1D("yPos_singleEle_bgo", "", nBins, -xMax, xMax);
  TH2D* h2_xyPos_singleEle_bgo = new TH2D("xyPos_singleEle_bgo", "", nBins, -xMax, xMax, nBins, -xMax, xMax);

  TH1D* h1_xPos_hodo = new TH1D("xPos_hodo", "", nBins, -xMax, xMax);
  TH1D* h1_yPos_hodo = new TH1D("yPos_hodo", "", nBins, -xMax, xMax);
  TH2D* h2_xyPos_hodo = new TH2D("xyPos_hodo", "", nBins, -xMax, xMax, nBins, -xMax, xMax);

  TH1D* h1_xPos_singleEle_hodo = new TH1D("xPos_singleEle_hodo", "", nBins, -xMax, xMax);
  TH1D* h1_yPos_singleEle_hodo = new TH1D("yPos_singleEle_hodo", "", nBins, -xMax, xMax);
  TH2D* h2_xyPos_singleEle_hodo = new TH2D("xyPos_singleEle_hodo", "", nBins, -xMax, xMax, nBins, -xMax, xMax);

  TH1D* h1_xPos_singleEle_hodoClust = new TH1D("xPos_singleEle_hodoClust", "", nBins, -xMax, xMax);
  TH1D* h1_yPos_singleEle_hodoClust = new TH1D("yPos_singleEle_hodoClust", "", nBins, -xMax, xMax);
  TH2D* h2_xyPos_singleEle_hodoClust = new TH2D("xyPos_singleEle_hodoClust", "", nBins, -xMax, xMax, nBins, -xMax, xMax);

  TH1D* h1_xPos_calo = new TH1D("xPos_calo", "", nBins, -xMax, xMax);
  TH1D* h1_yPos_calo = new TH1D("yPos_calo", "", nBins, -xMax, xMax);
  TH2D* h2_xyPos_calo = new TH2D("xyPos_calo", "", nBins, -xMax, xMax, nBins, -xMax, xMax);

  TH1D* h1_xPos_singleEle_calo = new TH1D("xPos_singleEle_calo", "", nBins, -xMax, xMax);
  TH1D* h1_yPos_singleEle_calo = new TH1D("yPos_singleEle_calo", "", nBins, -xMax, xMax);
  TH2D* h2_xyPos_singleEle_calo = new TH2D("xyPos_singleEle_calo", "", nBins, -xMax, xMax, nBins, -xMax, xMax);

  TH1D* h1_xPos_calo_vs_hodo = new TH1D("xPos_calo_vs_hodo", "", nBins, -xMax, xMax);
  TH1D* h1_yPos_calo_vs_hodo = new TH1D("yPos_calo_vs_hodo", "", nBins, -xMax, xMax);

  TH1D* h1_xPos_calo_vs_beam = new TH1D("xPos_calo_vs_beam", "", nBins, -xMax, xMax);
  TH1D* h1_yPos_calo_vs_beam = new TH1D("yPos_calo_vs_beam", "", nBins, -xMax, xMax);

  TH1D* h1_xPos_calo_vs_hodo_singleElectron = new TH1D("xPos_calo_vs_hodo_singleElectron", "", nBins, -xMax, xMax);
  TH1D* h1_yPos_calo_vs_hodo_singleElectron = new TH1D("yPos_calo_vs_hodo_singleElectron", "", nBins, -xMax, xMax);

  TH1D* h1_xPos_calo_vs_beam_singleElectron = new TH1D("xPos_calo_vs_beam_singleElectron", "", nBins, -xMax, xMax);
  TH1D* h1_yPos_calo_vs_beam_singleElectron = new TH1D("yPos_calo_vs_beam_singleElectron", "", nBins, -xMax, xMax);

  TH1D* h1_xPos_calo_vs_hodo_singleElectron_HR = new TH1D("xPos_calo_vs_hodo_singleElectron_HR", "", nBins, -xMax, xMax);
  TH1D* h1_yPos_calo_vs_hodo_singleElectron_HR = new TH1D("yPos_calo_vs_hodo_singleElectron_HR", "", nBins, -xMax, xMax);

  TH1D* h1_xPos_calo_vs_beam_singleElectron_HR = new TH1D("xPos_calo_vs_beam_singleElectron_HR", "", nBins, -xMax, xMax);
  TH1D* h1_yPos_calo_vs_beam_singleElectron_HR = new TH1D("yPos_calo_vs_beam_singleElectron_HR", "", nBins, -xMax, xMax);


  TH2D* h2_correlation_cef3_hodo_xPos = new TH2D("correlation_cef3_hodo_xPos", "", 100, -12.5, 12.5,  100, -12.5, 12.5);
  TH2D* h2_correlation_cef3_hodo_yPos = new TH2D("correlation_cef3_hodo_yPos", "", 100, -12.5, 12.5,  100, -12.5, 12.5);

  TH2D* h2_correlation_cef3_bgo_xPos = new TH2D("correlation_cef3_bgo_xPos", "", 100, -12.5, 12.5,  100, -12.5, 12.5);
  TH2D* h2_correlation_cef3_bgo_yPos = new TH2D("correlation_cef3_bgo_yPos", "", 100, -12.5, 12.5,  100, -12.5, 12.5);

  TH2D* h2_correlation_hodo_bgo_xPos = new TH2D("correlation_hodo_bgo_xPos", "", 100, -12.5, 12.5,  100, -12.5, 12.5);
  TH2D* h2_correlation_hodo_bgo_yPos = new TH2D("correlation_hodo_bgo_yPos", "", 100, -12.5, 12.5,  100, -12.5, 12.5);


  TH2D* h2_correlation_cef3_hodo_xPos_singleEle = new TH2D("correlation_cef3_hodo_xPos_singleEle", "", 100, -12.5, 12.5,  100, -12.5, 12.5);
  TH2D* h2_correlation_cef3_hodo_yPos_singleEle = new TH2D("correlation_cef3_hodo_yPos_singleEle", "", 100, -12.5, 12.5,  100, -12.5, 12.5);

  TH2D* h2_correlation_cef3_bgo_xPos_singleEle = new TH2D("correlation_cef3_bgo_xPos_singleEle", "", 100, -12.5, 12.5,  100, -12.5, 12.5);
  TH2D* h2_correlation_cef3_bgo_yPos_singleEle = new TH2D("correlation_cef3_bgo_yPos_singleEle", "", 100, -12.5, 12.5,  100, -12.5, 12.5);

  TH2D* h2_correlation_hodo_bgo_xPos_singleEle = new TH2D("correlation_hodo_bgo_xPos_singleEle", "", 100, -12.5, 12.5,  100, -12.5, 12.5);
  TH2D* h2_correlation_hodo_bgo_yPos_singleEle = new TH2D("correlation_hodo_bgo_yPos_singleEle", "", 100, -12.5, 12.5,  100, -12.5, 12.5);



  int nentries = tree->GetEntries();


  if( isOnlyRunNumber ) {
    // modify runname in such a way that it's useful for getBeamPosition and outfile:
    runName = "BTF_" + runName + "_beam";
  }



  std::string outputdir = "PosAnTrees_"+tag;
  system( Form("mkdir -p %s", outputdir.c_str()) );
  std::string outfileName = outputdir + "/PosAn_" + runName + ".root";
  TFile* outfile = TFile::Open( outfileName.c_str(), "RECREATE" );

  TTree* outTree = new TTree("posTree","posTree");
  float xPos_calo_, yPos_calo_;
  float xPos_bgo_, yPos_bgo_;
  float xPos_new_, yPos_new_;
  float xPos_regr2D_, yPos_regr2D_;
  float r02_, r13_;

  outTree->Branch( "isSingleEle_scintFront", &isSingleEle_scintFront, "isSingleEle_scintFront/O" );
  outTree->Branch( "nHodoClustersX", &nHodoClustersX, "nHodoClustersX/I" );
  outTree->Branch( "nHodoClustersY", &nHodoClustersY, "nHodoClustersY/I" );
  outTree->Branch( "cef3_corr", cef3_corr, "cef3_corr[4]/F" );
  outTree->Branch( "r02", &r02_, "r02_/F" );
  outTree->Branch( "r13", &r13_, "r13_/F" );
  outTree->Branch( "xBeam", &xBeam, "xBeam/F" );
  outTree->Branch( "yBeam", &yBeam, "yBeam/F" );
  outTree->Branch( "xPos_bgo", &xPos_bgo_, "xPos_bgo_/F" );
  outTree->Branch( "yPos_bgo", &yPos_bgo_, "yPos_bgo_/F" );
  outTree->Branch( "xPos_calo", &xPos_calo_, "xPos_calo_/F" );
  outTree->Branch( "yPos_calo", &yPos_calo_, "yPos_calo_/F" );
  outTree->Branch( "xPos_new", &xPos_new_, "xPos_new_/F" );
  outTree->Branch( "yPos_new", &yPos_new_, "yPos_new_/F" );
  outTree->Branch( "xPos_regr2D", &xPos_regr2D_, "xPos_regr2D_/F" );
  outTree->Branch( "yPos_regr2D", &yPos_regr2D_, "yPos_regr2D_/F" );

  float diag02_calo_;
  float diag13_calo_;
  outTree->Branch( "diag02_calo", &diag02_calo_, "diag02_calo_/F" );
  outTree->Branch( "diag13_calo", &diag13_calo_, "diag13_calo_/F" );
  float diag02_new_;
  float diag13_new_;
  outTree->Branch( "diag02_new", &diag02_new_, "diag02_new_/F" );
  outTree->Branch( "diag13_new", &diag13_new_, "diag13_new_/F" );
  float diag02_beam_;
  float diag13_beam_;
  outTree->Branch( "diag02_beam", &diag02_beam_, "diag02_beam_/F" );
  outTree->Branch( "diag13_beam", &diag13_beam_, "diag13_beam_/F" );

  
  std::vector<float> xbgo, ybgo;
  for( unsigned i=0; i<BGO_CHANNELS; ++i ) {
    float x,y;
    RunHelper::getBGOCoordinates( i, x, y );
    xbgo.push_back( x );
    ybgo.push_back( y );
  }


  
  



  float cef3_regr[CEF3_CHANNELS];
  //TMVA::Reader* readerRegrX = new TMVA::Reader( "!Color:!Silent" );
  //readerRegrX->AddVariable("cef3_corr[0]/(cef3_corr[0]+cef3_corr[1]+cef3_corr[2]+cef3_corr[3])", &cef3_regr[0] );
  //readerRegrX->AddVariable("cef3_corr[1]/(cef3_corr[0]+cef3_corr[1]+cef3_corr[2]+cef3_corr[3])", &cef3_regr[1] );
  //readerRegrX->AddVariable("cef3_corr[2]/(cef3_corr[0]+cef3_corr[1]+cef3_corr[2]+cef3_corr[3])", &cef3_regr[2] );
  //readerRegrX->AddVariable("cef3_corr[3]/(cef3_corr[0]+cef3_corr[1]+cef3_corr[2]+cef3_corr[3])", &cef3_regr[3] );

  //TMVA::Reader* readerRegrY = new TMVA::Reader( "!Color:!Silent" );
  //readerRegrY->AddVariable("cef3_corr[0]/(cef3_corr[0]+cef3_corr[1]+cef3_corr[2]+cef3_corr[3])", &cef3_regr[0] );
  //readerRegrY->AddVariable("cef3_corr[1]/(cef3_corr[0]+cef3_corr[1]+cef3_corr[2]+cef3_corr[3])", &cef3_regr[1] );
  //readerRegrY->AddVariable("cef3_corr[2]/(cef3_corr[0]+cef3_corr[1]+cef3_corr[2]+cef3_corr[3])", &cef3_regr[2] );
  //readerRegrY->AddVariable("cef3_corr[3]/(cef3_corr[0]+cef3_corr[1]+cef3_corr[2]+cef3_corr[3])", &cef3_regr[3] ); // let try this trick

  //TMVA::Reader* readerRegr2D = new TMVA::Reader( "!Color:!Silent" );
  //readerRegr2D->AddVariable("cef3_corr[0]", &cef3_corr_[0] );
  //readerRegr2D->AddVariable("cef3_corr[1]", &cef3_corr_[1] );
  //readerRegr2D->AddVariable("cef3_corr[2]", &cef3_corr_[2] );
  //readerRegr2D->AddVariable("cef3_corr[3]", &cef3_corr_[3] );
  //readerRegr2D->BookMVA( "MLP", "TMVA/weights/TMVARegression_MLP.weights.xml" );


  std::vector<std::string> methodNames;
  //methodNames.push_back("BDTG");
  ////methodNames.push_back("FDA_MT");
  //methodNames.push_back("LD");
  //methodNames.push_back("MLP");
  ////methodNames.push_back("PDERS");

 
  //
  //std::cout << "-> Booking TMVA Reader" << std::endl;
  //for( unsigned i=0; i<methodNames.size(); ++i ) {
  //  readerRegrX->BookMVA( methodNames[i], Form("TMVA/weights/TMVARegression_%s.weights.xml", methodNames[i].c_str()) ); 
  //  readerRegrY->BookMVA( methodNames[i], Form("TMVA/weights/TMVARegression_%s.weights.xml", methodNames[i].c_str()) ); 
  //}


  std::vector< TH1D* > h1_xPos_regr_vs_calo;
  std::vector< TH1D* > h1_yPos_regr_vs_calo;
  std::vector< TH2D* > h2_xyPos_regr;
  std::vector< TH1D* > h1_xPos_regr_vs_calo_singleEle;
  std::vector< TH1D* > h1_yPos_regr_vs_calo_singleEle;
  std::vector< TH2D* > h2_xyPos_singleEle_regr;
  for( unsigned i=0; i<methodNames.size(); ++i ) {
    TH1D* newHistx = new TH1D( Form("xPos_regr%s_vs_calo", methodNames[i].c_str()), "", nBins, -xMax, xMax);
    h1_xPos_regr_vs_calo.push_back( newHistx );
    TH1D* newHisty = new TH1D( Form("yPos_regr%s_vs_calo", methodNames[i].c_str()), "", nBins, -xMax, xMax);
    h1_yPos_regr_vs_calo.push_back( newHisty );
    TH2D* newHistxy = new TH2D( Form("xyPos_regr%s", methodNames[i].c_str()), "", nBins, -xMax, xMax, nBins, -xMax, xMax);
    h2_xyPos_regr.push_back( newHistxy );
    TH1D* newHistx_singleEle = new TH1D( Form("xPos_regr%s_vs_calo_singleEle", methodNames[i].c_str()), "", nBins, -xMax, xMax);
    h1_xPos_regr_vs_calo_singleEle.push_back( newHistx_singleEle );
    TH1D* newHisty_singleEle = new TH1D( Form("yPos_regr%s_vs_calo_singleEle", methodNames[i].c_str()), "", nBins, -xMax, xMax);
    h1_yPos_regr_vs_calo_singleEle.push_back( newHisty_singleEle );
    TH2D* newHistxy_singleEle = new TH2D( Form("xyPos_singleEle_regr%s", methodNames[i].c_str()), "", nBins, -xMax, xMax, nBins, -xMax, xMax);
    h2_xyPos_singleEle_regr.push_back( newHistxy_singleEle );
  }


  TH2D* h2_xyPos_regr2D = new TH2D("xyPos_regr2D", "", nBins, -xMax, xMax, nBins, -xMax, xMax);
  TH2D* h2_xyPos_singleEle_regr2D = new TH2D("xyPos_singleEle_regr2D", "", nBins, -xMax, xMax, nBins, -xMax, xMax);





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

    xPos_bgo_ = -999.;
    yPos_bgo_ = -999.;

    xPos_calo_ = -999.;
    yPos_calo_ = -999.;


    tree->GetEntry(iEntry);

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

    if( !bgo_corr_ok ) continue;

    r02_ = cef3_corr[0]/cef3_corr[2];
    r13_ = cef3_corr[1]/cef3_corr[3];

    // FIRST GET POSITION FROM HODOSCOPE:


    float xPos_hodo = getMeanposHodo(nHodoClustersX, pos_hodoClustX);
    float yPos_hodo = getMeanposHodo(nHodoClustersY, pos_hodoClustY);



    if( xPos_hodo>-100. )
      h1_xPos_hodo->Fill(xPos_hodo);
    if( yPos_hodo>-100. )
      h1_yPos_hodo->Fill(yPos_hodo);

    if( xPos_hodo>-100. && yPos_hodo>-100. ) 
      h2_xyPos_hodo->Fill(xPos_hodo, yPos_hodo);


    if( isSingleEle_scintFront ) {

      if( xPos_hodo>-100. )
        h1_xPos_singleEle_hodo->Fill(xPos_hodo);
      if( yPos_hodo>-100. )
        h1_yPos_singleEle_hodo->Fill(yPos_hodo);

      if( xPos_hodo>-100. && yPos_hodo>-100. ) 
        h2_xyPos_singleEle_hodo->Fill(xPos_hodo, yPos_hodo);

    }



    std::vector<float> xPosW_bgo;
    std::vector<float> yPosW_bgo;

    std::vector<float> v_bgo_corr;
    for( unsigned i=0; i<BGO_CHANNELS; ++i ) v_bgo_corr.push_back(bgo_corr[i]);

    float eTot_bgo_corr = sumVector(v_bgo_corr);

    if( bgo_ok && bgo_corr_ok ) {

      //   0  1  2
      //   3     4
      //   5  6  7

      xPosW_bgo.push_back(bgo_corr[0]*xbgo[0]);
      xPosW_bgo.push_back(bgo_corr[1]*xbgo[1]);
      xPosW_bgo.push_back(bgo_corr[2]*xbgo[2]);
      xPosW_bgo.push_back(bgo_corr[3]*xbgo[3]);
      xPosW_bgo.push_back(bgo_corr[4]*xbgo[4]);
      xPosW_bgo.push_back(bgo_corr[5]*xbgo[5]);
      xPosW_bgo.push_back(bgo_corr[6]*xbgo[6]);
      xPosW_bgo.push_back(bgo_corr[7]*xbgo[7]);
      
      yPosW_bgo.push_back(bgo_corr[0]*ybgo[0]);
      yPosW_bgo.push_back(bgo_corr[1]*ybgo[1]);
      yPosW_bgo.push_back(bgo_corr[2]*ybgo[2]);
      yPosW_bgo.push_back(bgo_corr[3]*ybgo[3]);
      yPosW_bgo.push_back(bgo_corr[4]*ybgo[4]);
      yPosW_bgo.push_back(bgo_corr[5]*ybgo[5]);
      yPosW_bgo.push_back(bgo_corr[6]*ybgo[6]);
      yPosW_bgo.push_back(bgo_corr[7]*ybgo[7]);
      

      xPos_bgo_ = sumVector( xPosW_bgo )/eTot_bgo_corr;
      yPos_bgo_ = sumVector( yPosW_bgo )/eTot_bgo_corr;
      
      h1_xPos_bgo->Fill( xPos_bgo_ );
      h1_yPos_bgo->Fill( yPos_bgo_ );
      h2_xyPos_bgo->Fill( xPos_bgo_, yPos_bgo_ );

      h2_correlation_hodo_bgo_xPos->Fill( xPos_hodo, xPos_bgo_ );
      h2_correlation_hodo_bgo_yPos->Fill( yPos_hodo, yPos_bgo_ );
      
      if( isSingleEle_scintFront ) {

        h1_xPos_singleEle_bgo->Fill( xPos_bgo_ );
        h1_yPos_singleEle_bgo->Fill( yPos_bgo_ );
        h2_xyPos_singleEle_bgo->Fill( xPos_bgo_, yPos_bgo_ );

        h2_correlation_hodo_bgo_xPos_singleEle->Fill( xPos_hodo, xPos_bgo_ );
        h2_correlation_hodo_bgo_yPos_singleEle->Fill( yPos_hodo, yPos_bgo_ );

      }
      
    }  // if bgo ok



    // THEN USE CeF3 DATA:

    if( cef3_ok ) {


      std::vector<float> v_cef3_corr;
      for(unsigned i=0; i<CEF3_CHANNELS; ++i) v_cef3_corr.push_back(cef3_corr[i]);

      float eTot_corr = sumVector(v_cef3_corr);

      

      if( cef3_corr_ok ) {


        //   0      1
        //          
        //          
        //   3      2


        float position = 12. - 0.696; // using FN's infallible trigonometry

        //std::vector

        std::vector<float> xPosW;
        xPosW.push_back(cef3_corr[0]*(-position));
        xPosW.push_back(cef3_corr[1]*(+position));
        xPosW.push_back(cef3_corr[2]*(+position));
        xPosW.push_back(cef3_corr[3]*(-position));

        std::vector<float> yPosW;
        yPosW.push_back(cef3_corr[0]*(+position));
        yPosW.push_back(cef3_corr[1]*(+position));
        yPosW.push_back(cef3_corr[2]*(-position));
        yPosW.push_back(cef3_corr[3]*(-position));


        getCeF3Position( v_cef3_corr, xPos_new_, yPos_new_ );
        //diag02_new_ = xPos_new_;
        //diag13_new_ = yPos_new_;

        float pi = 3.14159;
        float theta = pi/4.; // 45 degrees 
        TVector2 vnew( xPos_new_, yPos_new_ );
        TVector2 dnew = vnew.Rotate(-theta);
        diag02_new_ = dnew.Y();
        diag13_new_ = dnew.X();


        TVector2 vBeam( xBeam, yBeam );
        TVector2 dBeam = vBeam.Rotate(-theta);
        diag02_beam_ = dBeam.Y();
        diag13_beam_ = dBeam.X();

        float xPos = sumVector(xPosW)/eTot_corr;
        float yPos = sumVector(yPosW)/eTot_corr;

        h1_xPos->Fill( xPos );
        h1_yPos->Fill( yPos );

        h2_xyPos->Fill( xPos, yPos );

        h1_xPos_new->Fill( xPos_new_ );
        h1_yPos_new->Fill( yPos_new_ );

        h2_xyPos_new->Fill( xPos_new_, yPos_new_ );


        // positioning with all 9 calorimeter channels:
        //float xPos_calo = sumVector( xPosW_bgo )/(eTot_bgo_corr + eTot_corr*0.07); // cef3 is in 0,0
        //float yPos_calo = sumVector( yPosW_bgo )/(eTot_bgo_corr + eTot_corr*0.08); // so counts only in denominator
        xPos_calo_ = sumVector( xPosW_bgo )/(eTot_bgo_corr + eTot_corr*0.06); // cef3 is in 0,0
        yPos_calo_ = sumVector( yPosW_bgo )/(eTot_bgo_corr + eTot_corr*0.10); // so counts only in denominator
        //float xPos_calo = sumVector( xPosW_bgo )/(eTot_bgo_corr + eTot_corr*0.791577); // cef3 is in 0,0
        //float yPos_calo = sumVector( yPosW_bgo )/(eTot_bgo_corr + eTot_corr*0.791577); // so counts only in denominator

        TVector2 vcalo( xPos_calo_, yPos_calo_ );
        TVector2 dcalo = vcalo.Rotate(-theta);
        diag02_calo_ = dcalo.Y();
        diag13_calo_ = dcalo.X();

        //xPos_regr2D_ = readerRegr2D->EvaluateRegression( "MLP" )[0];
        //yPos_regr2D_ = readerRegr2D->EvaluateRegression( "MLP" )[1];

        cef3_regr[0] = cef3_corr[0]/(cef3_corr[0]+cef3_corr[1]+cef3_corr[2]+cef3_corr[3]);
        cef3_regr[1] = cef3_corr[1]/(cef3_corr[0]+cef3_corr[1]+cef3_corr[2]+cef3_corr[3]);
        cef3_regr[2] = cef3_corr[2]/(cef3_corr[0]+cef3_corr[1]+cef3_corr[2]+cef3_corr[3]);
        cef3_regr[3] = cef3_corr[3]/(cef3_corr[0]+cef3_corr[1]+cef3_corr[2]+cef3_corr[3]);
  
        if( bgo_ok && bgo_corr_ok ) {

          h1_xPos_calo->Fill( xPos_calo_ );
          h1_yPos_calo->Fill( yPos_calo_ );
          h2_xyPos_calo->Fill( xPos_calo_, yPos_calo_ );

          //for( unsigned i=0; i<methodNames.size(); ++i ) {
          //  Float_t xPos_regr = (readerRegrX->EvaluateRegression( methodNames[i] ))[0];
          //  Float_t yPos_regr = (readerRegrY->EvaluateRegression( methodNames[i] ))[0];
          //  h1_xPos_regr_vs_calo[i]->Fill( xPos_regr-xPos_calo_ );
          //  h1_yPos_regr_vs_calo[i]->Fill( yPos_regr-yPos_calo_ );
          //  h2_xyPos_regr[i]->Fill( xPos_regr, yPos_regr );
          //}
          //h2_xyPos_regr2D->Fill( xPos_regr2D_, yPos_regr2D_ );

          h1_xPos_calo_vs_hodo->Fill( xPos_calo_-xPos_hodo );
          h1_yPos_calo_vs_hodo->Fill( yPos_calo_-yPos_hodo );

          h1_xPos_calo_vs_beam->Fill( xPos_calo_-xBeam );
          h1_yPos_calo_vs_beam->Fill( yPos_calo_-yBeam );

          // CORRELATIONS BETWEEN CALO AND HODO:

          h2_correlation_cef3_bgo_xPos->Fill( xPos, xPos_bgo_ );
          h2_correlation_cef3_bgo_yPos->Fill( yPos, yPos_bgo_ );

        }

        if( isSingleEle_scintFront ) {

          h1_xPos_singleEle->Fill( xPos );
          h1_yPos_singleEle->Fill( yPos );
          h2_xyPos_singleEle->Fill( xPos, yPos );

          h1_xPos_new_singleEle->Fill( xPos_new_ );
          h1_yPos_new_singleEle->Fill( yPos_new_ );
          h2_xyPos_new_singleEle->Fill( xPos_new_, yPos_new_ );

          h1_xPos_calo_vs_hodo_singleElectron->Fill( xPos_calo_-xPos_hodo );
          h1_yPos_calo_vs_hodo_singleElectron->Fill( yPos_calo_-yPos_hodo );

          h1_xPos_calo_vs_beam_singleElectron->Fill( xPos_calo_-xBeam );
          h1_yPos_calo_vs_beam_singleElectron->Fill( yPos_calo_-yBeam );

          if( nHodoClustersX==1 && nHodoClustersY==1 && nFibres_hodoClustX[0]<=2 && nFibres_hodoClustY[0]<=2 ) {

            h1_xPos_calo_vs_hodo_singleElectron_HR->Fill( xPos_calo_-xPos_hodo );
            h1_yPos_calo_vs_hodo_singleElectron_HR->Fill( yPos_calo_-yPos_hodo );
  
            h1_xPos_calo_vs_beam_singleElectron_HR->Fill( xPos_calo_-xBeam );
            h1_yPos_calo_vs_beam_singleElectron_HR->Fill( yPos_calo_-yBeam );

          }


          h2_correlation_cef3_hodo_xPos_singleEle->Fill( xPos, xPos_hodo );
          h2_correlation_cef3_hodo_yPos_singleEle->Fill( yPos, yPos_hodo );

  
          if( bgo_ok && bgo_corr_ok ) {

            h1_xPos_singleEle_calo->Fill( xPos_calo_ );
            h1_yPos_singleEle_calo->Fill( yPos_calo_ );
            h2_xyPos_singleEle_calo->Fill( xPos_calo_, yPos_calo_ );

            //for( unsigned i=0; i<methodNames.size(); ++i ) {
            //  Float_t xPos_regr = (readerRegrX->EvaluateRegression( methodNames[i] ))[0];
            //  Float_t yPos_regr = (readerRegrY->EvaluateRegression( methodNames[i] ))[0];
            //  h1_xPos_regr_vs_calo_singleEle[i]->Fill( xPos_regr-xPos_calo_ );
            //  h1_yPos_regr_vs_calo_singleEle[i]->Fill( yPos_regr-yPos_calo_ );
            //  h2_xyPos_singleEle_regr[i]->Fill( xPos_regr, yPos_regr );
            //}

            //h2_xyPos_singleEle_regr2D->Fill( xPos_regr2D_, yPos_regr2D_ );

            h2_correlation_cef3_bgo_xPos_singleEle->Fill( xPos, xPos_bgo_ );
            h2_correlation_cef3_bgo_yPos_singleEle->Fill( yPos, yPos_bgo_ );

          }

        }

        
        outTree->Fill();


      } // if cef3_ok

    }

  }


  outfile->cd();

  outTree->Write();


  for( unsigned i=0; i<h1_xPos_regr_vs_calo.size(); ++i ) {
    h1_xPos_regr_vs_calo[i]->Write();
    h1_yPos_regr_vs_calo[i]->Write();
    h1_xPos_regr_vs_calo_singleEle[i]->Write();
    h1_yPos_regr_vs_calo_singleEle[i]->Write();
    h2_xyPos_regr[i]->Write();
    h2_xyPos_singleEle_regr[i]->Write();
  }




  h1_xPos->Write();
  h1_yPos->Write();
  h2_xyPos->Write();

  h1_xPos_singleEle->Write();
  h1_yPos_singleEle->Write();
  h2_xyPos_singleEle->Write();

  h1_xPos_new->Write();
  h1_yPos_new->Write();
  h2_xyPos_new->Write();

  h1_xPos_new_singleEle->Write();
  h1_yPos_new_singleEle->Write();
  h2_xyPos_new_singleEle->Write();

  
  
  h1_xPos_bgo->Write();
  h1_yPos_bgo->Write();
  h2_xyPos_bgo->Write();
  

  h1_xPos_hodo->Write();
  h1_yPos_hodo->Write();
  h2_xyPos_hodo->Write();

  
  h1_xPos_calo_vs_hodo->Write();
  h1_yPos_calo_vs_hodo->Write();

  h1_xPos_calo_vs_beam->Write();
  h1_yPos_calo_vs_beam->Write();
  
  h1_xPos_calo_vs_hodo_singleElectron->Write();
  h1_yPos_calo_vs_hodo_singleElectron->Write();

  h1_xPos_calo_vs_beam_singleElectron->Write();
  h1_yPos_calo_vs_beam_singleElectron->Write();
  
  h1_xPos_calo_vs_hodo_singleElectron_HR->Write();
  h1_yPos_calo_vs_hodo_singleElectron_HR->Write();

  h1_xPos_calo_vs_beam_singleElectron_HR->Write();
  h1_yPos_calo_vs_beam_singleElectron_HR->Write();
  

  std::cout << std::endl;

  

  h2_correlation_cef3_hodo_xPos->Write();
  h2_correlation_cef3_hodo_yPos->Write();

  h2_correlation_cef3_bgo_xPos->Write();
  h2_correlation_cef3_bgo_yPos->Write();

  h2_correlation_hodo_bgo_xPos->Write();
  h2_correlation_hodo_bgo_yPos->Write();

  h1_xPos_singleEle_bgo->Write();
  h1_yPos_singleEle_bgo->Write();
  h2_xyPos_singleEle_bgo->Write();
  
  h1_xPos_singleEle_hodo->Write();
  h1_yPos_singleEle_hodo->Write();
  h2_xyPos_singleEle_hodo->Write();

  h1_xPos_singleEle_hodoClust->Write();
  h1_yPos_singleEle_hodoClust->Write();
  h2_xyPos_singleEle_hodoClust->Write();

  h1_xPos_calo->Write();
  h1_yPos_calo->Write();
  h2_xyPos_calo->Write();
  
  h1_xPos_singleEle_calo->Write();
  h1_yPos_singleEle_calo->Write();
  h2_xyPos_singleEle_calo->Write();
  

  h2_correlation_cef3_hodo_xPos_singleEle->Write();
  h2_correlation_cef3_hodo_yPos_singleEle->Write();

  h2_correlation_cef3_bgo_xPos_singleEle->Write();
  h2_correlation_cef3_bgo_yPos_singleEle->Write();

  h2_correlation_hodo_bgo_xPos_singleEle->Write();
  h2_correlation_hodo_bgo_yPos_singleEle->Write();


  outfile->Close();
  std::cout << "-> Histograms saved in: " << outfile->GetName() << std::endl;


  return 0;

}
예제 #11
0
void mergeForest(TString fname = "/data/jisun/temp/*.root",
		 TString outfile="/data/jisun/pp_2015_HeavyFlavor_AOD_tkpt1_D0pt1_eta2p5_D3d1_Prob0p05_1202.root",
		 bool failOnError = true)
{
  // First, find on of the files within 'fname' and use it to make a
  // list of trees. Unfortunately we have to know in advance at least
  // one of the tree names. hiEvtAnalyzer/HiTree is a safe choice for
  // HiForests. We also assume that every TTree is inside a
  // TDirectoryFile which is in the top level of the root file.
  TChain *dummyChain = new TChain("hltanalysis/HltTree");
  dummyChain->Add(fname);
  TFile *testFile = dummyChain->GetFile();
  TList *topKeyList = testFile->GetListOfKeys();

  std::vector<TString> trees;
  std::vector<TString> dir;

  for(int i = 0; i < topKeyList->GetEntries(); ++i)
  {
    TDirectoryFile *dFile = (TDirectoryFile*)testFile->Get(topKeyList->At(i)->GetName());
    if(strcmp(dFile->ClassName(), "TDirectoryFile") != 0) continue;
    
    TList *bottomKeyList = dFile->GetListOfKeys();

    for(int j = 0; j < bottomKeyList->GetEntries(); ++j)
    {
      TString treeName = dFile->GetName();
      treeName += "/";
      treeName += bottomKeyList->At(j)->GetName();

      TTree* tree = (TTree*)testFile->Get(treeName);
      if(strcmp(tree->ClassName(), "TTree") != 0 && strcmp(tree->ClassName(), "TNtuple") != 0) continue;

      trees.push_back(treeName);
      dir.push_back(dFile->GetName());
    }
  }

  testFile->Close();
  delete dummyChain;

  // Now use the list of tree names to make a new root file, filling
  // it with the trees from 'fname'.
  const int Ntrees = trees.size();
  TChain* ch[Ntrees];

  Long64_t nentries = 0;
  for(int i = 0; i < Ntrees; ++i){
    ch[i] = new TChain(trees[i]);
    ch[i]->Add(fname);
    std::cout << "Tree loaded : " << trees[i] << std::endl;
    std::cout << "Entries : " << ch[i]->GetEntries() << std::endl;

    // If the number of entries in this tree is different from other
    // trees there is a problem. Quit and inform the user without
    // producing output.
    if(failOnError)
    {
      if(strcmp(trees[i],"HiForest/HiForestVersion") == 0) continue;
      if(i == 0) nentries = ch[i]->GetEntries();
      else if (nentries != ch[i]->GetEntries())
      {
	std::cout << "ERROR: number of entries in this tree does not match." << std::endl;
	std::cout << "First inconsistent file: " <<ch[i]->GetFile()->GetName()<<std::endl;
	std::cout << "Exiting. Please check input." << std::endl;
	return;
      }
    }
    else
    {
      std::cout << "WARN: error checking disabled" << std::endl;
    }
  }

  TFile* file = new TFile(outfile, "RECREATE");

  for(int i = 0; i < Ntrees; ++i)
  {
    file->cd();
    std::cout << trees[i] << std::endl;
    if (i==0)
    {
      file->mkdir(dir[i])->cd();
    }
    else
    {
      if ( dir[i] != dir[i-1] )
  	file->mkdir(dir[i])->cd();
      else
  	file->cd(dir[i]);
    }
    ch[i]->Merge(file,0,"keep");
    delete ch[i];
  }
  //file->Write();
  file->Close();

  std::cout << "Done. Output: " << outfile << std::endl;
}
예제 #12
0
void analyzeDijetAj(std::vector<std::string> urls, const char *outname = "eventObjects.root", Long64_t nentries = 20, Int_t firstF = -1, Int_t lastF = -1, Int_t firstEvent = 0) {

  /*
    ptminType: minimum raw pt for particles used by puppi
    0 : 0 GeV
    1 : 1 GeV
    2 : 2 GeV

    jetSignalType: jets used to select jetty region in events
    0 : detector-level jets (akPu4PF)
    1 : particle-level jets (gen jets)
   */

  double ptminjet = 30.;
  TString jetName = "aktCs4PF";
  TString jetTreeName = "akCs4PFJetAnalyzer";
  //jetName = "akCs4PFFilter";
  //jetTreeName = "akCs4PFFilterJetAnalyzer";

  std::cout << "analyzing subjets for: " << jetName << " tree: " << jetTreeName << std::endl;
   
  std::cout << "nfiles: " << urls.size() << std::endl;
  for (auto i = urls.begin(); i != urls.end(); ++i)
    std::cout << *i << std::endl;

  size_t firstFile = 0;
  size_t lastFile = urls.size();

  if(firstF>-1) {
    firstFile = (size_t)firstF;
    lastFile = std::min((size_t)lastF,lastFile);
  }
  std::cout << "firstFile: " << firstFile << "  lastFile: " << lastFile << std::endl;

  Int_t lastEvent = nentries;
  if(firstEvent>0) {
    lastEvent = firstEvent + nentries;
  }
  std::cout << "firstEvent: " << firstEvent << std::endl;
  
  //add files to chain
  TChain *chain = NULL;
  chain = new TChain("hiEvtAnalyzer/HiTree");
  for(size_t i=firstFile; i<lastFile; i++) chain->Add(urls[i].c_str());
  Printf("hiTree done");

  TChain *skimTree = new TChain("skimanalysis/HltTree");
  for(size_t i=firstFile; i<lastFile; i++) skimTree->Add(urls[i].c_str());
  chain->AddFriend(skimTree);
  Printf("skimTree done");

  TChain *hltTree = new TChain("hltanalysis/HltTree");
  for(size_t i=firstFile; i<lastFile; i++) hltTree->Add(urls[i].c_str());
  chain->AddFriend(hltTree);
  Printf("hltTree done");
  
  TChain *jetTree = new TChain(Form("%s/t",jetTreeName.Data()));
  for(size_t i=firstFile; i<lastFile; i++) jetTree->Add(urls[i].c_str());
  chain->AddFriend(jetTree);
  Printf("jetTree done");

  // TChain *csJetTree = new TChain(Form("%s/t","akCs4PFJetAnalyzer"));
  // for(size_t i=firstFile; i<lastFile; i++) csJetTree->Add(urls[i].c_str());
  // chain->AddFriend(csJetTree);
  // Printf("csJetTree done");

  TList *fEventObjects = new TList();

  //---------------------------------------------------------------
  // producers
  //
  hiEventProducer *p_evt = new hiEventProducer("hiEvtProd");
  p_evt->SetInput(chain);
  p_evt->SetHIEventContName("hiEventContainer");
  p_evt->SetEventObjects(fEventObjects);

  triggerProducer *p_trg = new triggerProducer("trigProd");
  p_trg->SetInput(chain);//hltTree);
  p_trg->SetTriggerMapName("triggerMap");
  p_trg->AddTrigger("HLT_HIPuAK4CaloJet100_Eta5p1_v1");
  p_trg->SetEventObjects(fEventObjects);

  lwJetFromForestProducer *p_PUJet = new lwJetFromForestProducer("lwJetForestProd");
  p_PUJet->SetInput(chain);
  p_PUJet->SetJetContName(jetName);
  p_PUJet->SetGenJetContName("");
  p_PUJet->SetEventObjects(fEventObjects);
  p_PUJet->SetRadius(0.4);
  p_PUJet->SetMinJetPt(ptminjet);
  // lwJetFromForestProducer *p_CSJet = new lwJetFromForestProducer("lwJetForestProd");
  // p_CSJet->SetInput(csJetTree);
  // p_CSJet->SetJetContName("aktCs4PF");
  // p_CSJet->SetGenJetContName("");
  // p_CSJet->SetEventObjects(fEventObjects);
  // p_CSJet->SetRadius(0.4);
  
  //---------------------------------------------------------------
  //analysis modules
  //

  //handler to which all modules will be added
  anaBaseTask *handler = new anaBaseTask("handler","handler");

  anaDijetAj *anadijetAj = new anaDijetAj("anaDijetAj","anaDijetAj");
  anadijetAj->ConnectEventObject(fEventObjects);
  anadijetAj->SetHiEvtName("hiEventContainer");
  anadijetAj->DoCollisionEventSel(true);
  anadijetAj->DoHBHENoiseFilter(true);
  anadijetAj->DoHBHENoiseFilterLoose(true);
  anadijetAj->DoPrimaryVertexFilter(true);
  anadijetAj->DoClusterCompatibilityFilter(true);
  anadijetAj->DoHFCoincFilter(true);
  anadijetAj->SetTriggerMapName("triggerMap");
  anadijetAj->AddTriggerSel("HLT_HIPuAK4CaloJet100_Eta5p1_v1");
  anadijetAj->SetJetsName(jetName);
  anadijetAj->SetNCentBins(5);
  anadijetAj->SetJetEtaRange(-1.3,1.3);
  anadijetAj->SetDoDijets(true);
  anadijetAj->AddLeadingJetPtBin(120.,150.);
  anadijetAj->AddLeadingJetPtBin(150.,180.);
  anadijetAj->AddLeadingJetPtBin(180.,220.);
  anadijetAj->AddLeadingJetPtBin(220.,260.);
  anadijetAj->AddLeadingJetPtBin(260.,300.);
  anadijetAj->AddLeadingJetPtBin(300.,500.);
  anadijetAj->SetPtMinSubleading(40.);
  handler->Add(anadijetAj);

  anaDijetAj *anadijetAjMassCut = new anaDijetAj("anaDijetAjMassCut","anaDijetAjMassCut");
  anadijetAjMassCut->ConnectEventObject(fEventObjects);
  anadijetAjMassCut->SetHiEvtName("hiEventContainer");
  anadijetAjMassCut->DoCollisionEventSel(true);
  anadijetAjMassCut->DoHBHENoiseFilter(true);
  anadijetAjMassCut->DoHBHENoiseFilterLoose(true);
  anadijetAjMassCut->DoPrimaryVertexFilter(true);
  anadijetAjMassCut->DoClusterCompatibilityFilter(true);
  anadijetAjMassCut->DoHFCoincFilter(true);
  anadijetAjMassCut->SetTriggerMapName("triggerMap");
  anadijetAjMassCut->AddTriggerSel("HLT_HIPuAK4CaloJet100_Eta5p1_v1");
  anadijetAjMassCut->SetJetsName(jetName);
  anadijetAjMassCut->SetNCentBins(5);
  anadijetAjMassCut->SetJetEtaRange(-1.,3.);
  anadijetAjMassCut->SetDoDijets(true);
  anadijetAjMassCut->AddLeadingJetPtBin(120.,150.);
  anadijetAjMassCut->AddLeadingJetPtBin(150.,180.);
  anadijetAjMassCut->AddLeadingJetPtBin(180.,220.);
  anadijetAjMassCut->AddLeadingJetPtBin(220.,260.);
  anadijetAjMassCut->AddLeadingJetPtBin(260.,300.);
  anadijetAjMassCut->AddLeadingJetPtBin(300.,500.);
  anadijetAjMassCut->SetPtMinSubleading(40.);
  anadijetAjMassCut->SetMinMassLeading(10.);
  handler->Add(anadijetAjMassCut);
  
  //---------------------------------------------------------------
  //Event loop
  //---------------------------------------------------------------
  Long64_t entries_tot =  chain->GetEntries(); //93064
  if(nentries<0) lastEvent = chain->GetEntries();
  Printf("nentries: %lld  tot: %lld",nentries,entries_tot);
  for (Long64_t jentry=firstEvent; jentry<lastEvent; ++jentry) {
    if(jentry%10000==0) cout << "entry: "<< jentry << endl;
    //Run producers
    //Printf("produce hiEvent");
    p_evt->Run(jentry);   //hi event properties
    //Printf("produce PU jets");
    p_PUJet->Run(jentry); //forest jets
    p_trg->Run(jentry);	    

    //Execute all analysis tasks
    handler->ExecuteTask();
  }
    
  fEventObjects->Print();

  TFile *out = new TFile(outname,"RECREATE");
  TList *tasks = handler->GetListOfTasks();
  TIter next(tasks);
  anaBaseTask *obj;
  while ((obj = dynamic_cast<anaBaseTask*>(next()) ))
    if(obj->GetOutput()) obj->GetOutput()->Write(obj->GetName(),TObject::kSingleKey);
  
  out->Write();
  out->Close();
  
}
예제 #13
0
void frameViewerAngles_Mall(char* arg){

	//Take the arguments and save them into respective strings
	std::string infileName;
	std::string inF;
	std::string inPrefix;
	std::string runs, layers;
	std::string runCount;
	std::istringstream stm(arg);

	inPrefix = "/home/p180f/Do_Jo_Ol_Ma/Analysis/MainProcedure/testMain/rawRoot/";

	while (true) {	
		if (std::getline(stm, layers, ' ')) {

			//load the input root files
			TChain *chain = new TChain("fourChamTree");

			for (int i=0; ; i++) {
				runCount = std::to_string(i);
				inF = "run" + runCount + "_" + layers + "layers.root";
				infileName = inPrefix + inF;
				ifstream fin;
				fin.open(infileName.c_str());
				if (!fin.fail()) {
					fin.close();
					chain->Add(infileName.c_str());
					std::cout << "Got " << inF << std::endl;
				} else break;
			}

			//define frame arrays
			int frame[480][640]={0};
			
			const int width = 480;
			const int height = 640;

			//define picture numbers for each tree
			// (in case they are needed)
			int pNum = 0;

			//get branch info from these guyz
			chain->SetBranchAddress("pNum", &pNum);
			chain->SetBranchAddress("frame", &frame);

			//define analysis variables
			Double_t ang[3] = {0};
			Double_t angD = 0;
			Double_t x[4] = {0};
			Double_t y[4] = {0};
			Double_t x_int[1];
			Double_t x_diff= 0;
			Double_t y_int[1];
			Double_t m0 = 0;
			Double_t m1 = 0;
			Double_t b0 = 0;
			Double_t b1 = 0;
			Double_t const Pi = 3.14159265359;
			Double_t convert = 180 / Pi;
			
			TH2D *frameHisto = new TH2D("frameHisto","Muon Tracking by Line Fitting",width,0,width,height,0,height);	//histogram for the stacked images
			TH1D *chamber1x = new TH1D("chamber1x", "Chamber 1x", width, 0, width);
			TH1D *chamber1y = new TH1D("chamber1y", "Chamber 1y", height, 0, height);
			TH1D *chamber2x = new TH1D("chamber2x", "Chamber 2x", width, 0, width);
			TH1D *chamber2y = new TH1D("chamber2y", "Chamber 2y", height, 0, height);
			TH1D *chamber3x = new TH1D("chamber3x", "Chamber 3x", width, 0, width);
			TH1D *chamber3y = new TH1D("chamber3y", "Chamber 3y", height, 0, height);
			TH1D *chamber4x = new TH1D("chamber4x", "Chamber 4x", width, 0, width);
			TH1D *chamber4y = new TH1D("chamber4y", "Chamber 4y", height, 0, height);

			TCanvas *pc2 = new TCanvas("pc2","Frame",0,0,800,800);

			pc2->cd();
			frameHisto->SetStats(false);
			frameHisto->GetXaxis()->SetTitle("X position (px)");
			frameHisto->GetXaxis()->CenterTitle();
			frameHisto->GetYaxis()->SetTitle("Y position (px)");
			frameHisto->GetYaxis()->CenterTitle();
		
			Int_t nentries = chain->GetEntries();
			int count = 0;
			for (Int_t i=0; i<nentries; i++) {
				chain->GetEntry(i);
				for (int x=0; x<width; x++) {
					for (int y=0; y<height; y++) {
						frameHisto->Fill(x, y, frame[x][y]);
						if (frame[x][y]>0) {
							if (y>580 && y<610) {
								chamber1x->Fill(x, frame[x][y]);
								chamber1y->Fill(y, frame[x][y]);
							}
							else if (y>400 && y<440) {
								chamber2x->Fill(x, frame[x][y]);
								chamber2y->Fill(y, frame[x][y]);
							}
							else if (y>240 && y<280) {
								chamber3x->Fill(x, frame[x][y]);
								chamber3y->Fill(y, frame[x][y]);
							}
							else if (y>50 && y<100)	{
								chamber4x->Fill(x, frame[x][y]);
								chamber4y->Fill(y, frame[x][y]);
							}
						}
					}
				}

				//Get the means and fill the x, y coordinates
				x[0] = chamber1x->GetMean();
				y[0] = chamber1y->GetMean();
				x[1] = chamber2x->GetMean();
				y[1] = chamber2y->GetMean();
				x[2] = chamber3x->GetMean();
				y[2] = chamber3y->GetMean();
				x[3] = chamber4x->GetMean();
				y[3] = chamber4y->GetMean();
		
				Double_t x_pos = 0;
				Double_t y_pos = 0;
				
				//Calculate slopes and intercepts
				m0 = ((y[1]-y[0])/(x[1]-x[0]));
				m1 = ((y[3]-y[2])/(x[3]-x[2]));
				b0 = (y[0]-(m0*x[0]));
				b1 = (y[2]-(m1*x[2]));
				
				//Calculate the intersection coordinates
				x_int[0] = ((b1-b0)/(m0-m1));
				y_int[0] = ((m0*x_int[0])+b0);
				
				//Calculate the angle
				ang[0] = atan(m0)*convert;
				ang[1] = atan(m1)*convert;

				//Calculate the rough difference in x in medium
				x_diff = ((340-b0)/m0) - ((340-b1)/m1);

//				std::cout << "ang[0], frame" << i << " = " << ang[0]<< std::endl;
//				std::cout << "ang[1], frame" << i << " = " << ang[1]<< std::endl;
//				cin.ignore();

				//Make array of xdiff RMS
				Double_t x_diffRMS[5] = {41.06, 45.03, 43.29, 40.71, 34.25};		
				Double_t xRMS[4] = {0};
		
				xRMS[0] = chamber1x->GetRMS();
				xRMS[1] = chamber2x->GetRMS();
				xRMS[2] = chamber3x->GetRMS();
				xRMS[3] = chamber4x->GetRMS();
 
				if(ang[0] < 0)
					ang[0] += 180;
				if(ang[1] < 0)
					ang[1] += 180;
				ang[2] = (ang[1]-ang[0]);
			
				//OTHER WAY TO FIND THE ANGLES
				Double_t x_comp[2] = {(x[3]-x[2]), (x[1]-x[0])};
				Double_t y_comp[2] = {(y[3]-y[2]), (y[1]-y[0])};
					
				Double_t vec_mag[2];
				vec_mag[0] = TMath::Sqrt(x_comp[0]*x_comp[0]+y_comp[0]*y_comp[0]);	
				vec_mag[1] = TMath::Sqrt(x_comp[1]*x_comp[1]+y_comp[1]*y_comp[1]);
	
				Double_t cosArg = ((x_comp[0]*x_comp[1]+y_comp[0]*y_comp[1])/(vec_mag[0]*vec_mag[1]));
				angD = acos(cosArg)*convert;	

				if (x_comp[1]<x_comp[0]) {
					angD*=-1;
				}	

				Double_t x_RMS[4];
				x_RMS[0] = chamber1x->GetRMS();
				x_RMS[1] = chamber2x->GetRMS();
				x_RMS[2] = chamber3x->GetRMS();
				x_RMS[3] = chamber4x->GetRMS();

				std::cout << "Processing frame number: " << pNum << "\r";
	
				if (x_RMS[0]>5 && x_RMS[1]>5 && x_RMS[2]>5 && x_RMS[3]>5) {

					//find new x points from given ymin, ymax
					
					double x_min[2];
					double x_max[2];
					double y_min[2] = {0,0};
					double y_max[2] = {640,640};				

					x_min[0] = (y_min[0] - b0) / m0;
					x_max[0] = (y_max[0] - b0) / m0;
					x_min[1] = (y_min[1] - b1) / m1;
					x_max[1] = (y_max[1] - b1) / m1;

					TLine *line0 = new TLine(x_min[0], y_min[0], x_max[0], y_max[0]);
					TLine *line1 = new TLine(x_min[1], y_min[1], x_max[1], y_max[1]);
					TGraph *intersect = new TGraph(1, x_int, y_int); 
					
					pc2->cd();
					frameHisto->Draw("COLZ");
					line0->Draw();
					line1->Draw();
					intersect->Draw("F1*");
					gPad->Update();				

					//wait for user input to advance to next event
					std::cout << "Frame Number=" << pNum << std::endl;
					std::cout << "Press enter to advance to the next frame" << std::endl;
					std::cout << "x[0] RMS = " << x_RMS[0] << std::endl;
					std::cout << "x[1] RMS = " << x_RMS[1] << std::endl;
					std::cout << "x[2] RMS = " << x_RMS[2] << std::endl;
					std::cout << "x[3] RMS = " << x_RMS[3] << std::endl;
					std::cin.ignore();
					
					//clear the old frame from the histogram
					frameHisto->Reset();
					chamber1x->Reset();
					chamber1y->Reset();
					chamber2x->Reset();
					chamber2y->Reset();
					chamber3x->Reset();
					chamber3y->Reset();
					chamber4x->Reset();
					chamber4y->Reset();
				}
			}
		} else {
			break;
		}
	} 
	std::cout << "Complete!\n";
}
예제 #14
0
int main(int argc, char ** argv)
{
  // select fed
  int month = atoi(argv[1]);
  string month_name [12] = {"Gen","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};

  if (month < 0 || month > 12) {
   cout << "Give as argument a number between 1 and 12 corresponding to the chosen month" << endl;
   return 0;
  }

  if (month > 10) {
   cout << "No data corresponding to the chosen month..yet!" << endl;
   return 0;
  }


  //Get old tree 
  TChain *tx = new TChain("x");
  tx->Add(argv[2]);
 
  init_ttree(tx, &x);

  TTree *oldtree = (TTree*)tx;

  Long64_t nentries = oldtree->GetEntries();
  cout<< "Number of entries in the tree : " << nentries << endl;


  //Create a new file + a clone of old tree in new file
  char fname[1000];
  sprintf(fname,argv[3],(month_name[month - 1]).c_str());
  TFile *newfile = new TFile(fname,"recreate");
  TTree *newtree = oldtree->CloneTree(0);

  int lowerRun, upperRun = 0;

  if (month == 1) {
    lowerRun = 153941;
    upperRun = 156054;
  }

  if (month == 2) {
    lowerRun = 156225;
    upperRun = 159130;
  }

  if (month == 3) {
    lowerRun = 159248;
    upperRun = 161732;
  }

  if (month == 4) {
    lowerRun = 161846;
    upperRun = 163726;
  }

  if (month == 5) {
    lowerRun = 163762;
    upperRun = 166139;
  }

  if (month == 6) {
    lowerRun = 166243;
    upperRun = 168148;
  }

  if (month == 7) {
    lowerRun = 168266;
    upperRun = 172266;
  }

  if (month == 8) {
    lowerRun = 172319;
    upperRun = 174912;
  }

  if (month == 9) {
    lowerRun = 175118;
    upperRun = 177519;
  }

  if (month == 10) {
    lowerRun = 177624;
    upperRun = 179998;
  }


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

    if (i%10000000==0) cout << "Analyzing entry " << i << endl;
    oldtree->GetEntry(i);

    if ( x.run > lowerRun && x.run < upperRun ) newtree->Fill();
  }
  
  newtree->Print();
  newtree->AutoSave();
  
  delete newfile;


}
예제 #15
0
// The actual job
int convertTreeForDatacards(TString inFile, TString outfile, bool useJET, bool VBFtag){
  TChain* treedata ;
  treedata= new TChain("SelectedTree");
  treedata->Add(inFile);

  int neventOut=0;
  Int_t run;
  Int_t ls=0;
  Long64_t event;
  float mzz, mzzErr;
  float p0plus_VAJHU, bkg_VAMCFM;
  float m1, m2;
  //float ZZVAKD;
  float pt4l, fisher;
  int NJets_30;

  //Spin analysis variables
  float psigM4l,pbkgM4l;
  float p0minusVA, p0hplusVA,p1minusVA,p1plusVA,p2minimalVA,p2minimalVA_qq,p2hplusVA,p2hminusVA,p2bplusVA,p1minusProdIndepVA,p1plusProdIndepVA,p2mProdIndepVA,pbkg_ProdIndep_VA;

  treedata->SetBranchAddress("RunNumber",&run);
  //  treedata->SetBranchAddress("LumiNumber",&ls);
  treedata->SetBranchAddress("EventNumber",&event);
  treedata->SetBranchAddress("ZZMass",&mzz);
  treedata->SetBranchAddress("ZZMassErrCorr",&mzzErr);
  treedata->SetBranchAddress("p0plus_VAJHU",&p0plus_VAJHU);
  treedata->SetBranchAddress("bkg_VAMCFM",&bkg_VAMCFM);
  //treedata->SetBranchAddress("ZZVAKD",&ZZVAKD);
  treedata->SetBranchAddress("Z1Mass",&m1);
  treedata->SetBranchAddress("Z2Mass",&m2);

  treedata->SetBranchAddress("ZZPt",&pt4l);
  //treedata->SetBranchAddress("ZZRapidity",&Y4l);
  treedata->SetBranchAddress("Fisher",&fisher);

  treedata->SetBranchAddress("NJets30", &NJets_30);

  //Spin Disc variables
  treedata->SetBranchAddress("p0plus_m4l",&psigM4l);
  treedata->SetBranchAddress("bkg_m4l",&pbkgM4l);
  treedata->SetBranchAddress("p0minus_VAJHU",&p0minusVA);
  treedata->SetBranchAddress("p0hplus_VAJHU",&p0hplusVA);
  treedata->SetBranchAddress("p1plus_VAJHU",&p1plusVA);
  treedata->SetBranchAddress("p1_VAJHU",&p1minusVA);
  treedata->SetBranchAddress("p2_VAJHU",&p2minimalVA);
  treedata->SetBranchAddress("p2qqb_VAJHU",&p2minimalVA_qq);
  treedata->SetBranchAddress("p2hplus_VAJHU", &p2hplusVA);
  treedata->SetBranchAddress("p2hminus_VAJHU", &p2hminusVA);
  treedata->SetBranchAddress("p2bplus_VAJHU", &p2bplusVA);
  treedata->SetBranchAddress("p1_prodIndep_VAJHU", &p1minusProdIndepVA);
  treedata->SetBranchAddress("p1plus_prodIndep_VAJHU", &p1plusProdIndepVA);
  treedata->SetBranchAddress("p2_prodIndep_VAJHU", &p2mProdIndepVA);
  treedata->SetBranchAddress("bkg_prodIndep_VAMCFM", &pbkg_ProdIndep_VA);
 
   
  TFile* newFile  = new TFile(outfile, "RECREATE");
  newFile->cd();
  TTree* newTree = new TTree("data_obs","data_obs"); 
  Double_t CMS_zz4l_mass, melaLD, CMS_zz4l_massErr, CMS_zz4l_massRelErr;
  Double_t pt = -99, Fisher = -99;

  newTree->Branch("CMS_zz4l_mass",&CMS_zz4l_mass,"CMS_zz4l_mass/D");
  newTree->Branch("CMS_zz4l_massErr",&CMS_zz4l_massErr,"CMS_zz4l_massErr/D");
  newTree->Branch("CMS_zz4l_massRelErr",&CMS_zz4l_massRelErr,"CMS_zz4l_massRelErr/D");
  newTree->Branch("melaLD",&melaLD,"melaLD/D");
  newTree->Branch("CMS_zz4l_Fisher",&Fisher,"CMS_zz4l_Fisher/D");
  newTree->Branch("CMS_zz4l_Pt",&pt,"CMS_zz4l_Pt/D");

  //Spin Analysis Branches
  Double_t sKD,pseudoKD,graviKD,p0hplusKD,p1plusKD,p1minusKD,qqgraviKD,p2hplusKD,p2hminusKD,p2bplusKD,gravi_piKD,qqgravi_piKD,p1minus_piKD,p1plus_piKD, PIsKD;
  newTree->Branch("CMS_zz4l_smd",&sKD,"CMS_zz4l_smd/D");
  newTree->Branch("CMS_zz4l_pseudoKD",&pseudoKD,"CMS_zz4l_pseudoKD/D");
  newTree->Branch("CMS_zz4l_graviKD",&graviKD,"CMS_zz4l_graviKD/D");
  newTree->Branch("CMS_zz4l_p0hplusKD",&p0hplusKD,"CMS_zz4l_p0hplusKD/D");
  newTree->Branch("CMS_zz4l_p1plusKD",&p1plusKD,"CMS_zz4l_p1plusKD/D");
  newTree->Branch("CMS_zz4l_p1minusKD",&p1minusKD,"CMS_zz4l_p1minusKD/D");
  newTree->Branch("CMS_zz4l_qqgraviKD",&qqgraviKD,"CMS_zz4l_qqgraviKD/D");
  newTree->Branch("CMS_zz4l_p2hplusKD",&p2hplusKD,"CMS_zz4l_p2hplusKD/D");
  newTree->Branch("CMS_zz4l_p2hminusKD",&p2hminusKD,"CMS_zz4l_p2hminusKD/D");
  newTree->Branch("CMS_zz4l_p2bplusKD",&p2bplusKD,"CMS_zz4l_p2bplusKD/D");
  newTree->Branch("CMS_zz4l_gravi_ProdIndepKD",&gravi_piKD,"CMS_zz4l_gravi_ProdIndepKD/D");
  newTree->Branch("CMS_zz4l_qqgravi_ProdIndepKD",&qqgravi_piKD,"CMS_zz4l_qqgravi_ProdIndepKD/D");
  newTree->Branch("CMS_zz4l_p1minus_ProdIndepKD",&p1minus_piKD,"CMS_zz4l_p1minus_ProdIndepKD/D");
  newTree->Branch("CMS_zz4l_p1plus_ProdIndepKD",&p1plus_piKD,"CMS_zz4l_p1plus_ProdIndepKD/D");
  newTree->Branch("CMS_zz4l_ProdIndepSKD",&PIsKD,"CMS_zz4l_ProdIndepSKD/D");


  cout << inFile << " entries: " << treedata->GetEntries() << endl;
  for(int iEvt=0; iEvt<treedata->GetEntries(); iEvt++){
    //    if(iEvt%5000==0) cout << "event: " << iEvt << endl;
    treedata->GetEntry(iEvt);

    //cout << run << endl;
    
    if (onlyICHEPStat && run>=198049) continue;

    //if( NJets_30 > 0) cout << "NJets_30: " << NJets_30 << endl;

    if ((useJET && VBFtag && NJets_30 < 2) || (useJET && !VBFtag && NJets_30 >= 2)) continue;

    CMS_zz4l_mass = double(mzz);
    CMS_zz4l_massErr = double(mzzErr);
    CMS_zz4l_massRelErr = double(mzzErr/mzz);
    //pseudomelaLD = pseudomela;
    //melaLD = mela;
    //supermelaLD = 0;
    melaLD=double(p0plus_VAJHU/(p0plus_VAJHU+bkg_VAMCFM));
    //ZZVAKD=double(p0plus_VAJHU/(bkg_VAMCFM + p0plus_VAJHU));
    if(useJET && !VBFtag) 
      {
	if(pt4l > 200.)
	  {
	    //if pt out of range set to middle of higest bin
	    pt4l = 198.;
	  }
	pt = double(pt4l);
      }
    if(useJET && VBFtag) 
      {
	if(fisher > 2.)
	  {
	    //if fisher out of range set to middle of higest bin
	    fisher = 1.98;
	  }
	Fisher = double(fisher);
      }

    //make variables for spin analysis
    sKD = double((p0plus_VAJHU*psigM4l)/(p0plus_VAJHU*psigM4l + bkg_VAMCFM*pbkgM4l));
    pseudoKD = double(p0plus_VAJHU/(p0plus_VAJHU + p0minusVA));
    graviKD = double(p0plus_VAJHU/(p0plus_VAJHU + p2minimalVA));
    p0hplusKD = double(p0plus_VAJHU/(p0plus_VAJHU + p0hplusVA));
    p1plusKD = double(p0plus_VAJHU/(p0plus_VAJHU + p1plusVA));
    p1minusKD = double(p0plus_VAJHU/(p0plus_VAJHU + p1minusVA));
    qqgraviKD = double(p0plus_VAJHU/(p0plus_VAJHU + p2minimalVA_qq));
    p2hplusKD = double(p0plus_VAJHU/(p0plus_VAJHU + p2hplusVA));
    p2hminusKD = double(p0plus_VAJHU/(p0plus_VAJHU + p2hminusVA));
    p2bplusKD = double(p0plus_VAJHU/(p0plus_VAJHU + p2bplusVA));
    gravi_piKD = double(p0plus_VAJHU/(p0plus_VAJHU + p2mProdIndepVA));
    qqgravi_piKD = double(p0plus_VAJHU/(p0plus_VAJHU + p2mProdIndepVA));
    p1plus_piKD = double (p0plus_VAJHU/(p0plus_VAJHU + p1plusProdIndepVA));
    p1minus_piKD = double (p0plus_VAJHU/(p0plus_VAJHU + p1minusProdIndepVA));
    PIsKD = double((p0plus_VAJHU*psigM4l)/(p0plus_VAJHU*psigM4l + pbkg_ProdIndep_VA*pbkgM4l));
  
#ifdef LINKMELA
    if(recompute_){
      float KD, psig, pbkg;
      myMELA->computeKD(mzz,m1,m2,
		       costhetastar,
		       costheta1,
		       costheta2,
		       phi,
		       phi1,
		       KD,psig,pbkg,
		       withPt_,pt4l,
		       withY_, Y4l,
		       sqrts);
      
      melaLD = KD;
    }
#endif
    ++neventOut;
    newTree->Fill();
    if (dumpEvents) {
      if (!useJET && !VBFtag) {
	cout.setf(ios::fixed);
	int ifs=-1;
	if (outfile.Contains("4e")) ifs = 0;
	else if (outfile.Contains("4mu")) ifs = 1;
	else if (outfile.Contains("2e2mu")) ifs = 2;
	cout << run << ":" << ls << ":" << event << " " << ifs << " " << setprecision(2) << CMS_zz4l_mass << " " << m1 << " " << m2 << " " << CMS_zz4l_massErr << " "  <<  setprecision(3) << melaLD << " "  <<  setprecision(2)  << ((pt4l>0)?pt4l:-1) << " " << setprecision(3) << ((NJets_30 >= 2)?fisher:-1) << endl;
      }
    }
  }
  newTree->Write("data_obs"); 
  newFile->Close();
  
  cout << "written: " << outfile << " entries: " << neventOut << endl << endl;
  return  neventOut;
  
}
void template_ntupleViewer_Chain(){

  const double beamspot=-2.64157;

//  gROOT->Reset();
  gStyle->SetOptStat(1111);
  gStyle->SetCanvasBorderMode(0);
  gStyle->SetPadBorderMode(0);

  gStyle->SetCanvasColor(10);
  gStyle->SetPadColor(10);
  gStyle->SetFillColor(10);
  gStyle->SetStatColor(10);
  gStyle->SetTitleFillColor(10);

std::string addMe = "DATA_";

TH1D* eta_All             =new TH1D( (addMe + std::string("eta_All")).c_str()        , (addMe + std::string("eta_All")).c_str(),25,-3,3);
TH1D* eta_withVertex      =new TH1D( (addMe + std::string("eta_withVertex")).c_str() , (addMe + std::string("eta_withVertex")).c_str(),25,-3,3);
TH1D* eta_AssVertex       =new TH1D( (addMe + std::string("eta_AssVertex")).c_str()  , (addMe + std::string("eta_AssVertex")).c_str(),25,-3,3);
  TH1D* phi_All             =new TH1D( (addMe + std::string("phi_All")).c_str()        , (addMe + std::string("phi_All")).c_str(),25,-3.1415,3.1415);
  TH1D* phi_withVertex      =new TH1D( (addMe + std::string("phi_withVertex")).c_str() , (addMe + std::string("phi_withVertex")).c_str(),25,-3.1415,3.1415);
  TH1D* phi_AssVertex       =new TH1D( (addMe + std::string("phi_AssVertex")).c_str()  , (addMe + std::string("phi_AssVertex")).c_str(),25,-3.1415,3.1415);
TH1D* pt_All              =new TH1D( (addMe + std::string("pt_All")).c_str()         , (addMe + std::string("pt_All")).c_str(),400,0.,40);
TH1D* pt_withVertex       =new TH1D( (addMe + std::string("pt_withVertex")).c_str()  , (addMe + std::string("pt_withVertex")).c_str(),400,0.,40);
TH1D* pt_AssVertex        =new TH1D( (addMe + std::string("pt_AssVertex")).c_str()   , (addMe + std::string("pt_AssVertex")).c_str(),400,0.,40);
  TH1D* track_multip_All       =new TH1D( (addMe + std::string("track_multip_All")).c_str()       , (addMe + std::string("track_multip_All")).c_str(),201,0,200);
  TH1D* track_multip_withVertex=new TH1D( (addMe + std::string("track_multip_withVertex")).c_str(), (addMe + std::string("track_multip_withVertex")).c_str(),201,0,200);
  TH1D* track_multip_AssVertex =new TH1D( (addMe + std::string("track_multip_AssVertex")).c_str() , (addMe + std::string("track_multip_AssVertex")).c_str(),201,0,200);
TH2D* pt_vs_multip_All              =new TH2D( (addMe + std::string("pt_vs_multip_All")).c_str()         , (addMe + std::string("pt_vs_multip_All")).c_str(),400,0.,40,201,0,200);
TH2D* pt_vs_multip_withVertex       =new TH2D( (addMe + std::string("pt_vs_multip_withVertex")).c_str()  , (addMe + std::string("pt_vs_multip_withVertex")).c_str(),400,0.,40,201,0,200);
TH2D* pt_vs_multip_AssVertex        =new TH2D( (addMe + std::string("pt_vs_multip_AssVertex")).c_str()   , (addMe + std::string("pt_vs_multip_AssVertex")).c_str(),400,0.,40,201,0,200);
  TH2D* pt_vs_ndof_All              =new TH2D( (addMe + std::string("pt_vs_ndof_All")).c_str()         , (addMe + std::string("pt_vs_ndof_All")).c_str(),400,0.,40,61,0,60);
  TH2D* pt_vs_ndof_withVertex       =new TH2D( (addMe + std::string("pt_vs_ndof_withVertex")).c_str()  , (addMe + std::string("pt_vs_ndof_withVertex")).c_str(),400,0.,40,61,0,60);
  TH2D* pt_vs_ndof_AssVertex        =new TH2D( (addMe + std::string("pt_vs_ndof_AssVertex")).c_str()   , (addMe + std::string("pt_vs_ndof_AssVertex")).c_str(),400,0.,40,61,0,60);
TH1D* ndof_All              =new TH1D( (addMe + std::string("ndof_All")).c_str()         , (addMe + std::string("ndof_All")).c_str(),61,0,60);
TH1D* ndof_withVertex       =new TH1D( (addMe + std::string("ndof_withVertex")).c_str()  , (addMe + std::string("ndof_withVertex")).c_str(),61,0,60);
TH1D* ndof_AssVertex        =new TH1D( (addMe + std::string("ndof_AssVertex")).c_str()   , (addMe + std::string("ndof_AssVertex")).c_str(),61,0,60);
  TH1D* normChi2_All        =new TH1D( (addMe + std::string("normChi2_All")).c_str()        , (addMe + std::string("normChi2_All")).c_str(),25,0,20);
  TH1D* normChi2_withVertex =new TH1D( (addMe + std::string("normChi2_withVertex")).c_str() , (addMe + std::string("normChi2_withVertex")).c_str(),25,0,20);
  TH1D* normChi2_AssVertex  =new TH1D( (addMe + std::string("normChi2_AssVertex")).c_str()  , (addMe + std::string("normChi2_AssVertex")).c_str(),25,0,20);
TH2D* chi2_vs_pT_All       =new TH2D( (addMe + std::string("chi2_vs_pT_All")).c_str()       , (addMe + std::string("chi2_vs_pT_All")).c_str(),25,0,20,400,0.,40);
TH2D* chi2_vs_pT_withVertex=new TH2D( (addMe + std::string("chi2_vs_pT_withVertex")).c_str(), (addMe + std::string("chi2_vs_pT_withVertex")).c_str(),25,0,20,400,0.,40);
TH2D* chi2_vs_pT_AssVertex =new TH2D( (addMe + std::string("chi2_vs_pT_AssVertex")).c_str() , (addMe + std::string("chi2_vs_pT_AssVertex")).c_str(),25,0,20,400,0.,40);
  TH2D* chi2_vs_pT_lowMultip_All       =new TH2D( (addMe + std::string("chi2_vs_pT_lowMultip_All")).c_str()       , (addMe + std::string("chi2_vs_pT_lowMultip_All")).c_str(),25,0,20,400,0.,40);
  TH2D* chi2_vs_pT_lowMultip_withVertex=new TH2D( (addMe + std::string("chi2_vs_pT_lowMultip_withVertex")).c_str(), (addMe + std::string("chi2_vs_pT_lowMultip_withVertex")).c_str(),25,0,20,400,0.,40);
  TH2D* chi2_vs_pT_lowMultip_AssVertex =new TH2D( (addMe + std::string("chi2_vs_pT_lowMultip_AssVertex")).c_str() , (addMe + std::string("chi2_vs_pT_lowMultip_AssVertex")).c_str(),25,0,20,400,0.,40);
TH2D* chi2_vs_pT_highMultip_All       =new TH2D( (addMe + std::string("chi2_vs_pT_highMultip_All")).c_str()       , (addMe + std::string("chi2_vs_pT_highMultip_All")).c_str(),25,0,20,400,0.,40);
TH2D* chi2_vs_pT_highMultip_withVertex=new TH2D( (addMe + std::string("chi2_vs_pT_highMultip_withVertex")).c_str(), (addMe + std::string("chi2_vs_pT_highMultip_withVertex")).c_str(),25,0,20,400,0.,40);
TH2D* chi2_vs_pT_highMultip_AssVertex =new TH2D( (addMe + std::string("chi2_vs_pT_highMultip_AssVertex")).c_str() , (addMe + std::string("chi2_vs_pT_highMultip_AssVertex")).c_str(),25,0,20,400,0.,40);
  TH1D* vertexes            =new TH1D( (addMe + std::string("vertexes")).c_str()       , (addMe + std::string("vertexes")).c_str(),5,0,5);
  TH1D* vertexes_z          =new TH1D( (addMe + std::string("vertexes_z")).c_str()     , (addMe + std::string("vertexes_z")).c_str(),25,-20,20);
  TH2D* vertexes_xy         =new TH2D( (addMe + std::string("vertexes_xy")).c_str()    , (addMe + std::string("vertexes_xy")).c_str(),200,-10,10,200,-10,10);
  TH1D* deltaZ_trackPV      =new TH1D( (addMe + std::string("deltaZ_trackPV")).c_str() , (addMe + std::string("deltaZ_trackPV")).c_str(),50,-25,25);
  TH1D* deltaZ_trackPV_ZOOM      =new TH1D( (addMe + std::string("deltaZ_trackPV_ZOOM")).c_str() , (addMe +  std::string("deltaZ_trackPV_ZOOM")).c_str(),100,-3,3);
TH1D* deltaX_trackPV      =new TH1D( (addMe + std::string("deltaX_trackPV")).c_str() , (addMe + std::string("deltaX_trackPV")).c_str(),50,-25,25);
TH1D* deltaX_trackPV_ZOOM      =new TH1D( (addMe + std::string("deltaX_trackPV_ZOOM")).c_str() , (addMe + std::string("deltaX_trackPV_ZOOM")).c_str(),100,-3,3);
  TH1D* deltaY_trackPV      =new TH1D( (addMe + std::string("deltaY_trackPV")).c_str() , (addMe + std::string("deltaY_trackPV")).c_str(),50,-25,25);
  TH1D* deltaY_trackPV_ZOOM      =new TH1D( (addMe + std::string("deltaY_trackPV_ZOOM")).c_str() , (addMe + std::string("deltaY_trackPV_ZOOM")).c_str(),100,-3,3);
TH1D* vertexesNum_NoutTrk =new TH1D( (addMe + std::string("vertexesNum_NoutTrk")).c_str() , (addMe + std::string("vertexesNum_NoutTrk")).c_str(),50,0,50);
TH1D* deltaZ_v1v2         =new TH1D( (addMe + std::string("deltaZ_v1v2")).c_str()    , (addMe + std::string("deltaZ_v1v2")).c_str(),100,0,50);
  TH1D* dZ_All      =new TH1D( (addMe + std::string("dZ_All")).c_str() , (addMe +  std::string("dZ_All")).c_str(),100,-3,3);
  TH1D* d0_All      =new TH1D( (addMe + std::string("d0_All")).c_str() , (addMe + std::string("d0_All")).c_str(),100,-3,3);
TH1D* dZPoint_Ass      =new TH1D( (addMe + std::string("dZPoint_Ass")).c_str() , (addMe +  std::string("dZPoint_Ass")).c_str(),100,-3,3);
TH1D* d0Point_Ass      =new TH1D( (addMe + std::string("d0Point_Ass")).c_str() , (addMe + std::string("d0Point_Ass")).c_str(),100,-3,3);
TH1D* dZ_Ass      =new TH1D( (addMe + std::string("dZ_Ass")).c_str() , (addMe +  std::string("dZ_Ass")).c_str(),100,-3,3);
TH1D* d0_Ass      =new TH1D( (addMe + std::string("d0_Ass")).c_str() , (addMe + std::string("d0_Ass")).c_str(),100,-3,3);
  TH1D* dZPoint_Vtx      =new TH1D( (addMe + std::string("dZPoint_Vtx")).c_str() , (addMe +  std::string("dZPoint_Vtx")).c_str(),100,-3,3);
  TH1D* d0Point_Vtx      =new TH1D( (addMe + std::string("d0Point_Vtx")).c_str() , (addMe + std::string("d0Point_Vtx")).c_str(),100,-3,3);
  TH1D* dZ_Vtx      =new TH1D( (addMe + std::string("dZ_Vtx")).c_str() , (addMe +  std::string("dZ_Vtx")).c_str(),100,-3,3);
  TH1D* d0_Vtx      =new TH1D( (addMe + std::string("d0_Vtx")).c_str() , (addMe + std::string("d0_Vtx")).c_str(),100,-3,3);
TH1D* dZ_Vtx_LARGE      =new TH1D( (addMe + std::string("dZ_Vtx_LARGE")).c_str() , (addMe + std::string("dZ_Vtx_LARGE")).c_str(),500,-15,15);
  TH1D* hthrust_z_All            =new TH1D( (addMe + std::string("hthrust_z_All")).c_str()       , (addMe + std::string("thrust_z_All")).c_str(),50,-1.1,1.1);
  TH1D* hthrust_z_withVertex     =new TH1D( (addMe + std::string("hthrust_z_withVertex")).c_str(), (addMe + std::string("thrust_y_withVertex")).c_str(),50,-1.1,1.1);
  TH1D* hthrust_z_AssVertex      =new TH1D( (addMe + std::string("hthrust_z_AssVertex")).c_str() , (addMe + std::string("thrust_z_AssVertex")).c_str(),50,-1.1,1.1);
TH1D* chargeAsymmetry_All = new TH1D( (addMe + std::string("chargeAsymmetry_All")).c_str() , (addMe + std::string("chargeAsymmetry_All")).c_str(),20,-10,10);
TH1D* chargeAsymmetry_AssVertex = new TH1D( (addMe + std::string("chargeAsymmetry_AssVertex")).c_str() , (addMe + std::string("chargeAsymmetry_AssVertex")).c_str(),20,-10,10);

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

  TChain fChain ("MyAnalyzer/EventTree") ;
  fChain.Add("/res/*root");
  dati Input(&fChain);
  int entries = fChain.GetEntries();

//*******  TRUST_Z histograms *****
//deleted
//

//*******  TRACK parameters  ******

cout<<"corro su "<<entries<<" entries"<<endl;

for(int eventn=0;eventn<entries;eventn++){
  fChain.GetEntry(eventn);


  if (realdata)
    if ( rejectRunLumi(Input.runNumber,Input.lumiBlock) ) continue; 

  int chargePlusY=0;
  int chargeMinusY=0;

//All
  track_multip_All->Fill(Input.numTracks);
  for(Int_t trackn=0;trackn<Input.numTracks;trackn++){ //tutte le tracce dell'evento	
      	  
    eta_All->Fill(Input.track_eta[trackn]);
    phi_All->Fill(Input.track_phi[trackn]);
    pt_All->Fill(Input.track_pt[trackn]);
    normChi2_All->Fill(Input.track_normalizedChi2[trackn]);
    chi2_vs_pT_All->Fill(Input.track_normalizedChi2[trackn],Input.track_pt[trackn]);
    pt_vs_multip_All->Fill(Input.track_pt[trackn],Input.numTracks);
    pt_vs_ndof_All->Fill(Input.track_pt[trackn],Input.track_ndof[trackn]);
    ndof_All->Fill(Input.track_ndof[trackn]);
    if (Input.numTracks>100)    chi2_vs_pT_highMultip_All->Fill(Input.track_normalizedChi2[trackn],Input.track_pt[trackn]);
    else                  chi2_vs_pT_lowMultip_All->Fill(Input.track_normalizedChi2[trackn],Input.track_pt[trackn]);
    dZ_All->Fill( Input.track_dz[trackn] );
    d0_All->Fill( Input.track_d0[trackn] );

    if ( Input.track_py[trackn]>0. )  chargePlusY+=Input.track_charge[trackn];
    else                              chargeMinusY+=Input.track_charge[trackn];

    }//tutte le tracce dell'evento
 
  chargeAsymmetry_All->Fill(chargePlusY+chargeMinusY);


//vertex presence requirement
  for(Int_t vertexn=0;vertexn<Input.numVertices;vertexn++)
    {
    if(Input.vertex_z[vertexn]!=beamspot){  //vertice non ricostruito valore del beam spot
      if(fabs(Input.vertex_z[vertexn]-beamspot)<10){
        track_multip_withVertex->Fill(Input.numTracks);
	for(Int_t trackn=0;trackn<Input.numTracks;trackn++){
      	  
	  //if (track_pt[trackn]>8.) continue;
	  
	  eta_withVertex->Fill(Input.track_eta[trackn]);
	  phi_withVertex->Fill(Input.track_phi[trackn]);
	  pt_withVertex->Fill(Input.track_pt[trackn]);
	  normChi2_withVertex->Fill(Input.track_normalizedChi2[trackn]); 
          chi2_vs_pT_withVertex->Fill(Input.track_normalizedChi2[trackn],Input.track_pt[trackn]);
          pt_vs_multip_withVertex->Fill(Input.track_pt[trackn],Input.numTracks);
          pt_vs_ndof_withVertex->Fill(Input.track_pt[trackn],Input.track_ndof[trackn]);
          ndof_withVertex->Fill(Input.track_ndof[trackn]);
          if (Input.numTracks>100)    chi2_vs_pT_highMultip_withVertex->Fill(Input.track_normalizedChi2[trackn],Input.track_pt[trackn]);
          else                  chi2_vs_pT_lowMultip_withVertex->Fill(Input.track_normalizedChi2[trackn],Input.track_pt[trackn]);

	  dZPoint_Vtx->Fill( (Input.track_vz[trackn]-Input.vertex_z[vertexn])- ( (Input.track_vx[trackn]-Input.vertex_x[vertexn])*Input.track_px[trackn] +  (Input.track_vy[trackn]-Input.vertex_y[vertexn])*Input.track_py[trackn])/(Input.track_pt[trackn]) * Input.track_pz[trackn]/Input.track_pt[trackn] );
	  d0Point_Vtx->Fill( (-(Input.track_vx[trackn]-Input.vertex_x[vertexn])*Input.track_py[trackn]+(Input.track_vy[trackn]-Input.vertex_y[vertexn])*Input.track_px[trackn])/Input.track_pt[trackn] );
	    dZ_Vtx->Fill( Input.track_dz[trackn] );
	    dZ_Vtx_LARGE->Fill( Input.track_dz[trackn] );
	    d0_Vtx->Fill( Input.track_d0[trackn] );
          
	  }
	}
      break; 
      }//vertice non ricostruito valore del beam spot
    }


//Vertex Association requirement

  chargePlusY=0;
  chargeMinusY=0;

  for(Int_t vertexn=0;vertexn<Input.numVertices;vertexn++)
    {
    //std::cout<<"vertices z: "<<Input.vertex_z[vertexn]<<endl;
    if(Input.vertex_z[vertexn]!=beamspot){  //vertice non ricostruito valore del beam spot
      if(fabs(Input.vertex_z[vertexn]-beamspot)<10){
        int fillCounter=0;
	for(Int_t trackn=0;trackn<Input.numTracks;trackn++){
      	  
	  double dZ_cut= (Input.track_vz[trackn]-Input.vertex_z[vertexn])- ( (Input.track_vx[trackn]-Input.vertex_x[vertexn])*Input.track_px[trackn] +  (Input.track_vy[trackn]-Input.vertex_y[vertexn])*Input.track_py[trackn])/(Input.track_pt[trackn]) * Input.track_pz[trackn]/Input.track_pt[trackn] ;
	  double d0_cut= (-(Input.track_vx[trackn]-Input.vertex_x[vertexn])*Input.track_py[trackn]+(Input.track_vy[trackn]-Input.vertex_y[vertexn])*Input.track_px[trackn])/Input.track_pt[trackn] ;
	  
	  //if ( fabs(track_vz[trackn]-vertex_z[vertexn])<1. )  //old cut in acceptance
	  if ( fabs(dZ_cut)<0.36 && fabs(d0_cut)<0.18 && Input.track_highPurity[trackn]==1 )
	    {
	    fillCounter++;
	    eta_AssVertex->Fill(Input.track_eta[trackn]);
	    phi_AssVertex->Fill(Input.track_phi[trackn]);
	    pt_AssVertex->Fill(Input.track_pt[trackn]);
	    normChi2_AssVertex->Fill(Input.track_normalizedChi2[trackn]);
            chi2_vs_pT_AssVertex->Fill(Input.track_normalizedChi2[trackn],Input.track_pt[trackn]);
            pt_vs_multip_AssVertex->Fill(Input.track_pt[trackn],Input.numTracks);
            pt_vs_ndof_AssVertex->Fill(Input.track_pt[trackn],Input.track_ndof[trackn]);
            ndof_AssVertex->Fill(Input.track_ndof[trackn]);
            if (Input.numTracks>100)    chi2_vs_pT_highMultip_AssVertex->Fill(Input.track_normalizedChi2[trackn],Input.track_pt[trackn]);
            else                  chi2_vs_pT_lowMultip_AssVertex->Fill(Input.track_normalizedChi2[trackn],Input.track_pt[trackn]);
	    
	    dZPoint_Ass->Fill( (Input.track_vz[trackn]-Input.vertex_z[vertexn])- ( (Input.track_vx[trackn]-Input.vertex_x[vertexn])*Input.track_px[trackn] +  (Input.track_vy[trackn]-Input.vertex_y[vertexn])*Input.track_py[trackn])/(Input.track_pt[trackn]) * Input.track_pz[trackn]/Input.track_pt[trackn] );
	    d0Point_Ass->Fill( (-(Input.track_vx[trackn]-Input.vertex_x[vertexn])*Input.track_py[trackn]+(Input.track_vy[trackn]-Input.vertex_y[vertexn])*Input.track_px[trackn])/Input.track_pt[trackn] );
	    dZ_Ass->Fill( Input.track_dz[trackn] );
	    d0_Ass->Fill( Input.track_d0[trackn] );

            if ( Input.track_py[trackn]>0. )  chargePlusY+=Input.track_charge[trackn];
            else                        chargeMinusY+=Input.track_charge[trackn];

	    }
          }
	  
        chargeAsymmetry_AssVertex->Fill(chargePlusY+chargeMinusY);
	}
      break; 
      }//vertice non ricostruito valore del beam spot
    }

}

  
//***** VERTEX properties *****

int contime=0;
cout<<"corro su "<<entries<<" entries"<<endl;
for(int eventn=0;eventn<entries;eventn++){
  fChain.GetEntry(eventn);

  if (realdata)
   if ( rejectRunLumi(Input.runNumber,Input.lumiBlock) ) continue; 

  int fill;
  if (Input.numVertices==1){
    if (Input.vertex_z[0]==beamspot) fill = 0;
    else                             fill = 1;
    }
  else fill = Input.numVertices;  
  vertexes->Fill(fill);

  if (Input.numVertices>1)
    deltaZ_v1v2->Fill( fabs(Input.vertex_z[0]-Input.vertex_z[1]) );
  
  for(Int_t vertexn=0;vertexn<Input.numVertices;vertexn++){
    if(Input.vertex_z[vertexn]!=beamspot){  //vertice non ricostruito valore del beam spot
	vertexesNum_NoutTrk->Fill(Input.vertex_nOutgoingTracks[vertexn]);
	vertexes_z->Fill(Input.vertex_z[vertexn]);
	vertexes_xy->Fill(Input.vertex_x[vertexn],Input.vertex_y[vertexn]);
    }//vertice non ricostruito valore del beam spot
  }

  for(Int_t vertexn=0;vertexn<Input.numVertices;vertexn++)
    {
    if(Input.vertex_z[0]!=beamspot){  //vertice non ricostruito valore del beam spot
      if(fabs(Input.vertex_z[vertexn]-beamspot)<10){
        contime++;
	for(Int_t trackn=0;trackn<Input.numTracks;trackn++){
	  deltaZ_trackPV->Fill(Input.track_vz[trackn]-Input.vertex_z[vertexn]);  
	  deltaZ_trackPV_ZOOM->Fill(Input.track_vz[trackn]-Input.vertex_z[vertexn]);  
	    deltaX_trackPV->Fill(Input.track_vx[trackn]-Input.vertex_x[vertexn]);  
	    deltaX_trackPV_ZOOM->Fill(Input.track_vx[trackn]-Input.vertex_x[vertexn]);  
	  deltaY_trackPV->Fill(Input.track_vy[trackn]-Input.vertex_y[vertexn]);  
	  deltaY_trackPV_ZOOM->Fill(Input.track_vy[trackn]-Input.vertex_y[vertexn]);  
          }
	break;       
      }
      }//vertice non ricostruito valore del beam spot
    }

}

cout<<"li gavemo contai: "<<contime<<endl;
double averageMultip = track_multip_AssVertex->GetMean();
TH1D* KNO_scaling = new TH1D("KNO_scaling","KNO_scaling",track_multip_AssVertex->GetNbinsX(),0.,double(track_multip_AssVertex->GetNbinsX())/averageMultip);
  KNO_scaling->GetXaxis()->SetTitle("n / < n >");
  KNO_scaling->GetYaxis()->SetTitle("< n >   P_{n}");
  for (int k=1; k<=KNO_scaling->GetNbinsX(); k++)
    KNO_scaling->SetBinContent(k,averageMultip*track_multip_AssVertex->GetBinContent(k));


if (realdata){

  //********* SetStatisticalError Real Data *********

  setStatError(eta_withVertex);
  setStatError(eta_All);
  setStatError(eta_AssVertex);
  setStatError(phi_withVertex);
  setStatError(phi_All);
  setStatError(phi_AssVertex);
  setStatError(pt_withVertex);
  setStatError(pt_All);
  setStatError(pt_AssVertex);
  setStatError(normChi2_withVertex);
  setStatError(normChi2_All);
  setStatError(normChi2_AssVertex);
  setStatError(vertexes);
  setStatError(vertexes_z);
  setStatError(deltaZ_trackPV);
  setStatError(vertexesNum_NoutTrk);
  setStatError(ndof_All);
  setStatError(ndof_withVertex);
  setStatError(ndof_AssVertex);
  setStatError(track_multip_All);
  setStatError(track_multip_withVertex);
  setStatError(track_multip_AssVertex);

  //****   marker styles  *****  

  eta_withVertex->SetMarkerStyle(22);
  eta_AssVertex->SetMarkerStyle(22);
  eta_All->SetMarkerStyle(22);
  phi_withVertex->SetMarkerStyle(22);
  phi_AssVertex->SetMarkerStyle(22);
  phi_All->SetMarkerStyle(22);
  pt_withVertex->SetMarkerStyle(22);
  pt_AssVertex->SetMarkerStyle(22);
  pt_All->SetMarkerStyle(22);
  normChi2_withVertex->SetMarkerStyle(22);
  normChi2_AssVertex->SetMarkerStyle(22);
  normChi2_All->SetMarkerStyle(22);

  vertexes_z->SetMarkerStyle(22);
  deltaZ_trackPV->SetMarkerStyle(22);
  vertexesNum_NoutTrk->SetMarkerStyle(22);

  vertexes->SetMarkerStyle(22);
  }

  vertexes->GetXaxis()->SetBinLabel(1,"BeamSpot");
  vertexes->GetXaxis()->SetBinLabel(2,"1 Vertex");
  vertexes->GetXaxis()->SetBinLabel(3,"2 Vertices");
  vertexes->GetXaxis()->SetBinLabel(4,"3 Vertices");
  vertexes->GetXaxis()->SetBinLabel(5,"4 Vertices");
  vertexes->GetXaxis()->SetTitle("N^{vtx}/evt");

  deltaZ_v1v2->GetXaxis()->SetTitle("|v^{1}_{z}-v^{1}_{z}|");


//***** saving histos *****

  std::string fileToOpen="histoDATA_fromChain.root";  
  TFile outFile((fileToOpen).c_str(),"RECREATE");
 
  eta_withVertex->Write();
  eta_All->Write();
  phi_withVertex->Write();
  phi_All->Write();
  pt_withVertex ->Write();
  pt_All->Write();
  normChi2_withVertex->Write();
  normChi2_All->Write();

  vertexes->Write();
  vertexes_z->Write();
  vertexes_xy->Write();
  deltaZ_trackPV->Write();
  vertexesNum_NoutTrk->Write();
  deltaZ_v1v2->Write();

  eta_AssVertex->Write();
  phi_AssVertex->Write();
  pt_AssVertex ->Write();
  normChi2_AssVertex->Write();
  
  hthrust_z_All->Write();
  hthrust_z_withVertex->Write();
  hthrust_z_AssVertex->Write();

  track_multip_All->Write();
  track_multip_withVertex->Write();
  track_multip_AssVertex->Write();
    chi2_vs_pT_All->Write();
    chi2_vs_pT_withVertex->Write();
    chi2_vs_pT_AssVertex->Write();
  chi2_vs_pT_lowMultip_All->Write();
  chi2_vs_pT_lowMultip_withVertex->Write();
  chi2_vs_pT_lowMultip_AssVertex->Write();
    chi2_vs_pT_highMultip_All->Write();
    chi2_vs_pT_highMultip_withVertex->Write();
    chi2_vs_pT_highMultip_AssVertex->Write();

  pt_vs_multip_All->Write();
  pt_vs_multip_withVertex->Write();
  pt_vs_multip_AssVertex->Write();  
    pt_vs_ndof_All->Write();        
    pt_vs_ndof_withVertex->Write(); 
    pt_vs_ndof_AssVertex->Write();  

  deltaX_trackPV->Write();
  deltaX_trackPV_ZOOM->Write(); 
    deltaY_trackPV->Write();  
    deltaY_trackPV_ZOOM->Write();  

    dZ_All->Write();
    d0_All->Write();
  dZPoint_Ass->Write();
  d0Point_Ass->Write();
    dZ_Ass->Write();
    d0_Ass->Write();
  dZPoint_Vtx->Write();
  d0Point_Vtx->Write();
    dZ_Vtx->Write();
    dZ_Vtx_LARGE->Write();
    d0_Vtx->Write();

   KNO_scaling->Write();

   ndof_All->Write();
   ndof_withVertex->Write();
   ndof_AssVertex->Write();
  
  chargeAsymmetry_All->Write();
  chargeAsymmetry_AssVertex->Write();
  
  outFile.Close();
}
TChain* CreateAODChain(const char* aDataDir, Int_t aRuns, Int_t offset)
{
  // creates chain of files in a given directory or file containing a list.
  // In case of directory the structure is expected as:
  // <aDataDir>/<dir0>/AliAOD.root
  // <aDataDir>/<dir1>/AliAOD.root
  // ...

  if (!aDataDir)
    return 0;

  Long_t id, size, flags, modtime;
  if (gSystem->GetPathInfo(aDataDir, &id, &size, &flags, &modtime))
  {
    printf("%s not found.\n", aDataDir);
    return 0;
  }

  TChain* chain = new TChain("aodTree");
  TChain* chaingAlice = 0;

  if (flags & 2)
  {
    TString execDir(gSystem->pwd());
    TSystemDirectory* baseDir = new TSystemDirectory(".", aDataDir);
    TList* dirList            = baseDir->GetListOfFiles();
    Int_t nDirs               = dirList->GetEntries();
    gSystem->cd(execDir);

    Int_t count = 0;

    for (Int_t iDir=0; iDir<nDirs; ++iDir)
    {
      TSystemFile* presentDir = (TSystemFile*) dirList->At(iDir);
      if (!presentDir || !presentDir->IsDirectory() || strcmp(presentDir->GetName(), ".") == 0 || strcmp(presentDir->GetName(), "..") == 0)
        continue;

      if (offset > 0)
      {
        --offset;
        continue;
      }

      if (count++ == aRuns)
        break;

      TString presentDirName(aDataDir);
      presentDirName += "/";
      presentDirName += presentDir->GetName();
      chain->Add(presentDirName + "/AliAOD.root/aodTree");
      // cerr<<presentDirName<<endl;
    }

  }
  else
  {
    // Open the input stream
    ifstream in;
    in.open(aDataDir);

    Int_t count = 0;

    // Read the input list of files and add them to the chain
    TString aodfile;
    while(in.good())
    {
      in >> aodfile;
      if (!aodfile.Contains("root")) continue; // protection

      if (offset > 0)
      {
        --offset;
        continue;
      }

      if (count++ == aRuns)
        break;

      // add aod file
      chain->Add(aodfile);
    }

    in.close();
  }

  return chain;

} // end of TChain* CreateAODChain(const char* aDataDir, Int_t aRuns, Int_t offset)
예제 #18
0
void v_src_fit(){

  int CRunNumberR=20591;
  int endCRunNumberR=22461;
  int HeRunNumberR=20596;
  int endHeRunNumberR=20789;
// NOTE: There is a problem with the BCM values. When fixed, swap below and above lines.
//  int endHeRunNumberR=20879;

  TString Q2 = "1.0";
  TString vartodraw = "PriKineR.Q2 / (PriKineR.nu * 2 * 0.9315)";
//Range is of the form (bins, start, end)
//  TString range = "(800,0.5,4.0)";
  double bins = 50;
  double plotmin = 0.5;
  double plotmax = 2.0;
  TString title = "12C/3He x with Target cut, Run # ";
  title += CRunNumberR;
  title += " & ";
  title += HeRunNumberR;

	TCut cut = "";  
	TCut kinematics = "PriKineR.Q2<10 && GoodElectron==1 && PriKineR.nu<10";
//	TCut eventtype = "D.evtypebits&(1<<1)>0";
	TCut eventtype = "(D.evtypebits&2)==2";
	TCut gold = "ExTgtCor_R.dp>-0.04 && ExTgtCor_R.dp<0.055";
	TCut target = "ReactPt_R.z>-0.172 && ReactPt_R.z<0.175";
	TCut sieve = "abs(ExTgtCor_R.ph)<0.03 && abs(ExTgtCor_R.th)<0.06";

//	TCut cut = "";
//	TCut eventtype = "";
//	TCut target = "";
//	TCut sieve = "";
//	TCut gold = "";

  TCut cuts = kinematics && target && sieve && gold && eventtype;

  TString whattodraw = vartodraw;
//  whattodraw += ">>";
//  whattodraw += title;
//  whattodraw += range;
  TString whattodrawC = whattodraw;
  whattodrawC += ">>histCR";
  TString whattodrawHe = whattodraw;
  whattodrawHe += ">>histHeR";
  TChain* chainCR = new TChain("T");
  TChain* chainHeR = new TChain("T");

  gStyle->SetErrorX(.25);
  gStyle->SetEndErrorSize(.25);
  ifstream inp;
  ofstream out;

  TString filenameCR;
  TString filenameHeR;


// Below is the loop for adding chains for the Carbon run
  for (int thisCRunNumberR=CRunNumberR; thisCRunNumberR<(endCRunNumberR+1); thisCRunNumberR++)
  {
 		if(thisCRunNumberR==20592){thisCRunNumberR=20731;}
		if(thisCRunNumberR==20735){thisCRunNumberR=20762;}
		if(thisCRunNumberR==20765){thisCRunNumberR=22380;}
		if(thisCRunNumberR==22381){thisCRunNumberR=22389;}
		if(thisCRunNumberR==22390){thisCRunNumberR=22425;}
		if(thisCRunNumberR==22427){thisCRunNumberR=22461;}
		if(thisCRunNumberR==22462){thisCRunNumberR=99999;}

   for (int t=0; t<1000;t++)
    {
      filenameCR = "/home/ellie/physics/e05-102/terabyte/ROOTfiles/e05102_R_";
      filenameCR += thisCRunNumberR;
      if (t!=0)
      {
        filenameCR += "_";
        filenameCR += t;
      }
      filenameCR += ".root";
      ifstream ifileCR(filenameCR);
      if (ifileCR)
      {
        cout << "Adding file to chainCR: " << filenameCR << endl;
        chainCR->Add(filenameCR);
      }
      else
      {
        cout << "File " << filenameCR << " does not exist. Ending here." << endl;
        t=9999999;
      }

    }
	
// Uncommenting the line below will let the code only go through one run (Good for debugging purposes)
//	thisCRunNumberR = 99999999;

  }




// Below is the loop for adding chains for the 3He run

  for (int thisHeRunNumberR=HeRunNumberR;thisHeRunNumberR<(endHeRunNumberR+1); thisHeRunNumberR++)
  {
	// Skipping Vertical Carbon Runs
	if(thisHeRunNumberR==20591){thisHeRunNumberR=20596;}
	if(thisHeRunNumberR==20731){thisHeRunNumberR=20738;}
	if(thisHeRunNumberR==20732){thisHeRunNumberR=20738;}
	if(thisHeRunNumberR==20733){thisHeRunNumberR=20738;}
	if(thisHeRunNumberR==20734){thisHeRunNumberR=20738;}
	if(thisHeRunNumberR==20736){thisHeRunNumberR=20738;}
	if(thisHeRunNumberR==20737){thisHeRunNumberR=20738;}
	if(thisHeRunNumberR==20762){thisHeRunNumberR=20789;}
	if(thisHeRunNumberR==20763){thisHeRunNumberR=20789;}
	if(thisHeRunNumberR==20764){thisHeRunNumberR=20789;}
	if(thisHeRunNumberR==20791){thisHeRunNumberR=20814;}
	if(thisHeRunNumberR==20792){thisHeRunNumberR=20814;}

	// Skipping Longitudinal Carbon Runs
	if(thisHeRunNumberR==22380){thisHeRunNumberR=22393;}
	if(thisHeRunNumberR==22389){thisHeRunNumberR=22393;}
	if(thisHeRunNumberR==22425){thisHeRunNumberR=22436;}
	if(thisHeRunNumberR==22426){thisHeRunNumberR=22436;}

	// Skipping Transverse Carbon Runs
	if(thisHeRunNumberR==22461){thisHeRunNumberR=22465;}
	if(thisHeRunNumberR==20591){thisHeRunNumberR=20596;}

   if(thisHeRunNumberR==22397){thisHeRunNumberR=22398;}
    for (int t=0; t<1000;t++)
    {
      filenameHeR = "/home/ellie/physics/e05-102/terabyte/ROOTfiles/e05102_R_";
      filenameHeR += thisHeRunNumberR;
      if (t!=0)
      {
        filenameHeR += "_";
        filenameHeR += t;
      }
      filenameHeR += ".root";
      ifstream ifileHeR(filenameHeR);
      if (ifileHeR)
      {
        cout << "Adding file to chainHeR: " << filenameHeR << endl;
        chainHeR->Add(filenameHeR);
      }
      else
      {
        cout << "File " << filenameHeR << " does not exist. Ending here." << endl;
        t=9999999;
      }

    }

// Uncommenting the line below will let the code only go through one run (Good for debugging purposes)
//	thisHeRunNumberR = 999999999;

  }


	
	gStyle->SetPalette(1);
	gStyle->SetOptFit(0001);

	// Defines Canvas
	TCanvas *c1 = new TCanvas("c1","x of 12C and 3He",1360,800);//x,y
	pad01 = new TPad("pad01","pad01",0.0000,0.8333,0.2000,1.0000,0,0,0);
	pad02 = new TPad("pad02","pad02",0.2000,0.8333,0.4000,1.0000,0,0,0);
	pad03 = new TPad("pad03","pad03",0.4000,0.8333,0.6000,1.0000,0,0,0);
	pad04 = new TPad("pad04","pad04",0.6000,0.8333,0.8000,1.0000,0,0,0);
	pad05 = new TPad("pad05","pad05",0.0000,0.6666,0.2000,0.8333,0,0,0);
	pad06 = new TPad("pad06","pad06",0.2000,0.6666,0.4000,0.8333,0,0,0);
	pad07 = new TPad("pad07","pad07",0.4000,0.6666,0.6000,0.8333,0,0,0);
	pad08 = new TPad("pad08","pad08",0.6000,0.6666,0.8000,0.8333,0,0,0);
	pad09 = new TPad("pad09","pad09",0.0000,0.3333,0.3333,0.6666,0,0,0);
	pad10 = new TPad("pad10","pad10",0.3333,0.3333,0.6666,0.6666,0,0,0);
	pad11 = new TPad("pad11","pad11",0.6666,0.3333,1.0000,0.6666,0,0,0);
	pad12 = new TPad("pad12","pad12",0.0000,0.0000,0.3333,0.3333,0,0,0);
	pad13 = new TPad("pad13","pad13",0.3333,0.0000,0.6666,0.3333,0,0,0);
	pad14 = new TPad("pad14","pad14",0.6666,0.0000,1.0000,0.3333,0,0,0);
	pad15 = new TPad("pad15","pad15",0.8000,0.8333,1.0000,1.0000,0,0,0);
	pad16 = new TPad("pad16","pad16",0.8000,0.6666,1.0000,0.8333,0,0,0);
	pad01->Draw();pad02->Draw();pad03->Draw();pad04->Draw();pad05->Draw();pad06->Draw();pad07->Draw();pad08->Draw();pad09->Draw();pad10->Draw();pad11->Draw();pad12->Draw();pad13->Draw();pad14->Draw();pad15->Draw();pad16->Draw();

	// Everything below here makes graphs for each section of the canvas

	pad01->cd();
	TString titledpHe = "dp Cut from 3He Runs";
	cout << "Drawing " << titledpHe << "..." << endl;
	chainHeR->Draw("ExTgtCor_R.dp>>HedpNoCut(400,-0.08,0.08)", "", "");
	chainHeR->Draw("ExTgtCor_R.dp>>HedpCut(400,-0.08,0.08)", gold, "");
	HedpNoCut->SetTitle(titledpHe);
	HedpNoCut->Draw();
	HedpCut->SetLineColor(kBlack);
	HedpCut->SetFillColor(kViolet);
	HedpCut->Draw("same");

	pad05->cd();
	TString titledpC = "dp Cut from 12C Runs";
	cout << "Drawing " << titledpC << "..." << endl;
	chainCR->Draw("ExTgtCor_R.dp>>CdpNoCut(400,-0.08,0.08)", "", "");
	chainCR->Draw("ExTgtCor_R.dp>>CdpCut(400,-0.08,0.08)", gold, "");
	CdpNoCut->SetTitle(titledpC);
	CdpNoCut->Draw();
	CdpCut->SetLineColor(kBlack);
	CdpCut->SetFillColor(kViolet);
	CdpCut->Draw("same");

	pad02->cd();
	TString titleTargetHe = "Target Cut for 3He Runs";
	cout << "Drawing " << titleTargetHe << "..." << endl;
	chainHeR->Draw("ReactPt_R.z>>HeReactZNoCut(400,-0.3,0.3)", "", "");
	chainHeR->Draw("ReactPt_R.z>>HeReactZCut(400,-0.3,0.3)", target, "");
	HeReactZNoCut->SetTitle(titleTargetHe);
	HeReactZNoCut->Draw();
	HeReactZCut->SetLineColor(kBlack);
	HeReactZCut->SetFillColor(kViolet);
	HeReactZCut->Draw("same");

	pad06->cd();
	TString titleTargetC = "Target Cut for 12C Runs";
	cout << "Drawing " << titleTargetC << "..." << endl;
	chainCR->Draw("ReactPt_R.z>>CReactZNoCut(400,-0.3,0.3)", "", "");
	chainCR->Draw("ReactPt_R.z>>CReactZCut(400,-0.3,0.3)", target, "");
	CReactZNoCut->SetTitle(titleTargetC);
	CReactZNoCut->Draw();
	CReactZCut->SetLineColor(kBlack);
	CReactZCut->SetFillColor(kViolet);
	CReactZCut->Draw("same");

	pad03->cd();
	TString titleThetaPhiHe = "Theta and Phi, No Cut, for 3He";
	cout << "Drawing " << titleThetaPhiHe << "..." << endl;
	chainHeR->Draw("ExTgtCor_R.th:ExTgtCor_R.ph>>HeSieveNoCut(100,-0.05,0.05,100,-0.1,0.1)", target, "");
	HeSieveNoCut->SetTitle(titleThetaPhiHe);
	HeSieveNoCut->SetStats(kFALSE);
	HeSieveNoCut->Draw("COLZ");

	pad07->cd();
	TString titleThetaPhiC = "Theta and Phi, No Cut, for 12C";
	cout << "Drawing " << titleThetaPhiC << "..." << endl;
	chainCR->Draw("ExTgtCor_R.th:ExTgtCor_R.ph>>CSieveNoCut(100,-0.05,0.05,100,-0.1,0.1)", target, "");
	CSieveNoCut->SetTitle(titleThetaPhiC);
	CSieveNoCut->SetStats(kFALSE);
	CSieveNoCut->Draw("COLZ");

	pad04->cd();
	TString titleThetaCutHe = "Theta and Phi Cut for 3He";
	cout << "Drawing " << titleThetaCutHe << "..." << endl;
	chainHeR->Draw("ExTgtCor_R.th:ExTgtCor_R.ph>>HeSieveCut(100,-0.05,0.05,100,-0.1,0.1)", target && sieve, "");
	HeSieveCut->SetTitle(titleThetaCutHe);
	HeSieveCut->SetStats(kFALSE);
	HeSieveCut->Draw("COLZ");

	pad08->cd();
	TString titleThetaCutC = "Theta and Phi Cut for 12C";
	cout << "Drawing " << titleThetaCutC << "..." << endl;
	chainCR->Draw("ExTgtCor_R.th:ExTgtCor_R.ph>>CSieveCut(100,-0.05,0.05,100,-0.1,0.1)", target && sieve, "");
	CSieveCut->SetTitle(titleThetaCutC);
	CSieveCut->SetStats(kFALSE);
	CSieveCut->Draw("COLZ");

	pad15->cd();
	TString titleQ2WHe = "Q2 v. Nu for 3He";
	cout << "Drawing " << titleQ2WHe << "..." << endl;
	chainHeR->Draw("PriKineR.Q2:PriKineR.nu>>Q2WHe(100,0.3,0.8,400,0,1.6)", cuts, "");
	Q2WHe->SetTitle(titleQ2WHe);
	Q2WHe->SetStats(kFALSE);
	Q2WHe->Draw("COLZ");

	pad16->cd();
	TString titleQ2WC = "Q2 v. Nu for 12C";
	cout << "Drawing " << titleQ2WC << "..." << endl;
	chainCR->Draw("PriKineR.Q2:PriKineR.nu>>Q2WC(100,0.3,0.8,400,0,1.6,100)", cuts, "");
	Q2WC->SetTitle(titleQ2WC);
	Q2WC->SetStats(kFALSE);
	Q2WC->Draw("COLZ");


	pad09->cd();
	TString titleC = "x for 12C at Q2 of ";
	titleC += Q2;
//	titleC += " and Target Cut of ";
//	titleC += target;
	cout << "Drawing " << titleC << "..." << endl;
	TH1F *histCR = new TH1F("histCR",titleC,bins,plotmin,plotmax);
	histCR->Sumw2();
	chainCR->Draw(whattodrawC, cuts, "E");
	histCR.Scale(1/0.0161297);
	histCR->Draw();
	TF1 *fitC1 = new TF1("fitC1","[0]*exp(-x*[1])",1.45,1.6);
	fitC1->SetParNames("C Red p1","C Red p2");
	Double_t fitC1const = fitC1->GetParameter(0);
	Double_t fitC1expconst = fitC1->GetParameter(1);
//	Double_t fitC1exp = fitC1->GetParameter(2);
	Double_t fitC1consterror = fitC1->GetParError(0);
	Double_t fitC1expconsterror = fitC1->GetParError(1);
//	Double_t fitC1experror = fitC1->GetParError(2);
	fitC1->SetLineColor(kRed);
	TF1 *fit2 = new TF1("fitC2","[0]*exp(-x*[1])",1.6,1.8);
	fitC2->SetParNames("C Blue p1","C Blue p2");
	Double_t fitC2const = fitC2->GetParameter(0);
	Double_t fitC2expconst = fitC2->GetParameter(1);
//	Double_t fitC2exp = fitC2->GetParameter(2);
	Double_t fitC2consterror = fitC2->GetParError(0);
	Double_t fitC2expconsterror = fitC2->GetParError(1);
//	Double_t fitC2experror = fitC2->GetParError(2);
	fitC2->SetLineColor(kBlue);
	TF1 *fitC3 = new TF1("fitC3","[0]*exp(-x*[1])",1.35,1.45);
	fitC3->SetParNames("C Green p1","C Green p2");
	Double_t fitC3const = fitC3->GetParameter(0);
	Double_t fitC3expconst = fitC3->GetParameter(1);
//	Double_t fitC3exp = fitC3->GetParameter(2);
	Double_t fitC3consterror = fitC3->GetParError(0);
	Double_t fitC3expconsterror = fitC3->GetParError(1);
//	Double_t fitC3experror = fitC3->GetParError(2);
	fitC3->SetLineColor(kGreen);

	histCR->Fit("fitC2","R");
	histCR->Fit("fitC3","R+");
	histCR->Fit("fitC1","R+");
	

	pad12->cd();
	pad12->SetLogy();
	cout << "Drawing " << titleC << " in log scale..." << endl;
	TH1F *histCR = new TH1F("histCR",titleC,bins,plotmin,plotmax);
	histCR->Sumw2();
	chainCR->Draw(whattodrawC, cuts, "E");
	histCR->Draw();
	histCR->Fit("fitC1","R");
	histCR->Fit("fitC3","R+");
	histCR->Fit("fitC2","R+");

	pad10->cd();
	TString titleHe = "x for 3He at Q2 of ";
	titleHe += Q2;
//	titleHe += " and Target Cut of ";
//	titleHe += target;
	cout << "Drawing " << titleHe << "..." << endl;
	TH1F *histHeR = new TH1F("histHeR",titleHe,bins,plotmin,plotmax);
	histHeR->Sumw2();
	chainHeR->Draw(whattodrawHe, cuts, "E");
	histHeR.Scale(1/2.33878);
	histHeR->Draw();
	TF1 *fitHe1 = new TF1("fitHe1","[0]*exp(-x*[1])",1.45,1.6);
	fitHe1->SetParNames("He Red p1", "He Red p2");
	Double_t fitHe1const = fitHe1->GetParameter(0);
	Double_t fitHe1expconst = fitHe1->GetParameter(1);
//	Double_t fitHe1exp = fitHe1->GetParameter(2);
	Double_t fitHe1consterror = fitHe1->GetParError(0);
	Double_t fitHe1expconsterror = fitHe1->GetParError(1);
//	Double_t fitHe1experror = fitHe1->GetParError(2);
	fitHe1->SetLineColor(kRed);
	TF1 *fitHe2 = new TF1("fitHe2","[0]*exp(-x*[1])",1.6,1.8);
	fitHe2->SetParNames("He Blue p1","He Blue p2");
	Double_t fitHe2const = fitHe2->GetParameter(0);
	Double_t fitHe2expconst = fitHe2->GetParameter(1);
//	Double_t fitHe2exp = fitHe2->GetParameter(2);
	Double_t fitHe2consterror = fitHe2->GetParError(0);
	Double_t fitHe2expconsterror = fitHe2->GetParError(1);
//	Double_t fitHe2experror = fitHe2->GetParError(2);
	fitHe2->SetLineColor(kBlue);
	TF1 *fitHe3 = new TF1("fitHe3","[0]*exp(-x*[1])",1.35,1.45);
	fitHe3->SetParNames("He Green p1","He Green p2");
	Double_t fitHe3const = fitHe3->GetParameter(0);
	Double_t fitHe3expconst = fitHe3->GetParameter(1);
//	Double_t fitHe3exp = fitHe3->GetParameter(2);
	Double_t fitHe3consterror = fitHe3->GetParError(0);
	Double_t fitHe3expconsterror = fitHe3->GetParError(1);
//	Double_t fitHe3experror = fitHe3->GetParError(2);
	fitHe3->SetLineColor(kGreen);

	histHeR->Fit("fitHe2","R+");
	histHeR->Fit("fitHe3","R+");
	histHeR->Fit("fitHe1","R+");
	
	pad13->cd();
	pad13->SetLogy();
	cout << "Drawing " << titleHe << " in log scale..." << endl;
	TH1F *histHeR = new TH1F("histHeR",titleHe,bins,plotmin,plotmax);
	histHeR->Sumw2();
	chainHeR->Draw(whattodrawHe, cuts, "E");
	histHeR->Draw();
	histHeR->Fit("fitHe1","R+");
	histHeR->Fit("fitHe3","R+");
	histHeR->Fit("fitHe2","R+");

	pad11->cd();
	TString titleCoverHe = "12C/3He for Q2 of ";
	titleCoverHe += Q2;
//	titleCoverHe += " and Target Cut of ";
//	titleCoverHe += target;
	cout << "Drawing " << titleCoverHe << "..." << endl;
	TH1F *histCoverHeR = new TH1F("histCoverHeR",titleCoverHe,bins,plotmin,plotmax);
	histCoverHeR->Sumw2();
	histCoverHeR->Divide(histCR,histHeR,1,0.0918143);
	histCoverHeR->Draw("E");

	pad14->cd();
	pad14->SetLogy();
	cout << "Drawing " << titleCoverHe << " in log scale..." << endl;
	TH1F *histCoverHeR = new TH1F("histCoverHeR",titleCoverHe,bins,plotmin,plotmax);
	histCoverHeR->Sumw2();
	histCoverHeR->Divide(histCR,histHeR,1,0.0918143);
	histCoverHeR->Draw("E");

   
	TString imagename = "xbj_scaling_plots/Vertical_xbj_scaling_plots_all_at_Q2_of_";
	imagename += Q2;
	imagename += ".png";
	c1->Print(imagename);

	cout << "All done!" << endl;


}
예제 #19
0
void Diagnostics()
{
  gSystem->Load("src/RunData12.so");
  RunData12 * RD = new RunData12();
  const Int_t NBINS=400; // NUMBER OF BINS

  // open chain
  TChain * tr = new TChain("str");
  tr->Add("./redset/Red*.root");
  Float_t E12,Pt,Eta,Phi,M12,Z,b_pol,y_pol;
  Bool_t kicked,isConsistent;
  Int_t TrigBits,runnum,bx,ClIndex;
  Float_t N12;

  Float_t E12_min,Pt_min,Eta_min,Phi_min;
  Float_t E12_max,Pt_max,Eta_max,Phi_max;
  E12_min=Pt_min=Eta_min=Phi_min=1000;
  E12_max=Pt_max=Eta_max=Phi_max=0;

  str->SetBranchAddress("runnum",&runnum);
  str->SetBranchAddress("Bunchid7bit",&bx);
  str->SetBranchAddress("E12",&E12);
  str->SetBranchAddress("Pt",&Pt);
  str->SetBranchAddress("Eta",&Eta);
  str->SetBranchAddress("Phi",&Phi);
  str->SetBranchAddress("M12",&M12);
  str->SetBranchAddress("Z",&Z);
  str->SetBranchAddress("TrigBits",&TrigBits);
  str->SetBranchAddress("N12",&N12);
  str->SetBranchAddress("ClIndex",&ClIndex);
  Int_t runnum_tmp=0;

  
  // get kinematics ranges for eta,Pt,Phi using the reduced data set and looking for maxima and minima
  // -- this is useful for looking at kinematic distrbutions beyond the kinematic boundaries set in Bin_Splitter.C
  // -- below there is a section to get the kinematic ranges using Bin_Splitter.C; comment either this section
  //    or the next to choose which one to use
  /*
  for(Int_t x=0; x<tr->GetEntries(); x++)
  {
    if((x%100000)==0) printf("computing kin ranges: %.2f%%\n",100*((Float_t)x)/((Float_t)tr->GetEntries()));
    tr->GetEntry(x);
    kicked = RD->Kicked(runnum,bx);
    if(runnum!=runnum_tmp)
    {
      b_pol = RD->BluePol(runnum);
      y_pol = RD->YellPol(runnum);
      isConsistent = RD->RellumConsistent(runnum);
      runnum_tmp=runnum;
    }
    // n photon cut
    //if(N12==1 && kicked==0 && isConsistent==1 && b_pol*y_pol!=0)
    // pi0 cut
    if(fabs(M12-0.135)<0.1 && Z<0.8 && (TrigBits&0x200) && N12==2 && kicked==0 && isConsistent==1 && b_pol*y_pol!=0 && Pt<15)
    {
      E12_min = (E12 < E12_min) ? E12:E12_min;
      Pt_min  = (Pt  < Pt_min)  ? Pt:Pt_min;
      Eta_min = (Eta < Eta_min) ? Eta:Eta_min;
      Phi_min = (Phi < Phi_min) ? Phi:Phi_min;

      E12_max = (E12 > E12_max) ? E12:E12_max;
      Pt_max  = (Pt  > Pt_max)  ? Pt:Pt_max;
      Eta_max = (Eta > Eta_max) ? Eta:Eta_max;
      Phi_max = (Phi > Phi_max) ? Phi:Phi_max;
    };
  };
  */


  // get kinematic ranges using the current binning set by Bin_Splitter.C
  // -- choose this section or the previous one to set the kinematic ranges to plot in diag.root 
  ///*
  Int_t phi_bins0, eta_bins0, pt_bins0, en_bins0;
  if(gSystem->Getenv("PHI_BINS")==NULL){fprintf(stderr,"ERROR: source env vars\n"); return;};
  sscanf(gSystem->Getenv("PHI_BINS"),"%d",&phi_bins0);
  sscanf(gSystem->Getenv("ETA_BINS"),"%d",&eta_bins0);
  sscanf(gSystem->Getenv("PT_BINS"),"%d",&pt_bins0);
  sscanf(gSystem->Getenv("EN_BINS"),"%d",&en_bins0);
  const Int_t phi_bins = phi_bins0;
  const Int_t eta_bins = eta_bins0;
  const Int_t pt_bins = pt_bins0;
  const Int_t en_bins = en_bins0;
  Float_t phi_div[phi_bins+1];
  Float_t eta_div[eta_bins+1];
  Float_t pt_div[pt_bins+1];
  Float_t en_div[en_bins+1];
  char phi_div_env[phi_bins+1][20];
  char eta_div_env[eta_bins+1][20];
  char pt_div_env[pt_bins+1][20];
  char en_div_env[en_bins+1][20];
  for(Int_t i=0; i<=phi_bins; i++)
  {
    sprintf(phi_div_env[i],"PHI_DIV_%d",i);
    sscanf(gSystem->Getenv(phi_div_env[i]),"%f",&(phi_div[i]));
    printf("%s %f\n",phi_div_env[i],phi_div[i]);
  };
  for(Int_t i=0; i<=eta_bins; i++)
  {
    sprintf(eta_div_env[i],"ETA_DIV_%d",i);
    sscanf(gSystem->Getenv(eta_div_env[i]),"%f",&(eta_div[i]));
    printf("%s %f\n",eta_div_env[i],eta_div[i]);
  };
  for(Int_t i=0; i<=pt_bins; i++)
  {
    sprintf(pt_div_env[i],"PT_DIV_%d",i);
    sscanf(gSystem->Getenv(pt_div_env[i]),"%f",&(pt_div[i]));
    printf("%s %f\n",pt_div_env[i],pt_div[i]);
  };
  for(Int_t i=0; i<=en_bins; i++)
  {
    sprintf(en_div_env[i],"EN_DIV_%d",i);
    sscanf(gSystem->Getenv(en_div_env[i]),"%f",&(en_div[i]));
    printf("%s %f\n",en_div_env[i],en_div[i]);
  };
  sscanf(gSystem->Getenv("PHI_LOW"),"%f",&Phi_min);
  sscanf(gSystem->Getenv("PHI_HIGH"),"%f",&Phi_max);
  sscanf(gSystem->Getenv("ETA_LOW"),"%f",&Eta_min);
  sscanf(gSystem->Getenv("ETA_HIGH"),"%f",&Eta_max);
  sscanf(gSystem->Getenv("PT_LOW"),"%f",&Pt_min);
  sscanf(gSystem->Getenv("PT_HIGH"),"%f",&Pt_max);
  sscanf(gSystem->Getenv("EN_LOW"),"%f",&E12_min);
  sscanf(gSystem->Getenv("EN_HIGH"),"%f",&E12_max);
  //*/

  
  // load run exclusion trees
  TTree * exclusion_sph = new TTree("exclusion_sph","exclusion_sph");
  TTree * exclusion_pi0 = new TTree("exclusion_pi0","exclusion_pi0");
  TTree * exclusion_thr = new TTree("exclusion_thr","exclusion_thr");
  exclusion_sph->ReadFile("exclusion_list_sph","runnum/I");
  exclusion_pi0->ReadFile("exclusion_list_pi0","runnum/I");
  exclusion_thr->ReadFile("exclusion_list_thr","runnum/I");
  Bool_t exclude_sph,exclude_pi0,exclude_thr;
  Int_t rn_sph,rn_pi0,rn_thr;
  exclusion_sph->SetBranchAddress("runnum",&rn_sph);
  exclusion_pi0->SetBranchAddress("runnum",&rn_pi0);
  exclusion_thr->SetBranchAddress("runnum",&rn_thr);


  TH2D * sph_pt_vs_eta = new TH2D("sph_pt_vs_eta","single #gamma :: p_{T} vs. #eta",NBINS,Eta_min,Eta_max,NBINS,0,Pt_max);
  TH2D * sph_en_vs_eta = new TH2D("sph_en_vs_eta","single #gamma :: E vs. #eta",NBINS,Eta_min,Eta_max,NBINS,0,E12_max);
  TH2D * sph_pt_vs_phi = new TH2D("sph_pt_vs_phi","single #gamma :: p_{T} vs. #phi",NBINS,-3.14,3.14,NBINS,0,Pt_max);
  TH2D * sph_en_vs_phi = new TH2D("sph_en_vs_phi","single #gamma :: E vs. #phi",NBINS,-3.14,3.14,NBINS,0,E12_max);
  TH2D * sph_eta_vs_phi = new TH2D("sph_eta_vs_phi","single #gamma :: #eta vs. #phi",NBINS,-3.14,3.14,NBINS,Eta_min,Eta_max);
  TH2D * sph_en_vs_pt = new TH2D("sph_en_vs_pt","single #gamma :: E vs. p_{T}",NBINS,0,Pt_max,NBINS,0,E12_max);

  TH2D * pi0_pt_vs_eta = new TH2D("pi0_pt_vs_eta","#pi^{0} (naive M cut) :: p_{T} vs. #eta",NBINS,Eta_min,Eta_max,NBINS,0,Pt_max);
  TH2D * pi0_en_vs_eta = new TH2D("pi0_en_vs_eta","#pi^{0} (naive M cut) :: E vs. #eta",NBINS,Eta_min,Eta_max,NBINS,0,E12_max);
  TH2D * pi0_pt_vs_phi = new TH2D("pi0_pt_vs_phi","#pi^{0} (naive M cut) :: p_{T} vs. #phi",NBINS,-3.14,3.14,NBINS,0,Pt_max);
  TH2D * pi0_en_vs_phi = new TH2D("pi0_en_vs_phi","#pi^{0} (naive M cut) :: E vs. #phi",NBINS,-3.14,3.14,NBINS,0,E12_max);
  TH2D * pi0_eta_vs_phi = new TH2D("pi0_eta_vs_phi","#pi^{0} (naive M cut) :: #eta vs. #phi",NBINS,-3.14,3.14,NBINS,Eta_min,Eta_max);
  TH2D * pi0_en_vs_pt = new TH2D("pi0_en_vs_pt","#pi^{0} (naive M cut) :: E vs. p_{T}",NBINS,0,Pt_max,NBINS,0,E12_max);

  TH2D * thr_pt_vs_eta = new TH2D("thr_pt_vs_eta","N_{#gamma}>2 :: p_{T} vs. #eta",NBINS,Eta_min,Eta_max,NBINS,0,Pt_max);
  TH2D * thr_en_vs_eta = new TH2D("thr_en_vs_eta","N_{#gamma}>2 :: E vs. #eta",NBINS,Eta_min,Eta_max,NBINS,0,E12_max);
  TH2D * thr_pt_vs_phi = new TH2D("thr_pt_vs_phi","N_{#gamma}>2 :: p_{T} vs. #phi",NBINS,-3.14,3.14,NBINS,0,Pt_max);
  TH2D * thr_en_vs_phi = new TH2D("thr_en_vs_phi","N_{#gamma}>2 :: E vs. #phi",NBINS,-3.14,3.14,NBINS,0,E12_max);
  TH2D * thr_eta_vs_phi = new TH2D("thr_eta_vs_phi","N_{#gamma}>2 :: #eta vs. #phi",NBINS,-3.14,3.14,NBINS,Eta_min,Eta_max);
  TH2D * thr_en_vs_pt = new TH2D("thr_en_vs_pt","N_{#gamma}>2 :: E vs. p_{T}",NBINS,0,Pt_max,NBINS,0,E12_max);

  TH2D * pi0_z_vs_eta = new TH2D("pi0_z_vs_eta","#pi^{0} (naive M cut) :: Z vs. #eta",NBINS,Eta_min,Eta_max,NBINS,0,1);
  TH2D * pi0_z_vs_phi = new TH2D("pi0_z_vs_phi","#pi^{0} (naive M cut) :: Z vs. #phi",NBINS,-3.14,3.14,NBINS,0,1);

  TH1D * mass_dist = new TH1D("mass_dist","M_{#gamma#gamma} distribution (#pi^{0} cuts without mass cut)",NBINS,0,1);
  TH1D * z_dist = new TH1D("z_dist","Z distribution (N12==2, jet1, abs(M12-0.135)<0.1, kicked==0)",NBINS,0,1);
  TH1D * trig_dist = new TH1D("trig_dist","TrigBits distribution (N12==2)",NBINS,7500,33500);
  
  TH2D * mass_vs_en = new TH2D("mass_vs_en","M_{#gamma#gamma} vs. E_{#gamma#gamma} (#pi^{0} cuts without mass cut)",
    NBINS,0,E12_max,NBINS,0,1);
  TH2D * mass_vs_pt = new TH2D("mass_vs_pt","M_{#gamma#gamma} vs. p_{T} (#pi^{0} cuts without mass cut)",
    NBINS,0,Pt_max,NBINS,0,1);

  TH1D * mass_dist_for_enbin[10];
  char mass_dist_for_enbin_n[10][64];
  char mass_dist_for_enbin_t[10][256];
  for(Int_t ee=0; ee<10; ee++)
  {
    sprintf(mass_dist_for_enbin_n[ee],"mass_dist_for_enbin%d",ee);
    sprintf(mass_dist_for_enbin_t[ee],"M_{#gamma#gamma} distribution for E_{#gamma#gamma}#in[%d,%d) GeV",ee*10,(ee+1)*10);
    mass_dist_for_enbin[ee] = new TH1D(mass_dist_for_enbin_n[ee],mass_dist_for_enbin_t[ee],NBINS,0,1);
  };

  runnum_tmp=0;
  Int_t ENT = tr->GetEntries();
  //ENT=10000;
  for(Int_t x=0; x<ENT; x++)
  {
    if((x%100000)==0) printf("filling histograms: %.2f%%\n",100*((Float_t)x)/((Float_t)ENT));
    tr->GetEntry(x);
    kicked = RD->Kicked(runnum,bx);
    if(runnum!=runnum_tmp)
    {
      b_pol = RD->BluePol(runnum);
      y_pol = RD->YellPol(runnum);
      isConsistent = RD->RellumConsistent(runnum);
      runnum_tmp=runnum;
      exclude_sph=0;
      exclude_pi0=0;
      exclude_thr=0;
      for(Int_t xx=0; xx<exclusion_sph->GetEntries(); xx++) { exclusion_sph->GetEntry(xx); if(runnum==rn_sph) exclude_sph=1; };
      for(Int_t xx=0; xx<exclusion_pi0->GetEntries(); xx++) { exclusion_pi0->GetEntry(xx); if(runnum==rn_pi0) exclude_pi0=1; };
      for(Int_t xx=0; xx<exclusion_thr->GetEntries(); xx++) { exclusion_thr->GetEntry(xx); if(runnum==rn_thr) exclude_thr=1; };
    }
    // rellum / pol cut
    if( kicked==0 && isConsistent==1 && b_pol>0 && y_pol>0)
    {
      // IF YOU CHANGE THE CUTS HERE, CHANGE THEM IN THE PLOT TITLES TOO!!!!!
      if(exclude_pi0==0 && 
         (TrigBits&0xFFF) &&
         ClIndex==0 &&
         fabs(N12-2)<0.01 &&
         Z<0.8 &&
         ( (((runnum/1000000)-1 == 12) && Pt>=2.5 && Pt<10) ||
           (((runnum/1000000)-1 == 13) && Pt>=2.0 && Pt<10) ) &&
         E12>=30 && E12<100 &&
         M12>0) 
      {
        mass_dist->Fill(M12);
        mass_vs_en->Fill(E12,M12);
        mass_vs_pt->Fill(Pt,M12);
        for(Int_t ee=0; ee<10; ee++)
        {
          if(E12>=(ee*10) && E12<((ee+1)*10)) mass_dist_for_enbin[ee]->Fill(M12);
        };
        // naive mass cut for correlation plots
        if(fabs(M12-0.135)<0.1)
        {
          pi0_pt_vs_eta->Fill(Eta,Pt);
          pi0_en_vs_eta->Fill(Eta,E12);
          pi0_pt_vs_phi->Fill(Phi,Pt);
          pi0_en_vs_phi->Fill(Phi,E12);
          pi0_eta_vs_phi->Fill(Phi,Eta);
          pi0_en_vs_pt->Fill(Pt,E12);
          pi0_z_vs_eta->Fill(Eta,Z);
          pi0_z_vs_phi->Fill(Phi,Z);
        };
      }
      if(exclude_pi0==0 && fabs(N12-2)<0.01 && (TrigBits&0xFFF) && ClIndex==0 && fabs(M12-0.135)<0.1) z_dist->Fill(Z);
      if(exclude_pi0==0 && fabs(N12-2)<0.01 && ClIndex==0) trig_dist->Fill(TrigBits);

      // single photon cut
      if(exclude_sph==0 && fabs(N12-1)<0.01)
      {
        sph_pt_vs_eta->Fill(Eta,Pt);
        sph_en_vs_eta->Fill(Eta,E12);
        sph_pt_vs_phi->Fill(Phi,Pt);
        sph_en_vs_phi->Fill(Phi,E12);
        sph_eta_vs_phi->Fill(Phi,Eta);
        sph_en_vs_pt->Fill(Pt,E12);
      };

      // three or more photons cut
      if(exclude_thr==0 && N12>2.5)
      {
        thr_pt_vs_eta->Fill(Eta,Pt);
        thr_en_vs_eta->Fill(Eta,E12);
        thr_pt_vs_phi->Fill(Phi,Pt);
        thr_en_vs_phi->Fill(Phi,E12);
        thr_eta_vs_phi->Fill(Phi,Eta);
        thr_en_vs_pt->Fill(Pt,E12);
      };
    };
  };


  /*
  // draw output -- MOVED TO DrawDiagnostics.C
  gStyle->SetOptStat(0);

  TCanvas * cc0 = new TCanvas("cc0","cc0",1000,1200);
  cc0->Divide(1,3);
  cc0->cd(1); mass_dist->Draw();
  cc0->cd(2); z_dist->Draw();
  cc0->cd(3); cc0->GetPad(3)->SetLogy(); trig_dist->Draw();


  TCanvas * cc1 = new TCanvas("cc1","cc1",1000,1200);
  cc1->Divide(2,3);
  cc1->cd(1); pt_vs_eta->Draw("colz");
  cc1->cd(2); pt_vs_phi->Draw("colz");
  cc1->cd(3); en_vs_eta->Draw("colz");
  cc1->cd(4); en_vs_phi->Draw("colz");
  cc1->cd(5); z_vs_eta->Draw("colz");
  cc1->cd(6); z_vs_phi->Draw("colz");

  TCanvas * cc2 = new TCanvas("cc2","cc2",1000,1200);
  cc2->Divide(2,3);
  cc2->cd(1); eta_vs_phi->Draw("colz");
  cc2->cd(2); en_vs_pt->Draw("colz");


  cc0->Print("diag_lin.pdf(","pdf");
  cc1->Print("diag_lin.pdf","pdf");
  cc2->Print("diag_lin.pdf)","pdf");
  printf("\ndiag_lin.pdf diagnostic kinematics file produced\n");

  for(Int_t i=1; i<=3; i++) cc0->GetPad(i)->SetLogy();
  for(Int_t i=1; i<=6; i++)
  {
    cc1->GetPad(i)->SetLogz();
    cc2->GetPad(i)->SetLogz();
  };

  cc0->Print("diag_log.pdf(","pdf");
  cc1->Print("diag_log.pdf","pdf");
  cc2->Print("diag_log.pdf)","pdf");
  printf("\ndiag_log.pdf diagnostic kinematics file produced\n");

  printf("E12 range: %f -- %f\n",E12_min,E12_max);
  printf("Pt range: %f -- %f\n",Pt_min,Pt_max);
  printf("Eta range: %f -- %f\n",Eta_min,Eta_max);
  printf("Phi range: %f -- %f\n",Phi_min,Phi_max);
  */

  // write output
  TFile * outfile = new TFile("diag.root","RECREATE");

  mass_dist->Write();
  z_dist->Write();
  trig_dist->Write();
  mass_vs_en->Write();
  mass_vs_pt->Write();

  for(Int_t ee=0; ee<10; ee++) mass_dist_for_enbin[ee]->Write();

  sph_pt_vs_eta->Write();
  sph_en_vs_eta->Write();
  sph_pt_vs_phi->Write();
  sph_en_vs_phi->Write();
  sph_eta_vs_phi->Write();
  sph_en_vs_pt->Write();

  pi0_pt_vs_eta->Write();
  pi0_en_vs_eta->Write();
  pi0_pt_vs_phi->Write();
  pi0_en_vs_phi->Write();
  pi0_eta_vs_phi->Write();
  pi0_en_vs_pt->Write();

  thr_pt_vs_eta->Write();
  thr_en_vs_eta->Write();
  thr_pt_vs_phi->Write();
  thr_en_vs_phi->Write();
  thr_eta_vs_phi->Write();
  thr_en_vs_pt->Write();

  pi0_z_vs_eta->Write();
  pi0_z_vs_phi->Write();


}
예제 #20
0
int main(int argc, char ** argv){
  char inputFileName[2000];
  bool isList=true;
  char outFileName[2000];
  char cfg[400];
  bool isData=false;
  int start=0;
  int stop=-1;
  
  ArgParser parser(argc,argv);
  parser.addLongOption("isData",ArgParser::noArg,"Specify data or MC");
  parser.addLongOption("json",ArgParser::reqArg,"Specify the JSON to use");
  parser.addLongOption("config",ArgParser::reqArg, "Specify the configuration file");
  parser.addLongOption("start",ArgParser::reqArg, "first event to process");
  parser.addLongOption("stop",ArgParser::reqArg, "last event to process");
  parser.addShortOption('f',ArgParser::noArg,"Specify whether the input file is a single file"); //use this if we only specify one file, not a list
  parser.addArgument("inputFile",ArgParser::required,"input file, expects a list unless -f is set");
  parser.addArgument("outputFile",ArgParser::required,"output file");

    std::string error;
  int retCode = parser.process(error);

  if(retCode != 0){
    cout << "ERROR Parsing option: " << error << "   return code: " << retCode << endl;
    parser.printOptions("CaltechAnalyzerApp");
    return 0;
  }

  isData = parser.longFlagPres("isData");
  strncpy(cfg,parser.getLongFlag("config").c_str(),400);
  isList = !parser.shortFlagPres('f');

  if(parser.longFlagPres("start")) start = atoi(parser.getLongFlag("start").c_str());
  if(parser.longFlagPres("stop")) stop = atoi(parser.getLongFlag("stop").c_str());

  strncpy(inputFileName,parser.getArgument("inputFile").c_str(),2000);
  strncpy(outFileName,parser.getArgument("outputFile").c_str(),2000);
  
  cout << "Running with Arguments: " << endl
       << "isData: " << isData << endl
       << "isList: " << isList << endl
       << "config: " << cfg << endl
       << "inputFile: " << inputFileName << endl
       << "outputFile: " << outFileName << endl;

    TChain *theChain = new TChain("ntp1");
  char Buffer[2000];
  char MyRootFile[2000];  
  if(isList){
    ifstream *inputFile = new ifstream(inputFileName);
    char tmpFileName[2000];
    while( !(inputFile->eof()) ){
      inputFile->getline(Buffer,2000);
      if (!strstr(Buffer,"#") && !(strspn(Buffer," ") == strlen(Buffer)))
	{
	  sscanf(Buffer,"%s",MyRootFile);
	  if(string(MyRootFile).find("eos") != std::string::npos) {
	    theChain->Add("root:/"+TString(MyRootFile));
	  } else if(string(MyRootFile).find("castor") != std::string::npos) {
	    theChain->Add("rfio:"+TString(MyRootFile));
	  } else{
	    theChain->Add(TString(MyRootFile));	 
	  }
	  // theChain->Add("root://castorcms/"+TString(MyRootFile));
	  //        theChain->Add(TString(MyRootFile));
	  std::cout << "chaining " << MyRootFile << std::endl;
	  //	if ( nfiles==1 ) {
	  //	  TFile *firstfile = TFile::Open("root://castorcms/"+TString(MyRootFile));
	  //	  treeCond = (TTree*)firstfile->Get("Conditions");
	  //	}
	  //        nfiles++;
	}
    }
    inputFile->close();
    
  }else{
    if(string(inputFileName).find("eos") != std::string::npos) {
      theChain->Add("root:/"+TString(inputFileName));
    } else if(string(inputFileName).find("castor") != std::string::npos) {
      theChain->Add("rfio:"+TString(inputFileName));
    } else{
      theChain->Add(TString(inputFileName));	 
    }
    std::cout << "chaining " << inputFileName << std::endl;
  }

  __ANALYSIS__ analyzer(theChain,__ANALYSIS__,outFileName,isData);
  analyzer.setConfigFile(cfg);
  analyzer.process(start,stop);
}
예제 #21
0
//int data_MC_Pt_Comparison_entries(int EndCaps = 0, int r9sup = 1, int log = 0)
int main(int argc, char *argv[])
{

	for(int iarg = 0 ; iarg < argc; iarg++)
        {
                cout << "argv[" << iarg << "]= " << argv[iarg] << endl;
        }

        if( argc == 1 ) 
        {
                cerr << "arguments should be passed : directoryName, eta, r9, xVariable, log" <<endl; 
                return 1;

        }    

	string directoryName = "Data_MC_Mmumugamma_Comparison_ScaleAndSmearing/smearingFactors";
	string eta = "Barrel_1";
	string r9 = "all";
	string ptCut = "25"; // "30" "35"

	if( argc > 1 ) directoryName = argv[1];
	if( argc > 2 ) eta = argv[2];
        if( argc > 3 ) r9 = argv[3];	
	if( argc > 4 ) ptCut = argv[4];	

	


	int nBins = 50; //FIXME
	double xMin, xMax;
	xMin = 0.9; //FIXME
	xMax = 1.1; //FIXME
	
	string xVariableName, yVariableName;

	gROOT->Reset();
        TGaxis::SetMaxDigits(3);
        setTDRStyle();
	//setEgammaStyle();

	string directoryName_2 = directoryName;
	string fileName = directoryName;

	cout<<endl<<"fileName = "<<fileName<<endl;
	cout<<endl<<"directoryName = "<<directoryName<<endl;
	directoryName += Form("/%s_%sR9/",eta.c_str(), r9.c_str());
	
	TString cut = Form("(Photon_Et > %s && isJanLooseMMG == 1",ptCut.c_str());

	if(r9 == "low" && eta == "Barrel_1") cut += " && Photon_isEB == 1 && Photon_r9 < 0.94 && abs(Photon_SC_Eta) < 1";
        if(r9 == "low" && eta == "Barrel_2") cut += " && Photon_isEB == 1 && Photon_r9 < 0.94 && abs(Photon_SC_Eta) > 1";
	if(r9 == "high" && eta == "Barrel_1") cut += " && Photon_isEB == 1 && Photon_r9 > 0.94 && abs(Photon_SC_Eta) < 1";
	if(r9 == "high" && eta == "Barrel_2") cut += " && Photon_isEB == 1 && Photon_r9 > 0.94 && abs(Photon_SC_Eta) > 1";
        if(r9 == "low" && eta == "Endcaps_1") cut += " && Photon_isEE == 1 && Photon_r9 < 0.95 && abs(Photon_SC_Eta) < 2";
	if(r9 == "low" && eta == "Endcaps_2") cut += " && Photon_isEE == 1 && Photon_r9 < 0.95 && abs(Photon_SC_Eta) > 2";
        if(r9 == "high" && eta == "Endcaps_1") cut += " && Photon_isEE == 1 && Photon_r9 > 0.95 && abs(Photon_SC_Eta) < 2";
	if(r9 == "high" && eta == "Endcaps_2") cut += " && Photon_isEE == 1 && Photon_r9 > 0.95 && abs(Photon_SC_Eta) > 2";
        if(r9 == "all" && eta == "Barrel_1") cut += " && Photon_isEB == 1 && abs(Photon_SC_Eta) < 1";
	if(r9 == "all" && eta == "Barrel_2") cut += " && Photon_isEB == 1 && abs(Photon_SC_Eta) > 1";
        if(r9 == "all" && eta == "Endcaps_1") cut += " && Photon_isEE == 1 && abs(Photon_SC_Eta) < 2";
	if(r9 == "all" && eta == "Endcaps_2") cut += " && Photon_isEE == 1 && abs(Photon_SC_Eta) > 2";
	if(r9 == "all" && eta == "all") cut += " && (Photon_isEE == 1 || Photon_isEB == 1)";

	cut += ")*weight_pileUp"; 

	cout<<endl<<"cut = "<<cut<<endl;

        TChain * dYToMuMuFSRChainNew = new TChain("miniTree");
        TChain * dYToMuMuNonFSRChainNew = new TChain("miniTree");
        TChain * ttJetsChainNew = new TChain("miniTree");
        TChain * wJetsChainNew = new TChain("miniTree");

        dYToMuMuFSRChainNew->Add("/sps/cms/sgandurr/CMSSW_4_2_8_patch7/src/Zmumugamma_miniTrees_rereco_2011_lastTag/miniTree_DYToMuMu_M-20_CT10_TuneZ2_7TeV-powheg-pythia_Fall11-PU_S6_START42_V14B-v1_September12_NewSelection_1_scaleAndsmearing_v4_partALL.root");
        dYToMuMuNonFSRChainNew->Add("/sps/cms/sgandurr/CMSSW_4_2_8_patch7/src/Zmumugamma_miniTrees_rereco_2011_lastTag/miniTree_DYToMuMu_M-20_CT10_TuneZ2_7TeV-powheg-pythia_Fall11-PU_S6_START42_V14B-v1_September12_NewSelection_2_scaleAndsmearing_v4_partALL.root");
        ttJetsChainNew->Add("/sps/cms/sgandurr/CMSSW_4_2_8_patch7/src/Zmumugamma_miniTrees_rereco_2011_lastTag/miniTree_TTJets_TuneZ2_7TeV-madgraph-tauola_NewSelection_3_scaleAndsmearing_v4_partALL.root");
        wJetsChainNew->Add("/sps/cms/sgandurr/CMSSW_4_2_8_patch7/src/Zmumugamma_miniTrees_rereco_2011_lastTag/miniTree_WJetsToLNu_TuneZ2_7TeV-madgraph-tauola_NewSelection_3_scaleAndsmearing_v4_partALL.root");
	

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

        TH1D *dYToMuMuFSRNew = new TH1D("dYToMuMuFSRNew","dYToMuMuFSRNew", nBins, xMin, xMax);
        TH1D *dYToMuMuNonFSRNew = new TH1D("dYToMuMuNonFSRNew","dYToMuMuNonFSRNew", nBins, xMin, xMax);
        TH1D *ttJetsNew = new TH1D("ttJetsNew","ttJetsNew", nBins, xMin, xMax);
        TH1D *wJetsNew = new TH1D("wJetsNew","wJetsNew", nBins, xMin, xMax);

        dYToMuMuFSRChainNew->Draw("shervinSmearing>>dYToMuMuFSRNew",cut);
        dYToMuMuNonFSRChainNew->Draw("shervinSmearing>>dYToMuMuNonFSRNew",cut);
        ttJetsChainNew->Draw("shervinSmearing>>ttJetsNew",cut);
        wJetsChainNew->Draw("shervinSmearing>>wJetsNew",cut);


	// --- 2012 Lumi --- //
        //double lumidata = 808.472 + 82.136 + 4429.0 + 495.003 + 134.242 + 6397.0 + 7274.0;
        //double lumiDY = 48819386.0 / 1914.894;
        //double lumiTtJets = 6736135.0 / 234.0;
        //double lumiwJets = 57709905.0 / 37509.25;	

	// --- 2011 Lumi --- //
	double lumidata = (0.706370 + 0.385819 + 2.741 + 1.099) * 1000;
	double lumiDY = 29743564.0 / 1665.835;
	double lumiTtJets = 3701947.0 / 165.0;
	double lumiwJets = 81345381.0 / 31314.0;	

	// --- 2011 Lumi old --- //
	//double lumiDY = 29743564.0 / 1626.0;
        //double lumiTtJets = 3701947.0 / 94.76;
        //double lumiwJets = 81345381.0 / 27770.0;

	ttJetsNew->Scale(lumiDY / lumiTtJets);
	wJetsNew->Scale(lumiDY / lumiwJets);
		
	dYToMuMuFSRNew->Add(dYToMuMuNonFSRNew);
	dYToMuMuFSRNew->Add(ttJetsNew);
	dYToMuMuFSRNew->Add(wJetsNew);

	dYToMuMuNonFSRNew->Add(ttJetsNew);
	dYToMuMuNonFSRNew->Add(wJetsNew);

	ttJetsNew->Add(wJetsNew);

	c1->Clear();


	dYToMuMuFSRNew->GetYaxis()->SetTitle("Events / 0.004"); //FIXME
       	dYToMuMuFSRNew->GetXaxis()->SetTitle("smearing factors");	

	/*
	dYToMuMuFSR->GetXaxis()->SetLabelFont(42);
	dYToMuMuFSR->GetXaxis()->SetTitleFont(42);
	dYToMuMuFSR->GetYaxis()->SetLabelFont(42);
	dYToMuMuFSR->GetYaxis()->SetTitleFont(42);
	dYToMuMuFSR->GetYaxis()->SetTitleOffset(1.65);
	*/

	dYToMuMuFSRNew->SetFillColor(kGreen-7);
        dYToMuMuNonFSRNew->SetFillColor(kAzure-5);
        ttJetsNew->SetFillColor(kBlue-1);
        wJetsNew->SetFillColor(kCyan+2);

	dYToMuMuFSRNew->Draw("");


	// --- Fit --- //

        TF1 * f1 = new TF1("f1","gaus",xMin,xMax);
	//TF1 * f1 = new TF1("f1","gaus",0.96,1.04);
	//f1->FixParameter(1,1.0); //FIXME
        //f1->FixParameter(2,1.0); //FIXME
        dYToMuMuFSRNew->Fit(f1);
        f1->SetLineColor(kBlue);
        f1->SetLineWidth(2);
        f1->Draw("SAMES");

        c1->Clear();
        dYToMuMuFSRNew->Draw("E");
        f1->Draw("SAMES");

        dYToMuMuFSRNew->SetMarkerStyle(20);
        dYToMuMuFSRNew->SetMarkerSize(0.5);
	
	TLatex latexLabel;
	latexLabel.SetTextFont(42);
	latexLabel.SetTextSize(0.028);
	latexLabel.SetNDC();
	//latexLabel.DrawLatex(0.25, 0.96, "CMS Preliminary 2011               #sqrt{s} = 7 TeV               L = 4.93 fb^{-1}");
	
	//double Ymin = 0;
	//double Ymax = max(dYToMuMuFSR->GetMaximum(),data->GetMaximum()) + max(dYToMuMuFSR->GetMaximum(),data->GetMaximum()) * 0.1;	
	//cout << "Ymax = "<<Ymax<<endl;

	//dYToMuMuFSRNew->GetYaxis()->SetRangeUser(Ymin,Ymax);

	plotsRecording(directoryName, fileName, c1);

	c1->Clear();

	f1->Delete();
	f1 = 0;
        dYToMuMuFSRNew->Delete();
        dYToMuMuFSRNew = 0;
        dYToMuMuNonFSRNew->Delete();
        dYToMuMuNonFSRNew = 0;
        ttJetsNew->Delete();
        ttJetsNew = 0;
        wJetsNew->Delete();
        wJetsNew = 0;
        dYToMuMuFSRChainNew->Delete();
        dYToMuMuFSRChainNew = 0;
        dYToMuMuNonFSRChainNew->Delete();
        dYToMuMuNonFSRChainNew = 0;
        ttJetsChainNew->Delete();
        ttJetsChainNew = 0;
        wJetsChainNew->Delete();
        wJetsChainNew = 0;


	
	delete c1;
	c1 = 0;	
	
	return 0;

}
예제 #22
0
파일: SMS.C 프로젝트: cmstas/ZMet2012
void SMS(char* sample = "wzsms" , bool print = false){

  //--------------------------------------------------
  // input parameters
  //--------------------------------------------------
  
  const float denom    = 100000;
  const float lumi     =   9200;
  const char* filename = Form("../../output/V00-01-05/%s_baby_oldIso.root",sample);

  cout << "Using file        " << filename << endl;
  cout << "Using denominator " << denom    << " events" << endl;
  cout << "Using lumi        " << lumi     << " pb-1" << endl;

  //--------------------------------------------------
  // set text stuff
  //--------------------------------------------------

  char* xtitle  = "m_{#chi_{2}^{0}} = m_{#chi_{1}^{#pm}} [GeV]";
  char* ytitle  = "m_{#chi_{1}^{0}} [GeV]";
  char* label   = "CMS Preliminary   #sqrt{s} = 8 TeV, #scale[0.6]{#int}Ldt = 9.2 fb^{-1}";
  char* process = "pp #rightarrow#chi_{2}^{0} #chi_{1}^{#pm} #rightarrow WZ+E_{T}^{miss}";

  //--------------------------------------------------
  // read in TChain
  //--------------------------------------------------

  TChain *ch = new TChain("T1");
  ch->Add(filename);

  //--------------------------------------------------
  // read in reference cross section
  //--------------------------------------------------

  TFile *xsecfile = TFile::Open("C1N2_8TeV_finer.root");
  TH1F* refxsec   = (TH1F*) xsecfile->Get("C1N2_8TeV_NLO");

  //--------------------------------------------------
  // preselection
  //--------------------------------------------------

  TCut pt2020("lep1.pt()>20.0 && lep2.pt()>20.0");
  TCut Zmass("dilmass>81 && dilmass<101");
  TCut sf = "leptype<2";
  TCut njets2("njets>=2");
  TCut bveto("nbcsvm==0");
  TCut nlep2("nlep==2");
  TCut mjj("mjj>70.0 && mjj<110.0");

  TCut presel;
  presel += pt2020;
  presel += Zmass;
  presel += sf;
  presel += njets2;
  presel += bveto;
  presel += mjj;
  presel += nlep2;

  TCut weight("vtxweight * trgeff");

  cout << "Using selection   " << presel.GetTitle() << endl;
  cout << "Using weight      " << weight.GetTitle() << endl;

  //--------------------------------------------------
  // signal regions
  //--------------------------------------------------

  vector<TCut>    sigcuts;
  vector<string>  signames;
  vector<string>  labels;
  vector<int>     cuts;

  TCut met60 ("pfmet > 60.0");
  TCut met80 ("pfmet > 80.0");
  TCut met100("pfmet > 100.0");
  TCut met120("pfmet > 120.0");
  TCut met140("pfmet > 140.0");
  TCut met160("pfmet > 160.0");
  TCut met180("pfmet > 180.0");
  TCut met200("pfmet > 200.0");

  // sigcuts.push_back(TCut(presel+met60));      signames.push_back("E_{T}^{miss} > 60 GeV");      labels.push_back("met60");  cuts.push_back(60);
  // sigcuts.push_back(TCut(presel+met80));      signames.push_back("E_{T}^{miss} > 80 GeV");      labels.push_back("met80");  cuts.push_back(80);
  // sigcuts.push_back(TCut(presel+met100));     signames.push_back("E_{T}^{miss} > 100 GeV");     labels.push_back("met100"); cuts.push_back(100);
  sigcuts.push_back(TCut(presel+met120));     signames.push_back("E_{T}^{miss} > 120 GeV");     labels.push_back("met120"); cuts.push_back(120);
  // sigcuts.push_back(TCut(presel+met140));     signames.push_back("E_{T}^{miss} > 140 GeV");     labels.push_back("met140"); cuts.push_back(140);
  // sigcuts.push_back(TCut(presel+met160));     signames.push_back("E_{T}^{miss} > 160 GeV");     labels.push_back("met160"); cuts.push_back(160);
  // sigcuts.push_back(TCut(presel+met180));     signames.push_back("E_{T}^{miss} > 180 GeV");     labels.push_back("met180"); cuts.push_back(180);
  // sigcuts.push_back(TCut(presel+met200));     signames.push_back("E_{T}^{miss} > 200 GeV");     labels.push_back("met200"); cuts.push_back(200);

  const unsigned int nsig = sigcuts.size();

  //--------------------------------------------------
  // make efficiency and xsec TH2's
  //--------------------------------------------------
  
  TH2F* heff[nsig];
  TH2F* heffup[nsig];
  TH2F* heffdn[nsig];
  TH2F* hxsec[nsig];
  TH2F* hxsec_exp[nsig];
  TH2F* hexcl[nsig];
  TH2F* hjes[nsig];
  
  TCanvas *ctemp = new TCanvas();
  ctemp->cd();

  for( unsigned int i = 0 ; i < nsig ; ++i ){

    TString jesup(sigcuts.at(i));
    jesup.ReplaceAll("njets","njetsup");
    jesup.ReplaceAll("pfmet","pfmetup");

    TString jesdn(sigcuts.at(i));
    jesdn.ReplaceAll("njets","njetsdn");
    jesdn.ReplaceAll("pfmet","pfmetdn");

    TCut jesupcut(jesup);
    TCut jesdncut(jesdn);

    cout << endl << endl;
    cout << "Signal region : " << labels.at(i)  << endl;
    cout << "Selection     : " << sigcuts.at(i) << endl;
    cout << "Selection up  : " << jesupcut      << endl;
    cout << "Selection dn  : " << jesdncut      << endl;

    int   nx   =  26;
    float xmin =  95;
    float xmax = 355;

    int   ny   =  36;
    float ymin =  -5;
    float ymax = 355;
    
    heff[i]      = new TH2F(Form("heff_%i",i)        , Form("heff_%i",i)       ,  nx , xmin , xmax , ny , ymin , ymax );
    heffup[i]    = new TH2F(Form("heffup_%i",i)      , Form("heffup_%i",i)     ,  nx , xmin , xmax , ny , ymin , ymax );
    heffdn[i]    = new TH2F(Form("heffdn_%i",i)      , Form("heffdn_%i",i)     ,  nx , xmin , xmax , ny , ymin , ymax );
    hxsec[i]     = new TH2F(Form("hxsec_%i",i)       , Form("hxsec_%i",i)      ,  nx , xmin , xmax , ny , ymin , ymax );
    hxsec_exp[i] = new TH2F(Form("hxsec_exp_%i",i)   , Form("hxsec_exp_%i",i)  ,  nx , xmin , xmax , ny , ymin , ymax );
    hexcl[i]     = new TH2F(Form("hexcl_%i",i)       , Form("hexcl_%i",i)      ,  nx , xmin , xmax , ny , ymin , ymax );
    hjes[i]      = new TH2F(Form("hjes_%i",i)        , Form("hjes_%i",i)       ,  nx , xmin , xmax , ny , ymin , ymax );

    ch->Draw(Form("ml:mg>>heff_%i",i),sigcuts.at(i)*weight);
    heff[i]->Scale(1.0/denom);

    // ch->Draw(Form("ml:mg>>heffup_%i",i),jesupcut*weight);
    // heffup[i]->Scale(1.0/denom);

    // ch->Draw(Form("ml:mg>>heffdn_%i",i),jesdncut*weight);
    // heffdn[i]->Scale(1.0/denom);

    for( unsigned int ibin = 1 ; ibin <= nx ; ibin++ ){
      for( unsigned int jbin = 1 ; jbin <= ny ; jbin++ ){

	float mg = heff[i]->GetXaxis()->GetBinCenter(ibin);
	float ml = heff[i]->GetYaxis()->GetBinCenter(jbin);

	float eff    = heff[i]->GetBinContent(ibin,jbin);
	// float effup  = heffup[i]->GetBinContent(ibin,jbin);
	// float effdn  = heffdn[i]->GetBinContent(ibin,jbin);

	if( eff   < 1e-20 ) continue;

	// float dup    = effup/eff-1;
	// float ddn    = 1-effdn/eff;
	// float djes   = 0.5 * (dup+ddn);
	// hjes[i]->SetBinContent(ibin,jbin,djes);

	// float toterr = sqrt( 0.04*0.04 + 0.05*0.05 + 0.05*0.05 + djes*djes );

	//float this_ul = getObservedLimit( cuts.at(i) , toterr );
	float this_ul = getObservedUpperLimit( cuts.at(i) );
	float xsecul  = this_ul / ( lumi * eff );

	//float this_ul_exp = getExpectedLimit( cuts.at(i) , toterr );
	float this_ul_exp = getExpectedUpperLimit( cuts.at(i) );
	float xsecul_exp  = this_ul_exp / ( lumi * eff );

	if( eff > 0 ){
	  hxsec[i]->SetBinContent(ibin,jbin, xsecul );
	  hxsec_exp[i]->SetBinContent(ibin,jbin, xsecul_exp );
	}

	int   bin = refxsec->FindBin(mg);
	float xsec = refxsec->GetBinContent(bin);

	hexcl[i]->SetBinContent(ibin,jbin,0);
	if( xsec > xsecul )   hexcl[i]->SetBinContent(ibin,jbin,1);
	//cout << "ibin jbin mg xsec " << ibin << " " << jbin << " " << mg << " " << xsec << endl;
      }
    }
  }

  delete ctemp;

  cout << endl << endl;

  //--------------------------------------------------
  // make pretty pictures
  //--------------------------------------------------
  
  TLatex *t = new TLatex();
  t->SetNDC();
  t->SetTextSize(0.04);

  TCanvas* can[nsig];

  for( unsigned int i = 0 ; i < nsig ; ++i ){
  
    //can[i] = new TCanvas(Form("can_%i",i),Form("can_%i",i),1200,600);
    //can[i]->Divide(2,1);
    //can[i] = new TCanvas(Form("can_%i",i),Form("can_%i",i),1800,600);
    //can[i]->Divide(3,1);
    can[i] = new TCanvas(Form("can_%i",i),Form("can_%i",i),1000,1000);
    can[i]->Divide(2,2);

    //-------------------------------
    // efficiency
    //-------------------------------

    can[i]->cd(1);
    gPad->SetTopMargin(0.1);
    gPad->SetRightMargin(0.2);
    heff[i]->GetXaxis()->SetLabelSize(0.035);
    heff[i]->Scale(1000);
    heff[i]->GetYaxis()->SetTitle(ytitle);
    heff[i]->GetXaxis()->SetTitle(xtitle);
    heff[i]->GetZaxis()->SetTitle("efficiency (10^{-3})");
    heff[i]->Draw("colz");

    
    t->DrawLatex(0.2 ,0.83,process);
    t->DrawLatex(0.2 ,0.71,signames.at(i).c_str());
    t->DrawLatex(0.18,0.92,label);

    //-------------------------------
    // cross section
    //-------------------------------
  
    can[i]->cd(2);
    gPad->SetTopMargin(0.1);
    gPad->SetRightMargin(0.2);
    gPad->SetLogz();
    hxsec[i]->GetXaxis()->SetLabelSize(0.035);
    hxsec[i]->GetYaxis()->SetTitle(ytitle);
    hxsec[i]->GetXaxis()->SetTitle(xtitle);
    hxsec[i]->GetXaxis()->SetRangeUser(95,305);
    hxsec[i]->GetYaxis()->SetRangeUser(-5,305);
    hxsec[i]->GetZaxis()->SetTitle("#sigma upper limit [pb]");
    hxsec[i]->Draw("colz");
    hxsec[i]->SetMinimum(0.01);
    hxsec[i]->SetMaximum(100);

    TGraph* gr2011 = getGraph_2011();
    TGraph* gr2012 = getGraph_2012();

    gr2011->Draw("same");
    gr2012->Draw("same");

    // TGraph* gr_excl      = getRefXsecGraph(hxsec[i], "T5zz", 1.0);
    // TGraph* gr_excl_down = getRefXsecGraph(hxsec[i], "T5zz", 1./3.);
    // TGraph* gr_excl_up   = getRefXsecGraph(hxsec[i], "T5zz", 3.);

    // gr_excl->SetLineWidth(2);
    // gr_excl_up->SetLineWidth(2);
    // gr_excl_down->SetLineWidth(2);
    // gr_excl_up->SetLineStyle(2);
    // gr_excl_down->SetLineStyle(3);
    // gr_excl->Draw("same");
    // gr_excl_up->Draw("same");
    // gr_excl_down->Draw("same");

    TLegend *leg = new TLegend(0.2,0.53,0.53,0.67);
    // leg->AddEntry(gr_excl,"#sigma^{prod} = #sigma^{NLO-QCD}","l");
    // leg->AddEntry(gr_excl_up,"#sigma^{prod} = 3 #times #sigma^{NLO-QCD}","l");
    // leg->AddEntry(gr_excl_down,"#sigma^{prod} = 1/3 #times #sigma^{NLO-QCD}","l");
    leg->AddEntry(gr2011,"2011 observed","l");
    leg->AddEntry(gr2012,"2012 expected","l");
    leg->SetFillColor(0);
    leg->SetBorderSize(0);
    leg->Draw();

    // t->DrawLatex(0.2,0.83,"pp #rightarrow #tilde{g}#tilde{g}, #tilde{g} #rightarrow 2j+#chi_{2}^{0}, #chi_{2}^{0} #rightarrow Z #chi_{1}^{0}");
    // t->DrawLatex(0.2,0.77,"m(#tilde{q}) >> m(#tilde{g})");
    // t->DrawLatex(0.2,0.71,signames.at(i).c_str());
    // t->DrawLatex(0.18,0.92,"CMS Preliminary            #sqrt{s} = 7 TeV, #scale[0.6]{#int}Ldt = 4.7 fb^{-1}");

    t->DrawLatex(0.2 ,0.83,process);
    t->DrawLatex(0.2 ,0.71,signames.at(i).c_str());
    t->DrawLatex(0.18,0.92,label);

    //-------------------------------
    // excluded points
    //-------------------------------

    can[i]->cd(3);
    gPad->SetGridx();
    gPad->SetGridy();
    gPad->SetRightMargin(0.2);
    gPad->SetTopMargin(0.1);
    hexcl[i]->GetXaxis()->SetRangeUser(150,250);
    hexcl[i]->GetYaxis()->SetRangeUser(-10,100);
    hexcl[i]->GetYaxis()->SetTitle("#chi^{0}_{1} mass (GeV)");
    hexcl[i]->GetXaxis()->SetTitle("gluino mass (GeV)");
    hexcl[i]->GetZaxis()->SetTitle("excluded points");
    hexcl[i]->Draw("colz");

    gr2012->Draw("same");
    gr2012->Draw("samep");

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

    // t->DrawLatex(0.2,0.83,"pp #rightarrow #tilde{g}#tilde{g}, #tilde{g} #rightarrow 2j+#chi_{2}^{0}, #chi_{2}^{0} #rightarrow Z #chi_{1}^{0}");
    // t->DrawLatex(0.2,0.77,"m(#tilde{q}) >> m(#tilde{g})");
    // t->DrawLatex(0.2,0.71,signames.at(i).c_str());
    // t->DrawLatex(0.18,0.92,"CMS Preliminary            #sqrt{s} = 7 TeV, #scale[0.6]{#int}Ldt = 4.7 fb^{-1}");

    t->DrawLatex(0.2 ,0.83,process);
    t->DrawLatex(0.2 ,0.71,signames.at(i).c_str());
    t->DrawLatex(0.18,0.92,label);

    //-------------------------------
    // JES uncertainty
    //-------------------------------

    can[i]->cd(4);
    gPad->SetRightMargin(0.2);
    gPad->SetTopMargin(0.1);
    hjes[i]->GetYaxis()->SetTitle("#chi^{0}_{1} mass (GeV)");
    hjes[i]->GetXaxis()->SetTitle("gluino mass (GeV)");
    hjes[i]->GetZaxis()->SetTitle("JES uncertainty");
    hjes[i]->Draw("colz");

    t->DrawLatex(0.2 ,0.83,process);
    t->DrawLatex(0.2 ,0.71,signames.at(i).c_str());
    t->DrawLatex(0.18,0.92,label);

    // t->DrawLatex(0.2,0.83,"pp #rightarrow #tilde{g}#tilde{g}, #tilde{g} #rightarrow 2j+#chi_{2}^{0}, #chi_{2}^{0} #rightarrow Z #chi_{1}^{0}");
    // t->DrawLatex(0.2,0.77,"m(#tilde{q}) >> m(#tilde{g})");
    // t->DrawLatex(0.2,0.71,signames.at(i).c_str());
    // t->DrawLatex(0.18,0.92,"CMS Preliminary            #sqrt{s} = 7 TeV, #scale[0.6]{#int}Ldt = 4.7 fb^{-1}");

    if( print ){
      can[i]->Print(Form("../../plots/%s.pdf",labels.at(i).c_str()));
      //can[i]->Print(Form("../plots/%s.eps",labels.at(i).c_str()));
      //gROOT->ProcessLine(Form(".! ps2pdf ../plots/%s.eps  ../plots/%s.pdf",labels.at(i).c_str(),labels.at(i).c_str()));
    }

    int bin = heff[i]->FindBin(250,50);
    cout << "efficiency (250,50)  " << heff[i]->GetBinContent(bin) << endl;
    cout << "xsec UL              " << hxsec[i]->GetBinContent(bin) << endl;
    cout << "xsec UL exp          " << hxsec_exp[i]->GetBinContent(bin) << endl;
    cout << "JES                  " << hjes[i]->GetBinContent(bin) << endl;
    cout << "tot err              " << sqrt(pow(hjes[i]->GetBinContent(bin),2)+0.06*0.06+0.05*0.05) << endl;
    cout << endl << endl;
  }
  
  TFile *outfile = TFile::Open(Form("%s_histos.root",sample),"RECREATE");
  outfile->cd();
  for( unsigned int i = 0 ; i < nsig ; ++i ){
    hxsec[i]->Write();
    heff[i]->Write();
    hxsec_exp[i]->Write();
  }
  outfile->Close();

}
예제 #23
0
void AddDetectorEffects(TString infile,TString outfile)
{
	InitExterns();
	const int kMaxTrack = 10;	// maximal number of particles in a single event.
	
	
	int evt = -999;
	
	int nPhoton = 0;
	float photonPt[kMaxTrack];
	float photonEta[kMaxTrack];
	float photonPhi[kMaxTrack];
	
	int nElectron = 0;
	float electronPt[kMaxTrack];
	float electronEta[kMaxTrack];
	float electronPhi[kMaxTrack];
	int electronQ[kMaxTrack];
	int electronTag[kMaxTrack];
	float electronCal02[kMaxTrack];
	float electronCal03[kMaxTrack];
	float electronCal04[kMaxTrack];
	float electronTrk02[kMaxTrack];
	float electronTrk03[kMaxTrack];
	float electronTrk04[kMaxTrack];
	float electronSign[kMaxTrack];
	
	int nMuon = 0;
	float muonPt[kMaxTrack];
	float muonEta[kMaxTrack];
	float muonPhi[kMaxTrack];
	int muonQ[kMaxTrack];
	int muonTag[kMaxTrack];
	float muonCal02[kMaxTrack];
	float muonCal03[kMaxTrack];
	float muonCal04[kMaxTrack];
	float muonTrk02[kMaxTrack];
	float muonTrk03[kMaxTrack];
	float muonTrk04[kMaxTrack];
	float muonSign[kMaxTrack];
	
	int nTau = 0;
	float tauPt[kMaxTrack];
	float tauEta[kMaxTrack];
	float tauPhi[kMaxTrack];
	int tauQ[kMaxTrack];
	int tauTag[kMaxTrack];
	float tauCal02[kMaxTrack];
	float tauCal03[kMaxTrack];
	float tauCal04[kMaxTrack];
	float tauTrk02[kMaxTrack];
	float tauTrk03[kMaxTrack];
	float tauTrk04[kMaxTrack];
	float tauSign[kMaxTrack];
	
	int nJet = 0;
	float jetPt[kMaxTrack];
	float jetEta[kMaxTrack];
	float jetPhi[kMaxTrack];
	int jetQ[kMaxTrack];
	int jetTag[kMaxTrack];
	float jetCal02[kMaxTrack];
	float jetCal03[kMaxTrack];
	float jetCal04[kMaxTrack];
	float jetTrk02[kMaxTrack];
	float jetTrk03[kMaxTrack];
	float jetTrk04[kMaxTrack];
	
	float metPt = -999.;
	float metEta = -999.;
	float metPhi = -999.;

	float sf_mu_reco_eff[kMaxTrack];	// scale factor muon reco efficiency
	float sf_el_reco_eff[kMaxTrack];	// scale factor electron reco efficiency
	
	
	TFile f(outfile,"recreate");	// the file and tree
	TTree *t = new TTree("t","Reconst ntuple");
	
	
	// adding branches:
	// t->Branch(Branch name in the browser, pointer to the variable, variable name)
	
	t->Branch("evt",&evt,"evt/I");

	t->Branch("nPhoton",&nPhoton,"nPhoton/I");
	t->Branch("photonPt",photonPt,"photonPt[nPhoton]/F");
	t->Branch("photonEta",photonEta,"photonEta[nPhoton]/F");
	t->Branch("photonPhi",photonPhi,"photonPhi[nPhoton]/F");

	t->Branch("nElectron",&nElectron,"nElectron/I");
	t->Branch("electronPt",electronPt,"electronPt[nElectron]/F");
	t->Branch("electronEta",electronEta,"electronEta[nElectron]/F");
	t->Branch("electronPhi",electronPhi,"electronPhi[nElectron]/F");
	t->Branch("electronQ",electronQ,"electronQ[nElectron]/I");
	t->Branch("electronTag",electronTag,"electronTag[nElectron]/I");
	t->Branch("electronCal02",electronCal02,"electronCal02[nElectron]/F");
	t->Branch("electronCal03",electronCal03,"electronCal03[nElectron]/F");
	t->Branch("electronCal04",electronCal04,"electronCal04[nElectron]/F");
	t->Branch("electronTrk02",electronTrk02,"electronTrk02[nElectron]/F");
	t->Branch("electronTrk03",electronTrk03,"electronTrk03[nElectron]/F");
	t->Branch("electronTrk04",electronTrk04,"electronTrk04[nElectron]/F");
	t->Branch("electronSign",electronSign,"electronSign[nElectron]/F");
	
	t->Branch("nMuon",&nMuon,"nMuon/I");
	t->Branch("muonPt",muonPt,"muonPt[nMuon]/F");
	t->Branch("muonEta",muonEta,"muonEta[nMuon]/F");
	t->Branch("muonPhi",muonPhi,"muonPhi[nMuon]/F");
	t->Branch("muonQ",muonQ,"muonQ[nMuon]/I");
	t->Branch("muonTag",muonTag,"muonTag[nMuon]/I");
	t->Branch("muonCal02",muonCal02,"muonCal02[nMuon]/F");
	t->Branch("muonCal03",muonCal03,"muonCal03[nMuon]/F");
	t->Branch("muonCal04",muonCal04,"muonCal04[nMuon]/F");
	t->Branch("muonTrk02",muonTrk02,"muonTrk02[nMuon]/F");
	t->Branch("muonTrk03",muonTrk03,"muonTrk03[nMuon]/F");
	t->Branch("muonTrk04",muonTrk04,"muonTrk04[nMuon]/F");
	t->Branch("muonSign",muonSign,"muonSign[nMuon]/F");
	
	t->Branch("nTau",&nTau,"nTau/I");
	t->Branch("tauPt",tauPt,"tauPt[nTau]/F");
	t->Branch("tauEta",tauEta,"tauEta[nTau]/F");
	t->Branch("tauPhi",tauPhi,"tauPhi[nTau]/F");
	t->Branch("tauQ",tauQ,"tauQ[nTau]/I");
	t->Branch("tauTag",tauTag,"tauTag[nTau]/I");
	t->Branch("tauCal02",tauCal02,"tauCal02[nTau]/F");
	t->Branch("tauCal03",tauCal03,"tauCal03[nTau]/F");
	t->Branch("tauCal04",tauCal04,"tauCal04[nTau]/F");
	t->Branch("tauTrk02",tauTrk02,"tauTrk02[nTau]/F");
	t->Branch("tauTrk03",tauTrk03,"tauTrk03[nTau]/F");
	t->Branch("tauTrk04",tauTrk04,"tauTrk04[nTau]/F");
	t->Branch("tauSign",tauSign,"tauSign[nTau]/F");
	
	t->Branch("nJet",&nJet,"nJet/I");
	t->Branch("jetPt",jetPt,"jetPt[nJet]/F");
	t->Branch("jetEta",jetEta,"jetEta[nJet]/F");
	t->Branch("jetPhi",jetPhi,"jetPhi[nJet]/F");
	t->Branch("jetQ",jetQ,"jetQ[nJet]/I");
	t->Branch("jetTag",jetTag,"jetTag[nJet]/I");
	t->Branch("jetCal02",jetCal02,"jetCal02[nJet]/F");
	t->Branch("jetCal03",jetCal03,"jetCal03[nJet]/F");
	t->Branch("jetCal04",jetCal04,"jetCal04[nJet]/F");
	t->Branch("jetTrk02",jetTrk02,"jetTrk02[nJet]/F");
	t->Branch("jetTrk03",jetTrk03,"jetTrk03[nJet]/F");
	t->Branch("jetTrk04",jetTrk04,"jetTrk04[nJet]/F");
	
	t->Branch("metPt",&metPt,"metPt/F");
	t->Branch("metEta",&metEta,"metEta/F");
	t->Branch("metPhi",&metPhi,"metPhi/F");
	
	t->Branch("sf_mu_reco_eff",sf_mu_reco_eff,"sf_mu_reco_eff[nMuon]/F");	// my branches
	t->Branch("sf_el_reco_eff",sf_el_reco_eff,"sf_el_reco_eff[nElectron]/F");
	
	// This next part is taken from looper.
	
	TChain* chain = new TChain("t");
	chain->Add("../run/"+infile+"/t");
	TTree* tree = chain;
	
	SimData* data = new SimData(tree);

    if(data->fChain == 0) {
		cout << " fchain is empty" << endl;
	}
    Int_t nentries = Int_t(data->fChain->GetEntries());
    cout << " Reading data ..." << nentries << " in physics tree" << endl;

    Int_t nTen = nentries/10;
    Int_t nbytes = 0, nb = 0;


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

		Int_t ientry = data->LoadTree(jentry);
		if (ientry < 0) break;
		
		nb = data->fChain->GetEntry(jentry);
		nbytes += nb;
		
		if (nTen!=0) if (jentry%nTen==0) cout << " " << 10*(jentry/nTen) << "%-" <<flush;

//		printf("evt %d: nPhoton %d, nElectron %d, nMuon %d, nTau %d, nJet %d \n",
//		data->evt,data->nPhoton,data->nElectron,data->nMuon,data->nTau,data->nJet);

		evt = data->evt;

		nPhoton = data->nPhoton;
		nElectron = data->nElectron;
		nMuon = data->nMuon;
		nTau = data->nTau;
		nJet = data->nJet;

		for (int i = 0; i < kMaxTrack; i++) {

			photonPt[i] = data->photonPt[i];
			photonEta[i] = data->photonEta[i];
			photonPhi[i] = data->photonPhi[i];
			
			electronPt[i] = data->electronPt[i];
			electronEta[i] = data->electronEta[i];
			electronPhi[i] = data->electronPhi[i];
			electronQ[i] = data->electronQ[i];
//			electronTag[i] = data->electronTag[i];
//			electronCal02[i] = data->electronCal02[i];
//			electronCal03[i] = data->electronCal03[i];
//			electronCal04[i] = data->electronCal04[i];
//			electronTrk02[i] = data->electronTrk02[i];
//			electronTrk03[i] = data->electronTrk03[i];
//			electronTrk04[i] = data->electronTrk04[i];
//			electronSign[i] = data->electronSign[i];
			
			muonPt[i] = data->muonPt[i];
			muonEta[i] = data->muonEta[i];
			muonPhi[i] = data->muonPhi[i];
			muonQ[i] = data->muonQ[i];
//			muonTag[i] = data->muonTag[i];
//			muonCal02[i] = data->muonCal02[i];
//			muonCal03[i] = data->muonCal03[i];
//			muonCal04[i] = data->muonCal04[i];
//			muonTrk02[i] = data->muonTrk02[i];
//			muonTrk03[i] = data->muonTrk03[i];
//			muonTrk04[i] = data->muonTrk04[i];
//			muonSign[i] = data->muonSign[i];

			tauPt[i] = data->tauPt[i];
			tauEta[i] = data->tauEta[i];
			tauPhi[i] = data->tauPhi[i];
			tauQ[i] = data->tauQ[i];
//			tauTag[i] = data->tauTag[i];
//			tauCal02[i] = data->tauCal02[i];
//			tauCal03[i] = data->tauCal03[i];
//			tauCal04[i] = data->tauCal04[i];
//			tauTrk02[i] = data->tauTrk02[i];
//			tauTrk03[i] = data->tauTrk03[i];
//			tauTrk04[i] = data->tauTrk04[i];
//			tauSign[i] = data->tauSign[i];
			
			jetPt[i] = data->jetPt[i];
			jetEta[i] = data->jetEta[i];
			jetPhi[i] = data->jetPhi[i];
			jetQ[i] = data->jetQ[i];
//			jetTag[i] = data->jetTag[i];
//			jetCal02[i] = data->jetCal02[i];
//			jetCal03[i] = data->jetCal03[i];
//			jetCal04[i] = data->jetCal04[i];
//			jetTrk02[i] = data->jetTrk02[i];
//			jetTrk03[i] = data->jetTrk03[i];
//			jetTrk04[i] = data->jetTrk04[i];

		}

		metPt = data->metPt;
		metEta = data->metEta;
		metPhi = data->metPhi;

		// smearing and efficiency for electrons
//		for (int i = 0; i < nElectron; i++) {
//
//			float mean = data->electronPt[i];
//			float sd = DeviationForParameter("electronPt",mean);
//			// Box-Muller method:
//			electronPt[i] = mean + sd * sqrt(-2*log(float(rand())/RAND_MAX))*cos(2*M_PI*float(rand())/RAND_MAX);
//
//			sf_el_reco_eff[i] = EfficiencyForParticle("electron", electronPt[i], electronEta[i], electronPhi[i]);
//		}

		// smearing and efficiency for muons
//		for (int i = 0; i < nMuon; i++) {
//
//			float mean = data->muonPt[i];
//			float sd = DeviationForParameter("muonPt",mean);
//			muonPt[i] = mean + sd * sqrt(-2*log(float(rand())/RAND_MAX))*cos(2*M_PI*float(rand())/RAND_MAX);
//
//			sf_mu_reco_eff[i] = EfficiencyForParticle("muon", muonPt[i], muonEta[i], muonPhi[i]);
//		}

		// effective smearing for met.
		// I say effective because the met is calculated from the particles, but we "delete" some of them...
		float mean = data->metPt;
		float sd = DeviationForParameter("metPt",mean);
//		TRandom r; r.SetSeed(12);
		metPt = RAND.Gaus(mean,sd);
		if (metPt<0){metPt=0;}

				//sqrt(-2*log(float(rand())/RAND_MAX))*cos(2*M_PI*float(rand())/RAND_MAX);

		t->Fill();

	}

	f.cd();
	t->Write("",TObject::kOverwrite);
	
	
	delete data;
}
예제 #24
0
int main(int argc, char *argv[])
{
  char appName[] = "root2pileup";
  stringstream message;
  TChain *inputChain = 0;
  ExRootTreeReader *treeReader = 0;
  TClonesArray *branchParticle = 0;
  TIterator *itParticle = 0;
  GenParticle *particle = 0;
  DelphesPileUpWriter *writer = 0;
  Long64_t entry, allEntries;
  Int_t i;

  if(argc < 3)
  {
    cout << " Usage: " << appName << " output_file" << " input_file(s)" << endl;
    cout << " output_file - output binary pile-up file," << endl;
    cout << " input_file(s) - input file(s) in ROOT format." << endl;
    return 1;
  }

  signal(SIGINT, SignalHandler);

  gROOT->SetBatch();

  int appargc = 1;
  char *appargv[] = {appName};
  TApplication app(appName, &appargc, appargv);

  try
  {
    inputChain = new TChain("Delphes");
    for(i = 2; i < argc && !interrupted; ++i)
    {
      inputChain->Add(argv[i]);
    }

    treeReader = new ExRootTreeReader(inputChain);
    branchParticle = treeReader->UseBranch("Particle");
    itParticle = branchParticle->MakeIterator();

    writer = new DelphesPileUpWriter(argv[1]);

    allEntries = treeReader->GetEntries();
    cout << "** Input file(s) contain(s) " << allEntries << " events" << endl;

    if(allEntries > 0)
    {
      ExRootProgressBar progressBar(allEntries - 1);
      // Loop over all events in the input file
      for(entry = 0; entry < allEntries && !interrupted; ++entry)
      {
        if(!treeReader->ReadEntry(entry))
        {
          cerr << "** ERROR: cannot read event " << entry << endl;
          break;
        }

        itParticle->Reset();
        while((particle = static_cast<GenParticle*>(itParticle->Next())))
        {
          writer->WriteParticle(particle->PID,
            particle->X, particle->Y, particle->Z, particle->T,
            particle->Px, particle->Py, particle->Pz, particle->E);
        }
        
        writer->WriteEntry();

        progressBar.Update(entry);
      }
      progressBar.Finish();

      writer->WriteIndex();
    }

    cout << "** Exiting..." << endl;

    delete writer;
    delete itParticle;
    delete treeReader;
    delete inputChain;
    return 0;
  }
  catch(runtime_error &e)
  {
    if(writer) delete writer;
    if(itParticle) delete itParticle;
    if(treeReader) delete treeReader;
    if(inputChain) delete inputChain;
    cerr << "** ERROR: " << e.what() << endl;
    return 1;
  }
}
예제 #25
0
void TMVARegression( TString myMethodList = "" ) 
{
   // The explicit loading of the shared libTMVA is done in TMVAlogon.C, defined in .rootrc
   // if you use your private .rootrc, or run from a different directory, please copy the 
   // corresponding lines from .rootrc

   // methods to be processed can be given as an argument; use format:
   //
   // mylinux~> root -l TMVARegression.C\(\"myMethod1,myMethod2,myMethod3\"\)
   //

   // this loads the library
   TMVA::Tools::Instance();

   //---------------------------------------------------------------
   // default MVA methods to be trained + tested
   std::map<std::string,int> Use;

   Use["PDERS"]           = 0;
   Use["PDERSkNN"]        = 0; // depreciated until further notice
   Use["PDEFoam"]         = 0; // preparation for new TMVA version "reader". This method is not available in this version of TMVA
   // ---
   Use["KNN"]             = 0;
   // ---
   Use["LD"]		  = 0;
   // ---
   Use["FDA_GA"]          = 0;
   Use["FDA_MC"]          = 0;
   Use["FDA_MT"]          = 0;
   Use["FDA_GAMT"]        = 0;
   // ---
   Use["MLP"]             = 0; 
   // ---
   Use["SVM"]             = 0;
   // ---
   Use["BDT"]             = 0;
   Use["BDTG"]            = 1;
   // ---------------------------------------------------------------

   std::cout << std::endl;
   std::cout << "==> Start TMVARegression" << std::endl;

   if (myMethodList != "") {
      for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) it->second = 0;

      std::vector<TString> mlist = gTools().SplitString( myMethodList, ',' );
      for (UInt_t i=0; i<mlist.size(); i++) {
         std::string regMethod(mlist[i]);

         if (Use.find(regMethod) == Use.end()) {
            std::cout << "Method \"" << regMethod << "\" not known in TMVA under this name. Choose among the following:" << std::endl;
            for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) std::cout << it->first << " ";
            std::cout << std::endl;
            return;
         }
         Use[regMethod] = 1;
      }
   }

   // Create a new root output file
   TString outfileName( "TMVAReg_TarggetAPDPN.root" );
   TFile* outputFile = TFile::Open( outfileName, "RECREATE" );

   // Create the factory object. Later you can choose the methods
   // whose performance you'd like to investigate. The factory will
   // then run the performance analysis for you.
   //
   // The first argument is the base of the name of all the
   // weightfiles in the directory weight/ 
   //
   // The second argument is the output file for the training results
   // All TMVA output can be suppressed by removing the "!" (not) in 
   // front of the "Silent" argument in the option string
   TMVA::Factory *factory = new TMVA::Factory( "TMVARegression", outputFile, 
                                               "!V:!Silent:Color:DrawProgressBar" );

   // If you wish to modify default settings 
   // (please check "src/Config.h" to see all available global options)
   //    (TMVA::gConfig().GetVariablePlotting()).fTimesRMS = 8.0;
   //    (TMVA::gConfig().GetIONames()).fWeightFileDir = "myWeightDirectory";

   // Define the input variables that shall be used for the MVA training
   // note that you may also use variable expressions, such as: "3*var1/var2*abs(var3)"
   // [all types of expressions that can also be parsed by TTree::Draw( "expression" )]
//    factory->AddVariable( "laser.qmax", "Qmax", "ADC", 'D' );
//    factory->AddVariable( "laser.tmax", "T_{0}", "ns", 'D' );
//    factory->AddVariable( "laser.fwhm", "FWHM","ns", 'D');
//    factory->AddVariable( "laser.prepulse","Prepulse indicator","A.U.", 'D' );
//    factory->AddVariable( "laser.w10","Width at 10%","ns", 'D' );

   factory->AddVariable( "qmax[0]", "Qmax", "ADC", 'D' );
   factory->AddVariable( "tmax[0]", "T_{0}", "ns", 'D' );
   factory->AddVariable( "l_fwhm[0]", "FWHM","ns", 'D');
   factory->AddVariable( "l_prepulse[0]","Prepulse indicator","A.U.", 'D' );
   factory->AddVariable( "l_width90[0]","Width at 10%","ns", 'D' );

   // You can add so-called "Spectator variables", which are not used in the MVA training, 
   // but will appear in the final "TestTree" produced by TMVA. This TestTree will contain the 
   // input variables, the response values of all trained MVAs, and the spectator variables
   //   factory->AddSpectator( "spec1:=var1*2",  "Spectator 1", "units", 'F' );
   //   factory->AddSpectator( "spec2:=timeStamp",  "Spectator 1", "units", 'F' );

   // Add the variable carrying the regression target
   factory->AddTarget  ( "apdpnAB[0]" ); 

   // It is also possible to declare additional targets for multi-dimensional regression, ie:
   // -- factory->AddTarget( "fvalue2" );
   // BUT: this is currently ONLY implemented for MLP

   // read training and test data (see TMVAClassification for reading ASCII files)
   // load the signal and background event samples from ROOT trees
//    TFile *input(0);
//    TString fname = "./stabTreeFed630.root";
//    if (!gSystem->AccessPathName( fname )) {
//       input = TFile::Open( fname ); // check if file in local directory exists
//    } 

//    if (!input) {
//       std::cout << "ERROR: could not open data file" << std::endl;
//       exit(1);
//    }
//    std::cout << "--- TMVARegression           : Using input file: " << input->GetName() << std::endl;


   TChain * ntu = new TChain("x");
   ntu->Add("/data2/EcalLaserMonitoringData/ntuples_2011_158851_178888/ntu_data_0015*.root");
   ntu->Add("/data2/EcalLaserMonitoringData/ntuples_2011_158851_178888/ntu_data_0016*.root");

   //TTree *regTree = (TTree*)input->Get("ntu");

   // global event weights per tree (see below for setting event-wise weights)
   Double_t regWeight  = 1.0;   

   // ====== register trees ====================================================
   //
   // the following method is the prefered one:
   // you can add an arbitrary number of regression trees
   //factory->AddRegressionTree( regTree, regWeight );
   factory->AddRegressionTree( ntu, regWeight );

   // Alternative call:
   // -- factory->AddRegressionTree( regTree, regWeight );
   
   // This would set individual event weights (the variables defined in the 
   // expression need to exist in the original TTree)
   //   factory->SetWeightExpression( "fwhm-26", "Regression" );

   // Apply additional cuts on the signal and background samples (can be different)
   //   TCut mycut = "abs(0.5*(apd0+apd1)-1)<0.015 && timeStamp<1299.8e6"; // for example: TCut mycut = "abs(var1)<0.5 && abs(var2-0.5)<1";
   cout << "Defining cuts..." << endl;
   TCut mycut = "fed[0] == 605 && harness == 6 && field > 0.1 && run < 161200 && apdpnAB[0] > 0"; 

   // Count selected events and use them all
   TCanvas cdummy("cdummy","cdummy"); cdummy.cd(); 
   Int_t selectedEvts = ntu->Draw("l_fwhm[0]",mycut,"N");
   cdummy.Delete(); 
   cout << selectedEvts << endl;
   char trainPara[132];
   sprintf(trainPara,"nTrain_Regression=%d:nTest_Regression=0:SplitMode=Random:NormMode=NumEvents:!V",selectedEvts-10);

   // tell the factory to use all remaining events in the trees after training for testing:
   factory->PrepareTrainingAndTestTree( mycut, trainPara ); 

   // If no numbers of events are given, half of the events in the tree are used for training, and 
   // the other half for testing:
   //   factory->PrepareTrainingAndTestTree( mycut, "SplitMode=random:!V" );  
   // To also specify the number of testing events, use:
   //    factory->PrepareTrainingAndTestTree( mycut, 
   //                                         "NSigTrain=3000:NBkgTrain=3000:NSigTest=3000:NBkgTest=3000:SplitMode=Random:!V" );  

   // ---- Book MVA methods
   //
   // please lookup the various method configuration options in the corresponding cxx files, eg:
   // src/MethoCuts.cxx, etc, or here: http://tmva.sourceforge.net/optionRef.html
   // it is possible to preset ranges in the option string in which the cut optimisation should be done:
   // "...:CutRangeMin[2]=-1:CutRangeMax[2]=1"...", where [2] is the third input variable

   cout << "Booking MVA methods" << endl;

   // PDE - RS method
   if (Use["PDERS"])
      factory->BookMethod( TMVA::Types::kPDERS, "PDERS", 
                           "!H:!V:NormTree=T:VolumeRangeMode=Adaptive:KernelEstimator=Gauss:GaussSigma=0.3:NEventsMin=40:NEventsMax=60:VarTransform=None" );
   // And the options strings for the MinMax and RMS methods, respectively:
   //      "!H:!V:VolumeRangeMode=MinMax:DeltaFrac=0.2:KernelEstimator=Gauss:GaussSigma=0.3" );   
   //      "!H:!V:VolumeRangeMode=RMS:DeltaFrac=3:KernelEstimator=Gauss:GaussSigma=0.3" );   

   if (Use["PDERSkNN"]) // depreciated until further notice
      factory->BookMethod( TMVA::Types::kPDERS, "PDERSkNN", 
                           "!H:!V:VolumeRangeMode=kNN:KernelEstimator=Gauss:GaussSigma=0.3:NEventsMin=400:NEventsMax=600" );

   if (Use["PDEFoam"])
       factory->BookMethod( TMVA::Types::kPDEFoam, "PDEFoam", 
			    "!H:!V:MultiTargetRegression=F:TargetSelection=Mpv:TailCut=0.001:VolFrac=0.0333:nActiveCells=500:nSampl=2000:nBin=5:Compress=T:Kernel=None:CutNmin=T:Nmin=10:VarTransform=None" );


   // K-Nearest Neighbour classifier (KNN)
   if (Use["KNN"])
      factory->BookMethod( TMVA::Types::kKNN, "KNN", 
                           "nkNN=20:ScaleFrac=0.8:SigmaFact=1.0:Kernel=Gaus:UseKernel=F:UseWeight=T:!Trim" );

   // Linear discriminant
   if (Use["LD"])
      factory->BookMethod( TMVA::Types::kLD, "LD", 
                           "!H:!V:VarTransform=N" );

	// Function discrimination analysis (FDA) -- test of various fitters - the recommended one is Minuit (or GA or SA)
   if (Use["FDA_MC"]) 
      factory->BookMethod( TMVA::Types::kFDA, "FDA_MC",
                          "!H:!V:Formula=(0)+(1)*x0+(2)*x1:ParRanges=(-100,100);(-100,100);(-100,100):FitMethod=MC:SampleSize=100000:Sigma=0.1:VarTransform=D" );
   
   if (Use["FDA_GA"]) // can also use Simulated Annealing (SA) algorithm (see Cuts_SA options) .. the formula of this example is good for parabolas
      factory->BookMethod( TMVA::Types::kFDA, "FDA_GA",
                           "!H:!V:Formula=(0)+(1)*x0+(2)*x1:ParRanges=(-100,100);(-100,100);(-100,100):FitMethod=GA:PopSize=100:Cycles=3:Steps=30:Trim=True:SaveBestGen=1:VarTransform=Norm" );

   if (Use["FDA_MT"]) 
      factory->BookMethod( TMVA::Types::kFDA, "FDA_MT",
                           "!H:!V:Formula=(0)+(1)*x0+(2)*x1:ParRanges=(-100,100);(-100,100);(-100,100);(-10,10):FitMethod=MINUIT:ErrorLevel=1:PrintLevel=-1:FitStrategy=2:UseImprove:UseMinos:SetBatch" );

   if (Use["FDA_GAMT"]) 
      factory->BookMethod( TMVA::Types::kFDA, "FDA_GAMT",
                           "!H:!V:Formula=(0)+(1)*x0+(2)*x1:ParRanges=(-100,100);(-100,100);(-100,100):FitMethod=GA:Converger=MINUIT:ErrorLevel=1:PrintLevel=-1:FitStrategy=0:!UseImprove:!UseMinos:SetBatch:Cycles=1:PopSize=5:Steps=5:Trim" );

   // Neural network (MLP)
   if (Use["MLP"])
      factory->BookMethod( TMVA::Types::kMLP, "MLP", "!H:!V:VarTransform=Norm:NeuronType=tanh:NCycles=5000:HiddenLayers=N+5,N+2:TestRate=6:TrainingMethod=BP:Sampling=0.3:SamplingEpoch=0.8:ConvergenceImprove=1e-6:ConvergenceTests=15" );

   // Support Vector Machine
   if (Use["SVM"])
      factory->BookMethod( TMVA::Types::kSVM, "SVM", "Gamma=0.25:Tol=0.001:VarTransform=Norm" );

   // Boosted Decision Trees
   if (Use["BDT"])
     factory->BookMethod( TMVA::Types::kBDT, "BDT",
                           "!H:!V:NTrees=100:nEventsMin=5:BoostType=AdaBoostR2:SeparationType=RegressionVariance:nCuts=20:PruneMethod=CostComplexity:PruneStrength=30" );

   if (Use["BDTG"])
     factory->BookMethod( TMVA::Types::kBDT, "BDTG",
                           "!H:!V:NTrees=200::BoostType=Grad:Shrinkage=1.0:UseBaggedGrad:SeparationType=GiniIndex:nCuts=20:NNodesMax=5" );
   // --------------------------------------------------------------------------------------------------

   // ---- Now you can tell the factory to train, test, and evaluate the MVAs

   // Train MVAs using the set of training events
   factory->TrainAllMethods();

   // ---- Evaluate all MVAs using the set of test events
   factory->TestAllMethods();

   // ----- Evaluate and compare performance of all configured MVAs
   factory->EvaluateAllMethods();    

   // --------------------------------------------------------------
   
   // Save the output
   outputFile->Close();

   std::cout << "==> Wrote root file: " << outputFile->GetName() << std::endl;
   std::cout << "==> TMVARegression is done!" << std::endl;      

   delete factory;

   // Launch the GUI for the root macros
   //if (!gROOT->IsBatch()) TMVARegGui( outfileName );
}
예제 #26
0
파일: runTask.C 프로젝트: ktf/AliPhysics
void runTask(Float_t etamax=0.5,const char * incollection = 0, const char * outfile = "dndeta.root", Bool_t skipNorm = kFALSE)
{
  // for running with root only
  gSystem->Load("libTree");
  gSystem->Load("libGeom");
  gSystem->Load("libVMC");
  gSystem->Load("libSTEERBase");
  gSystem->Load("libESD");
  gSystem->Load("libAOD");

  // load analysis framework
  gSystem->Load("libANALYSIS");
  gSystem->Load("libANALYSISalice");


  TChain * chain = new TChain ("TE");
  if (incollection == 0) {
    chain->Add("galice.root");
  }
  else if (TString(incollection).Contains("xml")){
    TGrid::Connect("alien://");
    TAlienCollection * coll = TAlienCollection::Open (incollection);
    while(coll->Next()){
      chain->Add(TString("alien://")+coll->GetLFN());
    }
  } else {
    ifstream file_collect(incollection);
    TString line;
    while (line.ReadLine(file_collect) ) {
      chain->Add(line.Data());
    }
  }
  chain->GetListOfFiles()->Print();

  // for includes use either global setting in $HOME/.rootrc
  // ACLiC.IncludePaths: -I$(ALICE_ROOT)/include
  // or in each macro
  gSystem->AddIncludePath("-I$ALICE_ROOT/include");

  // Create the analysis manager
  AliAnalysisManager *mgr = new AliAnalysisManager("dNdeta");

  AliVEventHandler* esdH = new AliESDInputHandler;
  ((AliESDInputHandler*)esdH)->SetReadFriends(kFALSE);
  mgr->SetInputEventHandler(esdH);

  // Create tasks
  gROOT->LoadMacro("AliAnalysisTaskdNdetaMC.cxx++g");

  AliAnalysisTask *task1 = new AliAnalysisTaskdNdetaMC("TaskdNdeta");
  ((AliAnalysisTaskdNdetaMC*)task1)->SetEtaMax(etamax);
  if (skipNorm) ((AliAnalysisTaskdNdetaMC*)task1)->SkipNormalization();
  // Enable MC event handler

  AliMCEventHandler* handler = new AliMCEventHandler;
  handler->SetReadTR(kFALSE);
  mgr->SetMCtruthEventHandler(handler);

  // Add tasks
  mgr->AddTask(task1);

  // Create containers for input/output
  AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("coutput", TList::Class(),    AliAnalysisManager::kOutputContainer, outfile);

  // Connect input/output
  mgr->ConnectInput(task1, 0, cinput);
  mgr->ConnectOutput(task1, 1, coutput1);

  // Enable debug printouts
  mgr->SetDebugLevel(0);

  if (!mgr->InitAnalysis()) return;

  mgr->PrintStatus();

  mgr->StartAnalysis("local", chain);
}
예제 #27
0
int main (int argc, char** argv)
{

  if (argc < 3) {
    printHelp() ;
    exit (1) ;
  }

  std::string inputfiles, inputdir ;
  std::string outputRootName = "histoTPG.root" ;
  int verbose = 0 ;
  int occupancyCut = 0 ;
  std::string l1algo ; 

  bool ok(false) ;
  for (int i=0 ; i<argc ; i++) {
    if (argv[i] == std::string("-h") ) {
      printHelp() ;
      exit(1);
    }
    if (argv[i] == std::string("-i") && argc>i+1) {
      ok = true ;
      inputfiles = argv[i+1] ;
    }
    if (argv[i] == std::string("-d") && argc>i+1) inputdir = argv[i+1] ;
    if (argv[i] == std::string("-o") && argc>i+1) outputRootName = argv[i+1] ;
    if (argv[i] == std::string("-v") && argc>i+1) verbose = atoi(argv[i+1]) ;
    if (argv[i] == std::string("-l1") && argc>i+1) l1algo =  std::string(argv[i+1]) ;
    if (argv[i] == std::string("--cutTPOccup") && argc>i+1) occupancyCut = atoi(argv[i+1]) ;
  }
  if (!ok) {
    std::cout<<"No input files have been given: nothing to do!"<<std::endl ;
    printHelp() ;
    exit(1);
  }
  
  std::vector<int> algobits ;
  std::vector<std::string> algos = split(l1algo,",") ;
  for (unsigned int i=0 ; i<algos.size() ; i++) algobits.push_back(atoi(algos[i].c_str())) ;


  unsigned int ref = 2 ;



  ///////////////////////
  // book the histograms
  ///////////////////////

  TH2F * occupancyTP = new TH2F("occupancyTP", "Occupancy TP data", 72, 1, 73, 38, -19, 19) ;
  occupancyTP->GetYaxis()->SetTitle("eta index") ;
  occupancyTP->GetXaxis()->SetTitle("phi index") ;
  TH2F * occupancyTPEmul = new TH2F("occupancyTPEmul", "Occupancy TP emulator", 72, 1, 73, 38, -19, 19) ;
  occupancyTPEmul->GetYaxis()->SetTitle("eta index") ;
  occupancyTPEmul->GetXaxis()->SetTitle("phi index") ;

  TH1F * TP = new TH1F("TP", "TP", 256, 0., 256.) ;
  TP->GetXaxis()->SetTitle("TP (ADC)") ;
  TH1F * TPEmul = new TH1F("TPEmul", "TP Emulator", 256, 0., 256.) ;
  TPEmul->GetXaxis()->SetTitle("TP (ADC)") ;
  TH1F * TPEmulMax = new TH1F("TPEmulMax", "TP Emulator max", 256, 0., 256.) ;
  TPEmulMax->GetXaxis()->SetTitle("TP (ADC)") ;
  TH3F * TPspectrumMap3D = new TH3F("TPspectrumMap3D", "TP data spectrum map", 72, 1, 73, 38, -19, 19, 256, 0., 256.) ;
  TPspectrumMap3D->GetYaxis()->SetTitle("eta index") ;
  TPspectrumMap3D->GetXaxis()->SetTitle("phi index") ;

  TH1F * TPMatchEmul = new TH1F("TPMatchEmul", "TP data matching Emulator", 7, -1., 6.) ;
  TH1F * TPEmulMaxIndex = new TH1F("TPEmulMaxIndex", "Index of the max TP from Emulator", 7, -1., 6.) ;
  TH3I * TPMatchEmul3D = new TH3I("TPMatchEmul3D", "TP data matching Emulator", 72, 1, 73, 38, -19, 19, 7, -1, 6) ;
  TPMatchEmul3D->GetYaxis()->SetTitle("eta index") ;
  TPMatchEmul3D->GetXaxis()->SetTitle("phi index") ;

  TH2I * ttfMismatch = new TH2I("ttfMismatch", "TTF mismatch map",  72, 1, 73, 38, -19, 19) ;
  ttfMismatch->GetYaxis()->SetTitle("eta index") ;
  ttfMismatch->GetXaxis()->SetTitle("phi index") ;

  ///////////////////////
  // Chain the trees:
  ///////////////////////

  TChain * chain = new TChain ("EcalTPGAnalysis") ;
  std::vector<std::string> files ;
  if (inputfiles.find(std::string(",")) != std::string::npos) files = split(inputfiles,",") ;
  if (inputfiles.find(std::string(":")) != std::string::npos) {
    std::vector<std::string> filesbase = split(inputfiles,":") ;
    if (filesbase.size() == 4) {
      int first = atoi(filesbase[1].c_str()) ;
      int last = atoi(filesbase[2].c_str()) ;
      for (int i=first ; i<=last ; i++) {
	std::stringstream name ;
	name<<filesbase[0]<<i<<filesbase[3] ;
	files.push_back(name.str()) ;
      }
    }
  }
  for (unsigned int i=0 ; i<files.size() ; i++) {
    files[i] = inputdir+"/"+files[i] ;
    std::cout<<"Input file: "<<files[i]<<std::endl ;
    chain->Add (files[i].c_str()) ;
  }

  EcalTPGVariables treeVars ;
  setBranchAddresses (chain, treeVars) ;

  int nEntries = chain->GetEntries () ;
  std::cout << "Number of entries: " << nEntries <<std::endl ;    



  ///////////////////////
  // Main loop over entries
  ///////////////////////

  for (int entry = 0 ; entry < nEntries ; ++entry) {
    chain->GetEntry (entry) ;
    if (entry%1000==0) std::cout <<"------> "<< entry+1 <<" entries processed" << " <------\n" ; 
    if (verbose>0) std::cout<<"Run="<<treeVars.runNb<<" Evt="<<treeVars.runNb<<std::endl ;

    // trigger selection if any
    bool keep(false) ;
    if (!algobits.size()) keep = true ; // keep all events when no trigger selection
    for (unsigned int algo = 0 ; algo<algobits.size() ; algo++)
      for (unsigned int ntrig = 0 ; ntrig < treeVars.nbOfActiveTriggers ; ntrig++)
	if (algobits[algo] == treeVars.activeTriggers[ntrig]) keep = true ;
    if (!keep) continue ;
    
             
    // loop on towers
    for (unsigned int tower = 0 ; tower < treeVars.nbOfTowers ; tower++) {

      int tp = getEt(treeVars.rawTPData[tower]) ;
      int emul[5] = {getEt(treeVars.rawTPEmul1[tower]),  
		     getEt(treeVars.rawTPEmul2[tower]),
		     getEt(treeVars.rawTPEmul3[tower]),
		     getEt(treeVars.rawTPEmul4[tower]),
		     getEt(treeVars.rawTPEmul5[tower])} ;
      int maxOfTPEmul = 0 ;
      int indexOfTPEmulMax = -1 ;
      for (int i=0 ; i<5 ; i++) if (emul[i]>maxOfTPEmul) {
	maxOfTPEmul = emul[i] ; 
	indexOfTPEmulMax = i ;
      }
      int ieta = treeVars.ieta[tower] ;
      int iphi = treeVars.iphi[tower] ;
      int nbXtals = treeVars.nbOfXtals[tower] ;
      int ttf = getTtf(treeVars.rawTPData[tower]) ;


      if (verbose>9 && (tp>0 || maxOfTPEmul>0)) {
	std::cout<<"(phi,eta, Nbxtals)="<<std::dec<<iphi<<" "<<ieta<<" "<<nbXtals<<std::endl ;
	std::cout<<"Data Et, TTF: "<<tp<<" "<<ttf<<std::endl ;
	std::cout<<"Emulator: " ;
	for (int i=0 ; i<5 ; i++) std::cout<<emul[i]<<" " ;
	std::cout<<std::endl ;
      }


      // Fill TP spctrum
      TP->Fill(tp) ;
      TPEmul->Fill(emul[ref]) ;
      TPEmulMax->Fill(maxOfTPEmul) ;
      TPspectrumMap3D->Fill(iphi, ieta, tp) ;


      // Fill TP occupancy
      if (tp>occupancyCut) occupancyTP->Fill(iphi, ieta) ;
      if (emul[ref]>occupancyCut) occupancyTPEmul->Fill(iphi, ieta) ;


      // Fill TP-Emulator matching
      // comparison is meaningful when:
      if (tp>0 && nbXtals == 25) {
	bool match(false) ;
	for (int i=0 ; i<5 ; i++) {
	  if (tp == emul[i]) {
	    TPMatchEmul->Fill(i+1) ;
	    TPMatchEmul3D->Fill(iphi, ieta, i+1) ;
	    match = true ;
	  }
	}
	if (!match) {
	  TPMatchEmul->Fill(-1) ;
	  TPMatchEmul3D->Fill(iphi, ieta, -1) ;
	  if (verbose>5) {
	    std::cout<<"MISMATCH"<<std::endl ;
	    std::cout<<"(phi,eta, Nbxtals)="<<std::dec<<iphi<<" "<<ieta<<" "<<nbXtals<<std::endl ;
	    std::cout<<"Data Et, TTF: "<<tp<<" "<<ttf<<std::endl ;
	    std::cout<<"Emulator: " ;
	    for (int i=0 ; i<5 ; i++) std::cout<<emul[i]<<" " ;
	    std::cout<<std::endl ;
	  }
	}
      }
      if (maxOfTPEmul>0) TPEmulMaxIndex->Fill(indexOfTPEmulMax+1) ;


      // Fill TTF mismatch
      if ((ttf==1 || ttf==3) && nbXtals != 25) ttfMismatch->Fill(iphi, ieta) ;


    } // end loop towers


  } // endloop entries

  

  ///////////////////////
  // Format & write histos
  ///////////////////////


  // 1. TP Spectrum  
  TProfile2D * TPspectrumMap = TPspectrumMap3D->Project3DProfile("yx") ;
  TPspectrumMap->SetName("TPspectrumMap") ;

  // 2. TP Timing
  TH2F * TPMatchEmul2D = new TH2F("TPMatchEmul2D", "TP data matching Emulator", 72, 1, 73, 38, -19, 19) ;
  TH2F * TPMatchFraction2D = new TH2F("TPMatchFraction2D", "TP data: fraction of non-single timing", 72, 1, 73, 38, -19, 19) ;
  TPMatchEmul2D->GetYaxis()->SetTitle("eta index") ; 
  TPMatchEmul2D->GetXaxis()->SetTitle("phi index") ;
  TPMatchEmul2D->GetZaxis()->SetRangeUser(-1,6) ;
  TPMatchFraction2D->GetYaxis()->SetTitle("eta index") ; 
  TPMatchFraction2D->GetXaxis()->SetTitle("phi index") ;
  for (int binx=1 ; binx<=72 ; binx++)    
    for (int biny=1 ; biny<=38 ; biny++) {
      int maxBinz = 5 ;
      double maxCell = TPMatchEmul3D->GetBinContent(binx, biny, maxBinz) ;
      double totalCell(0) ;
      for (int binz=1; binz<=7 ; binz++) {
	double content = TPMatchEmul3D->GetBinContent(binx, biny, binz) ;
	if (content>maxCell) {
	  maxCell = content ;
	  maxBinz = binz ;
	}
	totalCell += content ;
      }
      if (maxCell <=0) maxBinz = 2 ; // empty cell
      TPMatchEmul2D->SetBinContent(binx, biny, float(maxBinz)-2.) ; //z must be in [-1,5] 
      double fraction = 0 ;
      if (totalCell>0) fraction = 1.- maxCell/totalCell ;
      TPMatchFraction2D->SetBinContent(binx, biny, fraction) ;
      if (totalCell > maxCell && verbose>9) {
	std::cout<<"--->"<<std::endl ;	
	for (int binz=1; binz<=7 ; binz++) {	  
	  std::cout<< "(phi,eta, z): (" 
		   << TPMatchEmul3D->GetXaxis()->GetBinLowEdge(binx) 
		   << ", " << TPMatchEmul3D->GetYaxis()->GetBinLowEdge(biny) 
		   << ", " << TPMatchEmul3D->GetZaxis()->GetBinLowEdge(binz)		   
		   << ") Content="<<TPMatchEmul3D->GetBinContent(binx, biny, binz)		   
		   << ", erro="<<TPMatchEmul3D->GetBinContent(binx, biny, binz)	   
		   << std::endl ;	
	}
      }
    }



  TFile saving (outputRootName.c_str (),"recreate") ;
  saving.cd () ;
  
  occupancyTP->Write() ;
  occupancyTPEmul->Write() ;
  
  TP->Write() ;
  TPEmul->Write() ;
  TPEmulMax->Write() ;
  TPspectrumMap->Write() ;

  TPMatchEmul->Write() ; 
  TPMatchEmul3D->Write() ; 
  TPEmulMaxIndex->Write() ;
  TPMatchEmul2D->Write() ; 
  TPMatchFraction2D->Write() ; 

  ttfMismatch->Write() ; 

     
  saving.Close () ;
  delete chain ;

  return 0 ;
}
예제 #28
0
void readTree(TString filelist="/global/project/projectdirs/star/pwg/starhf/zamiller/minBiasTemplates101015/Trees.list",TString outFile="/global/project/projectdirs/star/pwg/starhf/zamiller/minBiasTemplates101015/readTreeOutSubmitTEST.root")
{

  //TString filelist=Form("%s/%s",localDir,fileIn);
  //TString outFile=Form("%s/%s",outDir,fileOut);

  TFile fout(outFile,"RECREATE");
  TH1F::SetDefaultSumw2(); 
  TH1D::SetDefaultSumw2(); 

  for(Int_t c=0; c< numPtBins; c++)
  {
    lowpt[c] = anaConst::lpt[c];
    highpt[c] = anaConst::hpt[c];
  }
  for(Int_t ptbin = 0; ptbin < numPtBins; ptbin++)
  {
    hdEtaRawce[ptbin] = new TH1D(Form("hdEtaRawce_%i",ptbin),"hdEtaRawce",100, -5,5);
    hdEtaRawbe[ptbin] = new TH1D(Form("hdEtaRawbe_%i",ptbin),"hdEtaRawbe",100, -5,5);
    hEventTallyce[ptbin] = new TH1D(Form("ceEventTally_%i",ptbin),"ceEvent Tally",1,0,1);
    hEventTallybe[ptbin] = new TH1D(Form("beEventTally_%i",ptbin),"beEvent Tally",1,0,1);
    hEventTallybce[ptbin] = new TH1D(Form("bceEventTally_%i",ptbin),"bceEvent Tally",1,0,1);
    hdPhiRawce[ptbin] = new TH1D(Form("hdPhiRawce_%i",ptbin),"hdPhiRawce",Phibin, -10,10);
    hdPhiRawbe[ptbin] = new TH1D(Form("hdPhiRawbe_%i",ptbin),"hdPhiRawbe",Phibin, -10,10);
    hdPhiRawbce[ptbin] = new TH1D(Form("hdPhiRawbce_%i",ptbin),"hdPhiRawbce",Phibin, -10,10);
    hept[ptbin] = new TH1D(Form("hept_%i",ptbin),"hept",200,0.,20.);
  }

  // Make Chain
  TChain* chain = new TChain("tree");
  int nfile = 0;
  /*  nfile += chain->Add("Oct30_set13/pythia_tree_Oct30_13.root");
      nfile += chain->Add("Oct30_set14/pythia_tree_Oct30_14.root");
      nfile += chain->Add("Oct30_set15/pythia_tree_Oct30_15.root");
      nfile += chain->Add("Oct30_set16/pythia_tree_Oct30_16.root");
      nfile += chain->Add("Oct30_set17/pythia_tree_Oct30_17.root");
  //  nfile += chain->Add("Oct30_set12/pythia_tree_Oct30_12.root");
  //  nfile += chain->Add("Oct26_set3/pythia_tree_Oct26_3.root");
  // nfile += chain->Add("Oct18_set4/pythia_tree_Oct18_4.root");
  //nfile += chain->Add("liweiTemplate_part2.root");*/
  char filename[1000];
  ifstream fstream(filelist.Data());
  int ifile = 0;
  while (fstream >> filename)
  {
    nfile+= chain->Add(filename);
    std::cout << "Got File: " << filename << std::endl;
  }

  std::cout <<"Added "<<nfile<<" files"<<std::endl;
  std::cout<<"# entries in chain: "<<chain->GetEntries()<<std::endl;
  if (chain == 0) return;

  int ceNtrigger=0;
  int beNtrigger=0;
  int bceNtrigger=0;
  int ptbin,maxptbin;

  //define variables
  Int_t   Event, numberofcElectrons, numberofbElectrons,numberofbcElectrons, numberofHadrons, noTracks;   //
  Float_t celectron_id,celectron_status,celectron_pt,celectron_pz,celectron_phi,celectron_eta,celectron_y;                //track info
  Float_t belectron_id,belectron_status,belectron_pt,belectron_pz,belectron_phi,belectron_eta,belectron_y;
  Float_t bcelectron_id,bcelectron_status,bcelectron_pt,bcelectron_pz,bcelectron_phi,bcelectron_eta,bcelectron_y;
  Float_t assoh_id,assoh_status,assoh_pt,assoh_pz,assoh_phi,assoh_eta,assoh_y;

  int goodEvent = 0;


  Long64_t nentries = chain->GetEntriesFast();
  int x = 0; int n = nentries; int w = 25;

  for(int i = 0; i < nentries; i++){
    Long64_t ientry = chain->LoadTree(i);
    if (ientry < 0) break;
    TBranch *b_destep = chain->GetBranch("hf2eDecay");

    TLeaf* leaf_Event_id            = b_destep->GetLeaf("Event_id");
    TLeaf* leaf_refMult             = b_destep->GetLeaf("refMult");
    TLeaf* leaf_numberofcElectrons  = b_destep->GetLeaf("numberofcElectrons");
    TLeaf* leaf_numberofbElectrons  = b_destep->GetLeaf("numberofbElectrons");
    TLeaf* leaf_numberofbcElectrons = b_destep->GetLeaf("numberofbcElectrons");
    TLeaf* leaf_numberofHadrons     = b_destep->GetLeaf("numberofHadrons");
    TLeaf* leaf_noTracks            = b_destep->GetLeaf("noTracks");

    TLeaf* leaf_ce_id               = b_destep->GetLeaf("ce_id");
    TLeaf* leaf_ce_status           = b_destep->GetLeaf("ce_status");
    TLeaf* leaf_ce_pt               = b_destep->GetLeaf("ce_pt");
    TLeaf* leaf_ce_pz               = b_destep->GetLeaf("ce_pz");
    TLeaf* leaf_ce_phi              = b_destep->GetLeaf("ce_phi");
    TLeaf* leaf_ce_eta              = b_destep->GetLeaf("ce_eta");
    TLeaf* leaf_ce_y                = b_destep->GetLeaf("ce_y");

    TLeaf* leaf_be_id               = b_destep->GetLeaf("be_id");
    TLeaf* leaf_be_status           = b_destep->GetLeaf("be_status");
    TLeaf* leaf_be_pt               = b_destep->GetLeaf("be_pt");
    TLeaf* leaf_be_pz               = b_destep->GetLeaf("be_pz");
    TLeaf* leaf_be_phi              = b_destep->GetLeaf("be_phi");
    TLeaf* leaf_be_eta              = b_destep->GetLeaf("be_eta");
    TLeaf* leaf_be_y                = b_destep->GetLeaf("be_y");

    TLeaf* leaf_bce_id              = b_destep->GetLeaf("bce_id");
    TLeaf* leaf_bce_status          = b_destep->GetLeaf("bce_status");
    TLeaf* leaf_bce_pt              = b_destep->GetLeaf("bce_pt");
    TLeaf* leaf_bce_pz              = b_destep->GetLeaf("bce_pz");
    TLeaf* leaf_bce_phi             = b_destep->GetLeaf("bce_phi");
    TLeaf* leaf_bce_eta             = b_destep->GetLeaf("bce_eta");
    TLeaf* leaf_bce_y               = b_destep->GetLeaf("bce_y");

    TLeaf* leaf_hadron_id           = b_destep->GetLeaf("hadron_id");
    TLeaf* leaf_hadron_status       = b_destep->GetLeaf("hadron_status");
    TLeaf* leaf_hadron_pt           = b_destep->GetLeaf("hadron_pt");
    TLeaf* leaf_hadron_pz           = b_destep->GetLeaf("hadron_pz");
    TLeaf* leaf_hadron_phi          = b_destep->GetLeaf("hadron_phi");
    TLeaf* leaf_hadron_eta          = b_destep->GetLeaf("hadron_eta");
    TLeaf* leaf_hadron_y            = b_destep->GetLeaf("hadron_y");

    x = i+1;
    // Process Completion bar
    if ( (x != n) && (x % (n/100) == 0) )
    {
      float ratio  =  (float)x/(float)n;
      int   c      =  ratio * w;

      if(ratio < 1){
        std::cout << (int)(ratio*100) << "% [";
        for (int x=0; x<c; x++) std::cout << "=";
        for (int x=c; x<w; x++) std::cout << " ";
        std::cout << "]\r" << std::flush ;
      }
    }


    // if(i%10000 == 0)
    //   std::cout <<"Entry: "<< i << std::endl;
    chain->GetEntry(i);

    Event   = (int)leaf_Event_id->GetValue(0);
    numberofcElectrons = (int)leaf_numberofcElectrons->GetValue(0);
    // std::cout << numberofcElectrons << " ";
    numberofbElectrons = (int)leaf_numberofbElectrons->GetValue(0);
    numberofbcElectrons = (int)leaf_numberofbcElectrons->GetValue(0);
    numberofHadrons = (int)leaf_numberofHadrons->GetValue(0);
    // std::cout << "numHad: " << numberofHadrons << std::endl;
    noTracks        = leaf_noTracks->GetValue(0);
    hrefmult -> Fill(noTracks);

    //loop through matched primary tracks electron find c decayed electron
    int ceNtrigcount=0;
    maxptbin = 0;
    for(int trki = 0; trki < numberofcElectrons; trki++){
      celectron_id      = (int)leaf_ce_id->GetValue(trki);
      celectron_status  = (int)leaf_ce_status->GetValue(trki);
      celectron_pt      = leaf_ce_pt->GetValue(trki);
      celectron_pz      = leaf_ce_pz->GetValue(trki);
      celectron_phi     = leaf_ce_phi->GetValue(trki);
      celectron_eta     = leaf_ce_eta->GetValue(trki);
      celectron_y       = leaf_ce_y->GetValue(trki);
      if(celectron_eta > EtaCut || celectron_eta < -EtaCut) continue;
      ptbin = getPtBin(celectron_pt);
      if(ptbin == -99) continue;
      if(ptbin > maxptbin)
        maxptbin = ptbin;
      hept[ptbin]->Fill(celectron_pt);
      hEventTallyce[maxptbin]->Fill(0.5); //fill for each NPE

      for(int trkj = 0; trkj < numberofHadrons; trkj++){

        assoh_id = (int)leaf_hadron_id->GetValue(trkj);
        assoh_status  = (int)leaf_hadron_status->GetValue(trkj);
        assoh_pt      = leaf_hadron_pt->GetValue(trkj);
        assoh_pz      = leaf_hadron_pz->GetValue(trkj);
        assoh_phi     = leaf_hadron_phi->GetValue(trkj);
        assoh_eta     = leaf_hadron_eta->GetValue(trkj);
        assoh_y       = leaf_hadron_y->GetValue(trkj);
        if(assoh_eta > hEtaCut || assoh_eta < -hEtaCut) continue;

        float deltPhi = assoh_phi - celectron_phi;
        float deltEta = assoh_eta - celectron_eta;
        if(deltPhi < -PI)  deltPhi += 2*PI;
        if(deltPhi >  PI) deltPhi -= 2*PI;
        if(abs(deltEta) > deletacut) continue;
        if(assoh_pt>hptCut)
        {
          hdPhiRawce[ptbin]->Fill(deltPhi); 
          hdEtaRawce[ptbin]->Fill(deltEta);
          ceNtrigcount++;
        }
      }
    }
    //if(ceNtrigcount>0)hEventTallyce[maxptbin]->Fill(0.5);
    //if(ceNtrigcount>0)ceNtrigger++;

    //b decayed electron-------------------------------------------------- 
    int beNtrigcount=0;
    maxptbin = 0;
    for(int trki = 0; trki < numberofbElectrons; trki++){
      belectron_id = (int)leaf_be_id->GetValue(trki);
      belectron_status  = (int)leaf_be_status->GetValue(trki);
      belectron_pt      = leaf_be_pt->GetValue(trki);
      belectron_pz      = leaf_be_pz->GetValue(trki);
      belectron_phi     = leaf_be_phi->GetValue(trki);
      belectron_eta     = leaf_be_eta->GetValue(trki);
      belectron_y        = leaf_be_y->GetValue(trki);
      if(belectron_eta > EtaCut || belectron_eta < -EtaCut) continue;
      ptbin = getPtBin(belectron_pt);
      if(ptbin == -99) continue;
      if(ptbin > maxptbin)
        maxptbin = ptbin;
      hept[ptbin]->Fill(belectron_pt);
      hEventTallybe[maxptbin]->Fill(0.5); //fill for each NPE
      for(int trkj = 0; trkj < numberofHadrons; trkj++){

        assoh_id = (int)leaf_hadron_id->GetValue(trkj);
        assoh_status  = (int)leaf_hadron_status->GetValue(trkj);
        assoh_pt      = leaf_hadron_pt->GetValue(trkj);
        assoh_pz      = leaf_hadron_pz->GetValue(trkj);
        assoh_phi     = leaf_hadron_phi->GetValue(trkj);
        assoh_eta     = leaf_hadron_eta->GetValue(trkj);
        assoh_y       = leaf_hadron_y->GetValue(trkj);
        if(assoh_eta > hEtaCut || assoh_eta < -hEtaCut) continue;

        float deltPhi = assoh_phi - belectron_phi;
        float deltEta = assoh_eta - belectron_eta;
        if(deltPhi < -PI)  deltPhi += 2*PI;
        if(deltPhi >  PI) deltPhi -= 2*PI;
        if(abs(deltEta) > deletacut) continue;
        if(assoh_pt>hptCut)
        {
          hdPhiRawbe[ptbin]->Fill(deltPhi);
          hdEtaRawbe[ptbin]->Fill(deltEta);  
          beNtrigcount++;
        }
      }
    }
    //    if(beNtrigcount>0)hEventTallybe[maxptbin]->Fill("be non photonic electron",1);
    //    if(beNtrigcount>0)beNtrigger++;
    //bce decayed electron-----------------------------------------------------------------                                                                                           
    int bceNtrigcount=0;
    maxptbin = 0;
    for(int trki = 0; trki < numberofbcElectrons; trki++){
      bcelectron_id = (int)leaf_bce_id->GetValue(trki);
      bcelectron_status  = (int)leaf_bce_status->GetValue(trki);
      bcelectron_pt      = leaf_bce_pt->GetValue(trki);
      bcelectron_pz      = leaf_bce_pz->GetValue(trki);
      bcelectron_phi     = leaf_bce_phi->GetValue(trki);
      bcelectron_eta     = leaf_bce_eta->GetValue(trki);
      bcelectron_y       = leaf_bce_y->GetValue(trki);
      if(bcelectron_eta > EtaCut || bcelectron_eta < -EtaCut) continue;
      ptbin = getPtBin(bcelectron_pt);
      if(ptbin == -99) continue;
      if(ptbin > maxptbin)
        maxptbin = ptbin;
      hept[ptbin]->Fill(bcelectron_pt);
      hEventTallybe[maxptbin]->Fill(0.5); //fill for each NPE
      for(int trkj = 0; trkj < numberofHadrons; trkj++){

        assoh_id = (int)leaf_hadron_id->GetValue(trkj);
        assoh_status  = (int)leaf_hadron_status->GetValue(trkj);
        assoh_pt      = leaf_hadron_pt->GetValue(trkj);
        assoh_pz      = leaf_hadron_pz->GetValue(trkj);
        assoh_phi     = leaf_hadron_phi->GetValue(trkj);
        assoh_eta     = leaf_hadron_eta->GetValue(trkj);
        assoh_y       = leaf_hadron_y->GetValue(trkj);
        if(assoh_eta > hEtaCut || assoh_eta < -hEtaCut) continue;

        float deltPhi = assoh_phi - bcelectron_phi;
        float deltEta = assoh_eta - celectron_eta;
        if(deltPhi < -PI)  deltPhi += 2*PI;
        if(deltPhi >  PI) deltPhi -= 2*PI;
        if(abs(deltEta) > deletacut) continue;
        if(assoh_pt>hptCut)
        {
          hdPhiRawbe[ptbin]->Fill(deltPhi);
          hdEtaRawbe[ptbin]->Fill(deltEta);  
          bceNtrigcount++;
        }
      }
    }
    //    if(bceNtrigcount>0)hEventTallybe[maxptbin]->Fill("be non photonic electron",1);
    //    if(bceNtrigcount>0)beNtrigger++;


    /* if(ceNtrigger+bceNtrigger+beNtrigger > 0){
       std::cout<<"ce Trigger electron number = "<<ceNtrigger<<std::endl;
       std::cout<<"be Trigger electron number = "<<beNtrigger<<std::endl;
       std::cout<<"bce Trigger electron number = "<<bceNtrigger<<std::endl;
       }*/
  }

  // After Fill Manipulations
  for(int qq = 0; qq < numPtBins; qq++)
  {
    hdPhiRawceN[qq] = (TH1D*)hdPhiRawce[qq]->Clone();
    hdPhiRawceN[qq] -> SetName(Form("hdPhiRawceN_%i",qq));
    hdPhiRawceN[qq] -> Sumw2();
    hdPhiRawceN[qq] -> Scale(1./(Double_t)hEventTallyce[qq]->GetBinContent(1));
    hdPhiRawbeN[qq] = (TH1D*)hdPhiRawbe[qq]->Clone();
    hdPhiRawbeN[qq] -> SetName(Form("hdPhiRawbeN_%i",qq));
    hdPhiRawbeN[qq] -> Sumw2();
    hdPhiRawbeN[qq] -> Scale(1./(Double_t)hEventTallybe[qq]->GetBinContent(1));
  }

  std::cout << "100% [";
  for (int x=0; x<w; x++) std::cout << "=";
  std::cout << "]" << std::endl;
  fout.Write();
  fout.Close();
  delete chain;
}
예제 #29
0
파일: Sigma0.C 프로젝트: ktf/AliPhysics
void Hyperon(const char* dataset="collection.xml")
{
  /* $Id$ */
  TStopwatch timer;
  timer.Start();


    TStringToken libs("Core,Tree,Geom,VMC,Physics,Minuit,Gui,XMLParser,Minuit2,Proof,STEERBase,ESD,AOD,OADB,ANALYSIS,ANALYSISalice,CDB,RAWDatabase,STEER,CORRFW,PHOSUtils,PHOSbase,PHOSpi0Calib,PHOSrec,PHOSshuttle,PHOSsim", ",");
  while( libs.NextToken() )
    gSystem->Load( Form("lib%s", libs.Data()) );

  gSystem->Load("libTree");
  gSystem->Load("libGeom");
  gSystem->Load("libVMC");
  gSystem->Load("libPhysics");
  gSystem->Load("libPWGGAGammaConv");
  gSystem->Load("libPWGGAHyperon");
  
  //load analysis framework
  gSystem->Load("libANALYSIS");
  gSystem->Load("libANALYSISalice"); //AliAnalysisTaskSE
  
  // Connect to alien
  TString token = gSystem->Getenv("GRID_TOKEN") ;
  if (1) // token == "OK" ) 
    TGrid::Connect("alien://");
  else 
    AliInfo("You are not connected to the GRID") ; 

  cout << "Pi0Analysis: processing collection " << dataset << endl;

  // Create the chain
  TChain* chain = new TChain("aodTree");

  TGridCollection * collection = dynamic_cast<TGridCollection*>(TAlienCollection::Open(dataset));
  
  TAlienResult* result = collection->GetGridResult("",0 ,0);
  TList* rawFileList = result->GetFileInfoList();
  
  for (Int_t counter=0 ; counter < rawFileList->GetEntries() ; counter++) {
    TFileInfo * fi =  static_cast<TFileInfo*>(rawFileList->At(counter)) ; 
    const char * rawFile = fi->GetCurrentUrl()->GetUrl() ;  
    printf("Processing %s\n", rawFile) ;
    chain->Add(rawFile);
    printf("Chain: %d entries.\n",chain->GetEntriesFast()); 
  }

  // Make the analysis manager
  AliAnalysisManager *mgr = new AliAnalysisManager("Hyperon");
  mgr->SetCommonFileName("histos.root");
  
  // AOD input handler
  AliAODInputHandler* aodH = new AliAODInputHandler();
  mgr->SetInputEventHandler(aodH);

  
  // Debug level
  mgr->SetDebugLevel(2);

   gROOT->LoadMacro("$ALICE_PHYSICS/OADB/macros/AddTaskCentrality.C"); 
   AliCentralitySelectionTask* taskCentrality = AddTaskCentrality(); 
   if (analysisMC) 
    taskCentrality->SetMCInput(); 

  // // Update it for Hyperon (YK 22.01.2015)
  // gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskEventplane.C");
  // AliEPSelectionTask *taskEP = AddTaskEventplane() ; 

  // gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskVZEROEPSelection.C");
  // AliVZEROEPSelectionTask *selTask = AddTaskVZEROEPSelection();  

  // Add my task
  AliAnalysisHyperon* task = new AliAnalysisHyperon();
  // gROOT->LoadMacro("$ALICE_ROOT/PWGGA/PHOSTasks/PHOS_PbPb/AddTaskPHOSPi0Flow.C"); // Update it for Hyperon (YK 22.01.2015)
  // task = AddTaskPHOSPi0Flow();

  
  // // Create containers for input/output
  AliAnalysisDataContainer *cinput   = mgr->GetCommonInputContainer(); 
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("Hyperon",TList::Class(),AliAnalysisManager::kOutputContainer,"HyperonHist.root");
  
  // // Connect input/output
  mgr->ConnectInput(task , 0, cinput);
  mgr->ConnectOutput(task, 1, coutput1);
 
  if (mgr->InitAnalysis()) {
    mgr->PrintStatus();
    mgr->StartAnalysis("local", chain);
  }

  timer.Stop();
  timer.Print();
}
예제 #30
0
void produce_elefakepho(){//main  

//  TFile *efile = TFile::Open("plot_elefakepho_test.root","read");
//  TTree* etree = (TTree*)efile->Get("FakeRateTree");

 TChain *etree = new TChain("FakeRateTree");
 etree->Add("../data/plot_elefakepho_Calib.root"); 


  int tracks=0; 
  int nVertex=0;
  float mass_denmg=0,mass_nummg=0,et_denmg=0,et_nummg=0, rap_denmg=0, rap_nummg=0;
  float mass_denrandom=0,mass_numrandom=0,et_denrandom=0,et_numrandom=0,rap_denrandom=0,rap_numrandom=0;
  std::vector<float> *mass_denbothcount=0;
  std::vector<float> *mass_numbothcount=0;
  std::vector<float> *et_denbothcount=0;
  std::vector<float> *et_numbothcount=0;
  std::vector<float> *rap_denbothcount=0;
  std::vector<float> *rap_numbothcount=0;
  std::vector<float> *track_denbothcount=0;
  std::vector<float> *track_numbothcount=0;
  std::vector<float> *tagEta=0;
  std::vector<float> *tagPhi=0;
  std::vector<float> *tagPt=0;
  std::vector<float> *probeEta=0;
  std::vector<float> *probePhi=0;
  std::vector<float> *probePt=0;
  std::vector<float> *invmass=0;
  std::vector<bool>  *vetovalue=0;
  
  etree->SetBranchAddress("tracks",&tracks);
  etree->SetBranchAddress("nVertex",&nVertex);
  etree->SetBranchAddress("mass_denrandom",      &mass_denrandom);    
  etree->SetBranchAddress("mass_numrandom",      &mass_numrandom);
  etree->SetBranchAddress("et_denrandom",        &et_denrandom);   
  etree->SetBranchAddress("et_numrandom",        &et_numrandom);  
  etree->SetBranchAddress("rap_denrandom",       &rap_denrandom);   
  etree->SetBranchAddress("rap_numrandom",       &rap_numrandom);  
  etree->SetBranchAddress("mass_denbothcount",   &mass_denbothcount); 
  etree->SetBranchAddress("mass_numbothcount",   &mass_numbothcount); 
  etree->SetBranchAddress("et_denbothcount",     &et_denbothcount);   
  etree->SetBranchAddress("et_numbothcount",     &et_numbothcount);   
  etree->SetBranchAddress("rap_denbothcount",    &rap_denbothcount);  
  etree->SetBranchAddress("rap_numbothcount",    &rap_numbothcount);  
  etree->SetBranchAddress("track_denbothcount",  &track_denbothcount);
  etree->SetBranchAddress("track_numbothcount",  &track_numbothcount);
  etree->SetBranchAddress("tagEta",              &tagEta);
  etree->SetBranchAddress("tagPhi",              &tagPhi);
  etree->SetBranchAddress("tagPt",               &tagPt);
  etree->SetBranchAddress("probeEta",            &probeEta);
  etree->SetBranchAddress("probePhi",            &probePhi);
  etree->SetBranchAddress("probePt",             &probePt);
  etree->SetBranchAddress("invmass",             &invmass);
  etree->SetBranchAddress("vetovalue",           &vetovalue);

  //float PtBins[]={25,30,35,40,45,50,60,70,90,110};
  float PtBins[]={25,30,35,40,50,60,70};
  float NtrkBins[] = {10,20,30,40,50,60,70,90,120};
  float EtaBins[] = {0.0,0.1,0.2,0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3};
  float VertexBins[]={0,4,8,10,11,12,13,14,15,16,17,18,20};
  unsigned nPtBins = sizeof(PtBins)/sizeof(float);
  unsigned nNtrkBins = sizeof(NtrkBins)/sizeof(float);
  unsigned nEtaBins = sizeof(EtaBins)/sizeof(float);
  unsigned nVertexBins = sizeof(VertexBins)/sizeof(float);

  TFile *outputfile = TFile::Open("histo_elefakepho_Calib.root","RECREATE");
  outputfile->cd();

  TH1F* den_random_pt[nPtBins]; 
  TH1F* den_random_trk[nNtrkBins];
  TH1F* den_random_eta[nEtaBins];
  TH1F* den_random_vtx[nVertexBins];
  TH1F* num_random_pt[nPtBins]; 
  TH1F* num_random_trk[nNtrkBins];
  TH1F* num_random_eta[nEtaBins];
  TH1F* num_random_vtx[nVertexBins];

  TH1F* den_both_pt[nPtBins]; 
  TH1F* den_both_trk[nNtrkBins];
  TH1F* den_both_eta[nEtaBins];
  TH1F* den_both_vtx[nVertexBins];
  TH1F* num_both_pt[nPtBins]; 
  TH1F* num_both_trk[nNtrkBins];
  TH1F* num_both_eta[nEtaBins];
  TH1F* num_both_vtx[nVertexBins];

  TH1F *event_type=new TH1F("event_type","",10,0,10);
 
  std::ostringstream binname; 
  for(unsigned iPt(0); iPt < nPtBins; iPt++){
    binname.str("");
    if(iPt != nPtBins-1)binname << "den_random_pt-" << PtBins[iPt] << "-" << PtBins[iPt+1];
    else binname << "den_random_pt-" << PtBins[iPt] << "-inf";
    den_random_pt[iPt] = new TH1F(binname.str().c_str(), binname.str().c_str(), 60, 60,120);
    binname.str("");
    if(iPt != nPtBins-1)binname << "num_random_pt-" << PtBins[iPt] << "-" << PtBins[iPt+1];
    else binname << "num_random_pt-" << PtBins[iPt] << "-inf";
    num_random_pt[iPt] = new TH1F(binname.str().c_str(), binname.str().c_str(), 60, 60,120);
    binname.str("");
    if(iPt != nPtBins-1)binname << "den_both_pt-" << PtBins[iPt] << "-" << PtBins[iPt+1];
    else binname << "den_both_pt-" << PtBins[iPt] << "-inf";
    den_both_pt[iPt] = new TH1F(binname.str().c_str(), binname.str().c_str(), 60, 60,120);
    binname.str("");
    if(iPt != nPtBins-1)binname << "num_both_pt-" << PtBins[iPt] << "-" << PtBins[iPt+1];
    else binname << "num_both_pt-" << PtBins[iPt] << "-inf";
    num_both_pt[iPt] = new TH1F(binname.str().c_str(), binname.str().c_str(), 60, 60,120);
  }
    

  for(unsigned iNtrk(0); iNtrk < nNtrkBins; iNtrk++){
    binname.str("");
    if(iNtrk != nNtrkBins-1)binname << "den_random_trk-" << NtrkBins[iNtrk] << "-" << NtrkBins[iNtrk+1];
    else binname << "den_random_trk-" << NtrkBins[iNtrk] << "-inf";
    den_random_trk[iNtrk] = new TH1F(binname.str().c_str(), binname.str().c_str(), 60, 60,120);
    binname.str("");
    if(iNtrk != nNtrkBins-1)binname << "num_random_trk-" << NtrkBins[iNtrk] << "-" << NtrkBins[iNtrk+1];
    else binname << "num_random_trk-" << NtrkBins[iNtrk] << "-inf";
    num_random_trk[iNtrk] = new TH1F(binname.str().c_str(), binname.str().c_str(), 60, 60,120);
    binname.str("");
    if(iNtrk != nNtrkBins-1)binname << "den_both_trk-" << NtrkBins[iNtrk] << "-" << NtrkBins[iNtrk+1];
    else binname << "den_both_trk-" << NtrkBins[iNtrk] << "-inf";
    den_both_trk[iNtrk] = new TH1F(binname.str().c_str(), binname.str().c_str(), 60, 60,120);
    binname.str("");
    if(iNtrk != nNtrkBins-1)binname << "num_both_trk-" << NtrkBins[iNtrk] << "-" << NtrkBins[iNtrk+1];
    else binname << "num_both_trk-" << NtrkBins[iNtrk] << "-inf";
    num_both_trk[iNtrk] = new TH1F(binname.str().c_str(), binname.str().c_str(), 60, 60,120);
  }


  for(unsigned iEta(0); iEta < nEtaBins; iEta++){
    binname.str("");
    if(iEta != nEtaBins-1)binname << "den_random_eta-" << EtaBins[iEta] << "-" << EtaBins[iEta+1];
    else binname << "den_random_eta-" << EtaBins[iEta] << "-inf";
    den_random_eta[iEta] = new TH1F(binname.str().c_str(), binname.str().c_str(), 60, 60,120);
    binname.str("");
    if(iEta != nEtaBins-1)binname << "num_random_eta-" << EtaBins[iEta] << "-" << EtaBins[iEta+1];
    else binname << "num_random_eta-" << EtaBins[iEta] << "-inf";
    num_random_eta[iEta] = new TH1F(binname.str().c_str(), binname.str().c_str(), 60, 60,120);
    binname.str("");
    if(iEta != nEtaBins-1)binname << "den_both_eta-" << EtaBins[iEta] << "-" << EtaBins[iEta+1];
    else binname << "den_both_eta-" << EtaBins[iEta] << "-inf";
    den_both_eta[iEta] = new TH1F(binname.str().c_str(), binname.str().c_str(), 60, 60,120);
    binname.str("");
    if(iEta != nEtaBins-1)binname << "num_both_eta-" << EtaBins[iEta] << "-" << EtaBins[iEta+1];
    else binname << "num_both_eta-" << EtaBins[iEta] << "-inf";
    num_both_eta[iEta] = new TH1F(binname.str().c_str(), binname.str().c_str(), 60, 60,120);
  }

  for(unsigned iVertexBins(0); iVertexBins < nVertexBins; iVertexBins++){
    binname.str("");
    if(iVertexBins != nVertexBins-1)binname << "den_random_vtx-" << VertexBins[iVertexBins] << "-" << VertexBins[iVertexBins+1];
    else binname << "den_random_vtx-" << VertexBins[iVertexBins] << "-inf";
    den_random_vtx[iVertexBins] = new TH1F(binname.str().c_str(), binname.str().c_str(), 60, 60,120);
    binname.str("");
    if(iVertexBins != nVertexBins-1)binname << "num_random_vtx-" << VertexBins[iVertexBins] << "-" << VertexBins[iVertexBins+1];
    else binname << "num_random_vtx-" << VertexBins[iVertexBins] << "-inf";
    num_random_vtx[iVertexBins] = new TH1F(binname.str().c_str(), binname.str().c_str(), 60, 60,120);
    binname.str("");
    if(iVertexBins != nVertexBins-1)binname << "den_both_vtx-" << VertexBins[iVertexBins] << "-" << VertexBins[iVertexBins+1];
    else binname << "den_both_vtx-" << VertexBins[iVertexBins] << "-inf";
    den_both_vtx[iVertexBins] = new TH1F(binname.str().c_str(), binname.str().c_str(), 60, 60,120);
    binname.str("");
    if(iVertexBins != nVertexBins-1)binname << "num_both_vtx-" << VertexBins[iVertexBins] << "-" << VertexBins[iVertexBins+1];
    else binname << "num_both_vtx-" << VertexBins[iVertexBins] << "-inf";
    num_both_vtx[iVertexBins] = new TH1F(binname.str().c_str(), binname.str().c_str(), 60, 60,120);
  }

  const unsigned nEvts = etree->GetEntries(); 
  for(unsigned iEvt(0); iEvt < nEvts; iEvt++){
    etree->GetEntry(iEvt);
    nVertex = nVertex+0.1;

    if(mass_denrandom > 40.0){
      den_random_pt[findIndex(PtBins,et_denrandom,nPtBins)]->Fill(mass_denrandom);
      den_random_trk[findIndex(NtrkBins,tracks,nNtrkBins)]->Fill(mass_denrandom);
      den_random_eta[findIndex(EtaBins,fabs(rap_denrandom),nEtaBins)]->Fill(mass_denrandom); 
      den_random_vtx[findIndex(VertexBins,nVertex, nVertexBins)]->Fill(mass_denrandom);
    }

    if(mass_numrandom > 40.0){
      num_random_pt[findIndex(PtBins,et_numrandom,nPtBins)]->Fill(mass_numrandom);
      num_random_trk[findIndex(NtrkBins,tracks,nNtrkBins)]->Fill(mass_numrandom);
      num_random_eta[findIndex(EtaBins,fabs(rap_numrandom),nEtaBins)]->Fill(mass_numrandom); 
      num_random_vtx[findIndex(VertexBins,nVertex, nVertexBins)]->Fill(mass_numrandom);
    }

    if(mass_denbothcount->size()>0){
      for(unsigned ii(0); ii<mass_denbothcount->size(); ii++){
        den_both_pt[findIndex(PtBins, (*et_denbothcount)[ii], nPtBins)]->Fill( (*mass_denbothcount)[ii]);
        den_both_trk[findIndex(NtrkBins, (*track_denbothcount)[ii], nNtrkBins)]->Fill((*mass_denbothcount)[ii]);
        den_both_eta[findIndex(EtaBins, fabs((*rap_denbothcount)[ii]), nEtaBins)]->Fill((*mass_denbothcount)[ii]);
        den_both_vtx[findIndex(VertexBins,nVertex, nVertexBins)]->Fill((*mass_denbothcount)[ii]);
      }
    }

    if(mass_numbothcount->size()>0){
      for(unsigned ii(0); ii<mass_numbothcount->size(); ii++){
        num_both_pt[findIndex(PtBins, (*et_numbothcount)[ii], nPtBins)]->Fill( (*mass_numbothcount)[ii]);
        num_both_trk[findIndex(NtrkBins, (*track_numbothcount)[ii], nNtrkBins)]->Fill((*mass_numbothcount)[ii]);
        num_both_eta[findIndex(EtaBins, fabs((*rap_numbothcount)[ii]), nEtaBins)]->Fill((*mass_numbothcount)[ii]);
        num_both_vtx[findIndex(VertexBins,nVertex, nVertexBins)]->Fill((*mass_numbothcount)[ii]);
      }
    }

  }

outputfile->Write();
outputfile->Close();
}