void PP_MC_normResponseMatrix(int radius = 3){

  gStyle->SetOptStat(0);
  
  bool printDebug = true;
  
  TFile * fin = TFile::Open(Form("pp_MC_new_ak%d_20_eta_20.root",radius));
  
  TH2F * mPP_Matrix;
  TH2F * mPP_Response;
  TH2F * mPP_ResponseNorm;
  TH2F * mPP_ResponseNorm_recoTrunc;

  // TH2F * mPbPb_Matrix_recoTrunc[nbins_cent];
  // TH2F * mPbPb_Response_recoTrunc[nbins_cent];
  // TH2F * mPbPb_ResponseNorm_recoTrunc[nbins_cent];

  TFile fout(Form("PP_kineticEfficiency_correctionFactors_R%d.root",radius),"RECREATE");
  fout.cd();
  
  TH1F * hGen_Projection;
  TH1F * hGen_Projection_recoTrunc;
  TH1F * hKineticEfficiency;

  TCanvas * cGenProj = new TCanvas("cGenProj","",800,600);
  TCanvas * cKineticEfficiency = new TCanvas("cKineticEfficiency","",800,600);  

  TCanvas * cMatrix = new TCanvas("cMatrix","",800,600);
  TCanvas * cMatrix_recoTrunc = new TCanvas("cMatrix_recoTrunc","",800,600);
  
  mPP_Matrix = (TH2F*)fin->Get(Form("hpp_matrix_HLT_R%d_20_eta_20",radius));
  mPP_Matrix->Rebin2D(10, 10);

  for (int y=1;y<=mPP_Matrix->GetNbinsY();y++) {
    double sum=0;
    for (int x=1;x<=mPP_Matrix->GetNbinsX();x++) {
      if (mPP_Matrix->GetBinContent(x,y)<=1*mPP_Matrix->GetBinError(x,y)) {
	mPP_Matrix->SetBinContent(x,y,0);
	mPP_Matrix->SetBinError(x,y,0);
      }
      sum+=mPP_Matrix->GetBinContent(x,y);
    }
    
    for (int x=1;x<=mPP_Matrix->GetNbinsX();x++) {	   
      double ratio = 1;
      // if (hGenSpectraCorrPP->GetBinContent(x)!=0) ratio = 1e5/hGenSpectraCorrPP->GetBinContent(x);
      mPP_Matrix->SetBinContent(x,y,mPP_Matrix->GetBinContent(x,y)*ratio);
      mPP_Matrix->SetBinError(x,y,mPP_Matrix->GetBinError(x,y)*ratio);
    }
  }
  // mPbPb_Matrix[i]->Smooth(0);
  
  // Ok major differences here between my code and Kurt in b-jet Tools under Unfold - lines 469 and above.  

  if(printDebug) cout<<"getting the response matrix"<<endl;

  mPP_Response = (TH2F*)mPP_Matrix->Clone("mPP_Response");
  TH1F *hProjPP = (TH1F*)mPP_Response->ProjectionY()->Clone("hProjPP");
  
  
  for (int y=1;y<=mPP_Response->GetNbinsY();y++) {
    double sum=0;
    for (int x=1;x<=mPP_Response->GetNbinsX();x++) {
      if (mPP_Response->GetBinContent(x,y)<=1*mPP_Response->GetBinError(x,y)) {
	// in the above if statement, kurt has 1*error and my old has 0*error
	mPP_Response->SetBinContent(x,y,0);
	mPP_Response->SetBinError(x,y,0);
      }
      sum+=mPP_Response->GetBinContent(x,y);
    }
    
    for (int x=1;x<=mPP_Response->GetNbinsX();x++) {  	
      if (sum==0) continue;
      double ratio = 1;
      //if(dPbPb_TrgComb[i]->GetBinContent(y)==0) ratio = 1e-100/sum;
      // else ratio = dPbPb_TrgComb[i]->GetBinContent(y)/sum
      ratio = 1./sum;
      if (hProjPP->GetBinContent(y)==0) ratio = 1e-100/sum;
      else ratio = hProjPP->GetBinContent(y)/sum;
      mPP_Response->SetBinContent(x,y,mPP_Response->GetBinContent(x,y)*ratio);
      mPP_Response->SetBinError(x,y,mPP_Response->GetBinError(x,y)*ratio);
    }
  }
  if(printDebug) cout<<"getting the normalized response matrix"<<endl;
  mPP_ResponseNorm = (TH2F*)mPP_Matrix->Clone("mPP_ResponseNorm");
  for (int x=1;x<=mPP_ResponseNorm->GetNbinsX();x++) {
    double sum=0;
    for (int y=1;y<=mPP_ResponseNorm->GetNbinsY();y++) {
      if (mPP_ResponseNorm->GetBinContent(x,y)<=1*mPP_ResponseNorm->GetBinError(x,y)) {
	mPP_ResponseNorm->SetBinContent(x,y,0);
	mPP_ResponseNorm->SetBinError(x,y,0);
      }
      sum+=mPP_ResponseNorm->GetBinContent(x,y);
    }
    
    for (int y=1;y<=mPP_ResponseNorm->GetNbinsY();y++) {  	
      if (sum==0) continue;
      double ratio = 1./sum;
      mPP_ResponseNorm->SetBinContent(x,y,mPP_ResponseNorm->GetBinContent(x,y)*ratio);
      mPP_ResponseNorm->SetBinError(x,y,mPP_ResponseNorm->GetBinError(x,y)*ratio);
    }
    
    
  }

  
  hGen_Projection = (TH1F*)mPP_ResponseNorm->ProjectionX();
  hGen_Projection->SetName("hGen_Projection");
  // hGen_Projection->Rebin(10);

  cout<<"Finished getting histograms for full untruncated response matrix"<<endl;

  mPP_ResponseNorm_recoTrunc = (TH2F*)mPP_ResponseNorm->Clone("mPP_ResponseNorm_recoTrunc");

  for(int x = 0; x < mPP_ResponseNorm->GetNbinsX(); ++x){

    for(int y = 0; y < mPP_ResponseNorm->GetNbinsY(); ++y){

      if(y < mPP_ResponseNorm->GetYaxis()->FindBin(50) || y > mPP_ResponseNorm->GetYaxis()->FindBin(350)){
	mPP_ResponseNorm_recoTrunc->SetBinContent(x, y, 0.0);
	mPP_ResponseNorm_recoTrunc->SetBinError(x, y, 0.0);
      }
	
    }
      
  }
    
  hGen_Projection_recoTrunc = (TH1F*)mPP_ResponseNorm_recoTrunc->ProjectionX();
  hGen_Projection_recoTrunc->SetName("hGen_Projection_recoTrunc");
  // hGen_Projection_recoTrunc->Rebin(10);

  cout<<"finished getting histograms for truncted response matrix"<<endl;
    
  hKineticEfficiency = (TH1F*)hGen_Projection_recoTrunc->Clone("hKineticEfficiency");
  hKineticEfficiency->Divide(hGen_Projection);

  for(int bin = 1; bin<=hKineticEfficiency->GetNbinsX(); ++bin){
    double val = hKineticEfficiency->GetBinContent(bin);
    val = 1./val;
    hKineticEfficiency->SetBinContent(bin, val);
  }

  cout<<"Plotting kinetic efficiency"<<endl;
    
  cKineticEfficiency->cd();

  hKineticEfficiency->SetTitle(" ");
  hKineticEfficiency->SetXTitle("Gen p_{T} (GeV/c)");
  hKineticEfficiency->SetYTitle("Kinetic Efficiency");

  hKineticEfficiency->SetMarkerStyle(20);
  hKineticEfficiency->SetMarkerColor(kBlack);
  hKineticEfficiency->SetAxisRange(60, 299, "X");
  hKineticEfficiency->SetAxisRange(0.98, 1.05, "Y");
  hKineticEfficiency->Draw();

  drawText("PYTHIA, Kinetic Efficiency", 0.25,0.7,14);
  drawText(Form("ak%dPF Jets",radius), 0.25, 0.65, 14);
    
  cout<<"Finished plotting kinetic efficiency"<<endl;

  cGenProj->cd();
  hGen_Projection->SetTitle(" ");
  hGen_Projection->SetXTitle("Gen p_{T} (GeV/c)");
  hGen_Projection->SetYTitle("GenProjection of Normalized Response Matrix");
  hGen_Projection->Scale(1./10);
  hGen_Projection->SetMarkerStyle(33);
  hGen_Projection->SetMarkerColor(kBlack);
  hGen_Projection->SetAxisRange(20, 350, "X");
  hGen_Projection->SetAxisRange(0.6, 1.4, "Y");
  hGen_Projection->Draw();

  hGen_Projection_recoTrunc->Scale(1./10);
  hGen_Projection_recoTrunc->SetMarkerStyle(25);
  hGen_Projection_recoTrunc->SetMarkerColor(kRed);
  hGen_Projection_recoTrunc->Draw("same");

  drawText("PYTHIA, Projection onto Gen axis", 0.25,0.7,14);
  drawText(Form("ak%dPF Jets",radius), 0.25, 0.65, 14);
    
  TLegend * leg = myLegend(0.3,0.6,0.7,0.7);
  leg->AddEntry(hGen_Projection,"No Truncation in Reco pT","pl");
  leg->AddEntry(hGen_Projection_recoTrunc,"reco pT truncated 40 to 350 GeV","pl");
  leg->SetTextSize(0.04);
  leg->Draw();


  cMatrix->cd();
  // mPP_ResponseNorm->Rebin2D(10, 10);
  // mPP_ResponseNorm->Scale(1./TMath::Sqrt(10));
  makeHistTitle(mPP_ResponseNorm," ","Gen p_{T} (GeV/c)","Reco p_{T} (GeV/c)");
  mPP_ResponseNorm->SetAxisRange(0, 500, "X");
  mPP_ResponseNorm->SetAxisRange(0, 500, "Y");
  mPP_ResponseNorm->SetAxisRange(0.001, 1, "Z");
  mPP_ResponseNorm->Draw("colz");  
  drawText("PYTHIA", 0.15,0.8,14);
  drawText(Form("ak%dPF Jets",radius), 0.15, 0.75, 14);

  
  cMatrix_recoTrunc->cd();
  // mPP_ResponseNorm_recoTrunc->Rebin2D(10, 10);
  // mPP_ResponseNorm_recoTrunc->Scale(1./TMath::Sqrt(10));
  makeHistTitle(mPP_ResponseNorm_recoTrunc," ","Gen p_{T} (GeV/c)","Reco p_{T} (GeV/c)");
  mPP_ResponseNorm_recoTrunc->SetAxisRange(0, 500, "X");
  mPP_ResponseNorm_recoTrunc->SetAxisRange(0, 500, "Y");
  mPP_ResponseNorm_recoTrunc->SetAxisRange(0.001, 1, "Z");
  mPP_ResponseNorm_recoTrunc->Draw("colz");  
  drawText("PYTHIA, reco p_{T} truncated", 0.15,0.8,14);
  drawText(Form("ak%dPF Jets",radius), 0.15, 0.75, 14);
  
  cKineticEfficiency->SaveAs(Form("KineticEfficiency_R%d_PPMC.pdf",radius),"RECREATE");
  cGenProj->SaveAs(Form("GenProjection_R%d_PPMC.pdf",radius),"RECREATE");
  cMatrix->SaveAs(Form("ResponseMatrix_R%d_PPMC.pdf",radius),"RECREATE");
  cMatrix_recoTrunc->SaveAs(Form("ResponseMatrix_recoTrunc_R%d_PPMC.pdf",radius),"RECREATE");
  
  
  fout.Write();
  fout.Close();
  
}
Пример #2
0
int main() {
  float min_logL1 = 5986.94;
  float min_logL0 = 5987.16;
  
  string filepath="FINAL_RESULT_AB.root_RESULT__RESULT";
  filepath="/shome/buchmann/KillerKoala/CBAF/Development/exchange/RooFit__WorkSpace__Exchange_201417_175622__RNSG_46692.4.root__RESULT__RESULT"; // final MCwS 
  
  filepath="/shome/buchmann/KillerKoala/CBAF/Development/exchange/RooFit__WorkSpace__Exchange_201417_175622__RNSG_46692.4.root__RESULT__RESULT";


  filepath="/shome/buchmann/KillerKoala/CBAF/Development/exchange/RooFit__WorkSpace__Exchange_201417_141126__RNSG_97048.1.root__RESULT__RESULT";
//  *************************************************************************************

  setlumi(PlottingSetup::luminosity);
  setessentialcut(PlottingSetup::essential);  // this sets the essential cut; this one is used in the draw command so it is AUTOMATICALLY applied everywhere. IMPORTANT: Do NOT store weights here!
  stringstream resultsummary;

  // write_analysis_type(PlottingSetup::RestrictToMassPeak,PlottingSetup::DoBTag);
  do_png(true);
  do_pdf(true);
  do_eps(false);
  do_C(true);
  do_root(false);

  PlottingSetup::directoryname = "pValuePlot";
  gROOT->SetStyle("Plain");
  bool do_fat_line = false;  // if you want to have HistLineWidth=1 and FuncWidth=1 as it was before instead of 2
  setTDRStyle(do_fat_line);
  gStyle->SetTextFont(42);
  bool showList = true;
  set_directory(PlottingSetup::directoryname);  // Indicate the directory name where you'd like to save the output files in Setup.C
  set_treename("events");        // you can set the treename here to be used; options are "events" (for reco) for "PFevents" (for particle flow)


  
  TFile *f = new TFile(filepath.c_str());

  if(f->IsZombie()) {
    cout << "Seems to be a zombie. goodbye." << endl;
    return -1;
  }

  RooWorkspace *wa = (RooWorkspace*)f->Get("transferSpace");
  RooPlot *plot = (RooPlot*) wa->obj("frame_mlledge_109fde50");
  
  
//  cout << plot << endl;
wa->Print("v");
  


   TCanvas *can = new TCanvas("can","can");
   
cout << "Address of plot : " << plot << endl;
//   plot->Draw();
   
   float pVal_mllmin=35;
   float pVal_mllmax=90;
   int is_data=PlottingSetup::data;
   
   vector < std::pair < float, float> > loglikelihoods;
   
   string function="";
   for(int i=0; i< plot->numItems();i++){
     string name = plot->getObject(i)->GetName();
     if (plot->getObject(i)->IsA()->InheritsFrom( "RooCurve" ))function=name;
   }
   
   RooCurve* curve = (RooCurve*) plot->findObject(function.c_str(),RooCurve::Class()) ;
   if (!curve) { 
     dout << "RooPlot::residHist(" << plot->GetName() << ") cannot find curve" << endl ;
     return 0 ;
   }
   
   int iMinimum=0;
   float min=1e7;

   for(int i=0;i<curve->GetN();i++) {
     double x,y;
     curve->GetPoint(i,x,y);
     if(y<min & y>=0) {
       min=y;
       iMinimum=i;
     }
   }
   
   double x,y;
   curve->GetPoint(iMinimum,x,y);
   cout << "Minimum is at " << x << " : " << y << endl;
   loglikelihoods.push_back(make_pair(x,y+min_logL1));
   
   //move right starting from the minimum
   for(int i=iMinimum+1;i<curve->GetN();i++) {
     float yold=y;
     curve->GetPoint(i,x,y);
     //if(abs((y-yold)/yold)>0.5) continue;
     loglikelihoods.push_back(make_pair(x,y+min_logL1));
   }
   
   /*  
   for(int i=0;i<curve->GetN();i++) {
     double x,y;
     curve->GetPoint(i,x,y);
     loglikelihoods.push_back(make_pair(x,y+min_logL1));
   }*/
     
     
   
   cout << "The whole thing contains " << loglikelihoods.size() << " points " << endl;
   ProduceSignificancePlots(min_logL0, loglikelihoods, pVal_mllmin, pVal_mllmax, is_data, "", "");
   
   
   
   can->SaveAs("Crap.png");
   
   delete can;
   delete plot;
   delete wa;
   f->Close();
  return 0;
}
Пример #3
0
void PhotonIsolation()

{
  const float chargeHadronIsoCut_LWP_EB = 1.3;
  const float chargeHadronIsoCut_MWP_EB = 0.44;
  const float chargeHadronIsoCut_TWP_EB = 0.2;

  const float chargeHadronIsoCut_LWP_EE = 1.36;
  const float chargeHadronIsoCut_MWP_EE = 0.82;
  const float chargeHadronIsoCut_TWP_EE = 0.27;

  const float HoverECut_LWP_EB = 0.06;
  const float HoverECut_MWP_EB = 0.04;
  const float HoverECut_TWP_EB = 0.027;

  const float HoverECut_LWP_EE = 0.027;
  const float HoverECut_MWP_EE = 0.021;
  const float HoverECut_TWP_EE = 0.020;

  const float SigIEtaIEtaCut_LWP_EB = 0.01031;
  const float SigIEtaIEtaCut_MWP_EB = 0.01023;
  const float SigIEtaIEtaCut_TWP_EB = 0.00994;

  const float SigIEtaIEtaCut_LWP_EE = 0.0269;
  const float SigIEtaIEtaCut_MWP_EE = 0.0259;
  const float SigIEtaIEtaCut_TWP_EE = 0.0258;

  const float beamSpotZ = 0.282329;
  const float beamSpotSigmaZ = 43.131299;
  const float NPU = 140.0;

  const int n_density = 5;

  float IsoEff_NoTiming[n_density] = {0.0};// for n_density pu density bins, ranging from 0 to 2.0, bin width 0.1
  float Err_IsoEff_NoTiming[n_density] = {0.0};// for n_density pu density bins, ranging from 0 to 2.0, bin width 0.1
  float IsoEff_Timing50_TrkVtx[n_density] = {0.0}; 
  float IsoEff_Timing80_TrkVtx[n_density] = {0.0}; 
  float Err_IsoEff_Timing80_TrkVtx[n_density] = {0.0}; 
  float IsoEff_Timing120_TrkVtx[n_density] = {0.0}; 

  float IsoEff_Timing50_TrkPho[n_density] = {0.0}; 
  float IsoEff_Timing80_TrkPho[n_density] = {0.0}; 
  float IsoEff_Timing120_TrkPho[n_density] = {0.0}; 
  float Err_IsoEff_Timing120_TrkPho[n_density] = {0.0}; 


  int N_Pho_Total_NoBin = 0;
  int N_Pho_Total_NoBin200 = 0;
  int N_Pho_Total[n_density] = {0};
  int N_Pho_Total200[n_density] = {0};
  int N_Pho_PassIso_NoTiming[n_density] = {0}; 
  int N_Pho_PassIso_Timing50_TrkVtx[n_density] = {0}; 
  int N_Pho_PassIso_Timing80_TrkVtx[n_density] = {0}; 
  int N_Pho_PassIso_Timing120_TrkVtx[n_density] = {0}; 
 
  int N_Pho_PassIso_Timing50_TrkPho[n_density] = {0}; 
  int N_Pho_PassIso_Timing80_TrkPho[n_density] = {0}; 
  int N_Pho_PassIso_Timing120_TrkPho[n_density] = {0}; 
 

  TTree * tree = 0;
  TFile *f  =new TFile("/afs/cern.ch/work/z/zhicaiz/public/release/CMSSW_8_1_0_pre15/src/SUSYBSMAnalysis/RazorTuplizer/python/razorNtuple_PU140_Timing_Iso.root");
  TDirectory * dir = (TDirectory*)f->Get("/afs/cern.ch/work/z/zhicaiz/public/release/CMSSW_8_1_0_pre15/src/SUSYBSMAnalysis/RazorTuplizer/python/razorNtuple_PU140_Timing_Iso.root:/ntuples");
  dir->GetObject("RazorEvents",tree);
  //cout<<tree->GetEntries()<<endl;  
  int NEntries = tree->GetEntries();

  TTree * tree200 = 0;
  TFile *f200  =new TFile("/afs/cern.ch/work/z/zhicaiz/public/release/CMSSW_8_1_0_pre15/src/SUSYBSMAnalysis/RazorTuplizer/python/razorNtuple_PU200_Timing_Iso.root");
  TDirectory * dir200 = (TDirectory*)f200->Get("/afs/cern.ch/work/z/zhicaiz/public/release/CMSSW_8_1_0_pre15/src/SUSYBSMAnalysis/RazorTuplizer/python/razorNtuple_PU200_Timing_Iso.root:/ntuples");
  dir200->GetObject("RazorEvents",tree200);
  //cout<<tree->GetEntries()<<endl;  
  int NEntries200 = tree200->GetEntries();


  Int_t           nPhotons;

  Float_t         pvZ;
  Float_t         phoSigmaIetaIeta[700];
  Float_t         pho_superClusterEta[700];
  Float_t         pho_superClusterEnergy[700];
  Float_t         pho_HoverE[700];
  Bool_t          pho_passEleVeto[700];
  
  Float_t         pho_sumChargedHadronPt_NewPV_NoTiming[700];
  Float_t         pho_sumChargedHadronPt_NewPV_Timing50_TrkVtx[700];
  Float_t         pho_sumChargedHadronPt_NewPV_Timing80_TrkVtx[700];
  Float_t         pho_sumChargedHadronPt_NewPV_Timing120_TrkVtx[700];
 
  Float_t         pho_sumChargedHadronPt_NewPV_Timing50_TrkPho[700];
  Float_t         pho_sumChargedHadronPt_NewPV_Timing80_TrkPho[700];
  Float_t         pho_sumChargedHadronPt_NewPV_Timing120_TrkPho[700];
  
  tree->SetBranchAddress("nPhotons", &nPhotons);
  tree->SetBranchAddress("pvZ_New", &pvZ);
  tree->SetBranchAddress("phoSigmaIetaIeta", phoSigmaIetaIeta);
  tree->SetBranchAddress("pho_superClusterEta", pho_superClusterEta);
  tree->SetBranchAddress("pho_superClusterEnergy", pho_superClusterEnergy);
  tree->SetBranchAddress("pho_HoverE", pho_HoverE);
  tree->SetBranchAddress("pho_passEleVeto", pho_passEleVeto);
  
  tree->SetBranchAddress("pho_sumChargedHadronPt_NewPV_NoTiming", pho_sumChargedHadronPt_NewPV_NoTiming);
  tree->SetBranchAddress("pho_sumChargedHadronPt_NewPV_Timing50_TrkVtx", pho_sumChargedHadronPt_NewPV_Timing50_TrkVtx);
  tree->SetBranchAddress("pho_sumChargedHadronPt_NewPV_Timing80_TrkVtx", pho_sumChargedHadronPt_NewPV_Timing80_TrkVtx);
  tree->SetBranchAddress("pho_sumChargedHadronPt_NewPV_Timing120_TrkVtx", pho_sumChargedHadronPt_NewPV_Timing120_TrkVtx);

  tree->SetBranchAddress("pho_sumChargedHadronPt_NewPV_Timing50_TrkPho", pho_sumChargedHadronPt_NewPV_Timing50_TrkPho);
  tree->SetBranchAddress("pho_sumChargedHadronPt_NewPV_Timing80_TrkPho", pho_sumChargedHadronPt_NewPV_Timing80_TrkPho);
  tree->SetBranchAddress("pho_sumChargedHadronPt_NewPV_Timing120_TrkPho", pho_sumChargedHadronPt_NewPV_Timing120_TrkPho);

  tree200->SetBranchAddress("nPhotons", &nPhotons);
  tree200->SetBranchAddress("pvZ_New", &pvZ);
  tree200->SetBranchAddress("phoSigmaIetaIeta", phoSigmaIetaIeta);
  tree200->SetBranchAddress("pho_superClusterEta", pho_superClusterEta);
  tree200->SetBranchAddress("pho_superClusterEnergy", pho_superClusterEnergy);
  tree200->SetBranchAddress("pho_HoverE", pho_HoverE);
  tree200->SetBranchAddress("pho_passEleVeto", pho_passEleVeto);
  
  tree200->SetBranchAddress("pho_sumChargedHadronPt_NewPV_NoTiming", pho_sumChargedHadronPt_NewPV_NoTiming);
  tree200->SetBranchAddress("pho_sumChargedHadronPt_NewPV_Timing50_TrkVtx", pho_sumChargedHadronPt_NewPV_Timing50_TrkVtx);
  tree200->SetBranchAddress("pho_sumChargedHadronPt_NewPV_Timing80_TrkVtx", pho_sumChargedHadronPt_NewPV_Timing80_TrkVtx);
  tree200->SetBranchAddress("pho_sumChargedHadronPt_NewPV_Timing120_TrkVtx", pho_sumChargedHadronPt_NewPV_Timing120_TrkVtx);

  tree200->SetBranchAddress("pho_sumChargedHadronPt_NewPV_Timing50_TrkPho", pho_sumChargedHadronPt_NewPV_Timing50_TrkPho);
  tree200->SetBranchAddress("pho_sumChargedHadronPt_NewPV_Timing80_TrkPho", pho_sumChargedHadronPt_NewPV_Timing80_TrkPho);
  tree200->SetBranchAddress("pho_sumChargedHadronPt_NewPV_Timing120_TrkPho", pho_sumChargedHadronPt_NewPV_Timing120_TrkPho);


  TH1F * h_pho_sumChargedHadronPt_NewPV_NoTiming = new TH1F("h_pho_sumChargedHadronPt_NewPV_NoTiming","h_pho_sumChargedHadronPt_NewPV_NoTiming", 100,0,5);
  TH1F * h_pho_sumChargedHadronPt_NewPV_Timing50_TrkVtx = new TH1F("h_pho_sumChargedHadronPt_NewPV_Timing50_TrkVtx","h_pho_sumChargedHadronPt_NewPV_Timing50_TrkVtx", 100,0,5);
  TH1F * h_pho_sumChargedHadronPt_NewPV_Timing80_TrkVtx = new TH1F("h_pho_sumChargedHadronPt_NewPV_Timing80_TrkVtx","h_pho_sumChargedHadronPt_NewPV_Timing80_TrkVtx", 100,0,5);
  TH1F * h_pho_sumChargedHadronPt_NewPV_Timing120_TrkVtx = new TH1F("h_pho_sumChargedHadronPt_NewPV_Timing120_TrkVtx","h_pho_sumChargedHadronPt_NewPV_Timing120_TrkVtx", 100,0,5);

  TH1F * h_pho_sumChargedHadronPt_NewPV_Timing50_TrkPho = new TH1F("h_pho_sumChargedHadronPt_NewPV_Timing50_TrkPho","h_pho_sumChargedHadronPt_NewPV_Timing50_TrkPho", 100,0,5);
  TH1F * h_pho_sumChargedHadronPt_NewPV_Timing80_TrkPho = new TH1F("h_pho_sumChargedHadronPt_NewPV_Timing80_TrkPho","h_pho_sumChargedHadronPt_NewPV_Timing80_TrkPho", 100,0,5);
  TH1F * h_pho_sumChargedHadronPt_NewPV_Timing120_TrkPho = new TH1F("h_pho_sumChargedHadronPt_NewPV_Timing120_TrkPho","h_pho_sumChargedHadronPt_NewPV_Timing120_TrkPho", 100,0,5);


  for(int i=0;i<NEntries;i++)
 { 
	tree->GetEntry(i);
	for(int j=0;j<nPhotons;j++)
	{
        bool passCut = false;
	if(abs(pho_superClusterEta[j])<1.47 && phoSigmaIetaIeta[j]<SigIEtaIEtaCut_LWP_EB && pho_HoverE[j]<HoverECut_LWP_EB && pho_superClusterEnergy[j]/cosh(pho_superClusterEta[j])> 40.0 && pho_passEleVeto[j]==1) passCut = true;
	else if(abs(pho_superClusterEta[j])<2.5 && phoSigmaIetaIeta[j]<SigIEtaIEtaCut_LWP_EE && pho_HoverE[j]<HoverECut_LWP_EE && pho_superClusterEnergy[j]/cosh(pho_superClusterEta[j])> 40.0 && pho_passEleVeto[j]==1) passCut = true;
	if(!passCut) continue;

        N_Pho_Total_NoBin ++;		

	float pu_density =  140*TMath::Gaus(pvZ*10.0,beamSpotZ,beamSpotSigmaZ,1);
	//cout<<"event "<<i<<"  photon "<<j<<" pu_density "<<pu_density<<endl;	
	int pu_density_bin = int(pu_density*n_density/2.0);
 	if(pu_density_bin >= n_density) continue;

  	N_Pho_Total[pu_density_bin] ++;

        //if(pho_sumChargedHadronPt_NewPV_NoTiming[j]>-1.0) h_pho_sumChargedHadronPt_NewPV_NoTiming->Fill(pho_sumChargedHadronPt_NewPV_NoTiming[j]);	
        //if(pho_sumChargedHadronPt_NewPV_Timing50_TrkVtx[j]>-1.0) h_pho_sumChargedHadronPt_NewPV_Timing50_TrkVtx->Fill(pho_sumChargedHadronPt_NewPV_Timing50_TrkVtx[j]);	
        //if(pho_sumChargedHadronPt_NewPV_Timing80_TrkVtx[j]>-1.0) h_pho_sumChargedHadronPt_NewPV_Timing80_TrkVtx->Fill(pho_sumChargedHadronPt_NewPV_Timing80_TrkVtx[j]);	
        //if(pho_sumChargedHadronPt_NewPV_Timing120_TrkVtx[j]>-1.0) h_pho_sumChargedHadronPt_NewPV_Timing120_TrkVtx->Fill(pho_sumChargedHadronPt_NewPV_Timing120_TrkVtx[j]);	
	
 	if(pho_sumChargedHadronPt_NewPV_Timing50_TrkPho[j]>-1.0) h_pho_sumChargedHadronPt_NewPV_Timing50_TrkPho->Fill(pho_sumChargedHadronPt_NewPV_Timing50_TrkPho[j]);	
        if(pho_sumChargedHadronPt_NewPV_Timing80_TrkPho[j]>-1.0) h_pho_sumChargedHadronPt_NewPV_Timing80_TrkPho->Fill(pho_sumChargedHadronPt_NewPV_Timing80_TrkPho[j]);	
        if(pho_sumChargedHadronPt_NewPV_Timing120_TrkPho[j]>-1.0) h_pho_sumChargedHadronPt_NewPV_Timing120_TrkPho->Fill(pho_sumChargedHadronPt_NewPV_Timing120_TrkPho[j]);	
	

	if(abs(pho_superClusterEta[j])<1.47)
	{
	//if( pho_sumChargedHadronPt_NewPV_NoTiming[j] < chargeHadronIsoCut_LWP_EB) N_Pho_PassIso_NoTiming[pu_density_bin]++;
	//if( pho_sumChargedHadronPt_NewPV_Timing50_TrkVtx[j] < chargeHadronIsoCut_LWP_EB) N_Pho_PassIso_Timing50_TrkVtx[pu_density_bin]++;
	//if( pho_sumChargedHadronPt_NewPV_Timing80_TrkVtx[j] < chargeHadronIsoCut_LWP_EB) N_Pho_PassIso_Timing80_TrkVtx[pu_density_bin]++;
	//if( pho_sumChargedHadronPt_NewPV_Timing120_TrkVtx[j] < chargeHadronIsoCut_LWP_EB) N_Pho_PassIso_Timing120_TrkVtx[pu_density_bin]++;

	if( pho_sumChargedHadronPt_NewPV_Timing50_TrkPho[j] < chargeHadronIsoCut_LWP_EB) N_Pho_PassIso_Timing50_TrkPho[pu_density_bin]++;
	if( pho_sumChargedHadronPt_NewPV_Timing80_TrkPho[j] < chargeHadronIsoCut_LWP_EB) N_Pho_PassIso_Timing80_TrkPho[pu_density_bin]++;
	if( pho_sumChargedHadronPt_NewPV_Timing120_TrkPho[j] < chargeHadronIsoCut_LWP_EB) N_Pho_PassIso_Timing120_TrkPho[pu_density_bin]++;

	}
	else if(abs(pho_superClusterEta[j])<2.5)
	{
	//if( pho_sumChargedHadronPt_NewPV_NoTiming[j] < chargeHadronIsoCut_LWP_EE) N_Pho_PassIso_NoTiming[pu_density_bin]++;
	//if( pho_sumChargedHadronPt_NewPV_Timing50_TrkVtx[j] < chargeHadronIsoCut_LWP_EE) N_Pho_PassIso_Timing50_TrkVtx[pu_density_bin]++;
	//if( pho_sumChargedHadronPt_NewPV_Timing80_TrkVtx[j] < chargeHadronIsoCut_LWP_EE) N_Pho_PassIso_Timing80_TrkVtx[pu_density_bin]++;
	//if( pho_sumChargedHadronPt_NewPV_Timing120_TrkVtx[j] < chargeHadronIsoCut_LWP_EE) N_Pho_PassIso_Timing120_TrkVtx[pu_density_bin]++;

	if( pho_sumChargedHadronPt_NewPV_Timing50_TrkPho[j] < chargeHadronIsoCut_LWP_EE) N_Pho_PassIso_Timing50_TrkPho[pu_density_bin]++;
	if( pho_sumChargedHadronPt_NewPV_Timing80_TrkPho[j] < chargeHadronIsoCut_LWP_EE) N_Pho_PassIso_Timing80_TrkPho[pu_density_bin]++;
	if( pho_sumChargedHadronPt_NewPV_Timing120_TrkPho[j] < chargeHadronIsoCut_LWP_EE) N_Pho_PassIso_Timing120_TrkPho[pu_density_bin]++;
	}
	}
 }

//  cout<<"Total photons in sample that pass cuts: "<<N_Pho_Total_NoBin<<endl;

  for(int i=0;i<NEntries200;i++)
 { 
	tree200->GetEntry(i);
	for(int j=0;j<nPhotons;j++)
	{
        bool passCut = false;
	if(abs(pho_superClusterEta[j])<1.47 && phoSigmaIetaIeta[j]<SigIEtaIEtaCut_LWP_EB && pho_HoverE[j]<HoverECut_LWP_EB && pho_superClusterEnergy[j]/cosh(pho_superClusterEta[j])> 40.0 && pho_passEleVeto[j]==1) passCut = true;
	else if(abs(pho_superClusterEta[j])<2.5 && phoSigmaIetaIeta[j]<SigIEtaIEtaCut_LWP_EE && pho_HoverE[j]<HoverECut_LWP_EE && pho_superClusterEnergy[j]/cosh(pho_superClusterEta[j])> 40.0 && pho_passEleVeto[j]==1) passCut = true;
	if(!passCut) continue;

        N_Pho_Total_NoBin200 ++;		

	float pu_density =  200*TMath::Gaus(pvZ*10.0,beamSpotZ,beamSpotSigmaZ,1);
	//cout<<"event "<<i<<"  photon "<<j<<" pu_density "<<pu_density<<endl;	
	int pu_density_bin = int(pu_density*n_density/2.0);
 	if(pu_density_bin >= n_density) continue;

  	N_Pho_Total200[pu_density_bin] ++;

        if(pho_sumChargedHadronPt_NewPV_NoTiming[j]>-1.0) h_pho_sumChargedHadronPt_NewPV_NoTiming->Fill(pho_sumChargedHadronPt_NewPV_NoTiming[j]);	
        if(pho_sumChargedHadronPt_NewPV_Timing50_TrkVtx[j]>-1.0) h_pho_sumChargedHadronPt_NewPV_Timing50_TrkVtx->Fill(pho_sumChargedHadronPt_NewPV_Timing50_TrkVtx[j]);	
        if(pho_sumChargedHadronPt_NewPV_Timing80_TrkVtx[j]>-1.0) h_pho_sumChargedHadronPt_NewPV_Timing80_TrkVtx->Fill(pho_sumChargedHadronPt_NewPV_Timing80_TrkVtx[j]);	
        if(pho_sumChargedHadronPt_NewPV_Timing120_TrkVtx[j]>-1.0) h_pho_sumChargedHadronPt_NewPV_Timing120_TrkVtx->Fill(pho_sumChargedHadronPt_NewPV_Timing120_TrkVtx[j]);	
	

	if(abs(pho_superClusterEta[j])<1.47)
	{
	if( pho_sumChargedHadronPt_NewPV_NoTiming[j] < chargeHadronIsoCut_LWP_EB) N_Pho_PassIso_NoTiming[pu_density_bin]++;
	if( pho_sumChargedHadronPt_NewPV_Timing50_TrkVtx[j] < chargeHadronIsoCut_LWP_EB) N_Pho_PassIso_Timing50_TrkVtx[pu_density_bin]++;
	if( pho_sumChargedHadronPt_NewPV_Timing80_TrkVtx[j] < chargeHadronIsoCut_LWP_EB) N_Pho_PassIso_Timing80_TrkVtx[pu_density_bin]++;
	if( pho_sumChargedHadronPt_NewPV_Timing120_TrkVtx[j] < chargeHadronIsoCut_LWP_EB) N_Pho_PassIso_Timing120_TrkVtx[pu_density_bin]++;

	}
	else if(abs(pho_superClusterEta[j])<2.5)
	{
	if( pho_sumChargedHadronPt_NewPV_NoTiming[j] < chargeHadronIsoCut_LWP_EE) N_Pho_PassIso_NoTiming[pu_density_bin]++;
	if( pho_sumChargedHadronPt_NewPV_Timing50_TrkVtx[j] < chargeHadronIsoCut_LWP_EE) N_Pho_PassIso_Timing50_TrkVtx[pu_density_bin]++;
	if( pho_sumChargedHadronPt_NewPV_Timing80_TrkVtx[j] < chargeHadronIsoCut_LWP_EE) N_Pho_PassIso_Timing80_TrkVtx[pu_density_bin]++;
	if( pho_sumChargedHadronPt_NewPV_Timing120_TrkVtx[j] < chargeHadronIsoCut_LWP_EE) N_Pho_PassIso_Timing120_TrkVtx[pu_density_bin]++;

	}
	}
 }

 
  float pu_density[n_density];
  float ex[n_density] = {0.0};

  cout<<"Total number of photons (PU200): "<<N_Pho_Total_NoBin200<<endl;

  for(int i=0;i<n_density;i++)
  {
//	ex[i] = 0.5*2.0/n_density;
	pu_density[i] = 2.0*(i+0.5)/n_density;
	cout<<"bin: "<<i<<"  #pho = "<<N_Pho_Total200[i]<<"   #pho_passIso(NoTiming) = "<<N_Pho_PassIso_NoTiming[i]<<endl;
	if(N_Pho_Total[i]>0)
	{
//	IsoEff_NoTiming[i] =100.0* (N_Pho_PassIso_NoTiming[i]*1.0)/(N_Pho_Total[i]);
//	IsoEff_Timing50_TrkVtx[i] = 100.0* (N_Pho_PassIso_Timing50_TrkVtx[i]*1.0)/(N_Pho_Total[i]);
//	IsoEff_Timing80_TrkVtx[i] = 100.0* (N_Pho_PassIso_Timing80_TrkVtx[i]*1.0)/(N_Pho_Total[i]);
//	IsoEff_Timing120_TrkVtx[i] = 100.0* (N_Pho_PassIso_Timing120_TrkVtx[i]*1.0)/(N_Pho_Total[i]);

	IsoEff_Timing50_TrkPho[i] = 100.0* (N_Pho_PassIso_Timing50_TrkPho[i]*1.0)/(N_Pho_Total[i]);
	IsoEff_Timing80_TrkPho[i] = 100.0* (N_Pho_PassIso_Timing80_TrkPho[i]*1.0)/(N_Pho_Total[i]);
	IsoEff_Timing120_TrkPho[i] = 100.0* (N_Pho_PassIso_Timing120_TrkPho[i]*1.0)/(N_Pho_Total[i]);
	Err_IsoEff_Timing120_TrkPho[i] = IsoEff_Timing120_TrkPho[i]* sqrt(1.0/N_Pho_PassIso_Timing120_TrkPho[i] + 1.0/N_Pho_Total[i]);
	}
	if(N_Pho_Total200[i]>0)
	{
	IsoEff_NoTiming[i] =100.0* (N_Pho_PassIso_NoTiming[i]*1.0)/(N_Pho_Total200[i]);
	Err_IsoEff_NoTiming[i] = IsoEff_NoTiming[i]* sqrt(1.0/N_Pho_PassIso_NoTiming[i] + 1.0/N_Pho_Total200[i]);
	IsoEff_Timing50_TrkVtx[i] = 100.0* (N_Pho_PassIso_Timing50_TrkVtx[i]*1.0)/(N_Pho_Total200[i]);
	IsoEff_Timing80_TrkVtx[i] = 100.0* (N_Pho_PassIso_Timing80_TrkVtx[i]*1.0)/(N_Pho_Total200[i]);
	Err_IsoEff_Timing80_TrkVtx[i] = IsoEff_Timing80_TrkVtx[i]* sqrt(1.0/N_Pho_PassIso_Timing80_TrkVtx[i] + 1.0/N_Pho_Total200[i]);
	IsoEff_Timing120_TrkVtx[i] = 100.0* (N_Pho_PassIso_Timing120_TrkVtx[i]*1.0)/(N_Pho_Total200[i]);
	}

  }


  float MaxY = 0.0;
  float MinY = 999.9;

  TGraphErrors *gr_NoTiming = new TGraphErrors(n_density, pu_density, IsoEff_NoTiming,ex,Err_IsoEff_NoTiming);
  TGraphErrors *gr_Timing80_TrkVtx = new TGraphErrors(n_density, pu_density, IsoEff_Timing80_TrkVtx,ex, Err_IsoEff_Timing80_TrkVtx);
  TGraphErrors *gr_Timing120_TrkPho = new TGraphErrors(n_density, pu_density, IsoEff_Timing120_TrkPho,ex, Err_IsoEff_Timing120_TrkPho);

  TGraph *gr_Timing80_TrkPho = new TGraph(n_density, pu_density, IsoEff_Timing80_TrkPho);
  TGraph *gr_Timing120_TrkVtx = new TGraph(n_density, pu_density, IsoEff_Timing120_TrkVtx);


  gStyle->SetOptStat(0);


  TCanvas *cv = 0;
  TLegend *legend = 0;
  TLegend *legend_h = 0;
  bool firstdrawn = false;
  TLatex *tex = 0;
  TLine *line = 0;


  cv = new TCanvas("cv","cv", 800,800);
  cv->SetLeftMargin(0.15);
  cv->SetBottomMargin(0.12);

  legend_h = new TLegend(0.20,0.75,0.60,0.88, NULL,"brNDC");
  legend_h->SetTextSize(0.03);
  legend_h->SetBorderSize(0);
  legend_h->SetLineColor(1);
  legend_h->SetLineStyle(1);
  legend_h->SetLineWidth(1);
  legend_h->SetFillColor(0);
  legend_h->SetFillStyle(1001);

  legend_h->AddEntry(h_pho_sumChargedHadronPt_NewPV_NoTiming, "No Timing cut (PU200)");
  legend_h->AddEntry(h_pho_sumChargedHadronPt_NewPV_Timing80_TrkVtx, "Track-Vertex Timing 80ps cut (PU200)");
  //legend_h->AddEntry(h_pho_sumChargedHadronPt_NewPV_Timing120_TrkVtx, "Track-Vertex Timing 120ps cut (PU200)");
  //legend_h->AddEntry(h_pho_sumChargedHadronPt_NewPV_Timing80_TrkPho, "Track-Photon Timing 80ps cut (PU140)");
  legend_h->AddEntry(h_pho_sumChargedHadronPt_NewPV_Timing120_TrkPho, "Track-Photon Timing 120ps cut (PU140)");

 
  h_pho_sumChargedHadronPt_NewPV_NoTiming->Draw();
  h_pho_sumChargedHadronPt_NewPV_Timing80_TrkVtx->Draw("same");
 // h_pho_sumChargedHadronPt_NewPV_Timing120_TrkVtx->Draw("same");
 // h_pho_sumChargedHadronPt_NewPV_Timing80_TrkPho->Draw("same");
  h_pho_sumChargedHadronPt_NewPV_Timing120_TrkPho->Draw("same");
  legend_h->Draw();

  h_pho_sumChargedHadronPt_NewPV_NoTiming->SetLineColor(2);
  h_pho_sumChargedHadronPt_NewPV_Timing80_TrkVtx->SetLineColor(4);
  h_pho_sumChargedHadronPt_NewPV_Timing120_TrkPho->SetLineColor(3);

  h_pho_sumChargedHadronPt_NewPV_NoTiming->SetTitle("");
  h_pho_sumChargedHadronPt_NewPV_NoTiming->GetXaxis()->SetTitle("sum charged hadron Pt / GeV");
  h_pho_sumChargedHadronPt_NewPV_NoTiming->GetXaxis()->SetTitleSize(0.045);
  h_pho_sumChargedHadronPt_NewPV_NoTiming->GetXaxis()->SetTitleOffset(1.1);
  h_pho_sumChargedHadronPt_NewPV_NoTiming->GetYaxis()->SetTitle("Events");
  h_pho_sumChargedHadronPt_NewPV_NoTiming->GetYaxis()->SetTitleOffset(1.2);
  h_pho_sumChargedHadronPt_NewPV_NoTiming->GetYaxis()->SetTitleSize(0.045);
  h_pho_sumChargedHadronPt_NewPV_NoTiming->GetYaxis()->SetRangeUser(0,200);


  cv->SaveAs("~/www/sharebox/tomyself/Timing/h_chargedHadronPt.pdf");
  cv->SaveAs("~/www/sharebox/tomyself/Timing/h_chargedHadronPt.png");
  cv->SaveAs("~/www/sharebox/tomyself/Timing/h_chargedHadronPt.C");

  legend = new TLegend(0.20,0.75,0.60,0.88, NULL,"brNDC");
  legend->SetTextSize(0.03);
  legend->SetBorderSize(0);
  legend->SetLineColor(1);
  legend->SetLineStyle(1);
  legend->SetLineWidth(1);
  legend->SetFillColor(0);
  legend->SetFillStyle(1001);

  legend->AddEntry(gr_NoTiming, "No Timing cut (PU200)");
  legend->AddEntry(gr_Timing80_TrkVtx, "Track-Vertex Timing 80ps cut (PU200)");
  //legend->AddEntry(gr_Timing120_TrkVtx, "Track-Vertex Timing 120ps cut (PU200)");
  //legend->AddEntry(gr_Timing80_TrkPho, "Track-Photon Timing 80ps cut (PU140)");
  legend->AddEntry(gr_Timing120_TrkPho, "Track-Photon Timing 120ps cut (PU140)");


  gr_NoTiming->Draw("AP");
  gr_Timing80_TrkVtx->Draw("P");
  //gr_Timing120_TrkVtx->Draw("P");

  //gr_Timing80_TrkPho->Draw("P");
  gr_Timing120_TrkPho->Draw("P");
 
  legend->Draw();

  gr_NoTiming->SetFillStyle(0);
  gr_NoTiming->SetLineColor(kRed);
  gr_NoTiming->SetLineWidth(2);
  gr_NoTiming->SetMarkerColor(kRed);
  gr_NoTiming->SetMarkerStyle(20);
  gr_NoTiming->SetMarkerSize(2);

  gr_Timing80_TrkVtx->SetFillStyle(0);
  gr_Timing80_TrkVtx->SetLineColor(kBlue);
  gr_Timing80_TrkVtx->SetLineWidth(2);
  gr_Timing80_TrkVtx->SetMarkerColor(kBlue);
  gr_Timing80_TrkVtx->SetMarkerStyle(22);
  gr_Timing80_TrkVtx->SetMarkerSize(2);


  gr_Timing120_TrkPho->SetFillStyle(0);
  gr_Timing120_TrkPho->SetLineColor(kGreen);
  gr_Timing120_TrkPho->SetLineWidth(2);
  gr_Timing120_TrkPho->SetMarkerColor(kGreen);
  gr_Timing120_TrkPho->SetMarkerStyle(21);
  gr_Timing120_TrkPho->SetMarkerSize(2);


 
  gr_NoTiming->SetTitle("");
  gr_NoTiming->GetXaxis()->SetTitle("Linear Pileup Density (events / mm)");
  gr_NoTiming->GetXaxis()->SetTitleSize(0.045);
  gr_NoTiming->GetXaxis()->SetTitleOffset(1.1);
  gr_NoTiming->GetYaxis()->SetTitle("Photon Charged Isolation Eff (%)");
  gr_NoTiming->GetYaxis()->SetTitleOffset(1.2);
  gr_NoTiming->GetYaxis()->SetTitleSize(0.045);
  gr_NoTiming->GetYaxis()->SetRangeUser(60,105);
  gr_NoTiming->GetXaxis()->SetRangeUser(0,2.0);

  cv->SaveAs("~/www/sharebox/tomyself/Timing/PhotonIsolationEff.pdf");
  cv->SaveAs("~/www/sharebox/tomyself/Timing/PhotonIsolationEff.C");
  cv->SaveAs("~/www/sharebox/tomyself/Timing/PhotonIsolationEff.png");

}
Пример #4
0
int mumucross()
{
  TCanvas *c1 = new TCanvas("c1","di-mu cross section");
  TF1 *f1 = new TF1("f1",mumuxsdang,2,3.1,0);
  f1->GetXaxis()->SetTitle("Ecm (GeV)");
  f1->GetYaxis()->SetTitle("#sigma (nbar)");
  f1->Draw();
  
  TCanvas *c2 = new TCanvas("c2","BhaBha cross section");
  TF1 *f2 = new TF1("f2",bhabhaxsdang,2,3.1,0);
  f2->GetXaxis()->SetTitle("Ecm (GeV)");
  f2->GetYaxis()->SetTitle("#sigma (nbar)");
  f2->Draw();
  //return 0;

  double energys[22] = {
  2.0000, 2.0500, 2.1000, 2.1500, 2.1750,
  2.2000, 2.2324, 2.3094, 2.3864, 2.3960,
  2.5000, 2.6444, 2.6464, 2.7000, 2.8000,
  2.9000, 2.9500, 2.9810, 3.0000, 3.0200,
  3.0800, 2.125
  };
  double luminosity[22] = {
  10074,   3343,   12167,  2841,   10625,
  13699,  11856,   21089, 22549,   66869,
   1098,  33722,   34003,  1034,    1008,
 105253,  15942,   16071, 15881,   17290,
  126188, 108490
  };
  double mccross[22] = {
  22.3763923, 21.2939032, 20.4018357, 19.4157221, 18.9842334,
  18.5074456, 18.0584889, 16.9121088, 15.8285505, 15.6795155,
  14.3957219, 12.9117968, 12.9257851, 12.3962790, 11.5661025,
  10.7698318, 10.4156161, 10.2122681, 10.0576468, 9.9391192,
  9.5904453,  21.1564523
  };
  double nevt[22] = {
  5.0e5, 5.0e5, 5.0e5, 5.0e5, 5.0e5,
  5.0e5, 5.0e5, 5.0e5, 5.0e5, 1.07e6,
  5.0e5, 5.0e5, 5.0e5, 5.0e5, 5.0e5,
  1.13e6, 5.0e5, 5.0e5, 5.0e5, 5.0e5,
  1.16e6, 1.93e6
  };

  TFile *file = new TFile("output/output_bck.root");

  TH1D *hdata;
  TH1D *hmcmu;
  TH1D *hmcKK;
  gStyle->SetOptStat(0);
  for (int i=0 ;i<22;i++) {
    //double nmumu = luminosity[i]*f1->Eval(energys[i]);
    //cout<<nmumu<<"\t events at "<< energys[i] <<" GeV."<<endl;
    //double nee = luminosity[i]*f2->Eval(energys[i]);
    //cout<<nee<<"\t events at "<< energys[i] <<" GeV."<<endl;
    cout<<"ene "<<energys[i]<<", scale is "<< luminosity[i]/(nevt[i]/mccross[i])<<endl;
    //continue;
    char hname[100];
    // get data spectrum
    //sprintf(hname,"hp_KK_%d",(int)(energys[i]*10000+0.5));
    sprintf(hname,"hp_mcKK_%.4f",energys[i]);
    hdata = (TH1D*)file->Get(hname);
    hdata->SetFillColor(0);
    //hdata->SetTitle("momentum spectrum of data and di-#mu MC");
    hdata->SetTitle("");
    hdata->GetXaxis()->SetTitle("p (GeV/c)");
    hdata->GetYaxis()->SetTitle("Counts");
    // get dimu spectrum
    sprintf(hname,"hp_mcmumu_%.4f",energys[i]);
    hmcmu = (TH1D*)file->Get(hname);

    // get mc KK spectrum
    sprintf(hname,"hp_mcKK2_%.4f",energys[i]);
    hmcKK = (TH1D*)file->Get(hname);
    int binid;
    double maxdata = getMax(hdata,1,50,binid);
    double maxmcKK = getMax(hmcKK,1,50,binid);

    cout<< hdata <<"\t"<<hmcmu<<" ndata,nmcKK "<< maxdata<<" "<<maxmcKK<<endl;
    sprintf(hname,"Canvas_%02d",i+1);
    
    TCanvas *chp = new TCanvas(hname,"Background analysis");
    chp->SetMargin(0.15,0.1,0.15,0.1);
    hdata->SetLineColor(1);
    hdata->SetTitle("");
    hdata->GetXaxis()->SetNdivisions(505);
    hdata->GetXaxis()->SetTitleSize(0.05);
    hdata->GetXaxis()->SetLabelSize(0.05);
    hdata->GetYaxis()->SetNdivisions(505);
    hdata->GetYaxis()->SetTitleSize(0.05);
    hdata->GetYaxis()->SetLabelSize(0.05);
    hdata->GetYaxis()->SetTitleOffset(1.1);

    hdata->Draw("E");
    // scale dimu to data according luminosity
    hmcmu->Scale(luminosity[i]/(nevt[i]/mccross[i]));
    hmcmu->SetLineColor(2);
    hmcmu->SetMarkerColor(2);
    hmcmu->SetFillColor(0);
    hmcmu->Draw("same");
    
    // scale KK MC
    hmcKK->Scale((maxdata-hmcmu->GetBinContent(binid))/maxmcKK);
    hmcKK->SetLineColor(3);
    hmcKK->SetMarkerColor(3);
    hmcKK->SetFillColor(0);
    hmcKK->Draw("same");

    sprintf(hname,"%.4f GeV",energys[i]);
    TLegend* leg = new TLegend(0.4,0.55,0.6,0.85,hname);
    leg->AddEntry(hdata,"data");
    leg->AddEntry(hmcmu,"#mu^{+} #mu^{-} MC");
    leg->AddEntry(hmcKK,"K^{+} K^{-} MC");
    leg->SetBorderSize(0);
    leg->SetFillStyle(0);
    leg->Draw();
    sprintf(hname,"Canvas_%02d.pdf",i+1);
    chp->Print(hname);
    delete chp;
    
  }
  return 0;
}
Пример #5
0
//注意,主函数名称和文件名称要一样
int rootelectron(void)
{
    const double PI = 3.1415926535897932384626433832795;
    ///////////////////////%%%%%%输入参数%%%%%%%%%%%/////////////////////////////////////////////////////////////
    string filename="spectrum.root";                                                        //数据文件名称
    //root文件中tree的名称,需要和Geant4中的一致
    string treename="selectree";
    string branchname = "particledata";                                                 //root文件中branch的名称,需要和Geant4中的一致
    //    string treename[4]={"pelectree","pgamatree","selectree","sgamatree"};
    double Ebins=200;   //统计能谱的直方图中bin的个数,
    double Elow=-75.0;      //能谱的低能截止,单位keV
    double Eup=95.5555673; //能谱的高能能截止,单位keV
    double cbins[3] = {180,180,180};//统计角分布的三个直方图中bin的个数【x,y,z】
    double chlow[3] = {0,-90,0};//统计角分布的三个直方图的左边界【x,y,z】
    double chup[3] = {180,90,90};//统计角分布的三个直方图的左边界【x,y,z】
    double eneconv=1;//1000->MeV,1->keV将输入的能量转换单位

    ///////////////////////%%%%%%读入ROOT文件和Tree%%%%%%%%%%%/////////////////////////////////////////////////////////////
    gROOT->Reset();
    cout<<endl;
    cout << "\nStart\n" <<endl;
    TFile *myfile = new TFile(&filename[0]);    //新建对象,指向数据文件
if (!myfile)    {
        cout <<"no input file!" <<endl;
        return;
    }
    cout<<"Open file: "<<filename<<endl;
    TTree *mytree = (TTree *)myfile->Get(&treename[0]);//新建tree,用于处理数据
    if (!mytree)    {
        cout <<"no  tree named:  "<<treename<<endl;
        return;
    }
    cout << "input tree: "<<treename <<endl;

    //////////////////////////////%%设置新tree,用于数据处理%%%%%%/////////////////////////////////////%%%%%%%%%%%%%%%

    double data[4]={0};//保存从root文件中取出的数据。
    mytree->SetBranchAddress(&branchname[0],data);//设置新建的tree中branch的指向。
    //create two histograms
    double EEup=Eup/eneconv;
    double EElow=Elow/eneconv;
    double sintheta=0;
    TH1D * h1     = new TH1D("E","Energy Spectrum of source",Ebins,EElow,EEup);             //统计能谱
   // TH2D *h2Ex = new TH2D("h2Ex","h2 Energy vs x",cbins[0],chlow[0],chup[0],Ebins,EElow,EEup);//统计角分布,出射方向与X方向的夹角
   // TH2D *h2Ey = new TH2D("h2Ey","h2 Energy vs y",cbins[1],chlow[1],chup[1],Ebins,EElow,EEup);//统计角分布,出射方向与Y方向的夹角
    TH2D *h2Ez = new TH2D("h2Ez","h2 Energy vs z",cbins[2],chlow[2],chup[2],Ebins,EElow,EEup);//统计角分布,出射方向与Z方向的夹角(横坐标名,纵坐标名,横坐标bins,横坐标低截止,横坐标高截止,纵坐标bins,纵坐标低截止,纵坐标高截止)

    //read all entries and fill the histograms
    Long64_t nentries = mytree->GetEntries();   //注意:因为事例entry很多,所以需要Long64_t
    for (Long64_t i=0;i<nentries;i++) {
        mytree->GetEntry(i);
        //将处理数据的tree指向数据文件中的第i个事例,由于上面设置了的tree中branch的指针为变量data,所以处理data变量就处理了数据。
        h1->Fill(data[3]);                      //统计能谱
      //  sintheta= -sqrt(1-data[3]*data[3]);//data[3]=cos(theta)
       // h2Ex->Fill(acos(data[1]/sintheta)/PI*180,data[0]);
       // h2Ey->Fill(asin(data[2]/sintheta)/PI*180,data[0]);
        h2Ez->Fill(acos(data[1])/PI*180,data[0]);
    }

    ///////////////////////%%%%%%%%%Profile Histogram%%%%%%%/////////////////////////////////////
    TH1D* az;
  //  ax=h2Ex->ProjectionX();   //将二维散点图投影到1维就得到了一维的角分布,
  //  ay=h2Ey->ProjectionX();   //将二维散点图投影到1维就得到了一维的角分布,
    az=h2Ez->ProjectionX();   //将二维散点图投影到1维就得到了一维的角分布,

    ///////////////////////%%%%%%%%%Plot Histogram%%%%%%%/////////////////////////////////////
    //gROOT->SetStyle("Plain");   // uncomment to set a different style
    gStyle->SetPalette(1);        // use precomputed color palette 1
    gStyle->SetOptStat("ner");

 /*   TCanvas *c1 = new TCanvas();
    c1->cd();
    h2Ex->Draw("C");  //energy
    h2Ex->SetTitle("Energy Spectrum");     //散点图
    h2Ex->GetXaxis()->SetTitle("alpha(x)");
    h2Ex->GetYaxis()->SetTitle("Energy (keV)");
    h2Ex->GetXaxis()->CenterTitle();
    h2Ex->GetYaxis()->CenterTitle();
    gPad->Update();
    //    eneh->GetXaxis()->SetRangeUser(0, 1200);
    //    eneh->GetYaxis()->SetRangeUser(1e-8,1e-1);
    //        gPad->SetLogx();
    //            gPad->SetLogy();

    TCanvas *c2 = new TCanvas();
    c2->cd();
    h2Ey->Draw("C");  //energy
    h2Ey->SetTitle("Energy Spectrum");
    h2Ey->GetXaxis()->SetTitle("beta(y)");
    h2Ey->GetYaxis()->SetTitle("Energy (MeV)");
    h2Ey->GetXaxis()->CenterTitle();
    h2Ey->GetYaxis()->CenterTitle();
    gPad->Update();            */
   /*
    TCanvas *c3 = new TCanvas();           
    c3->cd();
    h2Ez->Draw("C");  //energy
    h2Ez->SetTitle("Energy Spectrum");
    h2Ez->GetXaxis()->SetTitle("gamma(z)");
    h2Ez->GetYaxis()->SetTitle("Energy (keV)");
    h2Ez->GetXaxis()->CenterTitle();
    h2Ez->GetYaxis()->CenterTitle();
    gPad->Update();

    TCanvas *c4 = new TCanvas();
    c4->cd();
    az->Draw("C");  //energy
    az->SetTitle("Augler  Distribution");//出射的次级粒子数目与出射角gamma的关系
    az->GetXaxis()->SetTitle("gamma(z)");
    az->GetYaxis()->SetTitle("Intensity)");
    az->GetXaxis()->CenterTitle();
    az->GetYaxis()->CenterTitle();
    gPad->Update();
*/
    TCanvas *c5 = new TCanvas();
    c5->cd();
    h1->Draw("C");  //Particle Distribution
    h1->SetTitle("Particle Distribution");   //IP板上电子沿长边的粒子数分布
    h1->GetXaxis()->SetTitle("X(mm)");
    h1->GetYaxis()->SetTitle("Intensity");
    h1->GetXaxis()->CenterTitle();
    h1->GetYaxis()->CenterTitle();
    gPad->Update();
    //    TGraphPolar * grP1 = new TGraphPolar(1000,r,theta);
    //    grP1->SetLineColor(2);
    //    grP1->Draw("AOL");
    //    gPad->Update();

    ///////////////////////%%%%%%%%%Write  Out Put File%%%%%%/////////////////////////////////////
    cout<<"write data file to disk"<<endl;
    // ofstream ofile(&nameofoutfile[0],ios_base::binary);//输出二进制文件
    ofstream ofile1("gamma-e-.txt",ios_base::out);//输出数据文件
    ofstream ofile2("angulargamma.txt",ios_base::out);
    //    第一列为能量,keV
    //    第二列为计数,个
 //  ofstream ofile2("Augler  Distribution(x).txt",ios_base::out);//输出数据文件
    //    第一列为出射角与X轴的夹角,keV
    //    第二列为计数,个
 //   ofstream ofile3("Augler  Distribution(y).txt",ios_base::out);//输出数据文件
 //   ofstream ofile4("Augler  Distribution(z).txt",ios_base::out);//输出数据文件
    //输出数据
    for(i=1;i<(Ebins+1);i++)    {
        double xxx=h1->GetXaxis()->GetBinCenter(i);
        double xxx1=(xxx+75.0)/0.8527778365 ;
        ofile1<<xxx1<<"\t"<< (h1->GetBinContent(i))<<"\t"<<endl;


    }                              //读取数据保存为文本形式
    
    for(j=1;j<(cbins[2]+1);j++)    {
		for(k=1;k<(Ebins+1);k++)   {
			ofile2<<h2Ez->GetXaxis()->GetBinCenter(j)<<"\t"<<h2Ez->GetYaxis()->GetBinCenter(k)<<"\t"<< h2Ez->GetBinContent(j,k)<<"\t"<<endl;
			}
	}

 /*   for(i=1;i<(cbins[0]+1);i++)    {
        ofile2<<ax->GetXaxis()->GetBinCenter(i)<<"\t"<< ax->GetBinContent(i)<<"\t"<<endl;
    }
    for(i=1;i<(cbins[1]+1);i++)    {
        ofile3<<ay->GetXaxis()->GetBinCenter(i)<<"\t"<< ay->GetBinContent(i)<<"\t"<<endl;
    }
    for(i=1;i<(cbins[2]+1);i++)    {
        ofile3<<az->GetXaxis()->GetBinCenter(i)<<"\t"<< az->GetBinContent(i)<<"\t"<<endl;
    }
    ofile1.close();//读写文件后需要关闭文件
 //   ofile2.close();
  //  ofile3.close();
 //   ofile4.close();      */

    cout<<"\nEnd!\n"<<endl;
    return 0;
}
Пример #6
0
void hackedbob(bool eff = false)
{
    using namespace std;
    
    double integral, preInt = 1.0;
    
    vector<pair<string,string> > fnames;
    vector<pair<string,string> > hnames;

    //TFile * tfile = new TFile("/home/ugrad/pastika/cms/HeavyNu/CMSSW_4_2_7/src/HeavyNu/AnalysisModules/analysis.root");
    TFile * tfile = new TFile("/local/cms/user/pastika/heavynu/heavynu_2011Bg_summer11_DYToLL_M-50_7TeV-sherpa_nov3.root");
    hnames.push_back(pair<string,string>("none","hNu%s/cut0_none/mWR"));
    hnames.push_back(pair<string,string>("LLJJ Pt","hNu%s/cut1_LLJJpt/mWR"));
    hnames.push_back(pair<string,string>("trig","hNu%s/cut2_TrigMatches/mWR"));
    hnames.push_back(pair<string,string>("vertex","hNu%s/cut3_Vertex/mWR"));
    hnames.push_back(pair<string,string>("mu1 pt","hNu%s/cut4_Mu1HighPt/mWR"));
    hnames.push_back(pair<string,string>("Mll","hNu%s/cut5_diLmass/mWR"));
    hnames.push_back(pair<string,string>("MWR","hNu%s/cut6_mWRmass/mWR"));

    fnames.push_back(pair<string,string>("nom Mu24", "Mu24"));
    fnames.push_back(pair<string,string>("nom Mu40", "Mu40"));
    //fnames.push_back(pair<string,string>("JES Hi Mu24", "Mu24jesHi"));
    //fnames.push_back(pair<string,string>("JES Lo Mu24", "Mu24jesLo"));
    //fnames.push_back(pair<string,string>("JES Hi Mu40", "Mu40jesHi"));
    //fnames.push_back(pair<string,string>("JES Lo Mu40", "Mu40jesLo"));
    //fnames.push_back(pair<string,string>("MES Hi Mu24", "Mu24mesHi"));
    //fnames.push_back(pair<string,string>("MES Lo Mu24", "Mu24mesLo"));
    //fnames.push_back(pair<string,string>("MES Hi Mu40", "Mu40mesHi"));
    //fnames.push_back(pair<string,string>("MES Lo Mu40", "Mu40mesLo"));
    //fnames.push_back(pair<string,string>("MuID Hi Mu24", "Mu24midHi"));
    //fnames.push_back(pair<string,string>("MuID Lo Mu24", "Mu24midLo"));
    //fnames.push_back(pair<string,string>("MuID Hi Mu40", "Mu40midHi"));
    //fnames.push_back(pair<string,string>("MuID Lo Mu40", "Mu40midLo"));
    //fnames.push_back(pair<string,string>("Trig Hi Mu24", "Mu24trigHi"));
    //fnames.push_back(pair<string,string>("Trig Lo Mu24", "Mu24trigLo"));
    //fnames.push_back(pair<string,string>("Trig Hi Mu40", "Mu40trigHi"));
    //fnames.push_back(pair<string,string>("Trig Lo Mu40", "Mu40trigLo"));
    fnames.push_back(pair<string,string>("Pileup Hi Mu24", "Mu24puHi"));
    fnames.push_back(pair<string,string>("Pileup Lo Mu24", "Mu24puLo"));
    fnames.push_back(pair<string,string>("Pileup Hi Mu40", "Mu40puHi"));
    fnames.push_back(pair<string,string>("Pileup Lo Mu40", "Mu40puLo"));
    
	printf("%8s", "cut");
	for(vector<pair<string,string> >::const_iterator i = fnames.begin(); i != fnames.end(); i++)
	{
		printf(eff?" & %15s        ":" & %15s", i->first.c_str());
	}
	printf(" \\\\ \\hline\n");
	for(vector<pair<string,string> >::const_iterator j = hnames.begin(); j != hnames.end(); j++)
	{
		printf("%8s", j->first.c_str());
		for(vector<pair<string,string> >::const_iterator i = fnames.begin(); i != fnames.end(); i++)
		{
		    char histname[256];
		    sprintf(histname, j->second.c_str(), i->second.c_str());
			TH1* h = (TH1*)tfile->Get(histname);
			integral = h->Integral(0, h->GetNbinsX()+1);
			
			if(integral > 10) printf((j == hnames.begin() && eff)?" & %15.0f        ":" & %15.0f", integral);
			else if(integral > 1) printf((j == hnames.begin() && eff)?" & %15.2f        ":" & %15.2f", integral);
			else printf((j == hnames.begin() && eff)?" & %15.3f        ":" & %15.3f", integral);
			//if(j != hnames.begin() && eff) 
			//{
			//	TH1* hpre = (TH1*)tfile->Get((j-1)->second.c_str());
			//	preInt = hpre->Integral(0, h->GetNbinsX()+1);
			//	printf("  (%4.2f)", integral/preInt);
			//}
		} 
		printf(" \\\\ \\hline\n");
	}
}
Пример #7
0
void plotMVAOutput( bool printgif = false ){

  //gROOT->ProcessLine(".x selection.h");

  //char* path    = "Trainings/H130_WWTo2L2Nu/output";
  //char* path    = "Trainings/H130_WWTo2L2Nu_WJetsToLNu/output";
  char* path    = "Trainings/H130_allbkg_4vars/output";

  //char* mvaname = "MVA_PDERS";
  //char* mvaname = "MVA_MLPBNN";
  //char* mvaname = "MVA_BDT";
  //char* mvaname = "LikelihoodPCA";

  vector<char*> mvanames;
  mvanames.push_back("BDT");
  mvanames.push_back("MLPBNN");
  const unsigned int nmva = mvanames.size();

  int rebin     = 10;
  int colors[]  = { 5 , 2 , 4 , 3 , 7 , 8 , 6 , 9 , 10};

  vector<char*> samples;
  samples.push_back("WWTo2L2Nu");
  samples.push_back("GluGluToWWTo4L");
  samples.push_back("WZ");
  samples.push_back("ZZ");
  samples.push_back("TTJets");
  samples.push_back("tW");
  samples.push_back("WJetsToLNu");
  samples.push_back("DY");
  const unsigned int nsamples = samples.size();

  char* higgssample = "Higgs130";
  //char* higgssample = "Higgs160";
  //char* higgssample = "Higgs200";

  TCanvas *can[nmva];


  for( unsigned int imva = 0 ; imva < nmva ; ++imva ){


    TFile*   file     = new TFile();
    TH1F*    hist     = new TH1F();
    TH1F*    bkghist  = new TH1F();
    THStack* bkgstack = new THStack("bkgstack","bkgstack");
    TLegend *leg      = new TLegend(0.3,0.7,0.5,0.9);
    leg->SetBorderSize(1);
    leg->SetFillColor(0);

    //loop over backgrounds
    for( unsigned int i = 0 ; i < nsamples ; ++i ){

      file = TFile::Open(Form("%s/%s.root",path,samples.at(i)));
      hist = cloneHist( (TH1F*) file->Get( Form("MVA_%s",mvanames.at(imva) ) ) );
   
      hist->SetFillColor(colors[i]);
    
      leg->AddEntry(hist,samples.at(i),"f");
  
      if( i == 0 ) bkghist = (TH1F*) hist->Clone();
      else         bkghist -> Add(hist);

      hist->Rebin( rebin );
      bkgstack->Add(hist);

    }

    //higgs sample
    file = TFile::Open(Form("%s/%s.root",path,higgssample));
    TH1F* higgshist = cloneHist( (TH1F*) file->Get( Form("MVA_%s",mvanames.at(imva) ) ) );
    higgshist->SetLineWidth(2);
    leg->AddEntry(higgshist,higgssample,"l");



    float bkg    = 0;
    float sig    = 0;
    float minbkg = 1.48;
    //float minbkg = 1.10;
    float cut    = 0.;

    for( int ibin = 1 ; ibin < bkghist->GetNbinsX() ; ibin++ ){

      bkg = bkghist->Integral( ibin , 10000 );
      sig = higgshist->Integral( ibin , 10000 );

      if( bkg < minbkg ){
        cut = bkghist->GetBinCenter(ibin);
        cout << endl;
        cout << "S/B       " << sig/bkg    << endl;
        cout << "Sig       " << sig        << endl;
        cout << "Bkg       " << bkg        << endl;
        cout << "cut value " << cut        << endl;
        break;
      }

    }

    float cutsig = sig;
    float cutbkg = bkg;
 
    float maxfom      = -1;
    float maxfom_sig  = -1;
    float maxfom_bkg  = -1;
    float cutval      = -1;
  

    for( int ibin = 1 ; ibin < bkghist->GetNbinsX() ; ibin++ ){

      bkg = bkghist->Integral( ibin , 10000 );
      sig = higgshist->Integral( ibin , 10000 );

      float fom = sig / sqrt( sig + bkg + pow( 0.35 * bkg , 2 ) );
    
      if( fom > maxfom ){
        maxfom  = fom;
        maxfom_sig = sig;
        maxfom_bkg = bkg;
        cutval  = bkghist->GetBinCenter(ibin);
      }

    }

    cout << endl;
    cout << "Max FOM   " << maxfom        << endl;
    cout << "Sig       " << maxfom_sig    << endl;
    cout << "Bkg       " << maxfom_bkg    << endl;
    cout << "cut value " << cutval        << endl;


    bkghist->Rebin( rebin );
    higgshist->Rebin( rebin );

    can[imva] = new TCanvas(Form("can_%i",imva),Form("can_%i",imva),800,600);
    can[imva]->cd();

    //gPad->SetLogy();
    bkghist->GetXaxis()->SetTitle(Form("%s output",mvanames.at(imva)));
    bkghist->Draw();
    bkgstack->Draw("same");
    higgshist->Scale(10.);
    higgshist->Draw("same");
    bkghist->Draw("axissame");
    //leg->Draw();

    TLatex *t = new TLatex();
    t->SetNDC();
    t->SetTextColor(2);
    t->DrawLatex(0.2,0.85,Form("FOM: %.2f",maxfom));
    t->SetTextColor(1);
    t->DrawLatex(0.2,0.80,Form("Sig: %.2f",maxfom_sig));
    t->DrawLatex(0.2,0.75,Form("Bkg: %.2f",maxfom_bkg));

    t->SetTextColor(4);
    t->DrawLatex(0.2,0.55,Form("S/B: %.2f",cutsig/cutbkg));
    t->SetTextColor(1);
    t->DrawLatex(0.2,0.50,Form("Sig: %.2f",cutsig));
    t->DrawLatex(0.2,0.45,Form("Bkg: %.2f",cutbkg));
  
    TLine  line;
    line.SetLineColor(2);
    line.DrawLine( cutval , bkghist->GetMinimum() , cutval , 1.05 * bkghist->GetMaximum() );
    line.SetLineColor(4);
    line.DrawLine( cut , bkghist->GetMinimum() , cut , 1.05 * bkghist->GetMaximum() );

    if( printgif ) can[imva]->Print(Form("plots/%s.gif",mvanames.at(imva)));
  }
}
Пример #8
0
float ComputeTestStat(TString wsfile, double mu_susy_sig_val) {

  gROOT->Reset();

  TFile* wstf = new TFile( wsfile ) ;

  RooWorkspace* ws = dynamic_cast<RooWorkspace*>( wstf->Get("ws") );
  ws->Print() ;
  
  ModelConfig* modelConfig = (ModelConfig*) ws->obj( "SbModel" ) ;
  
  modelConfig->Print() ;

  RooDataSet* rds = (RooDataSet*) ws->obj( "ra2b_observed_rds" ) ;
  
  rds->Print() ;
  rds->printMultiline(cout, 1, kTRUE, "") ;
  
  RooAbsPdf* likelihood = modelConfig->GetPdf() ;
  
  RooRealVar* rrv_mu_susy_sig = ws->var("mu_susy_all0lep") ;
  if ( rrv_mu_susy_sig == 0x0 ) {
    printf("\n\n\n *** can't find mu_susy_all0lep in workspace.  Quitting.\n\n\n") ;
    return ;
  } else {
    printf(" current value is : %8.3f\n", rrv_mu_susy_sig->getVal() ) ; cout << flush ;
    rrv_mu_susy_sig->setConstant(kFALSE) ;
  }

  /*
  // check the impact of varying the qcd normalization:

  RooRealVar *rrv_qcd_0lepLDP_ratioH1 = ws->var("qcd_0lepLDP_ratio_H1");
  RooRealVar *rrv_qcd_0lepLDP_ratioH2 = ws->var("qcd_0lepLDP_ratio_H2");
  RooRealVar *rrv_qcd_0lepLDP_ratioH3 = ws->var("qcd_0lepLDP_ratio_H3");
  
  rrv_qcd_0lepLDP_ratioH1->setVal(0.3);
  rrv_qcd_0lepLDP_ratioH2->setVal(0.3);
  rrv_qcd_0lepLDP_ratioH3->setVal(0.3);
  
  rrv_qcd_0lepLDP_ratioH1->setConstant(kTRUE);
  rrv_qcd_0lepLDP_ratioH2->setConstant(kTRUE);
  rrv_qcd_0lepLDP_ratioH3->setConstant(kTRUE);
  */
  
  printf("\n\n\n  ===== Doing a fit with SUSY component floating ====================\n\n") ;

  RooFitResult* fitResult = likelihood->fitTo( *rds, Save(true), PrintLevel(0) ) ;
  double logLikelihoodSusyFloat = fitResult->minNll() ;
  
  double logLikelihoodSusyFixed(0.) ;
  double testStatVal(-1.) ;
  if ( mu_susy_sig_val >= 0. ) {
    printf("\n\n\n  ===== Doing a fit with SUSY fixed ====================\n\n") ;
    printf(" fixing mu_susy_sig to %8.2f.\n", mu_susy_sig_val ) ;
    rrv_mu_susy_sig->setVal( mu_susy_sig_val ) ;
    rrv_mu_susy_sig->setConstant(kTRUE) ;
    
    fitResult = likelihood->fitTo( *rds, Save(true), PrintLevel(0) ) ;
    logLikelihoodSusyFixed = fitResult->minNll() ;
    testStatVal = 2.*(logLikelihoodSusyFixed - logLikelihoodSusyFloat) ;
    printf("\n\n\n ======= test statistic : -2 * ln (L_fixed / ln L_max) = %8.3f\n\n\n", testStatVal ) ;
  }


  return testStatVal ;

}
void makeStackedPlot_Jet1pT(){

  gROOT->SetStyle("Plain");
  gStyle->SetErrorX(0);

  TCanvas c1("c1","Stacked Histogram",10,10,700,800);
  TPad *p_2=new TPad("p_2", "p_2", 0, 0, 1, 0.35);
  TPad *p_1=new TPad("p_1", "p_1", 0, 0.35, 1, 1);
  p_1->SetBottomMargin(0.005);
  p_1->SetFillStyle(4000);
  p_1->SetFrameFillColor(0);
  p_2->SetFillStyle(4000);
  p_2->SetFrameFillColor(0);
  p_1->SetLogy();
  p_1->Draw();
  p_2->Draw();
  p_1->cd();

  double qcd_100_200 = 27540000.0*209.0/80093092.0;
  double qcd_200_300 = 1735000.0*209.0/18717349.0;
  double qcd_300_500 = 366800.0*209.0/20086103.0;
  double qcd_500_700 = 29370.0*209.0/19542847.0;
  double qcd_700_1000 = 6524.0*209.0/15011016.0;
  double qcd_1000_1500 = 1064.0*209.0/4963895.0;
  double qcd_1500_2000 = 121.5*209.0/3848411.0;
  double qcd_2000_inf =  25.4*209.0/1961774.0;

  THStack hs("hs","Jet pT > 50 GeV");

  TFile* file0 = TFile::Open("output_QCD_HT_100_200.root");
  TH1F *h0 = (TH1F*)file0->Get("general/jet_pT50");
  h0->Rebin(1);
  h0->GetXaxis()->SetRangeUser(0, 300);
  h0->Scale(qcd_100_200); 
  h0->SetFillColor(kYellow);
  h0->Draw();
  hs.Add(h0);

  TFile* file1 = TFile::Open("output_QCD_HT_200_300.root");
  TH1F *h1 = (TH1F*)file1->Get("general/jet_pT50");
  h1->Rebin(1);
  h1->GetXaxis()->SetRangeUser(0, 300);
  h1->Scale(qcd_200_300);
  h1->SetFillColor(kYellow);
  h1->Draw();
  hs.Add(h1);

  TFile* file2 = TFile::Open("output_QCD_HT_300_500.root");
  TH1F *h2 = (TH1F*)file2->Get("general/jet_pT50");
  h2->Rebin(1);
  h2->GetXaxis()->SetRangeUser(0, 300);
  h2->Scale(qcd_300_500);
  h2->SetFillColor(kYellow);
  h2->Draw();
  hs.Add(h2);

  TFile* file3 = TFile::Open("output_QCD_HT_500_700.root");
  TH1F *h3 = (TH1F*)file3->Get("general/jet_pT50");
  h3->Rebin(1);
  h3->GetXaxis()->SetRangeUser(0, 300);
  h3->Scale(qcd_500_700);
  h3->SetFillColor(kYellow);
  h3->Draw();
  hs.Add(h3);

  TFile* file4 = TFile::Open("output_QCD_HT_700_1000.root");
  TH1F *h4 = (TH1F*)file4->Get("general/jet_pT50");
  h4->Rebin(1);
  h4->GetXaxis()->SetRangeUser(0, 300);
  h4->Scale(qcd_700_1000);
  h4->SetFillColor(kYellow);
  h4->Draw();
  hs.Add(h4);

  TFile* file5 = TFile::Open("output_QCD_HT_1000_1500.root");
  TH1F *h5 = (TH1F*)file5->Get("general/jet_pT50");
  h5->Rebin(1);
  h5->GetXaxis()->SetRangeUser(0, 300);
  h5->Scale(qcd_1000_1500);
  h5->SetFillColor(kYellow);
  h5->Draw();
  hs.Add(h5);

  TFile* file6 = TFile::Open("output_QCD_HT_1500_2000.root");
  TH1F *h6 = (TH1F*)file6->Get("general/jet_pT50");
  h6->Rebin(1);
  h6->GetXaxis()->SetRangeUser(0, 300);
  h6->Scale(qcd_1500_2000);
  h6->SetFillColor(kYellow);
  h6->Draw();
  hs.Add(h6);

  TFile* file7 = TFile::Open("output_QCD_HT_2000_inf.root");
  TH1F *h7 = (TH1F*)file7->Get("general/jet_pT50");
  h7->Rebin(1);
  h7->GetXaxis()->SetRangeUser(0, 300);
  h7->Scale(qcd_2000_inf);
  h7->SetFillColor(kYellow);
  h7->Draw();
  hs.Add(h7);

  hs.Draw("HIST");
  hs.SetMaximum(100000000.0);
  hs.SetMinimum(0.1);
  hs.GetXaxis()->SetRangeUser(0, 300);
  hs.GetXaxis()->SetTitle("Jet pT > 50 (GeV)");
  hs.GetXaxis()->SetLabelSize(0.02);
  hs.GetXaxis()->SetTitleSize(0.02);

  TFile* data = TFile::Open("histo_data_All.root");
  TH1F *h8 = (TH1F*)data->Get("general/jet_pT50");
  h8->Rebin(1);
  h8->SetLineColor(kBlack);
  h8->SetMarkerStyle(20);
  h8->SetMarkerSize(1.0);
  h8->GetXaxis()->SetRangeUser(0, 300);
  h8->Draw("SAME E");

  c1.SaveAs("h_Stacked_Jet1pT.pdf");
  c1.SaveAs("h_Stacked_Jet1pT.png");

}
void Plot_AM_events_07Sep_Susy_1_auto() {
 TString cutNameBefore = Form("Data/");

 //                            cut_variable 
 TString cutNameAfter  = Form("_1_6_Tot_temp");

 gROOT->LoadMacro("PlotVHqqHggH.C+");
 gInterpreter->ExecuteMacro("LatinoStyle2.C");

 TCanvas* c1 = new TCanvas("events","events",500,600);
 TFile* f = new TFile("~/Cern/Code/VBF/qqHWW/AnalysisPackage_qqHWWlnulnu/out_test_Latinos_07Sep2012_2000_Run2012AB_8TeV_SUSY.root");


 PlotVHqqHggH* hs = new PlotVHqqHggH();

 hs->setLumi(5.063);
 hs->setLabel("event");
 hs->addLabel("    #sqrt{s} = 8 TeV");

 TString name;

 std::vector<int> vectColourBkg;        
 std::vector<double> vectSystBkg;       
 std::vector<std::string> vectNameBkg;  
 std::vector<TH1F*> vectTHBkg;          

 std::vector<int> vectColourSig;      
 std::vector<double> vectSystSig;       
 std::vector<std::string> vectNameSig;  
 std::vector<TH1F*> vectTHSig;          

 ///==== signal (begin) ====

 name = Form("%sT2tt-350-70%s",cutNameBefore.Data(),cutNameAfter.Data());
 vectTHSig.push_back ( (TH1F*) f->Get(name) );
 vectNameSig.push_back ("T2tt-stop350-lsp70");
 vectColourSig.push_back(6);

 name = Form("%sT2tt-500-70%s",cutNameBefore.Data(),cutNameAfter.Data());
 vectTHSig.push_back ( (TH1F*) f->Get(name) );
 vectNameSig.push_back ("T2tt-stop500-lsp70");
 vectColourSig.push_back(97);

 name = Form("%sT2tt-350-100%s",cutNameBefore.Data(),cutNameAfter.Data());
 vectTHSig.push_back ( (TH1F*) f->Get(name) );
 vectNameSig.push_back ("T2tt-stop350-lsp100");
 vectColourSig.push_back(70);

 name = Form("%sT2tt-500-100%s",cutNameBefore.Data(),cutNameAfter.Data());
 vectTHSig.push_back ( (TH1F*) f->Get(name) );
 vectNameSig.push_back ("T2tt-stop500-lsp100");
 vectColourSig.push_back(65);

 name = Form("%sT2tt-500-200%s",cutNameBefore.Data(),cutNameAfter.Data());
 vectTHSig.push_back ( (TH1F*) f->Get(name) );
 vectNameSig.push_back ("T2tt-stop500-lsp200");
 vectColourSig.push_back(5);

 name = Form("%sT2tt-200-0%s",cutNameBefore.Data(),cutNameAfter.Data());
 vectTHSig.push_back ( (TH1F*) f->Get(name) );
 vectNameSig.push_back ("T2tt-stop200-lsp0");
 vectColourSig.push_back(7);

 ///==== signal (end)  ====

 name = Form("%sDATA%s",cutNameBefore.Data(),cutNameAfter.Data());
 hs->setDataHist ((TH1F*)f->Get(name));



 hs->setBlindBinSx(0);
 hs->setBlindBinDx(0);

 hs->setCutSx(-999,">");
 hs->setCutDx(-999,"<");


 ///==== background (begin)  ====

 name = Form("%sH-125%s",cutNameBefore.Data(),cutNameAfter.Data());
 vectTHBkg.push_back ( (TH1F*) f->Get(name) );
 vectNameBkg.push_back ("H-125");
 vectColourBkg.push_back(633);
 vectSystBkg.push_back(0.00);


 name = Form("%sVV%s",cutNameBefore.Data(),cutNameAfter.Data());
 vectTHBkg.push_back ( (TH1F*) f->Get(name) );
 vectNameBkg.push_back ("WZ/ZZ");
 vectColourBkg.push_back(858);
 vectSystBkg.push_back(0.00);

 name = Form("%sWJets%s",cutNameBefore.Data(),cutNameAfter.Data());
 vectTHBkg.push_back ( (TH1F*) f->Get(name) );
 vectNameBkg.push_back ("W+jets");
 vectColourBkg.push_back(921);
 vectSystBkg.push_back(0.36);

 name = Form("%sTop%s",cutNameBefore.Data(),cutNameAfter.Data());
 vectTHBkg.push_back ( (TH1F*) f->Get(name) );
 vectNameBkg.push_back ("top");
 vectColourBkg.push_back(400);
 vectSystBkg.push_back(0.00);

 name = Form("%sZJets%s",cutNameBefore.Data(),cutNameAfter.Data());
 vectTHBkg.push_back ( (TH1F*) f->Get(name) );
 vectNameBkg.push_back ("DY+jets");
 vectColourBkg.push_back(418);
 vectSystBkg.push_back(0.00);
 name = Form("%sWW%s",cutNameBefore.Data(),cutNameAfter.Data());
 vectTHBkg.push_back ( (TH1F*) f->Get(name) );
 vectNameBkg.push_back ("WW");
 vectColourBkg.push_back(851);
 vectSystBkg.push_back(0.00);




 ///==== background (end)  ====


 hs->set_vectTHBkg     (vectTHBkg);      
 hs->set_vectNameBkg   (vectNameBkg);    
 hs->set_vectColourBkg (vectColourBkg);  
 hs->set_vectSystBkg   (vectSystBkg);    

 hs->set_vectTHSig     (vectTHSig);      
 hs->set_vectNameSig   (vectNameSig);    
 hs->set_vectColourSig (vectColourSig);  
 //  hs->set_vectSystSig   (vectSystSig);



 hs->set_addSignal (0); //---- stack signal = 1, no stack signal = 0  


 hs->prepare();


 ///==== draw ====



 hs->Draw(c1,1,true);

 c1->Print("07Sep_Susy_1/events.pdf");
 c1->Print("07Sep_Susy_1/events.png");

 c1->SetLogy();
 hs->Draw(c1,1,true);
 c1->Print("07Sep_Susy_1/events_logy.pdf");
 c1->Print("07Sep_Susy_1/events_logy.png");
}
Пример #11
0
void DrawStatUncertainty()
{
  TFile *f;
  TString ss("ExpStat_PYTHIA_canvasOutFile.root");
  f = new TFile(ss);
  TCanvas *c
  c = (TCanvas*)f->Get("_R92777");
  TString algoTitle;
  algoTitle = "k_{T} D = 0.6";
  TList *li = (TList*)gPad->GetListOfPrimitives();
  TObject *obj;
  
  TIter next(li);
  TH1D *histList[100], *htmp;
  int i,j,N;
  

  while ((obj = (TObject*)next()))
    {
      TString cname = obj->ClassName();
      TString name = obj->GetName();
      
      cout << cname <<" "<<name<<endl;    
      if (cname=="TH1D")
        {
          
          histList[N] = (TH1D*)gPad->FindObject(obj);
          histList[N]->SetFillColor(0);
          histList[N]->SetFillStyle(0);
          N++;
        } 
    }
  
  TCanvas *c = new TCanvas("c","c");
  gPad->SetLogx();
  gPad->SetLogy();
  //histList[0]->SetMaximum(1e+10);
  histList[0]->SetTitle("");
  histList[0]->GetXaxis()->SetTitle("jet p_{T} (GeV)");
  histList[0]->GetXaxis()->SetTitleFont(42);
  histList[0]->GetXaxis()->SetLabelFont(42);
  histList[0]->GetXaxis()->SetTitleSize(0.05);
  histList[0]->GetXaxis()->SetLabelSize(0.05);
  histList[0]->GetYaxis()->SetTitle("Relative Statistical Uncertainty");
  histList[0]->GetYaxis()->SetTitleFont(42);
  histList[0]->GetYaxis()->SetLabelFont(42);
  histList[0]->GetYaxis()->SetTitleSize(0.05);
  histList[0]->GetYaxis()->SetLabelSize(0.05);
  histList[0]->GetYaxis()->SetNdivisions(505);

  histList[0]->SetLineWidth(1);
  histList[0]->SetLineStyle(1);
  histList[0]->SetLineColor(1);
  histList[0]->SetMarkerColor(1);
  histList[0]->SetMarkerStyle(20);
  histList[0]->SetMarkerSize(1.2); 

  histList[1]->SetLineColor(2);
  histList[1]->SetMarkerColor(2);
  histList[1]->SetLineWidth(1);
  histList[1]->SetMarkerStyle(25);
  histList[1]->SetLineStyle(1);
  histList[1]->SetMarkerSize(1.2); 

  histList[2]->SetLineWidth(1);
  histList[2]->SetLineStyle(1);
  histList[2]->SetLineColor(4);
  histList[2]->SetMarkerColor(4);
  histList[2]->SetMarkerStyle(22);
  histList[2]->SetMarkerSize(1.2); 

  histList[0]->Draw("P");
  histList[1]->Draw("sameP");
  histList[2]->Draw("sameP");

  TLegend *leg = new TLegend(0.47,0.2,0.92,0.35);
  leg->SetTextFont(42);
  leg->AddEntry(histList[0],"|y| < 0.55","P");
  leg->AddEntry(histList[1],"1.10 < |y| < 1.70","P");
  leg->AddEntry(histList[2],"1.70 < |y| < 2.50","P");
  leg->SetFillColor(0);
  leg->SetBorderSize(0);
  leg->Draw();

  TPaveText *pave3 = new TPaveText(0.2,0.65,0.45,0.9,"NDC");
  pave3->SetTextFont(42);
  pave3->AddText("CMS preliminary");
  pave3->AddText(algoTitle);
  pave3->AddText("#sqrt{s} = 10 TeV");
  pave3->AddText("");
  pave3->AddText("#int L dt = 10 pb^{-1}");
  pave3->SetFillColor(0);
  pave3->SetBorderSize(0);
  pave3->Draw();

  c->Print("KT6_StatUncertainty.eps");
  
}
Пример #12
0
int Ana(const char *filename, const char* outdir, TFile *fileout)
{
  //TFile *file = new TFile("mc_KPI_22324.root");
  TFile *file;
  if (filename==0) file= new TFile("KK_22324.root");
  else file = new TFile(filename);
  std::cout<<"File name is "<<file->GetName()<<std::endl;
  if (file==0) return -1;
  TTree *tree = (TTree*)file->Get("TwoProng");
  if (tree==0) return -2;

  double ene[22];
  double pcut[22];
  double epcut[22];
  double thecut[22];
  double m_pcut;
  double m_epcut;
  double m_thecut;
  ifstream cutin("cutpar");
  char line[1000];
  if (cutin.is_open()) cutin.getline(line,1000);
  int iene=0;
  // set E/p and p cut, mark: set cut
  while (!cutin.eof()){
    cutin.getline(line,1000);
    istringstream iss;
    iss.str(line);
    iss>>ene[iene]>>pcut[iene]>>epcut[iene];
    iene++;
    if (iene==22) break;
  }
  for (int i=0;i<22;i++) epcut[i] = 1.64295 - 0.629622*ene[i] + 0.104755 *pow(ene[i],2);
  //for (int i=0;i<21;i++) thecut[i] = 173.946 + 1.74736*ene[i];
  //for (int i=0;i<22;i++) thecut[i] = 179;

  double kappx,kappy,kappz,kampx,kampy,kampz;
  int nneu;
  int run;
  int idxmc;
  int pdgid[100];
  int motheridx[100];
  int emcstatusInt;
  short emcstatusShort;
  double emctrk1;
  double emctrk2;
  double epratio1;
  double epratio2;
  int ntof1;
  int ntof2;
  int tofl1[5];
  int tofl2[5];
  double tof1[5];
  double tof2[5];
  tree->SetBranchAddress("run",&run);
  tree->SetBranchAddress("indexmc",&idxmc);
  tree->SetBranchAddress("pdgid",pdgid);
  tree->SetBranchAddress("motheridx",motheridx);
  tree->SetBranchAddress("kappx",&kappx);
  tree->SetBranchAddress("kappy",&kappy);
  tree->SetBranchAddress("kappz",&kappz);
  tree->SetBranchAddress("kampx",&kampx);
  tree->SetBranchAddress("kampy",&kampy);
  tree->SetBranchAddress("kampz",&kampz);
  //tree->SetBranchAddress("costheta",&costheta);
  tree->SetBranchAddress("nneu",&nneu);
  if (strncmp(tree->GetBranch("emcstatus")->GetLeaf("emcstatus")->GetTypeName(),"Short_t",7)==0)
  	tree->SetBranchAddress("emcstatus",&emcstatusShort);
  else 
  	tree->SetBranchAddress("emcstatus",&emcstatusInt);
  tree->SetBranchAddress("epratio1",&epratio1);
  tree->SetBranchAddress("epratio2",&epratio2);
  tree->SetBranchAddress("emctrk1",&emctrk1);
  tree->SetBranchAddress("emctrk2",&emctrk2);
  tree->SetBranchAddress("ntof1",&ntof1);
  tree->SetBranchAddress("toflayer1",tofl1);
  tree->SetBranchAddress("tof1",tof1);
  tree->SetBranchAddress("ntof2",&ntof2);
  tree->SetBranchAddress("toflayer2",tofl2);
  tree->SetBranchAddress("tof2",tof2);
  double pi = TMath::Pi();
  double mka = 0.493677;
  //double mka = 0.13957;
  //double mka = 0.1057;
  

  tree->GetEntry(0);
  double Ebeam = GetEnergy(run);
  if (Ebeam<1.0) Ebeam = getEne(filename);
  //Ebeam = 3.08;
  for (int iene=0;iene<22;iene++){
    if (fabs(Ebeam-ene[iene])<1e-4) {
      m_pcut = pcut[iene];
      m_epcut = epcut[iene];
      m_thecut = thecut[iene];
      break;
    }
  }
  //m_epcut = m_epcut +0.05; // change E/p to determine uncertainty from this cut
  //m_thecut = 179+0.2; // uncertainty from theta cut
  //m_pcut = 0.956409;
  m_thecut = 179;
  m_epcut = 1.64295 - 0.629622*Ebeam + 0.104755 *pow(Ebeam,2);
  double m_tofcut = 3;
  //m_tofcut = 3-1;
  std::cout<<"pcut "<<m_pcut<<", E/p cut "<<m_epcut<<std::endl;


//std::cout<<"output file name is "<<name<<std::endl;
  //TFile *fileout = new TFile(name,"recreate");
  const char *pureName = getPureName2(filename);
  std::cout<<"Pure Name: "<< pureName <<std::endl;
  char name1[1000];
  //sprintf(name1,"output/%s.root",pureName);
//sprintf(name1,"output/%s.root",pureName);
//TFile *dir = new TFile(name1,"recreate");
//TTree *vars = new TTree("vars","vars");

  fileout->cd();
  TDirectory *dir = fileout->GetDirectory(pureName);
  if (dir==0) dir = fileout->mkdir(pureName);;
  dir->cd();
  TTree *vars = new TTree("vars","vars");

  TLorentzVector kap,kam;
  double mass;

  double totp, costheta1, costheta2;
  double costheta, theta;
  double p1,p2;
  double pt1,pt2;
  double tof11=-1000,tof21=-1000;
  int tofid;
  int isrtag=0;
  int tof1tag=0;
  int tof2tag=0;
  int emctag=0;
  double dtof;
  double eop1,eop2;
//vars->Branch("run",&run,"run/I");
//vars->Branch("indexmc",&idxmc,"indexmc/I");
//vars->Branch("pdgid",pdgid,"pdgid[indexmc]/I");
//vars->Branch("motheridx",motheridx,"motheridx[indexmc]/I");
//vars->Branch("costheta",&costheta,"costheta/D");
//vars->Branch("theta",&theta,"theta/D");
  vars->Branch("costheta1",&costheta1,"costheta1/D");
  vars->Branch("costheta2",&costheta2,"costheta2/D");
  vars->Branch("p1",&p1,"p1/D");
  vars->Branch("p2",&p2,"p2/D");
  vars->Branch("pt1",&pt1,"pt1/D");
  vars->Branch("pt2",&pt2,"pt2/D");
  vars->Branch("dtof",&dtof,"dtof/D");
  vars->Branch("eop1",&eop1,"eop1/D");
  vars->Branch("eop2",&eop2,"eop2/D");
  
  //fileout->cd();

  int nentries = tree->GetEntries();
  double pexp = sqrt(pow(Ebeam/2,2)-pow(mka,2));
  std::cout<<"Total entries is " << nentries << std::endl;
  std::cout<<"Beam energy is " << Ebeam << std::endl;
  std::cout<<"Expected K momentum is " << pexp << std::endl;
  int count0=0,count1=0,count2=0,count3=0;
  int count[10]={0};
  int tagmc=0;

  for (int ien=0;ien<nentries;ien++){
    tree->GetEntry(ien);
    
    isrtag = 0;
    for (int j=0;j<idxmc;j++){
      if (pdgid[j] == 22 && motheridx[j]==j) { tagmc++; isrtag=1;}
    }
    if (emcstatusShort!=0x3 && emcstatusInt!=0x3) continue;
    if (ntof1<1) continue;
    if (ntof2<1) continue;
    for (int i=0;i<ntof1;i++){
      if (tofl1[i]==1) tof11=tof1[i];
    }
    for (int i=0;i<ntof2;i++){
      if (tofl2[i]==1) tof21=tof2[i];
    }
 
    count0++;

    kap.SetVectMag(TVector3(kappx,kappy,kappz),mka);
    kam.SetVectMag(TVector3(kampx,kampy,kampz),mka);
    
    // angular information in lab coordinate
    costheta1 = kap.CosTheta();
    costheta2 = kam.CosTheta();
    
    // momentum information in cms coordinalte
    pt1 = kap.Perp();
    pt2 = kam.Perp();
    kap.Boost(-0.011,0,0);
    kam.Boost(-0.011,0,0);
    costheta = kap.Vect().Dot(kam.Vect())/(kap.Vect().Mag()*kam.Vect().Mag());
    theta = kap.Vect().Angle(kam.Vect())/TMath::Pi()*180.;
    mass = (kap+kam).M();
    totp = (kap+kam).Rho();
    p1 = kap.Rho();
    p2 = kam.Rho();
    dtof = tof11 - tof21;
    eop1 = epratio1;
    eop2 = epratio2;

    //vars->Fill();

    if (fabs(costheta1)<0.93 && costheta1 < 0.8 ) { count[4]++;
    if (fabs(costheta2)<0.93 && costheta2 > -0.8){ count[5]++;
    if (theta>m_thecut)
    { count[2]++;
    //if (epratio1<m_epcut)
    { count[0]++;
      //if (epratio2<m_epcut)
      { count[1]++;
        //if (fabs(tof11-tof21)<m_tofcut)
        if (p1<m_pcut && p2<m_pcut)
        {
          count3++;
          vars->Fill();
        //if (p2<m_pcut) {/*datasel2->Fill();*/ count2++; // p2 dis
        //  //datasel1->Fill();
        //  vars->Fill();
        //}
        }
      }
    }
    }
    
    }
    }
  }
  dir->Write();

  ofstream cutflow("cutflow2",std::ios::app);
  //ofstream cutflow("cutflow_cmp665andp01",std::ios::app);
  cutflow<<filename<<std::endl;
  //std::cout<<"data selction 2 size is "<<datasel2->GetEntries()<<" "<<count2<<std::endl;
  cutflow<<"Initial size      :"<<nentries<<std::endl;
  cutflow<<"Tagged ISR evt    :"<< tagmc  <<std::endl;
  cutflow<<"Tagged no ISR evt :"<< nentries - tagmc  <<std::endl;
  cutflow<<"Valid tof and emc :"<<count0<<std::endl;
  cutflow<<"After cos1<0.8    :"<<count[4]<<std::endl;
  cutflow<<"After cos2>-0.8   :"<<count[5]<<std::endl;
  cutflow<<"After theta cut   :"<<count[2]<<std::endl;
  cutflow<<"After ep1         :"<<count[0]<<std::endl;
  cutflow<<"After ep2         :"<<count[1]<<std::endl;
  //cutflow<<"After totp<0.05   :"<<count[3]<<std::endl;
  cutflow<<"After dtof<3      :"<<count3<<std::endl;
  //cutflow<<"p1-exp<0.08 for p1:"<<count1<<std::endl;
  cutflow<<"p1-exp<3 sigma    :"<<count2<<std::endl;

  return 0;
 
}
Пример #13
0
void Draweff(){
	int sth=0, Gth=0;
	TFile *f = TFile::Open(outG);
	if(sth==0){TString dirname = "std";}
        else if(sth==1){TString dirname ="Gri055";}
        else {TString dirname ="Gri101";}
	gStyle->SetErrorX(0);
	TString name;
        TObjString* dataname = (TObjString*)f->Get(Form("dataname"));
        TObjString* histoname = (TObjString*)f->Get(Form("histoname"));
        if(Gth==0)
                name = "G0";
        else if(Gth<nGlau)
                name = Form("Glau_%d",Gth);
        else
                name = Form("bin_%d",Gth-nGlau+1);
        TObjString* Glaubername = (TObjString*)f->Get(Form("%s/%s/Glaubername",dirname.Data(),name.Data()));
        TVectorD* xmin = (TVectorD*)f->Get(Form("%s/%s/xmin",dirname.Data(),name.Data()));
        TVectorD* xmax = (TVectorD*)f->Get(Form("%s/%s/xmax",dirname.Data(),name.Data()));
        TVectorD* mubest = (TVectorD*)f->Get(Form("%s/%s/mubest",dirname.Data(),name.Data()));
        TVectorD* kbest = (TVectorD*)f->Get(Form("%s/%s/kbest",dirname.Data(),name.Data()));
        TVectorD* Ndf = (TVectorD*)f->Get(Form("%s/%s/Ndf",dirname.Data(),name.Data()));
        TVectorD* chis = (TVectorD*)f->Get(Form("%s/%s/chis",dirname.Data(),name.Data()));
	TVectorD *kpoint = (TVectorD*)f->Get(Form("%s/%s/kpoint",dirname.Data(),name.Data()));
	TFile *fdata = TFile::Open(dataname->GetString());
	TH1D *histo_obs = (TH1D*)fdata->Get(histoname->GetString());
	histo_obs->Sumw2();
	TFile *fGlauber = TFile::Open(Glaubername->GetString());
        int binnum = histo_obs->GetNbinsX();
        double Minx = histo_obs->GetXaxis()->GetXmin();
        double Maxx = histo_obs->GetXaxis()->GetXmax();
	double binsize = (Double_t)(Maxx-Minx)/binnum;
        int xbinmin=(int)(((*xmin)[0]-Minx)/binsize);
        int xbinmax=(int)(((*xmax)[0]-Minx)/binsize);
	TH1D *histo_exp = new TH1D("histo_exp","Simulated distribution;Multiplicity;Event Fraction",binnum,Minx,Maxx);
	histo_exp->Sumw2();
	Int_t ibin;
		
	TH1D *histo_obs_norm = (TH1D*)histo_obs->Clone();
        histo_obs_norm->Scale(1/histo_obs->Integral(xbinmin,xbinmax));

	TF1 *NBD_fun = new 
	TF1("NBD_fun","[0]*TMath::Gamma(x+[1])/(TMath::Gamma(x+1)*TMath::Gamma([1]))*TMath::Power([2]/[1],x)/TMath::Power([2]/[1]+1,x+[1])",0,100);
	NBD_fun->SetParameter(0,1);	//[0]: Normalized constant
	NBD_fun->SetParameter(1,(*kbest)[0]);	//[1]: k value
	NBD_fun->SetParameter(2,(*mubest)[0]);	//[2]: mu value
		
	TTree *t = (TTree*) fGlauber->Get("nt_Pb_Pb");
	Long_t Nevent;

	Nevent = (Long_t) t->GetEntries();

	Long_t Ev;	Int_t Bino;	Double_t Para, Bi_Para, Mult;
	Float_t Ncoll;
	t->SetBranchAddress("Ncoll",&Ncoll);

	for(Ev=0; Ev<Nevent; Ev++){
		if(Ev%100000==0)	 cout<<"Have run "<<Ev<<" events"<<endl;
		t->GetEntry(Ev);
		Para = 0; //make sure that Para doesn't accumulate through loops
		for(Bino=0; Bino<Ncoll; Bino++){
                         Bi_Para = NBD_fun->GetRandom();
                         Para += Bi_Para;
		}	
		histo_exp->Fill(Para);
	}
	Double_t SumEvent, scale;
	SumEvent = histo_exp->Integral(xbinmin,xbinmax);
	scale = 1/SumEvent;
	TH1D *histo_exp_norm = (TH1D*) histo_exp->Clone();
	histo_exp_norm->Scale(scale);

	TCanvas *c1 = new TCanvas();
        gStyle->SetOptStat(kFALSE);

	double hfbin[]={0,1,2,3,4,6,8,10,13,16,20,25,30,40,55,70,90};
	int nhfbin = 16;
	rehisto_obs_norm = (TH1D*)histo_obs_norm->Rebin(nhfbin,"rehisto_obs_norm",hfbin);
	normalizeByBinWidth(rehisto_obs_norm);
	rehisto_exp_norm = (TH1D*)histo_exp_norm->Rebin(nhfbin,"rehisto_exp_norm",hfbin);
	normalizeByBinWidth(rehisto_exp_norm);
	TH1D* ratio = (TH1D*)rehisto_obs_norm->Clone("ratio");
	ratio->Divide(rehisto_exp_norm);
        ratio->SetMaximum(1.2);
        ratio->SetMinimum(0);
        ratio->GetXaxis()->SetTitle("HF #Sigma E_{T}");
       	ratio->GetYaxis()->SetTitle("ratio");
/*
Пример #14
0
void make_rValues(std::string model, int m1, int m2){

  //setup file to hold r-values if it doesn't already exist
  TFile *f_temp = new TFile(Form("r-values_%s.root", model.c_str()), "NEW");
  if(f_temp){
    // default case: T5ZZ binning
    int m1_max = 2125;
    int m1_min = 775;
    int m2_max = 2025;
    int m2_min = 75;
    int m1_div = 50;
    int m2_div = 50;

    if (model.find("TChiWZ") != std::string::npos) {
      m1_max = 712.5;
      m1_min = 87.5;
      m2_max = 305;
      m2_min = -5;
      m1_div = 25;
      m2_div = 10;
    }

    int nbinsx = (m1_max - m1_min)/m1_div;
    int nbinsy = (m2_max - m2_min)/m2_div;
    
    TH2F *hExp   = new TH2F("hExp",   "hExp"  , nbinsx, m1_min, m1_max, nbinsy, m2_min, m2_max);
    TH2F *hObs   = new TH2F("hObs",   "hObs"  , nbinsx, m1_min, m1_max, nbinsy, m2_min, m2_max);
    TH2F *hExp1m = new TH2F("hExp1m", "hExp1m", nbinsx, m1_min, m1_max, nbinsy, m2_min, m2_max);
    TH2F *hExp2m = new TH2F("hExp2m", "hExp2m", nbinsx, m1_min, m1_max, nbinsy, m2_min, m2_max);
    TH2F *hExp1p = new TH2F("hExp1p", "hExp1p", nbinsx, m1_min, m1_max, nbinsy, m2_min, m2_max);
    TH2F *hExp2p = new TH2F("hExp2p", "hExp2p", nbinsx, m1_min, m1_max, nbinsy, m2_min, m2_max);
    //TH2F *hSig   = new TH2F("hSig",   "hSig"  , nbinsx, m1_min, m1_max, nbinsy, m2_min, m2_max);

    f_temp->Write();
    f_temp->Close();
  }
  delete f_temp;

  //This file is created earlier by running combine
  TFile *limit_file = new TFile(Form("limit_%s_%d_%d.root", model.c_str(), m1, m2), "READ");
  TTree *limit_tree = (TTree*)limit_file->Get("limit");

  //This file is created earlier by running combine
  //TFile *significance_file = new TFile(Form("significance_%s_%d_%d.root", model.c_str(), m1, m2), "READ");
  //TTree *significance_tree = (TTree*)significance_file->Get("limit");

  //This file will hold 2d histograms with limit r-values and discovery significance
  TFile *f = new TFile(Form("r-values_%s.root", model.c_str()), "UPDATE");

  double value = -1.0;
  limit_tree->SetBranchAddress("limit", &value);

  double limit   = -1.0; //observed limit
  double rm2s    = -1.0; //expected - 2 sigma
  double rm1s    = -1.0; //expected - 1 sigma
  double rmedian = -1.0; //expected limit
  double rp1s    = -1.0; //expected + 1 sigma
  double rp2s    = -1.0; //expected + 2 sigma

  for(int i=0; i< 6; i++){
    limit_tree->GetEntry(i);
    if(i==0)      rm2s    = value;
    else if(i==1) rm1s    = value;
    else if(i==2) rmedian = value;
    else if(i==3) rp1s    = value;
    else if(i==4) rp2s    = value;
    else if(i==5) limit   = value;
  }

  //double sig = -1.0;
  //significance_tree->SetBranchAddress("limit", &sig);
  //significance_tree->GetEntry(0);

  delete limit_tree;
  limit_file->Close();
  delete limit_file;

  //delete significance_tree;
  //significance_file->Close();
  //delete significance_file;

  // // not sure what this is protecting against..
  // if( value > 21263 ) exit(0);
  
  f->cd();

  TH2F *hExp   = (TH2F*)f->Get("hExp");
  TH2F *hObs   = (TH2F*)f->Get("hObs");
  TH2F *hExp1m = (TH2F*)f->Get("hExp1m");
  TH2F *hExp2m = (TH2F*)f->Get("hExp2m");
  TH2F *hExp1p = (TH2F*)f->Get("hExp1p");
  TH2F *hExp2p = (TH2F*)f->Get("hExp2p");
  //TH2F *hSig   = (TH2F*)f->Get("hSig");

  Fill2d(hExp  , rmedian, m1, m2);    
  Fill2d(hObs  , limit  , m1, m2);  
  Fill2d(hExp1m, rm1s   , m1, m2);  
  Fill2d(hExp2m, rm2s   , m1, m2);  
  Fill2d(hExp1p, rp1s   , m1, m2);  
  Fill2d(hExp2p, rp2s   , m1, m2);  
  //Fill2d(hSig  , sig    , m1, m2);  

  hExp  ->Write("",TObject::kOverwrite);
  hObs  ->Write("",TObject::kOverwrite);
  hExp1m->Write("",TObject::kOverwrite);
  hExp2m->Write("",TObject::kOverwrite);
  hExp1p->Write("",TObject::kOverwrite);
  hExp2p->Write("",TObject::kOverwrite);
  //hSig  ->Write("",TObject::kOverwrite);
  f->Close();
  delete f;

}
Пример #15
0
void M2gHist( UInt_t chan)
{
	UInt_t cbin;
	Double_t factor;
	TString name;

	TFile* file;

	cbin = chan+1;

	// Target FULL
	// Prompt
	TH2D *hP = (TH3D*)full.Get( "THR_M2gTaggP_v_TChanM2gP");
	hP->GetXaxis()->SetRange( cbin, cbin);
	TH1D *hPf_y = hP->ProjectionY( "M2gP");

	// Random
	TH3D *hR = (TH3D*)full.Get( "THR_M2gTaggR_v_TChanM2gR");
	hR->GetXaxis()->SetRange( cbin, cbin);
	TH1D *hRf_y = hR->ProjectionY( "M2gR");
	hRf_y->Scale( 0.5);

	// Subtracted
	hSf = (TH1D*) hPf_y->Clone( "FullSubt");
	hSf->Sumw2();
	hSf->Add( hRf_y, -1.0);

	// Target EMPTY
	// Prompt
	TH2D *hP = (TH3D*)empty.Get( "THR_M2gTaggP_v_TChanM2gP");
	hP->GetXaxis()->SetRange( cbin, cbin);
	TH1D *hPf_y = hP->ProjectionY( "M2gP");

	// Random
	TH3D *hR = (TH3D*)empty.Get( "THR_M2gTaggR_v_TChanM2gR");
	hR->GetXaxis()->SetRange( cbin, cbin);
	TH1D *hRe_y = hR->ProjectionY( "M2gR");
	hRe_y->Scale( 0.5);

	// Subtracted
	hSe = (TH1D*) hPe_y->Clone( "EmptySubt");
	hSe->Sumw2();
	hSe->Add( hRe_y, -1.0);

	// COMPLETELY SUBTRACTED

	// Dead-time correction
	file = full;
	f_dead_f = DeadTimeSF( file);
	file = empty;
	f_dead_e = DeadTimeSF( file);

	// Scale full to empty
	factor = HistSF( hesc, hfsc, cbin, cbin)*f_dead_f/f_dead_e;

	hSf->Scale( factor);
	hS = (TH1D*) hSf->Clone( "Subtracted");
	hS->Add( hSe, -1.0);

	fhist = (TH1D*) hSf->Clone( "Full");
	ehist = (TH1D*) hSe->Clone( "Empty");
	shist = (TH1D*) hS->Clone( "Subt");
}
Пример #16
0
int main(int argc, char** argv){//main  

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

  //////////////////////////////////////////////////////////
  //// Hardcoded config ////////////////////////////////////
  //////////////////////////////////////////////////////////
  bool concept = true;

  //for xvsy plots
  double minX=-1700,maxX=1700;
  double minY=-1700,maxY=1700;
  double minZ=3170,maxZ=3370;
  //double minX=-510,maxX=510;
  //double minY=-510,maxY=510;
  //double minZ=-1000,maxZ=1000;

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

  //size of signal region to perform Chi2 position fit.
  //in units of 2.5mm cells to accomodate different granularities
  unsigned nSR = 12;

  //maximum value of residuals to use in error matrix: discard positions that are too far away 
  double residualMax = 25;//mm

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

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

  std::string inFilePath = filePath+simFileName;

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

  //unsigned genEn;
  //genEn = atoi(argv[7]);

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

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

  std::cout << " -- Input parameters: " << std::endl
	    << " -- Input file path: " << filePath << std::endl
	    << " -- Output file path: " << outPath << std::endl
	    << " -- Output folder: " << outFolder << std::endl
    //<< " -- Generated energy: " << genEn << std::endl
	    << " -- Requiring " << nSiLayers << " si layers." << std::endl
	    << " -- Number cells in signal region for fit: " << nSR << " *2.5*2.5 mm^2 cells" << std::endl
	    << " -- Processing ";
  if (pNevts == 0) std::cout << "all events." << std::endl;
  else std::cout << pNevts << " events." << std::endl;

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

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

  std::ostringstream input;
  input << filePath << "/" << simFileName;

  TFile *simFile = TFile::Open(input.str().c_str());

  if (!simFile) {
    std::cout << " -- Error, input file " << input.str() << " cannot be opened. Exiting..." << std::endl;
    return 1;
  }
  else std::cout << " -- input file " << simFile->GetName() << " successfully opened." << std::endl;
  
  TTree *lSimTree = (TTree*)simFile->Get("HGCSSTree");
  if (!lSimTree){
    std::cout << " -- Error, tree HGCSSTree cannot be opened. Exiting..." << std::endl;
    return 1;
  }

  input.str("");
  input << filePath << "/" << recoFileName;
  
  TFile *recFile = TFile::Open(input.str().c_str());

  if (!recFile) {
    std::cout << " -- Error, input file " << input.str() << " cannot be opened. Exiting..." << std::endl;
    return 1;
  }
  else std::cout << " -- input file " << recFile->GetName() << " successfully opened." << std::endl;

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


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

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

  //extract input energy

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


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

  myDetector.buildDetector(versionNumber,concept,isCaliceHcal);

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

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

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

  HGCSSGeometryConversion geomConv(inFilePath,model,cellSize);
  //assemble in 7.5*7.5 to fill maxE
  std::vector<unsigned> granularity;
  granularity.resize(nLayers,4);
  geomConv.setGranularity(granularity);
  geomConv.initialiseHistos(false,"_10");

  //////////////////////////////////////////////////
  //////////////////////////////////////////////////
  ///////// Output histos  /////////////////////////
  //////////////////////////////////////////////////
  //////////////////////////////////////////////////

  TFile *outputFile = TFile::Open(outPath.c_str(),"RECREATE");
  
  if (!outputFile) {
    std::cout << " -- Error, output file " << outPath << " cannot be opened. Please create output directory. Exiting..." << std::endl;
    return 1;
  }
  else {
    std::cout << " -- output file " << outputFile->GetName() << " successfully opened." << std::endl;
  }
    outputFile->cd();
  TH1F *p_nSimHits = new TH1F("p_nSimHits","n(SimHits)",
			      1000,0,500000);
  p_nSimHits->StatOverflows();
  
  TH1F *p_nRecHits = new TH1F("p_nRecHits","n(RecHits)",
			      1000,0,5000);
  p_nRecHits->StatOverflows();

  TH1F *p_EsimTotal = new TH1F("p_EsimTotal",";Esim (MIPs)",5000,0,50000);
  TH1F *p_ErecoTotal = new TH1F("p_ErecoTotal",";Ereco (MIPs)",5000,0,50000);
  p_EsimTotal->StatOverflows();
  p_ErecoTotal->StatOverflows();

  TH2F *p_genxy[nLayers];
  TH2F *p_xy[nLayers];
  TH2F *p_recoxy[nLayers];

  TH1F *p_residuals_x = new TH1F("p_residuals_x",";xreco-xtruth (mm)",1000,-50,50);
  TH1F *p_residuals_y = new TH1F("p_residuals_y",";yreco-ytruth (mm)",1000,-50,50);
  p_residuals_x->StatOverflows();
  p_residuals_y->StatOverflows();

  std::ostringstream lName;
  for (unsigned iL(0); iL<nLayers; ++iL){
    lName.str("");
    lName << "p_genxy_" << iL;
    p_genxy[iL] = new TH2F(lName.str().c_str(),";x(mm);y(mm)",
			   nX*10,minX,maxX,
			   nY*10,minY,maxY);
    lName.str("");
    lName << "p_xy_" << iL;
    p_xy[iL] = new TH2F(lName.str().c_str(),";x(mm);y(mm)",
   			nX,minX,maxX,
   			nY,minY,maxY);
    lName.str("");
    lName << "p_recoxy_" << iL;
    p_recoxy[iL] = new TH2F(lName.str().c_str(),";x(mm);y(mm)",
   			    nX,minX,maxX,
   			    nY,minY,maxY);
  }

    //////////////////////////////////////////////////
    //////////////////////////////////////////////////
    ///////// Event loop /////////////////////////////
    //////////////////////////////////////////////////
    //////////////////////////////////////////////////

  HGCSSEvent * event = 0;
  std::vector<HGCSSSamplingSection> * ssvec = 0;
  std::vector<HGCSSSimHit> * simhitvec = 0;
  std::vector<HGCSSRecoHit> * rechitvec = 0;
  std::vector<HGCSSGenParticle> * genvec = 0;
  
  lSimTree->SetBranchAddress("HGCSSEvent",&event);
  lSimTree->SetBranchAddress("HGCSSSamplingSectionVec",&ssvec);
  lSimTree->SetBranchAddress("HGCSSSimHitVec",&simhitvec);
  lSimTree->SetBranchAddress("HGCSSGenParticleVec",&genvec);
  
  lRecTree->SetBranchAddress("HGCSSRecoHitVec",&rechitvec);

  const unsigned nEvts = ((pNevts > lSimTree->GetEntries() || pNevts==0) ? static_cast<unsigned>(lSimTree->GetEntries()) : pNevts) ;
  
  std::cout << "- Processing = " << nEvts  << " events out of " << lSimTree->GetEntries() << std::endl;
  
  //Initialise histos
  //necessary to have overflows ?
  gStyle->SetOptStat(1111111);
  double EtotSim[nLayers];
  double EtotRec[nLayers];
  //initialisation for error matrix
  double mean[2][nLayers];//sum residuals for x and y
  double sigma[2][nLayers][nLayers];//sum square
  unsigned nL_mean[nLayers];//number of valid layers
  unsigned nL_sigma[nLayers][nLayers];

  std::vector<double> avgZ;
  avgZ.resize(nLayers,0);


  for (unsigned iL(0);iL<nLayers;++iL){
    EtotSim[iL] = 0;
    EtotRec[iL] = 0;
    nL_mean[iL] = 0;
    mean[0][iL] = 0;
    mean[1][iL] = 0;
    for (unsigned jL(0);jL<nLayers;++jL){
      nL_sigma[iL][jL] = 0;
      sigma[0][iL][jL] = 0;
      sigma[1][iL][jL] = 0;
    }
  }



  bool firstEvent = true;

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

    if (debug){
      std::cout << "... Size of hit vectors: sim = " <<  (*simhitvec).size() << ", reco = " << (*rechitvec).size()<< std::endl;
    }

    //////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////
    //////// output files to save position for chi2 fit //////////
    //////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////

    std::ofstream fout;
    std::ostringstream foutname;
    foutname << outFolder << "_initialPos_evt" << ievt << ".dat";
    fout.open(foutname.str());
    if (!fout.is_open()){
      std::cout << " Cannot open outfile " << foutname.str() << " for writing ! Exiting..." << std::endl;
      return 1;
    }


    //////////////////////////////////////////////////
    //////////////////////////////////////////////////
    ///////// SimHits ////////////////////////////////
    //////////////////////////////////////////////////
    //////////////////////////////////////////////////

    //loop on simhits
    double etotmips = 0;
    unsigned prevLayer = 10000;
    DetectorEnum type = DetectorEnum::FECAL;
    unsigned subdetLayer=0;

    TH2F *etavsphi = new TH2F("etavsphi",";#phi;#eta;hits",150,-3.1416,3.1416,160,1.4,3.0);

    for (unsigned iH(0); iH<(*simhitvec).size(); ++iH){//loop on hits
      HGCSSSimHit lHit = (*simhitvec)[iH];

      //discard some si layers...
      if (lHit.silayer() >= nSiLayers) continue; 

      unsigned layer = lHit.layer();

      if (layer >= nLayers) {
	//std::cout << " WARNING! SimHits with layer " << layer << " outside of detector's definition range ! Please fix the digitiser or the detector definition used here. Ignoring..." << std::endl;
	continue;
      }
      if (layer != prevLayer){
	const HGCSSSubDetector & subdet = myDetector.subDetectorByLayer(layer);
	type = subdet.type;
	subdetLayer = layer-subdet.layerIdMin;
	prevLayer = layer;
	if (debug > 1) std::cout << " - layer " << layer << " " << subdet.name << " " << subdetLayer << std::endl;
      }     

      //unsigned sec =  myDetector.getSection(layer);

      double posx = lHit.get_x(cellSize);
      double posy = lHit.get_y(cellSize);
      double posz = lHit.get_z();
      //double radius = sqrt(posx*posx+posy*posy);
      double lRealTime = mycalib.correctTime(lHit.time(),posx,posy,posz);
      double energy = lHit.energy()*mycalib.MeVToMip(layer);

      //if (energy>1) std::cout << "Hit " << layer << " " << posx << " " << posy << " " << posz << " " << energy << std::endl;

      if (type == DetectorEnum::FECAL ||
	  type == DetectorEnum::MECAL ||
	  type == DetectorEnum::BECAL){
	//correct for si thickness
	//default for 200um
	energy *= 2./nSiLayers;
      }
      
      geomConv.fill(type,subdetLayer,energy,lRealTime,posx,posy,posz);

      bool passTime = myDigitiser.passTimeCut(type,lRealTime);
      if (!passTime) continue;

      if (debug>1) {
	std::cout << " --  SimHit " << iH << "/" << (*simhitvec).size() << " --" << std::endl
		  << " --  position x,y " << posx << "," << posy << std::endl;
	lHit.Print(std::cout);
      }

      EtotSim[layer] += energy;
      p_xy[layer]->Fill(posx,posy,energy);

      ROOT::Math::XYZVector pos(posx,posy,posz);
      etavsphi->Fill(pos.phi(),pos.eta(),energy);

      //double absweight = myDetector.subDetectorByLayer(layer).absWeight;
      double absweight = (*ssvec)[layer].volX0trans()/(*ssvec)[1].volX0trans();

      //if (versionNumber==12){
	//absweight = layer%2==0 ?
	//(*ssvec)[layer].volX0trans()/refThicknessEven : 
	//(*ssvec)[layer].volX0trans()/refThicknessOdd;
	//}
      etotmips += energy*absweight;
      
    }//loop on hits

    p_nSimHits->Fill((*simhitvec).size());
 
    if (debug)  std::cout << std::endl;


    //get position of maximum E tower
    int maxbin = etavsphi->GetMaximumBin();
    int binx,biny,binz;
    etavsphi->GetBinXYZ(maxbin,binx,biny,binz);
    double phimax =etavsphi->GetXaxis()->GetBinCenter(binx); 
    double etamax =etavsphi->GetYaxis()->GetBinCenter(biny); 

    //std::cout << " MaxE cell eta,phi = " << etamax << " " << phimax << std::endl;
    //////////////////////////////////////////////////
    //////////////////////////////////////////////////
    ///////// GenParticles////////////////////////////
    //////////////////////////////////////////////////
    //////////////////////////////////////////////////

    //get truth position

    std::vector<ROOT::Math::XYPoint> truthPos;
    truthPos.resize(nLayers,ROOT::Math::XYPoint());

    for (unsigned iP(0); iP<(*genvec).size(); ++iP){//loop on gen particles    
      //if ((*genvec).size()!= 1) (*genvec)[iP].Print(std::cout);
      if ((*genvec)[iP].trackID()==1){
	double x0 = (*genvec)[iP].x();
	double y0 = (*genvec)[iP].y();
	double z0 = (*genvec)[iP].z();
	double p = sqrt(pow((*genvec)[iP].px(),2)+pow((*genvec)[iP].py(),2)+pow((*genvec)[iP].pz(),2));
	//double energy = sqrt(pow((*genvec)[iP].mass(),2)+pow(p,2));
	//p_genxy[0]->Fill(x0,y0,energy);
	//std::cout << "init : " << x0 << " " << y0 << " " << z0 << std::endl;
	//fill layers by propagating with momentum
	ROOT::Math::XYZVector unit((*genvec)[iP].px()/p,(*genvec)[iP].py()/p,(*genvec)[iP].pz()/p);

	//std::cout << " Gen particle eta,phi = " << unit.eta() << " " << unit.phi() << std::endl;

	for (unsigned iL(0); iL<nLayers; ++iL){
	  if (avgZ[iL]<z0) avgZ[iL] = geomConv.getAverageZ(iL);
	  if (avgZ[iL]>z0) {
	    double xy = (avgZ[iL]-z0)/sinh(unit.eta());
	    double x = xy*cos(unit.phi())+x0;
	    double y = xy*sin(unit.phi())+y0;
	    
	    //std::cout << "Lay " << iL << ": " << x << " " << y << " " << avgZ[iL] << std::endl;
	    p_genxy[iL]->Fill(x,y,1);
	    truthPos[iL] = ROOT::Math::XYPoint(x,y);
	  }
	}

      }

      //p_genPartId->Fill((*genvec)[iP].pdgid());
    }//loop on gen particles

    //////////////////////////////////////////////////
    //////////////////////////////////////////////////
    ///////// RecHits ////////////////////////////////
    //////////////////////////////////////////////////
    //////////////////////////////////////////////////

    double Etotcal = 0;
    std::vector<double> xmax;
    xmax.resize(nLayers,0);
    std::vector<double> ymax;
    ymax.resize(nLayers,0);
    std::vector<double> dRmin;
    dRmin.resize(nLayers,10);

    for (unsigned iH(0); iH<(*rechitvec).size(); ++iH){//loop on rechits
      HGCSSRecoHit lHit = (*rechitvec)[iH];
      if (debug>1) {
	std::cout << " --  RecoHit " << iH << "/" << (*rechitvec).size() << " --" << std::endl
		  << " --  position x,y " << lHit.get_x() << "," << lHit.get_y() << std::endl;
	lHit.Print(std::cout);
      }
      
      double energy = lHit.energy();//in MIP already...
      unsigned layer = lHit.layer();

      if (layer >= nLayers) {
	std::cout << " WARNING! RecoHits with layer " << layer << " outside of detector's definition range ! Please fix the digitiser or the detector definition used here. Ignoring..." << std::endl;
	continue;
      }

      double posx = lHit.get_x();
      double posy = lHit.get_y();
      double posz = lHit.get_z();
      ROOT::Math::XYZVector pos(posx,posy,posz);
      double deta = fabs(pos.eta()-etamax);
      double dphi = fabs(pos.phi()-phimax);
      double dR = sqrt(pow(deta,2)+pow(dphi,2));
      if (dR<dRmin[layer]) {
	dRmin[layer] = dR;
	xmax[layer] = posx;
	ymax[layer] = posy;
      }


      //unsigned sec =  myDetector.getSection(layer);
      
      p_recoxy[layer]->Fill(posx,posy,energy);
      EtotRec[layer] += energy;

      if (debug>1) std::cout << "-hit" << iH << "-" << layer << " " << energy << " " << EtotRec[layer];

      double absweight = (*ssvec)[layer].volX0trans()/(*ssvec)[1].volX0trans();

      Etotcal += energy*absweight;
    }//loop on rechits
    
    p_nRecHits->Fill((*rechitvec).size());

    p_EsimTotal->Fill(etotmips);
    p_ErecoTotal->Fill(Etotcal);
    
    //for (unsigned iL(0);iL<nLayers;++iL){//loop on layers
      //p_EsimvsLayer->Fill(iL,EtotSim[iL]);
      // p_ErecovsLayer->Fill(iL,EtotRec[iL]);
      //}

    //get energy-weighted position around maximum
    std::vector<ROOT::Math::XYPoint> recoPos;
    recoPos.resize(nLayers,ROOT::Math::XYPoint(0,0));
    std::vector<double> eSum;
    eSum.resize(nLayers,0);
    std::vector<unsigned> nHits;
    nHits.resize(nLayers,0);
    for (unsigned iH(0); iH<(*rechitvec).size(); ++iH){//loop on rechits
      HGCSSRecoHit lHit = (*rechitvec)[iH];
      double energy = lHit.energy();//in MIP already...
      unsigned layer = lHit.layer();
      double posx = lHit.get_x();
      double posy = lHit.get_y();
      double posz = lHit.get_z();
      double step = cellSize*nSR/2.+0.1;//+0.1 to accomodate double precision
      if (fabs(posx-xmax[layer]) < step && 
	  fabs(posy-ymax[layer]) < step){
	recoPos[layer].SetX(recoPos[layer].X() + posx*energy);
	recoPos[layer].SetY(recoPos[layer].Y() + posy*energy);
	eSum[layer] += energy;
	if (energy>0) nHits[layer]++;
      }

    }//loop on rechits


    //fill error matrix
    if (debug) std::cout << " Summary of reco and truth positions:" << std::endl;
    for (unsigned iL(0);iL<nLayers;++iL){//loop on layers
      if (nHits[iL]==0) continue;
      recoPos[iL].SetX(recoPos[iL].X()/eSum[iL]);
      recoPos[iL].SetY(recoPos[iL].Y()/eSum[iL]);
      if (debug) std::cout << iL << " nHits=" << nHits[iL] << " Max=(" << xmax[iL] << "," << ymax[iL] << ")\t Reco=(" << recoPos[iL].X() << "," << recoPos[iL].Y() << ")\t Truth=(" << truthPos[iL].X() << "," << truthPos[iL].Y() << ")" << std::endl;
      fout << iL << " " << recoPos[iL].X() << " " << recoPos[iL].Y() << " " << avgZ[iL] << " " << truthPos[iL].X() << " " << truthPos[iL].Y() << std::endl;
    }
    for (unsigned iL(0);iL<nLayers;++iL){//loop on layers
      if (nHits[iL]==0) continue;
      double residual_xi = recoPos[iL].X()-truthPos[iL].X();
      double residual_yi = recoPos[iL].Y()-truthPos[iL].Y();
      p_residuals_x->Fill(residual_xi);
      p_residuals_y->Fill(residual_yi);
      if (fabs(residual_xi)>residualMax || fabs(residual_yi)>residualMax) continue;
      mean[0][iL] += residual_xi;
      mean[1][iL] += residual_yi;
      ++nL_mean[iL];
      for (unsigned jL(0);jL<nLayers;++jL){//loop on layers
	if (nHits[jL]==0) continue;
	double residual_xj = recoPos[jL].X()-truthPos[jL].X();
	double residual_yj = recoPos[jL].Y()-truthPos[jL].Y();
	if (fabs(residual_xj)>residualMax || fabs(residual_yj)>residualMax) continue;
	double sigma_x = residual_xi*residual_xj;
	double sigma_y = residual_yi*residual_yj;
	sigma[0][iL][jL] += sigma_x;
	sigma[1][iL][jL] += sigma_y;
	++nL_sigma[iL][jL];
      }//loop on layers
    }//loop on layers

    geomConv.initialiseHistos();
    etavsphi->Delete();

    fout.close();

    firstEvent = false;
  }//loop on entries
  std::cout << " -- Total Esim in MIPS: "
	    <<  p_EsimTotal->GetEntries() 
	    << " mean " << p_EsimTotal->GetMean() 
	    << " rms " << p_EsimTotal->GetRMS() 
	    << " rms/mean " << p_EsimTotal->GetRMS()/p_EsimTotal->GetMean()
	    << " underflows " << p_EsimTotal->GetBinContent(0)
	    << " overflows " << p_EsimTotal->GetBinContent(p_EsimTotal->GetNbinsX()+1)
	    << std::endl;
  
  std::cout << " -- Total Ereco in MIPS: "
	    <<  p_ErecoTotal->GetEntries() 
	    << " mean " << p_ErecoTotal->GetMean() 
	    << " rms " << p_ErecoTotal->GetRMS() 
	    << " rms/mean " << p_ErecoTotal->GetRMS()/p_ErecoTotal->GetMean()
	    << " underflows " << p_ErecoTotal->GetBinContent(0)
	    << " overflows " << p_ErecoTotal->GetBinContent(p_ErecoTotal->GetNbinsX()+1)
	    << std::endl;
  

  //finalise error matrix
  std::ofstream fmatrix;
  std::ostringstream fmatrixname;
  fmatrixname << outFolder << "_errorMatrix_ref.dat";
  fmatrix.open(fmatrixname.str());
  if (!fmatrix.is_open()){
    std::cout << " Cannot open outfile " << fmatrixname.str() << " for writing ! Exiting..." << std::endl;
    exit(1);
  }



  TMatrixD matrix(nLayers,nLayers);
  outputFile->cd();
  TH2F *p_errorMatrix = new TH2F("p_errorMatrix",";i;j;M_{ij}",
			    nLayers,0,nLayers,
			    nLayers,0,nLayers);
  TH2F *p_corrMatrix = new TH2F("p_corrMatrix",";i;j;M_{ij}",
				nLayers,0,nLayers,
				nLayers,0,nLayers);

  for (unsigned iL(0);iL<nLayers;++iL){//loop on layers
    mean[0][iL] = mean[0][iL]/nL_mean[iL];
    mean[1][iL] = mean[1][iL]/nL_mean[iL];
  }
  for (unsigned iL(0);iL<nLayers;++iL){//loop on layers
    for (unsigned jL(0);jL<nLayers;++jL){//loop on layers
      sigma[0][iL][jL] = sigma[0][iL][jL]/nL_sigma[iL][jL];
      sigma[1][iL][jL] = sigma[1][iL][jL]/nL_sigma[iL][jL];
      //consider average of both x and y in one matrix
      matrix[iL][jL] = 0.5*(sigma[0][iL][jL]-mean[0][iL]*mean[0][jL]+
			    sigma[1][iL][jL]-mean[1][iL]*mean[1][jL]);
      //matrix[jL][iL] = matrix[iL][jL];
      p_errorMatrix->Fill(iL,jL,matrix[iL][jL]);
 
      fmatrix << iL << " " << jL << " " << std::setprecision(17) << matrix[iL][jL] << std::endl;

      //if (iL!=jL){
      //p_matrix->Fill(jL,iL,matrix[iL][jL]);
      //}
    }
  }
  fmatrix.close();

  //fill correlation matrix
  for (unsigned iL(0);iL<nLayers;++iL){//loop on layers
    for (unsigned jL(0);jL<nLayers;++jL){//loop on layers
      if (matrix[iL][iL]!=0 && matrix[jL][jL]!= 0) 
	p_corrMatrix->Fill(iL,jL,matrix[iL][jL]/sqrt(matrix[iL][iL]*matrix[jL][jL]));
    }
  }

  //get back data for each event and perform chi2 fit:
  std::cout << " -- Performing chi2 fit for each event" << std::endl;

  unsigned nInvalidFits=0;
  TH1F *p_chi2[2];
  TH1F *p_chi2overNDF[2];

  p_chi2[0] = new TH1F("p_chi2",";#chi^{2};n_{events}",100,0,500);
  p_chi2overNDF[0] = new TH1F("p_chi2overNDF",";#chi^{2}/NDF;n_{events}",100,0,10);
  p_chi2[1] = new TH1F("p_chi2_truth",";#chi^{2};n_{events}",100,0,500);
  p_chi2overNDF[1] = new TH1F("p_chi2overNDF_truth",";#chi^{2}/NDF;n_{events}",100,0,10);
  for (unsigned rt(0); rt<2;++rt){
  p_chi2[rt]->StatOverflows();
  p_chi2overNDF[rt]->StatOverflows();
  }

  TH1F *p_impactX[2];
  p_impactX[0] = new TH1F("p_impactX",";x front face impact (mm);n_{events}",200,-500,500);
  p_impactX[1] = new TH1F("p_impactX_truth",";x front face impact (mm);n_{events}",200,-500,500);
  TH1F *p_impactY[2];
  p_impactY[0] = new TH1F("p_impactY",";y front face impact (mm);n_{events}",240,300,1500);
  p_impactY[1] = new TH1F("p_impactY_truth",";y front face impact (mm);n_{events}",240,300,1500);
  TH1F *p_angleX[2];
  p_angleX[0] = new TH1F("p_angleX",";x direction angle (rad);n_{events}",150,-3.1416,3.1416);
  p_angleX[1] = new TH1F("p_angleX_truth",";x direction angle (rad);n_{events}",150,-3.1416,3.1416);
  TH1F *p_angleY[2];
  p_angleY[0] = new TH1F("p_angleY",";y direction angle (rad);n_{events}",150,-3.1416,3.1416);
  p_angleY[1] = new TH1F("p_angleY_truth",";y direction angle (rad);n_{events}",150,-3.1416,3.1416);

  TH1F *p_positionReso[2];
  TH1F *p_angularReso[2];
  p_positionReso[0] = new TH1F("p_positionResoX",";#sigma_{x,y} (mm);n_{events}",100,0,20);
  p_positionReso[1] = new TH1F("p_positionResoY",";#sigma_{x,y} (mm);n_{events}",100,0,20);
  p_angularReso[0] = new TH1F("p_angularResoX",";#sigma_{#theta} (rad);n_{events}",100,0,1);
  p_angularReso[1] = new TH1F("p_angularResoY",";#sigma_{#theta} (rad);n_{events}",100,0,1);

  //open new file to save accurate positions
  std::ofstream fout;
  std::ostringstream foutname;
  foutname << outFolder << "_accuratePos.dat";
  fout.open(foutname.str());
  if (!fout.is_open()){
    std::cout << " Cannot open outfile " << foutname.str() << " for writing ! Exiting..." << std::endl;
    return 1;
  }

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

    std::ifstream fin;
    std::ostringstream finname;
    finname << outFolder << "_initialPos_evt" << ievt << ".dat";
    fin.open(finname.str());
    if (!fin.is_open()){
      std::cout << " Cannot open input file " << finname.str() << "! Exiting..." << std::endl;
      return 1;
    }

    std::vector<unsigned> layerId;
    std::vector<double> posx;
    std::vector<double> posy;
    std::vector<double> posz;
    std::vector<double> posxtruth;
    std::vector<double> posytruth;
    layerId.reserve(nLayers);
    posx.reserve(nLayers);
    posy.reserve(nLayers);
    posz.reserve(nLayers);
    posxtruth.reserve(nLayers);
    posytruth.reserve(nLayers);

    while (!fin.eof()){
      unsigned l=nLayers;
      double xr=0,yr=0,z=0,xt=0,yt=0;
      fin>>l>>xr>>yr>>z>>xt>>yt;
      if (l<nLayers){
	layerId.push_back(l);
	posx.push_back(xr);
	posy.push_back(yr);
	posz.push_back(z);
	posxtruth.push_back(xt);
	posytruth.push_back(yt);	
      }
    }

    fin.close();

    const unsigned nL = layerId.size();

    //for (unsigned iL(0); iL<nL;++iL){
      //std::cout << layerId[iL] << " " << posx[iL] << " " << posy[iL] << " " << posz[iL] << std::endl;
    //}

    //if less than 3 valid layers: no point doing a fit !!
    if (nL<3){
      nInvalidFits++;
      continue;
    }

    //number of points: x and y per layer minus number of parameters: 2 for x + 2 for y.
    double ndf = 2*nL-4;

    //Get error matrix removing lines with zero hits
    TMatrixDSym e(nL);
    TVectorD u(nL),z(nL),x(nL),y(nL);
    
    for(unsigned i(0);i<nL;++i) {
      u(i)=1.0;
      z(i)=posz[i];
      //std::cout << "fit() z(" << i << ") = " << z(i) << std::endl;
      
      for(unsigned j(i);j<nL;++j) {
	e(i,j)=matrix(layerId[i],layerId[j]);
	e(j,i)=matrix(layerId[j],layerId[i]);
      }
    }

    e.Invert();

    
    //do fit for reco and truth

    for (unsigned rt(0); rt<2;++rt){
      if (debug) {
	std::cout << "... Processing ";
	if (rt==0) std::cout << " fit to reco position.";
	else std::cout << " fit to truth position.";
	std::cout << std::endl;
      }
      double chiSq(0.0);
      double position[2];
      double positionFF[2];
      double TanAngle[2];
      
      TMatrixD fitMatrix(4,4);
      
      //resolve equation for x and y separately
      for(unsigned xy(0);xy<2;xy++) {//loop on x or y
	if (debug) {
	  std::cout << "... Processing ";
	  if (xy==0) std::cout << " fit to x position.";
	  else std::cout << " fit to y position.";
	  std::cout << std::endl;
	}
	for(unsigned i(0);i<nL;i++) {
	  x(i)= rt==0 ? ((xy==0) ? posx[i] : posy[i]) : ((xy==0) ? posxtruth[i] : posytruth[i]);
	  //std::cout << "fit() x(" << i << ") = " << x(i) << std::endl;
	}
	
	TMatrixD w(2,2);
	TVectorD v(2),p(2);
	
	w(0,0)=u*(e*u);
	w(0,1)=u*(e*z);
	w(1,0)=z*(e*u);
	w(1,1)=z*(e*z);

	v(0)=u*(e*x);
	v(1)=z*(e*x);
	
	w.Invert();
	
	p=w*v;
	if (debug) {
	  std::cout << "fit() w(0,0) = " << w(0,0) << std::endl;
	  std::cout << "fit() w(0,1) = " << w(0,1) << std::endl;
	  std::cout << "fit() w(1,0) = " << w(1,0) << std::endl;
	  std::cout << "fit() w(1,1) = " << w(1,1) << std::endl;	
	  std::cout << "fit() p(0) = " << p(0) << std::endl;
	  std::cout << "fit() p(1) = " << p(1) << std::endl;
	}

	position[xy] = p(0);
	positionFF[xy] = p(0)+p(1)*posz[0];
	TanAngle[xy] = p(1);
	
	fitMatrix[2*xy][2*xy]=w(0,0);
	fitMatrix[2*xy][2*xy+1]=w(0,1);
	fitMatrix[2*xy+1][2*xy]=w(1,0);
	fitMatrix[2*xy+1][2*xy+1]=w(1,1);
	
	
	TVectorD dp(nL);
	for(unsigned i(0);i<nL;i++) {
	  dp(i)=x(i)-p(0)-p(1)*z(i);
	}
	
	chiSq+=dp*(e*dp);
      }//loop on x or y
      
      p_chi2[rt]->Fill(chiSq);
      p_chi2overNDF[rt]->Fill(chiSq/ndf);
      p_impactX[rt]->Fill(positionFF[0]);
      p_angleX[rt]->Fill(atan(TanAngle[0]));
      p_impactY[rt]->Fill(positionFF[1]);
      p_angleY[rt]->Fill(atan(TanAngle[1]));

      if (rt==0) {
	p_positionReso[0]->Fill(sqrt(fabs(fitMatrix[0][0])));
	p_positionReso[1]->Fill(sqrt(fabs(fitMatrix[2][2])));
	p_angularReso[0]->Fill(sqrt(fabs(fitMatrix[1][1])));
	p_angularReso[1]->Fill(sqrt(fabs(fitMatrix[3][3])));

	fout << ievt << " " 
	     << position[0] << " " 
	     << sqrt(fabs(fitMatrix[0][0])) << " " 
	     << TanAngle[0] << " " 
	     << sqrt(fabs(fitMatrix[1][1])) << " "
	     << position[1] << " " 
	     << sqrt(fabs(fitMatrix[2][2])) << " "
	     << TanAngle[1] << " "
	     << sqrt(fabs(fitMatrix[3][3]))
	     << std::endl;
      }

    }//reco or truth

  }//loop on entries
  
  fout.close();    


  std::cout << " -- Number of invalid fits: " << nInvalidFits << std::endl;


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


}//main
Пример #17
0
void M2gChan( UInt_t chan = 250, UInt_t rebin = 1, TString tgt = "full")
{
	UInt_t left, right, bin_lo, bin_hi, rebin;
	Double_t eg, deg;
	TString name;

	gStyle->SetOptStat( 0);

	if ( !gROOT->GetListOfCanvases()->IsEmpty()) {
		delete c1;
	}

	TCanvas *c1 = new TCanvas ( "c1", "Subtraction", 200, 20, 700, 400);
   c1->SetGrid();
   c1->GetFrame()->SetFillColor( 21);
   c1->GetFrame()->SetBorderSize( 12);
	c1->Divide( 2, 1);

	eg = tcd[chan].energy;
	deg = tcd[chan].denergy;

	name = Form( "Egamma = %5.1f +/- %3.1f MeV", eg, deg/2);
	cout << name << endl;

	left = 0;
	right = 200;

	// Prompt
	name = "THR_M2gTaggP_v_TChanM2gP";
	if ( tgt == "full") TH2D *hp2d = (TH2D*)full.Get( name);
	else if ( tgt == "empty") TH2D *hp2d = (TH2D*)empty.Get( name);
	bin_lo = hp2d->GetXaxis()->FindBin( chan);
	bin_hi = hp2d->GetXaxis()->FindBin( chan);
	hp2d->GetXaxis()->SetRange( bin_lo, bin_hi);
	name = Form( "M2gP_r%d", rebin);
	TH1D *hp = hp2d->ProjectionY( name);
	hp->Rebin( rebin);

	// Random
	name = "THR_M2gTaggR_v_TChanM2gR";
	if ( tgt == "full") TH2D *hr2d = (TH2D*)full.Get( name);
	else if ( tgt == "empty") TH2D *hr2d = (TH2D*)empty.Get( name);
	hr2d->GetXaxis()->SetRange( bin_lo, bin_hi);
	name = Form( "M2gR_r%d", rebin);
	TH1D *hr = hr2d->ProjectionY( name);
	hr->Rebin( rebin);

	c1->cd( 1);
	// Prompt
	hp->SetLineWidth( 3);
	hp->SetLineColor( 4);
	name = Form( "2#gamma Invariant Mass for E_{#gamma} = %5.1f #pm %3.1f MeV",
			eg, deg/2);
	hp->SetTitle( name);
	hp->GetXaxis()->SetTitleOffset( 1.1);
	hp->GetXaxis()->SetLabelSize( 0.03);
	hp->GetXaxis()->CenterTitle();
	hp->GetXaxis()->SetTitle( "M_{#gamma#gamma} (MeV)");
	hp->GetXaxis()->SetRangeUser( left, right);
	hp->DrawCopy();

	// Random
	hr->Scale( 0.5);
	hr->SetLineWidth( 3);
	hr->SetLineColor( 2);
	hr->Draw( "same");

	// Subtracted
	hp->Sumw2();
	hp->Add( hr, -1.0);
	hp->SetMarkerStyle( 21);
	hp->SetMarkerColor( 1);
	hp->SetLineWidth( 3);
	hp->SetLineColor( 1);
	c1->cd(2);
	hp->SetTitle();
	hp->Draw( "E");
	hp->GetXaxis()->SetRangeUser( left, right);

	l = new TLine( left, 0, right, 0);
	l->SetLineStyle( 2);
	l->Draw();
}
Пример #18
0
TH1D* getResHist(const string& inFileName, const string& histName, 
		 double minResRatio) {

    cout<<"Creating histogram for "<<inFileName<<endl;

    // Get the hit-to-lpc residual for residuals > 30% of maximum residual
    int nR = 120;
    double rMin = 0.0;
    double rMax = 600.0;

    TH1D* theHist = new TH1D(histName.c_str(), "", nR, rMin, rMax);
    theHist->SetDirectory(0);

    theHist->SetXTitle("Hit-to-lpc residuals #delta r' larger than 30% of #delta r_{max} (mm)");

    theHist->GetYaxis()->SetTicks("+");
    theHist->GetYaxis()->SetLabelOffset(-0.03);
    theHist->SetTitleOffset(1.25, "Y");
    theHist->GetXaxis()->CenterTitle(kTRUE);
    theHist->SetTitleSize(0.045, "X");
    theHist->SetLabelSize(0.045, "X");
    theHist->SetLabelSize(0.05, "Y");

    TFile* theFile = TFile::Open(inFileName.c_str(), "read");

    TTree* lpcTree = dynamic_cast<TTree*>(theFile->Get("lpcTree"));

    vector<double>* hitResiduals = 0;
    lpcTree->SetBranchAddress("hitResiduals", &hitResiduals);

    int nEntries = lpcTree->GetEntries();

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

	// Get the residual info
	lpcTree->GetEntry(i);

	// Sort the vector of hit residuals for this lpc cluster
	std::sort(hitResiduals->begin(), hitResiduals->end());

	// Get the maximum residual
	int nResiduals = hitResiduals->size();
	double maxResidual = (*hitResiduals)[nResiduals-1];

	// Only consider hit residuals that are larger than minResidual
	double minResidual = minResRatio*maxResidual;

	double nPassRes(0.0), nTotRes(0.0);
	for (int j = 0; j < nResiduals; j++) {

	    double resValue = (*hitResiduals)[j];
	    if (resValue > minResidual) {

		// We have a residual distance that is large enough
		theHist->Fill(resValue);

	    }

	} // Loop over residuals

    }

    // Normalise the histogram
    double scale(1.0);
    double integral = theHist->Integral();
    if (integral > 0.0) {scale = 1.0/integral;}
    
    theHist->Scale(scale);
    
    theFile->Close();

    return theHist;

}
void TMVAClassificationApplication( TString myMethodList = "" , TString decay_mode) 
{   
#ifdef __CINT__
   gROOT->ProcessLine( ".O0" ); // turn off optimization in CINT
#endif

   //---------------------------------------------------------------

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

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

   // --- Cut optimisation
   Use["Cuts"]            = 1;
   Use["CutsD"]           = 1;
   Use["CutsPCA"]         = 0;
   Use["CutsGA"]          = 0;
   Use["CutsSA"]          = 0;
   // 
   // --- 1-dimensional likelihood ("naive Bayes estimator")
   Use["Likelihood"]      = 1;
   Use["LikelihoodD"]     = 0; // the "D" extension indicates decorrelated input variables (see option strings)
   Use["LikelihoodPCA"]   = 1; // the "PCA" extension indicates PCA-transformed input variables (see option strings)
   Use["LikelihoodKDE"]   = 0;
   Use["LikelihoodMIX"]   = 0;
   //
   // --- Mutidimensional likelihood and Nearest-Neighbour methods
   Use["PDERS"]           = 1;
   Use["PDERSD"]          = 0;
   Use["PDERSPCA"]        = 0;
   Use["PDEFoam"]         = 1;
   Use["PDEFoamBoost"]    = 0; // uses generalised MVA method boosting
   Use["KNN"]             = 1; // k-nearest neighbour method
   //
   // --- Linear Discriminant Analysis
   Use["LD"]              = 1; // Linear Discriminant identical to Fisher
   Use["Fisher"]          = 0;
   Use["FisherG"]         = 0;
   Use["BoostedFisher"]   = 0; // uses generalised MVA method boosting
   Use["HMatrix"]         = 0;
   //
   // --- Function Discriminant analysis
   Use["FDA_GA"]          = 1; // minimisation of user-defined function using Genetics Algorithm
   Use["FDA_SA"]          = 0;
   Use["FDA_MC"]          = 0;
   Use["FDA_MT"]          = 0;
   Use["FDA_GAMT"]        = 0;
   Use["FDA_MCMT"]        = 0;
   //
   // --- Neural Networks (all are feed-forward Multilayer Perceptrons)
   Use["MLP"]             = 0; // Recommended ANN
   Use["MLPBFGS"]         = 0; // Recommended ANN with optional training method
   Use["MLPBNN"]          = 1; // Recommended ANN with BFGS training method and bayesian regulator
   Use["CFMlpANN"]        = 0; // Depreciated ANN from ALEPH
   Use["TMlpANN"]         = 0; // ROOT's own ANN
   //
   // --- Support Vector Machine 
   Use["SVM"]             = 1;
   // 
   // --- Boosted Decision Trees
   Use["BDT"]             = 1; // uses Adaptive Boost
   Use["BDTG"]            = 0; // uses Gradient Boost
   Use["BDTB"]            = 0; // uses Bagging
   Use["BDTD"]            = 0; // decorrelation + Adaptive Boost
   // 
   // --- Friedman's RuleFit method, ie, an optimised series of cuts ("rules")
   Use["RuleFit"]         = 1;
   // ---------------------------------------------------------------
   Use["Plugin"]          = 0;
   Use["Category"]        = 0;
   Use["SVM_Gauss"]       = 0;
   Use["SVM_Poly"]        = 0;
   Use["SVM_Lin"]         = 0;

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

   // Select methods (don't look at this code - not of interest)
   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 the Reader object

   TMVA::Reader *reader = new TMVA::Reader( "!Color:!Silent" );    

   // Create a set of variables and declare them to the reader
   // - the variable names MUST corresponds in name and type to those given in the weight file(s) used
   Float_t met, mT, mT2W;


   reader->AddVariable("met", &met);
   reader->AddVariable("mT", &mT);
   reader->AddVariable("mT2W",&mT2W);
   

   // Spectator variables declared in the training have to be added to the reader, too
/*   Float_t spec1,spec2;
   reader->AddSpectator( "spec1 := var1*2",   &spec1 );
   reader->AddSpectator( "spec2 := var1*3",   &spec2 );

   Float_t Category_cat1, Category_cat2, Category_cat3;
   if (Use["Category"]){
    // Add artificial spectators for distinguishing categories
      reader->AddSpectator( "Category_cat1 := var3<=0",             &Category_cat1 );
      reader->AddSpectator( "Category_cat2 := (var3>0)&&(var4<0)",  &Category_cat2 );
      reader->AddSpectator( "Category_cat3 := (var3>0)&&(var4>=0)", &Category_cat3 );
   }
*/
   // --- Book the MVA methods

   TString dir    = "weights/";
   TString prefix = "TMVAClassification";

   // Book method(s)
   for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) {
      if (it->second) {
         TString methodName = TString(it->first) + TString(" method");
         TString weightfile = dir + prefix + TString("_") + TString(it->first) + TString(".weights.xml");
         reader->BookMVA( methodName, weightfile ); 
      }
   }
   
   // Book output histograms
   UInt_t nbin = 100;
   TH1F   *histLk(0), *histLkD(0), *histLkPCA(0), *histLkKDE(0), *histLkMIX(0), *histPD(0), *histPDD(0);
   TH1F   *histPDPCA(0), *histPDEFoam(0), *histPDEFoamErr(0), *histPDEFoamSig(0), *histKNN(0), *histHm(0);
   TH1F   *histFi(0), *histFiG(0), *histFiB(0), *histLD(0), *histNn(0),*histNnbfgs(0),*histNnbnn(0);
   TH1F   *histNnC(0), *histNnT(0), *histBdt(0), *histBdtG(0), *histBdtD(0), *histRf(0), *histSVMG(0);
   TH1F   *histSVMP(0), *histSVML(0), *histFDAMT(0), *histFDAGA(0), *histCat(0), *histPBdt(0);

   if (Use["Likelihood"])    histLk      = new TH1F( "MVA_Likelihood",    "MVA_Likelihood",    nbin, -1, 1 );
   if (Use["LikelihoodD"])   histLkD     = new TH1F( "MVA_LikelihoodD",   "MVA_LikelihoodD",   nbin, -1, 0.9999 );
   if (Use["LikelihoodPCA"]) histLkPCA   = new TH1F( "MVA_LikelihoodPCA", "MVA_LikelihoodPCA", nbin, -1, 1 );
   if (Use["LikelihoodKDE"]) histLkKDE   = new TH1F( "MVA_LikelihoodKDE", "MVA_LikelihoodKDE", nbin,  -0.00001, 0.99999 );
   if (Use["LikelihoodMIX"]) histLkMIX   = new TH1F( "MVA_LikelihoodMIX", "MVA_LikelihoodMIX", nbin,  0, 1 );
   if (Use["PDERS"])         histPD      = new TH1F( "MVA_PDERS",         "MVA_PDERS",         nbin,  0, 1 );
   if (Use["PDERSD"])        histPDD     = new TH1F( "MVA_PDERSD",        "MVA_PDERSD",        nbin,  0, 1 );
   if (Use["PDERSPCA"])      histPDPCA   = new TH1F( "MVA_PDERSPCA",      "MVA_PDERSPCA",      nbin,  0, 1 );
   if (Use["KNN"])           histKNN     = new TH1F( "MVA_KNN",           "MVA_KNN",           nbin,  0, 1 );
   if (Use["HMatrix"])       histHm      = new TH1F( "MVA_HMatrix",       "MVA_HMatrix",       nbin, -0.95, 1.55 );
   if (Use["Fisher"])        histFi      = new TH1F( "MVA_Fisher",        "MVA_Fisher",        nbin, -4, 4 );
   if (Use["FisherG"])       histFiG     = new TH1F( "MVA_FisherG",       "MVA_FisherG",       nbin, -1, 1 );
   if (Use["BoostedFisher"]) histFiB     = new TH1F( "MVA_BoostedFisher", "MVA_BoostedFisher", nbin, -2, 2 );
   if (Use["LD"])            histLD      = new TH1F( "MVA_LD",            "MVA_LD",            nbin, -2, 2 );
   if (Use["MLP"])           histNn      = new TH1F( "MVA_MLP",           "MVA_MLP",           nbin, -1.25, 1.5 );
   if (Use["MLPBFGS"])       histNnbfgs  = new TH1F( "MVA_MLPBFGS",       "MVA_MLPBFGS",       nbin, -1.25, 1.5 );
   if (Use["MLPBNN"])        histNnbnn   = new TH1F( "MVA_MLPBNN",        "MVA_MLPBNN",        nbin, -1.25, 1.5 );
   if (Use["CFMlpANN"])      histNnC     = new TH1F( "MVA_CFMlpANN",      "MVA_CFMlpANN",      nbin,  0, 1 );
   if (Use["TMlpANN"])       histNnT     = new TH1F( "MVA_TMlpANN",       "MVA_TMlpANN",       nbin, -1.3, 1.3 );
   if (Use["BDT"])           histBdt     = new TH1F( "MVA_BDT",           "MVA_BDT",           nbin, -0.8, 0.8 );
   if (Use["BDTD"])          histBdtD    = new TH1F( "MVA_BDTD",          "MVA_BDTD",          nbin, -0.8, 0.8 );
   if (Use["BDTG"])          histBdtG    = new TH1F( "MVA_BDTG",          "MVA_BDTG",          nbin, -1.0, 1.0 );
   if (Use["RuleFit"])       histRf      = new TH1F( "MVA_RuleFit",       "MVA_RuleFit",       nbin, -2.0, 2.0 );
   if (Use["SVM_Gauss"])     histSVMG    = new TH1F( "MVA_SVM_Gauss",     "MVA_SVM_Gauss",     nbin,  0.0, 1.0 );
   if (Use["SVM_Poly"])      histSVMP    = new TH1F( "MVA_SVM_Poly",      "MVA_SVM_Poly",      nbin,  0.0, 1.0 );
   if (Use["SVM_Lin"])       histSVML    = new TH1F( "MVA_SVM_Lin",       "MVA_SVM_Lin",       nbin,  0.0, 1.0 );
   if (Use["FDA_MT"])        histFDAMT   = new TH1F( "MVA_FDA_MT",        "MVA_FDA_MT",        nbin, -2.0, 3.0 );
   if (Use["FDA_GA"])        histFDAGA   = new TH1F( "MVA_FDA_GA",        "MVA_FDA_GA",        nbin, -2.0, 3.0 );
   if (Use["Category"])      histCat     = new TH1F( "MVA_Category",      "MVA_Category",      nbin, -2., 2. );
   if (Use["Plugin"])        histPBdt    = new TH1F( "MVA_PBDT",          "MVA_BDT",           nbin, -0.8, 0.8 );

   // PDEFoam also returns per-event error, fill in histogram, and also fill significance
   if (Use["PDEFoam"]) {
      histPDEFoam    = new TH1F( "MVA_PDEFoam",       "MVA_PDEFoam",              nbin,  0, 1 );
      histPDEFoamErr = new TH1F( "MVA_PDEFoamErr",    "MVA_PDEFoam error",        nbin,  0, 1 );
      histPDEFoamSig = new TH1F( "MVA_PDEFoamSig",    "MVA_PDEFoam significance", nbin,  0, 10 );
   }

   // Book example histogram for probability (the other methods are done similarly)
   TH1F *probHistFi(0), *rarityHistFi(0);
   if (Use["Fisher"]) {
      probHistFi   = new TH1F( "MVA_Fisher_Proba",  "MVA_Fisher_Proba",  nbin, 0, 1 );
      rarityHistFi = new TH1F( "MVA_Fisher_Rarity", "MVA_Fisher_Rarity", nbin, 0, 1 );
   }



   TString fname; 
   Double_t event_weight; // events weights are: xsection * efficiency (preselection)

   if (decay_mode == "TT_1Lep") {fname  = "Example_Rootfiles/ttbar_1l/output/ttbar_1l.root"; 		event_weight = 0.153;}
   if (decay_mode == "TT_2Lep") {fname  = "Example_Rootfiles/ttbar_2l/output/ttbar_2l.root"; 		event_weight = 0.129;}
   if (decay_mode == "WJets")   {fname  = "Example_Rootfiles/wjets_all/output/wjets_all.root"; 		event_weight = 0.67;}  
   if (decay_mode == "Others")  {fname  = "Example_Rootfiles/others_all/output/others_all.root"; 	event_weight = 0.106;}

   if (decay_mode == "T2tt_R1") { fname  = "Example_Rootfiles/t2tt_all/R1/output/t2tt_all_R1.root"; 	event_weight = 1592./24845.;}
   if (decay_mode == "T2tt_R2") { fname  = "Example_Rootfiles/t2tt_all/R2/output/t2tt_all_R2.root"; 	event_weight = 1018./24994.;}
   if (decay_mode == "T2tt_R3") { fname  = "Example_Rootfiles/t2tt_all/R3/output/t2tt_all_R3.root"; 	event_weight = 306./25006.;}
   if (decay_mode == "T2tt_R4") { fname  = "Example_Rootfiles/t2tt_all/R4/output/t2tt_all_R4.root"; 	event_weight = 87./25094.;}
   if (decay_mode == "T2tt_R5") { fname  = "Example_Rootfiles/t2tt_all/R5/output/t2tt_all_R5.root"; 	event_weight = 28./25075.;}
   if (decay_mode == "T2tt_R6") { fname  = "Example_Rootfiles/t2tt_all/R6/output/t2tt_all_R6.root"; 	event_weight = 9./24863.;}



   TFile *input = TFile::Open( fname );


   std::cout << "--- TMVAClassification       : Using input file: " << input->GetName() << std::endl;
   
   // --- //Event loop

   // Prepare the event tree
   // - here the variable names have to corresponds to your tree
   // - you can use the same variables as above which is slightly faster,
   //   but of course you can use different ones and copy the values inside the event loop
   //
   std::cout << "--- Select signal sample" << std::endl;
   TTree *theTree     = (TTree*)input->Get("BDTtree");

   Float_t met, mT, mT2W;
   Int_t event;

   theTree->SetBranchAddress("met",   &met);
   theTree->SetBranchAddress("mT",    &mT);
   theTree->SetBranchAddress("mT2W",  &mT2W);
   theTree->SetBranchAddress("event", &event);



   // Efficiency calculator for cut method
   Int_t    nSelCutsGA = 0;
   Double_t effS       = 0.7;

   std::vector<Float_t> vecVar(4); // vector for EvaluateMVA tests

   Int_t totevt;

    if (string(decay_mode).find("T2tt") != std::string::npos) totevt = 50000;  // Takes too long (for exercise) to run over all the signal events 
    else totevt = theTree->GetEntries();
 
   std::cout << "--- Processing: " << totevt << " events" << std::endl;
   TStopwatch sw;
   sw.Start();
   for (Long64_t ievt=0; ievt<totevt; ievt++) {

      theTree->GetEntry(ievt);
      if (ievt%1000 == 0) std::cout << "--- ... Processing event: " << ievt << std::endl;

      if ( event%2 == 1 ) continue; // remove all odd numbers from our actual analysis 

    
 
      // --- Return the MVA outputs and fill into histograms

      // this gives you the mva value per event 
      // cout << reader->EvaluateMVA("BDT method") << endl;

      if (Use["CutsGA"]) {
         // Cuts is a special case: give the desired signal efficienciy
         Bool_t passed = reader->EvaluateMVA( "CutsGA method", effS );
         if (passed) nSelCutsGA++;
      }

      if (Use["Likelihood"   ])   histLk     ->Fill( reader->EvaluateMVA( "Likelihood method"    ) );
      if (Use["LikelihoodD"  ])   histLkD    ->Fill( reader->EvaluateMVA( "LikelihoodD method"   ) );
      if (Use["LikelihoodPCA"])   histLkPCA  ->Fill( reader->EvaluateMVA( "LikelihoodPCA method" ) );
      if (Use["LikelihoodKDE"])   histLkKDE  ->Fill( reader->EvaluateMVA( "LikelihoodKDE method" ) );
      if (Use["LikelihoodMIX"])   histLkMIX  ->Fill( reader->EvaluateMVA( "LikelihoodMIX method" ) );
      if (Use["PDERS"        ])   histPD     ->Fill( reader->EvaluateMVA( "PDERS method"         ) );
      if (Use["PDERSD"       ])   histPDD    ->Fill( reader->EvaluateMVA( "PDERSD method"        ) );
      if (Use["PDERSPCA"     ])   histPDPCA  ->Fill( reader->EvaluateMVA( "PDERSPCA method"      ) );
      if (Use["KNN"          ])   histKNN    ->Fill( reader->EvaluateMVA( "KNN method"           ) );
      if (Use["HMatrix"      ])   histHm     ->Fill( reader->EvaluateMVA( "HMatrix method"       ) );
      if (Use["Fisher"       ])   histFi     ->Fill( reader->EvaluateMVA( "Fisher method"        ) );
      if (Use["FisherG"      ])   histFiG    ->Fill( reader->EvaluateMVA( "FisherG method"       ) );
      if (Use["BoostedFisher"])   histFiB    ->Fill( reader->EvaluateMVA( "BoostedFisher method" ) );
      if (Use["LD"           ])   histLD     ->Fill( reader->EvaluateMVA( "LD method"            ) );
      if (Use["MLP"          ])   histNn     ->Fill( reader->EvaluateMVA( "MLP method"           ) );
      if (Use["MLPBFGS"      ])   histNnbfgs ->Fill( reader->EvaluateMVA( "MLPBFGS method"       ) );
      if (Use["MLPBNN"       ])   histNnbnn  ->Fill( reader->EvaluateMVA( "MLPBNN method"        ) );
      if (Use["CFMlpANN"     ])   histNnC    ->Fill( reader->EvaluateMVA( "CFMlpANN method"      ) );
      if (Use["TMlpANN"      ])   histNnT    ->Fill( reader->EvaluateMVA( "TMlpANN method"       ) );
      if (Use["BDT"          ])   histBdt    ->Fill( reader->EvaluateMVA( "BDT method"           ), event_weight ); 
      //if (Use["BDT"          ])   histBdt    ->Fill( reader->EvaluateMVA( "BDT method"           )); 
      if (Use["BDTD"         ])   histBdtD   ->Fill( reader->EvaluateMVA( "BDTD method"          ) );
      if (Use["BDTG"         ])   histBdtG   ->Fill( reader->EvaluateMVA( "BDTG method"          ) );
      if (Use["RuleFit"      ])   histRf     ->Fill( reader->EvaluateMVA( "RuleFit method"       ) );
      if (Use["SVM_Gauss"    ])   histSVMG   ->Fill( reader->EvaluateMVA( "SVM_Gauss method"     ) );
      if (Use["SVM_Poly"     ])   histSVMP   ->Fill( reader->EvaluateMVA( "SVM_Poly method"      ) );
      if (Use["SVM_Lin"      ])   histSVML   ->Fill( reader->EvaluateMVA( "SVM_Lin method"       ) );
      if (Use["FDA_MT"       ])   histFDAMT  ->Fill( reader->EvaluateMVA( "FDA_MT method"        ) );
      if (Use["FDA_GA"       ])   histFDAGA  ->Fill( reader->EvaluateMVA( "FDA_GA method"        ) );
      if (Use["Category"     ])   histCat    ->Fill( reader->EvaluateMVA( "Category method"      ) );
      if (Use["Plugin"       ])   histPBdt   ->Fill( reader->EvaluateMVA( "P_BDT method"         ) );

      // Retrieve also per-event error
      if (Use["PDEFoam"]) {
         Double_t val = reader->EvaluateMVA( "PDEFoam method" );
         Double_t err = reader->GetMVAError();
         histPDEFoam   ->Fill( val );
         histPDEFoamErr->Fill( err );         
         if (err>1.e-50) histPDEFoamSig->Fill( val/err );
      }         

      // Retrieve probability instead of MVA output
      if (Use["Fisher"])   {
         probHistFi  ->Fill( reader->GetProba ( "Fisher method" ) );
         rarityHistFi->Fill( reader->GetRarity( "Fisher method" ) );
      }
   }

   // Get elapsed time
   sw.Stop();
   std::cout << "--- End of event loop: "; sw.Print();

   // Get efficiency for cuts classifier
   if (Use["CutsGA"]) std::cout << "--- Efficiency for CutsGA method: " << double(nSelCutsGA)/theTree->GetEntries()
                                << " (for a required signal efficiency of " << effS << ")" << std::endl;

   if (Use["CutsGA"]) {

      // test: retrieve cuts for particular signal efficiency
      // CINT ignores dynamic_casts so we have to use a cuts-secific Reader function to acces the pointer  
      TMVA::MethodCuts* mcuts = reader->FindCutsMVA( "CutsGA method" ) ;

      if (mcuts) {      
         std::vector<Double_t> cutsMin;
         std::vector<Double_t> cutsMax;
         mcuts->GetCuts( 0.7, cutsMin, cutsMax );
         std::cout << "--- -------------------------------------------------------------" << std::endl;
         std::cout << "--- Retrieve cut values for signal efficiency of 0.7 from Reader" << std::endl;
         for (UInt_t ivar=0; ivar<cutsMin.size(); ivar++) {
            std::cout << "... Cut: " 
                      << cutsMin[ivar] 
                      << " < \"" 
                      << mcuts->GetInputVar(ivar)
                      << "\" <= " 
                      << cutsMax[ivar] << std::endl;
         }
         std::cout << "--- -------------------------------------------------------------" << std::endl;
      }
   }

   // --- Write histograms

   TFile *target  = new TFile( "results_"+decay_mode+".root","RECREATE" );
   if (Use["Likelihood"   ])   histLk     ->Write();
   if (Use["LikelihoodD"  ])   histLkD    ->Write();
   if (Use["LikelihoodPCA"])   histLkPCA  ->Write();
   if (Use["LikelihoodKDE"])   histLkKDE  ->Write();
   if (Use["LikelihoodMIX"])   histLkMIX  ->Write();
   if (Use["PDERS"        ])   histPD     ->Write();
   if (Use["PDERSD"       ])   histPDD    ->Write();
   if (Use["PDERSPCA"     ])   histPDPCA  ->Write();
   if (Use["KNN"          ])   histKNN    ->Write();
   if (Use["HMatrix"      ])   histHm     ->Write();
   if (Use["Fisher"       ])   histFi     ->Write();
   if (Use["FisherG"      ])   histFiG    ->Write();
   if (Use["BoostedFisher"])   histFiB    ->Write();
   if (Use["LD"           ])   histLD     ->Write();
   if (Use["MLP"          ])   histNn     ->Write();
   if (Use["MLPBFGS"      ])   histNnbfgs ->Write();
   if (Use["MLPBNN"       ])   histNnbnn  ->Write();
   if (Use["CFMlpANN"     ])   histNnC    ->Write();
   if (Use["TMlpANN"      ])   histNnT    ->Write();
   if (Use["BDT"          ])   histBdt    ->Write();
   if (Use["BDTD"         ])   histBdtD   ->Write();
   if (Use["BDTG"         ])   histBdtG   ->Write(); 
   if (Use["RuleFit"      ])   histRf     ->Write();
   if (Use["SVM_Gauss"    ])   histSVMG   ->Write();
   if (Use["SVM_Poly"     ])   histSVMP   ->Write();
   if (Use["SVM_Lin"      ])   histSVML   ->Write();
   if (Use["FDA_MT"       ])   histFDAMT  ->Write();
   if (Use["FDA_GA"       ])   histFDAGA  ->Write();
   if (Use["Category"     ])   histCat    ->Write();
   if (Use["Plugin"       ])   histPBdt   ->Write();

   // Write also error and significance histos
   if (Use["PDEFoam"]) { histPDEFoam->Write(); histPDEFoamErr->Write(); histPDEFoamSig->Write(); }

   // Write also probability hists
   if (Use["Fisher"]) { if (probHistFi != 0) probHistFi->Write(); if (rarityHistFi != 0) rarityHistFi->Write(); }
   target->Close();

   std::cout << "--- Created root file: \"results_"+decay_mode+".root\" containing the MVA output histograms" << std::endl;
  
   delete reader;
    
   std::cout << "==> TMVAClassificationApplication is done!" << endl << std::endl;
}
Пример #20
0
void TMVAClassificationMy( 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 TMVAClassification.C\(\"myMethod1,myMethod2,myMethod3\"\)
   //
   // if you like to use a method via the plugin mechanism, we recommend using
   //
   // mylinux~> root -l TMVAClassification.C\(\"P_myMethod\"\)
   // (an example is given for using the BDT as plugin (see below),
   // but of course the real application is when you write your own
   // method based)

   //---------------------------------------------------------------

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

   // to get access to the GUI and all tmva macros
    //TString tmva_dir(TString(gRootDir) + "/tmva");
    //if(gSystem->Getenv("TMVASYS"))
    //   tmva_dir = TString(gSystem->Getenv("TMVASYS"));
    //cout<<"tmva_dir:"<<tmva_dir<<endl;
    //gROOT->SetMacroPath(tmva_dir + "/test/:" + gROOT->GetMacroPath() );
    gROOT->ProcessLine(".L TMVAGui.C");



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

   // --- Cut optimisation
   Use["Cuts"]            = 1;
   Use["CutsD"]           = 0;
   Use["CutsPCA"]         = 0;
   Use["CutsGA"]          = 0;
   Use["CutsSA"]          = 0;
   // 
   // --- 1-dimensional likelihood ("naive Bayes estimator")
   Use["Likelihood"]      = 0;
   Use["LikelihoodD"]     = 0; // the "D" extension indicates decorrelated input variables (see option strings)
   Use["LikelihoodPCA"]   = 0; // the "PCA" extension indicates PCA-transformed input variables (see option strings)
   Use["LikelihoodKDE"]   = 0;
   Use["LikelihoodMIX"]   = 0;
   //
   // --- Mutidimensional likelihood and Nearest-Neighbour methods
   Use["PDERS"]           = 0;
   Use["PDERSD"]          = 0;
   Use["PDERSPCA"]        = 0;
   Use["PDEFoam"]         = 0;
   Use["PDEFoamBoost"]    = 0; // uses generalised MVA method boosting
   Use["KNN"]             = 0; // k-nearest neighbour method
   //
   // --- Linear Discriminant Analysis
   Use["LD"]              = 0; // Linear Discriminant identical to Fisher
   Use["Fisher"]          = 0;
   Use["FisherG"]         = 0;
   Use["BoostedFisher"]   = 0; // uses generalised MVA method boosting
   Use["HMatrix"]         = 0;
   //
   // --- Function Discriminant analysis
   Use["FDA_GA"]          = 0; // minimisation of user-defined function using Genetics Algorithm
   Use["FDA_SA"]          = 0;
   Use["FDA_MC"]          = 0;
   Use["FDA_MT"]          = 0;
   Use["FDA_GAMT"]        = 0;
   Use["FDA_MCMT"]        = 0;
   //
   // --- Neural Networks (all are feed-forward Multilayer Perceptrons)
   Use["MLP"]             = 0; // Recommended ANN
   Use["MLPBFGS"]         = 0; // Recommended ANN with optional training method
   Use["MLPBNN"]          = 0; // Recommended ANN with BFGS training method and bayesian regulator
   Use["CFMlpANN"]        = 0; // Depreciated ANN from ALEPH
   Use["TMlpANN"]         = 0; // ROOT's own ANN
   //
   // --- Support Vector Machine 
   Use["SVM"]             = 0;
   // 
   // --- Boosted Decision Trees
   Use["BDT"]             = 0; // uses Adaptive Boost
   Use["BDTG"]            = 0; // uses Gradient Boost
   Use["BDTB"]            = 0; // uses Bagging
   Use["BDTD"]            = 0; // decorrelation + Adaptive Boost
   Use["BDTF"]            = 0; // allow usage of fisher discriminant for node splitting 
   // 
   // --- Friedman's RuleFit method, ie, an optimised series of cuts ("rules")
   Use["RuleFit"]         = 0;
   // ---------------------------------------------------------------

   std::cout << std::endl;
   std::cout << "==> Start TMVAClassification" << std::endl;
   // Select methods (don't look at this code - not of interest)
   if (myMethodList != "") {
      for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) it->second = 0;

      std::vector<TString> mlist = TMVA::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;
	 cout<<regMethod<<" is on"<<endl;
      }
   }
   // -------------------------------------------------------------------------

   // --- Here the preparation phase begins

   // Create a ROOT output file where TMVA will store ntuples, histograms, etc.
   TString outfileName( "TMVA.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 is 
   // the only TMVA object you have to interact with
   //
   // 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( "TMVAClassification", outputFile,
"!V:!Silent:Color:DrawProgressBar:Transformations=I;D;G,D:AnalysisType=Classification" );
//                                               "!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D:AnalysisType=Classification";
   // 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( "myvar1 := var1+var2", 'F' );
   //factory->AddVariable( "myvar2 := var1-var2", "Expression 2", "", 'F' );
   //factory->AddVariable( "var3",                "Variable 3", "units", 'F' );
   //factory->AddVariable( "var4",                "Variable 4", "units", 'F' );

   //factory->AddVariable( "mHig",                "Higgs Mass", "", 'F' );
   //factory->AddVariable( "pfmet",                "PF Met", "", 'F' );
   //factory->AddVariable( "pupmet",               "PUPPI Met", "", 'F' );
   factory->AddVariable( "trkmet",               "Trk Met", "", 'F' );
   //
   // 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 := var1*3",  "Spectator 2", "units", 'F' );
   //
   factory->AddSpectator( "pfmet",                "PF Met", "", 'F' );
   factory->AddSpectator( "pupmet",               "PUPPI Met", "", 'F' );
   factory->AddSpectator( "trkmet",               "Trk Met", "", 'F' );
   // Read training and test data
   // (it is also possible to use ASCII format as input -> see TMVA Users Guide)
   //TString fname = "./tmva_class_example.root";
   //
   // ======================================
   // Signal and Backgroun Samples
   // ======================================
   //
   TString fname = "/terranova_1/HWWwidth/Phys14/gg2hPU40bx25/latino_stepB_latinosYieldSkim_MC_gg2hPU40bx25_wPUPPI.root";
   if (gSystem->AccessPathName( fname ))  // file does not exist in local directory
     exit(-1);
      //gSystem->Exec("wget http://root.cern.ch/files/tmva_class_example.root");
   TFile *SigInput = TFile::Open( fname );
   std::cout << "--- TMVAClassification  : Using Sig input file: " << SigInput->GetName() << std::endl;


   fname = "/terranova_1/HWWwidth/Phys14/DYPU30bx50/latino_stepB_latinosYieldSkim_MC_DYPU30bx50_wPUPPI.root";
   if (gSystem->AccessPathName( fname ))  // file does not exist in local directory
     exit(-1);
      //gSystem->Exec("wget http://root.cern.ch/files/tmva_class_example.root");
   TFile *BkgInput = TFile::Open( fname );
   std::cout << "--- TMVAClassification  : Using Bkg input file: " << BkgInput->GetName() << std::endl;
   
   // --- Register the training and test trees

   TTree *signal     = (TTree*)SigInput->Get("latino");
   TTree *background = (TTree*)BkgInput->Get("latino");
   
   // global event weights per tree (see below for setting event-wise weights)
   //Double_t signalWeight     = 1.0;
   //Double_t backgroundWeight = 1.0;
   
   // You can add an arbitrary number of signal or background trees
   factory->AddSignalTree    ( signal     );
   factory->AddBackgroundTree( background );
   //factory->AddSignalTree    ( signal,     signalWeight     );
   //factory->AddBackgroundTree( background, backgroundWeight );
   //TCut sigCut = "ch1*ch2==-1 && pt1>20 && pt2>10 && mll>12"; // for example: TCut mycuts = "abs(var1)<0.5 && abs(var2-0.5)<1";
   //TCut bkgCut = "mHig<160"; // for example: TCut mycutb = "abs(var1)<0.5";
   //factory->SetInputTrees(inputTree, sigCut, bkgCut);
   
   // To give different trees for training and testing, do as follows:
   //    factory->AddSignalTree( signalTrainingTree, signalTrainWeight, "Training" );
   //    factory->AddSignalTree( signalTestTree,     signalTestWeight,  "Test" );
   
   // Use the following code instead of the above two or four lines to add signal and background
   // training and test events "by hand"
   // NOTE that in this case one should not give expressions (such as "var1+var2") in the input
   //      variable definition, but simply compute the expression before adding the event
   //
   //     // --- begin ----------------------------------------------------------
   //     std::vector<Double_t> vars( 4 ); // vector has size of number of input variables
   //     Float_t  treevars[4], weight;
   //     
   //     // Signal
   //     for (UInt_t ivar=0; ivar<4; ivar++) signal->SetBranchAddress( Form( "var%i", ivar+1 ), &(treevars[ivar]) );
   //     for (UInt_t i=0; i<signal->GetEntries(); i++) {
   //        signal->GetEntry(i);
   //        for (UInt_t ivar=0; ivar<4; ivar++) vars[ivar] = treevars[ivar];
   //        // add training and test events; here: first half is training, second is testing
   //        // note that the weight can also be event-wise
   //        if (i < signal->GetEntries()/2.0) factory->AddSignalTrainingEvent( vars, signalWeight );
   //        else                              factory->AddSignalTestEvent    ( vars, signalWeight );
   //     }
   //   
   //     // Background (has event weights)
   //     background->SetBranchAddress( "weight", &weight );
   //     for (UInt_t ivar=0; ivar<4; ivar++) background->SetBranchAddress( Form( "var%i", ivar+1 ), &(treevars[ivar]) );
   //     for (UInt_t i=0; i<background->GetEntries(); i++) {
   //        background->GetEntry(i);
   //        for (UInt_t ivar=0; ivar<4; ivar++) vars[ivar] = treevars[ivar];
   //        // add training and test events; here: first half is training, second is testing
   //        // note that the weight can also be event-wise
   //        if (i < background->GetEntries()/2) factory->AddBackgroundTrainingEvent( vars, backgroundWeight*weight );
   //        else                                factory->AddBackgroundTestEvent    ( vars, backgroundWeight*weight );
   //     }
         // --- end ------------------------------------------------------------
   //
   // --- end of tree registration 

   // Set individual event weights (the variables must exist in the original TTree)
   //    for signal    : factory->SetSignalWeightExpression    ("weight1*weight2");
   //    for background: factory->SetBackgroundWeightExpression("weight1*weight2");
     
   //factory->SetBackgroundWeightExpression( "weight" );

   // Apply additional cuts on the signal and background samples (can be different)
   TCut mycut = "ch1*ch2==-1 && pt1>20 && pt2>10 && mll>12"; // for example: TCut mycuts = "abs(var1)<0.5 && abs(var2-0.5)<1";
   TCut mycuts = ""; // for example: TCut mycuts = "abs(var1)<0.5 && abs(var2-0.5)<1";
   TCut mycutb = ""; // for example: TCut mycutb = "abs(var1)<0.5";

   // Tell the factory how to use the training and testing events
   //
   // 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" );
   factory->PrepareTrainingAndTestTree( mycut,
   //factory->PrepareTrainingAndTestTree( mycuts, mycutb,
                                        "nTrain_Signal=0:nTrain_Background=0:SplitMode=Random:NormMode=NumEvents:!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

   // Cut optimisation
   if (Use["Cuts"])
      factory->BookMethod( TMVA::Types::kCuts, "Cuts",
                           "!H:!V:FitMethod=MC:EffSel:SampleSize=200000:VarProp=FSmart" );

   if (Use["CutsD"])
      factory->BookMethod( TMVA::Types::kCuts, "CutsD",
                           "!H:!V:FitMethod=MC:EffSel:SampleSize=200000:VarProp=FSmart:VarTransform=Decorrelate" );

   if (Use["CutsPCA"])
      factory->BookMethod( TMVA::Types::kCuts, "CutsPCA",
                           "!H:!V:FitMethod=MC:EffSel:SampleSize=200000:VarProp=FSmart:VarTransform=PCA" );

   if (Use["CutsGA"])
      factory->BookMethod( TMVA::Types::kCuts, "CutsGA",
                           "H:!V:FitMethod=GA:CutRangeMin[0]=-10:CutRangeMax[0]=10:VarProp[1]=FMax:EffSel:Steps=30:Cycles=3:PopSize=400:SC_steps=10:SC_rate=5:SC_factor=0.95" );

   if (Use["CutsSA"])
      factory->BookMethod( TMVA::Types::kCuts, "CutsSA",
                           "!H:!V:FitMethod=SA:EffSel:MaxCalls=150000:KernelTemp=IncAdaptive:InitialTemp=1e+6:MinTemp=1e-6:Eps=1e-10:UseDefaultScale" );

   // Likelihood ("naive Bayes estimator")
   if (Use["Likelihood"])
      factory->BookMethod( TMVA::Types::kLikelihood, "Likelihood",
                           "H:!V:TransformOutput:PDFInterpol=Spline2:NSmoothSig[0]=20:NSmoothBkg[0]=20:NSmoothBkg[1]=10:NSmooth=1:NAvEvtPerBin=50" );

   // Decorrelated likelihood
   if (Use["LikelihoodD"])
      factory->BookMethod( TMVA::Types::kLikelihood, "LikelihoodD",
                           "!H:!V:TransformOutput:PDFInterpol=Spline2:NSmoothSig[0]=20:NSmoothBkg[0]=20:NSmooth=5:NAvEvtPerBin=50:VarTransform=Decorrelate" );

   // PCA-transformed likelihood
   if (Use["LikelihoodPCA"])
      factory->BookMethod( TMVA::Types::kLikelihood, "LikelihoodPCA",
                           "!H:!V:!TransformOutput:PDFInterpol=Spline2:NSmoothSig[0]=20:NSmoothBkg[0]=20:NSmooth=5:NAvEvtPerBin=50:VarTransform=PCA" ); 

   // Use a kernel density estimator to approximate the PDFs
   if (Use["LikelihoodKDE"])
      factory->BookMethod( TMVA::Types::kLikelihood, "LikelihoodKDE",
                           "!H:!V:!TransformOutput:PDFInterpol=KDE:KDEtype=Gauss:KDEiter=Adaptive:KDEFineFactor=0.3:KDEborder=None:NAvEvtPerBin=50" ); 

   // Use a variable-dependent mix of splines and kernel density estimator
   if (Use["LikelihoodMIX"])
      factory->BookMethod( TMVA::Types::kLikelihood, "LikelihoodMIX",
                           "!H:!V:!TransformOutput:PDFInterpolSig[0]=KDE:PDFInterpolBkg[0]=KDE:PDFInterpolSig[1]=KDE:PDFInterpolBkg[1]=KDE:PDFInterpolSig[2]=Spline2:PDFInterpolBkg[2]=Spline2:PDFInterpolSig[3]=Spline2:PDFInterpolBkg[3]=Spline2:KDEtype=Gauss:KDEiter=Nonadaptive:KDEborder=None:NAvEvtPerBin=50" ); 

   // Test the multi-dimensional probability density estimator
   // here are 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["PDERS"])
      factory->BookMethod( TMVA::Types::kPDERS, "PDERS",
                           "!H:!V:NormTree=T:VolumeRangeMode=Adaptive:KernelEstimator=Gauss:GaussSigma=0.3:NEventsMin=400:NEventsMax=600" );

   if (Use["PDERSD"])
      factory->BookMethod( TMVA::Types::kPDERS, "PDERSD",
                           "!H:!V:VolumeRangeMode=Adaptive:KernelEstimator=Gauss:GaussSigma=0.3:NEventsMin=400:NEventsMax=600:VarTransform=Decorrelate" );

   if (Use["PDERSPCA"])
      factory->BookMethod( TMVA::Types::kPDERS, "PDERSPCA",
                           "!H:!V:VolumeRangeMode=Adaptive:KernelEstimator=Gauss:GaussSigma=0.3:NEventsMin=400:NEventsMax=600:VarTransform=PCA" );

   // Multi-dimensional likelihood estimator using self-adapting phase-space binning
   if (Use["PDEFoam"])
      factory->BookMethod( TMVA::Types::kPDEFoam, "PDEFoam",
                           "!H:!V:SigBgSeparate=F:TailCut=0.001:VolFrac=0.0666:nActiveCells=500:nSampl=2000:nBin=5:Nmin=100:Kernel=None:Compress=T" );

   if (Use["PDEFoamBoost"])
      factory->BookMethod( TMVA::Types::kPDEFoam, "PDEFoamBoost",
                           "!H:!V:Boost_Num=30:Boost_Transform=linear:SigBgSeparate=F:MaxDepth=4:UseYesNoCell=T:DTLogic=MisClassificationError:FillFoamWithOrigWeights=F:TailCut=0:nActiveCells=500:nBin=20:Nmin=400:Kernel=None:Compress=T" );

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

   // H-Matrix (chi2-squared) method
   if (Use["HMatrix"])
      factory->BookMethod( TMVA::Types::kHMatrix, "HMatrix", "!H:!V:VarTransform=None" );

   // Linear discriminant (same as Fisher discriminant)
   if (Use["LD"])
      factory->BookMethod( TMVA::Types::kLD, "LD", "H:!V:VarTransform=None:CreateMVAPdfs:PDFInterpolMVAPdf=Spline2:NbinsMVAPdf=50:NsmoothMVAPdf=10" );

   // Fisher discriminant (same as LD)
   if (Use["Fisher"])
      factory->BookMethod( TMVA::Types::kFisher, "Fisher", "H:!V:Fisher:VarTransform=None:CreateMVAPdfs:PDFInterpolMVAPdf=Spline2:NbinsMVAPdf=50:NsmoothMVAPdf=10" );

   // Fisher with Gauss-transformed input variables
   if (Use["FisherG"])
      factory->BookMethod( TMVA::Types::kFisher, "FisherG", "H:!V:VarTransform=Gauss" );

   // Composite classifier: ensemble (tree) of boosted Fisher classifiers
   if (Use["BoostedFisher"])
      factory->BookMethod( TMVA::Types::kFisher, "BoostedFisher", 
                           "H:!V:Boost_Num=20:Boost_Transform=log:Boost_Type=AdaBoost:Boost_AdaBoostBeta=0.2:!Boost_DetailedMonitoring" );

   // 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+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=MC:SampleSize=100000:Sigma=0.1" );

   if (Use["FDA_GA"]) // can also use Simulated Annealing (SA) algorithm (see Cuts_SA options])
      factory->BookMethod( TMVA::Types::kFDA, "FDA_GA",
                           "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=GA:PopSize=300:Cycles=3:Steps=20:Trim=True:SaveBestGen=1" );

   if (Use["FDA_SA"]) // can also use Simulated Annealing (SA) algorithm (see Cuts_SA options])
      factory->BookMethod( TMVA::Types::kFDA, "FDA_SA",
                           "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=SA:MaxCalls=15000:KernelTemp=IncAdaptive:InitialTemp=1e+6:MinTemp=1e-6:Eps=1e-10:UseDefaultScale" );

   if (Use["FDA_MT"])
      factory->BookMethod( TMVA::Types::kFDA, "FDA_MT",
                           "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-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+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=GA:Converger=MINUIT:ErrorLevel=1:PrintLevel=-1:FitStrategy=0:!UseImprove:!UseMinos:SetBatch:Cycles=1:PopSize=5:Steps=5:Trim" );

   if (Use["FDA_MCMT"])
      factory->BookMethod( TMVA::Types::kFDA, "FDA_MCMT",
                           "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=MC:Converger=MINUIT:ErrorLevel=1:PrintLevel=-1:FitStrategy=0:!UseImprove:!UseMinos:SetBatch:SampleSize=20" );

   // TMVA ANN: MLP (recommended ANN) -- all ANNs in TMVA are Multilayer Perceptrons
   if (Use["MLP"])
      factory->BookMethod( TMVA::Types::kMLP, "MLP", "H:!V:NeuronType=tanh:VarTransform=N:NCycles=600:HiddenLayers=N+5:TestRate=5:!UseRegulator" );

   if (Use["MLPBFGS"])
      factory->BookMethod( TMVA::Types::kMLP, "MLPBFGS", "H:!V:NeuronType=tanh:VarTransform=N:NCycles=600:HiddenLayers=N+5:TestRate=5:TrainingMethod=BFGS:!UseRegulator" );

   if (Use["MLPBNN"])
      factory->BookMethod( TMVA::Types::kMLP, "MLPBNN", "H:!V:NeuronType=tanh:VarTransform=N:NCycles=600:HiddenLayers=N+5:TestRate=5:TrainingMethod=BFGS:UseRegulator" ); // BFGS training with bayesian regulators

   // CF(Clermont-Ferrand)ANN
   if (Use["CFMlpANN"])
      factory->BookMethod( TMVA::Types::kCFMlpANN, "CFMlpANN", "!H:!V:NCycles=2000:HiddenLayers=N+1,N"  ); // n_cycles:#nodes:#nodes:...  

   // Tmlp(Root)ANN
   if (Use["TMlpANN"])
      factory->BookMethod( TMVA::Types::kTMlpANN, "TMlpANN", "!H:!V:NCycles=200:HiddenLayers=N+1,N:LearningMethod=BFGS:ValidationFraction=0.3"  ); // n_cycles:#nodes:#nodes:...

   // 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["BDTG"]) // Gradient Boost
      factory->BookMethod( TMVA::Types::kBDT, "BDTG",
                           "!H:!V:NTrees=1000:MinNodeSize=2.5%:BoostType=Grad:Shrinkage=0.10:UseBaggedBoost:BaggedSampleFraction=0.5:nCuts=20:MaxDepth=2" );

   if (Use["BDT"])  // Adaptive Boost
      factory->BookMethod( TMVA::Types::kBDT, "BDT",
                           "!H:!V:NTrees=850:MinNodeSize=2.5%:MaxDepth=3:BoostType=AdaBoost:AdaBoostBeta=0.5:UseBaggedBoost:BaggedSampleFraction=0.5:SeparationType=GiniIndex:nCuts=20" );

   if (Use["BDTB"]) // Bagging
      factory->BookMethod( TMVA::Types::kBDT, "BDTB",
                           "!H:!V:NTrees=400:BoostType=Bagging:SeparationType=GiniIndex:nCuts=20" );

   if (Use["BDTD"]) // Decorrelation + Adaptive Boost
      factory->BookMethod( TMVA::Types::kBDT, "BDTD",
                           "!H:!V:NTrees=400:MinNodeSize=5%:MaxDepth=3:BoostType=AdaBoost:SeparationType=GiniIndex:nCuts=20:VarTransform=Decorrelate" );

   if (Use["BDTF"])  // Allow Using Fisher discriminant in node splitting for (strong) linearly correlated variables
      factory->BookMethod( TMVA::Types::kBDT, "BDTMitFisher",
                           "!H:!V:NTrees=50:MinNodeSize=2.5%:UseFisherCuts:MaxDepth=3:BoostType=AdaBoost:AdaBoostBeta=0.5:SeparationType=GiniIndex:nCuts=20" );

   // RuleFit -- TMVA implementation of Friedman's method
   if (Use["RuleFit"])
      factory->BookMethod( TMVA::Types::kRuleFit, "RuleFit",
                           "H:!V:RuleFitModule=RFTMVA:Model=ModRuleLinear:MinImp=0.001:RuleMinDist=0.001:NTrees=20:fEventsMin=0.01:fEventsMax=0.5:GDTau=-1.0:GDTauPrec=0.01:GDStep=0.01:GDNSteps=10000:GDErrScale=1.02" );

   // For an example of the category classifier usage, see: TMVAClassificationCategory

   // -----------------------------------------------------------------------------------------

   // ---- Now you can optimize the setting (configuration) of the MVAs using the set of training events

   // ---- STILL EXPERIMENTAL and only implemented for BDT's ! 
   // factory->OptimizeAllMethods("SigEffAt001","Scan");
   // factory->OptimizeAllMethods("ROCIntegral","FitGA");

   // -----------------------------------------------------------------------------------------

   // ---- 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 << "==> TMVAClassification is done!" << std::endl;

   delete factory;

   // Launch the GUI for the root macros
   if (!gROOT->IsBatch()) TMVAGui( outfileName );
}
Пример #21
0
cpad2->SetFillColor(0);
cpad2->Draw();

TPad* cpad3 = new TPad("cpad3","cpad3",0.02, 0.02,0.48,0.48,4);
cpad3->SetFillColor(0);
cpad3->Draw();

TPad* cpad4 = new TPad("cpad4","cpad4",0.52,0.02,0.98,0.48,4);
cpad4->SetFillColor(0);
cpad4->Draw();


cpad4->cd();


TH1F* nh1 = (TH1F*)f.Get("ChrisAnalyzer/Photons/photonUnderMeasured");
nh1->SetLineWidth(2);
nh1->SetTitle("Photon p_{t}");
nh1->GetXaxis()->SetTitle("p_{t}");
nh1->Draw("histo");
c->Update();


cpad1->cd();

TH1F* nh2 = (TH1F*)f.Get("ChrisAnalyzer/Photons/electronUnderMeasured");
nh2->SetLineWidth(2);
nh2->SetTitle("Electron p_{t}");
nh2->GetXaxis()->SetTitle("p_{t}");
nh2->Draw("histo");
c->Update();
Пример #22
0
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();

}
void draw_Efficiencies_singleStage() {

  gStyle->SetOptTitle(0); 
  //gStyle->SetOptStat(1110); 
  gStyle->SetOptStat(0000); 
  //gStyle->SetOptFit(1); 
  gStyle->SetOptFit(0); 
  //gStyle->SetErrorX(0); 

  // inputs
  TFile *input    = new TFile("myOutputFileH4.root");  

  TGraphAsymmErrors *effSee = (TGraphAsymmErrors*)input->Get("effSee");
  TGraphAsymmErrors *effMgO_PadA = (TGraphAsymmErrors*)input->Get("effMgO_PadA");
  TGraphAsymmErrors *effMgO_PadB = (TGraphAsymmErrors*)input->Get("effMgO_PadB");
  TGraphAsymmErrors *effMgO_PadC = (TGraphAsymmErrors*)input->Get("effMgO_PadC");
  TGraphAsymmErrors *effMgO_PadD = (TGraphAsymmErrors*)input->Get("effMgO_PadD");

  TGraphAsymmErrors *effMgO = new TGraphAsymmErrors();
  
  std::vector<std::vector<double> > mean;
  mean.resize(effMgO_PadA->GetN());
  std::vector<std::vector<double> > error_up;
  error_up.resize(effMgO_PadA->GetN());
  std::vector<std::vector<double> > error_down;
  error_down.resize(effMgO_PadA->GetN());

  for(int ii = 0; ii<effMgO_PadA->GetN(); ii++)
  {
      double x,y;
      double errorUp, errorDown;

      effMgO_PadA->GetPoint(ii,x,y);
      mean.at(ii).push_back(y);
      error_up.at(ii).push_back(effMgO_PadA->GetErrorYhigh(ii));
      error_down.at(ii).push_back(effMgO_PadA->GetErrorYlow(ii));

      effMgO_PadB->GetPoint(ii,x,y);
      mean.at(ii).push_back(y);
      error_up.at(ii).push_back(effMgO_PadB->GetErrorYhigh(ii));
      error_down.at(ii).push_back(effMgO_PadB->GetErrorYlow(ii));

      effMgO_PadC->GetPoint(ii,x,y);
      mean.at(ii).push_back(y);
      error_up.at(ii).push_back(effMgO_PadC->GetErrorYhigh(ii));
      error_down.at(ii).push_back(effMgO_PadC->GetErrorYlow(ii));

      effMgO_PadD->GetPoint(ii,x,y);
      mean.at(ii).push_back(y);
      error_up.at(ii).push_back(effMgO_PadD->GetErrorYhigh(ii));
      error_down.at(ii).push_back(effMgO_PadD->GetErrorYlow(ii));
  }

  for(int ii = 0; ii<effMgO_PadA->GetN(); ii++)
  {
      float Mean = computeStat( mean.at(ii), error_up.at(ii), error_down.at(ii)).first;
      float Error_up = computeStat( mean.at(ii), error_up.at(ii), error_down.at(ii)).second.first;
      float Error_down = computeStat( mean.at(ii), error_up.at(ii), error_down.at(ii)).second.second;
        
      double x,y;
      effMgO_PadA->GetPoint(ii,x,y);
      effMgO->SetPoint(ii,x,Mean);
  }

  // inputsH4
  TFile *inputH4    = new TFile("myOutputFileH4.root");  

  TGraphAsymmErrors *effZS2Corr  = (TGraphAsymmErrors*)inputH4->Get("effZS2Corr");
  TGraphAsymmErrors *effMib3Corr = (TGraphAsymmErrors*)inputH4->Get("effMib3Corr");
  TGraphAsymmErrors *effZS2PMTCorr = (TGraphAsymmErrors*)inputH4->Get("effZS2PMTCorr");
 
  TF1* f1 = new TF1("f1",fitfunc,1000.,3200.,4);
  f1->SetParameters(0.2,0.1,1.,1450.);  
  f1->SetParLimits(1,0.,1.);
  f1->SetParLimits(3,1400.,1450.);
  //f1->FixParameter(0,0.);
  f1->SetLineColor(kCyan+2);
  f1->SetLineStyle(7);
  f1->SetLineWidth(2);
  effSee->Fit("f1","BR");

  TF1* f2 = new TF1("f2",fitfunc,1000.,3200.,4);
  f2->SetParameters(0.2,0.1,1.,2100.);  
  f2->SetParLimits(1,0.,1.);
  f2->SetParLimits(3,2000.,2100.);
  f2->FixParameter(0,0.);
  f2->SetLineColor(kGreen+2);
  f2->SetLineStyle(8);
  f2->SetLineWidth(2);
  effMgO->Fit("f2","BR");

  TF1* f3 = new TF1("f3",fitfunc,1300.,3200.,4);
  f3->SetParameters(0.2,1.,1.,2250.);  
  f3->SetParLimits(1,0.,1.);
  f3->SetParLimits(3,1800.,2250.);
  //f3->FixParameter(0,0.);
  f3->SetLineColor(kViolet+1);
  f3->SetLineStyle(7);
  f3->SetLineWidth(2);
  effZS2Corr->Fit("f3","BR");

  TF1* f4 = new TF1("f4",fitfunc,1300.,3200.,4);
  f4->SetParameters(0.2,1.,1.,2000.);  
  f4->SetParLimits(1,0.,1.);
  f4->SetParLimits(3,1800.,2050.);
  //f4->FixParameter(0,0.);
  f4->SetLineColor(kRed+2);
  f4->SetLineStyle(8);
  f4->SetLineWidth(2);
  effMib3Corr->Fit("f4","BR");

  TF1* f5 = new TF1("f5",fitfunc2,0.8,2.,3);
  f5->SetLineColor(kOrange+1);  
  f5->SetLineStyle(6);
  f5->SetLineWidth(2);
  f5->SetParameters(1.,1.,1.,1.); 
  f5->SetParLimits(0,0.,1.); 
  //f5->SetParLimits(1,0.,1.); 
  f5->SetParLimits(2,-3500,-1000.); 
  effZS2PMTCorr->Fit("f5","B");

  // cosmetics
  effSee->SetMarkerStyle(24);
  effSee->SetMarkerColor(kCyan+2);
  effSee->SetLineColor(kCyan+2);  
  effSee->SetLineStyle(4);
  effSee->SetLineWidth(2);
  effSee->SetMarkerSize(1.1);

  effMgO->SetMarkerStyle(25);
  effMgO->SetMarkerColor(kGreen+2);
  effMgO->SetLineColor(kGreen+2);  
  effMgO->SetLineStyle(5);
  effMgO->SetLineWidth(2);
  effMgO->SetMarkerSize(1.1);

  effZS2Corr->SetMarkerStyle(26);
  effZS2Corr->SetMarkerColor(kViolet+1);
  effZS2Corr->SetLineColor(kViolet+1);
  effZS2Corr->SetLineStyle(6);
  effZS2Corr->SetLineWidth(2);
  effZS2Corr->SetMarkerSize(1.3);

  effMib3Corr->SetMarkerStyle(32);
  effMib3Corr->SetMarkerColor(kRed+2);
  effMib3Corr->SetLineColor(kRed+2);
  effMib3Corr->SetLineStyle(7);
  effMib3Corr->SetLineWidth(2);
  effMib3Corr->SetMarkerSize(1.3);

  effZS2PMTCorr->SetMarkerStyle(33);
  effZS2PMTCorr->SetMarkerColor(kOrange+1);
  effZS2PMTCorr->SetLineColor(kOrange+1);  
  effZS2PMTCorr->SetLineStyle(8);
  effZS2PMTCorr->SetLineWidth(2);
  effZS2PMTCorr->SetMarkerSize(1.7);

  // plotting
  setStyle();

  TH2F* H2 = new TH2F("H2","",2300,1000.,3300.,100,0.,1.35);
  H2->GetXaxis()->SetTitle("MCP-stack bias (V)");
  H2->GetYaxis()->SetTitle("Efficiency");
  H2->GetXaxis()->SetNdivisions(505);

  TLine *line = new TLine(1000,1,3300,1);

  TLegend *legA;
  legA = new TLegend(0.23,0.75,0.43,0.90);
  legA->SetFillStyle(0);
  legA->SetBorderSize(0);
  legA->SetTextSize(0.03);
  legA->SetFillColor(0);
  legA->AddEntry(effMib3Corr,  "40x2 iMCP", "pl");
  legA->AddEntry(effSee,  "40x2 SEE-iMCP", "pl");
  legA->AddEntry(effMgO,  "40x2 MgO-iMCP, 150 GeV muons", "pl");

  TLegend *legB;
  legB = new TLegend(0.68,0.77,0.88,0.90);
  legB->SetFillStyle(0);
  legB->SetBorderSize(0);
  legB->SetTextSize(0.03);
  legB->SetFillColor(0);
  legB->AddEntry(effZS2Corr,  "40x3 iMCP", "pl");
  legB->AddEntry(effZS2PMTCorr,  "40x3 PMT-MCP", "pl");

  TCanvas* c1 = new TCanvas("c1","c",1);
  FPCanvasStyle(c1);
  H2->Draw();
  line->Draw();
  effZS2PMTCorr->Draw("Psame");
  effSee->Draw("Psame");
  effMgO->Draw("Psame");
  effZS2Corr->Draw("Psame");
  effMib3Corr->Draw("Psame");
  //c1->RedrawAxis("sameaxis");
  legA->Draw("same");
  legB->Draw("same");
  TLatex latex2(0.705, 0.94,"#bf{#bf{50 GeV electrons}}");;
  latex2.SetTextSize(0.04);
  latex2.SetNDC(kTRUE);
  latex2.Draw(); 
  c1->SaveAs("summaryEff_singleStage.png");
  c1->SaveAs("summaryEff_singleStage.pdf");
}
Пример #24
0
void makePlots_eff()
{
  gROOT->ProcessLine(" .L style.cc+");
  style();

  vector<string> list;
  list.push_back(string("Epos"));
  list.push_back(string("Hijing"));
  list.push_back(string("QGSJetII"));
  vector<string> name;
  name.push_back(string("EPOS-LHC"));
  name.push_back(string("HIJING 1.383"));
  name.push_back(string("QGSJetII-04"));

  TCanvas* c1 = new TCanvas;
  TCanvas* c2 = new TCanvas;
  TCanvas* c3 = new TCanvas;
  TCanvas* c4 = new TCanvas;

  TLegend* legan = new TLegend(0.23,0.23,0.43,0.45);
  TLegend* legeff = new TLegend(0.23,0.71,0.43,0.93);
  TLegend* legpas = new TLegend(0.23,0.23,0.43,0.38);
  SetLegAtt(legan,1.5);
  SetLegAtt(legeff,1.5);
  SetLegAtt(legpas,1.5);
  for(int i=0; i<int(list.size()); i++)
    {
      cout << i+1 << "/" << int(list.size()) << endl;
      TFile* file = TFile::Open("histos_test.root");

      TH1D* h_eff=file->Get(string(list[i]+string("/")+list[i]+string("_h_mc_eff")).c_str());
      TH1D* h_effgain_single=file->Get(string(list[i]+string("/")+list[i]+string("_h_mc_effgain_single")).c_str());
      TH1D* h_effgain_double=file->Get(string(list[i]+string("/")+list[i]+string("_h_mc_effgain_double")).c_str());

      int colour = kBlack;
      int marker = 21;
      if(list[i] == string("Epos"))
        {
         colour = kGreen-1;
         marker = 22;
        }
      if(list[i] == string("QGSJetII"))
        {
         colour = kBlue;
         marker = 34;
        }

      SetAttributes(h_eff,colour,marker);
      SetAttributes(h_effgain_single,colour,marker);
      SetAttributes(h_effgain_double,colour,marker);

      h_effgain_single->Scale(1./double(h_eff->GetBinContent(1)));
      h_effgain_double->Scale(1./double(h_eff->GetBinContent(1)));
      h_eff->Scale(1./double(h_eff->GetBinContent(1))); //order important

      h_eff->GetXaxis()->LabelsOption("u");
      h_effgain_single->GetXaxis()->LabelsOption("u");
      h_effgain_double->GetXaxis()->LabelsOption("u");

      h_eff->GetYaxis()->SetRangeUser(0.8,1.01);
      h_effgain_single->GetYaxis()->SetRangeUser(0.0,0.15);
      h_effgain_double->GetYaxis()->SetRangeUser(0.0,0.15);

      h_eff->SetTitle(name[i].c_str());
      h_effgain_single->SetTitle(name[i].c_str());
      h_effgain_double->SetTitle(name[i].c_str());

      h_eff->SetTitle(";;selection efficiency");
      h_effgain_single->SetTitle(";;selection efficiency gain");
      h_effgain_double->SetTitle(";;selection efficiency gain");

      legan->AddEntry(h_eff,name[i].c_str(),"p");
      legeff->AddEntry(h_eff,name[i].c_str(),"p");
      if(list[i] != string("Hijing"))
        legpas->AddEntry(h_eff,name[i].c_str(),"p");

      c1->cd();
      h_eff->Draw(i<1?"HIST P":"HIST P SAME");

      c2->cd();
      h_effgain_single->Draw(i<1?"HIST P":"HIST P SAME");

      c3->cd();
      h_effgain_double->Draw(i<1?"HIST P":"HIST P SAME");

      c4->cd();
      TH1D* h_eff2=h_eff->Clone((string("h_eff")+list[i]).c_str());
      h_eff2->GetXaxis()->SetRange(1,h_eff->GetNbinsX()-1);
      if(list[i] != string("Hijing"))
        h_eff2->Draw(i<1?"HIST P":"HIST P SAME");
    }
  c1->cd();
  CMSText(0,0,1);
  legan->Draw();
  c1->SaveAs((string("plots/mc_eff")+string(".pdf")).c_str());

  c2->cd();
  CMSText(0,0,1);
  legeff->Draw();
  c2->SaveAs((string("plots/mc_effgain_single")+string(".pdf")).c_str());

  c3->cd();
  CMSText(0,0,1);
  legeff->Draw();
  c3->SaveAs((string("plots/mc_effgain_double")+string(".pdf")).c_str());

  c4->cd();
  CMSText(0,0,1);
  legpas->Draw();
  c4->SaveAs((string("plots/mc_eff")+string("_PAS.pdf")).c_str());
}
Пример #25
0
int testRandom3() {

  Float_t RefValue[] = // running using a seed of 4357 ROOT 5.13.07 and checked with GSL 1.8
     {  0.999741749, 0.162909875, 0.282617805, 0.947201082, 0.231656543, 0.484973614, 0.957476957, 0.744305343,
        0.540043658, 0.739952981, 0.759943798, 0.658636614, 0.315637622, 0.804403015, 0.519672115, 0.168572422,
        0.47552973, 0.392313994, 0.221667687, 0.213190459,0.0303352042,  0.33353925, 0.194148851, 0.943716781,
        0.579931675, 0.898304858, 0.665563931,  0.49861031, 0.560628257, 0.182284646, 0.296525531, 0.117408933,
        0.0629176658, 0.648125575, 0.725418529, 0.637131158, 0.713885062,0.0995762432, 0.699267196,  0.10781247,
        0.129242751, 0.502403039, 0.207779906, 0.288910306,0.0831747944, 0.128124215, 0.547371411,0.0823195996,
        0.292141427, 0.891623737, 0.227117839, 0.431845463, 0.140733001, 0.400392135, 0.686946901, 0.170670911,
        0.440820868, 0.045336565, 0.311296414, 0.506181051,  0.18241084, 0.511032015, 0.740788205, 0.365988627,
        0.160808837, 0.460106785, 0.627836472, 0.677603688, 0.698196523, 0.478536868,0.0901075942, 0.338728522,
        0.0952137967, 0.436541964, 0.474673352, 0.419245926, 0.777536852, 0.624610565,  0.98043655, 0.370430201,
        0.830812636, 0.140806447, 0.744085307,  0.82973968, 0.391104318, 0.621956392, 0.346699478,0.0461695245,
        0.613066321, 0.567374048, 0.498894026, 0.723802079, 0.144550525,0.0423031633, 0.310787023, 0.121641154,
        0.242069671, 0.381058855, 0.440128537, 0.599795902, 0.644574654, 0.432626217, 0.555968262, 0.716841168,
        0.642362515, 0.685776725,0.0961581462, 0.122933464,0.0569974151, 0.820072044, 0.125539286, 0.315745071,
        0.180566925, 0.142227219, 0.664429613, 0.685189223, 0.191001933, 0.436343019, 0.964459225,  0.86816359,
        0.130879965,  0.48444228, 0.374654451, 0.900475122, 0.178656787, 0.679635131,  0.62287431,  0.98365595,
        0.44071478, 0.804737277, 0.994845061, 0.541550961, 0.255905455, 0.638945635,  0.57591027,  0.25872142,
        0.191593001, 0.445663047, 0.149266509, 0.996723689, 0.121762222,  0.65153928,0.0277950978, 0.389977602,
        0.827913044, 0.283813907, 0.610203644,  0.23641275,  0.41082105, 0.677714617, 0.847126588, 0.649256228,
        0.0813826511, 0.120830484, 0.479199264, 0.777878358, 0.471977701, 0.943337511, 0.980800992, 0.334554731,
        0.202667924, 0.342841234, 0.653544244, 0.682758797,  0.60993614,0.0999271029, 0.766254981, 0.735581528,
        0.24113914, 0.263178711, 0.960869899, 0.423395737, 0.336058146,0.000249497825, 0.868841017,0.00375315035,
        0.165846311,0.0118208411, 0.606455074, 0.729972019, 0.613824557, 0.965768184, 0.497098261, 0.529885403,
        0.461607532, 0.713033701, 0.579959768, 0.682802555, 0.953921514,0.0236552036, 0.280110147, 0.869526353,
        0.299333274, 0.319553603, 0.300951709, 0.941111486, 0.848127064, 0.753346129, 0.538244087, 0.408481381,
        0.212371316,0.0761404021, 0.289934908,0.0197818337, 0.241247899, 0.384619165, 0.454906886, 0.373982521,
        0.440188796, 0.117896808, 0.805429845, 0.164892641, 0.282529936, 0.172685399,  0.93584233,  0.68095306,
        0.133696739, 0.254761223, 0.399444876, 0.369235365, 0.726361892, 0.277837459, 0.693569104, 0.500354689,
        0.118405538, 0.151303335, 0.681446943, 0.720665918, 0.979646939, 0.696779111, 0.557210072, 0.680821482,
        0.95535205, 0.598208956, 0.770453895, 0.913597486, 0.658958649, 0.670974613, 0.578185175,  0.95303929,
        0.162923458, 0.335056986, 0.951824704, 0.109661644, 0.619302303, 0.956816742, 0.985243094,0.0707377489,
        0.50233039, 0.680721226, 0.553320066, 0.587005581, 0.691620562,  0.46264791, 0.574254294, 0.072890088,
        0.638266518, 0.387757288, 0.220960217,0.00223180233, 0.495656775, 0.191316523, 0.022265008, 0.903589021,
        0.738628175,  0.44453089, 0.417702243, 0.760861122, 0.437753222, 0.190982861, 0.577112962, 0.132688343,
        0.317824347,  0.48691649, 0.939091069, 0.933946281, 0.073660135, 0.612436295, 0.514748724, 0.624663582,
        0.130645262, 0.645210441,  0.13414855, 0.652925968, 0.265210009, 0.381805269,  0.59021506, 0.669704082,
        0.55433248,0.0195047602, 0.184346962, 0.991180462, 0.573677764, 0.637762085, 0.594857598, 0.515244688,
        0.330693509,  0.39674245,  0.88396548, 0.771485266, 0.599075381,0.0247266297,0.0122587895, 0.698452319,
        0.265991009, 0.736700721, 0.999972619, 0.749792316, 0.484955589, 0.823700529,  0.62277709, 0.902512094,
        0.0565051287, 0.739077389,  0.37617622, 0.036800765, 0.776198219, 0.837354186,  0.34508193,0.0818426476,
        0.222621545, 0.152476319, 0.401177195, 0.531612608, 0.811706602,0.0407775661, 0.117889008, 0.575189965,
        0.832362208, 0.204641853, 0.238721773,   0.9969287, 0.258590596, 0.892055968, 0.846859788, 0.306583706,
        0.0333624918, 0.706420498, 0.193615608, 0.508978138,0.0215451468, 0.672732793, 0.813562444, 0.807284052,
        0.481526843, 0.537519095, 0.780848606, 0.335848908, 0.699259371, 0.425855299, 0.825240663, 0.945613692,
        0.55484125, 0.710495188, 0.378360366, 0.648338731,0.0456727168, 0.155477323, 0.885353968, 0.721565725,
        0.961667201, 0.430300885, 0.132031354, 0.439331209, 0.467187736, 0.410083217, 0.277196711, 0.278509559,
        0.954620806, 0.804357491, 0.968510466, 0.999722791, 0.947160283, 0.248551138,0.0067049861, 0.444727315,
        0.674048778, 0.496480361,0.0210092501, 0.831763222, 0.108545852,0.0931516394,  0.89020564, 0.445945211,
        0.906906768, 0.554039821, 0.759434349, 0.815551384, 0.532968503,0.0551351462,0.0539856541,  0.89918819,
        0.146907374, 0.482647314,0.0673029809, 0.281161865, 0.932849165, 0.507317933, 0.564503014,   0.8007132,
        0.645887499, 0.309219498,0.0478066066,  0.25196583, 0.713881142, 0.670994017,  0.60528576, 0.148271899,
        0.79525035, 0.665277353, 0.854302043, 0.810533677,0.0711439839,0.0687935678, 0.890466573, 0.758045957,
        0.0703105873, 0.852094478, 0.775356902, 0.684895203, 0.234552787, 0.461575694, 0.936435457, 0.664946419,
        0.45967959,  0.88782351, 0.574622261,0.0301686234, 0.767354721, 0.345478555, 0.609123143,  0.21754287,
        0.643760561, 0.571392649, 0.802311049, 0.962335547, 0.401769856, 0.996553418, 0.745945812, 0.448411183,
        0.39578428, 0.123389926, 0.532614913, 0.833379602,  0.91767313, 0.825607567,   0.4459154, 0.267136201,
        0.6643989, 0.766860694, 0.665968275, 0.503955105, 0.835153702, 0.622405379, 0.457538918, 0.554983278,
        0.36581371, 0.656302231, 0.917038669, 0.276054591, 0.121214441, 0.966178254, 0.697439008, 0.443547789,
        0.630195824, 0.368346675, 0.238191956, 0.300273821, 0.710332172,0.0474748381, 0.492525443,0.0812539798,
        0.122016782,  0.99310218, 0.355091027, 0.764863731, 0.904099543, 0.396109613, 0.817134856, 0.348974222,
        0.266193634, 0.367501958, 0.752316213, 0.587800024, 0.489421095, 0.673474061, 0.328296139, 0.853945839,
        0.832380736, 0.159588686, 0.322411022, 0.950173707, 0.095376712, 0.231019855, 0.860607752, 0.359627192,
        0.984843699,0.0319756679, 0.828649914,  0.51680949, 0.489407924, 0.963977298, 0.960131739, 0.681816791,
        0.860788169, 0.455829282, 0.332390656,0.0591498043, 0.452245977, 0.217354216,  0.34560744, 0.549971993,
        0.317622252, 0.892976443,  0.49004545,  0.25647901, 0.968998638, 0.910636465, 0.226717598, 0.327828572,
        0.28670209, 0.142515054,0.0992817392, 0.192332409, 0.308376869, 0.871415959, 0.391148786, 0.788660882,
        0.200816041, 0.986475959, 0.882862126, 0.109862451, 0.354283255, 0.555742682, 0.690698458, 0.643815752,
        0.363104285,0.0788627111, 0.200820414,  0.71697353, 0.744353746,  0.76763643, 0.245442451, 0.668009119,
        0.886989377, 0.366849931, 0.531556628, 0.502843979,  0.31454367, 0.622541364,0.0199038582, 0.676355134,
        0.429818622, 0.232835212, 0.987619457, 0.306572135, 0.494637038, 0.748614893, 0.891843561,0.0452854959,
        0.427561072, 0.226978442, 0.484072985,  0.16464563,0.0898074883, 0.384263737,0.0238354723, 0.329734547,
        0.531230736, 0.476683361, 0.877482474, 0.455501628, 0.497302495, 0.396184301, 0.886124728, 0.736070092,
        0.108917595, 0.397921902, 0.842575021,  0.82620032, 0.936655165,  0.24558961, 0.639688616, 0.493335031,
        0.0734495069, 0.780138101,0.0421121232, 0.701116477, 0.940523267,  0.70054817, 0.776760272, 0.192742581,
        0.0069252688, 0.842983626, 0.919324176, 0.242083269, 0.190100674, 0.735084639, 0.164522319,  0.99030645,
        0.98284794, 0.657169539,0.0187736442, 0.759596482, 0.357567611, 0.509016344, 0.738899681, 0.567923164,
        0.289056634,  0.41501714, 0.981054561, 0.365884479, 0.517878261, 0.844209022, 0.968122653, 0.258894528,
        0.478310441, 0.437340986, 0.379398001, 0.203081884, 0.550820748, 0.255542723, 0.550098031, 0.870477939,
        0.241230214, 0.157108238, 0.218260827, 0.116277737, 0.749018275, 0.158290659, 0.476353907, 0.545327323,
        0.878978121,0.0171442169, 0.542981987, 0.318018082, 0.788805343, 0.871721374, 0.738490409,0.0923330146,
        0.301398643, 0.637103286, 0.571564271, 0.712810342, 0.644289242, 0.230476008, 0.971695586, 0.966159428,
        0.291883909, 0.175285818, 0.312882552,  0.98465128, 0.568391354, 0.844468564, 0.144433908,  0.45994061,
        0.607897905, 0.184122705, 0.342805493, 0.606432998, 0.838196585, 0.186188518,0.0302744689, 0.307391858,
        0.125286029, 0.270394965, 0.874161481, 0.370509557,  0.89423337, 0.407995674, 0.881878469, 0.647951238,
        0.236986727, 0.528807336, 0.293731542,0.0943204253, 0.934538626, 0.121679332,  0.34968176,0.0670268578,
        0.642196769, 0.692447138, 0.334926733, 0.374244194, 0.313885051, 0.538738295, 0.098592523, 0.490514225,
        0.32873567, 0.709725794,  0.88169803, 0.393000481, 0.854243273, 0.463776593,  0.52705639, 0.493309892,
        0.267784336, 0.583077476,0.0573514167, 0.959336368, 0.771417173,0.0427184631, 0.498433369,0.0522942701,
        0.56155145, 0.960361909, 0.619817314, 0.528628368, 0.698235179, 0.186162042, 0.553998168, 0.666120292,
        0.152731049, 0.948750157, 0.186825789, 0.580512664, 0.851024442, 0.106865844, 0.675861737,  0.79604524,
        0.657646103,0.00934952381, 0.206267588, 0.636420368,0.0382564603,  0.67771025, 0.677917925, 0.671684269,
        0.396317716, 0.661597047, 0.633360383, 0.962124239, 0.992711418,0.0993448263,0.0678932741, 0.426013152,
        0.947045502, 0.708326009, 0.466817846,0.0448362886, 0.748580922, 0.678370694, 0.210921343, 0.398490306,
        0.953675585,0.0289022848, 0.935766569, 0.846930474, 0.662760176, 0.867910903, 0.652359324,  0.45280494,
        0.305228982, 0.352034987, 0.279643402, 0.236045594,0.0270034608, 0.652062389, 0.712000227, 0.619930867,
        0.125439078, 0.452789963,  0.92233151, 0.120844359, 0.403808975, 0.260290446, 0.778843638,   0.6678412,
        0.0267894373, 0.491332301, 0.915060888, 0.704025347, 0.628200853, 0.578338467, 0.629156416, 0.730410649,
        0.641318334, 0.463709335, 0.614291239, 0.254470656, 0.808682692,  0.22898373, 0.450477996, 0.874235142,
        0.202773906, 0.523711192, 0.126518266, 0.579402899,  0.26188467, 0.207769057,  0.55283816, 0.851395364,
        0.513594437, 0.558259845, 0.666148535, 0.998974657, 0.178274074, 0.116739636,0.0684255431, 0.622713377,
        0.31448295, 0.889827933,  0.80647766, 0.429916949, 0.524695458,  0.45267553, 0.630743121, 0.566594485,
        0.958860663, 0.908052286, 0.700898262, 0.377025384, 0.683796226, 0.198088462, 0.617400699, 0.413726158,
        0.823588417, 0.755577948, 0.703097317, 0.364294278, 0.819786986, 0.751581763, 0.048769509, 0.528569003,
        0.616748192, 0.270942831, 0.800841747, 0.235174223, 0.903786552, 0.258801569, 0.191336412, 0.012410342,
        0.853413998, 0.621008712, 0.855861931, 0.140106201, 0.872687964, 0.708839735,0.0926409892,0.0207504195,
        0.782636518,0.0300825236, 0.504610632,0.0816221782, 0.773493745, 0.872577282, 0.880031248, 0.883524299,
        0.872427328, 0.458722225, 0.902298841, 0.547904952,0.0559884352, 0.591179888, 0.563941709, 0.776130076,
        0.295569778,0.0408536533, 0.398567183,  0.28227462, 0.806716321, 0.507159362, 0.688150965,  0.49466404,
        0.45454604, 0.421480091,0.0392517329,0.0911962031, 0.393815309, 0.135373195, 0.968650583, 0.811676111,
        0.325965411, 0.961999178, 0.100281202, 0.102924612,  0.30725909,  0.33368206, 0.857966134, 0.522921736,
        0.615500041, 0.981558684, 0.797484739, 0.198809674,  0.45670419, 0.570970797, 0.214908696, 0.686433314,
        0.278602115, 0.179739848, 0.397497946, 0.162858935, 0.802621762,0.0836459133, 0.638270752, 0.230856518,
        0.580094379, 0.864292514, 0.932738287, 0.821393124, 0.480590473, 0.636373016, 0.181508656, 0.469200501,
        0.309276441, 0.668810431, 0.722341161, 0.574856669, 0.527854513, 0.809231559, 0.986882661, 0.323860496,
        0.606396459, 0.759558966,  0.79096818,0.0699298142, 0.550465414,0.00929828244, 0.784629475, 0.689044114,
        0.963588091, 0.516441598, 0.357178305, 0.482336892, 0.429959602, 0.996306147, 0.601176011, 0.785004207,
        0.970542121, 0.487854549,0.0949267522, 0.979331773, 0.120877739, 0.630260336,  0.19424754, 0.213081703,
        0.0145987798, 0.366671115, 0.340100777, 0.721786347, 0.367533113,0.0210335371, 0.131687992, 0.586759676,
        0.73360464, 0.863635151, 0.136994646,0.0524269778, 0.406223408, 0.241656947, 0.472450703, 0.872215979,
        0.454719233,0.0715790696, 0.314061244, 0.492823114, 0.741721134, 0.694783663, 0.982867872, 0.319748137,
        0.804203704,0.0534678153, 0.746155348, 0.303474931,0.0930815139, 0.934531664, 0.746868186, 0.100048471,
        0.720296508,  0.21075374,  0.96309675, 0.749189411, 0.739621932, 0.510072327,0.0872929865, 0.650020469,
        0.0823648495, 0.726920745, 0.532618265, 0.749305866,  0.86126694,0.0346994482,0.0931224583, 0.655257095,
        0.959517847, 0.487057231, 0.859895745, 0.084794421, 0.718541715, 0.850918328, 0.818884782,  0.71627446,
        0.40822393,  0.63658567, 0.523838703, 0.372038872, 0.353426097, 0.598049047,0.0974868746, 0.276353038
     };

     Int_t rc1 = 0;
     Int_t rc2 = 0;
     TRandom3 r(4357);
     Float_t x;
     Int_t i;

     // check whether the sequence is ok or not
     for (i=0;i<1000;i++) {
       x = r.Rndm();
       // printf("%e ",x-RefValue[i]); if(i%8==7) printf("\n");
       if (TMath::Abs(x-RefValue[i]) > 10e-8) {
         printf("i=%d x=%.8f but should be %.8f\n",i,x,RefValue[i]);
         rc1 += 1;
       }
     }

     // check whether a state can be saved and restored
     TFile *file = new TFile("random3.root","RECREATE");
     file->SetCompressionLevel(0);
     r.Write("r");
     delete file;
     file = new TFile("random3.root");
     TRandom3 *rs = (TRandom3*) file->Get("r");
     for (i=0;i<1000;i++) {
       if (r.Rndm() - rs->Rndm() != 0) rc2 += 1;
     }
     if (rc2 != 0) printf("state restoration failed\n");

     return rc1 + rc2;
}
Пример #26
0
	Double_t dxs;

} TChanData;
TChanData tcd[352];

typedef struct {
	Int_t mid;
	Double_t lo;
	Double_t hi;
} ThetaBins;
ThetaBins theta[10];

Double_t pa = 0.0833;

TFile full( "histograms/FullPi0.root");
TH1D *hfsc = (TH1D*)full.Get( "SumScalers152to503");
TH1D *hdf = (TH1D*)full.Get( "SumScalers504to535");

TFile empty( "histograms/EmptyPi0.root");
TH1D *hesc = (TH1D*)empty.Get( "SumScalers152to503");
TH1D *hde = (TH1D*)empty.Get( "SumScalers504to535");

TH1D* fhist;
TH1D* ehist;
TH1D* shist;

void Init()
{
	gROOT->ProcessLine( ".L ReadParams.C");
	ReadTagEng( "xs/tageng855.dat");
Пример #27
0
forSync_ee() {

  ofstream fout; 
  TString decay="ElEl";
//  TString sample="ZJets";
  TString sample="TTbarTuneZ2";
  fout.open(decay+"_"+sample+".txt"); 
//  fout.open(decay+"_"+sample+"_ALL.txt"); 

  TFile* f = TFile::Open("./"+decay+"/vallot_"+sample+".root");
//  TFile* f = TFile::Open("./"+decay+"/vallot_"+sample+"_ALL.root");
  TTree* tree = (TTree*)f->Get("ElEl/tree");

  bool scan=true;
  double step0, step1, step2, step3, step4, step5;
  TCut cut0 = "";
  TCut cut1 = "ZMass > 12 && relIso1 < 0.17 && relIso2 < 0.17 && PairSign < 0 && pt1 > 20 && pt2 > 20";
  TCut cut2 = cut1 && "abs(ZMass - 91.2) > 15";  
  TCut cut3 = cut2 && "@jetspt30.size() >= 2";  
  TCut cut4 = cut3 && "MET > 30";  
  TCut cut5 = cut4 && "nbjets_CSVL >= 1";  

/*  step0=tree->GetEntries();
  step1=tree->GetEntries("ZMass > 12 && relIso1 < 0.2 && relIso2 < 0.2 && PairSign < 0 && pt1 > 20 && pt2 > 20");
  step2=tree->GetEntries("ZMass > 12 && relIso1 < 0.2 && relIso2 < 0.2 && PairSign < 0 && pt1 > 20 && pt2 > 20 && abs(ZMass - 91.2) > 15");
  step3=tree->GetEntries("ZMass > 12 && relIso1 < 0.2 && relIso2 < 0.2 && PairSign < 0 && pt1 > 20 && pt2 > 20 && abs(ZMass - 91.2) > 15 && @jetspt30.size() >= 2");
  step4=tree->GetEntries("ZMass > 12 && relIso1 < 0.2 && relIso2 < 0.2 && PairSign < 0 && pt1 > 20 && pt2 > 20 && abs(ZMass - 91.2) > 15 && @jetspt30.size() >= 2 && MET > 30");
  step5=tree->GetEntries("ZMass > 12 && relIso1 < 0.2 && relIso2 < 0.2 && PairSign < 0 && pt1 > 20 && pt2 > 20 && abs(ZMass - 91.2) > 15 && @jetspt30.size() >= 2 && MET > 30 && nbjets_CSVL >= 1");
*/
  step0=tree->GetEntries();
  step1=tree->GetEntries(cut1);
  step2=tree->GetEntries(cut2);
  step3=tree->GetEntries(cut3);
  step4=tree->GetEntries(cut4);
  step5=tree->GetEntries(cut5);

  cout << "===================================================================================" << endl;
  cout << "Synchronization Exercise with MC  (Decay channel = "+decay+", Sample = "+sample+") " << endl;
  cout << "===================================================================================" << endl;
  cout << "Cut at step1 ; " << "ZMass > 12 && relIso1 < 0.17 && relIso2 < 0.17 && PairSign < 0 && pt1 > 20 && pt2 > 20" << endl;
  cout << "Cut at step2 ; " << "Cut at step1 + && abs(ZMass - 91.2) > 15" << endl;
  cout << "Cut at step3 ; " << "Cut at step2 + && @jetspt30.size() >= 2 " << endl;
  cout << "Cut at step4 ; " << "Cut at step3 + && MET > 30" << endl;
  cout << "Cut at step5 ; " << "Cut at step4 + && nbjets_CSVL >= 1" << endl;
  cout << "===================================================================================" << endl;
  cout << "Step0 = " << step0 << endl; 
  cout << "Step1 = " << step1 << endl; 
  cout << "Step2 = " << step2 << endl; 
  cout << "Step3 = " << step3 << endl; 
  cout << "Step4 = " << step4 << endl; 
  cout << "Step5 = " << step5 << endl; 
  cout << "===================================================================================" << endl;

  if (scan==true) {
    cout << tree->Scan("RUN:LUMI:EVENT:ZMass:@jetspt30.size():MET:nbjets_CSVL",cut4) << endl; 
  }

  fout << "===================================================================================" << endl;
  fout << "Synchronization Exercise with MC  (Decay channel = "+decay+", Sample = "+sample+") " << endl;
  fout << "===================================================================================" << endl;
  fout << "Cut at step1 ; " << "ZMass > 12 && relIso1 < 0.17 && relIso2 < 0.17 && PairSign < 0 && pt1 > 20 && pt2 > 20" << endl;
  fout << "Cut at step2 ; " << "Cut at step1 + && abs(ZMass - 91.2) > 15" << endl;
  fout << "Cut at step3 ; " << "Cut at step2 + && @jetspt30.size() >= 2 " << endl;
  fout << "Cut at step4 ; " << "Cut at step3 + && MET > 30" << endl;
  fout << "Cut at step5 ; " << "Cut at step4 + && nbjets_CSVL >= 1" << endl;
  fout << "===================================================================================" << endl;
  fout << "Step0 = " << step0 << endl; 
  fout << "Step1 = " << step1 << endl; 
  fout << "Step2 = " << step2 << endl; 
  fout << "Step3 = " << step3 << endl; 
  fout << "Step4 = " << step4 << endl; 
  fout << "Step5 = " << step5 << endl; 
  fout << "===================================================================================" << endl;
  fout << "" << endl;
  fout << "" << endl;

  if (scan==true) {
    const string tmpFileName = decay+"_"+sample+"_tmp.txt";
    ((TTreePlayer*)(tree->GetPlayer()))->SetScanRedirect(true);
    ((TTreePlayer*)(tree->GetPlayer()))->SetScanFileName(tmpFileName.c_str());
    tree->Scan("RUN:LUMI:EVENT:ZMass:@jetspt30.size():MET:pt1:pt2",cut1);
    ((TTreePlayer*)(tree->GetPlayer()))->SetScanRedirect(false);
  }

  fout.close();
}
Пример #28
0
void Pi0Hist3D( UInt_t chan, UInt_t tbin, TString var_y)
{
	UInt_t cbin, tbin_lo, tbin_hi;
	TString name;
	TString var_x, var_z;
	TString hprompt, hrand;

	var_x = "TChan";
	var_z = "ThetaCM";

	hprompt = var_z + "P_v_" + var_y + "P_v_" + var_x + "P";
	hrand = var_z + "R_v_" + var_y + "R_v_" + var_x + "R";

	// Target FULL
	// Prompt
	TH3D *hP = (TH3D*)full.Get( hprompt);
	cbin = hP->GetXaxis()->FindBin( chan);
	hP->GetXaxis()->SetRange( cbin, cbin);
	tbin_lo = hP->GetZaxis()->FindBin( theta[tbin].lo);
	tbin_hi = hP->GetZaxis()->FindBin( theta[tbin].hi)-1;
	hP->GetZaxis()->SetRange( tbin_lo, tbin_hi);
	TH1D *hPf_y = hP->Project3D( "y");

	// Random
	TH3D *hR = (TH3D*)full.Get( hrand);
	hR->GetXaxis()->SetRange( cbin, cbin);
	hR->GetZaxis()->SetRange( tbin_lo, tbin_hi);
	TH1D *hRf_y = hR->Project3D( "y2");
	hRf_y->Scale( pa);

	// Subtracted
	hSf = (TH1D*) hPf_y->Clone( "FullSubt");
	hSf->Sumw2();
	hSf->Add( hRf_y, -1.0);

	// Target EMPTY
	// Prompt
	TH3D *hP = (TH3D*)empty.Get( hprompt);
	hP->GetXaxis()->SetRange( cbin, cbin);
	hP->GetZaxis()->SetRange( tbin_lo, tbin_hi);
	TH1D *hPe_y = hP->Project3D( "y");

	// Random
	TH3D *hR = (TH3D*)empty.Get( hrand);
	hR->GetXaxis()->SetRange( cbin, cbin);
	hR->GetZaxis()->SetRange( tbin_lo, tbin_hi);
	TH1D *hRe_y = hR->Project3D( "y2");
	hRe_y->Scale( pa);

	// Subtracted
	hSe = (TH1D*) hPe_y->Clone( "EmptySubt");
	hSe->Sumw2();
	hSe->Add( hRe_y, -1.0);

	// COMPLETELY SUBTRACTED
	Double_t f_tagg_f, f_tot_f, f_dead_f, fscal;
	Double_t f_tagg_e, f_tot_e, f_dead_e, escal;
	Double_t factor;

	f_tagg_f = hdf->GetBinContent( 32)/hdf->GetBinContent( 31);
	f_tot_f = hdf->GetBinContent( 25)/hdf->GetBinContent( 26);
	f_dead_f = f_tagg_f/f_tot_f;
	fscal = hfsc->GetBinContent( chan)*f_dead_f;
//	fscal = hfsc->GetBinContent( chan);

	f_tagg_e = hde->GetBinContent( 32)/hde->GetBinContent( 31);
	f_tot_e = hde->GetBinContent( 25)/hde->GetBinContent( 26);
	f_dead_e = f_tagg_e/f_tot_e;
	escal = hesc->GetBinContent( chan)*f_dead_e;
//	escal = hesc->GetBinContent( chan);

	factor = escal/fscal;
	hSf->Scale( factor);
	hS = (TH1D*) hSf->Clone( "Subtracted");
	hS->Add( hSe, -1.0);

	fhist = (TH1D*) hSf->Clone( "Full");
	ehist = (TH1D*) hSe->Clone( "Empty");
	shist = (TH1D*) hS->Clone( "Subt");
}
Пример #29
0
void compareEfficiencies() {
  TCanvas *cv =0;
  TLegend *legend =0;

  TFile *fileTTJetsAMCAtNLO = new TFile("Efficiency_PromptMuon_TTJets_aMCAtNLO_25ns_MiniIsoCut.root","READ");
  TFile *fileTTJetsMadgraph = new TFile("Efficiency_PromptMuon_TTJets_25ns_MiniIsoCut.root","READ");
  TFile *fileTTJetsHT2500ToInf = new TFile("Efficiency_PromptMuon_TTJetsHT2500ToInf_25ns_MiniIsoCut.root","READ");
  TFile *fileTTJetsHT600To800 = new TFile("Efficiency_PromptMuon_TTJetsHT600To800_25ns_MiniIsoCut.root","READ");
  TFile *fileWJetsHT2500ToInf = new TFile("Efficiency_PromptMuon_WJetsHT2500ToInf_25ns_MiniIsoCut.root","READ");
  TFile *fileWJetsHT400To600 = new TFile("Efficiency_PromptMuon_WJetsHT400To600_25ns_MiniIsoCut.root","READ");
  TFile *fileDYJetsHT600ToInf = new TFile("Efficiency_PromptMuon_DYJetsHT600ToInf_25ns_MiniIsoCut.root","READ");
  TFile *fileDYJetsHT200To400 = new TFile("Efficiency_PromptMuon_DYJetsHT200To400_25ns_MiniIsoCut.root","READ");

  TFile *fileTTJetsMadgraphAll = new TFile("Efficiency_PromptMuon_TTJetsMadgraphAll_25ns_MiniIsoCut.root","READ");
  TFile *fileWJetsMadgraphAll = new TFile("Efficiency_PromptMuon_WJetsMadgraphAll_25ns_MiniIsoCut.root","READ");
  TFile *fileDYJetsMadgraphAll = new TFile("Efficiency_PromptMuon_DYJetsMadgraphAll_25ns_MiniIsoCut.root","READ");


  TH2F* effTTJetsAMCAtNLO = (TH2F*)fileTTJetsAMCAtNLO->Get("Efficiency_PtActivity");
  TH2F* effTTJetsMadgraph = (TH2F*)fileTTJetsMadgraph->Get("Efficiency_PtActivity");
  TH2F* effTTJetsHT2500ToInf = (TH2F*)fileTTJetsHT2500ToInf->Get("Efficiency_PtActivity");
  TH2F* effTTJetsHT600To800 = (TH2F*)fileTTJetsHT600To800->Get("Efficiency_PtActivity");
  TH2F* effWJetsHT2500ToInf = (TH2F*)fileWJetsHT2500ToInf->Get("Efficiency_PtActivity");
  TH2F* effWJetsHT400To600 = (TH2F*)fileWJetsHT400To600->Get("Efficiency_PtActivity");
  TH2F* effDYJetsHT600ToInf = (TH2F*)fileDYJetsHT600ToInf->Get("Efficiency_PtActivity");
  TH2F* effDYJetsHT200To400 = (TH2F*)fileDYJetsHT200To400->Get("Efficiency_PtActivity");
  TH2F* effTTJetsMadgraphAll = (TH2F*)fileTTJetsMadgraphAll->Get("Efficiency_PtActivity");
  TH2F* effWJetsMadgraphAll = (TH2F*)fileWJetsMadgraphAll->Get("Efficiency_PtActivity");
  TH2F* effDYJetsMadgraphAll = (TH2F*)fileDYJetsMadgraphAll->Get("Efficiency_PtActivity");

  TH2F* effDifferenceRatio_TTJets_DifferentHTBins = compareEfficiency( effTTJetsHT600To800 , effTTJetsHT2500ToInf , false);
  TH2F* effDifferenceSigmas_TTJets_DifferentHTBins = compareEfficiency( effTTJetsHT600To800 , effTTJetsHT2500ToInf, true );
  TH2F* effDifferenceRatio_WJets_DifferentHTBins = compareEfficiency( effWJetsHT400To600 , effWJetsHT2500ToInf , false);
  TH2F* effDifferenceSigmas_WJets_DifferentHTBins = compareEfficiency( effWJetsHT400To600 , effWJetsHT2500ToInf, true );
  TH2F* effDifferenceRatio_DYJets_DifferentHTBins = compareEfficiency( effDYJetsHT200To400 , effDYJetsHT600ToInf , false);
  TH2F* effDifferenceSigmas_DYJets_DifferentHTBins = compareEfficiency( effDYJetsHT200To400 , effDYJetsHT600ToInf, true );

  TH2F* effDifferenceRatio_TTJetsVsDYJets = compareEfficiency( effTTJetsMadgraphAll , effDYJetsMadgraphAll , false);
  TH2F* effDifferenceSigmas_TTJetsVsDYJets = compareEfficiency( effTTJetsMadgraphAll, effDYJetsMadgraphAll, true );
  TH2F* effDifferenceRatio_WJetsVsDYJets = compareEfficiency( effWJetsMadgraphAll , effDYJetsMadgraphAll , false);
  TH2F* effDifferenceSigmas_WJetsVsDYJets = compareEfficiency( effWJetsMadgraphAll, effDYJetsMadgraphAll, true );

  TH2F* effDifferenceRatio_NLO = compareEfficiency( effTTJetsAMCAtNLO , effTTJetsMadgraph , false);
  TH2F* effDifferenceSigmas_NLO = compareEfficiency( effTTJetsAMCAtNLO , effTTJetsMadgraph, true );

  //color palette
  const Int_t Number = 5;
  Double_t Red[Number]    =  { 0.00, 0.85, 1.00, 1.00, 1.00};
  Double_t Green[Number]  =  { 0.00, 0.85, 1.00, 0.85, 0.00};
  Double_t Blue[Number]   =  { 1.00, 1.00, 1.00, 0.85, 0.00};
  Double_t Length[Number] =  { 0.00, 0.2 , 0.5,  0.8 , 1.00};
  Int_t nb=200;
  TColor::CreateGradientColorTable(Number,Length,Red,Green,Blue,nb);
  gStyle->SetPaintTextFormat("4.2f");

  //**************************************************
  //TTJets HT Bins
  //**************************************************

  cv = new TCanvas("cv","cv", 800,600);

  effDifferenceRatio_TTJets_DifferentHTBins->Draw("colz,text");
  effDifferenceRatio_TTJets_DifferentHTBins->SetStats(0);
  effDifferenceRatio_TTJets_DifferentHTBins->SetMaximum(0.2);
  effDifferenceRatio_TTJets_DifferentHTBins->SetMinimum(-0.2);
  cv->SetLogy();
  cv->SetLogx();
  cv->SaveAs("MuonMiniIsoEfficiency_TTJets_CompareHTBins_Ratio.gif");


  cv = new TCanvas("cv","cv", 800,600);

  effDifferenceSigmas_TTJets_DifferentHTBins->Draw("colz,text");
  effDifferenceSigmas_TTJets_DifferentHTBins->SetStats(0);
  effDifferenceSigmas_TTJets_DifferentHTBins->SetMaximum(5);
  effDifferenceSigmas_TTJets_DifferentHTBins->SetMinimum(-5);
  cv->SetLogy();
  cv->SetLogx();
  cv->SaveAs("MuonMiniIsoEfficiency_TTJets_CompareHTBins_Sigmas.gif");



  //**************************************************
  //TTJets NLO
  //**************************************************

  cv = new TCanvas("cv","cv", 800,600);

  effDifferenceRatio_NLO->Draw("colz,text");
  effDifferenceRatio_NLO->SetStats(0);
  effDifferenceRatio_NLO->SetMaximum(0.2);
  effDifferenceRatio_NLO->SetMinimum(-0.2);
  cv->SetLogy();
  cv->SetLogx();
  cv->SaveAs("MuonMiniIsoEfficiency_NLO_Ratio.gif");


  cv = new TCanvas("cv","cv", 800,600);

  effDifferenceSigmas_NLO->Draw("colz,text");
  effDifferenceSigmas_NLO->SetStats(0);
  effDifferenceSigmas_NLO->SetMaximum(5);
  effDifferenceSigmas_NLO->SetMinimum(-5);
  cv->SetLogy();
  cv->SetLogx();
  cv->SaveAs("MuonMiniIsoEfficiency_NLO_Sigmas.gif");

  //**************************************************
  //WJets HT Bins
  //**************************************************

  cv = new TCanvas("cv","cv", 800,600);

  effDifferenceRatio_WJets_DifferentHTBins->Draw("colz,text");
  effDifferenceRatio_WJets_DifferentHTBins->SetStats(0);
  effDifferenceRatio_WJets_DifferentHTBins->SetMaximum(0.2);
  effDifferenceRatio_WJets_DifferentHTBins->SetMinimum(-0.2);
  cv->SetLogy();
  cv->SetLogx();
  cv->SaveAs("MuonMiniIsoEfficiency_WJets_CompareHTBins_Ratio.gif");


  cv = new TCanvas("cv","cv", 800,600);

  effDifferenceSigmas_WJets_DifferentHTBins->Draw("colz,text");
  effDifferenceSigmas_WJets_DifferentHTBins->SetStats(0);
  effDifferenceSigmas_WJets_DifferentHTBins->SetMaximum(5);
  effDifferenceSigmas_WJets_DifferentHTBins->SetMinimum(-5);
  cv->SetLogy();
  cv->SetLogx();
  cv->SaveAs("MuonMiniIsoEfficiency_WJets_CompareHTBins_Sigmas.gif");


  //**************************************************
  //DYJets HT Bins
  //**************************************************

  cv = new TCanvas("cv","cv", 800,600);

  effDifferenceRatio_DYJets_DifferentHTBins->Draw("colz,text");
  effDifferenceRatio_DYJets_DifferentHTBins->SetStats(0);
  effDifferenceRatio_DYJets_DifferentHTBins->SetMaximum(0.2);
  effDifferenceRatio_DYJets_DifferentHTBins->SetMinimum(-0.2);
  cv->SetLogy();
  cv->SetLogx();
  cv->SaveAs("MuonMiniIsoEfficiency_DYJets_CompareHTBins_Ratio.gif");


  cv = new TCanvas("cv","cv", 800,600);

  effDifferenceSigmas_DYJets_DifferentHTBins->Draw("colz,text");
  effDifferenceSigmas_DYJets_DifferentHTBins->SetStats(0);
  effDifferenceSigmas_DYJets_DifferentHTBins->SetMaximum(5);
  effDifferenceSigmas_DYJets_DifferentHTBins->SetMinimum(-5);
  cv->SetLogy();
  cv->SetLogx();
  cv->SaveAs("MuonMiniIsoEfficiency_DYJets_CompareHTBins_Sigmas.gif");


  //**************************************************
  //Compare TTJets vs DY
  //**************************************************

  cv = new TCanvas("cv","cv", 800,600);

  effDifferenceRatio_TTJetsVsDYJets->Draw("colz,text");
  effDifferenceRatio_TTJetsVsDYJets->SetStats(0);
  effDifferenceRatio_TTJetsVsDYJets->SetMaximum(0.2);
  effDifferenceRatio_TTJetsVsDYJets->SetMinimum(-0.2);
  cv->SetLogy();
  cv->SetLogx();
  cv->SaveAs("MuonMiniIsoEfficiency_TTJetsVsDYJets_Ratio.gif");


  cv = new TCanvas("cv","cv", 800,600);

  effDifferenceSigmas_TTJetsVsDYJets->Draw("colz,text");
  effDifferenceSigmas_TTJetsVsDYJets->SetStats(0);
  effDifferenceSigmas_TTJetsVsDYJets->SetMaximum(5);
  effDifferenceSigmas_TTJetsVsDYJets->SetMinimum(-5);
  cv->SetLogy();
  cv->SetLogx();
  cv->SaveAs("MuonMiniIsoEfficiency_TTJetsVsDYJets_Sigmas.gif");

  //**************************************************
  //Compare WJets vs DY
  //**************************************************

  cv = new TCanvas("cv","cv", 800,600);

  effDifferenceRatio_WJetsVsDYJets->Draw("colz,text");
  effDifferenceRatio_WJetsVsDYJets->SetStats(0);
  effDifferenceRatio_WJetsVsDYJets->SetMaximum(0.2);
  effDifferenceRatio_WJetsVsDYJets->SetMinimum(-0.2);
  cv->SetLogy();
  cv->SetLogx();
  cv->SaveAs("MuonMiniIsoEfficiency_WJetsVsDYJets_Ratio.gif");


  cv = new TCanvas("cv","cv", 800,600);

  effDifferenceSigmas_WJetsVsDYJets->Draw("colz,text");
  effDifferenceSigmas_WJetsVsDYJets->SetStats(0);
  effDifferenceSigmas_WJetsVsDYJets->SetMaximum(5);
  effDifferenceSigmas_WJetsVsDYJets->SetMinimum(-5);
  cv->SetLogy();
  cv->SetLogx();
  cv->SaveAs("MuonMiniIsoEfficiency_WJetsVsDYJets_Sigmas.gif");



}
Пример #30
0
 void drawintlen_DBD(char* FILEN) {

   //char* title = "Material budget for ILD_O1_v05" ;


   double M_PI = 3.14159265358979312e+00 ;
   //   180./pi = 57.295779 ;
   
   //ntuple variables
   //   float theta, nrvxd, nrsit, nrtpc, nrset, thedeg;
   //   float theta, nlyoke,nlcoil,nlhcal,nlecal,nlset
   Float_t thedeg,theta,eta,nlset,nlecal,nlhcal,nlcoil,nlyoke ; 

   // stuff for histograms
   const int nhist = 5;
   TString htitle[nhist];
   htitle[0] = "Ecal (Lcal)";
   htitle[1] = "Hcal (LHcal/bcal)";
   htitle[2] = "Coil";
   htitle[3] = "";
   htitle[4] = "dummy";
   TString hname[nhist];
   hname[0] = "ECAL";
   hname[1] = "HCAL";
   hname[2] = "SIT";
   hname[3] = "VTX";
   hname[4] = "dummy";

   int nbin = 180;
   float xmin = -90;
   float xmax = -0;
   //   int color[nhist] = {9,8,2,38,1};
   int color[nhist] = {8,2,38,1,9};
   TString option[nhist];

   option[0] = "same";
   option[1] = "same";
   option[2] = "";
   option[3] = "";
   option[4] = "";
      
   //  TLegend *leg = new TLegend (0.25, 0.6, 0.5, 0.85);
  TLegend *leg = new TLegend (0.25, 0.3, 0.6, 0.55);
  leg->SetFillStyle(0);
  
  // stuff for histograms
  TH1F* hmat[nhist];

  for (int ihist = 0; ihist < nhist; ihist++) {

    hmat[ihist] = new TH1F(hname[ihist],"",nbin,xmin,xmax);
    //// ensure proper errors
    // hmat[ihist]->Sumw2();
    hmat[ihist]->SetLineColor(color[ihist]);
    hmat[ihist]->SetLineWidth(3);
    hmat[ihist]->SetTitle(";#theta / degrees;Interaction Lengths");
  }
  
  
  // read tree
  TFile* file = new TFile ( FILEN ) ;
  TTree* tree = (TTree *) file->Get("ntuple");
  if (!tree) {
    cout << "ERROR: Couldn't open tree ntuple on file: "<< FILEN << endl;
    return 1; 
  }
  
  tree->SetBranchAddress("theta", &theta);
  tree->SetBranchAddress("thedeg",&thedeg);
  tree->SetBranchAddress("nlset", &nlset);
  tree->SetBranchAddress("nlecal", &nlecal);
  tree->SetBranchAddress("nlhcal", &nlhcal);
  tree->SetBranchAddress("nlcoil", &nlcoil);
  tree->SetBranchAddress("nlyoke", &nlyoke);
  int entries = tree->GetEntries();
    cout << "tree has " << entries << " entries" << endl;
  
  // event loop
  for (int ievt = 0; ievt < entries; ++ievt) {
     tree->GetEntry(ievt);

     //,     if (thedeg < 4.41) continue;  // ???

     hmat[0]->Fill(-thedeg,nlecal);
     hmat[1]->Fill(-thedeg,nlhcal);
     hmat[2]->Fill(-thedeg,nlcoil);
     hmat[3]->Fill(-thedeg,nlyoke);
     hmat[4]->Fill(-thedeg,1);
  }
  
  //   for (int ibin = 0; ibin < nbin+1; ++ibin) {
  //     cout << "Bin " << ibin << " has " << hmat[4]->GetBinContent(ibin) << " entries" << endl;
//   }
  
  c1 = new TCanvas("c1","c1",600,600);
  
  
  hmat[2]->GetYaxis()->SetRangeUser(0.,14.) ;

  //  for (int ihist = 0; ihist < nhist-2; ihist++) {
  for (int ihist = nhist-3 ; ihist >=0 ; --ihist) {
    // average double counts 
    hmat[ihist]->Divide( hmat[4] ) ;
    // draw 

    hmat[ihist]->Draw(option[ihist]);


    if( ihist ==  nhist-3 ){
      c1->Update() ;
      TF1 *f1 = new TF1("f1","-x",0,90);
      hmat[ihist]->GetXaxis()->SetLabelOffset(99);
      Double_t x_min = c1->GetUxmin();
      Double_t x_max = c1->GetUxmax();
      Double_t y_min = c1->GetUymin();
      //std::cout << "x_min " << x_min << " x_max " << x_max << " y_min " << y_min << std::endl ;
      TGaxis *axis = new TGaxis( x_min, y_min, x_max, y_min, "f1", 5);    
      axis->SetLabelSize( 0.06 );
      axis->SetLabelFont( 42 ); 
      axis->Draw(); 
    }

    leg->AddEntry(hmat[ihist],htitle[ihist],"L");
  }
  leg->Draw();
  

  std::string pdfFile( std::string( FILEN ) + std::string( ".pdf" ) ) ;
  c1->Print( pdfFile.c_str() ) ;
  
}