void MeasureSmearing(TTree *Full, TTree *Fast,TString tag="",bool useElectrons=false) {
  //TChain *Full = loadList("/home/amott/HggApp/Hgg_53X/Caltech/Reduced/GluGluToHToGG_M-125_8TeV-powheg-pythia6_Summer12_DR53X-PU_S10_STAR53_V7A-v1.list","HggReduce");
  //TChain *Fast = loadList("/home/amott/HggApp/Hgg_53X/Caltech/Reduced/SMS-TChiHH_2b2g_2J_mChargino-130to500_mLSP-1to370_TuneZ2star_8TeV-madgraph-tauola__Summer12-START53_V19_FSIM-v1.list","HggReduce");
  
  Full->SetBranchStatus("*",0);
  if(useElectrons) Full->SetBranchStatus("Electrons.*",1);
  else Full->SetBranchStatus("Photons.*",1);

  Fast->SetBranchStatus("*",0);
  if(useElectrons) Fast->SetBranchStatus("Electrons.*",1);
  else Fast->SetBranchStatus("Photons.*",1);


  TString var = "Photons.correctedEnergy/Photons.genMatch.energy-1";
  if(useElectrons) var = "Electrons.correctedEnergy/Electrons.genMatch.energy-1";

  TString epVar = "Electrons.EOverP";
//   TString var_pho1 = "(pho1_pt*cosh(pho1_eta)-pho1_energyGen)/pho1_energyGen";
//   TString var_pho2 = "(pho2_pt*cosh(pho2_eta)-pho2_energyGen)/pho2_energyGen";

  TString FSIM_SCALE = "( (abs(Photons.SC.eta)<1.56)*1 + (abs(Photons.SC.eta)>=1.56 && abs(Photons.SC.eta)<2)*( (Photons.SC.r9>0.94)*1.0276 + (Photons.SC.r9<=0.94)*1.0195) + (abs(Photons.SC.eta)>=2. && abs(Photons.SC.eta)<2.5)*( (Photons.SC.r9>0.94)*1.0216 + (Photons.SC.r9<=0.94)*1.0330) )*";

  const int nCats=8;

   TString cats[nCats] = {
     "Photons.genMatch.index!=-1 && Photons.correctedEnergy/cosh(Photons.eta)>25 && abs(Photons.SC.eta)<1 && Photons.SC.r9>0.94",
     "Photons.genMatch.index!=-1 && Photons.correctedEnergy/cosh(Photons.eta)>25 && abs(Photons.SC.eta)>=1 && abs(Photons.SC.eta)<1.4442 && Photons.SC.r9>0.94",
     "Photons.genMatch.index!=-1 && Photons.correctedEnergy/cosh(Photons.eta)>25 && abs(Photons.SC.eta)>=1.56 && abs(Photons.SC.eta)<2 && Photons.SC.r9>0.94",
     "Photons.genMatch.index!=-1 && Photons.correctedEnergy/cosh(Photons.eta)>25 && abs(Photons.SC.eta)>=2 && abs(Photons.SC.eta)<2.5 && Photons.SC.r9>0.94",

     "Photons.genMatch.index!=-1 && Photons.correctedEnergy/cosh(Photons.eta)>25 && abs(Photons.SC.eta)<1 && Photons.SC.r9<0.94",
     "Photons.genMatch.index!=-1 && Photons.correctedEnergy/cosh(Photons.eta)>25 && abs(Photons.SC.eta)>=1 && abs(Photons.SC.eta)<1.4442 && Photons.SC.r9<0.94",
     "Photons.genMatch.index!=-1 && Photons.correctedEnergy/cosh(Photons.eta)>25 && abs(Photons.SC.eta)>=1.56 && abs(Photons.SC.eta)<2 && Photons.SC.r9<0.94",
     "Photons.genMatch.index!=-1 && Photons.correctedEnergy/cosh(Photons.eta)>25 && abs(Photons.SC.eta)>=2 && abs(Photons.SC.eta)<2.5 && Photons.SC.r9<0.94",
   };

   if(useElectrons) {
     FSIM_SCALE.ReplaceAll("Photons","Electrons");
     for(int i=0;i<nCats;i++) {
       cats[i].ReplaceAll("Photons","Electrons");
       std::cout << cats[i] << std::endl;
     }
   }

//   TString cats_pho1[nCats] = {
//     "pho1_genMatch==1 && pho1_pt>25 && abs(pho1_eta)>=0.00 && abs(pho1_eta)<1.000 && pho1_r9 > 0.94",
//     "pho1_genMatch==1 && pho1_pt>25 && abs(pho1_eta)>=1.00 && abs(pho1_eta)<1.442 && pho1_r9 > 0.94",
//     "pho1_genMatch==1 && pho1_pt>25 && abs(pho1_eta)>=1.56 && abs(pho1_eta)<2.000 && pho1_r9 > 0.94",
//     "pho1_genMatch==1 && pho1_pt>25 && abs(pho1_eta)>=2.00 && abs(pho1_eta)<2.500 && pho1_r9 > 0.94",

//     "pho1_genMatch==1 && pho1_pt>25 && abs(pho1_eta)>=0.00 && abs(pho1_eta)<1.000 && pho1_r9 <= 0.94",
//     "pho1_genMatch==1 && pho1_pt>25 && abs(pho1_eta)>=1.00 && abs(pho1_eta)<1.442 && pho1_r9 <= 0.94",
//     "pho1_genMatch==1 && pho1_pt>25 && abs(pho1_eta)>=1.56 && abs(pho1_eta)<2.000 && pho1_r9 <= 0.94",
//     "pho1_genMatch==1 && pho1_pt>25 && abs(pho1_eta)>=2.00 && abs(pho1_eta)<2.500 && pho1_r9 <= 0.94",
//   };

//   TString cats_pho2[nCats] = {
//     "pho2_genMatch==1 && pho2_pt>25 && abs(pho2_eta)>=0.00 && abs(pho2_eta)<1.000 && pho2_r9 > 0.94",
//     "pho2_genMatch==1 && pho2_pt>25 && abs(pho2_eta)>=1.00 && abs(pho2_eta)<1.442 && pho2_r9 > 0.94",
//     "pho2_genMatch==1 && pho2_pt>25 && abs(pho2_eta)>=1.56 && abs(pho2_eta)<2.000 && pho2_r9 > 0.94",
//     "pho2_genMatch==1 && pho2_pt>25 && abs(pho2_eta)>=2.00 && abs(pho2_eta)<2.500 && pho2_r9 > 0.94",

//     "pho2_genMatch==1 && pho2_pt>25 && abs(pho2_eta)>=0.00 && abs(pho2_eta)<1.000 && pho2_r9 <= 0.94",
//     "pho2_genMatch==1 && pho2_pt>25 && abs(pho2_eta)>=1.00 && abs(pho2_eta)<1.442 && pho2_r9 <= 0.94",
//     "pho2_genMatch==1 && pho2_pt>25 && abs(pho2_eta)>=1.56 && abs(pho2_eta)<2.000 && pho2_r9 <= 0.94",
//     "pho2_genMatch==1 && pho2_pt>25 && abs(pho2_eta)>=2.00 && abs(pho2_eta)<2.500 && pho2_r9 <= 0.94",
//   };

  TString catNames[nCats] = {
    "EBLow_Gold",
    "EBHigh_Gold",
    "EELow_Gold",
    "EEHigh_Gold",
    "EBLow_Bad",
    "EBHigh_Bad",
    "EELow_Bad",
    "EEHigh_Bad",
  };

  TCanvas cv;
  TH1D pt_full("pt_full","",80,0,400);
  pt_full.SetXTitle("p_{T} [GeV]");
  pt_full.SetYTitle("Events / 5 GeV");

  //Full->Project("pt_full","Photons.energy/cosh(Photons.eta)","Photons.genMatch.index != -1");

  TH1D pt_fast("pt_fast","",80,0,400);
  pt_fast.SetXTitle("p_{T} [GeV]");
  pt_fast.SetYTitle("Events / 5 GeV");

  //Fast->Project("pt_fast","Photons.energy/cosh(Photons.eta)","Photons.genMatch.index != -1");

  TH1D* ratio = (TH1D*)pt_fast.Clone("pt_ratio");
  ratio->Divide(&pt_full);



  TH1D h("h","",100,-0.2,0.2);
  TH1D h_p2("h_p2","",100,-0.2,0.2);
  h.SetXTitle("(E_{reco}-E_{MC})/E_{MC}");

  TH1D ep("ep","",200,0.6,1.4);
  ep.SetXTitle("E/p");

  for(int i=2;i<nCats;i++) {    
    std::cout << catNames[i] << std::endl;
    Full->Project("h",var,cats[i]);
//     Full->Project("h",var_pho1,cats_pho1[i]);
//     Full->Project("h_p2",var_pho2,cats_pho2[i]);
    //h.Add(&h_p2);
    std::pair<float,float> r_full = getFitRange(h);
    std::cout << "FullSIM fit range: " << r_full.first << " - " << r_full.second << std::endl;
    TF1 full_fit("full_fit",DoubleCrystalBall,-0.2,0.2,7);
    full_fit.SetParNames("#alpha_{1}","n_{1}","#alpha_{2}","n_{2}","Mean","#sigma","N");
    full_fit.SetParLimits(0,0.2,20);
    full_fit.SetParLimits(1,0.00001,100000);
    full_fit.SetParLimits(2,0.2,20);
    full_fit.SetParLimits(3,0.00001,100000);
    full_fit.SetParLimits(4,-0.1,0.1);
    full_fit.SetParLimits(5,0.001,1);
    full_fit.SetParameter(5,0.01);
    full_fit.SetParLimits(6,100,1e9);

    full_fit.SetParameter(0,1);
    full_fit.SetParameter(1,4);
    full_fit.SetParameter(2,1);
    full_fit.SetParameter(3,2);
    full_fit.SetParameter(4,0);
    full_fit.SetParameter(6,10000);
    //full_fit.FixParameter(6,h.Integral());

    h.Fit(&full_fit,"VEM");
    //h.Fit("gaus","","",r_full.first,r_full.second);
    h.Draw();
    cv.SaveAs("ValidationPlots/Smearing_FullSIM_"+catNames[i]+tag+".png");
    
    if(useElectrons && false) {
      Full->Project("ep",epVar,cats[i]);
      std::pair<float,float> r_ep_full = getFitRange(ep);
      std::cout << "FullSIM fit range: " << r_ep_full.first << " - " << r_ep_full.second << std::endl;      
      TF1 full_fit_ep("full_fit_ep",DoubleCrystalBall,0.6,1.4,7);
      full_fit_ep.SetParNames("#alpha_{1}","n_{1}","#alpha_{2}","n_{2}","Mean","#sigma","N");
      full_fit_ep.SetParLimits(0,0.2,20);
      full_fit_ep.SetParLimits(1,0.00001,100000);
      full_fit_ep.SetParLimits(2,0.2,20);
      full_fit_ep.SetParLimits(3,0.00001,100000);
      full_fit_ep.SetParLimits(4,0.9,1.1);
      full_fit_ep.SetParLimits(5,0.001,1);
      full_fit_ep.SetParameter(5,0.01);
      full_fit_ep.SetParLimits(6,100,1e9);
      full_fit_ep.SetParameter(6,h.Integral());

      full_fit_ep.SetParameter(0,1);
      full_fit_ep.SetParameter(1,4);
      full_fit_ep.SetParameter(2,1);
      full_fit_ep.SetParameter(3,2);
      full_fit_ep.SetParameter(4,1);
      full_fit_ep.SetParameter(6,10000);


      ep.Fit(&full_fit_ep,"VEMI");
      //ep.Fit("gaus","","",r_ep_full.first,r_ep_full.second);
      ep.Draw();
      cv.SaveAs("ValidationPlots/EP_FullSIM_"+catNames[i]+tag+".png");      
    }

    Fast->Project("h",var,cats[i]);
//     Fast->Project("h",var_pho1,cats_pho1[i]+" && m23 < 177.");
//     Fast->Project("h_p2",var_pho2,cats_pho2[i]+" && m23 < 175.");
    //h.Add(&h_p2);
    std::pair<float,float> r_fast = getFitRange(h);
    std::cout << "FastSIM fit range: " << r_fast.first << " - " << r_fast.second << std::endl;
    TF1 fast_fit("fast_fit",DoubleCrystalBall,-0.2,0.2,7);
    fast_fit.SetParNames("#alpha_{1}","n_{1}","#alpha_{2}","n_{2}","Mean","#sigma","N");
    fast_fit.SetParLimits(0,0.2,20);
    fast_fit.SetParLimits(1,0.00001,100000);
    fast_fit.SetParLimits(2,0.2,20);
    fast_fit.SetParLimits(3,0.00001,100000);
    fast_fit.SetParLimits(4,-0.08,0.08);
    fast_fit.SetParLimits(5,0.001,1);
    fast_fit.SetParameter(5,0.01);
    fast_fit.SetParLimits(6,100,1e9);
    fast_fit.SetParameter(6,h.Integral());

    fast_fit.SetParameter(0,1);
    fast_fit.SetParameter(1,4);
    fast_fit.SetParameter(2,1);
    fast_fit.SetParameter(3,2);
    fast_fit.SetParameter(4,0);
    fast_fit.SetParameter(6,10000);

    h.Fit(&fast_fit,"VEMI");
    //h.Fit("gaus","","",r_fast.first,r_fast.second);
    h.Draw();
    cv.SaveAs("ValidationPlots/Smearing_FastSIM_"+catNames[i]+tag+".png");    

    if(useElectrons) {
      Fast->Project("ep",epVar,cats[i]);
      std::pair<float,float> r_ep_fast = getFitRange(ep);
      std::cout << "FastSIM fit range: " << r_ep_fast.first << " - " << r_ep_fast.second << std::endl;      
      Full->Project("ep",epVar,cats[i]);
      std::pair<float,float> r_ep_full = getFitRange(ep);
      std::cout << "FullSIM fit range: " << r_ep_full.first << " - " << r_ep_full.second << std::endl;      

      TF1 fast_fit_ep("fast_fit_ep",DoubleCrystalBall,0.6,1.4,7);
      fast_fit_ep.SetParNames("#alpha_{1}","n_{1}","#alpha_{2}","n_{2}","Mean","#sigma","N");
      fast_fit_ep.SetParLimits(0,0.2,20);
      fast_fit_ep.SetParLimits(1,0.00001,100000);
      fast_fit_ep.SetParLimits(2,0.2,20);
      fast_fit_ep.SetParLimits(3,0.00001,100000);
      fast_fit_ep.SetParLimits(4,0.9,1.1);
      fast_fit_ep.SetParLimits(5,0.001,1);
      fast_fit_ep.SetParameter(5,0.01);
      fast_fit_ep.SetParLimits(6,100,1e9);
      fast_fit_ep.SetParameter(6,h.Integral());

      fast_fit_ep.SetParameter(0,1);
      fast_fit_ep.SetParameter(1,4);
      fast_fit_ep.SetParameter(2,1);
      fast_fit_ep.SetParameter(3,2);
      fast_fit_ep.SetParameter(4,1);
      fast_fit_ep.SetParameter(6,10000);


      ep.Fit(&fast_fit_ep,"VEMI");
      //ep.Fit("gaus","","",r_ep_fast.first,r_ep_fast.second);
      ep.Draw();
      cv.SaveAs("ValidationPlots/EP_FastSIM_"+catNames[i]+tag+".png");      
    }


    Fast->Project("h",FSIM_SCALE+var,cats[i]);
//     Fast->Project("h",var_pho1,cats_pho1[i]+" && m23 < 177.");
//     Fast->Project("h_p2",var_pho2,cats_pho2[i]+" && m23 < 175.");
    //h.Add(&h_p2);
    std::pair<float,float> r_fast_scale = getFitRange(h);
    std::cout << "Fast_ScaleSIM fit range: " << r_fast_scale.first << " - " << r_fast_scale.second << std::endl;
    TF1 fast_scale_fit("fast_scale_fit",DoubleCrystalBall,-0.2,0.2,7);
    fast_scale_fit.SetParNames("#alpha_{1}","n_{1}","#alpha_{2}","n_{2}","Mean","#sigma","N");
    fast_scale_fit.SetParLimits(0,0.2,20);
    fast_scale_fit.SetParLimits(1,0.00001,100000);
    fast_scale_fit.SetParLimits(2,0.2,20);
    fast_scale_fit.SetParLimits(3,0.00001,100000);
    fast_scale_fit.SetParLimits(4,-0.08,0.08);
    fast_scale_fit.SetParLimits(5,0.001,1);
    fast_scale_fit.SetParameter(5,0.01);
    fast_scale_fit.SetParLimits(6,100,1e9);
    fast_scale_fit.SetParameter(6,h.Integral());

    fast_scale_fit.SetParameter(0,1);
    fast_scale_fit.SetParameter(1,4);
    fast_scale_fit.SetParameter(2,1);
    fast_scale_fit.SetParameter(3,2);
    fast_scale_fit.SetParameter(4,0);
    fast_scale_fit.SetParameter(6,10000);

    h.Fit(&fast_scale_fit,"VEMI");
    //h.Fit("gaus","","",r_fast_scale.first,r_fast_scale.second);
    h.Draw();
    cv.SaveAs("ValidationPlots/Smearing_FastSIM_SCALED_"+catNames[i]+tag+".png");    

    if(useElectrons) {
      Fast->Project("ep",epVar,cats[i]);
      std::pair<float,float> r_ep_fast_scale = getFitRange(ep);
      std::cout << "Fast_ScaleSIM fit range: " << r_ep_fast_scale.first << " - " << r_ep_fast_scale.second << std::endl;      
      Full->Project("ep",epVar,cats[i]);
      std::pair<float,float> r_ep_full = getFitRange(ep);
      std::cout << "FullSIM fit range: " << r_ep_full.first << " - " << r_ep_full.second << std::endl;      

      TF1 fast_scale_fit_ep("fast_scale_fit_ep",DoubleCrystalBall,0.6,1.4,7);
      fast_scale_fit_ep.SetParNames("#alpha_{1}","n_{1}","#alpha_{2}","n_{2}","Mean","#sigma","N");
      fast_scale_fit_ep.SetParLimits(0,0.2,20);
      fast_scale_fit_ep.SetParLimits(1,0.00001,100000);
      fast_scale_fit_ep.SetParLimits(2,0.2,20);
      fast_scale_fit_ep.SetParLimits(3,0.00001,100000);
      fast_scale_fit_ep.SetParLimits(4,0.9,1.1);
      fast_scale_fit_ep.SetParLimits(5,0.001,1);
      fast_scale_fit_ep.SetParameter(5,0.01);
      fast_scale_fit_ep.SetParLimits(6,100,1e9);
      fast_scale_fit_ep.SetParameter(6,h.Integral());

      fast_scale_fit_ep.SetParameter(0,1);
      fast_scale_fit_ep.SetParameter(1,4);
      fast_scale_fit_ep.SetParameter(2,1);
      fast_scale_fit_ep.SetParameter(3,2);
      fast_scale_fit_ep.SetParameter(4,1);
      fast_scale_fit_ep.SetParameter(6,10000);

      ep.Fit(&fast_scale_fit_ep);
      //ep.Fit("gaus","","",r_ep_fast_scale.first,r_ep_fast_scale.second);
      ep.Draw();
      cv.SaveAs("ValidationPlots/EP_FastSIM_SCALED_"+catNames[i]+tag+".png");      
    }


  }
}
void savePlots2(const std::string& canvasName, TH1D& dataPlot, TH1D& fitPlot,
		TH1D& signalPlot, TH1D& bkgPlot) {
  TCanvas c(canvasName.c_str(), canvasName.c_str()) ;
  TPad mainPad("mainPad", "mainPad", 0., 0.2, 1., 1.) ;
  mainPad.Draw() ;
  TPad pullPad("pullPad", "pullPad", 0., 0., 1., 0.2) ;
  pullPad.Draw() ;

  mainPad.cd() ;
  dataPlot.SetStats(true) ;
  //dataPlot.SetOptStat(111111111);
  dataPlot.SetLineWidth(2) ;
  dataPlot.Draw() ;
  fitPlot.SetLineWidth(2) ;
  fitPlot.SetLineColor(kBlue) ;
  fitPlot.Draw("same") ;
  signalPlot.SetLineWidth(2) ;
  signalPlot.SetLineColor(kGreen) ;
  signalPlot.Draw("same") ;
  bkgPlot.SetLineColor(kRed) ;
  bkgPlot.SetLineWidth(2) ;
  bkgPlot.Draw("same") ;

  TLegend leg(0.6, 0.7, 0.9, 0.9) ;
  leg.AddEntry(&dataPlot, "Data") ;
  leg.AddEntry(&fitPlot, "Fit") ;
  leg.AddEntry(&signalPlot, "Signal") ;
  leg.AddEntry(&bkgPlot, "Background") ;
  leg.SetFillStyle(0) ;
  leg.SetBorderSize(0) ;
  leg.Draw() ;

  pullPad.cd() ;
  pullPad.SetGridy() ;
  TH1D* h_residuals(NULL), *h_pulls(NULL), *h_pullDistribution(NULL) ;
  FitterTools::makePullPlot(dataPlot, fitPlot, h_residuals, h_pulls, h_pullDistribution) ;
  h_pulls->Draw() ;

  c.Write() ;

  h_pulls->Write() ;
  delete h_pulls ;
  h_residuals->Write() ;
  delete h_residuals ;
  h_pullDistribution->Write() ;
  delete h_pullDistribution ;

  dataPlot.Write() ;
  fitPlot.Write() ;
}
Exemple #3
0
// *************************************** //
// this is a function that takes a set of  //
// histograms and draws them on a canvas   //
// in a stack, returning the canvas.       //
// It also plots the signal as a dashed    //
// line and the data with a ratio at the   //
// the bottom of data/allBackgrounds       //
// *************************************** //
TCanvas* drawPlots::plotAll(std::vector<TH1D*> histos, std::vector<std::string> names, std::string axisName, TH1D* signal, TH1D* data, TH1D* errDown, TH1D* errUp, bool isSignalRegion, bool doLogAxis){
         
   const unsigned int MAINPLOT_WIDTH  = 800;
   const unsigned int MAINPLOT_HEIGHT = 500;
   const unsigned int RATIOPLOT_HEIGHT = 125;
   const unsigned int OFFSET = 10;
   
  //LUKE: Title offset and title size are proportional in 
  //root, so you have to change them together, 
  //this makes me a sad panda 
   const double RATIOPLOT_YAXIS_TITLE_OFFSET = 0.4;
   const double RATIOPLOT_YAXIS_TITLE_SIZE   = 0.14;
   const double RATIOPLOT_YAXIS_TICK_LENGTH  = 0.01;
   const double RATIOPLOT_YAXIS_LABEL_SIZE   = 0.15;
  
   const double RATIOPLOT_XAXIS_TITLE_OFFSET = 0.9;
   const double RATIOPLOT_XAXIS_TITLE_SIZE   = 0.2;
   const double RATIOPLOT_XAXIS_TICK_LENGTH  = 0.05;
   const double RATIOPLOT_XAXIS_LABEL_SIZE   = 0.2;
   
   const double CANVAS_HEIGHT = MAINPLOT_HEIGHT+RATIOPLOT_HEIGHT+OFFSET;
   
   TCanvas* canvas = new TCanvas("canvas","canvas",0,0,MAINPLOT_WIDTH,CANVAS_HEIGHT);
   
   canvas->SetMargin(0.,0.,0.,0.);
   canvas->Clear();
   canvas->cd();
   
   // create main pad
   const double mainPad_ylow  = (CANVAS_HEIGHT - MAINPLOT_HEIGHT)/CANVAS_HEIGHT;
   const double mainPad_yhigh = 1.;
  
   const double pad_margin_left = 0.15;
   const double pad_margin_right  = 0.05;
   
   double main_y_max = -99;
   double main_y_min = -99;
   double main_x_max = -99;
   double main_x_min = -99;
   for(int a=0; a<histos.size(); a++){
     if(histos[a]){
       if(histos[a]->GetEntries()> 0.){
	 GetAxisLimits(histos[a], main_x_min, main_x_max, main_y_min, main_y_max);
       }
     }
   }
   
   if(data){
     int maxBinData = data->GetMaximumBin();
     double dataYmax = data->GetBinContent(maxBinData);
     if(dataYmax > main_y_max) main_y_max = dataYmax;
   }

   // create main pad
   TPad* mainPad = new TPad("main","main",0.,mainPad_ylow,1.,mainPad_yhigh);
   mainPad->SetMargin(pad_margin_left,pad_margin_right,0.,.05); // left, right, bottom, top
   mainPad->Draw();
   mainPad->cd();

   SetAtlasStyle();

   if(doLogAxis)mainPad->SetLogy();

   // clone signal or data because one should exist for each plot
   TH1D* allBackgrounds;
   bool gotSomething=false;
   if(signal)
     allBackgrounds = (TH1D*)signal->Clone("all_backgrounds");
   else if(data)
     allBackgrounds = (TH1D*)data->Clone("all_backgrounds");
   else{
     for(int b=0; b<histos.size(); b++){
       if(histos[b] && !gotSomething){
	 allBackgrounds = (TH1D*)histos[b]->Clone("all_backgrounds");
	 gotSomething=true;
       }
     }  
   }

   // set all bins to zero so that you can add all histograms to it
   for(int i=0; i<=allBackgrounds->GetNbinsX()+1; i++)
      allBackgrounds->SetBinContent(i,0);
   
   THStack* Stack = new THStack();
   std::string title = std::string(";") + axisName + ";Events";
   Stack->SetTitle(title.c_str());
   
   for(int b=0; b<histos.size(); b++){
     if(histos[b]){
       if(histos[b]->GetEntries() > 0.){
	 histos[b]->SetLineColor(1);
	 histos[b]->SetFillColor(tools::setColor(names[b]));
	 Stack->Add(histos[b]);
	 for(int j=0; j<=allBackgrounds->GetNbinsX()+1; j++){
	   double binContent=allBackgrounds->GetBinContent(j)+histos[b]->GetBinContent(j);
	   allBackgrounds->SetBinContent(j,binContent);
	 }
       }
     }
   }

   TH1D* backgroundsForRatio = (TH1D*)allBackgrounds->Clone("bkgds_for_ratio");
   
   if(doLogAxis){ 
     main_y_max = main_y_max*10;
     if(Stack->GetMinimum()>.1) Stack->SetMinimum(.1);
   }
   else main_y_max = main_y_max*1.4;
   Stack->SetMaximum(main_y_max);
   Stack->Draw("hist");
   errDown->Draw("E2same");
   errUp->Draw("E2Same");
   
   // make error histograms for the ratio plot
   TH1D* ratioErrDown = (TH1D*) errDown->Clone("ratio_error_down");
   TH1D* ratioErrUp = (TH1D*) errUp->Clone("ratio_error_up");

   ratioErrDown->Divide(backgroundsForRatio);
   ratioErrUp->Divide(backgroundsForRatio);

   if(!isSignalRegion && data)
      data->Draw("e same");

   if(signal){
     signal->SetLineStyle(2);
     signal->SetLineColor(kRed);
     signal->SetLineWidth(5);
     signal->Draw("hist same");
   }

   TLegend* leg = new TLegend(0.8,0.65,0.95,0.9);
   leg->SetFillStyle(0);
   leg->SetBorderSize(0);
   
   if(signal)
     leg->AddEntry(signal, "Signal", "l");
   if(!isSignalRegion)
     leg->AddEntry(data, "Data");
   for(int q=0; q<histos.size(); q++){
     if(histos[q]){
       if(histos[q]->GetEntries() > 0.)
	 leg->AddEntry(histos[q], names[q].c_str(), "f");
     }
   }
   leg->Draw("lpe");
   
   ATLAS_LABEL(0.2,0.85,1);
   char text[]="#sqrt{s}=8 TeV";
   myText(0.6,0.75,1,.04, text);
   char text_L[]="#int L dt = 20.3 fb^{-1}";
   myText(0.6, 0.85,1, .04, text_L);
   char inText[100];
   int t;
   if(signal)
     t=sprintf(inText, "N_{Signal} = %.1f", signal->Integral(0,signal->GetNbinsX()+1));
   else
     t=sprintf(inText, "N_{Signal} = %.1f", 0.);
   myText(0.2, 0.75, 1, .04, inText);
   double back_int = allBackgrounds->Integral(0,allBackgrounds->GetNbinsX()+1);
   if(back_int > 10000.)
     t=sprintf(inText, "N_{Bkgd} = %.3e", back_int);
   else
     t=sprintf(inText, "N_{Bkgd} = %.1f", back_int);
   myText(0.2, 0.7, 1, .04, inText);
   if(!isSignalRegion){
     if(data)
       t=sprintf(inText, "N_{Data} = %.0f", data->Integral(0,data->GetNbinsX()+1));
     else
       t=sprintf(inText, "N_{Data} = %.0f", 0.);
     myText(0.2, 0.65, 1, .04, inText);
   }
   
   canvas->cd();
   
   // Draw Ratio plot
   double ratio_max = 1.6;
   double ratio_min = 0.4;
  
   const double x_axis_size = 0.4;
   const double ratio_pad_height = RATIOPLOT_HEIGHT/CANVAS_HEIGHT;
   
   double pad_xlow = 0.,pad_xhigh = 1.;
   double pad_ylow = OFFSET/CANVAS_HEIGHT,pad_yhigh = ratio_pad_height;
   
   const char* pad_name = "pad";
   TPad* pad4ratio = new TPad(pad_name,pad_name,pad_xlow,pad_ylow,pad_xhigh,pad_yhigh);
   
   pad4ratio->SetMargin(pad_margin_left,pad_margin_right,x_axis_size,0.);
   pad4ratio->Draw();
   pad4ratio->cd();

   TH1D* ratioPlot;
   if(data) ratioPlot = (TH1D*)data->Clone("ratio");
   else if(signal) ratioPlot = (TH1D*)signal->Clone("ratio"); // if there is no data then use signal for axis 
   ratioPlot->SetTitle("");
   ratioPlot->GetYaxis()->SetTitle("Data/MC");
   ratioPlot->GetXaxis()->SetTitle(axisName.c_str());
   if(data){
     ratioPlot->Divide(allBackgrounds);
     // here change ratio_min and ratio_max if the ratio plot is quite flat
     double maxDeviation=0;
     double tempDev=0;
     for(int ibin=1; ibin<=allBackgrounds->GetNbinsX(); ibin++){
       tempDev = std::abs(ratioPlot->GetBinContent(ibin)-1.);
       if(tempDev > maxDeviation) maxDeviation = tempDev;
     }
     if(maxDeviation < 0.1){
       ratio_max = 1.12;
       ratio_min = 0.88;
     }
     else if(maxDeviation < 0.2){
       ratio_max = 1.25;
       ratio_min = .75;
     }
     ratioPlot->SetMinimum(ratio_min);
     ratioPlot->SetMaximum(ratio_max);
   }
   ratioPlot->GetXaxis()->SetLabelSize(RATIOPLOT_XAXIS_LABEL_SIZE);
   ratioPlot->GetXaxis()->SetTickLength(RATIOPLOT_XAXIS_TICK_LENGTH);
   ratioPlot->GetYaxis()->SetLabelSize(RATIOPLOT_YAXIS_LABEL_SIZE);
   ratioPlot->GetYaxis()->SetTickLength(RATIOPLOT_YAXIS_TICK_LENGTH);
   ratioPlot->GetYaxis()->SetNdivisions(3);
   ratioPlot->GetYaxis()->SetTitleSize(RATIOPLOT_YAXIS_TITLE_SIZE);
   ratioPlot->GetYaxis()->SetTitleOffset(RATIOPLOT_YAXIS_TITLE_OFFSET);
   ratioPlot->GetXaxis()->SetTitleSize(RATIOPLOT_XAXIS_TITLE_SIZE);
   ratioPlot->GetXaxis()->SetTitleOffset(RATIOPLOT_XAXIS_TITLE_OFFSET);
   
   if(!isSignalRegion && data){
     ratioPlot->Draw();
     // plot horizontal line at y=1
     TF1* horizontal = new TF1("horizontal","pol1",-10000,10000);
     horizontal->SetParameter(0,1.);
     horizontal->SetParameter(1,0.);
     horizontal->SetLineColor(kBlack);
     horizontal->SetLineStyle(2);
     horizontal->SetLineWidth(1);
     horizontal->Draw("same");
     ratioErrDown->Draw("E2same");
     ratioErrUp->Draw("E2same");
   }else if(isSignalRegion){
     ratioPlot->Draw("axis");
     char text[]="DATA IS BLINDED HERE";
     myText(0.4,0.6,1,.2,text);
   }else{ // in this case it is not the signal region but there is no data
     ratioPlot->Draw("axis");
     char text[]="NO DATA";
     myText(0.4,0.6,1,.2,text);
     }
   
   return canvas;
}
Exemple #4
0
TEfficiency* CalcEfficHadrons(const char* fileName, Bool_t makeDraw=kFALSE)
{
	// open the input file
	TFile *file = new TFile(fileName);
	
	// ********************************************
	// parameters to check before running the macro
	// ********************************************

	const Int_t NHISTS = 4; // Check the number of histograms for different particle species
	const Int_t NOUTPUTS = 3;
	const Int_t NHISTOUT[NOUTPUTS] = {1,1,1};
	const Int_t IHISTOUT[NOUTPUTS][NHISTS] = {{0,-1,-1,-1},{1,-1,-1,-1},{2,-1,-1,-1}};
	const Float_t CUT_RES = 0.02;
	
	Int_t style[NOUTPUTS] = {20,21,22};
	Int_t color[NOUTPUTS] = {1,2,4};
		
	const Int_t fgNumOfPtBins = 111; // Check the number of eta bins in the histograms
	const Int_t fgNumOfEtaBins = 16; // Check the number of E bins in the histograms
	const Int_t fgNumOfRBins = 45;
	
	Double_t fgPtAxis[117]= {0.0,0.01,0.02,0.03,0.04, 0.05, 0.06,0.07,0.08,0.09, 0.10,0.11, .12,0.13, .14,0.15, .16,0.17, .18,0.19,
		0.2, .22, .24, .26, .28, 0.30, 0.32, .34, .36, .38, 0.40, .42, .44, .46, .48,
		0.5, .52, .54, .56, .58, 0.60, 0.62, .64, .66, .68, 0.70, .72, .74, .76, .78,
		.80, .82, .84, .86, .88, 0.90, 0.92, .94, .96, .98, 1.00,1.05, 1.1,1.15, 1.2,
		1.25, 1.3,1.35,1.40,1.45, 1.50, 1.55, 1.6,1.65, 1.7, 1.75, 1.8,1.85, 1.9,1.95,
		2.0, 2.2, 2.4, 2.6, 2.8, 3.00, 3.20, 3.4, 3.6, 3.8, 4.00, 4.2, 4.4, 4.6, 4.8,
		5.0, 5.5, 6.0, 6.5, 7.0, 7.50, 8.00, 8.5, 9.0, 9.5, 10.0,12.0,14.0,16.0,18.0,
		20.0,25.0,30.0,35.0,40.0, 45.0, 50.0}; 
	
	// declare histograms and graphs
	TH2F *histNum[NHISTS];
	TH2F *histDen[NHISTS];
	TGraphErrors *graph[NOUTPUTS];
	TH1D* projYNum;
	TEfficiency *effic[NOUTPUTS];
	char efficName[50];
	
	// retrieve the input list of histogram. Check the TList name in the input file.
	TList *list = (TList*) file->Get("out1");
	
	// retrieve the histograms in the list. Check the name of the histograms
	histNum[0] = (TH2F*)list->FindObject("fHistPionRec_ResPt_EmcalMC");
	histNum[1] = (TH2F*)list->FindObject("fHistKaonRec_ResPt_EmcalMC");
	histNum[2] = (TH2F*)list->FindObject("fHistProtonRec_ResPt_EmcalMC");
	histNum[3] = (TH2F*)list->FindObject("fHistMuonRec_ResPt_EmcalMC");
	
	// retrieve the histograms in the list. Check the name of the histograms
	histDen[0] = (TH2F*)list->FindObject("fHistPionAcc_EtaPt_EmcalMC");
	histDen[1] = (TH2F*)list->FindObject("fHistKaonAcc_EtaPt_EmcalMC");
	histDen[2] = (TH2F*)list->FindObject("fHistProtonAcc_EtaPt_EmcalMC");
	histDen[3] = (TH2F*)list->FindObject("fHistMuonAcc_EtaPt_EmcalMC");
	
	// ********************************************

	Float_t x[fgNumOfPtBins]={0}, ex[fgNumOfPtBins]={0};
	Float_t y[fgNumOfPtBins]={0}, ey[fgNumOfPtBins]={0};
	Float_t num=0, den=0;
	//Int_t num=0, den=0;
	Float_t Res=0;
	
	// loop over different desired outputs
	for (int iOut=0; iOut<NOUTPUTS; iOut++)
	{
		sprintf(efficName,"effic_%d",iOut);
		effic[iOut] = new TEfficiency(efficName,efficName,fgNumOfPtBins,fgPtAxis);

		// loop over E bins
		for (int ix=0; ix<fgNumOfPtBins; ix++)
		{
			// initialize ET variables for a new particle species
			x[ix]=histNum[0]->GetXaxis()->GetBinCenter(ix+1);
			y[ix]=0;
			ex[ix]=0;
			ey[ix]=0;
			num = 0;
			den = 0;
			
			// loop over eta bins
			for (int iy=0; iy<fgNumOfEtaBins; iy++)
			{
				for (int iHist=0; iHist<NHISTOUT[iOut]; iHist++)
				{
					den += histDen[IHISTOUT[iOut][iHist]]->GetBinContent(ix+1,iy+1); // sum over all E bins in order to get total ET
				}
			}
			
			// loop over residual bins
			for (int iHist=0; iHist<NHISTOUT[iOut]; iHist++)
			{
				projYNum = histNum[IHISTOUT[iOut][iHist]]->ProjectionY();
				for (int iy=0; iy<fgNumOfRBins; iy++)
				{
					Res = projYNum->GetBinCenter(iy+1);
					if (Res<CUT_RES)
						num += histNum[IHISTOUT[iOut][iHist]]->GetBinContent(ix+1,iy+1); // sum over all E bins in order to get total ET
				}
			}
			
			if ((num>0) && (den>0))
			{
				effic[iOut]->SetTotalEvents(ix,den);
				effic[iOut]->SetPassedEvents(ix,num);
				y[ix] = num/den;
				ey[ix] = y[ix]*sqrt(1/num+1/den);
				//ey[ix] = ((num+1)*(num+2))/((den+2)*(den+3))-((num+1)*(num+1))/((den+2)*(den+2));
			}
			else
			{
				y[ix] = 0;	
				ey[ix] = 0;
			}
			
		} // end of loop over E bins

		graph[iOut] = new TGraphErrors(fgNumOfPtBins,x,y,ex,ey); // graphic of ET(>E_cut)/ET(total) for a given particle species and E cut

	} // end of loop over different outputs

	
	// Draw the plot
	
	if (makeDraw)
	{
		gStyle->SetOptTitle(0);
		gStyle->SetOptStat(0);
		gStyle->SetOptFit(0);	
		
		TCanvas *c = new TCanvas("c","c",500,400);
		//c->SetTopMargin(0.04);
		//c->SetRightMargin(0.04);
		//c->SetLeftMargin(0.181452);
		//c->SetBottomMargin(0.134409);
		c->SetBorderSize(0);
		c->SetFillColor(0);
		c->SetBorderMode(0);
		c->SetFrameFillColor(0);
		c->SetFrameBorderMode(0);
		
		/*
		 for (int i=0; i<NOUTPUTS; i++)
		 {
		 graph[i]->SetMarkerStyle(style[i]);
		 graph[i]->SetMarkerColor(color[i]);
		 graph[i]->SetLineColor(color[i]);
		 graph[i]->SetFillColor(0);
		 if (i == 0) 
		 {
		 graph[i]->GetXaxis()->SetTitle("E (GeV)");
		 graph[i]->GetYaxis()->SetTitle("effic");
		 graph[i]->SetMaximum(1.0);
		 graph[i]->SetMinimum(0.0);
		 graph[i]->Draw("AP");
		 }
		 else 
		 graph[i]->Draw("P");
		 }
		 */
		for (int i=0; i<NOUTPUTS; i++)
		{
			effic[i]->SetMarkerStyle(style[i]);
			effic[i]->SetMarkerColor(color[i]);
			effic[i]->SetLineColor(color[i]);
			effic[i]->SetFillColor(0);
			effic[i]->SetTitle("efficiency; p_{T} (GeV/c); #epsilon");
			if (i == 0) 
			{
				effic[i]->Draw();
			}
			else 
				effic[i]->Draw("Psame");
		}
		
		TLegend *leg = new TLegend(0.65,0.2,0.95,0.5);
		leg->AddEntry(effic[0],"pions");
		leg->AddEntry(effic[1],"kaons");
		leg->AddEntry(effic[2],"protons");
		//leg->AddEntry(effic[3],"muons");
		leg->SetFillStyle(0);
		leg->SetFillColor(0);
		leg->SetBorderSize(0);
		leg->SetTextSize(0.03);
		leg->Draw();
	}
	
	return effic[0];
}
void fitDVariable(TString variable="DsvpvDistance/DsvpvDisErr",TString variableplot="d_{xy}/#sigma(d_{xy})", TString inputdata="/data/wangj/MC2015/Dntuple/pp/ntD_pp_Dzero_kpi/ntD_EvtBase_20160203_Dfinder_20160201_pp_Pythia8_prompt_D0_dPt0tkPt0p5_pthatweight.root", TString inputmc="/data/wangj/MC2015/Dntuple/pp/ntD_pp_Dzero_kpi/ntD_EvtBase_20160203_Dfinder_20160201_pp_Pythia8_prompt_D0_dPt0tkPt0p5_pthatweight.root", TString trgselection="1",  TString cut="Dpt>20&&Dy>-1.&&Dy<1.&&Dtrk1highPurity&&Dtrk2highPurity&&Dtrk1Pt>2.0&&Dtrk2Pt>2.0&&(DsvpvDistance/DsvpvDisErr)>3&&(DlxyBS/DlxyBSErr)>1.5&&Dchi2cl>0.05&&Dalpha<0.12&&Dtrk1PtErr/Dtrk1Pt<0.1&&Dtrk2PtErr/Dtrk2Pt<0.1&&abs(Dtrk1Eta)<2.0&&abs(Dtrk2Eta)<2.0&&Dtrk1Algo>3&&Dtrk1Algo<8&&(Dtrk1PixelHit+Dtrk1StripHit)>=11", TString selmcgen="((GisSignal==1||GisSignal==2)&&(Gy>-1&&Gy<1))", int isMC=1, Double_t luminosity=26., int doweight=0, TString collsyst="PbPb", TString outputfile="mytest.root")
{
  collisionsystem=collsyst;
  seldata = Form("%s&&%s",trgselection.Data(),cut.Data());
  selmc = Form("%s",cut.Data());

  gStyle->SetTextSize(0.05);
  gStyle->SetTextFont(42);
  gStyle->SetPadRightMargin(0.043);
  gStyle->SetPadLeftMargin(0.18);
  gStyle->SetPadTopMargin(0.1);
  gStyle->SetPadBottomMargin(0.145);
  gStyle->SetTitleX(.0f);

  void clean0 (TH1D* h);
  TF1* fit (TString variable, TString variableplot, TTree* nt, TTree* ntMC, double ptmin, double ptmax, int isMC);

  if(!doweight) weight="1";
  TFile* inf = new TFile(inputdata.Data());
  TFile* infMC = new TFile(inputmc.Data());

  TTree* nt = (TTree*) inf->Get("ntDkpi");
  TTree* HltTree= (TTree*) inf->Get("ntHlt");
  HltTree->AddFriend(nt);
  nt->AddFriend(HltTree);
  TTree* ntHid = (TTree*) inf->Get("ntHi");
  nt->AddFriend(ntHid);
  
  TTree* ntMC = (TTree*)infMC->Get("ntDkpi");
  TTree* ntGen = (TTree*)infMC->Get("ntGen");
  TTree* ntHi = (TTree*)infMC->Get("ntHi");
  
  ntGen->AddFriend(ntMC);
  ntGen->AddFriend(ntHi);
  ntMC->AddFriend(ntGen);
  ntMC->AddFriend(ntHi);
  ntHi->AddFriend(ntMC);
  
  TH1D* hPt = new TH1D("hPt","",nBins,ptBins);
  TH1D* hPtRecoTruth = new TH1D("hPtRecoTruth","",nBins,ptBins);
  TH1D* hPtMC = new TH1D("hPtMC","",nBins,ptBins);
  TH1D* hPtGen = new TH1D("hPtGen","",nBins,ptBins);

  TH1D* hMean = new TH1D("hMean","",nBins,ptBins);                       
  TH1D* hSigmaGaus1 = new TH1D("hSigmaGaus1","",nBins,ptBins); 
  TH1D* hSigmaGaus2 = new TH1D("hSigmaGaus2","",nBins,ptBins); 
  TH1D* hRelMagnGaus1Gaus2 = new TH1D("hRelMagnGaus1Gaus2","",nBins,ptBins); 
  
  for(int i=0;i<nBins;i++)
    {
      TF1* f = fit(variable,variableplot,nt,ntMC,ptBins[i],ptBins[i+1],isMC);
      double yield = f->Integral(minhisto,maxhisto)/binwidthmass;
      double yieldErr = f->Integral(minhisto,maxhisto)/binwidthmass*f->GetParError(0)/f->GetParameter(0);
      hPt->SetBinContent(i+1,yield/(ptBins[i+1]-ptBins[i]));
      hPt->SetBinError(i+1,yieldErr/(ptBins[i+1]-ptBins[i]));
      hMean->SetBinContent(i+1,f->GetParameter(1));
      hMean->SetBinError(i+1,f->GetParError(1));
      hSigmaGaus1->SetBinContent(i+1,f->GetParameter(2));
      hSigmaGaus1->SetBinError(i+1,f->GetParError(2));
      hSigmaGaus2->SetBinContent(i+1,f->GetParameter(5));
      hSigmaGaus2->SetBinError(i+1,f->GetParError(5));
      hRelMagnGaus1Gaus2->SetBinContent(i+1,f->GetParameter(4));
      hRelMagnGaus1Gaus2->SetBinError(i+1,f->GetParError(4));
    }  

  ntMC->Project("hPtMC",variable.Data(),TCut(weight)*(TCut(selmc.Data())&&"(Dgen==23333)"));
  divideBinWidth(hPtMC);
  ntMC->Project("hPtRecoTruth",variable.Data(),TCut(selmc.Data())&&"(Dgen==23333)");
  divideBinWidth(hPtRecoTruth);
  ntGen->Project("hPtGen","Gpt",TCut(weight)*(TCut(selmcgen.Data())));
  divideBinWidth(hPtGen);

  TCanvas* cPt =  new TCanvas("cPt","",600,600);
  cPt->SetLogy();
  hPt->SetXTitle(Form("D^{0} %s",variable.Data()));
  hPt->SetYTitle("Uncorrected dN(D^{0})/dp_{T}");
  hPt->Sumw2();
  hPt->Draw();
  if(isMC)
    {
      hPtMC->Draw("same hist");
      TLegend* legPt = myLegend(0.55,0.80,0.90,0.94);
      legPt->AddEntry(hPt,"Signal extraction","pl");
      legPt->AddEntry(hPtMC,"Matched reco","lf");
      legPt->Draw("same");  
    }
  hPtMC->Sumw2();
  TH1D* hEff = (TH1D*)hPtMC->Clone("hEff");
  hEff->SetTitle(Form(";D^{0} %s",variable.Data()));
  hEff->Sumw2();
  hEff->Divide(hPtGen);
  TCanvas* cEff = new TCanvas("cEff","",600,600);
  hEff->Draw();
  
  TH1D* hPtCor = (TH1D*)hPt->Clone("hPtCor");
  hPtCor->SetTitle(Form(";D^{0} %s;Corrected dN(D^{0})/dp_{T}",variable.Data()));
  hPtCor->Divide(hEff);
  TCanvas* cPtCor=  new TCanvas("cCorResult","",600,600);
  cPtCor->SetLogy();
  hPtCor->Draw();
  if(isMC)
    {
      hPtGen->Draw("same hist");
      TLegend* legPtCor = myLegend(0.55,0.80,0.90,0.94);
      legPtCor->AddEntry(hPtCor,"Corrected signal","pl");
      legPtCor->AddEntry(hPtGen,"Generated D^{0}","lf");
      legPtCor->Draw("same");  
    }

  TH1D* hPtSigma= (TH1D*)hPtCor->Clone("hPtSigma");
  hPtSigma->SetTitle(Form(";D^{0} %s;d#sigma(D^{0})/d%s (pb/{units})",variable.Data(),variable.Data()));
  hPtSigma->Scale(1./(2*luminosity*BRchain));
  TCanvas* cPtSigma=  new TCanvas("cPtSigma","",600,600);
  cPtSigma->SetLogy();
  hPtSigma->Draw();
  
  TFile* outf = new TFile(outputfile.Data(),"recreate");
  outf->cd();
  hPt->Write();
  hEff->Write();
  hPtGen->Write();
  hPtMC->Write();
  hPtCor->Write();
  hPtSigma->Write();
  hMean->Write();
  hSigmaGaus1->Write();
  hSigmaGaus2->Write();
  hRelMagnGaus1Gaus2->Write();
  outf->Close();
}
Exemple #6
0
void combinedFit() {

  TH1D * hB = new TH1D("hB","histo B",100,0,100);
  TH1D * hSB = new TH1D("hSB","histo S+B",100, 0,100);

  TF1 * fB = new TF1("fB","expo",0,100);
  fB->SetParameters(1,-0.05);
  hB->FillRandom("fB");

  TF1 * fS = new TF1("fS","gaus",0,100);
  fS->SetParameters(1,30,5);

  hSB->FillRandom("fB",2000);
  hSB->FillRandom("fS",1000);

  // perform now global fit

  TF1 * fSB = new TF1("fSB","expo + gaus(2)",0,100);

  ROOT::Math::WrappedMultiTF1 wfB(*fB,1);
  ROOT::Math::WrappedMultiTF1 wfSB(*fSB,1);

  ROOT::Fit::DataOptions opt;
  ROOT::Fit::DataRange rangeB;
  // set the data range
  rangeB.SetRange(10,90);
  ROOT::Fit::BinData dataB(opt,rangeB);
  ROOT::Fit::FillData(dataB, hB);

  ROOT::Fit::DataRange rangeSB;
  rangeSB.SetRange(10,50);
  ROOT::Fit::BinData dataSB(opt,rangeSB);
  ROOT::Fit::FillData(dataSB, hSB);

  ROOT::Fit::Chi2Function chi2_B(dataB, wfB);
  ROOT::Fit::Chi2Function chi2_SB(dataSB, wfSB);

  GlobalChi2 globalChi2(chi2_B, chi2_SB);

  ROOT::Fit::Fitter fitter;

  const int Npar = 6;
  double par0[Npar] = { 5,5,-0.1,100, 30,10};

  // create before the parameter settings in order to fix or set range on them
  fitter.Config().SetParamsSettings(6,par0);
  // fix 5-th parameter
  fitter.Config().ParSettings(4).Fix();
  // set limits on the third and 4-th parameter
  fitter.Config().ParSettings(2).SetLimits(-10,-1.E-4);
  fitter.Config().ParSettings(3).SetLimits(0,10000);
  fitter.Config().ParSettings(3).SetStepSize(5);

  fitter.Config().MinimizerOptions().SetPrintLevel(0);
  fitter.Config().SetMinimizer("Minuit2","Migrad");

  // fit FCN function directly
  // (specify optionally data size and flag to indicate that is a chi2 fit)
  fitter.FitFCN(6,globalChi2,0,dataB.Size()+dataSB.Size(),true);
  ROOT::Fit::FitResult result = fitter.Result();
  result.Print(std::cout);

  TCanvas * c1 = new TCanvas("Simfit","Simultaneous fit of two histograms",
                             10,10,700,700);
  c1->Divide(1,2);
  c1->cd(1);
  gStyle->SetOptFit(1111);

  fB->SetFitResult( result, iparB);
  fB->SetRange(rangeB().first, rangeB().second);
  fB->SetLineColor(kBlue);
  hB->GetListOfFunctions()->Add(fB);
  hB->Draw();

  c1->cd(2);
  fSB->SetFitResult( result, iparSB);
  fSB->SetRange(rangeSB().first, rangeSB().second);
  fSB->SetLineColor(kRed);
  hSB->GetListOfFunctions()->Add(fSB);
  hSB->Draw();


}
void plotAngularResolution(){


   TChain *resChain = new TChain("angResTree");

   char resName[500];
   char fName[200];

   //   int sec1[17] = {04, 04, 04, 04, 04, 04, 10, 10, 12, 12, 12, 14, 14, 14, 16, 16, 17};
   //   int sec2[17] = {51, 51, 57, 57, 57, 58, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59};
   int temp = -1;
   //   int sec1[25] = {24, 30, 30, 25, 25, 25, 26, 26, 25, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 28, 29, 30, 30, 31};

   //   int sec1[17]={36, 36, 36, 36, 36, 33, 34, 34, 35, 36, 35, 36, 36, 37, 37, 37, 37};
   int sec1[3]= {19,21,21};

   for (int run=331;run<355;++run){ // 331-355 145-161 151-154

     temp = run - 151;
     //     cout << sec1[temp] << endl;
     //     sprintf(fName,"VPOL_10kVSeavey_2015_11_05_time_19_47_53");//  VPOL_10kVSeavey_2015_11_06_time_10_42_48
     // sprintf(fName,"VPOL_10kVSeavey_2015_11_06_time_10_42_48");
     // sprintf(fName,"LDBHPOL_10kVSeavey_2015_11_19_time_15_30_45");
     //     sprintf(fName,"VPOL_10kVSeavey_2015_11_19_time_11_49_04");
     sprintf(fName,"HPOL_seavey_pulses_2015_11_25");
     
          sprintf(resName,"/unix/anita3/treesForLinda/generateAngularResolutionTree_run%d-%dPlots.root",run,run);
     //     sprintf(resName,"/unix/anita3/strutt/antennaPositionCalibPlots/ldbPulses/%s/generateAngularResolutionTreeVPOLPlots_%d_2015-11-09_14-36-%02d.root",fName,run, sec2[temp]);
     //     sprintf(resName,"/unix/anita3/strutt/antennaPositionCalibPlots/newFittingOrder/newLindaNumbers_4steps_%s/generateAngularResolutionTreeVPOLPlots_%d_2015-11-23_12-42-%02d.root",fName,run, sec1[temp]);
     //sprintf(resName,"/unix/anita3/strutt/antennaPositionCalibPlots/ldbPulses/%s/generateAngularResolutionTreeHPolLDBPlots_%d_2015-11-25_12-25-%02d.root",fName,run, sec1[temp]);

     cout << resName << endl;
     resChain->Add(resName);
     
  }


   TH1D *hPhi = new TH1D("hPhi", "", 400, -2, 2);
   TH1D *hTheta = new TH1D("hTheta", "", 400, -2, 2);

   resChain->Draw("deltaPhiDeg >> hPhi", "", "off");
   resChain->Draw("deltaThetaDeg >> hTheta", "", "off");
   

   gStyle->SetOptStat(0);
   gStyle->SetOptFit(1);
   TCanvas *c1 = new TCanvas("c1");
   hPhi->SetTitle("#phi_{expected}-#phi_{zoom};#delta #phi (degrees);Events per bin");
   hPhi->Draw("");
   hPhi->Fit("gaus", "", "", -1, 1);
   c1->Print(Form("AngularResolution_phi_4steps_%s.png", fName));
   c1->Print(Form("AngularResolution_phi_4steps_%s.pdf", fName));


   hTheta->SetTitle("#theta_{expected}-#theta_{zoom};#delta #theta (degrees);Events per bin");
   hTheta->Draw("");
   hTheta->Fit("gaus");
   c1->Print(Form("AngularResolution_theta_4steps_%s.png", fName));
   c1->Print(Form("AngularResolution_theta_4steps_%s.pdf", fName));



}
void exampleStMuIOMaker(const char* file="/star/data14/reco/productionCentral/ReversedFullField/P02ge/2001/324/st_physics_2324001_raw_0006.MuDst.root") {
  gROOT->LoadMacro("$STAR/StRoot/StMuDSTMaker/COMMON/macros/loadSharedLibraries.C");
  loadSharedLibraries();

  StMuDebug::setLevel(0);  

  int counter=0;
  int iret=0;

  StMuIOMaker* maker = new StMuIOMaker("MuDst");  
  maker->SetFileAndOpen(file);
//  maker->SetFileName("st_physics_2313018_raw_0029.MuDst.root");
  TMemStat memStat("exampleMuIO");

  StMuDst* mu;
// evtid is an unique id of an event in a run which may involve several files!
// it is different from sequential index in a run which starts from "0"!
//  for ( int evtid=80673; evtid<80694; evtid++) {
//  for ( int evtid=6300; evtid<6321; evtid++) {
//	iret = maker->Make( StUKey(2271008,evtid) );  
//	iret = maker->Make( StUKey(2313018,evtid) );  
// alterative
for ( int i=0; i<20; i++) {
//	iret = maker->Make();  // read an event in natural sequential 
	iret = maker->Make(i);  // read an event with seqential index 
	if ( iret == kStOK) {
	   StMuDst* mu = maker->muDst();
	   if ( !mu ) continue;
//           if(i%10 != 0) continue;

// take a look at branches of tracks
	   int n;
	   n= mu->globalTracks()->GetEntries();
	   for (int l=0; l<n; l++) globalPt.Fill(mu->globalTracks(l)->pt());   
	   n= mu->primaryTracks()->GetEntries();
	   for (int l=0; l<n; l++) primaryPt.Fill(mu->primaryTracks(l)->pt()); 
	   n= mu->l3Tracks()->GetEntries();
	   for (int l=0; l<n; l++) {l3Pt.Fill( mu->l3Tracks(l)->pt() );}   

// take a look at event branch 
	   StMuEvent* muEvent = mu->event();
	   int referenceMultiplicity = muEvent->refMult();
	   refMult.Fill(referenceMultiplicity);

	   cout << "#" << i << " index=" << maker->currentIndex()
//	   cout << "eventId =" << evtid << " index=" << maker->currentIndex() 
                << " refmult= "<< referenceMultiplicity
	        << " used= "<< memStat.Used()
	        << " size= "<< memStat.ProgSize() << endl;
	   counter++;
	}
  }
  cout << " # of events:" << counter << endl;

  globalPt.Draw();
  primaryPt.Draw("same");
  l3Pt.Draw("same");
 
  TFile f("testMuIO.root","RECREATE");
  globalPt.Write();
  primaryPt.Write();
  l3Pt.Write();
  refMult.Write();
  f.Close();
}
void sqrtMethodSameSign(int ptBin, double ptCutLo, double ptCutHi, int massBin, double mCutLo, double mCutHi, int etaBin, double etaCutLo, double etaCutHi){
	
	//OPTIONS AND CUTS------------
	bool useBlueBeam = true;
	bool useYellowBeam = true;
	bool randomizeSpin = false;
	
	double PI = 3.14159265359;
	
	cout << "\n";
	if (useBlueBeam && useYellowBeam){cout << "using both beams-----" << endl;}
	if (useBlueBeam && !useYellowBeam){cout << "using blue beam------" << endl;}
	if (!useBlueBeam && useYellowBeam){cout << "using yellow beam----" << endl;}
	cout << "\n";
	if (randomizeSpin){cout << "randomizing spin-----" << endl;}
	
	
	
	//PION PAIR CUTS:
	/*
	 double ptCutLo = 4;
	 double ptCutHi = 10;
	 double mCutLo = .4;
	 double mCutHi = 1;
	 double etaCutLo = -1.4;
	 double etaCutHi = 1.4;
	 //*/
	//double phiCutLo = -.5;
	//double phiCutHi = .5;
	
	//----------------------------	
	
	
	//LOAD LIBS
	cout << "\n";
	gROOT->Macro("StRoot/LoadLibs.C");
	gSystem->Load("sameSignPair");
	cout << " loading of sameSignPair library done" << endl;

	
	
	//SET UP INPUT FILE	
	TFile* infile = new TFile("/star/u/klandry/ucladisk/2012IFF/schedOut_samesign_4_14/allSameSign_4_14.root");
	
	
	
	//SET UP TREE TO RECEIVE INPUT
	sameSignPair* pair1 = new sameSignPair();
	TTree* pairTree = infile->Get("sameSignTree");
	pairTree->SetBranchAddress("sameSignPair", &pair1);
	
	
	//SET UP HISTOGRAMS
	
	//event variable histograms
	TH1D* hInvarM    = new TH1D("invarM","invarM",80,0,2);
	TH1D* hEtaTot	   = new TH1D("etaTot","etaTot",60,-1.5,1.5);
	TH1D* hPhiR      = new TH1D("hPhiR","hPhiR",60,-4,4);
	TH1D* hPhiS      = new TH1D("hPhiS","hPhiS",60,-4,4);
	TH1D* hPhiSR     = new TH1D("hPhiSR","hPhiSR",60,-4,4);
	TH1D* hTheta     = new TH1D("hTheta","hTheta",30,-0.85,4);
	TH1D* hCosTheta  = new TH1D("hCosTheta","hCosTheta",80,-1,1);
	TH1D* hZ         = new TH1D("hZ","hZ",80,0,1);
	TH1D* hPtot      = new TH1D("hPtot","hPtot",80,0,20);
	TH1D* hPtTOT     = new TH1D("hPt","hPt",80,0,15);
	
	//histos for asym analysis	
	double histMin = -PI;
	double histMax =  PI;
	const int binNumber = 16;
	
	TH1D * hNumberUp   = new TH1D("hNumberUp","hNumberUp",binNumber,histMin,histMax);
	TH1D * hNumberDown = new TH1D("hNumberDown","hNumberDown",binNumber,histMin,histMax);
	
	TH1D * hDiff  = new TH1D("hNumberSum","hNumberSum",binNumber,histMin,histMax);
	TH1D * hAut = new TH1D("Aut","Aut",binNumber,histMin,histMax);
	
	
	//BEAM POLARIZATION
	
	ifstream polFile;
	polFile.open("/star/u/klandry/ucladisk/2012IFF/BeamPolarization2012.txt");
	
	
	map<int, double> polarizationOfFill_Y;
	map<int, double> polErrOfFill_Y;
	
	map<int, double> polarizationOfFill_B;
	map<int, double> polErrOfFill_B;
	
	
	
	int    fill;
	int    beamE;
	int    startT;
	string plusminus;
	
	double pAvrgBlue;
	double pErrAvrgBlue;
	
	double pInitialBlue;
	double pErrInitialBlue;
	double dPdTBlue;
	double dPdTErrBlue;
	
	double pAvrgYellow;
	double pErrAvrgYellow;
	
	double pInitialYellow;
	double pErrInitialYellow;
	double dPdTYellow;
	double dPdTErrYellow;
	
	string header;
	
	for (int i=0; i<19; i++){polFile >> header;}
	
	while (!polFile.eof())
	{
		
		polFile >> fill;
		polFile >> beamE;
		polFile >> startT;
		
		polFile >> pAvrgBlue;
		polFile >> plusminus;
		polFile >> pErrAvrgBlue;
		
		polFile >> pInitialBlue;
		polFile >> plusminus;
		polFile >> pErrInitialBlue;
		
		polFile >> dPdTBlue;
		polFile >> plusminus;
		polFile >> dPdTErrBlue;
		
		polFile >> pAvrgYellow;
		polFile >> plusminus;
		polFile >> pErrAvrgYellow;
		
		polFile >> pInitialYellow;
		polFile >> plusminus;
		polFile >> pErrInitialYellow;
		
		polFile >> dPdTYellow;
		polFile >> plusminus;
		polFile >> dPdTErrYellow;
		
		
		polarizationOfFill_B[fill] = pAvrgBlue/100.;
		polErrOfFill_B[fill] = pErrAvrgBlue/100.;
		
		polarizationOfFill_Y[fill] = pAvrgYellow/100.;
		polErrOfFill_Y[fill] = pErrAvrgYellow/100.;
		
		
		
	}
	
	double avgPolOfBinUp[binNumber];
	double polOfBinSumUp[binNumber];
	
	double avgPerrorOfBinUp[binNumber];
	double pErrorOfBinUp[binNumber];
	
	double avgPolOfBinDown[binNumber];
	double polOfBinSumDown[binNumber];
	
	double avgPerrorOfBinDown[binNumber];
	double pErrorOfBinDown[binNumber];
	
	for (int i=0; i<binNumber; i++)
	{
		avgPolOfBinUp[i] = 0;
		polOfBinSumUp[i] = 0;
		
		avgPerrorOfBinUp[i] = 0;
		pErrorOfBinUp[i] = 0;
		
		avgPolOfBinDown[i] = 0;
		polOfBinSumDown[i] = 0;
		
		avgPerrorOfBinDown[i] = 0;
		pErrorOfBinDown[i] = 0;
		
	}
	
	
	//   ======================================================================
	//============================================================================
	//START ANALYSIS==============================================================
	//============================================================================
	//   ======================================================================
	
	cout << pairTree->GetEntries() << endl;
	
	cout << "\n";
	cout << "<----STARTING ANALYSIS---->" << endl;
  cout << "\n";
	
	
	double blueFillNo;
	double yellowFillNo;
	
	int bin;
	
	TLorentzVector sum;
	TLorentzVector sumY;
	TLorentzVector sumB;
	
	//random number for randomizing spin.
	//set seed to zero to gaurenty unique numbers each time.
	TRandom3 r;
	r.SetSeed(0);
	
	int rand5 = 0;
	int rand6 = 0;
	int rand9 = 0;
	int rand10 = 0;
	
	
	int totalPairsFinal = 0;
	int blueD = 0;
	int blueU = 0;
	int yellowD = 0;
	int yellowU = 0;
	
	int pionStarNumber = 0;
	
	
	for (int iPair = pionStarNumber; iPair < pairTree->GetEntries(); iPair++)
	{
		if (iPair%10000 == 0) {cout << "processing pair number " << iPair << endl;}
		
		//if (iPair == pionStarNumber+2000000){break;}
		
		pairTree->GetEntry(iPair);
				
		
		if (pair1->withinRadius(0.05, 0.3))
		{
			
			
			bool triggerFired = false;
			bool fromKaon = false;
			
			StTriggerId trigId = pair1->triggerIds();
			
			
			//JP0,JP1,JP2,AJP
			if (trigId.isTrigger(370601) || trigId.isTrigger(370611) || trigId.isTrigger(370621) || trigId.isTrigger(370641))
			{
				triggerFired = true;
			}
			
			//BHT0VPD,BHT1VPD,BHT2BBC,BHT2
			if (trigId.isTrigger(370501) || trigId.isTrigger(370511) || trigId.isTrigger(370522) || trigId.isTrigger(370531))
			{
				triggerFired = true;
			}
			
			
			if (pair1->invarientMass() > .4921 && pair1->invarientMass() < .4990)
			{
				fromKaon = true;
			}
			
			
			
			if (triggerFired)
			{
				
				
				blueFillNo   = pair1->runInfo().beamFillNumber(1); //1 = blue beam
				yellowFillNo = pair1->runInfo().beamFillNumber(0); //0 = yellow beam 
				
				//cout << blueFillNo << "  " << yellowFillNo << endl;
				
				
				if (polarizationOfFill_B[blueFillNo] == 0 || polarizationOfFill_Y[yellowFillNo] == 0) //0 is gap
				{
					continue;
				}
				
				
				hInvarM->Fill(pair1->invarientMass());
				
				
				sum = pair1->pion1LV() + pair1->pion2LV();
				sumB = sum; //blue beam.
				
				
				//yellow beam must rotate around y axis by pi so the eta cut can be the same for both beams. 				
				sumY = sum;
				sumY.RotateY(PI);
				
				//cout << pair1->phiS('y')-pair1->phiR('y') << "   " << pair1->phiSR('y') << endl;
				
				//option for randomizing spin
				if (randomizeSpin)
				{
					
					int origSpinBit = pair1->spinBit();
					
					double randomSpin = r.Uniform(0, 1);
					
					int randomSpinBit;
					
					if (randomSpin >=0 && randomSpin <0.25)  {randomSpinBit = 5; rand5++;}
					if (randomSpin >=0.25 && randomSpin <0.5){randomSpinBit = 6; rand6++;}
					if (randomSpin >=0.5 && randomSpin <0.75){randomSpinBit = 9; rand9++;}
					if (randomSpin >=0.75 && randomSpin <1.0){randomSpinBit = 10; rand10++;}
					
					
					
					pair1->setSpinBit(randomSpinBit);
					
					
					
				}
				
				
				//cout << pair1->sinPhiSR('b') << "   " << pair1->cosPhiSR('b') << "   " << pair1->phiSR('b') << endl;
				
				
				//MANUALLY ALTER ANGLES FOR TESTING-----
				/*
				 double testPhiS_y = -pair1->phiS('y');
				 double testPhiR_y = pair1->phiR('y');
				 
				 double testPhiS_b = -pair1->phiS('b');
				 double testPhiR_b = pair1->phiR('b');
				 
				 
				 
				 double testPhiSR_y = testPhiS_y - testPhiR_y;
				 
				 double testPhiSR_b = testPhiS_b - testPhiR_b;
				 
				 //cout << testPhiS_b << " " << testPhiR_b << "  " << testPhiS_y << " " << testPhiR_y << endl;
				 
				 
				 if (testPhiSR_y > PI)
				 {
				 testPhiSR_y -= 2*PI;
				 }
				 
				 if (testPhiSR_y < -PI)
				 {
				 testPhiSR_y += 2*PI;
				 }
				 
				 if (testPhiSR_b > PI)
				 {
				 testPhiSR_b -= 2*PI;
				 }
				 
				 if (testPhiSR_b < -PI)
				 {
				 testPhiSR_b += 2*PI;
				 }
				 
				 //cout << testPhiSR_b << "   " << testPhiSR_y << endl;
				 //*/
				
				//CHECK CUTS
				if (sumB.Pt() > ptCutLo && sumB.Pt() < ptCutHi && sumB.M() > mCutLo && sumB.M() < mCutHi && sumB.Eta() > etaCutLo && sumB.Eta() < etaCutHi && useBlueBeam == true)
				{
					
					//BLUE BEAM SPIN UP: spin bin 9 and 10
					if (pair1->spinBit() == 9 || pair1->spinBit() == 10)
					{
						blueU++;
						
						
						//make sure to set it back if you randomized it for up/down.
						//still need origional spin bit to calc anlge.
						if (randomizeSpin){pair1->setSpinBit(origSpinBit);}
						
						bin = hNumberUp->FindBin(pair1->phiSR('b'));
						hNumberUp->Fill(pair1->phiSR('b'));
						
						//bin = hNumberUp->FindBin(testPhiSR_b);
						//hNumberUp->Fill(testPhiSR_b);
						
						
						
						polOfBinSumUp[bin] += polarizationOfFill_B[blueFillNo];
						pErrorOfBinUp[bin] += polErrOfFill_B[blueFillNo];
						
						
						//If rondomized spin, have to set the spin bit back to random
						//for next spin bit check
						if (randomizeSpin){pair1->setSpinBit(randomSpinBit);}
					}
					
					//BLUE BEAM SPIN DOWN: spin bin 5 and 6
					if (pair1->spinBit() == 5 || pair1->spinBit() == 6)
					{
						blueD++;
						
						if (randomizeSpin){pair1->setSpinBit(origSpinBit);}
						
						bin = hNumberDown->FindBin(pair1->phiSR('b'));
						hNumberDown->Fill(pair1->phiSR('b'));
						
						//bin = hNumberDown->FindBin(testPhiSR_b);
						//hNumberDown->Fill(testPhiSR_b);
						
						
						polOfBinSumDown[bin] += polarizationOfFill_B[blueFillNo];
						pErrorOfBinDown[bin] += polErrOfFill_B[blueFillNo];		
						
						if (randomizeSpin){pair1->setSpinBit(randomSpinBit);}
					}
					
				}//end blue cuts
				
				
				
				if (sumY.Pt()>ptCutLo && sumY.Pt() < ptCutHi && sumY.M() > mCutLo && sumY.M() < mCutHi && sumY.Eta() > etaCutLo && sumY.Eta() < etaCutHi && useYellowBeam == true)
				{
					
					//YELLOW BEAM SPIN UP: spin bin 6 and 10
					if (pair1->spinBit() == 6 || pair1->spinBit() == 10)
					{
						
						yellowU++;
						
						if (randomizeSpin){pair1->setSpinBit(origSpinBit);}
						
						bin = hNumberUp->FindBin(pair1->phiSR('y'));
						hNumberUp->Fill(pair1->phiSR('y'));
						
						
						//bin = hNumberUp->FindBin(testPhiSR_y);
						//hNumberUp->Fill(testPhiSR_y);
						
						
						
						polOfBinSumUp[bin] += polarizationOfFill_Y[yellowFillNo];
						pErrorOfBinUp[bin] += polErrOfFill_Y[yellowFillNo];
						
						if (randomizeSpin){pair1->setSpinBit(randomSpinBit);}
					}	
					//YELLOW BEAM SPIN DOWN: spin bit 5 and 9
					if (pair1->spinBit() == 5 || pair1->spinBit() == 9)
					{
						
						yellowD++;
						
						if (randomizeSpin){pair1->setSpinBit(origSpinBit);}
						
						bin = hNumberDown->FindBin(pair1->phiSR('y'));
						hNumberDown->Fill(pair1->phiSR('y'));
						
						//bin = hNumberDown->FindBin(testPhiSR_y);
						//hNumberDown->Fill(testPhiSR_y);
						
						
						polOfBinSumDown[bin] += polarizationOfFill_Y[yellowFillNo];
						pErrorOfBinDown[bin] += polErrOfFill_Y[yellowFillNo];
						
						if (randomizeSpin){pair1->setSpinBit(randomSpinBit);}
					}
				}//end yellow cuts
			}//end triger check
		}//end radius check
	}//end pairTree loop
	
	
	//CALCULATE ASYMMETRY BIN BY BIN
	cout << "\n";
	cout << "<----CALCULATING ASYMMETRY---->" << endl;
	cout << "\n";
	
	for (int ibin=1; ibin<=binNumber; ibin++)
	{
		
		if (ibin <= binNumber*0.5)
		{
			double nUp   = hNumberUp->GetBinContent(ibin);
			double nUpPi = hNumberUp->GetBinContent(ibin+binNumber*0.5);
			
			double nDown   = hNumberDown->GetBinContent(ibin);
			double nDownPi = hNumberDown->GetBinContent(ibin+binNumber*0.5);
			
			
			int binIndexPi = ibin+binNumber*0.5;
			
			double avgPolA = (polOfBinSumUp[ibin]+polOfBinSumDown[binIndexPi])/(nUp+nDownPi);
			double avgPolB = (polOfBinSumUp[binIndexPi]+polOfBinSumDown[ibin])/(nUpPi+nDown);
			
			double realAvgPol = (polOfBinSumUp[ibin]+polOfBinSumDown[binIndexPi]+polOfBinSumUp[binIndexPi]+polOfBinSumDown[ibin])/(nUp+nUpPi+nDown+nDownPi);
			
		}
		else
		{
			double nUp   = hNumberUp->GetBinContent(ibin);
			double nUpPi = hNumberUp->GetBinContent(ibin-binNumber*0.5);
			
			double nDown   = hNumberDown->GetBinContent(ibin);
			double nDownPi = hNumberDown->GetBinContent(ibin-binNumber*0.5);
			
			int binIndexPi = ibin-binNumber*0.5;
			
			double avgPolA = (polOfBinSumUp[ibin]+polOfBinSumDown[binIndexPi])/(nUp+nDownPi);
			double avgPolB = (polOfBinSumUp[binIndexPi]+polOfBinSumDown[ibin])/(nUpPi+nDown);
			
			double realAvgPol = (polOfBinSumUp[ibin]+polOfBinSumDown[binIndexPi]+polOfBinSumUp[binIndexPi]+polOfBinSumDown[ibin])/(nUp+nUpPi+nDown+nDownPi);
			
			double realAvgPolE = (pErrorOfBinUp[ibin]+pErrorOfBinDown[binIndexPi]+pErrorOfBinUp[binIndexPi]+pErrorOfBinDown[ibin])/(nUp+nUpPi+nDown+nDownPi);
			
		}
		
		
		cout << avgPolA << "   " << avgPolB << endl;
		
		
		
		
		hDiff->SetBinContent(ibin, sqrt(nUp*nDownPi) - sqrt(nDown*nUpPi));
		
		//hAut->SetBinContent(ibin, (1/avgPolA * sqrt(nUp*nDownPi) - 1/avgPolB * sqrt(nDown*nUpPi)) / (sqrt(nUp*nDownPi) + sqrt(nDown*nUpPi))    );
		
		
		hAut->SetBinContent(ibin, 1/realAvgPol * (sqrt(nUp*nDownPi) - sqrt(nDown*nUpPi)) / (sqrt(nUp*nDownPi) + sqrt(nDown*nUpPi))    );
		
		
		
		
		//error
		if (realAvgPol*pow(sqrt(nUp*nDownPi)+sqrt(nDown*nUpPi), 2) != 0)
		{
			
			double a = sqrt(nUp*nDownPi);
			double b = sqrt(nUpPi*nDown);
			
			
			double firstTerm = realAvgPol**2 * (nUpPi*nDown*(nUp+nDownPi) + nDownPi*nUp*(nUpPi+nDown));
			
			//double secondTerm = ((nUp*nDownPi)**2 +(nUpPi*nDown)**2 - 2*nUp*nDown*nUpPi*nDownPi)*realAvgPolE**2;
			
			double secondTerm = 0;
			
			
			double binError = 1/realAvgPol**2 * 1/(a+b)**2 * sqrt(firstTerm + secondTerm);
			
			
		}	
		else
		{
			double binError = 0.01;
			cout << "bin " << ibin << " Has problem with error" << endl;
		}
		
		hAut->SetBinError(ibin, binError);
		
	}//end Asym calc
	
	
	
	//DRAW HISTOGRAMS
	
	hInvarM->Draw();
	
	TCanvas* cNup = new TCanvas();
	hNumberUp->Draw();
	
	TCanvas* cNdown = new TCanvas();
	hNumberDown->Draw();
	
	TCanvas* cAut = new TCanvas();
	cAut->SetName("cAut");
	
	TF1* fitFunc = new TF1("fitFunc","[0]*cos(x)+[1]",-PI,PI);
	hAut->Fit("fitFunc","R");
	hAut->Draw();
	
	hAut->GetXaxis()->SetTitle("#phi_{S} - #phi_{R}");
	
	char title[150];
	sprintf(title, "%.1f < P_{T}^{#pi^{1}#pi^{2}} < %.1f  %.1f < M_{inv}^{#pi^{1}#pi^{2}} < %.1f  %.1f < #eta^{#pi^{1}#pi^{2}} < %.1f", ptCutLo, ptCutHi, mCutLo, mCutHi, etaCutLo, etaCutHi);
	
	hAut->SetTitle(title);
	
	
	cout << "Asym  = " << hAut->GetFunction("fitFunc")->GetParameter(0) << endl;
	cout << "error = " << hAut->GetFunction("fitFunc")->GetParError(0) << endl;
	cout << "chi2  = " << hAut->GetFunction("fitFunc")->GetChisquare() << endl;
	cout << "Nup   = " << hNumberUp->GetEntries() << endl;
	cout << "Ndown = " << hNumberDown->GetEntries() << endl;
  cout << "ran5  = " << rand5 << endl;
  cout << "ran6  = " << rand6 << endl;
  cout << "ran9  = " << rand9 << endl;
  cout << "ran10 = " << rand10 << endl;
	cout << "blueU = " << blueU << endl;
	cout << "blueD = " << blueD << endl;
	cout << "yellowU = " << yellowU << endl;
	cout << "yellowD = " << yellowD << endl;
	
	
	
	
	//SAVE CANVAS	
	
	
	stringstream pt;
	stringstream eta;
	stringstream mass;
	
	string part1 = "_ptBin";
	string part2 = "_massBin";
	string part3 = "_etaBin";
	
	string ptBinStr;
	string etaBinStr;
	string massBinStr;
	
	pt << ptBin;
	
	eta << etaBin;
	
	mass << massBin;
	
	if (ptBin == 9){ptBinStr = "All";}
	else{	ptBinStr = pt.str();}
	
	if (massBin == 9){massBinStr = "All";}
	else{	massBinStr = mass.str();}
	
	if (etaBin == 9){etaBinStr = "All";}
	else{	etaBinStr = eta.str();}
	
	cout << "total pairs " << totalPairsFinal << endl;
	
	
	stringstream pionNum;
	pionNum << pionStarNumber; 
	string pionNumStr = pionNum.str();
	
	
	string outFileName = "./results_samesign_4_14/sameSign"+part1+ptBinStr+part2+massBinStr+part3+etaBinStr+".root";
	TFile* outFile = new TFile(outFileName.c_str(),"Recreate");
	
	
	cout << "---WRITING FILE---" << endl; 
	//cAut->SaveAs(outFileName.c_str());
	hAut->Write();
	hNumberUp->Write();
	hNumberDown->Write();
	
	cout << "---END---" << endl; 
}
Exemple #10
0
void draw_from_trees(TString var, TCut other_cuts,
		     TString weights, TString title, int nbinsx, 
		     double xlow, double xup,
		     TString options="plotSig:plotLog:plotData",
		     double cut_low=-1, double cut_high=-1,
		     TString plot_title="default")
{

  bool plotSig = options.Contains("plotSig") && (!options.Contains("!plotSig"));
  bool plotLog = options.Contains("plotLog") && (!options.Contains("!plotLog"));
  bool plotData = options.Contains("plotData") && (!options.Contains("!plotData"));
  bool plotT1tttt = options.Contains("T1tttt") && (!options.Contains("!T1tttt"));

  // Book histograms
  TH1D * httbar = new TH1D("ttbar" , title, nbinsx, xlow, xup);
  TH1D * hqcd = new TH1D("qcd" , title, nbinsx, xlow, xup);
  TH1D * hznn = new TH1D("znn" , title, nbinsx, xlow, xup);
  TH1D * hwjets = new TH1D("wjets" , title, nbinsx, xlow, xup);
  TH1D * hother = new TH1D("other" , title, nbinsx, xlow, xup);
  TH1D * hmc_exp = new TH1D("mc_exp" , title, nbinsx, xlow, xup);
  TH1D * hsingle_top = new TH1D("single_top" , title, nbinsx, xlow, xup);  
  TH1D * ht1bbbb_1500_100 = new TH1D("t1bbbb_1500_100" , title, nbinsx, xlow, xup);
  TH1D * ht1bbbb_1000_900 = new TH1D("t1bbbb_1000_900" , title, nbinsx, xlow, xup);
  TH1D * ht1tttt_1500_100 = new TH1D("t1tttt_1500_100" , title, nbinsx, xlow, xup);
  TH1D * ht1tttt_1200_800 = new TH1D("t1tttt_1200_800" , title, nbinsx, xlow, xup);

  // Format cuts
  TCut cut(other_cuts);
  cout << "Filling histograms for " << var.Data() << endl;
  ttbar_ch->Project("ttbar",var,cut*weights);
  qcd_ch->Project("qcd",var,cut*weights);
  znn_ch->Project("znn",var,cut*weights);
  wjets_ch->Project("wjets",var,cut*weights);
  other_ch->Project("other",var,cut*weights);
  single_top_ch->Project("single_top",var,cut*weights);
  t1bbbb_1500_100_ch->Project("t1bbbb_1500_100",var,cut*weights);
  t1bbbb_1000_900_ch->Project("t1bbbb_1000_900",var,cut*weights);
  t1tttt_1500_100_ch->Project("t1tttt_1500_100",var,cut*weights);
  t1tttt_1200_800_ch->Project("t1tttt_1200_800",var,cut*weights);

  TH1D * hSMSLargeSplitting;
  TH1D * hSMSCompressed;

  if (plotT1tttt) {
    hSMSLargeSplitting=ht1tttt_1500_100;
    hSMSCompressed=ht1tttt_1200_800;
  } else {
    hSMSLargeSplitting=ht1bbbb_1500_100;
    hSMSCompressed=ht1bbbb_1000_900;
  }

  bool addOverflow(true);
  Double_t e_overflow(0.), i_overflow(0.);
  if (addOverflow) {
    i_overflow=httbar->IntegralAndError(nbinsx,nbinsx+1,e_overflow);
    httbar->SetBinContent(nbinsx, i_overflow);
    httbar->SetBinError(nbinsx, e_overflow);
    i_overflow=hqcd->IntegralAndError(nbinsx,nbinsx+1,e_overflow);
    hqcd->SetBinContent(nbinsx, i_overflow);
    hqcd->SetBinError(nbinsx, e_overflow);
    i_overflow=hznn->IntegralAndError(nbinsx,nbinsx+1,e_overflow);
    hznn->SetBinContent(nbinsx, i_overflow);
    hznn->SetBinError(nbinsx, e_overflow);
    i_overflow=hwjets->IntegralAndError(nbinsx,nbinsx+1,e_overflow);
    hwjets->SetBinContent(nbinsx, i_overflow);
    hwjets->SetBinError(nbinsx, e_overflow);
    i_overflow=hsingle_top->IntegralAndError(nbinsx,nbinsx+1,e_overflow);
    hsingle_top->SetBinContent(nbinsx, i_overflow);
    hsingle_top->SetBinError(nbinsx, e_overflow);
    i_overflow=hother->IntegralAndError(nbinsx,nbinsx+1,e_overflow);
    hother->SetBinContent(nbinsx, i_overflow);
    hother->SetBinError(nbinsx, e_overflow);
    i_overflow=hSMSLargeSplitting->IntegralAndError(nbinsx,nbinsx+1,e_overflow);
    hSMSLargeSplitting->SetBinContent(nbinsx, i_overflow);
    hSMSLargeSplitting->SetBinError(nbinsx, e_overflow);
    i_overflow=hSMSCompressed->IntegralAndError(nbinsx,nbinsx+1,e_overflow);
    hSMSCompressed->SetBinContent(nbinsx, i_overflow);
    hSMSCompressed->SetBinError(nbinsx, e_overflow);
  }

  
  // Add up MC histograms
  hmc_exp->Add(httbar);
  hmc_exp->Add(hqcd);
  hmc_exp->Add(hznn);
  hmc_exp->Add(hwjets);
  hmc_exp->Add(hsingle_top);
  hmc_exp->Add(hother);

  double binwidth = (xup - xlow) / nbinsx;
  TString ytitle = Form("Events / %.3f", binwidth);
  hmc_exp->GetXaxis()->SetTitle(httbar->GetXaxis()->GetTitle());
  hmc_exp->GetYaxis()->SetTitle(ytitle);
  cout << "... DONE: add all backgrounds to mc_exp." << endl;
  
  Double_t ttbar_e(0.), qcd_e(0.), znn_e(0.), wjets_e(0.), other_e(0.), single_top_e(0.), bg_tot_e(0.), t1bbbb_1500_100_e(0.);
  double ttbar_n(httbar->IntegralAndError(0,nbinsx+1, ttbar_e));
  double qcd_n(hqcd->IntegralAndError(0,nbinsx+1, qcd_e));
  double znn_n(hznn->IntegralAndError(0,nbinsx+1, znn_e));
  double wjets_n(hwjets->IntegralAndError(0,nbinsx+1, wjets_e));
  double other_n(hother->IntegralAndError(0,nbinsx+1, other_e));
  double single_top_n(hsingle_top->IntegralAndError(0,nbinsx+1, single_top_e));
  double bg_tot(hmc_exp->IntegralAndError(0,nbinsx+1, bg_tot_e));
  double t1bbbb_1500_100_n(ht1bbbb_1500_100->IntegralAndError(0,nbinsx+1, t1bbbb_1500_100_e));


  printf("Counts before cut: %s\n",var.Data());
  printf("&ttbar&qcd&znn&wjets&single top&other&t1bbbb_1500_100\\\\ \n");
  printf("%s & %3.2f+-%3.2f & %3.2f+-%3.2f & %3.2f+-%3.2f & %3.2f+-%3.2f & %3.2f+-%3.2f & %3.2f+-%3.2f & %3.2f+-%3.2f & %3.2f+-%3.2f \\\\\n",
	 var.Data(),
	 ttbar_n,ttbar_e,
	 qcd_n,qcd_e,
	 znn_n,znn_e,
	 wjets_n,wjets_e,
	 single_top_n,single_top_e,
	 other_n,other_e,
	 bg_tot,bg_tot_e,
	 t1bbbb_1500_100_n,t1bbbb_1500_100_e);


  cout << "... DONE: filled histograms." << endl;
  
  THStack * hs = new THStack("hs", "");
  hs->Add(hother);
  hs->Add(hznn);
  hs->Add(hsingle_top);
  hs->Add(hwjets);
  hs->Add(httbar);
  hs->Add(hqcd);

  //hs->GetYaxis()->SetTitle("Events / 5 fb^{-1}");
  //hs->GetXaxis()->SetTitle(httbar->GetXaxis()->GetTitle());

  // Setup histogram styles
  set_style(httbar, "ttbar");
  set_style(hqcd, "qcd");
  set_style(hznn, "znn");
  set_style(hwjets, "wjets");
  set_style(hother, "other");
  set_style(hsingle_top, "single_top");

  // Setup auxiliary histograms (ratios, errors, etc)
  TH1D * staterr = (TH1D *) hmc_exp->Clone("staterr");
  staterr->Sumw2();
  //staterr->SetFillColor(kRed);
  staterr->SetFillColor(kGray+3);
  staterr->SetMarkerSize(0);
  staterr->SetFillStyle(3013);

 
  // Setup legends
  TLegend * leg1 = new TLegend(0.48, 0.68, 0.72, 0.92);
  set_style(leg1,0.025);
  if (plotData) leg1->AddEntry(hsingle_top, "Data", "pel");
  if (plotSig) {
    if (plotT1tttt) {
      leg1->AddEntry(hSMSLargeSplitting, "#splitline{T1tttt}{(1500,100) GeV}", "l");
      leg1->AddEntry(hSMSCompressed, "#splitline{T1tttt}{(1200,800) GeV}", "l");
    }
    else {
      leg1->AddEntry(hSMSLargeSplitting, "#splitline{T1bbbb}{(1500,100) GeV}", "l");
      leg1->AddEntry(hSMSCompressed, "#splitline{T1bbbb}{(1000,900) GeV}", "l");
    }
  }
  leg1->AddEntry(httbar, "t#bar{t}", "f");
  leg1->AddEntry(hqcd, "QCD", "f");

  TLegend * leg2 = new TLegend(0.72, 0.68, 0.94, 0.92);
  set_style(leg2,0.025);
  leg2->AddEntry(hznn, "Z+jets", "f");
  leg2->AddEntry(hwjets, "W+jets", "f");
  leg2->AddEntry(hsingle_top, "Single Top", "f");
  leg2->AddEntry(hother, "Other", "f");
  leg2->AddEntry(staterr, "MC uncert.", "f");

  double ymax = hs->GetMaximum();


  if(plotLog) {
    hs->SetMaximum(100*ymax);
    hs->SetMinimum(0.1);
  }
  else hs->SetMaximum(1.1*ymax);
  // Vertical lines for cuts
  TLine* line_low = new TLine(cut_low,0,cut_low,1.5*ymax);
  TLine* line_high = new TLine(cut_high,0,cut_high,1.5*ymax);
  set_style(line_low);
  set_style(line_high);

  // Setup canvas and pads  
  TCanvas * c1 = new TCanvas("c1", "c1", 700, 700);
  TPad * pad1 = new TPad("pad1", "top pad" , 0.0, 0.3, 1.0, 1.0);
  TPad * pad2 = new TPad("pad2", "bottom pad", 0.0, 0.0, 1.0, 0.3);
  if(plotData) {
    pad1->SetBottomMargin(0.0);
    pad1->Draw();
    pad2->SetTopMargin(0.0);
    pad2->SetBottomMargin(0.35);
    pad2->Draw();
    pad1->cd();
    pad1->SetLogy(plotLog);
  }
  else {
    c1->cd();
    c1->SetLogy(plotLog);
  }
  // Draw hists
  hs->Draw("hist");
  hs->SetTitle(hmc_exp->GetTitle());
  hs->GetXaxis()->SetTitle(httbar->GetXaxis()->GetTitle());
  hs->GetYaxis()->SetTitle(ytitle);
  hs->GetXaxis()->SetLabelSize(0.04);
  hs->GetYaxis()->SetLabelSize(0.04);
  if (plotData) 
    {
      //  hsingle_top->Draw("e1 same");
      hs->GetXaxis()->SetLabelSize(0);
    }
  staterr->Draw("e2 same");
  if (plotSig) {
    hSMSLargeSplitting->SetLineColor(2);
    hSMSLargeSplitting->SetLineWidth(3);
    hSMSLargeSplitting->SetFillColor(0);
    hSMSCompressed->SetLineColor(kMagenta+2);
    hSMSCompressed->SetLineWidth(3);
    hSMSCompressed->SetFillColor(0);
    hSMSLargeSplitting->Draw("hist same");
    hSMSCompressed->Draw("hist same");
  }
  if (cut_low>0) line_low->Draw("same");
  if (cut_high>0) line_high->Draw("same");


  // Draw legends
  leg1->Draw();
  leg2->Draw();
  TLatex * latex = new TLatex();
  latex->SetNDC();
  latex->SetTextAlign(12);
  latex->SetTextFont(62);
  latex->SetTextSize(0.042);
  latex->DrawLatex(0.19, 0.89, "CMS Simulation");
  latex->SetTextSize(0.03);
  latex->DrawLatex(0.19, 0.84, "#sqrt{s} = 13 TeV, L = 20 fb^{-1}");
  
  // Print
  cout << "MakePlots(): Printing..." << endl;

  c1->cd();
  if (plot_title.EqualTo("default")) plot_title=plotdir+var;
  gPad->Print(plotdir+plot_title+".pdf");

  TFile* outrootfile = TFile::Open(plotdir+plot_title+".root", "RECREATE");
  httbar->Write();
  hqcd->Write();
  hznn->Write();
  hwjets->Write();
  hother->Write();
  hSMSLargeSplitting->Write();
  hSMSCompressed->Write();
  hmc_exp->Write();
  hsingle_top->Write();
  outrootfile->Close();

  // Clean up
  delete staterr;
  delete leg1;
  delete leg2;
  delete latex;
  // delete pave;
  delete hs;
  delete pad1;
  delete pad2;
  delete c1;

  delete httbar;
  delete hqcd;
  delete hznn;
  delete hwjets;
  delete hsingle_top;
  delete hother;
  delete hmc_exp;
  delete ht1bbbb_1500_100;
  delete ht1tttt_1500_100;
  delete ht1bbbb_1000_900;
  delete ht1tttt_1200_800;
  //  delete hSMSLargeSplitting;
  // delete hSMSCompressed;

  cout << "MakePlots(): DONE!" << endl;

  return;
}
void SF_e(TString fileName_Data = "SingleElectron_Run2016_TP.root", // // RooT file with TP otree for data 
					TString fileName_MC ="DYJetsToLL_TP_Electron.root", // RooT file with TP otree for MC
					TString what = "IdIso", // or Mu8, IsoMu, ...
					float iso = 0.1, //isolation cut to be used
					float norm = 1 // luminosity normalization factor (1 for data) 
					) 
{

	gErrorIgnoreLevel = kFatal;

  // output inizialization 
  TString lepton = "Electron";
	TString OutFileName = lepton + "_" + what + "_IsoLt" + Form("%.2f", iso) + "_eff_Spring16";
	TFile * outputFile = new TFile(OutFileName+".root","recreate");

	// Title of axis in plots  
	TString yTitle = "Efficiency";
	TString xTitle = lepton+"  p_{T}[GeV]";
	TString xtit; 
	xtit = "m_{ee}[GeV]"; 

	//names of final graphs - suffix
	TString SampleName = "_Data";

	//open input file
	TFile * file1 = new TFile(fileName_Data);
	TFile * file2 = new TFile(fileName_MC);
  file1->cd();
  TTree *t1 = (TTree*)(file1->Get("TagProbe"));
  file2->cd();
  TTree *t2 = (TTree*)(file2->Get("TagProbe"));
  file1->cd();


  //binning inizialization

  int nEtaBins = 2;
	float etaBins[3] = {0,1.48,2.5};

	TString EtaBins[2] = {"EtaLt1p48",
				"EtaGt1p48"};

	float ptBins_def[8] = {10,15,20,25,30,40,60,1000};

	TString PtBins_def[7] = {"Pt10to15",
       "Pt15to20",
       "Pt20to25",
       "Pt25to30",
       "Pt30to40",
       "Pt40to60",
       "PtGt60"};

  float ptBinsTrig_def[17] = {10,
			  13,
			  16,
			  19,
			  22,
			  25,
			  28,
			  31,
			  34,
			  37,
			  40,
			  45,
			  50,
			  60,
			  70,
			  100,
				1000};

	TString PtBinsTrig_def[16] = {"Pt10to13",
		    "Pt13to16",
		    "Pt16to19",
		    "Pt19to22",
		    "Pt22to25",
		    "Pt25to28",
		    "Pt28to31",
		    "Pt31to34",
		    "Pt34to37",
		    "Pt37to40",
		    "Pt40to45",
		    "Pt45to50",
		    "Pt50to60",
		    "Pt60to70",
		    "Pt70to100",
		    "PtGt100"};

	int nPtBins = 16; if(what == "IdIso") nPtBins = 7;
	float * ptBins = new float[nPtBins+1];
	TString * PtBins = new TString[nPtBins];

	if(what == "IdIso"){
		for(int i=0; i<nPtBins; ++i){
			ptBins[i] = ptBins_def[i];
			PtBins[i] = PtBins_def [i];
		}
		ptBins[nPtBins] = ptBins_def[nPtBins];
	} else {
		for(int i=0; i<nPtBins; ++i){
			ptBins[i] = ptBinsTrig_def[i];
			PtBins[i] = PtBinsTrig_def[i];
		}
		ptBins[nPtBins] = ptBinsTrig_def[nPtBins];
	}


  //	create eta histogram with eta ranges associated to their names (eg. endcap, barrel)   ***** //

	TH1D * etaBinsH = new TH1D("etaBinsH", "etaBinsH", nEtaBins, etaBins);
  etaBinsH->Draw();
  etaBinsH->GetXaxis()->Set(nEtaBins, etaBins);
  for (int i=0; i<nEtaBins; i++){ etaBinsH->GetXaxis()->SetBinLabel(i+1, EtaBins[i]);}
  etaBinsH->Draw();


	//	create pt histogram_s with pt ranges associated to their names (eg. Pt10to13, ..)   ***** //

	TH1D * ptBinsH =  new TH1D("ptBinsH", "ptBinsH", nPtBins, ptBins);
  ptBinsH->Draw();
  ptBinsH->GetXaxis()->Set(nPtBins, ptBins);
  for (int i=0; i<nPtBins; i++){ ptBinsH->GetXaxis()->SetBinLabel(i+1, PtBins[i]);}
  ptBinsH->Draw();

  float ptBins_edges[nPtBins+1];

	for (int i=0; i<nPtBins; i++) { ptBins_edges[i]=ptBinsH->GetBinLowEdge(i+1); }
	ptBins_edges[nPtBins]= ptBinsH->GetBinLowEdge(nPtBins+1); 

  
	// define if in the fit of failing probes
  // the FSR component will be used in the 
  // signal function 
  bool fitWithFSR[nPtBins];

  for (int i=0; i<nPtBins; i++)  fitWithFSR[i] = false;

  if(what == "IdIso"){
   	fitWithFSR[2]=true;
    fitWithFSR[3]=true;
  } 

	// building the histogram base name
  TString prefix = "ZMass";
  TString which = what; if (what == "IdIso") which = "";
  TString histBaseName; 

  TCut cut_flag_idiso_pass, cut_flag_hlt_pass, cut_flag_hlt_fail, cut_pt, cut_eta;

  if (what == "IdIso") {
  	cut_flag_idiso_pass = Form("id_probe == 1 && iso_probe < %f", iso);
  } else{
  		if(what == "hlt_1") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_1_probe == 0"; }
  		if(what == "hlt_2") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_2_probe == 0"; }
  		if(what == "hlt_3") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_3_probe == 0"; }
  		if(what == "hlt_4") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_4_probe == 0"; }
  		if(what == "hlt_5") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_5_probe == 0"; }
  		if(what == "hlt_6") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_6_probe == 0"; }
  		if(what == "hlt_7") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_7_probe == 0"; }
  		if(what == "hlt_8") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_8_probe == 0"; }
  		if(what == "hlt_9") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_9_probe == 0"; }
  		if(what == "hlt_10") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_10_probe == 0"; }
  		if(what == "hlt_11") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_11_probe == 0"; }
  		if(what == "hlt_12") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_12_probe == 0"; }
  		if(what == "hlt_13") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_13_probe == 0"; }
  		if(what == "hlt_14") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_14_probe == 0"; }
  		if(what == "hlt_15") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_15_probe == 0"; }
  		if(what == "hlt_16") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_16_probe == 0"; }
  		if(what == "hlt_17") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_17_probe == 0"; }
  		if(what == "hlt_18") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_18_probe == 0"; }
  		if(what == "hlt_19") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_19_probe == 0"; }
  		if(what == "hlt_20") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_20_probe == 0"; }
  	}


	TString dir_name1 = "Electron_";
	TString dir_name2 = "Electron_";
	dir_name1 += what;
	dir_name2 += what;
	dir_name1 += Form("%.2f", iso);
	dir_name2 += Form("%.2f", iso);
	dir_name2 += "_MC";
	dir_name1 += "_eff";
	dir_name2 += "_eff";
	gSystem->mkdir(dir_name1, kTRUE);
	gSystem->mkdir(dir_name2, kTRUE);

//////////////DATA

	for (int iEta = 0; iEta < nEtaBins; iEta++) {

		histBaseName = prefix+which+EtaBins[iEta];

		cut_eta = Form("abs(eta_probe)>= %f && abs(eta_probe)< %f", etaBins[iEta], etaBins[iEta+1]);

		TH1F * numeratorH   = new TH1F("numeratorH","",nPtBins,ptBins_edges);
		TH1F * denominatorH = new TH1F("denominatorH","",nPtBins,ptBins_edges);
	
	  for (int iPt=0; iPt<nPtBins; ++iPt) {

	  	cut_pt = Form("pt_probe > %f && pt_probe < %f", ptBins[iPt], ptBins[iPt+1]);

	  	TH1F * histPassOld = new TH1F("histPassOld","",250,50,300);
	  	TH1F * histFailOld = new TH1F("histFailOld","",250,50,300);
	  	
	  	if (what == "IdIso") {
		  	t1->Draw("m_vis>>histPassOld", "pu_weight*mcweight" + (cut_eta && cut_pt && cut_flag_idiso_pass));
		  	t1->Draw("m_vis>>histFailOld", "pu_weight*mcweight" + (cut_eta && cut_pt && !cut_flag_idiso_pass));
		  }else{
		  	t1->Draw("m_vis>>histPassOld", "pu_weight*mcweight" + (cut_eta && cut_pt && cut_flag_hlt_pass && cut_flag_idiso_pass));
		  	t1->Draw("m_vis>>histFailOld", "pu_weight*mcweight" + (cut_eta && cut_pt && cut_flag_hlt_fail && cut_flag_idiso_pass));
		  }

	  	int nBinsX = histPassOld->GetNbinsX();

	    for (int iB=1;iB<=nBinsX;++iB) {
	      histPassOld->SetBinContent(iB,norm*histPassOld->GetBinContent(iB));
	      histPassOld->SetBinError(iB,norm*histPassOld->GetBinError(iB));
	      histFailOld->SetBinContent(iB,norm*histFailOld->GetBinContent(iB));
	      histFailOld->SetBinError(iB,norm*histFailOld->GetBinError(iB));
	    }

	    float output[2];
	    TCanvas * c1 = new TCanvas("c1","",700,600);
	    TCanvas * c2 = new TCanvas("c2","",700,600);
	    bool fitPass = true; 
	    bool fitFail = true;
	    bool rebinPass = false;
	    bool rebinFail = false;
	    if(what != "IdIso") {fitPass= false; fitFail = false;}

	    FitPassAndFail(fileName_Data,
	    	histBaseName+PtBins[iPt],
	    	xtit,
	    	histPassOld,
	    	histFailOld,
	    	fitPass,
	    	fitFail,
	    	fitWithFSR[iPt],
	    	rebinPass,
	    	rebinFail,
	    	c1,
	    	c2,
	    	output,
	    	dir_name1);

	    c1->cd();
	    c1->Update();
	    c2->cd();
	    c2->Update();
	    numeratorH->SetBinContent(iPt+1,output[0]);
	    denominatorH->SetBinContent(iPt+1,output[0]+output[1]);

	  }

	  outputFile->cd();

	  TGraphAsymmErrors * eff = new TGraphAsymmErrors();
	  eff->Divide(numeratorH,denominatorH);

	  eff->GetXaxis()->SetTitle(xTitle);
	  //  eff->GetXaxis()->SetRangeUser(10.01,59.99);
	  eff->GetYaxis()->SetRangeUser(0,1.0);
	  eff->GetXaxis()->SetRangeUser(0,99.99);
	  eff->GetYaxis()->SetTitle(yTitle);
	  eff->GetXaxis()->SetTitleOffset(1.1);
	  eff->GetXaxis()->SetNdivisions(510);
	  eff->GetYaxis()->SetTitleOffset(1.1);
	  eff->SetMarkerStyle(21);
	  eff->SetMarkerSize(1);
	  eff->SetMarkerColor(kBlue);
	  eff->SetLineWidth(2);
	  eff->SetLineColor(kBlue);


	  TCanvas * canv = new TCanvas("canv","",700,600);
	  eff->Draw("APE");
	  canv->SetGridx();
	  canv->SetGridy();
	  canv->Update();

	  canv->SaveAs(dir_name1+ "/" + fileName_Data+"_" + histBaseName + ".png");
	  eff->Write(histBaseName+SampleName);

//	  for(int ip=0; ip<nPtBins; ++ip){
//		cout<<"PtBins "<<ip<<" content: "<<numeratorH->GetBinContent(ip)/ denominatorH->GetBinContent(ip)<<endl;
//		}

	}

//////////////MC

	SampleName = "_MC";

	for (int iEta = 0; iEta < nEtaBins; iEta++) {

		histBaseName = prefix+which+EtaBins[iEta];

		cut_eta = Form("abs(eta_probe)>= %f && abs(eta_probe)< %f", etaBins[iEta], etaBins[iEta+1]);

		TH1F * numeratorH   = new TH1F("numeratorH","",nPtBins,ptBins_edges);
		TH1F * denominatorH = new TH1F("denominatorH","",nPtBins,ptBins_edges);
	
	  for (int iPt=0; iPt<nPtBins; ++iPt) {

	  	cut_pt = Form("pt_probe > %f && pt_probe < %f", ptBins[iPt], ptBins[iPt+1]);

	  	TH1F * histPassOld = new TH1F("histPassOld","",250,50,300);
	  	TH1F * histFailOld = new TH1F("histFailOld","",250,50,300);
	  	
	  	if (what == "IdIso") {
		  	t2->Draw("m_vis>>histPassOld", "pu_weight*mcweight" + (cut_eta && cut_pt && cut_flag_idiso_pass));
		  	t2->Draw("m_vis>>histFailOld", "pu_weight*mcweight" + (cut_eta && cut_pt && !cut_flag_idiso_pass));
		  }else{
		  	t2->Draw("m_vis>>histPassOld", "pu_weight*mcweight" + (cut_eta && cut_pt && cut_flag_hlt_pass && cut_flag_idiso_pass));
		  	t2->Draw("m_vis>>histFailOld", "pu_weight*mcweight" + (cut_eta && cut_pt && cut_flag_hlt_fail && cut_flag_idiso_pass));
		  }

	  	int nBinsX = histPassOld->GetNbinsX();

	    for (int iB=1;iB<=nBinsX;++iB) {
	      histPassOld->SetBinContent(iB,norm*histPassOld->GetBinContent(iB));
	      histPassOld->SetBinError(iB,norm*histPassOld->GetBinError(iB));
	      histFailOld->SetBinContent(iB,norm*histFailOld->GetBinContent(iB));
	      histFailOld->SetBinError(iB,norm*histFailOld->GetBinError(iB));
	    }

	    float output[2];
	    TCanvas * c1 = new TCanvas("c1","",700,600);
	    TCanvas * c2 = new TCanvas("c2","",700,600);
	    bool fitPass = true; 
	    bool fitFail = true;
	    bool rebinPass = false;
	    bool rebinFail = false;
	    if(what != "IdIso") {fitPass= false; fitFail = false;}

	    FitPassAndFail(fileName_MC,
	    	histBaseName+PtBins[iPt],
	    	xtit,
	    	histPassOld,
	    	histFailOld,
	    	fitPass,
	    	fitFail,
	    	fitWithFSR[iPt],
	    	rebinPass,
	    	rebinFail,
	    	c1,
	    	c2,
	    	output,
	    	dir_name2);

	    c1->cd();
	    c1->Update();
	    c2->cd();
	    c2->Update();
	    numeratorH->SetBinContent(iPt+1,output[0]);
	    denominatorH->SetBinContent(iPt+1,output[0]+output[1]);

	  }

	  outputFile->cd();

	  TGraphAsymmErrors * eff = new TGraphAsymmErrors();
	  eff->Divide(numeratorH,denominatorH);

	  eff->GetXaxis()->SetTitle(xTitle);
	  //  eff->GetXaxis()->SetRangeUser(10.01,59.99);
	  eff->GetYaxis()->SetRangeUser(0,1.0);
	  eff->GetXaxis()->SetRangeUser(0,99.99);
	  eff->GetYaxis()->SetTitle(yTitle);
	  eff->GetXaxis()->SetTitleOffset(1.1);
	  eff->GetXaxis()->SetNdivisions(510);
	  eff->GetYaxis()->SetTitleOffset(1.1);
	  eff->SetMarkerStyle(21);
	  eff->SetMarkerSize(1);
	  eff->SetLineWidth(2);
  	eff->SetMarkerColor(kRed);
  	eff->SetLineColor(kRed);


	  TCanvas * canv = new TCanvas("canv","",700,600);
	  eff->Draw("APE");
	  canv->SetGridx();
	  canv->SetGridy();
	  canv->Update();

	  canv->SaveAs(dir_name2+ "/" + fileName_MC+"_" + histBaseName + ".png");
	  eff->Write(histBaseName+SampleName);

//	  for(int ip=0; ip<nPtBins; ++ip){
//		cout<<"PtBins "<<ip<<" content: "<<numeratorH->GetBinContent(ip)/ denominatorH->GetBinContent(ip)<<endl;
//		}

	}

	outputFile->cd(); 
  etaBinsH->Write();
  outputFile->Close();

}
Exemple #12
0
//----------------------------------------------------------------------
void phroc2ps( )
{
  using namespace std;

  gROOT->Time();

  // set styles:

  gStyle->SetTextFont(62); // 62 = Helvetica bold LaTeX
  gStyle->SetTextAlign(11);

  gStyle->SetTickLength( -0.02, "x" ); // tick marks outside
  gStyle->SetTickLength( -0.02, "y" );
  gStyle->SetTickLength( -0.02, "z" );

  gStyle->SetLabelOffset( 0.022, "x" );
  gStyle->SetLabelOffset( 0.022, "y" );
  gStyle->SetLabelOffset( 0.022, "z" );
  gStyle->SetLabelFont( 62, "X" );
  gStyle->SetLabelFont( 62, "Y" );
  gStyle->SetLabelFont( 62, "Z" );

  gStyle->SetTitleOffset( 1.3, "x" );
  gStyle->SetTitleOffset( 2.0, "y" );
  gStyle->SetTitleOffset( 1.9, "z" );
  gStyle->SetTitleFont( 62, "X" );
  gStyle->SetTitleFont( 62, "Y" );
  gStyle->SetTitleFont( 62, "Z" );

  gStyle->SetTitleBorderSize(0); // no frame around global title
  gStyle->SetTitleX( 0.20 ); // global title
  gStyle->SetTitleY( 0.98 ); // global title
  gStyle->SetTitleAlign(13); // 13 = left top align

  gStyle->SetLineWidth(1);// frames
  gStyle->SetHistLineColor(4); // 4=blau
  gStyle->SetHistLineWidth(3);
  gStyle->SetHistFillColor(5); // 5 = gelb
  //  gStyle->SetHistFillStyle(4050); // 4050 = half transparent
  gStyle->SetHistFillStyle(1001); // 1001 = solid

  gStyle->SetFrameLineWidth(2);

  // statistics box:

  gStyle->SetOptStat(11);
  gStyle->SetStatFormat( "8.6g" ); // more digits, default is 6.4g
  gStyle->SetStatFont(42); // 42 = Helvetica normal
  //  gStyle->SetStatFont(62); // 62 = Helvetica bold
  gStyle->SetStatBorderSize(1); // no 'shadow'

  gStyle->SetStatX(0.80); // cvsq
  gStyle->SetStatY(0.90);

  gStyle->SetPalette(1); // rainbow colors

  gStyle->SetHistMinimumZero(); // no zero suppression

  gStyle->SetOptDate();

  gROOT->ForceStyle();

  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  // book new histos:

  TH1D* hnpt = new TH1D( "hnpt", "data points;data points;pixels", 512, 0.5, 512.5 );
  TH1D* hiter = new TH1D( "hiter", "fit iterations;fit iterations;pixels", 100, 0, 1000 );
  TH1D* hchisq = new TH1D( "hchisq", "chisq/ndof;chisq/ndof;pixels", 100, 0, 10 );

  TH1D* hmax = new TH1D( "hmax", "Amax;Amax [ADC];pixels", 256, 0, 256 );

  TH1D* hoff = new TH1D( "hoff", "Weibull PH at 0;Weibull PH at 0 [ADC];pixels", 250, 0, 250 );
  TH1D* htop = new TH1D( "htop", "top PH;maximum PH [ADC];pixels", 256, -0.5, 255.5 );

  TH1D* hinf = new TH1D( "hinf", "inflection point;point of maximum gain [large Vcal DACs];pixels", 200, 0, 100 );
  TH1D* hslp = new TH1D( "hslp", "max slope;Weibull max slope [ADC/DAC];pixels", 500, 0, 5 );
  TH1D* hrat = new TH1D( "hrat", "large/small;large/small Vcal;pixels", 100, 6, 8 );

  TProfile2D* h10 = new TProfile2D( "h10", "Weibull PH at 0 map;col;row;Weibull PH at 0 [ADC]", 52, -0.5, 51.5, 80, -0.5, 79.5, -100, 250 );
  TProfile2D* h11 = new TProfile2D( "h11", "top PH map;col;row;maximum PH [ADC]", 52, -0.5, 51.5, 80, -0.5, 79.5, 0, 300 );
  TProfile2D* h12 = new TProfile2D( "h12", "inflection point map;col;row;Weibull inflection point [large Vcal DAC]", 52, -0.5, 51.5, 80, -0.5, 79.5, 0, 250 );
  TProfile2D* h13 = new TProfile2D( "h13", "maximum gain map;col;row;Weibull maximum gain [ADC/large Vcal DAC]", 52, -0.5, 51.5, 80, -0.5, 79.5, 0, 50 );
  TProfile2D* h14 = new TProfile2D( "h14", "ratio map;col;row;large/small Vcal", 52, -0.5, 51.5, 80, -0.5, 79.5, 0, 20 );
  TProfile2D* h15 = new TProfile2D( "h15", "chisq map;col;row;mpfit chisq", 52, -0.5, 51.5, 80, -0.5, 79.5, 0, 99 );

  // open output file:

  ofstream gainfile( "phroc.dat" );

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

  cout << "pwd: ";
  gDirectory->pwd();

  cout << "gDir " << gDirectory->GetName() << endl;

  gDirectory->ls();

  cout << "keys " << gDirectory->GetNkeys() << endl;

  TH2D * h24 = NULL; // large Vcal (CtrlReg 4)
  TH2D * h20 = NULL; // small Vcal (CtrlReg 0)
  int found = 0;

  TIter nextkey( gDirectory->GetListOfKeys() );

  TKey * key;

  while( ( key = (TKey*)nextkey() ) ) {

    TObject * obj = key->ReadObj();

    if( obj->InheritsFrom( "TH2D" ) ) {
      //    if( obj->IsA()->InheritsFrom( "TH2D" ) ) {     ROOT 5

      TH2D * h2 = (TH2D*)obj;

      string hn = h2->GetName(); // PH_DAC25_CR4_Vcal222_map

      if( h24 == NULL && hn.substr( 0, 12 ) == "PH_DAC25_CR4" ) {
	h24 = h2;
	found++;
	cout << "Large Vcal: " << hn
	     << " has " << h24->GetNbinsX()
	     << " x " << h24->GetNbinsY() << " bins"
	     << " with " << (int) h24->GetEntries() << " entries"
	     << ", sum " << h24->GetSum()
	     << endl;
      }

      if( h20 == NULL && hn.substr( 0, 12 ) == "PH_DAC25_CR0" ) {
	h20 = h2;
	found++;
	cout << "Small Vcal: " << hn
	     << " has " << h20->GetNbinsX()
	     << " x " << h20->GetNbinsY() << " bins"
	     << " with " << (int) h20->GetEntries() << " entries"
	     << ", sum " << h20->GetSum()
	     << endl;
      }

    } // TH2

  } // while over keys

  if( found != 2 ) {
    cout << "PH_DAC25_CR4, PH_DAC25_CR0 found " << found
	 << ", return"
	 << endl;
    return;
  }

  bool err = 0;
  int npx = 0;

  for( int px = 0; px < h24->GetNbinsX(); ++px ) { // pixels
    //for( int px = 200; px <= 200; ++px ) { // test
    //for( int px = 1559; px <= 1559; ++px ) { // debug
    //for( int px = 3331; px <= 3331; ++px ) { // debug

    npx++;

    double a = 0;
    double b = 0;
    double p = 0;
    double g = 0;
    double v = 0;
    double r = 0;

    int col = px / 80; // 0..51
    int row = px % 80; // 0..79

    cout << endl
	 << "pixel " << setw(2) << col << setw(3) << row << setw(5) << px
	 << endl;

    double phmax = 0;

    const int mdata = 256;
    double x4[mdata] = {0};
    double y4[mdata] = {0};

    int n4 = h24->GetNbinsY();
    if( n4 > mdata ) {
      cout << "h24 too many y bins " << n4 << endl;
      n4 = mdata;
    }

    for( int ii = 0; ii < n4; ++ii ) { // dacs

      double ph = h24->GetBinContent( px+1, ii+1 ); // ROOT bin counting starts at 1
      if( ph > phmax ) phmax = ph;
      x4[ii] = ii;
      y4[ii] = ph;

    }

    hmax->Fill( phmax );

    // valid data?

    if( phmax > 9 ) {

      // fit range:

      int ib0 = 1; // bin 0 is spike
      int ib9 = n4-1; // last bin
      double phprv = y4[ib9];

      for( int ii = ib9; ii > 0; --ii ) { // scan from right to left
	double ph = y4[ii];
	if( ph > 254.5 ) {
	  ib9 = ii-1; // avoid overflows
	  phprv = y4[ii-1];
	  continue;
	}
	//if( ph > 0 && abs( ph - phprv ) < 8 ) // stop at zero or spike
	if( ph > 0 ) // for high gain
	  ib0 = ii; // overwritten
	else
	  break; // first zero bin from right
	phprv = ph;
      }

      cout << "large Vcal fit range " << setw(3) << ib0
	   << " to " << setw(3) << ib9;

      // shift data vectors left:

      int jj = 0;
      for( int ii = ib0; ii <= ib9; ++ii ) {
	x4[jj] = x4[ii];
	y4[jj] = y4[ii];
	jj++;
      }
      cout << " = " << setw(3) << jj << " points" << endl;

      // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      // low range Vcal:

      double x0[mdata] = {0};
      double y0[mdata] = {0};
      int n0 = h20->GetNbinsY();
      if( n0 > mdata ) {
	cout << "h20 too many y bins " << n0 << endl;
	n0 = mdata;
      }

      for( int ii = 0; ii < n0; ++ii ) { // dacs

	double ph = h20->GetBinContent( px+1, ii+1 ); // ROOT bin counting starts at 1
	x0[ii] = ii;
	y0[ii] = ph;

      }

      int jb0 = 1; // first bin is spike
      int jb9 = n0-1;
      double phprv0 = y0[jb9];

      for( int ii = jb9; ii > 0; --ii ) { // scan from right to left

	double ph = y0[ii];
	//if( ph > 0 && abs( ph - phprv0 ) < 4 ) // stop at zero or spike
	if( ph > 0 ) // high gain
	  jb0 = ii; // overwritten
	else
	  break; // first zero bin from right
	phprv0 = ph;
      }

      // shift left:

      int j2 = 0;
      for( int ii = jb0; ii <= jb9; ++ii ) {
	x0[j2] = x0[ii];
	y0[j2] = y0[ii];
	j2++;
      }
      cout << "small Vcal fit range " << setw(3) << jb0
	   << " to " << setw(3) << jb9
	   << " = " << setw(3) << j2 << " points" << endl;

      hnpt->Fill( jj+j2 );

      data2_struct mydata;
      mydata.Ndata = jj;
      mydata.Ndata2 = j2;
      mydata.Ncall = 0;
      mydata.xx = x4;
      mydata.yy = y4;
      mydata.x2 = x0;
      mydata.y2 = y0;

      // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      // NLopt:

      const int npar = 6;

      if( npx == 1 ) {
	int major, minor, bugfix;
	nlopt_version( &major, &minor, &bugfix );
	cout << "NLOPT " << major << "." << minor << "." << bugfix << endl;
      }

      //nlopt_opt myopt = nlopt_create( NLOPT_GN_DIRECT_L, npar );
      //nlopt_opt myopt = nlopt_create( NLOPT_GN_DIRECT_L_NOSCAL,npar ); // bad

      //nlopt_opt myopt = nlopt_create( NLOPT_GN_CRS2_LM, npar ); // nice, 1'033
      //nlopt_opt myopt = nlopt_create( NLOPT_GN_ISRES, npar ); // nice, 12'067

      // Local, no derivative:

      nlopt_opt myopt = nlopt_create( NLOPT_LN_NELDERMEAD, npar ); // chisq 313
      //nlopt_opt myopt = nlopt_create( NLOPT_LN_SBPLX, npar ); // chisq 336
      //nlopt_opt myopt = nlopt_create( NLOPT_LN_PRAXIS, npar ); // chisq 461

      //nlopt_opt myopt = nlopt_create( NLOPT_LN_COBYLA, npar ); // slow
      //nlopt_opt myopt = nlopt_create( NLOPT_LN_NEWUOA_BOUND, npar ); // poor
      //nlopt_opt myopt = nlopt_create( NLOPT_LN_BOBYQA, npar ); // chisq 313

      // need derivative dF/dpar:

      //nlopt_opt myopt = nlopt_create(   NLOPT_LD_MMA, npar ); // chisq 313, robust!
      //nlopt_opt myopt = nlopt_create( NLOPT_LD_LBFGS, npar ); // chisq 314
      //nlopt_opt myopt = nlopt_create( NLOPT_LD_SLSQP, npar ); // failure
      //nlopt_opt myopt = nlopt_create( NLOPT_LD_TNEWTON_PRECOND_RESTART, npar ); // csq 313

      if( npx == 1 ) {
	cout << "Algorithm " << nlopt_get_algorithm(myopt) << ":" << endl;
	cout << nlopt_algorithm_name( nlopt_get_algorithm(myopt) ) << endl;
      }

      nlopt_set_min_objective( myopt, FCN, &mydata ); // minimize chisq

      nlopt_set_ftol_abs( myopt, 1e-6 ); // convergence

      // set start values from high range:

      double par[npar];
      par[0] = 0.999; // horizontal offset, critical!
      par[1] = 1.97; // width, x scaled
      par[2] = 3394; // power
      par[3] = 1.1*phmax; // critical !
      par[4] = phmax;
      par[5] = 6.7;

      // initial step size:

      double dx[npar];
      dx[0] = 0.01; // shift
      dx[1] = 0.1; // width
      dx[2] = 2.9; // power
      dx[3] = 2.9; // scale
      dx[4] = 2.9; // asymptote
      dx[5] = 0.3; // ratio
      //nlopt_set_initial_step( myopt, dx ); // not needed, better without

      // lower bounds:

      double lb[npar];
      lb[0] = 0.9; // 
      lb[1] = 0.5; // width
      lb[2] = 10; // power
      lb[3] = 10; // scale
      lb[4] = 10; // asymptote
      lb[5] = 1.0; // ratio
      nlopt_set_lower_bounds( myopt, lb );

      // upper bounds:

      double ub[npar];
      ub[0] = 1.0; // !
      ub[1] = 5.0; // 
      ub[2] = 99900; // 
      ub[3] = 2*phmax; // 
      ub[4] = 2*phmax; // 
      ub[5] = 99.0; // ratio
      nlopt_set_upper_bounds( myopt, ub );

      mydata.flag = 0;
      cout << "starting chisq " << FCN( npar, par, 0, &mydata ) << endl;

      double minFCN;
      nlopt_result ret = nlopt_optimize( myopt, par, &minFCN );

      // man nlopt
      // less /usr/local/include/nlopt.h
      /*
	typedef enum {
	NLOPT_FAILURE = -1, // generic failure code
	NLOPT_INVALID_ARGS = -2,
	NLOPT_OUT_OF_MEMORY = -3,
	NLOPT_ROUNDOFF_LIMITED = -4,
	NLOPT_FORCED_STOP = -5,
	NLOPT_SUCCESS = 1, // generic success code
	NLOPT_STOPVAL_REACHED = 2,
	NLOPT_FTOL_REACHED = 3,
	NLOPT_XTOL_REACHED = 4,
	NLOPT_MAXEVAL_REACHED = 5,
	NLOPT_MAXTIME_REACHED = 6
	} nlopt_result;
      */
      cout << "nlopt_result " << ret
	   << " after " << mydata.Ncall << " loops"
	   << endl;
      double chisq = FCN( npar, par, 0, &mydata );
      cout << "chisq = " << mydata.chisq4 << " + " << mydata.chisq0
	   << " = " << chisq << endl;

      for( int j = 0; j < npar; ++j )
	cout << "par[" << j << "] = " << par[j] << endl;

      hiter->Fill( mydata.Ncall );
      int ndf = jj+j2-npar;
      hchisq->Fill( chisq/ndf );
      h15->Fill( col, row, chisq / ndf );

      a = par[0];
      b = par[1];
      p = par[2];
      g = par[3];
      v = par[4];
      r = par[5];

      TF1 *f1 = new TF1( "f1", Weibull, 0, 256, npar );
      for( int i = 0; i < npar-1; ++i ) 
	f1->SetParameter( i, par[i] );
      f1->SetParameter( 5, 1 ); // large Vcal

      double A0 = f1->Eval(0); // amplitude at zero
      double A255 = f1->Eval(255); // amplitude at 255

      // gradient = derivative = slope:

      TF1 *g1 = new TF1( "g1", dWeibdx, 0, 256, npar );
      for( int i = 0; i < npar-1; ++i )
	g1->SetParameter( i,  par[i] );
      g1->SetParameter( 5, 1 ); // large Vcal

      double tmax = pow( (p-1)/p, 1/p ); // zero 2nd deriv
      double xmax = (b * (tmax - a) )/G; // pos of max slope
      double gmax = g1->Eval(xmax); // max slope

      cout << "A0 " << A0
	   << ", A255 " << A255
	   << ", gmax " << gmax
	   << " at " << xmax
	   << endl;

      hoff->Fill( A0 );
      htop->Fill( A255 );
      hinf->Fill( xmax );
      hslp->Fill( gmax );
      hrat->Fill( r );

      h10->Fill( col, row, A0 );
      h11->Fill( col, row, A255 );
      h12->Fill( col, row, xmax );
      h13->Fill( col, row, gmax );
      h14->Fill( col, row, r );

      delete f1;
      delete g1;

    } // phmax > 9

    gainfile << "map";
    gainfile << setw(4) << col;
    gainfile << setw(4) << row;

    gainfile.setf(ios::fixed);
    gainfile.setf(ios::showpoint);

    gainfile << "  ";
    gainfile << setprecision(6);
    gainfile << setw(12) << a;   // horiz

    gainfile << "  ";
    gainfile << setprecision(1);
    gainfile << setw(12) << b/G;     // wid

    gainfile << "  ";
    gainfile << setprecision(1);
    gainfile << setw(12) << p;     // pow

    gainfile << "  ";
    gainfile << setprecision(1);
    gainfile << setw(12) << g;     // gain

    gainfile << "  ";
    gainfile << setprecision(1);
    gainfile << setw(12) << v;  // vert

    gainfile << "  ";
    gainfile << setprecision(3);
    gainfile << setw(12) << r;  // ratio

    gainfile << endl;

  } // while pixels

  if( err ) cout << endl << "Error" << endl << endl;

  gainfile.close();

  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  // square:
  //               topleft x, y, width x, y
  TCanvas c1( "c1", "c1", 585, 246, 863, 837 );

  c1.SetBottomMargin(0.15);
  c1.SetLeftMargin(0.15);
  c1.SetRightMargin(0.20); // for colz

  gPad->Update();// required

  //cout << "PadWidth  " << c1.GetWw() << endl;
  //cout << "PadHeight " << c1.GetWh() << endl;

  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  // create postscript file:

  c1.Print( "phroc.ps[", "Portrait" ); // [ opens file

  gStyle->SetPaperSize( 18, 27 );

  gStyle->SetOptStat(111111);
  gROOT->ForceStyle();

  hnpt->Draw();
  c1.Print( "phroc.ps" );

  hiter->Draw();
  c1.Print( "phroc.ps" );

  hchisq->Draw();
  c1.Print( "phroc.ps" );

  hmax->Draw();
  c1.Print( "phroc.ps" );

  hoff->Draw();
  c1.Print( "phroc.ps" );

  htop->Draw();
  c1.Print( "phroc.ps" );

  hslp->Draw();
  c1.Print( "phroc.ps" );

  hinf->Draw();
  c1.Print( "phroc.ps" );

  hrat->Draw();
  c1.Print( "phroc.ps" );

  gStyle->SetOptStat(10);
  gStyle->SetStatY(0.95);

  h10->Draw( "colz" ); // Weibull at 0
  c1.Print( "phroc.ps" );

  h11->Draw( "colz" ); // phmax
  c1.Print( "phroc.ps" );

  h12->Draw( "colz" ); // inflection point
  c1.Print( "phroc.ps" );

  h13->Draw( "colz" ); // gmax
  c1.Print( "phroc.ps" );

  h14->Draw( "colz" ); // large / small Vcal
  c1.Print( "phroc.ps" );

  // chisq map:

  h15->Draw( "colz" );
  c1.Print( "phroc.ps" );

  if( !err && hmax->GetEntries() > 99 ) {

    for( int ix = 1; ix <= h10->GetNbinsX(); ++ix )
      for( int iy = 1; iy <= h10->GetNbinsY(); ++iy ){
	if( h10->GetBinContent(ix,iy) < 1 || h10->GetBinContent(ix,iy) > 255 )
	  cout << "col " << setw(2) << ix-1
	       << ", row " << setw(2) << iy-1
	       << ", pix " << 80*(ix-1)+iy-1
	       << " Weibull at zero " << h10->GetBinContent(ix,iy)
	       << endl;
	if( h11->GetBinContent(ix,iy) < 5 || h11->GetBinContent(ix,iy) > 255 )
	  cout << "col " << setw(2) << ix-1
	       << ", row " << setw(2) << iy-1
	       << ", pix " << 80*(ix-1)+iy-1
	       << " max PH " << h11->GetBinContent(ix,iy)
	       << endl;
	if( h12->GetBinContent(ix,iy) < 5 || h12->GetBinContent(ix,iy) > 200 )
	  cout << "col " << setw(2) << ix-1
	       << ", row " << setw(2) << iy-1
	       << ", pix " << 80*(ix-1)+iy-1
	       << " inflection point " << h12->GetBinContent(ix,iy)
	       << endl;
	if( h13->GetBinContent(ix,iy) < 0.1 || h13->GetBinContent(ix,iy) > 5 )
	  cout << "col " << setw(2) << ix-1
	       << ", row " << setw(2) << iy-1
	       << ", pix " << 80*(ix-1)+iy-1
	       << " max slope " << h13->GetBinContent(ix,iy)
	       << endl;
	if( h14->GetBinContent(ix,iy) < 1 || h14->GetBinContent(ix,iy) > 10 )
	  cout << "col " << setw(2) << ix-1
	       << ", row " << setw(2) << iy-1
	       << ", pix " << 80*(ix-1)+iy-1
	       << " bad Vcal ratio " << h14->GetBinContent(ix,iy)
	       << endl;
	if( h15->GetBinContent(ix,iy) > 10 )
	  cout << "col " << setw(2) << ix-1
	       << ", row " << setw(2) << iy-1
	       << " bad fit chisq " << h15->GetBinContent(ix,iy)
	       << endl;
      }
  }
  //--------------------------------------------------------------------

  c1.Print( "phroc.ps]" ); // ] closes file

  int ierr = 0;
  ierr = system( "ps2pdf phroc.ps" );
  ierr = system( "rm -f phroc.ps" );
  cout << "acroread phroc.pdf" << endl;

  //delete c1;

}
void plot_BGEst_trigger(string cutname="delphi", string histname="MHT"){

  ///////////////////////////////////////////////////////////////////////////////////////////
  ////Some cosmetic work for official documents. 
  //gROOT->LoadMacro("tdrstyle.C");
  //setTDRStyle();
  //gROOT->LoadMacro("CMS_lumi_v2.C");
  gStyle->SetOptStat(0);  ///to avoid the stat. on the plots 
  gStyle->SetPalette(1) ; // for better color output

  char tempname[200];
  char tempname2[200];
  int W = 600;
  int H = 600;
  int H_ref = 600;
  int W_ref = 800;
  float T = 0.08*H_ref;
  float B = 0.12*H_ref;
  float L = 0.12*W_ref;
  float R = 0.04*W_ref;

  TCanvas* canvas = new TCanvas("name","name",10,10,W,H);
  canvas->SetFillColor(0);
  canvas->SetBorderMode(0);
  canvas->SetFrameFillStyle(0);
  canvas->SetFrameBorderMode(0);
  canvas->SetLeftMargin( L/W );
  canvas->SetRightMargin( R/W );
  canvas->SetTopMargin( T/H );
  canvas->SetBottomMargin( B/H );
  canvas->SetTickx(0);
  canvas->SetTicky(0);
  
   canvas->Divide(1, 2);
  //
  // Define pads
  //
  TPad * canvas_up = (TPad*) canvas->GetListOfPrimitives()->FindObject("canvas_1");
  TPad * canvas_dw = (TPad*) canvas->GetListOfPrimitives()->FindObject("canvas_2");
  
   // set pad size
  canvas_up->SetPad(0., .25, 0.97, 1.);

  canvas_dw->SetPad(0., 0.07, 0.97, 0.25);
  canvas_up->SetFrameFillColor(0);
  canvas_up->SetFillColor(0);
  canvas_dw->SetFillColor(0);
  canvas_dw->SetFrameFillColor(0);
  canvas_dw->SetBottomMargin(0.3);

  // set top margin 0 for bottom figure
  canvas_dw->SetTopMargin(0);
  
  Float_t legendX1 = .20; //.50;
  Float_t legendX2 = .90; //.70;
  Float_t legendY1 = .70; //.65;
  Float_t legendY2 = .90;
  TLegend* catLeg1 = new TLegend(legendX1,legendY1,legendX2,legendY2);
  catLeg1->SetTextSize(0.032);
  catLeg1->SetTextFont(42);
  catLeg1->SetFillColor(0);
  catLeg1->SetLineColor(0);
  catLeg1->SetBorderSize(0);

  TFile *file_NoTrig = new TFile("InputRootFiles/HadTauEstimation_data_SingleMuon_v14c_.root","R");
  TFile *file_Mu15 = new TFile("InputRootFiles/HadTauEstimation_data_SingleMuon_v14c_HLT_Mu15_IsoVVVL_PFHT350_PFMET70_v_.root","R"); 
  TFile *file_Mu50   = new TFile("InputRootFiles/HadTauEstimation_data_SingleMuon_v14c_HLT_Mu50_v_.root","R");
  TFile *file_Mu15ORMu50 = new TFile("InputRootFiles/HadTauEstimation_data_SingleMuon_v14c_HLT_Mu50_v_OR_HLT_Mu15_IsoVVVL_PFHT350_PFMET70_v_.root","R"); 
  
    
  sprintf(tempname,"allEvents/%s/%s_%s_allEvents",cutname.c_str(),histname.c_str(),cutname.c_str());
  TH1D * NoTrigHist = (TH1D*)file_NoTrig->Get(tempname)->Clone();
  NoTrigHist->SetLineColor(41);
  NoTrigHist->SetLineWidth(2);
  TH1D * Mu15Hist = (TH1D*)file_Mu15->Get(tempname)->Clone();
  Mu15Hist->SetLineColor(1);
  Mu15Hist->SetLineWidth(2);
  TH1D * Mu50Hist = (TH1D*)file_Mu50->Get(tempname)->Clone();
  Mu50Hist->SetLineColor(2);
  Mu50Hist->SetLineWidth(2);
  TH1D * Mu15ORMu50Hist = (TH1D*)file_Mu15ORMu50->Get(tempname)->Clone();
  Mu15ORMu50Hist->SetLineColor(4);
  Mu15ORMu50Hist->SetLineWidth(2);
  
  NoTrigHist->SetMaximum(10.);
  if(histname=="MHT"){
	  NoTrigHist->SetMaximum(10.);
	  NoTrigHist->GetXaxis()->SetRangeUser(0.0,1000.);
  }
  if(histname=="HT"){
	  NoTrigHist->SetMaximum(10.);
	  NoTrigHist->GetXaxis()->SetRangeUser(0.0,1500.);
  }
  if(histname=="NJet"){
	  NoTrigHist->SetMaximum(10.);
	  NoTrigHist->GetXaxis()->SetRangeUser(3.0,10.);
  }
  if(histname=="NBtag"){
	  NoTrigHist->SetMaximum(15.);
	  NoTrigHist->GetXaxis()->SetRangeUser(0.0,4.);
  }
  NoTrigHist->SetTitle("");
  NoTrigHist->GetXaxis()->SetLabelFont(42);
  NoTrigHist->GetXaxis()->SetLabelOffset(0.007);
  NoTrigHist->GetXaxis()->SetLabelSize(0.032);
  NoTrigHist->GetXaxis()->SetTitleSize(0.036);
  NoTrigHist->GetXaxis()->SetTitleOffset(0.9);
  NoTrigHist->GetXaxis()->SetTitleFont(42);
  NoTrigHist->GetYaxis()->SetLabelFont(42);
  NoTrigHist->GetYaxis()->SetLabelOffset(0.007);
  NoTrigHist->GetYaxis()->SetLabelSize(0.032);
  NoTrigHist->GetYaxis()->SetTitleSize(0.036);
  NoTrigHist->GetYaxis()->SetTitleOffset(1.25);
  NoTrigHist->GetYaxis()->SetTitleFont(42);
  sprintf(tempname,"%s",histname.c_str());
  NoTrigHist->GetXaxis()->SetTitle(tempname);
  NoTrigHist->GetYaxis()->SetTitle("#event");
  
  
  // draw bottom figure 
  canvas_dw->cd();
  NoTrigHist->Draw(); 
  
  // draw top figure
  canvas_up->cd();
  
  
    catLeg1->SetHeader("Triggers:");
  
    NoTrigHist->Draw("same,hist");	
	sprintf(tempname,"(a): No Trigger");
    catLeg1->AddEntry(NoTrigHist,tempname,"l");

    Mu15Hist->Draw("same,hist");
    sprintf(tempname,"(b): HLT_Mu15_IsoVVVL_PFHT350_PFMET70_v");
    catLeg1->AddEntry(Mu15Hist,tempname,"l");
	
	Mu50Hist->Draw("same,hist");
	sprintf(tempname,"(c): HLT_Mu50_v");
	catLeg1->AddEntry(Mu50Hist,tempname,"l");
	
    Mu15ORMu50Hist->Draw("same,hist");
	sprintf(tempname,"(d): (b) or (c)");
	catLeg1->AddEntry(Mu15ORMu50Hist,tempname,"l");
  
  catLeg1->Draw();


  sprintf(tempname,"BGEstWithTriggers_%s_%s.png",cutname.c_str(),histname.c_str());
  canvas->Print(tempname);

}
Exemple #14
0
void plotRate(){
  //TFile * f_ttbar= new TFile("ttbar-output-2014-06-22.root");
  TFile * f= new TFile("./rateTest.root");
  std::vector<TString> jetnum;
  //jetnum.push_back("0");
  //jetnum.push_back("1");
  //jetnum.push_back("2");
  jetnum.push_back("3");
  std::vector<TString> truejetnum;
  //truejetnum.push_back("1");
//  truejetnum.push_back("2");
//  truejetnum.push_back("3");
  truejetnum.push_back("4");
  //jetType.push_back("calib_gct");
  int i = -1;
  for (iNum = jetnum.begin();iNum != jetnum.end(); iNum++)
  {
    i++;
    std::cout <<"jetNumber_"+*iNum+"/5400_calib_nopus_"+*iNum+"_Rate" << std::endl;
    TH1D* nopus = f->Get("jetNumber_"+*iNum+"/5400_calib_nopus_"+*iNum+"_Rate");
    TH1D* donutseed = f->Get("jetNumber_"+*iNum+"/5450_calib_donut_"+*iNum+"_Rate");
    TH1D* nopusseed = f->Get("jetNumber_"+*iNum+"/5450_calib_nopus_"+*iNum+"_Rate");
    TH1D* global = f->Get("jetNumber_"+*iNum+"/5400_calib_global_"+*iNum+"_Rate");
    TH1D* gct = f->Get("jetNumber_"+*iNum+"/gct_calib_gen_"+*iNum+"_Rate");


    TLegend* leg = new TLegend(0.55,0.55,0.85,0.85);
    leg->SetFillColor(0);
    TCanvas * c = new TCanvas("Turn on Curve "+*iNum+" (p_{T} ","",600,600);

    c->cd();
    nopus->GetXaxis()->SetTitle("Pt/GeV");
    nopus->SetTitle("");
    gStyle->SetOptStat(0);
    nopus->GetXaxis()->SetTitleOffset(1.4);
    nopus->GetYaxis()->SetTitle("Rate for jet "+truejetnum.at(i)+"/Hz");
    nopus->GetYaxis()->SetTitleOffset(1.4);
    nopus->SetLineColor(1);
    nopus->GetXaxis()->SetRangeUser(25,45);
    nopusseed->SetLineStyle(2);
    donutseed->SetLineColor(2);
    donutseed->SetMarkerColor(2);
    global->SetLineColor(4);
    gct->SetLineColor(8);
    global->SetMarkerColor(4);
    nopus->Draw();
    nopusseed->Draw("same");
    donutseed->Draw("same");
    global->Draw("same");
    gct->Draw("same");
    leg->AddEntry(nopus,"No PUS","l");
    leg->AddEntry(nopusseed,"No PUS (Seed 5)","l");
    leg->AddEntry(donutseed,"Donut Sub (Seed 5)","l");
    leg->AddEntry(global,"Global Sub","l");
    leg->AddEntry(gct,"GCT","l");
    leg->Draw("L");
    c->SaveAs("output/cmsweek/rate"+*iNum+".png");
  }
  return;
}
Exemple #15
0
int BfinderAna(
		TString infile="/data/twang/BfinderRun2/DoubleMu/BfinderData_pp_20151130/finder_pp_merged.root", 
		TString outfile="test.root", 
		Bool_t REAL=false, 
		Bool_t isPbPb=false, 
		Int_t startEntries=0, 
		Int_t endEntries=-1,  
		Bool_t skim=true, 
		Bool_t gskim=true, 
		Bool_t checkMatching=true, 
		Bool_t iseos=false, 
		Bool_t SkimHLTtree=true)
{
	if(istest)
	{
//		infile="/data/HeavyFlavourRun2/BfinderRun2/MC/crab_BfinderMC_pp_BJpsiMM_5p02TeV_TuneCUETP8M1_20160613_bPt0jpsiPt0tkPt0p5_Bp.root";
		infile="/data/HeavyFlavourRun2/BfinderRun2/MC/crab_BfinderMC_PbPb_Pythia8_BJpsiMM_ptJpsi_0_inf_Hydjet_MB_20160613_bPt5jpsiPt0tkPt0p8_Bp.root";
		outfile="test.root";
		REAL=false;
		isPbPb=false;
		skim=false;
		checkMatching=true;
		iseos=false;
	}

	cout<<endl;
	if(REAL) cout<<"--- Processing - REAL DATA";
	else cout<<"--- Processing - MC";
	if(isPbPb) cout<<" - PbPb";
	else cout<<" - pp";
	cout<<endl;

	TString ifname;
	if(iseos) ifname = Form("root://eoscms.cern.ch//eos/cms%s",infile.Data());
	else ifname = infile;
	TFile* f = TFile::Open(ifname);
	TTree* root = (TTree*)f->Get("Bfinder/root");
	TTree* hltroot = (TTree*)f->Get("hltanalysis/HltTree");
	TTree* skimroot = (TTree*)f->Get("skimanalysis/HltTree");
	TTree* hiroot = (TTree*)f->Get("hiEvtAnalyzer/HiTree");

	EvtInfoBranches     *EvtInfo = new EvtInfoBranches;
	VtxInfoBranches     *VtxInfo = new VtxInfoBranches;
	MuonInfoBranches    *MuonInfo = new MuonInfoBranches;
	TrackInfoBranches   *TrackInfo = new TrackInfoBranches;
	BInfoBranches       *BInfo = new BInfoBranches;
	GenInfoBranches     *GenInfo = new GenInfoBranches;

	setHltBranch(hltroot);
	setHiTreeBranch(hiroot);

	EvtInfo->setbranchadd(root);
	VtxInfo->setbranchadd(root);
	MuonInfo->setbranchadd(root);
	TrackInfo->setbranchadd(root);
	BInfo->setbranchadd(root);
	GenInfo->setbranchadd(root);

	Long64_t nentries = root->GetEntries();
	if(endEntries>nentries || endEntries == -1) endEntries = nentries;
	TFile *outf = TFile::Open(Form("%s", outfile.Data()),"recreate");

	cout<<"--- Check the number of events for four trees"<<endl;
	cout<<root->GetEntries()<<" "<<hltroot->GetEntries()<<" "<<hiroot->GetEntries();
	cout<<" "<<skimroot->GetEntries()<<endl;
	cout<<endl;

	//
	double min = 4.6;
	double max = 6.0;
	int nbin = (max-min)*50;
	TH1D* Bmass = new TH1D("Bmass","Bmass", nbin, min, max);
	TH1D* Bmass_nosig = new TH1D("Bmass_nosig","Bmass_nosig", nbin, min, max);
	TH1D* BmassBpPi = new TH1D("BmassBpPi","BmassBpPi", nbin, min, max);
	TH1D* BmassBpXPi = new TH1D("BmassBpXPi","BmassBpXPi", nbin, min, max);
	TH1D* BmassBpK = new TH1D("BmassBpK","BmassBpK", nbin, min, max);
	TH1D* BmassB0K = new TH1D("BmassB0K","BmassB0K", nbin, min, max);
	TH1D* BmassBpK_tkmatch = new TH1D("BmassBpK_tkmatch","BmassBpK_tkmatch", nbin, min, max);
	TH1D* BmassB0K_tkmatch = new TH1D("BmassB0K_tkmatch","BmassB0K_tkmatch", nbin, min, max);
	TH1D* BmassBpK_tknotmatch = new TH1D("BmassBpK_tknotmatch","BmassBpK_tknotmatch", nbin, min, max);
	TH1D* BmassB0K_tknotmatch = new TH1D("BmassB0K_tknotmatch","BmassB0K_tknotmatch", nbin, min, max);
	Bmass->SetMinimum(0);
	Bmass_nosig->SetMinimum(0); 
	BmassBpPi->SetMinimum(0); 
	BmassBpXPi->SetMinimum(0);
	BmassBpK->SetMinimum(0);
	BmassB0K->SetMinimum(0);
	BmassBpK_tkmatch->SetMinimum(0);
	BmassB0K_tkmatch->SetMinimum(0);
	BmassBpK_tknotmatch->SetMinimum(0);
	BmassB0K_tknotmatch->SetMinimum(0);

	std::map<int,int> BtypeCountBpK;
	std::map<int,int> BtypeCountB0K;
	cout<<"--- Processing events"<<endl;
	for(Int_t i=startEntries;i<endEntries;i++)
	{
		root->GetEntry(i);
		hltroot->GetEntry(i);
		skimroot->GetEntry(i);
		hiroot->GetEntry(i);

		if(i%100000==0) cout<<setw(7)<<i<<" / "<<endEntries<<endl;
		if(checkMatching)
		{
			if(((int)Bf_HLT_Event!=EvtInfo->EvtNo||(int)Bf_HLT_Run!=EvtInfo->RunNo||(int)Bf_HLT_LumiBlock!=EvtInfo->LumiNo) || 
					((int)Bf_HiTree_Evt!=EvtInfo->EvtNo||(int)Bf_HiTree_Run!=EvtInfo->RunNo||(int)Bf_HiTree_Lumi!=EvtInfo->LumiNo))
			{
				cout<<"Error: not matched "<<i<<" | (Hlt,Bfr,Hi) | ";
				cout<<"EvtNo("<<Bf_HLT_Event<<","<<EvtInfo->EvtNo<<","<<Bf_HiTree_Evt<<") ";
				cout<<"RunNo("<<Bf_HLT_Run<<","<<EvtInfo->RunNo<<","<<Bf_HiTree_Run<<") ";
				cout<<"LumiNo("<<Bf_HLT_LumiBlock<<","<<EvtInfo->LumiNo<<","<<Bf_HiTree_Lumi<<")"<<endl;
				continue;
			}
		}
		//Do oyur analysis here
		//example: checking GenInfo
	    for(int j=0;j<GenInfo->size;j++){
			if( int(GenInfo->pdgId[j]/100)%100 == 5){
//				cout<<GenInfo->pdgId[j]<<endl;
//				if(abs(GenInfo->pdgId[GenInfo->da1[j]]) == 443 || abs(GenInfo->pdgId[GenInfo->da2[j]]) == 443){
//					printDa(GenInfo, j, 1);
//				}
				if(abs(GenInfo->pdgId[j])==521)
				if(GenInfo->da1[j] != -1)
				if(abs(GenInfo->pdgId[GenInfo->da1[j]]) == 443)
				if(abs(GenInfo->pdgId[GenInfo->da2[j]]) == 211)
				{
					//printDa(GenInfo, j, 1);
				}

				if(abs(GenInfo->pdgId[j])==521)
				if(GenInfo->da1[j] != -1)
				if(abs(GenInfo->pdgId[GenInfo->da1[j]]) == 443)
				if((abs(GenInfo->pdgId[GenInfo->da2[j]])/100)%100 == 3)
				{
					//printDa(GenInfo, j, 1);
				}

				if(abs(GenInfo->pdgId[j])==511)
				if(GenInfo->da1[j] != -1)
				if(abs(GenInfo->pdgId[GenInfo->da1[j]]) == 443)
				if((abs(GenInfo->pdgId[GenInfo->da2[j]])/100)%100 == 3)
				{
					//printDa(GenInfo, j, 1);
				}
				
			}
		}

		bool isBsig = false;
		for(int j=0;j<BInfo->size;j++){
			int rtk1idx = BInfo->rftk1_index[j];
			int rtk2idx = BInfo->rftk2_index[j];
			int rmu1idx = BInfo->uj_rfmu1_index[BInfo->rfuj_index[j]];
			int rmu2idx = BInfo->uj_rfmu2_index[BInfo->rfuj_index[j]];
			int gtk1idx =  TrackInfo->geninfo_index[BInfo->rftk1_index[j]];
			int gtk2idx =  TrackInfo->geninfo_index[BInfo->rftk2_index[j]];
			int gmu1idx =  MuonInfo->geninfo_index[BInfo->uj_rfmu1_index[BInfo->rfuj_index[j]]];
			int gmu2idx =  MuonInfo->geninfo_index[BInfo->uj_rfmu2_index[BInfo->rfuj_index[j]]];

			//some recon cut
			bool cut = false;

			if(
			BInfo->mass[j] > min && BInfo->mass[j] < max && BInfo->pt[j] > 10 && BInfo->pt[j] < 1000
			&& fabs(BInfo->eta[j]) < 2.4
			){
				cut = true;
			}

//			if(
//			BInfo->mass[j] > min && BInfo->mass[j] < max && BInfo->pt[j] > 10 && BInfo->pt[j] < 1000
//			&&	((fabs(MuonInfo->eta[rmu1idx]) < 1.2 && MuonInfo->pt[rmu1idx] > 3.5) || (fabs(MuonInfo->eta[rmu1idx]) > 1.2 && fabs(MuonInfo->eta[rmu1idx]) < 2.1 && MuonInfo->pt[rmu1idx] > (5.77-1.8*fabs(MuonInfo->eta[rmu1idx]))) || (fabs(MuonInfo->eta[rmu1idx]) > 2.1 && fabs(MuonInfo->eta[rmu1idx]) < 2.4 && MuonInfo->pt[rmu1idx] > 1.8))
//			&&  MuonInfo->TMOneStationTight[rmu1idx] &&  MuonInfo->i_nPixelLayer[rmu1idx] > 0 && (MuonInfo->i_nPixelLayer[rmu1idx] + MuonInfo->i_nStripLayer[rmu1idx]) > 5 && MuonInfo->dxyPV[rmu1idx] < 0.3 && MuonInfo->dzPV[rmu1idx] < 20 && MuonInfo->isGlobalMuon[rmu1idx]
//			&&	((fabs(MuonInfo->eta[rmu2idx]) < 1.2 && MuonInfo->pt[rmu2idx] > 3.5) || (fabs(MuonInfo->eta[rmu2idx]) > 1.2 && fabs(MuonInfo->eta[rmu2idx]) < 2.1 && MuonInfo->pt[rmu2idx] > (5.77-1.8*fabs(MuonInfo->eta[rmu2idx]))) || (fabs(MuonInfo->eta[rmu2idx]) > 2.1 && fabs(MuonInfo->eta[rmu2idx]) < 2.4 && MuonInfo->pt[rmu2idx] > 1.8))
//			&&  MuonInfo->TMOneStationTight[rmu2idx] &&  MuonInfo->i_nPixelLayer[rmu2idx] > 0 && (MuonInfo->i_nPixelLayer[rmu2idx] + MuonInfo->i_nStripLayer[rmu2idx]) > 5 && MuonInfo->dxyPV[rmu2idx] < 0.3 && MuonInfo->dzPV[rmu2idx] < 20 && MuonInfo->isGlobalMuon[rmu2idx]
//			&& TrackInfo->highPurity[rtk1idx]
//			&& TrackInfo->pt[rtk1idx] > 1.0
//			&& fabs(TrackInfo->eta[rtk1idx]) < 2.4
//			&& fabs(BInfo->eta[j]) < 2.4
//			&& TMath::Prob(BInfo->vtxchi2[j],BInfo->vtxdof[j]) > 0.005
//			){
//				cut = true;
//			}
//
//			if(!cut) continue;
		
		
			//identify B sig
			Bmass->Fill(BInfo->mass[j]);
			bool isBsig = false;
			if(gmu1idx != -1 && gmu2idx != -1)
			if(abs(GenInfo->pdgId[gmu1idx]) == 13 && abs(GenInfo->pdgId[gmu2idx]) == 13)
			if((GenInfo->mo1[gmu1idx]) != -1 && (GenInfo->mo1[gmu2idx]) != -1 && GenInfo->mo1[gmu1idx] == GenInfo->mo1[gmu2idx])
			if(abs(GenInfo->pdgId[GenInfo->mo1[gmu1idx]]) == 443 && abs(GenInfo->pdgId[GenInfo->mo1[gmu2idx]]) == 443)
			if(GenInfo->mo1[GenInfo->mo1[gmu1idx]] != -1)
			if(gtk1idx != -1)
			if(GenInfo->mo1[gtk1idx] != -1)
			if(GenInfo->mo1[gtk1idx] == GenInfo->mo1[GenInfo->mo1[gmu1idx]] && abs(GenInfo->pdgId[GenInfo->mo1[gtk1idx]]) == 521 && abs(GenInfo->pdgId[gtk1idx]) == 321)
				isBsig = true;
			if(!isBsig) Bmass_nosig->Fill(BInfo->mass[j]);

			//identify jpsi + ?
			if(gmu1idx != -1 && gmu2idx != -1)
				if(abs(GenInfo->pdgId[gmu1idx]) == 13 && abs(GenInfo->pdgId[gmu2idx]) == 13)
					if((GenInfo->mo1[gmu1idx]) != -1 && (GenInfo->mo1[gmu2idx]) != -1 && GenInfo->mo1[gmu1idx] == GenInfo->mo1[gmu2idx])
						if(abs(GenInfo->pdgId[GenInfo->mo1[gmu1idx]]) == 443 && abs(GenInfo->pdgId[GenInfo->mo1[gmu2idx]]) == 443)
						{
							int mmu1idx = GenInfo->mo1[gmu1idx];
							int mmu2idx = GenInfo->mo1[gmu2idx];
							int mjpsiidx = GenInfo->mo1[mmu1idx];
							//B+ to jpsi pi+
							if(gtk1idx != -1){
								int mtk1idx = GenInfo->mo1[gtk1idx];
								if(mtk1idx != 1){
									int mtk1pdg = GenInfo->pdgId[mtk1idx];
									int tk1pdg = GenInfo->pdgId[gtk1idx];
									if(mtk1idx == mjpsiidx && abs(mtk1pdg) == 521 && abs(tk1pdg) == 211){
										if(gtk1idx == GenInfo->da2[mtk1idx]){
											//cout<<"-----"<<endl;
											//printDa(GenInfo, mtk1idx, 1);
											//cout<<"-----"<<endl;
											//printDa(GenInfo, mtk1idx, 1);
											//cout<<"Bmass: "<<BInfo->mass[j]<<endl;
											BmassBpPi->Fill(BInfo->mass[j]);
										}
										else{
											//printDa(GenInfo, mtk1idx, 1);
											//cout<<"Bmass: "<<BInfo->mass[j]<<endl;
											BmassBpXPi->Fill(BInfo->mass[j]);
										}
									}
								}
								//B+ to jpsi K 
								if(abs(GenInfo->pdgId[GenInfo->mo1[mmu1idx]]) == 521){
									int bidx = GenInfo->mo1[mmu1idx];
									int bda2idx = GenInfo->da2[bidx]; 
									int bda2pdg = GenInfo->pdgId[bda2idx];
									int tkancestor = getBAncestor(GenInfo, gtk1idx, 521);
									/*
									if(tkancestor != -1){
									cout<<"tk1 pt: "<<GenInfo->pt[gtk1idx]<<endl;
									cout<<"tk1anc: "<<tkancestor<<endl;
									cout<<"tk1anc pdg: "<<GenInfo->pdgId[tkancestor]<<endl;
									cout<<"bidx: "<<bidx<<endl;
                                    printDa(GenInfo, tkancestor, 1);
									}*/
									if((abs(bda2pdg)/100)%100==3
									&& abs(bda2pdg) != 321 
									){
										//printDa(GenInfo, bidx, 1);
										//cout<<"Bmass: "<<BInfo->mass[j]<<endl;
										BmassBpK->Fill(BInfo->mass[j]);
										if(tkancestor == bidx){
											BmassBpK_tkmatch->Fill(BInfo->mass[j]);
										}
										else{BmassBpK_tknotmatch->Fill(BInfo->mass[j]);}

										if(BtypeCountBpK.find(abs(bda2pdg)) == BtypeCountBpK.end()){
											BtypeCountBpK[abs(bda2pdg)] = 1;
										}
										else{
											BtypeCountBpK[abs(bda2pdg)] += 1;
										}
									}
								}

								//B0 to jpsi K 
								if(abs(GenInfo->pdgId[GenInfo->mo1[mmu1idx]]) == 511){
									int bidx = GenInfo->mo1[mmu1idx];
									int bda2idx = GenInfo->da2[bidx]; 
									int bda2pdg = GenInfo->pdgId[bda2idx];
									int tkancestor = getBAncestor(GenInfo, gtk1idx, 511);
									if((abs(bda2pdg)/100)%100==3){
										//printDa(GenInfo, bidx, 1);
										//cout<<"Bmass: "<<BInfo->mass[j]<<endl;
										BmassB0K->Fill(BInfo->mass[j]);
										if(tkancestor == bidx){
											BmassB0K_tkmatch->Fill(BInfo->mass[j]);
										}
										else{BmassB0K_tknotmatch->Fill(BInfo->mass[j]);}

										if(BtypeCountB0K.find(abs(bda2pdg)) == BtypeCountB0K.end()){
											BtypeCountB0K[abs(bda2pdg)] = 1;
										}
										else{
											BtypeCountB0K[abs(bda2pdg)] += 1;
										}
									}
								}
							}

						}
		}
		//

	}
	cout<<"Bp + K type count========="<<endl;
	std::map<int,int>::iterator BtypeCountBpKIt;
	for(BtypeCountBpKIt = BtypeCountBpK.begin(); BtypeCountBpKIt != BtypeCountBpK.end(); BtypeCountBpKIt++){
		cout<<"Ktype: "<<BtypeCountBpKIt->first<<" Count: "<<BtypeCountBpKIt->second<<endl;
	}

	cout<<"B0 + K type count========="<<endl;
	std::map<int,int>::iterator BtypeCountB0KIt;
	for(BtypeCountB0KIt = BtypeCountB0K.begin(); BtypeCountB0KIt != BtypeCountB0K.end(); BtypeCountB0KIt++){
		cout<<"Ktype: "<<BtypeCountB0KIt->first<<" Count: "<<BtypeCountB0KIt->second<<endl;
	}
	outf->Write();
	cout<<"--- Writing finished"<<endl;
	outf->Close();

	cout<<"--- In/Output files"<<endl;
	cout<<ifname<<endl;
	cout<<outfile<<endl;
	cout<<endl;

	return 1;
}
Exemple #16
0
void minuitFit()
{
  
  gStyle->SetOptFit(1111);
  gStyle->SetOptStat(0);

  Bool_t makePDF = checkMakePDF();
  
  char name[1000];
  sprintf(name,"/Users/zach/Research/pythia/ptHatTemplate/outputs/currentB.root");
  TFile *fB = new TFile(name,"READ");
  sprintf(name,"/Users/zach/Research/pythia/ptHatTemplate/outputs/currentC.root");
  TFile *fC = new TFile(name,"READ");
  sprintf(name,"/Users/zach/Research/rootFiles/run12NPEhPhi/currentData.root");
  TFile *fD = new TFile(name,"READ");
  if (fB->IsOpen()==kFALSE || fC->IsOpen()==kFALSE)
    { std::cout << "!!!!!! Either B,C, or Data File not found !!!!!!" << std::endl
		<< "Looking for currentB.root, currentC.root, and currentData.root" << std::endl;
      exit(1); }
  
  // Set constants and projection bins (from header file anaConst, analysis constants)
  
  Float_t lowpt[numPtBins],highpt[numPtBins];
  for(Int_t c=0; c< numPtBins; c++){
    lowpt[c] = anaConst::lpt[c];
    highpt[c] = anaConst::hpt[c];
  }
  Float_t hptCut=anaConst::hptCut;
  Double_t p00[numPtBins],p01[numPtBins],p20[numPtBins],p21[numPtBins];
  Double_t e00[numPtBins],e01[numPtBins],e20[numPtBins],e21[numPtBins];
  Double_t pC0[numPtBins],pC1[numPtBins],eC0[numPtBins],eC1[numPtBins];
  Double_t Rb0[numPtBins],Rb2[numPtBins],RbC[numPtBins],pT[numPtBins];
  Double_t eb0[numPtBins],eb2[numPtBins],ebC[numPtBins],dx[numPtBins];
  Double_t ptOFF1[numPtBins],ptOFF2[numPtBins];
  Int_t plotCount0 = 0, plotCount2 = 0, plotCount = 0;
  
  // Make Canvases
  TCanvas* deltaPhi  = new TCanvas("deltaPhi","Pythia Delta Phi",150,0,1150,1000);
  TCanvas* deltaPhi2  = new TCanvas("deltaPhi2","Pythia Delta Phi",150,0,1150,1000);
  TCanvas* fitResult0 = new TCanvas("fitResult0","RB Extraction HT0",150,0,1150,1000);
  TCanvas* fitResult2 = new TCanvas("fitResult2","RB Extraction HT2",150,0,1150,1000);
  TCanvas* fitResultC = new TCanvas("fitResultC","RB Extraction Combined Trigs",150,0,1150,1000);
  deltaPhi  ->Divide(3,3);
  deltaPhi2 ->Divide(3,3);
  fitResult0->Divide(3,4);
  fitResult2->Divide(3,4);
  fitResultC->Divide(3,4);

  // Get and Draw histos
  TPaveText* lbl[numPtBins];
  TPaveText* stat[3][numPtBins];
  char statLabel[100];
  char textLabel[100];
  Int_t plotbin;
  Float_t norm0,norm2,normB,normC;

  // Get ptbin independent hists
  histoNorms = (TH1F*)fD->Get("histoNorms");
  bPtNorms   = (TH1F*)fB->Get("ptNorm");
  cPtNorms   = (TH1F*)fC->Get("ptNorm");
  
  for(Int_t ptbin=0; ptbin<numPtBins; ptbin++)
    {
      norm0 = histoNorms->GetBinContent(histoNorms->GetBin(1,ptbin+1));
      norm2 = histoNorms->GetBinContent(histoNorms->GetBin(3,ptbin+1));
      normB = bPtNorms->GetBinContent(bPtNorms->GetBin(ptbin+1));
      normC = cPtNorms->GetBinContent(cPtNorms->GetBin(ptbin+1));

      if(norm0 == 0)
	{
	  cout << ptbin << " For this bin, some norm0 = 0" << endl;
	  continue;
	}
      if( norm2 == 0 )
	{
	  cout << ptbin << " For this bin, some norm2 = 0" << endl;
	  continue;
	}
      if( normB == 0 )
	{
	  cout << ptbin << " For this bin, some normB = 0" << endl;
	  continue;
	}
      if(normC == 0)
	{
	  cout << ptbin << " For this bin, some normC = 0" << endl;
	  continue;
	}
      plotbin = ptbin;
      // Init necessary plotting tools
      lbl[ptbin] = new TPaveText(.15,.15,.35,.23,Form("NB NDC%i",ptbin));
      sprintf(textLabel,"%.1f < P_{T,e} < %.1f",lowpt[ptbin],highpt[ptbin]);
      lbl[ptbin]->AddText(textLabel);
      lbl[ptbin]->SetFillColor(kWhite);

      projB[ptbin] = (TH1D*)fB->Get(Form("delPhi_%i",ptbin));
      projC[ptbin] = (TH1D*)fC->Get(Form("delPhi_%i",ptbin));
      projData0[ptbin]= (TH1D*)fD->Get(Form("NPEhDelPhi_0_%i",ptbin));
      projData2[ptbin]= (TH1D*)fD->Get(Form("NPEhDelPhi_2_%i",ptbin));
      // Do any rebinning
      Int_t RB = 1;
      projB[ptbin]->Rebin(RB);
      projC[ptbin]->Rebin(RB);
      projData0[ptbin]->Rebin(RB);
      projData2[ptbin]->Rebin(RB);

      // Clone to make plots without effecting fits
      plotD0[ptbin] = (TH1D*) projData0[ptbin]->Clone();
      plotD2[ptbin] = (TH1D*) projData2[ptbin]->Clone();
      plotB[ptbin]  = (TH1D*) projB[ptbin]->Clone();
      plotC[ptbin]  = (TH1D*) projC[ptbin]->Clone();

      // Set features that are the same in plots
      projData0[ptbin]->SetLineColor(kBlue);
      projData2[ptbin]->SetLineColor(kGreen+3);
      projB[ptbin]->SetLineColor(kRed);
      projC[ptbin]->SetLineColor(kBlack);
      projC[ptbin]->GetXaxis()->SetRangeUser(-3.5,3.5);
      plotD0[ptbin]->SetLineColor(kBlue);
      plotD2[ptbin]->SetLineColor(kGreen+3);
      plotD0[ptbin]->SetMarkerStyle(20);
      plotD0[ptbin]->SetMarkerColor(kBlue);
      plotD0[ptbin]->SetMarkerSize(0.4);
      plotB[ptbin]->SetLineColor(kRed);
      plotC[ptbin]->SetLineColor(kBlack);
      plotC[ptbin]->GetXaxis()->SetRangeUser(-3.5,3.5);

      combData[ptbin] = (TH1D*) projData0[ptbin]->Clone();
      combData[ptbin] -> Add(projData2[ptbin]);
      combData[ptbin]->SetLineColor(kBlue);
      combData[ptbin]->SetMarkerStyle(20);
      combData[ptbin]->SetMarkerColor(kBlue);
      combData[ptbin]->SetMarkerSize(0.4);
      combData[ptbin]->SetTitle("");
      
      // Normalize
      projB[ptbin]     -> Scale(1/normB);
      projC[ptbin]     -> Scale(1/normC);
      projData0[ptbin] -> Scale(1/norm0);
      projData2[ptbin] -> Scale(1/norm2);
      plotD0[ptbin]    -> Scale(1/norm0);
      plotD2[ptbin]    -> Scale(1/norm2);
      plotB[ptbin]     -> Scale(1/(normB));
      plotC[ptbin]     -> Scale(1/(normC));
      combData[ptbin]  -> Scale(1/(norm0+norm2));
    /*projB[ptbin]     -> Scale(projData0[ptbin]->GetBinContent(70)/projB[ptbin]->GetBinContent(70));
      projC[ptbin]     -> Scale(projData0[ptbin]->GetBinContent(70)/projC[ptbin]->GetBinContent(70));
      plotB[ptbin]     -> Scale(projData0[ptbin]->GetBinContent(70)/plotB[ptbin]->GetBinContent(70));
      plotC[ptbin]     -> Scale(projData0[ptbin]->GetBinContent(70)/plotC[ptbin]->GetBinContent(70));
      */
      
      // Draw Templates on own plots
      if(ptbin+1 <= 9) deltaPhi->cd(plotbin+1);
      if(ptbin+1 > 9) deltaPhi2->cd(ptbin-8);
      plotC[ptbin]->GetYaxis()->SetRangeUser(-.1,0.5);
      plotC[ptbin]  -> Draw("hist");
      plotB[ptbin]  -> Draw("same hist");
      plotD0[ptbin] -> Draw("same");
      plotD2[ptbin] -> Draw("same");
      lbl[ptbin]    -> Draw("same");

      TLegend* leg = new TLegend(0.65,0.6,0.85,0.85);
      leg->AddEntry(projB[ptbin],"b#bar{b}->NPE","lpe");
      leg->AddEntry(projC[ptbin],"c#bar{c}->NPE","lpe");
      leg->AddEntry(projData0[ptbin],"HT0","lpe");
      leg->AddEntry(projData2[ptbin],"HT2","lpe");
      leg->Draw();

      /////////////////////
      // Do the actual fits
      /////////////////////

      cout << "!!!!!!! HT0 ptbin: " << highpt[ptbin] << "-" << lowpt[ptbin] <<" !!!!!!!"<< endl;
      currentPtBin = ptbin;
      double arglist[10];int ierflg=0;
      TMinuit *gMinuit=new TMinuit(2); //initialize TMinuit with a maximum of 3 params
      gMinuit->SetMaxIterations(50000);
      gMinuit->SetFCN(chi2_0);
      arglist[0]=1; //error definition: chi^2 change by 1 to get 1 sigma
      gMinuit->mnexcm("SET ERR",arglist,1,ierflg);

      //starting values
      double vstart[2]={0.3,1}; //frac
      double step[2]={0.01,0.01}; //starting step
      gMinuit->mnparm(0,"BtoNPE frac",vstart[0],step[0],0.000,2,ierflg);
      gMinuit->mnparm(1,"Scale Factor",vstart[1],step[1],0.000,2,ierflg);
      //simple scan to get better start values
      gMinuit->mnexcm("SCAN",arglist,0,ierflg); 
      cout<<"done with first scan!"<<endl;

      //minimization
      arglist[0]=5000; //maxcalls
      arglist[1]=0.5; // tolerance = 0.001*[this value]*[error def] //5.0 before
      gMinuit->mnexcm("MINIMIZE",arglist,2,ierflg);

      cout<< "done with fit! Error Flag: " << ierflg << endl;

       //fit results
      double dum1,dum2;
      TString *str0 = new TString("BtoNPE frac");
      TString *str1 = new TString("Scale Factor");
      gMinuit->mnpout(0,*str0,p01[ptbin],e01[ptbin],dum1,dum2,ierflg);
      gMinuit->mnpout(1,*str1,p00[ptbin],e00[ptbin],dum1,dum2,ierflg);

      cout << endl << endl << "HT0 PT Bin: " << lowpt[ptbin] << "-" << highpt[ptbin] << endl
	   << "rB: " << p01[ptbin] << " rC: " << p00[ptbin] << endl
	   << "erB: " << e01[ptbin] << " erC: " << e00[ptbin] << endl << endl;
      
      //Print results
      double amin,edm,errdef;
      int nvpar,nparx,icstat;
      gMinuit->mnstat(amin,edm,errdef,nvpar,nparx,icstat);
      gMinuit->mnprin(4,amin);
      
      // assign to plotting variables
      if(highpt[ptbin] < 6)
	{
	  pT[ptbin] = (lowpt[ptbin]+highpt[ptbin])/2.;
	  dx[plotCount0] = 0.;
	  ptOFF1[plotCount0] = pT[ptbin];
	  Rb0[plotCount0] = p01[ptbin];///(p01[ptbin]+p00[ptbin]);
	  eb0[plotCount0] = e01[ptbin];
	  plotCount0++;
	}
    
      // Plot results
      fitResult0->cd(ptbin+1);
      TH1D* dClone = (TH1D*) projData0[ptbin]->Clone();
      TH1D* cClone = (TH1D*) projC[ptbin]->Clone();
      TH1D* bClone = (TH1D*) projB[ptbin]->Clone();
      stat[0][ptbin] = new TPaveText(.4,.75,.85,.85,Form("NB NDC%i",ptbin));
      sprintf(statLabel,"Chi2/NDF: %.2f/%.0f",curChi2,curNDF);
      stat[0][ptbin]->InsertText(statLabel);
      stat[0][ptbin]->SetFillColor(kWhite);
      cClone->Scale((1.-p01[ptbin])*p00[ptbin]); bClone->Scale(p00[ptbin]*p01[ptbin]); // scale by contribution param
      cClone->Add(bClone);
      //cClone->Scale(dClone->GetMaximum()/cClone->GetMaximum());
      dClone->GetXaxis()->SetRangeUser(anaConst::lowPhi,anaConst::highPhi);
      dClone->GetYaxis()->SetRangeUser(-0.1,0.4);
      dClone->Draw();
      cClone->Draw("same");
      stat[0][ptbin]->Draw("same");
      lbl[ptbin]->Draw("same");
            

      cout << "!!!!!!! HT2 ptbin: " <<  highpt[ptbin] << "-" << lowpt[ptbin] <<" !!!!!!!"<< endl;
      fitResult2->cd(ptbin+1);
      currentPtBin = ptbin;
      TMinuit *g2Minuit=new TMinuit(2); //initialize TMinuit with a maximum of 3 params
      g2Minuit->SetMaxIterations(50000);
      g2Minuit->SetFCN(chi2_2);
      arglist[0]=1; //error definition: chi^2 change by 1 to get 1 sigma
      g2Minuit->mnexcm("SET ERR",arglist,1,ierflg);

      //starting values
      double vstart2[2]={0.3,1}; //frac
      double step2[2]={0.01,0.01}; //starting step
      g2Minuit->mnparm(0,"BtoNPE frac",vstart2[0],step2[0],0.000,2,ierflg);
      g2Minuit->mnparm(1,"Scale Factor",vstart2[1],step2[1],0.000,2,ierflg);
      //simple scan to get better start values
      g2Minuit->mnexcm("SCAN",arglist,0,ierflg); 
      cout<<"done with first scan!"<<endl;

      //minimization
      arglist[0]=5000; //maxcalls
      arglist[1]=0.5; // tolerance = 0.001*[this value]*[error def] //5.0 before
      g2Minuit->mnexcm("MINIMIZE",arglist,2,ierflg);

      cout<< "done with fit! Error Flag: " << ierflg << endl;

       //fit results
      TString *str2 = new TString("BtoNPE frac");
      TString *str3 = new TString("Scale Factor");
      g2Minuit->mnpout(0,*str2,p21[ptbin],e21[ptbin],dum1,dum2,ierflg);
      g2Minuit->mnpout(1,*str3,p20[ptbin],e20[ptbin],dum1,dum2,ierflg);

      cout << endl << endl << "HT2 PT Bin: " << lowpt[ptbin] << "-" << highpt[ptbin] << endl
	   << "rB: " << p21[ptbin] << " rC: " << p20[ptbin] << endl
	   << "erB: " << e21[ptbin] << " erC: " << e20[ptbin] << endl << endl;
      
      //Print results
      g2Minuit->mnstat(amin,edm,errdef,nvpar,nparx,icstat);
      g2Minuit->mnprin(4,amin);
      
      // assign to plotting variables
      if(highpt[ptbin] > 3.6)
	{
	  pT[ptbin] = (lowpt[ptbin]+highpt[ptbin])/2.;
	  ptOFF2[plotCount2] = pT[ptbin];
	  Rb2[plotCount2] = p21[ptbin];///(p21[ptbin]+p20[ptbin]);
	  eb2[plotCount2] = e21[ptbin];
	  plotCount2++;
	}

      // Plot results
      fitResult2->cd(ptbin+1);
      dClone = (TH1D*) projData2[ptbin]->Clone();
      cClone = (TH1D*) projC[ptbin]->Clone();
      bClone = (TH1D*) projB[ptbin]->Clone();
      stat[2][ptbin] = new TPaveText(.4,.75,.85,.85,Form("NB NDC%i",ptbin));
      sprintf(statLabel,"Chi2/NDF: %.2f/%.2f",curChi2,curNDF);
      stat[2][ptbin]->InsertText(statLabel);
      stat[2][ptbin]->SetFillColor(kWhite);
      cClone->Scale((1.-p21[ptbin])*p20[ptbin]); bClone->Scale(p20[ptbin]*p21[ptbin]); // scale by contribution param
      cClone->Add(bClone);
      // cClone->Scale(dClone->GetMaximum()/cClone->GetMaximum());
      dClone->GetXaxis()->SetRangeUser(anaConst::lowPhi,anaConst::highPhi);
      dClone->GetYaxis()->SetRangeUser(-0.1,0.4);
      dClone->Draw();
      cClone->Draw("same");
      stat[2][ptbin]->Draw("same");
      lbl[ptbin]->Draw("same");

      cout << "!!!!!!! HT0&2 ptbin: " <<  highpt[ptbin] << "-" << lowpt[ptbin] <<" !!!!!!!"<< endl;
      fitResultC->cd(ptbin+1);
      currentPtBin = ptbin;
      TMinuit *gCMinuit=new TMinuit(2); //initialize TMinuit with a maximum of 3 params
      gCMinuit->SetMaxIterations(50000);
      gCMinuit->SetFCN(chi2_C);
      arglist[0]=1; //error definition: chi^2 change by 1 to get 1 sigma
      gCMinuit->mnexcm("SET ERR",arglist,1,ierflg);

      //starting values
      double vstartC[2]={0.3,1}; //frac
      double stepC[2]={0.01,0.01}; //starting step
      gCMinuit->mnparm(0,"BtoNPE frac",vstartC[0],stepC[0],0.000,2,ierflg);
      gCMinuit->mnparm(1,"Scale Factor",vstartC[1],stepC[1],0.000,2,ierflg);
      //simple scan to get better start values
      gCMinuit->mnexcm("SCAN",arglist,0,ierflg); 
      cout<<"done with first scan!"<<endl;

      //minimization
      arglist[0]=5000; //maxcalls
      arglist[1]=0.5; // tolerance = 0.001*[this value]*[error def] //5.0 before
      gCMinuit->mnexcm("MINIMIZE",arglist,2,ierflg);

      cout<< "done with fit! Error Flag: " << ierflg << endl;

       //fit results
      TString *str4 = new TString("BtoNPE frac");
      TString *str5 = new TString("Scale Factor");
      gCMinuit->mnpout(0,*str4,pC1[ptbin],eC1[ptbin],dum1,dum2,ierflg);
      gCMinuit->mnpout(1,*str5,pC0[ptbin],eC0[ptbin],dum1,dum2,ierflg);

      cout << endl << endl << "HTC PT Bin: " << lowpt[ptbin] << "-" << highpt[ptbin] << endl
	   << "rB: " << pC1[ptbin] << " rC: " << pC0[ptbin] << endl
	   << "erB: " << eC1[ptbin] << " erC: " << eC0[ptbin] << endl << endl;

      //Print results
      gCMinuit->mnstat(amin,edm,errdef,nvpar,nparx,icstat);
      gCMinuit->mnprin(4,amin);
      
      // assign to plotting variables
      pT[ptbin] = (lowpt[ptbin]+highpt[ptbin])/2.;
      RbC[plotCount] = pC1[ptbin];///(p21[ptbin]+p20[ptbin]);
      ebC[plotCount] = eC1[ptbin];
      plotCount++;
    }

  // Get FONLL Calc
  Int_t l=0;
  char line[1000];
  Float_t xF[100],yF[100],minF[100],maxF[100];
  ifstream fp("/Users/zach/Research/pythia/ptHatTemplate/FONLL.txt",ios::in);
  while (!fp.eof()){
    fp.getline(line,1000);
    sscanf(line,"%f %f %f %f",&xF[l],&yF[l],&minF[l],&maxF[l]);
    //  printf("L: %f %f\n",xF[l],yF[l]);
    l++;
  }
  fp.close();

  // Get Previous Analysis 
  Int_t p=0;
  Float_t xP[100],yP[100],dyP[100];
  ifstream fp1("/Users/zach/Research/pythia/ptHatTemplate/run5_6.txt",ios::in);
  while (!fp1.eof()){
    fp1.getline(line,1000);
    sscanf(line,"%f %f %f",&xP[p],&yP[p],&dyP[p]);
    // printf("L: %f %f\n",xF[l],yF[l]);
    p++;
  }
  fp1.close();

  //cout << "at bottom contrib plot" << endl;
  TCanvas* c1 = new TCanvas("c1","Bottom Contribution",150,0,1150,1000);
  TGraphErrors *gr0     = new TGraphErrors(plotCount0-1,ptOFF1,Rb0,dx,eb0);
  TGraphErrors *gr2     = new TGraphErrors(plotCount2-1,ptOFF2,Rb2,dx,eb2);
  TGraphErrors *grC     = new TGraphErrors(plotCount-1,pT,RbC,dx,ebC);
  TGraphErrors *grF     = new TGraphErrors(l-1,xF,yF);
  TGraphErrors *grFmax  = new TGraphErrors(l-1,xF,maxF);
  TGraphErrors *grFmin  = new TGraphErrors(l-1,xF,minF);
  TGraphErrors *grP     = new TGraphErrors(p-1,xP,yP,0,dyP);

  c1->cd(1);

  gr0->SetTitle("Bottom Contribution");
  gr0->GetXaxis()->SetTitle("p_{T,e}");
  gr0->GetYaxis()->SetTitle("#frac{r_{B}}{(r_{B}+r_{C})}");
  gr0->SetMarkerStyle(20);
  gr0->SetMarkerSize(1);
  gr0->SetLineColor(kBlue);
  gr0->SetMarkerColor(kBlue);
  gr2->SetMarkerStyle(22);
  gr2->SetMarkerSize(1);
  gr2->SetLineColor(kRed);
  gr2->SetMarkerColor(kRed);
  grC->SetMarkerStyle(21);
  grC->SetMarkerSize(1);
  grC->SetLineColor(kRed);
  grC->SetMarkerColor(kRed);
  gr0->GetXaxis()->SetLimits(1,14);
  gr0->GetYaxis()->SetRangeUser(0,1);
  grF->SetLineStyle(1);
  grFmax->SetLineStyle(2);
  grFmin->SetLineStyle(2);
  grP->SetMarkerStyle(33);
  grP->SetMarkerColor(kBlack);
  
  
  gr0->Draw("AP");
  // grC->Draw("same P");
  gr2->Draw("same P");
  grF->Draw("same");
  grFmax->Draw("same");
  grFmin->Draw("same");
  grP->Draw("same P");

  TLegend* leg2 = new TLegend(0.15,0.68,0.4,0.85);
  leg2->AddEntry(gr0,"High Tower 0 Trigs","pe");
  leg2->AddEntry(gr2,"High Tower 2 Trigs","pe");
  // leg2->AddEntry(grC,"Combined Trigs","pe");
  leg2->AddEntry(grF,"FONLL (Uncertainty: Scale Only)","l");
  leg2->AddEntry(grP,"Run 5/6 Analysis (Stat Uncertainty)","pe");
  leg2->Draw("same");
  
   // Make PDF with output canvases
  if(makePDF)
    {
      //Set front page
      TCanvas* fp = new TCanvas("fp","Front Page",100,0,1000,900);
      fp->cd();
      TBox *bLabel = new TBox(0.01, 0.88, 0.99, 0.99);
      bLabel->SetFillColor(38);
      bLabel->Draw();
      TLatex tl;
      tl.SetNDC();
      tl.SetTextColor(kWhite);
      tl.SetTextSize(0.033);
      char tlName[100];
      char tlName2[100];
      
      TString titlename = FileName;
      int found = titlename.Last('/');
      if(found >= 0){
	titlename.Replace(0, found+1, "");
      } 
      sprintf(tlName, "RUN 12 NPE-h   #Delta#phi Correlations");
      tl.SetTextSize(0.05);
      tl.SetTextColor(kWhite);
      tl.DrawLatex(0.05, 0.92,tlName);
      
      TBox *bFoot = new TBox(0.01, 0.01, 0.99, 0.12);
      bFoot->SetFillColor(38);
      bFoot->Draw();
      tl.SetTextColor(kWhite);
      tl.SetTextSize(0.05);
      tl.DrawLatex(0.05, 0.05, (new TDatime())->AsString());
      tl.SetTextColor(kBlack);
      tl.SetTextSize(0.03);
      tl.DrawLatex(0.1, 0.14, titlename);
      sprintf(tlName,"TEST");
      tl.DrawLatex(0.1, 0.8,tlName);
      
      // Place canvases in order
      TCanvas* temp = new TCanvas();
      sprintf(name, "FFOutput/%s.pdf[", FileName);
      temp->Print(name);
      sprintf(name, "FFOutput/%s.pdf", FileName);

      temp = deltaPhi; 
      temp->Print(name);
      temp = fitResult0;
      temp->Print(name);
      temp = fitResult2;
      temp->Print(name);
      temp = fitResultC;
      temp->Print(name);
      temp = c1;
      temp->Print(name);
      
      sprintf(name, "FFOutput/%s.pdf]", FileName);
      temp->Print(name);
    }
}
void ProduceDatacards_em(int nBins = 35,
			 float xmin = 0,
			 float xmax = 350,
			 bool pileUp = false) {

  double lumi = 2092;
  double normSS = 1.06;
    
  // sample names
  TString sampleNames[20] = {
    "MuEG_2015D", // data
    "DYJetsToLL_M-50_MG", // isZTT (ZTT)
    "DYJetsToLL_M-50_MG", // !isZTT (ZLL)
    "WJetsToLNu_MG", 
    "TTPowHeg",  
    "ST_t-channel_top_4f_leptonDecays",  
    "ST_t-channel_antitop_4f_leptonDecays",
    "ST_tW_antitop_5f_inclusiveDecays",
    "ST_tW_top_5f_inclusiveDecays",
    "VVTo2L2Nu",
    "WWToLNuQQ",
    "WZTo2L2Q",
    "WZTo1L1Nu2Q",
    "WZTo1L3Nu",
    "WZJets",
    "ZZTo4L",
    "ZZTo2L2Q",
    "",
    "",
    ""};

  double xsec[20] = {1, // data (0)
		     6025.2, // DY (1)
		     6025.2, // DY (2)
		     61526.7, // WJets (3)
		     831.76, // TT (4)
		     136.95, // ST_t-channel_top (5)
		     80.95,  // ST_t-channel_antitop (6)
		     35.6, // ST_tW_antitop (7)
		     35.6, // ST_tW_top_5f (8)
		     11.95,  // VV (9)
		     49.997, // WWToLNuQQ (10)
		     5.595, // WZTo2L2Q (11)
		     10.71, // WZTo1L1Nu2Q (12)
		     3.05, // WZTo1L3Nu (13)
		     5.26, // WZJets (3L1Nu) (14)
		     1.212, // ZZTo4L (15)
		     3.22, // ZZTo2L2Q (16)
		     0, //
		     0, //
		     0}; // 
  
  TString cuts[20];
  TString cutsSS[20];
  for (int i=0; i<20; ++i) {
    cuts[i] = "mcweight*(os>0.5)";
    cutsSS[i] = "mcweight*(os<0.5)";
  }

  cuts[0] = "os>0.5";
  cuts[1] = "mcweight*(os>0.5&&isZTT)";
  cuts[2] = "mcweight*(os>0.5&&!isZTT)";

  cutsSS[0] = "os<0.5";
  cutsSS[1] = "mcweight*(os<0.5&&isZTT)";
  cutsSS[2] = "mcweight*(os<0.5&&!isZTT)";
  
  if (pileUp) {
    for (int i=1; i<20; ++i) {
      cuts[i] = "puweight*" + cuts[i];
      cutsSS[i] = "puweight*" + cutsSS[i];
    }
  }

  TH1D * hist[20];
  TH1D * histSS[20];

  for (int i=0; i<17; ++i) {
    std::cout << sampleNames[i] << std::endl;
    TFile * file = new TFile(sampleNames[i]+".root");
    TH1D * histWeightsH = (TH1D*)file->Get("histWeightsH");
    TTree * tree = (TTree*)file->Get("TauCheck");
    double norm = xsec[i]*lumi/histWeightsH->GetSumOfWeights();
    TString histName = sampleNames[i] + "_mvis";
    TString histNameSS = sampleNames[i] + "_mvis_os";
    hist[i] = new TH1D(histName,"",nBins,xmin,xmax);
    histSS[i] = new TH1D(histNameSS,"",nBins,xmin,xmax);
    hist[i]->Sumw2();
    histSS[i]->Sumw2();
    tree->Draw("m_vis>>"+histName,cuts[i]);
    tree->Draw("m_vis>>"+histNameSS,cutsSS[i]);
    if (i>0) {
      for (int iB=1; iB<=nBins; ++iB) {
	double x = hist[i]->GetBinContent(iB);
	double e = hist[i]->GetBinError(iB);
    	hist[i]->SetBinContent(iB,norm*x);
    	hist[i]->SetBinError(iB,norm*e);
	double xSS = histSS[i]->GetBinContent(iB);
	double eSS = histSS[i]->GetBinError(iB);
    	histSS[i]->SetBinContent(iB,norm*xSS);
    	histSS[i]->SetBinError(iB,norm*eSS);
      }
    }
  }

  //  adding up single top and VV backgrounds
  for (int iH=6; iH<17; ++iH) {
    hist[5]->Add(hist[5],hist[iH]);
    histSS[5]->Add(histSS[5],histSS[iH]);
  }

  // subtracting background from SS
  for (int iH=1; iH<6; ++iH) {
    histSS[0]->Add(histSS[0],histSS[iH],1,-1);
  }

  for (int iB=1; iB<=nBins; ++iB) {
    double x = histSS[0]->GetBinContent(iB);
    double e = histSS[0]->GetBinError(iB);
    histSS[0]->SetBinContent(iB,normSS*x);
    histSS[0]->SetBinError(iB,normSS*e);
  }
  TString suffix("");
  if (!pileUp)
    suffix = "_noPU";

  TFile * file = new TFile("htt_em.inputs-sm-13TeV-mvis"+suffix+".root","recreate"); 
  file->mkdir("em_inclusive");
  file->cd("em_inclusive");
  TH1D * data_obs = (TH1D*)hist[0]->Clone("data_obs");
  TH1D * QCD = (TH1D*)histSS[0]->Clone("QCD");
  TH1D * ZTT = (TH1D*)hist[1]->Clone("ZTT");
  TH1D * ZLL = (TH1D*)hist[2]->Clone("ZLL");
  TH1D * W = (TH1D*)hist[3]->Clone("W");
  TH1D * TT = (TH1D*)hist[4]->Clone("TT");
  TH1D * VV = (TH1D*)hist[5]->Clone("VV");
  file->Write();
  file->Close();
  

}
Exemple #18
0
void hPYphocalc(){
	gStyle->SetOptStat(kFALSE);
	const int maxNpart = 100;
	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";}
        TObjString* dataname = (TObjString*)f->Get(Form("dataname"));
        TObjString* histoname = (TObjString*)f->Get(Form("histoname"));
	TFile *fdata = TFile::Open(dataname->GetName());
                TString name;
        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* k0 = (TVectorD*)f->Get(Form("%s/%s/k0",dirname.Data(),name.Data()));
        TVectorD* theta0 = (TVectorD*)f->Get(Form("%s/%s/theta0",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* thetabest = (TVectorD*)f->Get(Form("%s/%s/thetabest",dirname.Data(),name.Data()));
        TVectorD* kbest = (TVectorD*)f->Get(Form("%s/%s/kbest",dirname.Data(),name.Data()));
	TVectorD* kpoint = (TVectorD*)f->Get(Form("%s/%s/kpoint",dirname.Data(),name.Data()));
        TVectorD* NcollAver = (TVectorD*)f->Get(Form("%s/%s/NcollAver",dirname.Data(),name.Data()));
	TVectorD* centbin = (TVectorD*)f->Get(Form("%s/%s/centbin",dirname.Data(),name.Data()));

        TFile *fGlauber = TFile::Open(Glaubername->GetName());
        //(*k0)[0]=1.39;  (*kbest)[0]=0.425;
        //(*theta0)[0]=3.41;      (*thetabest)[0]=1.30;
        TF1 *gammafun[maxNpart];
        TF1 *gammafunevt[maxNpart];
        TF1 *gammafunnucl[maxNpart];
        TF1 *gammafunnuclNcoll[maxNpart];
        double kevt = (*k0)[0]-(*kbest)[0];
        for(int iNpart=0;iNpart<maxNpart;iNpart++){
        	gammafun[iNpart] = new TF1("gammafun","TMath::GammaDist(x,[0],0,[1])",0,200);
		gammafunevt[iNpart] = new TF1("gammafunevt","TMath::GammaDist(x,[0],0,[1])",0,200);
	        gammafunnucl[iNpart] = new TF1("gammafunnucl","TMath::GammaDist(x,[0],0,[1])",0,200);
        	gammafunnuclNcoll[iNpart] = new TF1("gammafunnuclNcoll","TMath::GammaDist(x,[0],0,[1])",0,200);
                double k_=(*k0)[0]+(*kbest)[0]*(iNpart-2);
                double theta_=(*theta0)[0]+(*thetabest)[0]*TMath::Log(iNpart-1);
                gammafun[iNpart]->SetParameter(0,k_);   //[1]: k value
                gammafun[iNpart]->SetParameter(1,theta_);       //[2]: theta value
		gammafunevt[iNpart]->SetParameter(0,kevt);
		gammafunevt[iNpart]->SetParameter(1,theta_);
		gammafunnucl[iNpart]->SetParameter(0,(*kbest)[0]);
		gammafunnucl[iNpart]->SetParameter(1,theta_);
		gammafunnuclNcoll[iNpart]->SetParameter(0,(*kbest)[0]*(iNpart-1));
		gammafunnuclNcoll[iNpart]->SetParameter(1,theta_);
		if(iNpart==2){
			gammafunnuclNcoll[iNpart]->SetNpx(1e4);
			gammafunnuclNcoll[iNpart]->SetRange(1e-11,200);
		}
       }

        TTree *t = (TTree*)fGlauber->Get("nt_p_Pb");
        Float_t Ncoll, Npart, B;        Long_t Nevent;
        t->SetBranchAddress("Ncoll",&Ncoll);
        t->SetBranchAddress("Npart",&Npart);
        t->SetBranchAddress("B",&B);

        Nevent = (Long_t) t->GetEntries();
        Long_t Ev;      Int_t Bino;     Double_t Para, Para_nucl, Para_p, Para_evt, Bi_Para_nucl, Bi_Para_evt;			

	double yUCM[8]={};
	double yPCM[8]={};
	double yVCM[8]={};
	double yUCM_[200]={};
	double yPCM_[200]={};
	double yVCM_[200]={};
	double C=1e-4;
	double PNcoll[maxNpart]={};
	TH1D *histo_obs = (TH1D*)fdata->Get(histoname->GetName());
        TH1D *histo_obs_norm = (TH1D*)histo_obs->Clone();
        histo_obs_norm->Scale(1/histo_obs->Integral());
	TH1D* hUCM = new TH1D("hUCM","hUCM",200,0,200);
	TH1D* hPCM = new TH1D("hPCM","hPCM",200,0,200);
	TH1D* hVCM = new TH1D("hVCM","hVCM",200,0,200);
	TH2D* NcollvsET = new TH2D("NcollvsET","NcollvsET",100,0,100,2000,0,400);
	for(Ev=0;Ev<Nevent;Ev++){
		t->GetEntry(Ev);
		PNcoll[(int)Ncoll]++;
	}
	for(int i=0;i<maxNpart;i++){
		PNcoll[i]/=Nevent;
		cout<<PNcoll[i]<<"\t";
	}
		cout<<endl;
	for(Ev=0;Ev<Nevent;Ev++){
		if(Ev%100000==0)	cout<<"\t"<<"Have run "<<Ev<<" events"<<endl;
		t->GetEntry(Ev);
		Para = gammafun[(int)Npart]->GetRandom();
		Para_nucl = gammafunnuclNcoll[(int)Npart]->GetRandom();
		Para_p = gammafunnuclNcoll[(int)Npart]->GetRandom();
		Para_evt = 0;
		for(int i=0;i<N-1;i++)
			if(Para>=(*kpoint)[i] && Para<(*kpoint)[i+1])
				int ibin = i;
		for(int Bino=0;Bino<Ncoll;Bino++){
			Bi_Para_evt = gammafunevt[(int)Npart]->GetRandom();
			Para_evt += Bi_Para_evt;
		}	
		double PNcollET = gammafun[(int)Npart]->Eval(Para);
//		double k = gammafun[(int)Npart]->GetParameter(0);
                double theta=(*theta0)[0]+(*thetabest)[0]*TMath::Log(Npart-1);
		double YNcollUCM = C*Ncoll;
		double YNcollPCM = C/1.0/(*kbest)[0]/theta*(Para_nucl);
		double YNcollVCM = C/2.0*(Para_nucl/(*kbest)[0]/theta+Ncoll);
		yUCM[ibin] += PNcoll[(int)Ncoll]*PNcollET*YNcollUCM;
		yPCM[ibin] += PNcoll[(int)Ncoll]*PNcollET*YNcollPCM;
		yVCM[ibin] += PNcoll[(int)Ncoll]*PNcollET*YNcollVCM;
		yUCM_[(int)Para] += PNcoll[(int)Ncoll]*PNcollET*YNcollUCM;
		yPCM_[(int)Para] += PNcoll[(int)Ncoll]*PNcollET*YNcollPCM;
		yVCM_[(int)Para] += PNcoll[(int)Ncoll]*PNcollET*YNcollVCM;

		NcollvsET->Fill(Ncoll,Para);
	}
	for(int ibin=1;ibin<hUCM->GetNbinsX();ibin++){
		hUCM->SetBinContent(ibin,yUCM_[ibin-1]);			
		hPCM->SetBinContent(ibin,yPCM_[ibin-1]);			
		hVCM->SetBinContent(ibin,yVCM_[ibin-1]);
	}
	TCanvas *c1 = new TCanvas();
	TCanvas *c2 = new TCanvas();
	c1->SetLogy();
	c2->SetLogx();
	c2->SetLogy();
	c2->SetLogz();
	c1->cd();
	TH1D* hFrame = new TH1D("","",200,0,200);
	hFrame->SetTitle("");
	hFrame->GetXaxis()->SetTitle("HF #Sigma E_{T} |#eta|>4");
	hFrame->GetYaxis()->SetTitle("Yield no units");
	hFrame->GetXaxis()->SetRangeUser(0,150);
	hFrame->GetYaxis()->SetRangeUser(1e-6,1);
	hFrame->Draw();
	histo_obs_norm->SetMarkerStyle(20);
	histo_obs_norm->SetMarkerSize(1.0);
	histo_obs_norm->SetMarkerColor(1);
	histo_obs_norm->Draw("Psame");
	hUCM->SetMarkerStyle(24);
	hUCM->SetMarkerSize(1.0);
	hUCM->SetMarkerColor(2);
        hPCM->SetMarkerStyle(29);
        hPCM->SetMarkerSize(1.0);
        hPCM->SetMarkerColor(4);
        hVCM->SetMarkerStyle(34);
        hVCM->SetMarkerSize(1.0);
        hVCM->SetMarkerColor(5);
	hUCM->Draw("Psame");
	hPCM->Draw("Psame");
	hVCM->Draw("Psame");
	TLegend *leg = new TLegend(0.1,0.2,0.5,0.45);	
        leg->SetFillColor(0);
        leg->SetFillStyle(0);
        leg->SetBorderSize(0);
        leg->SetTextFont(42);
        leg->SetTextSize(0.03);
	leg->AddEntry(histo_obs_norm,"minimum bias events","lp");
	leg->AddEntry(hUCM,"hard scattering events(UCM)","lp");
	leg->AddEntry(hPCM,"hard scattering events(PCM)","lp");
	leg->AddEntry(hVCM,"hard scattering events(VCM)","lp");
	leg->Draw("same");
	c1->Print("paperfig3_CMS.png");
	c2->cd();
	gStyle->SetOptStat("nemr");
	NcollvsET->GetXaxis()->SetTitle("Ncoll");
	NcollvsET->GetYaxis()->SetTitle("HF #Sigma E_{T} |#eta|>4");
	NcollvsET->Draw("colz");
	c2->Print("NcollvsET2D.png");
	ofstream fstr("result_CMS.dat");
	fstr<<"i"<<"\t"<<"centbin"<<"\t"<<"kpoint"<<"\t"<<"NcollAver"<<"\t"<<"UCM"<<"\t"<<"PCM"<<"\t"<<"VCM"<<"\t"<<"pho1"<<"\t"<<"pho2"<<"\t"<<"MB"<<endl;
	for(int i=0;i<N-1;i++){
		fstr<<i<<"\t"<<(*centbin)[i]*100<<"% to "<<(*centbin)[i+1]*100<<"% \t"<<(*kpoint)[i]<<" to "<<(*kpoint)[i+1]<<"\t"<<(*NcollAver)[i]<<"\t"<<yUCM[i]<<"\t"<<yPCM[i]<<"\t"<<yVCM[i]<<"\t"<<yPCM[i]/yUCM[i]<<"\t"<<yVCM[i]/yUCM[i]<<"\t"<<"undetermined"<<endl;
	}
}
SelectPPCoincMapRegions::SelectPPCoincMapRegions(SelectPPCoincMapRegions const& obj)
    : fPed(),
    fThresh(),
    fLowCut(),
    fHighCut(),
    fLowCut2(),
    fHighCut2(),
    fLowCut3(),
    fHighCut3(),
    fPedThresh(),
    fGlobalUpperBound(),
    fNRegions(0),

    regional_coinc(),
    regional_coinc_map(),

    data_in_region_of_strip(),

    region_multiplicity(fNRegions+2,0),
    mult_mismatch(fNRegions+2,0),
    fMaxMult(obj.fMaxMult),
    fChLow(obj.fChLow),
    fChHigh(obj.fChHigh)
{
#ifdef DEBUG
    std::cout << "Copy constructing SelectPPCoincMapRegions" << std::endl; std::cout.flush();
#endif

    if (this != &obj)
    {
        runcount = obj.runcount;
        nentries = obj.nentries;
        fNRegions = obj.fNRegions;
        regional_coinc_map = obj.regional_coinc_map;

        pce = obj.pce;   // Do not copy the object
        LoadSettings (pce);

        std::map<UInt_t, TH1D*>::const_iterator it;
        std::string key;

        it = obj.regional_coinc.begin();
        for (;it!=obj.regional_coinc.end(); it++)
        {
            TH1D* tmp = static_cast<TH1D*>(it->second->Clone());
            tmp->SetDirectory(0);

            regional_coinc.insert(std::make_pair(it->first, tmp));
        }

        runnumber = obj.runnumber;
        starttime = obj.starttime;
        endtime = obj.endtime;
        n_phys_events = obj.n_phys_events;

        nt_tdc = obj.nt_tdc;
        nt_adc = obj.nt_adc;

        b_evnum = obj.b_evnum;
        b_run = obj.b_run;
        b_start = obj.b_start;
        b_end = obj.b_end;
        b_nphyev = obj.b_nphyev;
        b_evtype = obj.b_evtype;
        b_latch = obj.b_latch;
        b_trigger = obj.b_trigger;

        b_tdc = obj.b_tdc;
        b_adc = obj.b_adc;

        ndet = obj.ndet;
        nadc_ch = obj.nadc_ch;
        ntdc_ch = obj.ntdc_ch;

        data_in_region_of_strip = obj.data_in_region_of_strip;

        willSave = obj.willSave;

        region_multiplicity = obj.region_multiplicity;

        mult_mismatch = obj.mult_mismatch;

    }
}
Exemple #20
0
/**
 * 1. Data sample : pp200 W->e nu with  pile-up corresponding to 1 MHz min. bias
 * events, 50 K event y2011, 10 K event y2012.
 *
 * 2. Proof of principal: no pile-up for both PPV and KFV
 *
 *   a.  Reconstructed primary track multiplicity versus corresponding MC
 *   "reconstructable" (i.e. in n STAR acceptance,no. TPC MC hits >= 15)  tracks
 *   multiplicity.
 *
 *   b.  Corrected reconstructed primary track multiplicity (i.e. multiplied by
 *   QA/100.) versus corresponding MC "reconstructable"  (i.e. in n STAR
 *   acceptance,no. TPC MC hits >= 15)  tracks multiplicity.
 *
 *   c.  Efficiency primary vertex reconstruction versus  MC "reconstructable"
 *   tracks multiplicity.
 *
 * 3. With pileup. repeat above (a-c) with old ranking scheme for
 *
 *     I. Any reconstructed primary vertex which is matched with MC trigger
 *     vertex (MC = 1)
 *
 *    II. The best (in sense of ranking) reconstructed primary vertex which is
 *    matched with MC trigger vertex (MC = 1)
 *
 *   III. The best (in sense of ranking) reconstructed primary vertex which is
 *   not matched with MC trigger vertex (MC != 1)
 *
 * 4. With pileup. repeat above (a-c) with new ranking scheme for cases I-III
 */
void MuMcPrVKFV2012(Long64_t nevent, const char *file, const std::string& outFile, bool fillNtuple)
{
#ifdef __TMVA__
   boost::replace_last(outFile, ".root", "");
   outFile += ".TMVArank.root";

   // 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) that you use
   TString separator(":");
   TString Vnames(vnames);
   TObjArray *array = Vnames.Tokenize(separator);

   std::vector<std::string> inputVars;
   TIter next(array);
   TObjString *objs;

   while ((objs = (TObjString *) next())) {
      std::cout << objs->GetString() << std::endl;
   }

   inputVars.push_back("beam");
   inputVars.push_back("postx");
   inputVars.push_back("prompt");
   inputVars.push_back("cross");
   inputVars.push_back("tof");
   inputVars.push_back("notof");
   inputVars.push_back("EEMC");
   inputVars.push_back("noEEMC");
   inputVars.push_back("chi2");

   std::vector<double> *inputVec = new std::vector<double>( inputVars.size() );
   IClassifierReader *classReader = new ReadBDT( inputVars );

#endif /* __TMVA__ */

   TFile *fOut = TFile::Open(outFile.c_str(), "recreate");
   data_t data;

   // Book histograms
   const int nMcRecMult = 75;
   TArrayD xMult(nMcRecMult + 1);
   xMult[0] = -0.5;

   for (int i = 1; i <= nMcRecMult; i++) {
      if      (xMult[i - 1] <  50) xMult[i] = xMult[i - 1] +   1; //  1 - 50
      else if (xMult[i - 1] < 100) xMult[i] = xMult[i - 1] +   2; // 51 - 75
      else if (xMult[i - 1] < 200) xMult[i] = xMult[i - 1] +  10; // 76 - 85
      else                         xMult[i] = xMult[i - 1] + 100; // 86 -100
   }

   TH1D *McRecMulT = new TH1D("McRecMulT", "Reconstructable multiplicity for trigger Mc Vertex", nMcRecMult, xMult.GetArray());
   struct Name_t {
      const Char_t *Name;
      const Char_t *Title;
   };
   const Name_t HCases[3] = {
      {"Any", "Any vertex matched with MC == 1"},
      {"Good", "The best rank vertex with MC == 1"},
      {"Bad", "The best rank vertex with MC != 1"}
   };
   const Name_t Plots[4] = {
      {"Mult"    , "the reconstructed (uncorrected) track multiplicity versus Reconstructable multiplicity"},
      {"MultQA"  , "the reconstructed (corrected for QA) track multiplicity versus Reconstructable multiplicity"},
      {"McRecMul", "Reconstructable multiplicity"},
      {"YvsX"    , "Bad versus Good value"}
   };
   /*         h  p  */
   TH1 *hists[3][4];

   for (int h = 0; h < 3; h++) {
      for (int p = 0; p < 4; p++) {
         TString Name(Plots[p].Name); Name += HCases[h].Name;
         TString Title(Plots[p].Title); Title += " for "; Title += HCases[h].Title; Title += " vertex";

         if      (p <  2)  hists[h][p] = new TH2D(Name, Title, nMcRecMult, xMult.GetArray(), nMcRecMult, xMult.GetArray());
         else if (p == 2)  hists[h][p] = new TH1D(Name, Title, nMcRecMult, xMult.GetArray());
      }
   }

   TNtuple *VertexG = new TNtuple("VertexG", "good vertex & global params info", vnames);
   TNtuple *VertexB = new TNtuple("VertexB", "bad  vertex & global params info", vnames);
   // ----------------------------------------------
   StMuDstMaker *maker = new StMuDstMaker(0, 0, "", file, "st:MuDst.root", 1e9); // set up maker in read mode
   //                       0,0                        this mean read mode
   //                           dir                    read all files in this directory
   //                               file               bla.lis real all file in this list, if (file!="") dir is ignored
   //                                    filter        apply filter to filenames, multiple filters are separated by ':'
   //                                          10      maximum number of file to read
   maker->SetStatus("*", 0);

   std::vector<std::string> activeBranchNames = {
      "MuEvent",
      "PrimaryVertices",
      "StStMuMcVertex",
      "StStMuMcTrack"
   };

   // Set Active braches
   for (const auto& branchName : activeBranchNames)
      maker->SetStatus(branchName.c_str(), 1);

   TChain *tree = maker->chain();
   Long64_t nentries = tree->GetEntries();
   nevent = TMath::Min(nevent, nentries);
   std::cout << nentries << " events in chain " << nevent << " will be read." << std::endl;
   tree->SetCacheSize(-1);        //by setting the read cache to -1 we set it to the AutoFlush value when writing
   tree->SetCacheLearnEntries(1); //one entry is sufficient to learn
   tree->SetCacheEntryRange(0, nevent);

   for (Long64_t ev = 0; ev < nevent; ev++) {
      if (maker->Make()) break;

      StMuDst *muDst = maker->muDst();   // get a pointer to the StMuDst class, the class that points to all the data
      StMuEvent *muEvent = muDst->event(); // get a pointer to the class holding event-wise information
      int referenceMultiplicity = muEvent->refMult(); // get the reference multiplicity

      TClonesArray *PrimaryVertices   = muDst->primaryVertices();
      int nPrimaryVertices = PrimaryVertices->GetEntriesFast();

      TClonesArray *MuMcVertices   = muDst->mcArray(0);
      int nMuMcVertices = MuMcVertices->GetEntriesFast();

      TClonesArray *MuMcTracks     = muDst->mcArray(1);
      int nMuMcTracks = MuMcTracks->GetEntriesFast();

      if ( nevent >= 10 && ev % int(nevent*0.1) == 0 )
      {
         std::cout << "Event #" << ev << "\tRun\t" << muEvent->runId()
                   << "\tId: " << muEvent->eventId()
                   << " refMult= " << referenceMultiplicity
                   << "\tPrimaryVertices " << nPrimaryVertices
                   << "\t" << " " << nMuMcVertices
                   << "\t" << " " << nMuMcTracks
                   << std::endl;
      }

      //    const Double_t field = muEvent->magneticField()*kilogauss;
      if (! nMuMcVertices || ! nMuMcTracks || nPrimaryVertices <= 0) {
         std::cout << "Ev. " << ev << " has no MC information ==> skip it" << std::endl;
         std::cout << "OR no reconstructed verticies found" << std::endl;
         continue;
      }

      // Count number of MC tracks at a vertex with TPC reconstructable tracks
      std::multimap<int, int> Mc2McHitTracks;

      for (int m = 0; m < nMuMcTracks; m++) {
         StMuMcTrack *McTrack = (StMuMcTrack *) MuMcTracks->UncheckedAt(m);

         if (McTrack->No_tpc_hit() < 15) continue;

         Mc2McHitTracks.insert(std::pair<int, int>(McTrack->IdVx(), McTrack->Id()));
      }

      // This is the "reconstructable" track multiplicity
      int nMcTracksWithHits = Mc2McHitTracks.count(1);

      // Let's skip events in which we do not expect to reconstruct any tracks
      // (and thus vertex) from the primary vertex
      if (nMcTracksWithHits <= 0) continue;

      // This is our denominator histogram for efficiencies
      McRecMulT->Fill(nMcTracksWithHits);

      // =============  Build map between  Rc and Mc vertices
      std::map<StMuPrimaryVertex *, StMuMcVertex *> reco2McVertices;
      TArrayF vertexRanks(nPrimaryVertices);
      int mcMatchedVertexIndex  = -1; // any vertex with MC==1 and highest reconstrated multiplicity.
      int vertexMaxMultiplicity = -1;

      // First loop over all verticies in this event. There is at least one
      // must be available
      for (int recoVertexIndex = 0; recoVertexIndex < nPrimaryVertices; recoVertexIndex++)
      {
         vertexRanks[recoVertexIndex] = -1e10;

         StMuPrimaryVertex *recoVertex = (StMuPrimaryVertex *) PrimaryVertices->UncheckedAt(recoVertexIndex);

         if ( !AcceptVX(recoVertex) ) continue;

         // Check Mc
         if (recoVertex->idTruth() < 0 || recoVertex->idTruth() > nMuMcVertices) {
            std::cout << "ERROR: Illegal idTruth " << recoVertex->idTruth() << " The track is ignored" << std::endl;
            continue;
         }

         StMuMcVertex *mcVertex = (StMuMcVertex *) MuMcVertices->UncheckedAt(recoVertex->idTruth() - 1);

         if (mcVertex->Id() != recoVertex->idTruth()) {
            std::cout << "ERROR: Mismatched idTruth " << recoVertex->idTruth() << " and mcVertex Id " <<  mcVertex->Id()
                 << " The vertex is ignored" <<  std::endl;
            continue;
         }

         reco2McVertices[recoVertex] = mcVertex;
         vertexRanks[recoVertexIndex] = recoVertex->ranking();

         if (recoVertex->idTruth() == 1 && recoVertex->noTracks() > vertexMaxMultiplicity)
         {
            mcMatchedVertexIndex  = recoVertexIndex;
            vertexMaxMultiplicity = recoVertex->noTracks();
         }

         FillData(data, recoVertex);

#ifdef __TMVA__
         Float_t *dataArray = &data.beam;

         for (size_t j = 0; j < inputVec->size(); j++)
            (*inputVec)[j] = dataArray[j];

         vertexRanks[recoVertexIndex] = classReader->GetMvaValue( *inputVec );
#endif
      }

      // If we reconstructed a vertex which matches the MC one we fill the
      // numerator of the "Any" efficiency histogram
      if (mcMatchedVertexIndex != -1) {

         StMuPrimaryVertex *recoVertexMatchedMc = (StMuPrimaryVertex*) PrimaryVertices->UncheckedAt(mcMatchedVertexIndex);

         double nTracks = recoVertexMatchedMc->noTracks();
         double nTracksQA = nTracks * recoVertexMatchedMc->qaTruth() / 100.;

         hists[0][0]->Fill(nMcTracksWithHits, nTracks);
         hists[0][1]->Fill(nMcTracksWithHits, nTracksQA);
         hists[0][2]->Fill(nMcTracksWithHits);
      }

      // Now deal with the highest rank vertex
      int maxRankVertexIndex = TMath::LocMax(nPrimaryVertices, vertexRanks.GetArray());

      StMuPrimaryVertex *recoVertexMaxRank = (StMuPrimaryVertex*) PrimaryVertices->UncheckedAt(maxRankVertexIndex);
      StMuMcVertex *mcVertex = reco2McVertices[recoVertexMaxRank];

      double nTracks = recoVertexMaxRank->noTracks();
      double nTracksQA = nTracks * recoVertexMaxRank->qaTruth() / 100.;

      // Fill numerator for "good" and "bad" efficiencies
      int h = ( mcVertex && mcVertex->Id() == 1) ? 1 : 2;

      hists[h][0]->Fill(nMcTracksWithHits, nTracks);
      hists[h][1]->Fill(nMcTracksWithHits, nTracksQA);
      hists[h][2]->Fill(nMcTracksWithHits);


      // Proceed with filling ntuple only if requested by the user
      if ( !fillNtuple ) continue;


      // Second loop over all verticies in this event
      for (int recoVertexIndex = 0; recoVertexIndex < nPrimaryVertices; recoVertexIndex++)
      {
         StMuPrimaryVertex *recoVertex = (StMuPrimaryVertex *) PrimaryVertices->UncheckedAt(recoVertexIndex);

         if ( !AcceptVX(recoVertex) ) continue;

         StMuMcVertex *mcVertex = reco2McVertices[recoVertex];

         if ( !mcVertex ) {
            std::cout << "No Match from RC to MC" << std::endl;
            continue;
         }

         if (vtxeval::gDebugFlag) {
            std::cout << Form("Vx[%3i]", recoVertexIndex) << *recoVertex << " " << *mcVertex;
            int nMcTracksWithHitsatL = Mc2McHitTracks.count(recoVertex->idTruth());
            std::cout << Form("Number of McTkHit %4i rank %8.3f", nMcTracksWithHitsatL, vertexRanks[recoVertexIndex]);
         }

         int IdPar = mcVertex->IdParTrk();

         if (IdPar > 0 && IdPar <= nMuMcTracks) {
            StMuMcTrack *mcTrack = (StMuMcTrack *) MuMcTracks->UncheckedAt(IdPar - 1);

            if (mcTrack && vtxeval::gDebugFlag) std::cout << " " << mcTrack->GeName();
         }

         FillData(data, recoVertex);

         double nTracks = recoVertex->noTracks();

         if (mcVertex->Id() == 1 && nTracks == vertexMaxMultiplicity) {// good
            VertexG->Fill(&data.beam);
         }
         else {   // bad
            VertexB->Fill(&data.beam);
         }
      }

      if ( !gROOT->IsBatch() ) {
         if (vtxeval::ask_user()) return;
      }
      else { vtxeval::gDebugFlag = false; }
   }

   fOut->Write();
}
void DrawNCLUSTER()
{
  //=========Macro generated from canvas: r1/Energy
  //=========  (Fri Apr  6 17:14:48 2012) by ROOT version5.28/00g
  TCanvas *r1 = new TCanvas("r1", "Ncluster",12,24,550,741);
  gStyle->SetOptStat(0);
  gStyle->SetOptTitle(0);
  gStyle->SetFrameLineWidth(1);
  r1->Range(0,0,1,1);
  r1->SetFillColor(0);
  r1->SetBorderMode(0);
  r1->SetBorderSize(0);
  r1->SetTickx(1);
  r1->SetTicky(1);
  r1->SetLeftMargin(0.16);
  r1->SetRightMargin(0.01);
  r1->SetTopMargin(0.0256917);
  r1->SetBottomMargin(0.07692308);
  r1->SetFrameBorderMode();
  
  // ------------>Primitives in pad: r1_1
  TPad *r1_1 = new TPad("r1_1", "Energy_1",0.02,0.37,0.95,0.99);
  r1_1->Draw();
  r1_1->cd();
  r1_1->Range(-19,0.01,95,95);
  r1_1->SetFillColor(0);
  r1_1->SetBorderMode(0);
  r1_1->SetBorderSize(2);
  r1_1->SetTickx(1);
  r1_1->SetTicky(1);
  r1_1->SetLeftMargin(0.16);
  r1_1->SetRightMargin(0.01);
  r1_1->SetTopMargin(0.02);
  r1_1->SetBottomMargin(0);
  r1_1->SetFrameBorderMode(0);
  r1_1->SetFrameBorderMode(0);
   
  TH1D *he = new TH1D("he"," ",55,0,55);
  he->SetMinimum(0.01);
  he->SetMaximum(70);
  he->SetStats(0);
  he->GetXaxis()->SetTitle("E_{beam} [GeV]");
  he->GetXaxis()->SetLabelFont(43);
  he->GetXaxis()->SetLabelSize(0);
  he->GetXaxis()->SetTitleFont(43);
  he->GetXaxis()->SetTitleSize(0); 
  he->GetYaxis()->SetTitle("<N_{cluster}>");
  he->GetYaxis()->SetLabelFont(43);
  he->GetYaxis()->SetTitleSize(30);
  he->GetYaxis()->SetLabelSize(20);
  he->GetYaxis()->SetTitleFont(43);
  he->GetYaxis()->SetTitleOffset(1.7);
  he->GetZaxis()->SetLabelFont(42);
  he->GetZaxis()->SetTitleSize(0.05);
  he->GetZaxis()->SetTitleFont(42);
  he->Draw("");
   
  std::vector<result> resultData=readTXT(std::string("ncluster_augsep2012_electron.txt"));
  TGraphErrors *gre = new TGraphErrors(resultData.size());
  gre->SetName("Graph");
  gre->SetTitle("Graph");
  gre->SetLineColor(1);
  gre->SetFillStyle(1);
  gre->SetFillColor(1);
  gre->SetLineWidth(2);
  gre->SetMarkerColor(1);
  gre->SetMarkerStyle(34);
  gre->SetMarkerSize(1.2);
  for(unsigned int i=0; i<resultData.size(); i++){
    gre->SetPoint(i,resultData.at(i).ebeam,resultData.at(i).ncluster);
    gre->SetPointError(i,0,resultData.at(i).nclusterError);
  }

  TH1F *Graph_Graph3 = new TH1F("Graph_Graph3","Graph",100,0,87.5);
  Graph_Graph3->SetMinimum(0);
  Graph_Graph3->SetMaximum(1193.483);
  Graph_Graph3->SetDirectory(0);
  Graph_Graph3->SetStats(0);
  Graph_Graph3->GetXaxis()->SetLabelFont(42);
  Graph_Graph3->GetXaxis()->SetTitleSize(0.05);
  Graph_Graph3->GetXaxis()->SetTitleFont(42);
  Graph_Graph3->GetYaxis()->SetLabelFont(42);
  Graph_Graph3->GetYaxis()->SetTitleSize(0.05);
  Graph_Graph3->GetYaxis()->SetTitleFont(42);
  Graph_Graph3->GetZaxis()->SetLabelFont(42);
  Graph_Graph3->GetZaxis()->SetTitleSize(0.05);
  Graph_Graph3->GetZaxis()->SetTitleFont(42);
  gre->SetHistogram(Graph_Graph3);
   
  gre->Draw("p");
   
  std::vector<result> resultFTFP=readTXT(std::string("ncluster_ftfp_bert_hp_electron.txt"));
  gre = new TGraphErrors(resultFTFP.size());
  gre->SetName("Graph");
  gre->SetTitle("Graph");
  gre->SetFillColor(kRed-3);
  gre->SetMarkerColor(kRed-3);
  gre->SetLineWidth(2);
  gre->SetMarkerStyle(20);
  for(unsigned int i=0; i<resultFTFP.size(); i++){
    gre->SetPoint(i,resultFTFP.at(i).ebeam,resultFTFP.at(i).ncluster);
    gre->SetPointError(i,0,resultFTFP.at(i).nclusterError);
  }
   
  TH1F *Graph1 = new TH1F("Graph1","Graph",100,0,87.17072);
  Graph1->SetMinimum(2.655724);
  Graph1->SetMaximum(88.56778);
  Graph1->SetDirectory(0);
  Graph1->SetStats(0);
  Graph1->GetXaxis()->SetLabelFont(42);
  Graph1->GetXaxis()->SetTitleSize(0.05);
  Graph1->GetXaxis()->SetTitleFont(42);
  Graph1->GetYaxis()->SetLabelFont(42);
  Graph1->GetYaxis()->SetTitleSize(0.05);
  Graph1->GetYaxis()->SetTitleFont(42);
  Graph1->GetZaxis()->SetLabelFont(42);
  Graph1->GetZaxis()->SetTitleSize(0.05);
  Graph1->GetZaxis()->SetTitleFont(42);
  gre->SetHistogram(Graph1);
   
  gre->Draw("p");

  std::vector<result> resultQGSP=readTXT(std::string("ncluster_qgsp_bert_hp_electron.txt"));
  gre = new TGraphErrors(resultQGSP.size());
  gre->SetName("Graph");
  gre->SetTitle("Graph");
  gre->SetFillColor(kBlue-6);
  gre->SetMarkerColor(kBlue-6);
  gre->SetLineWidth(2);
  gre->SetMarkerStyle(25);
  for(unsigned int i=0; i<resultQGSP.size(); i++){
    gre->SetPoint(i,resultQGSP.at(i).ebeam,resultQGSP.at(i).ncluster);
    gre->SetPointError(i,0,resultQGSP.at(i).nclusterError);
  }

  TH1F *Graph_Graph2 = new TH1F("Graph_Graph2","Graph",100,0,87.5);
  Graph_Graph2->SetMinimum(0);
  Graph_Graph2->SetMaximum(1193.483);
  Graph_Graph2->SetDirectory(0);
  Graph_Graph2->SetStats(0);
  Graph_Graph2->GetXaxis()->SetLabelFont(42);
  Graph_Graph2->GetXaxis()->SetTitleSize(0.05);
  Graph_Graph2->GetXaxis()->SetTitleFont(42);
  Graph_Graph2->GetYaxis()->SetLabelFont(42);
  Graph_Graph2->GetYaxis()->SetTitleSize(0.05);
  Graph_Graph2->GetYaxis()->SetTitleFont(42);
  Graph_Graph2->GetZaxis()->SetLabelFont(42);
  Graph_Graph2->GetZaxis()->SetTitleSize(0.05);
  Graph_Graph2->GetZaxis()->SetTitleFont(42);
  gre->SetHistogram(Graph_Graph2);
   
  gre->Draw("p");

  TLegend *leg = new TLegend(0.15,0.7,0.75,0.9,NULL,"brNDC");
  leg->SetBorderSize(0);
  leg->SetTextFont(62);
  leg->SetLineColor(1);
  leg->SetLineStyle(1);
  leg->SetLineWidth(1);
  leg->SetFillColor(0);
  leg->SetFillStyle(0);
   
  TLegendEntry *entry=leg->AddEntry("Graph_Graph3","SDHCAL DATA (H6 Cern SPS)","p");
  entry->SetLineColor(1);
  entry->SetLineStyle(1);
  entry->SetLineWidth(1);
  entry->SetMarkerColor(1);
  entry->SetMarkerStyle(34);
  entry->SetMarkerSize(1.2);

  entry=leg->AddEntry("Graph1","FTFP_BERT_HP","p");
  entry->SetLineColor(kRed-3);
  entry->SetLineStyle(kRed-3);
  entry->SetLineWidth(kRed-3);
  entry->SetMarkerColor(kRed-3);
  entry->SetMarkerStyle(20);
  entry->SetMarkerSize(1.0);

  entry=leg->AddEntry("Graph_Graph2","QGSP_BERT_HP","p");
  entry->SetLineColor(kBlue-6);
  entry->SetLineStyle(kBlue-6);
  entry->SetLineWidth(kBlue-6);
  entry->SetMarkerColor(kBlue-6);
  entry->SetMarkerStyle(25);
  entry->SetMarkerSize(0.9);

  leg->Draw();

  TText *tex=new TText();
  tex->SetTextSize(0.05);
  tex->SetTextColor(kGray+2);
  //tex->DrawTextNDC(0.5,0.05,"SDHCAL Preliminary");
  tex->DrawTextNDC(0.3,0.05,"CALICE Fe-SDHCAL Preliminary");
  r1_1->Modified();
  r1->cd();
  
  // ------------>Primitives in pad: r1_2
  TPad *r1_2 = new TPad("r1_2", "Energy_2",0.02,0.0,0.95,0.38);
  r1_2->Draw();
  r1_2->cd();
  r1_2->Range(-19,-0.06545455,95,0.048);
  r1_2->SetFillColor(0);
  r1_2->SetBorderMode(0);
  r1_2->SetBorderSize(2);
  r1_2->SetTickx(1);
  r1_2->SetTicky(1);
  r1_2->SetLeftMargin(0.16);
  r1_2->SetRightMargin(0.01);
  r1_2->SetTopMargin(0.0);
  r1_2->SetBottomMargin(0.23);
  r1_2->SetFrameBorderMode(0);
  r1_2->SetFrameBorderMode(0);
   
  TH1D *hd = new TH1D("hd"," ",55,0,55);
  hd->SetMinimum(-0.20);
  hd->SetMaximum(0.20);
  hd->SetStats(0);
  hd->GetXaxis()->SetTitle("E_{beam} [GeV]");
  hd->GetXaxis()->SetLabelFont(43);
  hd->GetXaxis()->SetLabelSize(20);
  hd->GetXaxis()->SetTitleFont(43);
  hd->GetXaxis()->SetTitleSize(30);
  hd->GetXaxis()->SetTitleOffset(2.);
  hd->GetYaxis()->SetTitle("(#DeltaN_{cluster})/N_{data}");
  hd->GetYaxis()->SetLabelFont(43);
  hd->GetYaxis()->SetLabelSize(20);
  hd->GetYaxis()->SetTitleSize(30);
  hd->GetYaxis()->SetTitleOffset(1.7);
  hd->GetYaxis()->SetTitleFont(43);
  hd->GetYaxis()->SetNdivisions(505);
  hd->GetZaxis()->SetLabelFont(42);
  hd->GetZaxis()->SetTitleSize(0.05);
  hd->GetZaxis()->SetTitleFont(42);
  hd->Draw("");
   
  float deltaError;
  float delta;
  gre = new TGraphErrors(resultQGSP.size());
  gre->SetName("Graph");
  gre->SetTitle("Graph");
  for(unsigned int i=0; i<resultQGSP.size(); i++){
    delta=(resultQGSP.at(i).ncluster-resultData.at(i).ncluster)/resultData.at(i).ncluster;
    deltaError=1/resultData.at(i).ncluster*
      sqrt(pow(resultQGSP.at(i).nclusterError,2) +
	   pow(resultQGSP.at(i).ncluster/resultData.at(i).ncluster*resultData.at(i).nclusterError,2));
    gre->SetPoint(i,resultQGSP.at(i).ebeam,delta);
    gre->SetPointError(i,0,deltaError);
  }
  gre->SetLineWidth(2);
  gre->SetLineColor(kBlue-6);
  gre->SetMarkerColor(kBlue-6);
  gre->SetMarkerSize(1.0);
  gre->SetMarkerStyle(25);
   
  gre->Draw("p");
   
  gre = new TGraphErrors(resultFTFP.size());
  gre->SetName("Graph");
  gre->SetTitle("Graph");
  for(unsigned int i=0; i<resultFTFP.size(); i++){
    delta=(resultFTFP.at(i).ncluster-resultData.at(i).ncluster)/resultData.at(i).ncluster;
    deltaError=1/resultData.at(i).ncluster*
      sqrt(pow(resultFTFP.at(i).nclusterError,2) +
	   pow(resultFTFP.at(i).ncluster/resultData.at(i).ncluster*resultData.at(i).nclusterError,2));
    gre->SetPoint(i,resultFTFP.at(i).ebeam,delta);
    gre->SetPointError(i,0,deltaError);
  }
  gre->SetLineWidth(2);
  gre->SetLineColor(kRed-3);
  gre->SetMarkerColor(kRed-3);
  gre->SetMarkerSize(1.0);
  gre->SetMarkerStyle(20);
   
  gre->Draw("p");
   
   
  TF1 *lin1 = new TF1("lin1","0",-0.01,95);
  lin1->SetFillColor(19);
  lin1->SetFillStyle(0);
  lin1->SetLineWidth(1);
  lin1->SetLineStyle(1);
  lin1->SetLineColor(1);
  lin1->GetXaxis()->SetLabelFont(42);
  lin1->GetXaxis()->SetTitleSize(0.05);
  lin1->GetXaxis()->SetTitleFont(42);
  lin1->GetYaxis()->SetLabelFont(42);
  lin1->GetYaxis()->SetTitleSize(0.05);
  lin1->GetYaxis()->SetTitleFont(42);
  lin1->Draw("same");
   
  lin1 = new TF1("lin1","0.1",0.01,95);
  lin1->SetFillColor(1);
  lin1->SetFillStyle(0);
  lin1->SetLineWidth(1);
  lin1->SetLineStyle(2);
  lin1->SetLineColor(17);
  lin1->GetXaxis()->SetLabelFont(42);
  lin1->GetXaxis()->SetTitleSize(0.05);
  lin1->GetXaxis()->SetTitleFont(42);
  lin1->GetYaxis()->SetLabelFont(42);
  lin1->GetYaxis()->SetTitleSize(0.05);
  lin1->GetYaxis()->SetTitleFont(42);
  lin1->Draw("same");
   
  lin1 = new TF1("lin1","-0.1",0.01,95);
  lin1->SetFillColor(1);
  lin1->SetFillStyle(0);
  lin1->SetLineWidth(1);
  lin1->SetLineStyle(2);
  lin1->SetLineColor(17);
  lin1->GetXaxis()->SetLabelFont(42);
  lin1->GetXaxis()->SetTitleSize(0.05);
  lin1->GetXaxis()->SetTitleFont(42);
  lin1->GetYaxis()->SetLabelFont(42);
  lin1->GetYaxis()->SetTitleSize(0.05);
  lin1->GetYaxis()->SetTitleFont(42);
  lin1->Draw("same");

  r1_2->Modified();
  r1->cd();
  r1->Modified();
  r1->cd();
  r1->SetSelected(r1);
  r1->SaveAs("../plots/NCLUSTERELECTRON.pdf");
}
Exemple #22
0
/** 
 * Draw the Poisson estimate of the occupancy
 * 
 * @param filename Input file name 
 * @param folder   Input folder name in file
 * 
 * @deprecated Use QATrender instead
 * @ingroup pwglf_forward_scripts_qa
 */
void
DrawOccupancy(const char* filename="forward.root", 
	      const char* folder="ForwardResults")
{
  gStyle->SetPalette(1);
  gStyle->SetOptFit(0);
  gStyle->SetOptStat(0);
  gStyle->SetOptTitle(0);
  gStyle->SetTitleW(.4);
  gStyle->SetTitleH(.1);
  gStyle->SetTitleX(.4);
  // gStyle->SetTitleY(.1);
  gStyle->SetTitleColor(0);
  gStyle->SetTitleStyle(0);
  gStyle->SetTitleBorderSize(0);
  
  TFile* file = TFile::Open(filename, "READ");
  if (!file) { 
    Error("DrawOccupancy", "failed to open %s", filename);
    return;
  }

  TList* forward = static_cast<TList*>(file->Get(folder));
  if (!forward) { 
    Error("DrawOccupancy", "List %s not found in %s", folder, filename);
    return;
  }

  TList* dc = static_cast<TList*>(forward->FindObject("fmdDensityCalculator"));
  if (!dc) { 
    Error("DrawOccupancy", "List fmdDensityCalculator not found in Forward");
    return;
  }
  
  TCanvas* c = new TCanvas("occupancy", 
			   "Mean Occupancy", 900, 700);
  c->SetFillColor(0);
  c->SetBorderSize(0);
  c->SetBorderMode(0);
  c->SetHighLightColor(0);
  c->SetBottomMargin(.15);
  c->SetTopMargin(.02);
  c->SetRightMargin(.02);
  c->SetLeftMargin(.15);
  c->Divide(3, 2, 0, 0);
  

  Double_t corrs[5];
  c->cd(1); corrs[0] = DrawRingOccupancy(dc, 1, 'I');
  c->cd(2); corrs[1] = DrawRingOccupancy(dc, 2, 'I');
  c->cd(5); corrs[2] = DrawRingOccupancy(dc, 2, 'O');
  c->cd(3); corrs[3] = DrawRingOccupancy(dc, 3, 'I');
  c->cd(6); corrs[4] = DrawRingOccupancy(dc, 3, 'O');

  TVirtualPad* p = c->cd(4);
  p->SetTopMargin(0.05);
  p->SetRightMargin(0.10);
  p->SetLeftMargin(0.15);
  p->SetBottomMargin(0.15);
  p->SetFillColor(0);

  TH1D* hc = new TH1D("occ", "Mean occupancy", 5, .5, 5.5);
  hc->SetFillColor(kRed+1);
  hc->SetFillStyle(3001);
  hc->SetMinimum(0.0);
  hc->GetXaxis()->SetBinLabel(1,"FMD1i"); hc->SetBinContent(1,corrs[0]);
  hc->GetXaxis()->SetBinLabel(2,"FMD2i"); hc->SetBinContent(2,corrs[1]);
  hc->GetXaxis()->SetBinLabel(3,"FMD2o"); hc->SetBinContent(3,corrs[2]);
  hc->GetXaxis()->SetBinLabel(4,"FMD3i"); hc->SetBinContent(4,corrs[3]);
  hc->GetXaxis()->SetBinLabel(5,"FMD3o"); hc->SetBinContent(5,corrs[4]);
  hc->GetXaxis()->SetLabelSize(0.08);
  hc->GetYaxis()->SetTitle("#bar{occupancy}");
  hc->SetMarkerSize(1.5);
  hc->Draw("text hist");
  hc->SetMaximum(hc->GetMaximum()*1.5);

  // TH2D* highCuts = static_cast<TH2D*>(dc->FindObject("highCuts"));
  // if (highCuts) highCuts->Draw("colz");
  c->cd();
  c->SaveAs("occupancy.png");
}
TF1* fit(TString variable, TString variableplot, TTree* nt, TTree* ntMC, Double_t ptmin, Double_t ptmax, int isMC)
{
  static int count=0;
  count++;

  TCanvas* c= new TCanvas(Form("c%d",count),"",600,600);
  TH1D* h = new TH1D(Form("h-%d",count),"",nbinsmasshisto,minhisto,maxhisto);
  TH1D* hMCSignal = new TH1D(Form("hMCSignal-%d",count),"",nbinsmasshisto,minhisto,maxhisto);
  TH1D* hMCSwapped = new TH1D(Form("hMCSwapped-%d",count),"",nbinsmasshisto,minhisto,maxhisto);
  
  TF1* f = new TF1(Form("f%d",count),"[0]*([7]*([9]*Gaus(x,[1],[2])/(sqrt(2*3.14159)*[2])+(1-[9])*Gaus(x,[1],[10])/(sqrt(2*3.14159)*[10]))+(1-[7])*Gaus(x,[1],[8])/(sqrt(2*3.14159)*[8]))+[3]+[4]*x+[5]*x*x+[6]*x*x*x", 1.7, 2.0);
  TString mycut=Form("(%s&&(%s)>%f&&(%s)<%f)",seldata.Data(),variable.Data(),ptmin,variable.Data(),ptmax);
  if(isMC==1) nt->Project(Form("h-%d",count),"Dmass",TCut(weight)*TCut(mycut));   
  else nt->Project(Form("h-%d",count),"Dmass",Form("(%s&&(%s)>%f&&(%s)<%f)",seldata.Data(),variable.Data(),ptmin,variable.Data(),ptmax));   
  
  ntMC->Project(Form("hMCSignal-%d",count),"Dmass",Form("%s*(%s&&(%s)>%f&&(%s)<%f&&(Dgen==23333))",weight.Data(),selmc.Data(),variable.Data(),ptmin,variable.Data(),ptmax));   
  ntMC->Project(Form("hMCSwapped-%d",count),"Dmass",Form("%s*(%s&&(%s)>%f&&(%s)<%f&&(Dgen==23344))",weight.Data(),selmc.Data(),variable.Data(),ptmin,variable.Data(),ptmax));   
  
  
  TFile *fout=new TFile(Form("FitsFiles/Fits_%s_%d.root",collisionsystem.Data(),count),"recreate");
  fout->cd();
  hMCSignal->Write();
  hMCSwapped->Write();
  h->Write();  
  fout->Close();
  
  
  f->SetParLimits(4,-1000,1000);
  f->SetParLimits(10,0.001,0.05);
  f->SetParLimits(2,0.01,0.1);
  f->SetParLimits(8,0.02,0.2);
  f->SetParLimits(7,0,1);
  f->SetParLimits(9,0,1);
  
  f->SetParameter(0,setparam0);
  f->SetParameter(1,setparam1);
  f->SetParameter(2,setparam2);
  f->SetParameter(10,setparam10);
  f->SetParameter(9,setparam9);

  f->FixParameter(8,setparam8);
  f->FixParameter(7,1);
  f->FixParameter(1,fixparam1);
  f->FixParameter(3,0);
  f->FixParameter(4,0);
  f->FixParameter(5,0);
  f->FixParameter(6,0);
  h->GetEntries();
  
  hMCSignal->Fit(Form("f%d",count),"q","",minhisto,maxhisto);
  hMCSignal->Fit(Form("f%d",count),"q","",minhisto,maxhisto);
  f->ReleaseParameter(1);
  hMCSignal->Fit(Form("f%d",count),"L q","",minhisto,maxhisto);
  hMCSignal->Fit(Form("f%d",count),"L q","",minhisto,maxhisto);
  hMCSignal->Fit(Form("f%d",count),"L m","",minhisto,maxhisto);
  
  f->FixParameter(1,f->GetParameter(1));
  f->FixParameter(2,f->GetParameter(2));
  f->FixParameter(10,f->GetParameter(10));
  f->FixParameter(9,f->GetParameter(9));
  f->FixParameter(7,0);
  f->ReleaseParameter(8);
  f->SetParameter(8,setparam8);
  
  hMCSwapped->Fit(Form("f%d",count),"L q","",minhisto,maxhisto);
  hMCSwapped->Fit(Form("f%d",count),"L q","",minhisto,maxhisto);
  hMCSwapped->Fit(Form("f%d",count),"L q","",minhisto,maxhisto);
  hMCSwapped->Fit(Form("f%d",count),"L m","",minhisto,maxhisto);
  
  f->FixParameter(7,hMCSignal->Integral(0,1000)/(hMCSwapped->Integral(0,1000)+hMCSignal->Integral(0,1000)));
  f->FixParameter(8,f->GetParameter(8));
  f->ReleaseParameter(3);
  f->ReleaseParameter(4);
  f->ReleaseParameter(5);
  f->ReleaseParameter(6);

  f->SetLineColor(kRed);
  
  h->Fit(Form("f%d",count),"q","",minhisto,maxhisto);
  h->Fit(Form("f%d",count),"q","",minhisto,maxhisto);
  f->ReleaseParameter(1);
  //f->ReleaseParameter(2);                                     // you need to release these two parameters if you want to perform studies on the sigma shape
  //f->ReleaseParameter(10);                                   // you need to release these two parameters if you want to perform studies on the sigma shape
  h->Fit(Form("f%d",count),"L q","",minhisto,maxhisto);
  h->Fit(Form("f%d",count),"L q","",minhisto,maxhisto);
  h->Fit(Form("f%d",count),"L q","",minhisto,maxhisto);
  h->Fit(Form("f%d",count),"L m","",minhisto,maxhisto);
  
  TF1* background = new TF1(Form("background%d",count),"[0]+[1]*x+[2]*x*x+[3]*x*x*x");
  background->SetParameter(0,f->GetParameter(3));
  background->SetParameter(1,f->GetParameter(4));
  background->SetParameter(2,f->GetParameter(5));
  background->SetParameter(3,f->GetParameter(6));
  background->SetLineColor(4);
  background->SetRange(minhisto,maxhisto);
  background->SetLineStyle(2);
  
  TF1* mass = new TF1(Form("fmass%d",count),"[0]*([3]*([4]*Gaus(x,[1],[2])/(sqrt(2*3.14159)*[2])+(1-[4])*Gaus(x,[1],[5])/(sqrt(2*3.14159)*[5])))");
  mass->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(2),f->GetParameter(7),f->GetParameter(9),f->GetParameter(10));
  mass->SetParError(0,f->GetParError(0));
  mass->SetParError(1,f->GetParError(1));
  mass->SetParError(2,f->GetParError(2));
  mass->SetParError(3,f->GetParError(7));
  mass->SetParError(4,f->GetParError(9));
  mass->SetParError(5,f->GetParError(10));
  mass->SetFillColor(kOrange-3);
  mass->SetFillStyle(3002);
  mass->SetLineColor(kOrange-3);
  mass->SetLineWidth(3);
  mass->SetLineStyle(2);
  
  TF1* massSwap = new TF1(Form("fmassSwap%d",count),"[0]*(1-[2])*Gaus(x,[1],[3])/(sqrt(2*3.14159)*[3])");
  massSwap->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(7),f->GetParameter(8));
  massSwap->SetParError(0,f->GetParError(0));
  massSwap->SetParError(1,f->GetParError(1));
  massSwap->SetParError(2,f->GetParError(7));
  massSwap->SetParError(3,f->GetParError(8));
  massSwap->SetFillColor(kGreen+4);
  massSwap->SetFillStyle(3005);
  massSwap->SetLineColor(kGreen+4);
  massSwap->SetLineWidth(3);
  massSwap->SetLineStyle(1);
  
  h->SetXTitle("m_{#piK} (GeV/c^{2})");
  h->SetYTitle("Entries / (5 MeV/c^{2})");
  h->GetXaxis()->CenterTitle();
  h->GetYaxis()->CenterTitle();
  h->SetAxisRange(0,h->GetMaximum()*1.4*1.2,"Y");
  h->GetXaxis()->SetTitleOffset(1.3);
  h->GetYaxis()->SetTitleOffset(1.8);
  h->GetXaxis()->SetLabelOffset(0.007);
  h->GetYaxis()->SetLabelOffset(0.007);
  h->GetXaxis()->SetTitleSize(0.045);
  h->GetYaxis()->SetTitleSize(0.045);
  h->GetXaxis()->SetTitleFont(42);
  h->GetYaxis()->SetTitleFont(42);
  h->GetXaxis()->SetLabelFont(42);
  h->GetYaxis()->SetLabelFont(42);
  h->GetXaxis()->SetLabelSize(0.04);
  h->GetYaxis()->SetLabelSize(0.04);
  h->SetMarkerSize(0.8);
  h->SetMarkerStyle(20);
  h->SetStats(0);
  h->Draw("e");

  background->Draw("same");   
  mass->SetRange(minhisto,maxhisto);	
  mass->Draw("same");
  massSwap->SetRange(minhisto,maxhisto);
  massSwap->Draw("same");
  f->Draw("same");
  
  Double_t yield = mass->Integral(minhisto,maxhisto)/binwidthmass;
  Double_t yieldErr = mass->Integral(minhisto,maxhisto)/binwidthmass*mass->GetParError(0)/mass->GetParameter(0);
  
  std::cout<<"YIELD="<<yield<<"and error"<<yieldErr<<std::endl;
  std::cout<<"relative error="<<yieldErr/yield<<std::endl;

  TLegend* leg = new TLegend(0.65,0.58,0.82,0.88,NULL,"brNDC");
  leg->SetBorderSize(0);
  leg->SetTextSize(0.04);
  leg->SetTextFont(42);
  leg->SetFillStyle(0);
  leg->AddEntry(h,"Data","pl");
  leg->AddEntry(f,"Fit","l");
  leg->AddEntry(mass,"D^{0}+#bar{D^{#lower[0.2]{0}}} Signal","f");
  leg->AddEntry(massSwap,"K-#pi swapped","f");
  leg->AddEntry(background,"Combinatorial","l");
  leg->Draw("same");

  TLatex Tl;
  Tl.SetNDC();
  Tl.SetTextAlign(12);
  Tl.SetTextSize(0.04);
  Tl.SetTextFont(42);
  Tl.DrawLatex(0.18,0.93, "#scale[1.25]{CMS} Preliminary");
  Tl.DrawLatex(0.65,0.93, Form("%s #sqrt{s_{NN}} = 5.02 TeV",collisionsystem.Data()));

  TLatex* tex;

  tex = new TLatex(0.22,0.78,Form("%.1f < %s  < %.1f",ptmin,variableplot.Data(),ptmax));
  tex->SetNDC();
  tex->SetTextFont(42);
  tex->SetTextSize(0.04);
  tex->SetLineWidth(2);
  tex->Draw();

  tex = new TLatex(0.22,0.83,"|y| < 1.0");
  tex->SetNDC();
  tex->SetTextFont(42);
  tex->SetTextSize(0.04);
  tex->SetLineWidth(2);
  tex->Draw();

  h->GetFunction(Form("f%d",count))->Delete();
  TH1F* histo_copy_nofitfun = ( TH1F * ) h->Clone("histo_copy_nofitfun");
  histo_copy_nofitfun->Draw("esame");
//
  if(nBins==1) c->SaveAs(Form("DMass-inclusive%s_%d.pdf",collisionsystem.Data(),count));
  else c->SaveAs(Form("DMass%s_%d.pdf",collisionsystem.Data(),count));
  
  return mass;
}
//______________________________________________________________________________
TH1D *GetITSTPCMatchingHisto(TString inFileNameData,
                             Int_t particleType,
                             Int_t species,
                             Bool_t isMatched,
                             Float_t lowLim,
                             Float_t upLim,
                             Int_t variable,
                             TString listname){
    
    //
    // ITS-TPC matching histograms as a funct. of pT, eta, phi, for each species
    //
    //axis 0 isMatched: -0.5 0.5, 1.5 (central value 0, 1)
    //axis 1 pT 0 - 20  0.1 --> 20 (50 bins)
    //axis 2 eta -1, 1 20 bins
    //axis 3 phi 0, 6.28 18 0, 2*TMath::Pi()
    //axis 4 pid 0 electrons, 1 pions,2 kaons 3 protont   4 all  -0.5, 5.5 6 bins
    //axis 5 : -1 all, 0 secondaries, 1 primaries, 3 bins -0.5, 2.5
    //axis 6 : 0: select on TOFBC, 1: no TOFbc
    //axis 7 : DCAxy
    //axis 8 : DCAz
    
    TFile * inFileData = TFile::Open(inFileNameData);
    TList * l = (TList * ) inFileData->Get(listname);
    
    //trackingUncert
    THnF * histITSTPC = (THnF *) l->FindObject("histTpcItsMatch");
    
    //TPC-ITS or TPC only
    if(isMatched) histITSTPC->GetAxis(0)->SetRangeUser(1,1);
    else histITSTPC->GetAxis(0)->SetRangeUser(0,0);
    
    double binw;
    //ptbins
    binw    = histITSTPC->GetAxis(1)->GetBinWidth(1)/2.;
    if(variable == kPt) {
        lowLim += binw;
        upLim  -= binw;
        histITSTPC->GetAxis(1)->SetRangeUser(lowLim,upLim);
    }
    else histITSTPC->GetAxis(1)->SetRangeUser(Ptarray[0]+binw,Ptarray[nptbins-1]-binw);
    
    //etabins
    binw    = histITSTPC->GetAxis(2)->GetBinWidth(1)/2.;
    if(variable == kEta) {
        lowLim += binw;
        upLim  -= binw;
        histITSTPC->GetAxis(2)->SetRangeUser(lowLim,upLim);
    }
    else histITSTPC->GetAxis(2)->SetRangeUser(minEta+binw,maxEta-binw);
    
    //phibins
    binw    = histITSTPC->GetAxis(3)->GetBinWidth(1)/2.;
    if(variable == kPhi) {
        lowLim += binw;
        upLim  -= binw;
        histITSTPC->GetAxis(3)->SetRangeUser(lowLim,upLim);
    }
    else histITSTPC->GetAxis(3)->SetRangeUser(minPhi+binw,maxPhi-binw);

    // select particleType
    double xmin,xmax;
    if(particleType==kElectron) {xmin=-0.5; xmax=0.5;}
    else if(particleType==kPion)     {xmin=0.5;  xmax=1.5;}
    else if(particleType==kKaon)     {xmin=1.5;  xmax=2.5;}
    else if(particleType==kProton)   {xmin=2.5;  xmax=3.5;}
    else if(particleType==kAll)      {xmin=3.5;  xmax=4.5;}
    else if(particleType==kPionKaon) {xmin=0.5;  xmax=2.5;}
    else {Printf("particleType not yet impelemented! Please provide it first!"); return 0x0;}
    binw    = histITSTPC->GetAxis(4)->GetBinWidth(1)/2.;
    histITSTPC->GetAxis(4)->SetRangeUser(xmin+binw,xmax-binw);
    
    //specie: primary, secondary, all
    binw    = histITSTPC->GetAxis(5)->GetBinWidth(1)/2.;
    if(species!=2)histITSTPC->GetAxis(5)->SetRangeUser(species-0.5+binw,species+0.5-binw);
    else histITSTPC->GetAxis(5)->SetRangeUser(-0.5+binw,1.5-binw);

    //TOF bc
    binw    = histITSTPC->GetAxis(6)->GetBinWidth(1)/2.;
    if(fIsSelectTOFBC)histITSTPC->GetAxis(6)->SetRangeUser(-0.5+binw,0.5-binw);

    //DCAxy
    binw    = histITSTPC->GetAxis(7)->GetBinWidth(1)/2.;
    histITSTPC->GetAxis(7)->SetRangeUser(-DCAxy+binw,DCAxy-binw);

    //DCAz
    binw    = histITSTPC->GetAxis(8)->GetBinWidth(1)/2.;
    histITSTPC->GetAxis(8)->SetRangeUser(-DCAz+binw,DCAz-binw);

    
    int projectionAxis=1;
    if(variable==kPt) projectionAxis = 1;
    else if(variable==kEta) projectionAxis = 2;
    else if(variable==kPhi) projectionAxis = 3;
    
    TH1D * hProj  = histITSTPC->Projection(projectionAxis);
    hProj->SetDirectory(0);
    hProj->SetNameTitle(Form("h%d",projectionAxis),Form("h%d",projectionAxis));

    
    delete l;
    inFileData->Close();
    return hProj;
}
void metDistribution(const Int_t signalRegion_flag = 1) {

  // if signalRegion_flag == 1 (default), will do met distribution in the monojet signal region, else it will do the control region

  gROOT->SetStyle("Plain");  // to have white legend (on my pc it's already white, but in tier2 it appears grey)
  gStyle->SetFillColor(10);

  string plotDirectoryPath = "/cmshome/ciprianim/CMSSW721/pdfsFromAnalysis/plots/monojet/met_distribution/";
  //string plotDirectoryPath = "./";
  string plotFileExtension = ".pdf";
  string suffix = "_mumu";

  TH1D* hmet = NULL;
  vector<TH1D*> hMCmetNoLep;

  vector<string> sampleName;
  vector<string> MC_TexLabel;
  setSampleName(signalRegion_flag, sampleName, MC_TexLabel);

  Int_t nFiles = (Int_t)sampleName.size();

  vector<Int_t> histColor;
   setHistColor(histColor, nFiles);

   string filenameBase;
   string canvasName;
   if (signalRegion_flag == 1) {
     filenameBase = "monojet_SR_spring15_25ns_";
     canvasName = "metDistribution_monojetSR";
   } else {
     filenameBase = "zmumujets_CS_spring15_25ns_";
     canvasName = "metDistribution_zjetsCS" + suffix;
   }
 
  string filenameExtension = ".root";

  vector<string> MCfileName;
  for (Int_t i = 0; i < nFiles; i++){
    MCfileName.push_back(filenameBase + sampleName[i] + filenameExtension);
  }

  for(Int_t i = 0; i < nFiles; i++) {

    cout<<"fileName : "<<MCfileName[i]<<endl;

    TFile* f = TFile::Open(MCfileName[i].c_str(),"READ");
    if (!f || !f->IsOpen()) {
      cout<<"*******************************"<<endl;
      cout<<"Error opening file \""<<MCfileName[i]<<"\".\nApplication will be terminated."<<endl;
      cout<<"*******************************"<<endl;
      exit(EXIT_FAILURE);
    }

    //cout << "check 1 " << endl;    

    hmet = (TH1D*)f->Get("HYieldsMetBin");
    if (!hmet) {
      cout << "Error: histogram not found in file ' " << MCfileName[i] << "'. End of programme." << endl;
      exit(EXIT_FAILURE);
    }
    hMCmetNoLep.push_back( (TH1D*)hmet->Clone() );

  } 

  THStack* hstack_metNoLep = new THStack("hstack_metNoLep","");

  for (Int_t j = 0; j < nFiles; j++) {

    for (Int_t i = 1; i <= hMCmetNoLep[j]->GetNbinsX(); i++) {

      hMCmetNoLep[j]->SetBinError(i,sqrt(hMCmetNoLep[j]->GetBinContent(i)));

    }

    hMCmetNoLep[j]->SetFillColor(histColor[j]);
    hstack_metNoLep->Add(hMCmetNoLep[j]);

  }

  // now here we go with the canvas
  // TH1D * ratioplot = NULL; // will use it for the ratio plots

  // TPad *subpad_1 = NULL;  // will use it to access specific subpad in canvas
  // TPad *subpad_2 = NULL; 
  TCanvas *c = new TCanvas(canvasName.c_str(),"met distribution");
  c->SetLogy();

  TLegend *leg = new TLegend(0.6,0.55,0.89,0.89);
  
  // subpad_1 = new TPad("pad_1","",0.0,0.28,1.0,1.0);
  // //subpad_1->SetBottomMargin(0);
  // subpad_2 = new TPad("pad_2","",0.0,0.0,1.0,0.32);
  // subpad_2->SetGridy();
  // //subpad_2->SetTopMargin(0);
  // subpad_2->SetBottomMargin(0.3);
  // subpad_1->Draw();
  // subpad_2->Draw();

  //subpad_1->cd();
  hstack_metNoLep->Draw("HIST");
  //hstack_metNoLep->SetMinimum(0.3);
  //hstack_metNoLep->SetMaximum(4000.0);
  TH1D* stackCopy = (TH1D*)(((TH1D*)hstack_metNoLep->GetStack()->Last())->DrawCopy("E2 SAME"));
  stackCopy->SetFillColor(kBlack);
  stackCopy->SetFillStyle(3017);
  hstack_metNoLep->GetXaxis()->SetTitle("#slash{E}_{T} [GeV]");
  hstack_metNoLep->GetXaxis()->SetTitleSize(0.06);
  hstack_metNoLep->GetXaxis()->SetTitleOffset(0.6);
  hstack_metNoLep->GetYaxis()->SetTitle("events");
  hstack_metNoLep->GetYaxis()->SetTitleSize(0.06);
  hstack_metNoLep->GetYaxis()->SetTitleOffset(0.8);
  hstack_metNoLep->GetYaxis()->CenterTitle();
  for (Int_t j = (nFiles-1); j >= 0; j--) {
    leg->AddEntry(hMCmetNoLep[j],Form("%s",MC_TexLabel[j].c_str()),"lf");
  }
  gStyle->SetStatStyle(0);
  leg->Draw(); 
  leg->SetMargin(0.3); 
  leg->SetBorderSize(0);

  // subpad_2->cd();
  // ratioplot = new TH1D(*hratio);
  // ratioplot->Divide(hBRratioOverAxe);
  // ratioplot->SetStats(0);
  // ratioplot->GetXaxis()->SetLabelSize(0.10);
  // ratioplot->GetXaxis()->SetTitle("#slash{E}_{T} [GeV]");
  // ratioplot->GetXaxis()->SetTitleSize(0.15);
  // ratioplot->GetXaxis()->SetTitleOffset(0.8);
  // ratioplot->GetYaxis()->SetLabelSize(0.10);
  // ratioplot->GetYaxis()->SetTitle("ratio");
  // ratioplot->GetYaxis()->SetTitleSize(0.15);
  // ratioplot->GetYaxis()->SetTitleOffset(0.3);
  // ratioplot->GetYaxis()->CenterTitle();
  // ratioplot->GetYaxis()->SetRangeUser(0.5,1.5);
  // ratioplot->GetYaxis()->SetNdivisions(011);
  // ratioplot->DrawCopy("HE");
  // ratioplot->SetMarkerStyle(8);  //medium dot
  c->SaveAs( (plotDirectoryPath + c->GetName() + plotFileExtension).c_str() );

}
Exemple #26
0
int main(int argc, char* argv[])
{
  TApplication theApp(srcName.Data(), &argc, argv);
//=============================================================================

  if (argc<5) return -1;
  TString sPath = argv[1]; if (sPath.IsNull()) return -1;
  TString sFile = argv[2]; if (sFile.IsNull()) return -1;
  TString sJetR = argv[3]; if (sJetR.IsNull()) return -1;
  TString sSjeR = argv[4]; if (sSjeR.IsNull()) return -1;
//=============================================================================

  sPath.ReplaceAll("#", "/");
//=============================================================================

  double dJetR = -1.;
  if (sJetR=="JetR02") dJetR = 0.2;
  if (sJetR=="JetR03") dJetR = 0.3;
  if (sJetR=="JetR04") dJetR = 0.4;
  if (sJetR=="JetR05") dJetR = 0.5;

  if (dJetR<0.) return -1;
  cout << "Jet R = " << dJetR << endl;
//=============================================================================

  double dSjeR = -1.;
  if (sSjeR=="SjeR01") dSjeR = 0.1;
  if (sSjeR=="SjeR02") dSjeR = 0.2;
  if (sSjeR=="SjeR03") dSjeR = 0.3;
  if (sSjeR=="SjeR04") dSjeR = 0.4;

  if (dSjeR<0.) return -1;
  cout << "Sub-jet R = " << dSjeR << endl;
//=============================================================================

  const double dJetsPtMin  = 0.001;
  const double dCutEtaMax  = 1.6;
  const double dJetEtaMax  = 1.;
  const double dJetAreaRef = TMath::Pi() * dJetR * dJetR;

  fastjet::GhostedAreaSpec areaSpc(dCutEtaMax);
  fastjet::JetDefinition   jetsDef(fastjet::antikt_algorithm, dJetR, fastjet::E_scheme, fastjet::Best);
  fastjet::AreaDefinition  areaDef(fastjet::active_area_explicit_ghosts,areaSpc);

  fastjet::Selector selectJet = fastjet::SelectorAbsEtaMax(dJetEtaMax);
  fastjet::JetDefinition subjDef(fastjet::kt_algorithm, dSjeR, fastjet::E_scheme, fastjet::Best);
//=============================================================================

  std::vector<fastjet::PseudoJet> fjInput;

  const Double_t dCut = TMath::TwoPi() / 3.;
  const double dMass  = TDatabasePDG::Instance()->GetParticle(211)->Mass();
//=============================================================================

  enum { kWgt, kLje, kLjr, kLtk, kLtr, kJet, kAje, kMje, k1sz, k1sA, k1sm, k1sr, k2sz, k2sA, k2sm, k2sr, kDsm, kDsr, kVar };

  TFile *file = TFile::Open(Form("%s.root",sFile.Data()), "NEW");
  TNtuple *nt = new TNtuple("nt", "", "fWgt:fLje:fLjr:fLtk:fLtr:fJet:fAje:fMje:f1sj:f1sA:f1sm:f1sr:f2sj:f2sA:f2sm:f2sr:fDsm:fDsr");
//=============================================================================

  HepMC::IO_GenEvent ascii_in(Form("%s/%s.hepmc",sPath.Data(),sFile.Data()), std::ios::in);
  HepMC::GenEvent *evt = ascii_in.read_next_event();

  while (evt) {
    fjInput.resize(0);

    double dLtk = -1.;
    TLorentzVector vPar, vLtk;
    for (HepMC::GenEvent::particle_const_iterator p=evt->particles_begin(); p!=evt->particles_end(); ++p) if ((*p)->status()==1) {
      double dEta = (*p)->momentum().eta(); if (TMath::Abs(dEta)>dCutEtaMax) continue;

      double dTrk = (*p)->momentum().perp();
      double dPhi = (*p)->momentum().phi();
      vPar.SetPtEtaPhiM(dTrk, dEta, dPhi, dMass);
      fjInput.push_back(fastjet::PseudoJet(vPar.Px(), vPar.Py(), vPar.Pz(), vPar.E()));
      if (dTrk>dLtk) { dLtk = dTrk; vLtk.SetPtEtaPhiM(dTrk, dEta, dPhi, dMass); }
    }
//=============================================================================

    fastjet::ClusterSequenceArea clustSeq(fjInput, jetsDef, areaDef);
    std::vector<fastjet::PseudoJet> includJets = clustSeq.inclusive_jets(dJetsPtMin);
    std::vector<fastjet::PseudoJet> selectJets = selectJet(includJets);
//=============================================================================

    if (selectJets.size()>0) {
      std::vector<fastjet::PseudoJet> sortedJets = fastjet::sorted_by_pt(selectJets);
      TLorentzVector vLje; vLje.SetPtEtaPhiM(sortedJets[0].pt(), sortedJets[0].eta(), sortedJets[0].phi(), sortedJets[0].m());

      TLorentzVector vJet;
      int kJrl = -1; double dJrl = -1.;
      int kTrl = -1; double dTrl = -1.;
      for (int j=0; j<sortedJets.size(); j++) {
        double dJet = sortedJets[j].pt();
        sortedJets[j].set_user_index(-1);
        vJet.SetPtEtaPhiM(dJet, sortedJets[j].eta(), sortedJets[j].phi(), sortedJets[j].m());
        if (TMath::Abs(vJet.DeltaPhi(vLje))>dCut) { sortedJets[j].set_user_index(1); if (dJet>dJrl) { dJrl = dJet; kJrl = j; } }
        if (TMath::Abs(vJet.DeltaPhi(vLtk))>dCut) { sortedJets[j].set_user_index(2); if (dJet>dTrl) { dTrl = dJet; kTrl = j; } }
      }
//=============================================================================

      TLorentzVector v1sj, v2sj, vDsj;
      for (int j=0; j<sortedJets.size(); j++) {
        Float_t dVar[kVar]; for (Int_t i=0; i<kVar; i++) dVar[i] = -1.; dVar[kWgt] = 1.;
        vJet.SetPtEtaPhiM(sortedJets[j].pt(), sortedJets[j].eta(), sortedJets[j].phi(), sortedJets[j].m());
//=============================================================================

        dVar[kLje] = vLje.Pt(); if (sortedJets[j].user_index()==1) { dVar[kLjr] = ((kJrl==j) ? 1.5 : 0.5); }
        dVar[kLtk] = vLtk.Pt(); if (sortedJets[j].user_index()==2) { dVar[kLtr] = ((kTrl==j) ? 1.5 : 0.5); }
//=============================================================================

        dVar[kJet] = sortedJets[j].pt();
        dVar[kAje] = sortedJets[j].area();
        dVar[kMje] = sortedJets[j].m();
//=============================================================================

        fastjet::Filter trimmer(subjDef, fastjet::SelectorPtFractionMin(0.));
        fastjet::PseudoJet trimmdJet = trimmer(sortedJets[j]);
        std::vector<fastjet::PseudoJet> trimmdSj = trimmdJet.pieces();

        double d1sj = -1.; int k1sj = -1;
        double d2sj = -1.; int k2sj = -1;
        for (int i=0; i<trimmdSj.size(); i++) {
          double dIsj = trimmdSj[i].pt(); if (dIsj<0.001) continue;

          if (dIsj>d1sj) {
            d2sj = d1sj; k2sj = k1sj;
            d1sj = dIsj; k1sj = i;
          } else if (dIsj>d2sj) {
            d2sj = dIsj; k2sj = i;
          }
        }
//=============================================================================

        if (d1sj>0.) {
          v1sj.SetPtEtaPhiM(d1sj, trimmdSj[k1sj].eta(), trimmdSj[k1sj].phi(), trimmdSj[k1sj].m());
          dVar[k1sz] = d1sj;
          dVar[k1sA] = trimmdSj[k1sj].area();
          dVar[k1sm] = trimmdSj[k1sj].m();
          dVar[k1sr] = v1sj.DeltaR(vJet);
        }

        if (d2sj>0.) {
          v2sj.SetPtEtaPhiM(d2sj, trimmdSj[k2sj].eta(), trimmdSj[k2sj].phi(), trimmdSj[k2sj].m());
          dVar[k2sz] = d2sj;
          dVar[k2sA] = trimmdSj[k2sj].area();
          dVar[k2sm] = trimmdSj[k2sj].m();
          dVar[k2sr] = v2sj.DeltaR(vJet);
        }

        if ((d1sj>0.) && (d2sj>0.)) {
          vDsj = v1sj + v2sj;
          dVar[kDsm] = vDsj.M();
          dVar[kDsr] = v2sj.DeltaR(v1sj);
        }

        nt->Fill(dVar);
      }
    }
//=============================================================================

    delete evt;
    ascii_in >> evt;
  }
//=============================================================================

  file->cd(); nt->Write(); file->Close();
//=============================================================================

  TString sXsec = sFile; sXsec.ReplaceAll("out", "xsecs");
  file = TFile::Open(Form("%s/xsecs/%s.root",sPath.Data(),sXsec.Data()), "READ");
  TH1D *hPtHat        = (TH1D*)file->Get("hPtHat");        hPtHat->SetDirectory(0);
  TH1D *hWeightSum    = (TH1D*)file->Get("hWeightSum");    hWeightSum->SetDirectory(0);
  TProfile *hSigmaGen = (TProfile*)file->Get("hSigmaGen"); hSigmaGen->SetDirectory(0);
  file->Close();
//=============================================================================

  sFile.ReplaceAll("out", "wgt");
  file = TFile::Open(Form("%s.root",sFile.Data()), "NEW");
  hPtHat->Write();
  hWeightSum->Write();
  hSigmaGen->Write();
  file->Close();
//=============================================================================

  cout << "DONE" << endl;
  return 0;
}
Exemple #27
0
int main(int argc, char* argv[])
{
  TApplication theApp(srcName.Data(), &argc, argv);
//=============================================================================

  if (argc<5) return -1;
  TString sPath = argv[1]; if (sPath.IsNull()) return -1;
  TString sFile = argv[2]; if (sFile.IsNull()) return -1;
  TString sJetR = argv[3]; if (sJetR.IsNull()) return -1;
  TString sSjeR = argv[4]; if (sSjeR.IsNull()) return -1;
//=============================================================================

  sPath.ReplaceAll("#", "/");
//=============================================================================

  double dJetR = -1.;
  if (sJetR=="JetR02") dJetR = 0.2;
  if (sJetR=="JetR03") dJetR = 0.3;
  if (sJetR=="JetR04") dJetR = 0.4;
  if (sJetR=="JetR05") dJetR = 0.5;

  if (dJetR<0.) return -1;
  cout << "Jet R = " << dJetR << endl;
//=============================================================================

  double dSjeR = -1.;
  if (sSjeR=="SjeR01") dSjeR = 0.1;
  if (sSjeR=="SjeR02") dSjeR = 0.2;
  if (sSjeR=="SjeR03") dSjeR = 0.3;
  if (sSjeR=="SjeR04") dSjeR = 0.4;

  if (dSjeR<0.) return -1;
  cout << "Sub-jet R = " << dSjeR << endl;
//=============================================================================

  const double dJetsPtMin  = 0.1;
  const double dJetEtaMax  = 2.;
  const double dCutEtaMax  = 2.6;

  fastjet::GhostedAreaSpec areaSpc(dCutEtaMax);
  fastjet::JetDefinition   jetsDef(fastjet::antikt_algorithm, dJetR, fastjet::BIpt_scheme, fastjet::Best);
  fastjet::AreaDefinition  areaDef(fastjet::active_area_explicit_ghosts,areaSpc);

  fastjet::Selector selectJet = fastjet::SelectorAbsEtaMax(dJetEtaMax);
  fastjet::JetDefinition subjDef(fastjet::kt_algorithm, dSjeR, fastjet::BIpt_scheme, fastjet::Best);
//=============================================================================

  std::vector<fastjet::PseudoJet> fjInput;
//=============================================================================

  TFile *file = TFile::Open(Form("%s.root",sFile.Data()), "NEW");
  TList *list = new TList();

  TH1D *hWeightSum = new TH1D("hWeightSum", "", 1, 0., 1.); list->Add(hWeightSum);

  TH2D *hTrkPtEta = new TH2D("hTrkPtEta", "", 1000, 0., 500., 60, -3., 3.); hTrkPtEta->Sumw2(); list->Add(hTrkPtEta);
  TH2D *hTrkPtPhi = new TH2D("hTrkPtPhi", "", 1000, 0., 500., 20, -1., 1.); hTrkPtPhi->Sumw2(); list->Add(hTrkPtPhi);

  TH2D *hJetPtNsj = new TH2D("hJetPtNsj", "", 1000, 0., 1000., 100, -0.5, 99.5); hJetPtNsj->Sumw2(); list->Add(hJetPtNsj);


  TH2D *hJetPtEta = new TH2D("hJetPtEta", "", 1000, 0., 1000., 60, -3., 3.); hJetPtEta->Sumw2(); list->Add(hJetPtEta);
  TH2D *hJetPtPhi = new TH2D("hJetPtPhi", "", 1000, 0., 1000., 20, -1., 1.); hJetPtPhi->Sumw2(); list->Add(hJetPtPhi);

  TH2D *hLjePtEta = new TH2D("hLjePtEta", "", 1000, 0., 1000., 60, -3., 3.); hLjePtEta->Sumw2(); list->Add(hLjePtEta);
  TH2D *hLjePtPhi = new TH2D("hLjePtPhi", "", 1000, 0., 1000., 20, -1., 1.); hLjePtPhi->Sumw2(); list->Add(hLjePtPhi);

  TH2D *hNjePtEta = new TH2D("hNjePtEta", "", 1000, 0., 1000., 60, -3., 3.); hNjePtEta->Sumw2(); list->Add(hNjePtEta);
  TH2D *hNjePtPhi = new TH2D("hNjePtPhi", "", 1000, 0., 1000., 20, -1., 1.); hNjePtPhi->Sumw2(); list->Add(hNjePtPhi);


  TH2D *hJe2PtEta = new TH2D("hJe2PtEta", "", 1000, 0., 1000., 60, -3., 3.); hJe2PtEta->Sumw2(); list->Add(hJe2PtEta);
  TH2D *hJe2PtPhi = new TH2D("hJe2PtPhi", "", 1000, 0., 1000., 20, -1., 1.); hJe2PtPhi->Sumw2(); list->Add(hJe2PtPhi);

  TH2D *hLj2PtEta = new TH2D("hLj2PtEta", "", 1000, 0., 1000., 60, -3., 3.); hLj2PtEta->Sumw2(); list->Add(hLj2PtEta);
  TH2D *hLj2PtPhi = new TH2D("hLj2PtPhi", "", 1000, 0., 1000., 20, -1., 1.); hLj2PtPhi->Sumw2(); list->Add(hLj2PtPhi);

  TH2D *hNj2PtEta = new TH2D("hNj2PtEta", "", 1000, 0., 1000., 60, -3., 3.); hNj2PtEta->Sumw2(); list->Add(hNj2PtEta);
  TH2D *hNj2PtPhi = new TH2D("hNj2PtPhi", "", 1000, 0., 1000., 20, -1., 1.); hNj2PtPhi->Sumw2(); list->Add(hNj2PtPhi);
//=============================================================================

  HepMC::IO_GenEvent ascii_in(Form("%s/%s.hepmc",sPath.Data(),sFile.Data()), std::ios::in);
  HepMC::GenEvent *evt = ascii_in.read_next_event();

  while (evt) {
    fjInput.resize(0);
    double dWeight = evt->weights().back();
    double dXsect  = evt->cross_section()->cross_section() / 1e9;
    double dNorm   = dWeight * dXsect;
    hWeightSum->Fill(0.5, dWeight);

    TVector3 vTrk;
    for (HepMC::GenEvent::particle_const_iterator p=evt->particles_begin(); p!=evt->particles_end(); ++p) if ((*p)->status()==1) {
      double dTrkPt  = (*p)->momentum().perp(); if (dTrkPt<0.5) continue;
      double dTrkEta = (*p)->momentum().eta();  if (TMath::Abs(dTrkEta)>dCutEtaMax) continue;
      double dTrkPhi = (*p)->momentum().phi();  vTrk.SetPtEtaPhi(dTrkPt, dTrkEta, dTrkPhi);
      double dTrkCos = TMath::Cos(dTrkPhi); if (dTrkCos==1.) dTrkCos = 1. - 1e-6;

      fjInput.push_back(fastjet::PseudoJet(vTrk.Px(), vTrk.Py(), vTrk.Pz(), vTrk.Mag()));

      hTrkPtEta->Fill(dTrkPt, dTrkEta, dNorm);
      hTrkPtPhi->Fill(dTrkPt, dTrkCos, dNorm);
    }
//=============================================================================

    fastjet::ClusterSequenceArea clustSeq(fjInput, jetsDef, areaDef);
    std::vector<fastjet::PseudoJet> includJets = clustSeq.inclusive_jets(dJetsPtMin);
    std::vector<fastjet::PseudoJet> selectJets = selectJet(includJets);
    std::vector<fastjet::PseudoJet> sortedJets = fastjet::sorted_by_pt(selectJets);
//=============================================================================

    for (int j=0; j<sortedJets.size(); j++) {
      double dJetPt  = sortedJets[j].pt();
      double dJetEta = sortedJets[j].eta();
      double dJetPhi = sortedJets[j].phi();
      double dJetCos = TMath::Cos(dJetPhi);
      if (dJetCos==1.) dJetCos = 1. - 1e-6;

      fastjet::Filter trimmer(subjDef, fastjet::SelectorPtFractionMin(0.));
      fastjet::PseudoJet trimmdJet = trimmer(sortedJets[j]);
      std::vector<fastjet::PseudoJet> trimmdSj = trimmdJet.pieces();

      int nSje = 0;
      for (int i=0; i<trimmdSj.size(); i++) if (trimmdSj[i].pt()>0.1) { nSje += 1; }
      hJetPtNsj->Fill(dJetPt, nSje, dNorm);

      hJetPtEta->Fill(dJetPt, dJetEta, dNorm); hJetPtPhi->Fill(dJetPt, dJetCos, dNorm);
      if (j==0) { hLjePtEta->Fill(dJetPt, dJetEta, dNorm); hLjePtPhi->Fill(dJetPt, dJetCos, dNorm); }
      if (j==1) { hNjePtEta->Fill(dJetPt, dJetEta, dNorm); hNjePtPhi->Fill(dJetPt, dJetCos, dNorm); }

      if (nSje>=2) {
        hJe2PtEta->Fill(dJetPt, dJetEta, dNorm); hJe2PtPhi->Fill(dJetPt, dJetCos, dNorm);
        if (j==0) { hLj2PtEta->Fill(dJetPt, dJetEta, dNorm); hLj2PtPhi->Fill(dJetPt, dJetCos, dNorm); }
        if (j==1) { hNj2PtEta->Fill(dJetPt, dJetEta, dNorm); hNj2PtPhi->Fill(dJetPt, dJetCos, dNorm); }
      }
    }
//=============================================================================

    delete evt;
    ascii_in >> evt;
  }
//=============================================================================

  file->cd(); list->Write(); file->Close();
//=============================================================================

  cout << "DONE" << endl;
//=============================================================================

  return 0;
}
int fillCSHistos(string vetoedInputFileName, string nonVetoInputFileName, bool useVetoPaddle, string macropulseFileName, string gammaCorrectionFileName, ofstream& logFile, string outputFileName)
{
    ifstream f(outputFileName);

    if(f.good())
    {
        cout << outputFileName << " already exists; skipping gated histogramming of events." << endl;
        logFile << outputFileName << " already exists; skipping gated histogramming of events." << endl;
        return 2;
    }

    logFile << endl << "*** Filling CS histos ***" << endl;

    TFile* vetoedInputFile;
    if(useVetoPaddle)
    {
        // open vetoed input tree
        vetoedInputFile = new TFile(vetoedInputFileName.c_str(),"READ");
        if(!vetoedInputFile->IsOpen())
        {
            cerr << "Error: failed to open " << vetoedInputFileName << "  to fill histos." << endl;
            return 1;
        }
    }

    // open non-vetoed input tree
    TFile* nonVetoInputFile = new TFile(nonVetoInputFileName.c_str(),"READ");
    if(!nonVetoInputFile->IsOpen())
    {
        cerr << "Error: failed to open " << nonVetoInputFileName << "  to fill histos." << endl;
        return 1;
    }

    // open macropulse tree
    TFile* macropulseFile = new TFile(macropulseFileName.c_str(),"READ");
    if(!macropulseFile->IsOpen())
    {
        cerr << "Error: failed to open " << macropulseFileName << "  to fill histos." << endl;
        vetoedInputFile->Close();
        return 1;
    }

    TTree* macropulseTree = (TTree*)(macropulseFile->Get("macropulses"));
    if(!macropulseTree)
    {
        cerr << "Error: failed to open macropulses tree to gate histos." << endl;
        vetoedInputFile->Close();
        macropulseFile->Close();
        return 1;
    }

    MacropulseEvent me;

    macropulseTree->SetBranchAddress("cycleNumber",&me.cycleNumber);
    macropulseTree->SetBranchAddress("macroNo",&me.macroNo);
    macropulseTree->SetBranchAddress("macroTime",&me.macroTime);
    macropulseTree->SetBranchAddress("targetPos",&me.targetPos);
    macropulseTree->SetBranchAddress("numberOfEventsInMacro",&me.numberOfEventsInMacro);
    macropulseTree->SetBranchAddress("numberOfMonitorsInMacro",&me.numberOfMonitorsInMacro);
    macropulseTree->SetBranchAddress("isGoodMacro",&me.isGoodMacro);

    vector<MacropulseEvent> macropulseList;

    int numberOfEntries = macropulseTree->GetEntries();

    if(numberOfEntries==0)
    {
        cerr << "Error: no macropulses found in macropulseTree during fillCSHistos." << endl;

        if(vetoedInputFile)
        {
            vetoedInputFile->Close();
        }

        nonVetoInputFile->Close();
        macropulseFile->Close();
        return 1;
    }

    for(int i=0; i<numberOfEntries; i++)
    {
        macropulseTree->GetEntry(i);

        macropulseList.push_back(me);
    }

    // open gamma correction file
    TFile* gammaCorrectionFile = new TFile(gammaCorrectionFileName.c_str(),"READ");
    if(!gammaCorrectionFile->IsOpen())
    {
        cerr << "Error: failed to open " << gammaCorrectionFileName << "  to read gamma correction." << endl;

        if(vetoedInputFile)
        {
            vetoedInputFile->Close();
        }

        nonVetoInputFile->Close();
        macropulseFile->Close();
        return 1;
    }

    TDirectory* gammaDirectory = (TDirectory*)gammaCorrectionFile->Get(config.analysis.GAMMA_CORRECTION_TREE_NAME.c_str());
    if(!gammaDirectory)
    {
        cerr << "Error: failed to open summedDet directory in " << gammaCorrectionFileName << " for reading gamma corrections." << endl;

        if(vetoedInputFile)
        {
            vetoedInputFile->Close();
        }

        nonVetoInputFile->Close();
        macropulseFile->Close();
        gammaCorrectionFile->Close();
        return 1;
    }

    gammaDirectory->cd();

    TH1D* gammaCorrectionHisto = (TH1D*)gammaDirectory->Get("gammaCorrection");
    if(!gammaCorrectionHisto)
    {
        cerr << "Error: failed to open gammaCorrections histo in " << gammaCorrectionFileName << " for reading gamma corrections." << endl;

        if(vetoedInputFile)
        {
            vetoedInputFile->Close();
        }

        nonVetoInputFile->Close();
        macropulseFile->Close();
        gammaCorrectionFile->Close();

        return 1;
    }

    vector<double> gammaCorrectionList;

    int gammaCorrectionBins = gammaCorrectionHisto->GetNbinsX();
    for(int i=1; i<=gammaCorrectionBins; i++)
    {
        gammaCorrectionList.push_back(gammaCorrectionHisto->GetBinContent(i));
    }

    // define gamma times
    const double GAMMA_TIME = pow(10,7)*config.facility.FLIGHT_DISTANCE/C;
    const double GAMMA_WINDOW_WIDTH = config.time.GAMMA_WINDOW_SIZE/2;

    // create outputFile
    TFile* outputFile = new TFile(outputFileName.c_str(),"UPDATE");

    for(auto& channel : config.digitizer.CHANNEL_MAP)
    {
        if(channel.second == "-" || channel.second == "macroTime"
                || channel.second == "targetChanger")
        {
            continue;
        }

        bool isDetector = false;

        TTree* tree;

        for(auto& detName : config.cs.DETECTOR_NAMES)
        {
            if(channel.second == detName)
            {
                isDetector = true;
                break;
            }
        }

        cout << "Filling gated histograms for tree \"" << channel.second << "\"..." << endl;

        if(isDetector && useVetoPaddle)
        {
            tree = (TTree*)vetoedInputFile->Get(channel.second.c_str());
        }

        else
        {
            tree = (TTree*)nonVetoInputFile->Get(channel.second.c_str());
        }

        if(!tree)
        {
            cerr << "Error: tried to populate advanced histos, but failed to find " << channel.second << " in " << vetoedInputFileName << endl;
            vetoedInputFile->Close();
            macropulseFile->Close();
            gammaCorrectionFile->Close();

            return 1;
        }

        // connect input tree to event data buffer
        DetectorEvent event;
        vector<int>* waveformPointer = 0;

        tree->SetBranchAddress("cycleNumber",&event.cycleNumber);
        tree->SetBranchAddress("macroNo",&event.macroNo);
        tree->SetBranchAddress("macroTime",&event.macroTime);
        tree->SetBranchAddress("fineTime",&event.fineTime);
        tree->SetBranchAddress("eventNo",&event.eventNo);
        tree->SetBranchAddress("completeTime",&event.completeTime);
        tree->SetBranchAddress("targetPos",&event.targetPos);
        tree->SetBranchAddress("sgQ",&event.sgQ);
        tree->SetBranchAddress("lgQ",&event.lgQ);
        tree->SetBranchAddress("waveform",&waveformPointer);

        if(isDetector)
        {
            tree->SetBranchAddress("vetoed",&event.vetoed);
        }

        TDirectory* directory = outputFile->mkdir(channel.second.c_str(),channel.second.c_str());
        directory->cd();

        vector<TH1D*> goodMacroHistos;
        for(string targetName : config.target.TARGET_ORDER)
        {
            string macroNumberName = targetName + "GoodMacros";
            goodMacroHistos.push_back(new TH1D(macroNumberName.c_str(),
                        macroNumberName.c_str(), 500000, 0, 500000));
        }

        // create other diagnostic histograms used to examine run data
        TH1D* timeDiffHisto = new TH1D("time since last event","time since last event",
                config.plot.TOF_RANGE,0,config.plot.TOF_RANGE);
        TH2D* timeDiffVEnergy1 = new TH2D("time difference vs. energy of first",
                "time difference vs. energy of first",config.plot.TOF_RANGE,
                0,config.plot.TOF_RANGE,10*config.plot.NUMBER_ENERGY_BINS,2,700);

        TH2D* time1Vtime2 = new TH2D("time of first vs. time of second",
                "time of first vs. time of second",config.plot.TOF_RANGE,0,
                config.plot.TOF_RANGE,config.plot.TOF_RANGE,0,
                config.plot.TOF_RANGE);

        TH2D* energy1VEnergy2 = new TH2D("energy of first vs. energy of second",
                "energy of first vs. energy of second",
                10*config.plot.NUMBER_ENERGY_BINS, floor(config.plot.ENERGY_LOWER_BOUND), ceil(config.plot.ENERGY_UPPER_BOUND),
                10*config.plot.NUMBER_ENERGY_BINS, floor(config.plot.ENERGY_LOWER_BOUND), ceil(config.plot.ENERGY_UPPER_BOUND));

        TH1D* microNoH = new TH1D("microNoH","microNo",config.facility.MICROS_PER_MACRO+1
                ,0,config.facility.MICROS_PER_MACRO+1);

        vector<TH1D*> TOFHistos;
        vector<TH2D*> triangleHistos;
        vector<TH1D*> vetoTOFHistos;
        vector<TH2D*> vetoTriangleHistos;

        for(string targetName : config.target.TARGET_ORDER)
        {
            string TOFName = targetName + "TOF";
            TOFHistos.push_back(new TH1D(TOFName.c_str(),
                        TOFName.c_str(),
                        config.plot.TOF_BINS,
                        config.plot.TOF_LOWER_BOUND,
                        config.plot.TOF_UPPER_BOUND));

            string triangleName = targetName + "Triangle";
            triangleHistos.push_back(new TH2D(triangleName.c_str(),
                        triangleName.c_str(),
                        config.plot.TOF_RANGE,
                        config.plot.TOF_LOWER_BOUND,
                        config.plot.TOF_UPPER_BOUND,
                        pow(2,9),0,pow(2,15)));

            string vetoTOFName = "veto" + TOFName;
            vetoTOFHistos.push_back(new TH1D(vetoTOFName.c_str(),
                        vetoTOFName.c_str(),
                        config.plot.TOF_BINS,
                        config.plot.TOF_LOWER_BOUND,
                        config.plot.TOF_UPPER_BOUND));

            string vetoTriangleName = "veto" + triangleName;
            vetoTriangleHistos.push_back(new TH2D(vetoTriangleName.c_str(),
                        vetoTriangleName.c_str(),
                        config.plot.TOF_RANGE,
                        config.plot.TOF_LOWER_BOUND,
                        config.plot.TOF_UPPER_BOUND,
                        pow(2,9),0,pow(2,15)));
        }

        double prevCompleteTime = 0;
        double prevlgQ = 0;

        double microTime;
        double prevMicroTime = 0;
        int microNo;

        double timeDiff;
        double eventTimeDiff = 0;
        double velocity;
        double rKE;
        double prevRKE = 0;

        double prevAverageTime = 0;

        const double MACRO_LENGTH = config.facility.MICROS_PER_MACRO*config.facility.MICRO_LENGTH;

        long badMacroEvent = 0;
        long badChargeGateEvent = 0;
        long badChargeRatioEvent = 0;
        long outsideMacro = 0;

        int totalEntries = tree->GetEntries();

        int currentMacropulse = 0;
        bool endGatedHistoFill = false;

        int startOfCycleMacro = 0;
        int prevCycleNumber = 0;

        int facilityCounter = 0;

        vector<int> targetPositionPreviousMacro(7,-1);
        vector<int> targetPositionMacroCounter(7,0);

        // fill advanced histos
        for(long i=0; i<totalEntries; i++)
        {
            tree->GetEntry(i);

            if(event.cycleNumber > prevCycleNumber)
            {
                startOfCycleMacro = event.macroNo;
                prevCycleNumber = event.cycleNumber;
            }

            if(event.macroNo > macropulseList[currentMacropulse].macroNo)
            {
                currentMacropulse++;
                if(currentMacropulse>(macropulseList.size()-1))
                {
                    cout << "Reached end of gatedMacropulseList; ending fillCSHistos." << endl;
                    break;
                }

                facilityCounter++;

                if(macropulseList[currentMacropulse].macroTime - 8.4*pow(10,6) > macropulseList[currentMacropulse-1].macroTime)
                {
                    facilityCounter = 0;
                }

                continue;
            }

            // throw away events during "bad" macropulses
            if(!(macropulseList[currentMacropulse].isGoodMacro))
            {
                badMacroEvent++;
                continue;
            }

            if((int)event.macroNo > targetPositionPreviousMacro[event.targetPos])
            {
                targetPositionPreviousMacro[event.targetPos] = event.macroNo;
                targetPositionMacroCounter[event.targetPos]++;
            }

            // charge gates:
            if(isDetector)
            {
                if(event.lgQ<config.analysis.CHARGE_GATE_LOW_THRESHOLD
                        || event.lgQ>config.analysis.CHARGE_GATE_HIGH_THRESHOLD)
                {
                    badChargeGateEvent++;
                    continue;
                }

                /*if(event.sgQ/(double)event.lgQ < config.analysis.Q_RATIO_LOW_THRESHOLD
                        || event.sgQ/(double)event.lgQ > config.analysis.Q_RATIO_HIGH_THRESHOLD)
                {
                    badChargeRatioEvent++;
                    continue;
                }*/
            }

            /*****************************************************************/
            // Calculate event properties

            // find which micropulse the event is in and the time since the start of
            // the micropulse (the TOF)
            timeDiff = event.completeTime-event.macroTime;

            // correct times using average gamma time
            timeDiff -= gammaCorrectionList[event.macroNo];

            // timing gate
            if(timeDiff > MACRO_LENGTH)
            {
                outsideMacro++;
                continue;
            }

            eventTimeDiff = event.completeTime-prevCompleteTime;
            microNo = floor(timeDiff/config.facility.MICRO_LENGTH);
            microTime = fmod(timeDiff,config.facility.MICRO_LENGTH);

            // micropulse gate:
            if(microNo < config.facility.FIRST_GOOD_MICRO
                    || microNo >= config.facility.LAST_GOOD_MICRO)
            {
                continue;
            }

            // veto gate: apply to neutron events only
            if(event.vetoed && microTime > GAMMA_TIME+GAMMA_WINDOW_WIDTH*2)
            {
                vetoTOFHistos[event.targetPos]->Fill(microTime);
                vetoTriangleHistos[event.targetPos]->Fill(microTime, event.lgQ);

                continue;
            }

            // convert micropulse time into neutron velocity based on flight path distance
            velocity = (pow(10.,7.)*config.facility.FLIGHT_DISTANCE)/microTime; // in meters/sec 

            // convert velocity to relativistic kinetic energy
            rKE = (pow((1.-pow((velocity/C),2.)),-0.5)-1.)*NEUTRON_MASS; // in MeV

            TOFHistos[event.targetPos]->Fill(microTime);
            triangleHistos[event.targetPos]->Fill(microTime, event.lgQ);

            // fill detector histograms with event data
            timeDiffHisto->Fill(eventTimeDiff);
            timeDiffVEnergy1->Fill(eventTimeDiff,prevRKE);
            time1Vtime2->Fill(prevMicroTime,microTime);
            energy1VEnergy2->Fill(prevRKE,rKE);
            microNoH->Fill(microNo);

            prevlgQ = event.lgQ;
            prevMicroTime = microTime;
            prevCompleteTime = event.completeTime;
            prevRKE = rKE;

            goodMacroHistos[event.targetPos]->Fill(event.macroNo+1);

            if(i%10000==0)
            {
                cout << "Processed " << i << " " << channel.second << " events into advanced CS histos...\r";
            }
        }

        cout << endl << "Finished populating \"" << channel.second << "\" events into CS histos." << endl;
        cout << "Total events processed = " << totalEntries << endl;

        logFile << endl << "Fraction events filtered out by good macro gate: "
            << 100*(double)badMacroEvent/totalEntries << "%." << endl;

        logFile << "Fraction events filtered out by charge gate (" << config.analysis.CHARGE_GATE_LOW_THRESHOLD
            << " < lgQ < " << config.analysis.CHARGE_GATE_HIGH_THRESHOLD << "): "
            << 100*(double)badChargeGateEvent/totalEntries << "%." << endl;

        logFile << "Fraction events filtered out by charge ratio gate (" << config.analysis.Q_RATIO_LOW_THRESHOLD
            << " < lgQ < " << config.analysis.Q_RATIO_HIGH_THRESHOLD << "): "
            << 100*(double)badChargeRatioEvent/totalEntries << "%." << endl;

        logFile << "Fraction events outside macropulse: "
            << 100*(double)outsideMacro/totalEntries << "%." << endl;

        for(auto& histo : TOFHistos)
        {
            histo->Write();
        }

        for(auto& histo : triangleHistos)
        {
            histo->Write();
        }

        for(auto& histo : vetoTOFHistos)
        {
            histo->Write();
        }

        for(auto& histo : vetoTriangleHistos)
        {
            histo->Write();
        }

        timeDiffHisto->Write();
        timeDiffVEnergy1->Write();
        time1Vtime2->Write();
        energy1VEnergy2->Write();
        microNoH->Write();

        for(auto& histo : goodMacroHistos)
        {
            histo->Write();
        }
    }

    macropulseFile->Close();

    if(useVetoPaddle)
    {
        vetoedInputFile->Close();
    }

    nonVetoInputFile->Close();

    outputFile->Close();

    logFile << endl << "*** Finished filling CS histos ***" << endl;

    return 0;
}
Exemple #29
0
// *************************************** //
// this is a function that takes a set of  //
// histograms and draws them on a canvas   //
// in a stack, returning the canvas.       //
// It also plots the signal as a dashed    //
// line and the data with a ratio at the   //
// the bottom of data/allBackgrounds       //
//                                         //
// This one is supposed to match the plots //
// make by JP                              //
// *************************************** //
TCanvas* drawPlots::plotAll_VLQ(std::vector<TH1D*> histos, std::vector<std::string> names, std::string axisName, std::vector<TH1D*> signal, TH1D* data, TGraphAsymmErrors* err, bool isSignalRegion, bool doLogAxis, std::string channel){

   const unsigned int CANVAS_WIDTH  = 720;
   const unsigned int CANVAS_HEIGHT = 750;
   const double RATIOPLOT_YAXIS_TITLE_OFFSET = 0.75;
   const double RATIOPLOT_YAXIS_TITLE_SIZE   = 0.11;
   const double RATIOPLOT_YAXIS_LABEL_SIZE   = 0.09;  
   const double RATIOPLOT_XAXIS_TITLE_OFFSET = 1.6;
   const double RATIOPLOT_XAXIS_TITLE_SIZE   = 0.11;
   const double RATIOPLOT_XAXIS_LABEL_SIZE   = 0.09;
   
   TCanvas* canvas = new TCanvas("canvas","canvas",0,0,CANVAS_WIDTH,CANVAS_HEIGHT);
   
   canvas->SetMargin(0.,0.,0.,0.);
   canvas->Clear();
   canvas->cd();
   
   SetAtlasStyle();
   gStyle->SetHistLineWidth(1.);
   
   // create histogram to store all backgrounds
   TH1D* allBackgrounds;
   bool gotSomething=false;
   for(int c=0; c<signal.size(); c++){
     if(signal[c]){
       allBackgrounds = (TH1D*)signal[c]->Clone("all_backgrounds");
       gotSomething=true;
     }
   }
   if(!gotSomething && data)
     allBackgrounds = (TH1D*)data->Clone("all_backgrounds");
   if(!gotSomething){
     for(int b=0; b<histos.size(); b++){
       if(histos[b] && !gotSomething){
	 allBackgrounds = (TH1D*)histos[b]->Clone("all_backgrounds");
	 gotSomething=true;
       }
     }
   }

   if(!gotSomething){
     std::cout << "Error: could not find any background, data, or signal for this plot" << std::endl;
     return canvas;
   }
   
   // set all bins to zero
   for(int i=0; i<=allBackgrounds->GetNbinsX()+1; i++)
     allBackgrounds->SetBinContent(i,0);
   
   // make stack of backgrounds, fill backgrounds histogram
   THStack* Stack = new THStack();
   for(int b=0; b<histos.size(); b++){
     if(histos[b]){
       if(histos[b]->GetEntries() > 0.){
	 histos[b]->SetLineColor(1);
	 histos[b]->SetFillColor(tools::setColor(names[b]));
	 Stack->Add(histos[b]);
	 for(int j=0; j<=allBackgrounds->GetNbinsX()+1; j++){
	   double binContent=allBackgrounds->GetBinContent(j)+histos[b]->GetBinContent(j);
	   allBackgrounds->SetBinContent(j,binContent);
	 }
       }
     }
   } 
   TH1D* backgroundsForRatio = (TH1D*)allBackgrounds->Clone("bkgds_for_ratio");

   // create main pad
   const double mainPad_ylow  = 0.3;
   const double mainPad_yhigh = 0.95;
   const double mainPad_xlow = 0.;
   const double mainPad_xhigh = 0.95;
   const double pad_margin_left = 0.2;
   const double pad_margin_right  = 0.02;
   double main_y_max = -99;
   double main_y_min = -99;

   TPad* mainPad = new TPad("main","main",mainPad_xlow,mainPad_ylow,mainPad_xhigh,mainPad_yhigh);
   mainPad->SetMargin(pad_margin_left,pad_margin_right,0.,.05); // left, right, bottom, top
   mainPad->Draw();
   mainPad->cd();

   // find max y
   if(allBackgrounds){
     int maxBinBkg = allBackgrounds->GetMaximumBin();
     double bkgYmax = allBackgrounds->GetBinContent(maxBinBkg);
     main_y_max = bkgYmax;
   }
   if(data){
     int maxBinData = data->GetMaximumBin();
     double dataYmax = data->GetBinContent(maxBinData);
     if(dataYmax > main_y_max) main_y_max = dataYmax;
   }
   if(main_y_max < .002) main_y_max = .1;

   if(doLogAxis){
     mainPad->SetLogy();
     main_y_min = 0.007;
     main_y_max*=600;
   }else{
     main_y_min = 0.001;
     main_y_max*=1.6;
   }

   // draw axis
   allBackgrounds->SetMaximum(main_y_max);
   allBackgrounds->SetMinimum(main_y_min);
   std::string title = std::string(";") + axisName + ";events/bin";
   allBackgrounds->SetTitle(title.c_str());   
   allBackgrounds->GetYaxis()->SetTitleOffset(1.4);
   allBackgrounds->GetYaxis()->SetTitleSize(0.06);
   allBackgrounds->GetXaxis()->SetTitleOffset(1.2);
   allBackgrounds->GetYaxis()->SetLabelSize(0.04);
   allBackgrounds->GetXaxis()->SetLabelSize(0.04);
   allBackgrounds->Draw("hist");

   // draw stack with error
   Stack->Draw("hist same");
   if(err){
     err->Draw("E2 same");
   }

   // make error histograms for the ratio plot
   TGraphAsymmErrors* ratioErr = tools::getRatio(err, backgroundsForRatio);

   // draw data
   if(!isSignalRegion && data)
      data->Draw("e same");

   // draw signal
   if(signal[0]){
     signal[0]->SetLineStyle(2);
     signal[0]->SetLineColor(kRed);
     signal[0]->SetLineWidth(5);
     signal[0]->Draw("hist same");
   }
   if(signal.size() > 1){
     if(signal[1]){
       signal[1]->SetLineStyle(2);
       signal[1]->SetLineColor(kOrange+7);
       signal[1]->SetLineWidth(4);
       signal[1]->Draw("hist same");
     }
     if(signal.size() > 2){
       if(signal[2]){
	 signal[2]->SetLineStyle(2);
	 signal[2]->SetLineColor(kPink-6);
	 signal[2]->SetLineWidth(4);
	 signal[2]->Draw("hist same");
       }
     }
   }
   allBackgrounds->Draw("axis same");

   // draw legend
   float leg_height = 0.45;
   float leg_width = 0.2;
   float leg_xoffset = 0.74;
   float leg_yoffset = 0.7;
   
   TLegend* leg = new TLegend(leg_xoffset,leg_yoffset-leg_height/2,leg_xoffset+leg_width,leg_yoffset+leg_height/2);
   leg->SetFillColor(0);
   leg->SetFillStyle(0);
   leg->SetBorderSize(0);
   leg->SetTextFont(52);
   leg->SetTextSize(0.033);
   
   // currently assuming first signal is Tbq (single T production), second is TTS, third is BBS
   if(signal[0])
     leg->AddEntry(signal[0], "Tbq (650 GeV)", "l");
   if(signal.size()>1){
     if(signal[1])
       leg->AddEntry(signal[1], "TT_{S} (650 GeV)", "l");
     if(signal[2])
       leg->AddEntry(signal[2], "BB_{S} (650 GeV)", "l");
   }
   if(!isSignalRegion)
     leg->AddEntry(data, "data 2012");
   for(int q=0; q<histos.size(); q++){
     if(histos[q]){
       if(histos[q]->GetEntries() > 0.)
	 leg->AddEntry(histos[q], plotLists::GetLegendName(names[q]).c_str(), "f");
     }
   }
   leg->Draw("lpe");
   
   ATLAS_LABEL(0.24,0.86,1);
   myText(0.36, 0.86, 1, .05, "Internal");
   char text[]="#sqrt{s}=8 TeV";
   myText(0.55,0.77,1,.04, text);
   char text_L[]="#int L dt = 20.3 fb^{-1}";
   myText(0.5, 0.84,1, .04, text_L);
   if(channel!=""){
     char chan_txt[channel.size()-1];
     strcpy(chan_txt, (channel.substr(1)).c_str());
     myText(0.5, 0.7, 1, .06, chan_txt);
   }
   char inText[100];
   int t;
   if(signal[0])
     t=sprintf(inText, "N_{Tbq} = %.1f", signal[0]->Integral(0,signal[0]->GetNbinsX()+1));
   else
     t=sprintf(inText, "N_{Tbq} = %.1f", 0.);
   myText(0.24, 0.7, 1, .04, inText);
   if(signal.size()>1){
     if(signal[1])
       t=sprintf(inText, "N_{TTS} = %.1f", signal[1]->Integral(0,signal[1]->GetNbinsX()+1));
     else
       t=sprintf(inText, "N_{TTS} = %.1f", 0.);
     myText(0.24, 0.65, 1, .04, inText);
     if(signal.size()>2){
       if(signal[2])
	 t=sprintf(inText, "N_{BBS} = %.1f", signal[2]->Integral(0,signal[2]->GetNbinsX()+1));
       else
	 t=sprintf(inText, "N_{BBS} = %.1f", 0.);
       myText(0.24, 0.6, 1, .04, inText);
     }
   }

   double back_int = allBackgrounds->Integral(0,allBackgrounds->GetNbinsX()+1);
   if(back_int > 10000.)
     t=sprintf(inText, "N_{B} = %.3e", back_int);
   else
     t=sprintf(inText, "N_{B} = %.1f", back_int);
   myText(0.24, 0.75, 1, .04, inText);
   if(!isSignalRegion){
     if(data)
       t=sprintf(inText, "N_{D} = %.0f", data->Integral(0,data->GetNbinsX()+1));
     else
       t=sprintf(inText, "N_{D} = %.0f", 0.);
     myText(0.24, 0.8, 1, .04, inText);
   }
   
   canvas->cd();
   
   // Draw Ratio plot
   double ratio_max = 1.6;
   double ratio_min = 0.4;
  
   double pad_xlow = 0.;
   double pad_xhigh = 0.95;
   double pad_ylow = 0.0;
   double pad_yhigh = 0.3;
   
   const char* pad_name = "pad";
   TPad* pad4ratio = new TPad(pad_name,pad_name,pad_xlow,pad_ylow,pad_xhigh,pad_yhigh);

   pad4ratio->SetMargin(pad_margin_left,pad_margin_right,0.46,0.);
   pad4ratio->Draw();
   pad4ratio->cd();

   TH1D* ratioPlot;
   if(data)
     ratioPlot = (TH1D*)data->Clone("ratio");
   else if (signal[0]) 
     ratioPlot = (TH1D*)signal[0]->Clone("ratio"); // just for getting the axis

   ratioPlot->SetTitle("");
   ratioPlot->Divide(allBackgrounds);
   ratioPlot->GetYaxis()->SetTitle("Data/MC");
   ratioPlot->GetXaxis()->SetTitle(axisName.c_str());

   if (data){
     // here change ratio_min and ratio_max if the ratio plot is quite flat
     double maxDeviation=0;
     double tempDev=0;
     for(int ibin=1; ibin<=allBackgrounds->GetNbinsX(); ibin++){
       tempDev = std::abs(ratioPlot->GetBinContent(ibin)-1.);
       if(tempDev > maxDeviation) maxDeviation = tempDev;
     }
     if(maxDeviation < 0.1){
       ratio_max = 1.12;
       ratio_min = 0.88;
     }
     else if(maxDeviation < 0.2){
       ratio_max = 1.25;
       ratio_min = .75;
     }
     ratioPlot->SetMinimum(ratio_min);
     ratioPlot->SetMaximum(ratio_max);
   }     

   if(ratioPlot->GetXaxis()->GetNdivisions() > ratioPlot->GetNbinsX())
     ratioPlot->GetXaxis()->SetNdivisions(ratioPlot->GetNbinsX());
   if(ratioPlot->GetXaxis()->GetNdivisions() > 11)
     ratioPlot->GetXaxis()->SetNdivisions(11);
   ratioPlot->GetXaxis()->SetLabelSize(RATIOPLOT_XAXIS_LABEL_SIZE);
   ratioPlot->GetYaxis()->SetLabelSize(RATIOPLOT_YAXIS_LABEL_SIZE);
   ratioPlot->GetYaxis()->SetNdivisions(3);
   ratioPlot->GetYaxis()->SetTitleSize(RATIOPLOT_YAXIS_TITLE_SIZE);
   ratioPlot->GetYaxis()->SetTitleOffset(RATIOPLOT_YAXIS_TITLE_OFFSET);
   ratioPlot->GetXaxis()->SetTitleSize(RATIOPLOT_XAXIS_TITLE_SIZE);
   ratioPlot->GetXaxis()->SetTitleOffset(RATIOPLOT_XAXIS_TITLE_OFFSET);
   
   if(!isSignalRegion && data){
     ratioPlot->Draw();
     // plot horizontal line at y=1
     TF1* horizontal = new TF1("horizontal","pol1",-10000,10000);
     horizontal->SetParameter(0,1.);
     horizontal->SetParameter(1,0.);
     horizontal->SetLineColor(kBlack);
     horizontal->SetLineStyle(2);
     horizontal->SetLineWidth(1);
     horizontal->Draw("same");
     ratioErr->Draw("E2 same");
   }else if(isSignalRegion){
     ratioPlot->Draw("axis");
     char text[]="DATA IS BLIND HERE";
     myText(0.4,0.6,1,.15,text);
   }else{ // in this case it is not the signal region but there is no data
     ratioPlot->Draw("axis");
     char text[]="NO DATA";
     myText(0.4,0.6,1,.15,text);
   }
   
   return canvas;
}
Exemple #30
0
void make( string charge = "p", bool lines = false, int iCen = 0, string cs = "Pi", string hFile = "histograms.root" ){

	Bichsel bgen;
	gStyle->SetPadLeftMargin(0.16);
	gStyle->SetPadBottomMargin(0.12);
	gStyle->SetPadRightMargin(0.12);

	set_plot_style();

	RooPlotLib rpl;
	string rpName = "rp_" + charge + "_dedx_beta_lines.pdf";
	if ( false == lines )
		rpName = "rp_" + charge + "_dedx_beta.pdf";

	string chargeName = "Positive Tracks : ";
	if ( "n" == charge )
		chargeName = "Negative Tracks : ";

	Reporter rp( rpName, 600, 800 );

	TFile * f = new TFile( hFile.c_str(), "READ" );

	TH1D * nlBeta = (TH1D*)f->Get( "nlBeta" );


	for ( int iPt = 0; iPt < 100; iPt ++ ){
		if ( iPt != 16 ) continue;


		TAxis * x = nlBeta->GetXaxis();
		double lpT = x->GetBinLowEdge( iPt + 1 );
		double hpT = x->GetBinLowEdge( iPt + 1 ) + x->GetBinWidth( iPt + 1 );
		double avgP = (lpT + hpT) / 2.0;

		string name = "dedx_tof/dedx_tof_" + cs + "_" + charge + "_" + ts(iCen) + "_" + ts( iPt);
		TH2D * h2 = (TH2D*)f->Get( name.c_str() );

		if ( !h2 )
			break;
		if ( iPt == 5 ) // what went wrong?
			continue;


		double x1 = h2->GetXaxis()->GetBinLowEdge( 1 );
		double x2 = h2->GetXaxis()->GetBinLowEdge( h2->GetNbinsX() ) + h2->GetXaxis()->GetBinWidth( h2->GetNbinsX() );
		double y1 = h2->GetYaxis()->GetBinLowEdge( 1 );
		double y2 = h2->GetYaxis()->GetBinLowEdge( h2->GetNbinsY() ) + h2->GetYaxis()->GetBinWidth( h2->GetNbinsY() );

		  

		rpl.style( h2 ).set( "draw", "col" )
			.set( "optstat", 0 ).set( "logz", 1 )
			.set( "title", " ; ln(dE/dx) - ln(dE/dx)_{#pi}  ; #beta^{-1} - #beta^{-1}_{#pi} " )
			.set( "ts", 0.16 )
			.set( "xts", 0.06 )
			.set( "xto", 0.75 )
			.set( "yts", 0.07 )
			.set( "yto", 0.85 )
			.set( "yoffset", 0.01 ).draw(); 



		if ( 16 == iPt ){
			gStyle->SetTitleFontSize( 0.45 );
			rpl.style(h2)
				.set( "xr", -0.3, 0.95 )
				.set( "yr", -0.15, 0.6 ).draw();
		}
		TLatex *text = new TLatex( -0.5, 0.64, (chargeName + dts(lpT) + " < p_{T} [GeV/c] < " + dts(hpT)).c_str() );
		text->SetTextSize(0.055);
		text->Draw("");


		if ( lines  ){
			double bKaon = one_beta( mK, avgP ) - one_beta( mPi, avgP );
			double bProton = one_beta( mP, avgP ) - one_beta( mPi, avgP );

			double dKaon = bgen.meanLog( avgP, mK, -1, 1000 ) - bgen.meanLog( avgP, mPi, -1, 1000 );
			double dProton = bgen.meanLog( avgP, mP, -1, 1000 ) - bgen.meanLog( avgP, mPi, -1, 1000 );

			drawTofLines( 0, kRed+1, x1, x2 );		
			drawTpcLines( 0, kRed + 1, y1, y2);
			// around Kaons
			drawTofLines( bKaon, kOrange+1, x1, x2 );	
			drawTpcLines( dKaon, kOrange + 1, y1, y2);
			// around Protons
			drawTofLines( bProton, kBlack, x1, x2 );	
			drawTpcLines( dProton, kBlack, y1, y2);
		}

		// double dElec = bgen.meanLog( avgP, mE, -1, 1000 ) - bgen.meanLog( avgP, mPi, -1, 1000 );
		// double bElec = one_beta( mE, avgP ) - one_beta( mPi, avgP );
		// //drawTpcLines( dMerged, kBlack, y1, y2);
		// TEllipse * ell = new TEllipse( dElec,bElec, sigTpc * 3, sigTof * 3 );
		// ell->SetFillColorAlpha( kBlack, 0 );
		// ell->Draw();
		// 
		
		gPad->SetRightMargin( 0.01 );
		gPad->SetBottomMargin( 0.10 );
		gPad->SetLeftMargin( 0.14 );

		rp.savePage();
		rp.saveImage( ("img/dedx_tof_" + ts(iPt) + ".pdf").c_str() );
		rp.saveImage( ("img/dedx_tof_" + ts(iPt) + ".png").c_str() );
	}

}