Esempio n. 1
0
void plotPdf_7D_VWW(double mH=125) {
    
    gROOT->ProcessLine(".L tdrstyle.C");
    setTDRStyle();
    TGaxis::SetMaxDigits(3);
    gROOT->ForceStyle();
    

    // Declaration of the PDFs to use
    gROOT->ProcessLine(".L PDFs/RooSpinOne_7D.cxx++");
    
    // W/Z mass and decay width constants
    double mV = 80.399;
    double gamV = 2.085;
    bool offshell = false;
    if ( mH < 2 * mV ) offshell = true;

    // for the pole mass and decay width of W 
    RooRealVar* mX = new RooRealVar("mX","mX", mH);
    RooRealVar* mW = new RooRealVar("mW","mW", mV);
    RooRealVar* gamW = new RooRealVar("gamW","gamW",gamV);

    //
    // Observables (7D)
    // 
    RooRealVar* wplusmass = new RooRealVar("wplusmass","m(W+)",mV,1e-09,120);
    wplusmass->setBins(50);
    RooRealVar* wminusmass = new RooRealVar("wminusmass","m(W-)",mV,1e-09,120);
    wminusmass->setBins(50);
    RooRealVar* hs = new RooRealVar("costhetastar","cos#theta*",-1,1);
    hs->setBins(20);
    RooRealVar* Phi1 = new RooRealVar("phistar1","#Phi_{1}",-TMath::Pi(),TMath::Pi());
    Phi1->setBins(20);
    RooRealVar* h1 = new RooRealVar("costheta1","cos#theta_{1}",-1,1);
    h1->setBins(20);
    RooRealVar* h2 = new RooRealVar("costheta2","cos#theta_{2}",-1,1);
    h2->setBins(20);
    RooRealVar* Phi = new RooRealVar("phi","#Phi",-TMath::Pi(),TMath::Pi());
    Phi->setBins(20);
    
    // 1-
    RooRealVar* g1ValV = new RooRealVar("g1ValV","g1ValV",1.);
    RooRealVar* g2ValV = new RooRealVar("g2ValV","g2ValV",0.);
    // Even more parameters, do not have to touch, based on W couplings
    RooRealVar* R1Val = new RooRealVar("R1Val","R1Val",-1.);
    RooRealVar* R2Val = new RooRealVar("R2Val","R2Val",-1.);
    
    // these are the acceptance terms associated with the production angles
    // the default setting is for setting no-acceptance
    RooRealVar* aParam = new RooRealVar("aParam","aParam",0);
    
    RooSpinOne_7D *myPDFV;

    if ( offshell ) 
      myPDFV = new RooSpinOne_7D("myPDF","myPDF", *mX, *wplusmass, *wminusmass, *h1, *h2, *hs, *Phi, *Phi1, 
				 *g1ValV, *g2ValV, *R1Val, *R2Val, *aParam, *mW, *gamW);
    else 
      myPDFV = new RooSpinOne_7D("myPDF","myPDF", *mX, *mW, *mW, *h1, *h2, *hs, *Phi, *Phi1, 
				*g1ValV, *g2ValV, *R1Val, *R2Val, *aParam, *mW, *gamW);
    
    // Grab input file to convert to RooDataSet
    TFile* finV = new TFile(Form("VWW_%.0f_JHU.root", mH));
    TTree* tinV = (TTree*) finV->Get("angles");
    if ( offshell ) 
      RooDataSet dataV("dataV","dataV",tinV,RooArgSet(*wplusmass, *wminusmass, *h1,*h2, *hs, *Phi, *Phi1));
    else 
      RooDataSet dataV("dataV","dataV",tinV,RooArgSet(*h1,*h2, *hs, *Phi, *Phi1));
    
    for (int i=1;i<1;i++) {
      RooArgSet* row = dataV.get(i);
      row->Print("v");
    }
    

    // 
    // 1+
    // 
    RooRealVar* g1ValA = new RooRealVar("g1ValA","g1ValA",0);
    RooRealVar* g2ValA = new RooRealVar("g2ValA","g2ValA",1);
    RooSpinOne_7D *myPDFA;
    
    if ( offshell ) 
      myPDFA = new RooSpinOne_7D("myPDF","myPDF", *mX, *wplusmass, *wminusmass, *h1, *h2, *hs, *Phi, *Phi1,
				 *g1ValA, *g2ValA, *R1Val, *R2Val, *aParam, *mW, *gamW);
    else 
      myPDFA = new RooSpinOne_7D("myPDF","myPDF", *mX, *mW, *mW, *h1, *h2, *hs, *Phi, *Phi1,
				 *g1ValA, *g2ValA, *R1Val, *R2Val, *aParam, *mW, *gamW);

    TFile* finA = new TFile(Form("AVWW_%.0f_JHU.root", mH));
    TTree* tinA = (TTree*) finA->Get("angles");
    if ( offshell ) 
      RooDataSet dataA("dataA","dataA",tinA,RooArgSet(*wplusmass, *wminusmass, *hs, *h1, *h2, *Phi, *Phi1));
     else 
       RooDataSet dataA("dataA","dataA",tinA,RooArgSet(*h1,*h2, *hs, *Phi, *Phi1));
    //
    // P L O T   . . .  
    // 

    bool drawv = true;
    bool drawa = true;
    bool drawpaper = true;

    double rescale = 1.0;
    if (drawpaper ) 
      rescale = 0.001;


    // for 1-
    TH1F* dum0 = new TH1F("dum0","dum0",1,0,1); dum0->SetLineColor(kRed); dum0->SetMarkerColor(kBlack); dum0->SetLineWidth(3);
    // for 1+
    TH1F* dum1 = new TH1F("dum1","dum1",1,0,1); dum1->SetLineColor(kBlue); dum1->SetMarkerColor(kBlack); dum1->SetMarkerStyle(24), dum1->SetLineWidth(3);
    TLegend * box3 = new TLegend(0.1,0.1,0.9,0.92);
    box3->SetFillColor(0);
    box3->SetBorderSize(0);
    if ( drawa ) 
      box3->AddEntry(dum0,"X#rightarrow WW JP = 1+","lp");
    if ( drawv )
    box3->AddEntry(dum1,"X#rightarrow WW JP = 1-","lp");

    // 
    //  h1
    // 
    RooPlot* h1frame =  h1->frame(20);
    h1frame->GetXaxis()->CenterTitle();
    h1frame->GetYaxis()->CenterTitle();
    h1frame->GetYaxis()->SetTitle(" ");

    double ymax_h1;
    TH1F *h1a = new TH1F("h1a", "h1a", 20, -1, 1);
    tinA->Project("h1a", "costheta1");
    ymax_h1 = h1a->GetMaximum();

    TH1F *h1_minus = new TH1F("h1_minus", "h1_minus", 20, -1, 1);
    tinV->Project("h1_minus", "costheta1");
    ymax_h1 = h1_minus->GetMaximum() > ymax_h1 ? h1_minus->GetMaximum() : ymax_h1;
    
    if ( drawa ) {
      dataA.plotOn(h1frame, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
      myPDFA->plotOn(h1frame, LineColor(kRed),LineWidth(2), Normalization(rescale));
    }
    if ( drawv ) {
      //dataV.plotOn(h1frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
      //myPDFV->plotOn(h1frame, LineColor(kBlue),LineWidth(2), Normalization(rescale));
      // tempoary
      dataV.plotOn(h1frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale*.95823), DataError(RooAbsData::None));
      myPDFV->plotOn(h1frame, LineColor(kBlue),LineWidth(2), Normalization(rescale*.95823));
    }
    if ( rescale != 1.)
      h1frame->GetYaxis()->SetRangeUser(0, ymax_h1 / 1000. * 1.3);

    
    // 
    //  h2
    // 
    
    RooPlot* h2frame =  h2->frame(20);
    h2frame->GetXaxis()->CenterTitle();
    h2frame->GetYaxis()->CenterTitle();
    h2frame->GetYaxis()->SetTitle(" ");

    double ymax_h2;
    TH1F *h2a = new TH1F("h2a", "h2a", 20, -1, 1);
    tinA->Project("h2a", "costheta2");
    ymax_h2 = h2a->GetMaximum();

    TH1F *h2_minus = new TH1F("h2_minus", "h2_minus", 20, -1, 1);
    tinV->Project("h2_minus", "costheta2");
    ymax_h2 = h2_minus->GetMaximum() > ymax_h2 ? h2_minus->GetMaximum() : ymax_h2;

    if ( drawa ) {
      dataA.plotOn(h2frame, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
      myPDFA->plotOn(h2frame, LineColor(kRed),LineWidth(2), Normalization(rescale));
    }
    if ( drawv ) {
      // dataV.plotOn(h2frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), yDataError(RooAbsData::None));
      // myPDFV->plotOn(h2frame, LineColor(kBlue),LineWidth(2), Normalization(rescale));
      dataV.plotOn(h2frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale*.95823), DataError(RooAbsData::None));
      myPDFV->plotOn(h2frame, LineColor(kBlue),LineWidth(2), Normalization(rescale*.95823));
    }
    if ( rescale != 1.) 
      h2frame->GetYaxis()->SetRangeUser(0, ymax_h2 / 1000. * 1.3);

    //
    // Phi
    // 
    RooPlot* Phiframe =  Phi->frame(20);
    Phiframe->GetXaxis()->CenterTitle();
    Phiframe->GetYaxis()->CenterTitle();
    Phiframe->GetYaxis()->SetTitle(" ");

    double ymax_Phi;
    TH1F *Phia = new TH1F("Phia", "Phia", 20,  -TMath::Pi(), TMath::Pi());
    tinA->Project("Phia", "phi");
    ymax_Phi = Phia->GetMaximum();

    TH1F *Phi_minus = new TH1F("Phi_minus", "Phi_minus", 20,  -TMath::Pi(), TMath::Pi());
    tinV->Project("Phi_minus", "phi");
    ymax_Phi = Phi_minus->GetMaximum() > ymax_Phi ? Phi_minus->GetMaximum() : ymax_Phi;
    
    if ( drawa ) {
      dataA.plotOn(Phiframe, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
      myPDFA->plotOn(Phiframe, LineColor(kRed),LineWidth(2), Normalization(rescale));
    }
    if ( drawv ) {
      //dataV.plotOn(Phiframe, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
      //myPDFV->plotOn(Phiframe, LineColor(kBlue),LineWidth(2), Normalization(rescale));
      dataV.plotOn(Phiframe, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale*.95823), DataError(RooAbsData::None));
      myPDFV->plotOn(Phiframe, LineColor(kBlue),LineWidth(2), Normalization(rescale*.95823));
    }
    if ( rescale != 1. ) 
      Phiframe->GetYaxis()->SetRangeUser(0, ymax_Phi / 1000. * 1.3);
    
    // 
    //  hs 
    // 
    RooPlot* hsframe =  hs->frame(20);

    hsframe->GetXaxis()->CenterTitle();
    hsframe->GetYaxis()->CenterTitle();
    hsframe->GetYaxis()->SetTitle(" ");

    double ymax_hs;
    TH1F *hsa = new TH1F("hsa", "hsa", 20, -1, 1);
    tinA->Project("hsa", "costhetastar");
    ymax_hs = hsa->GetMaximum();

    TH1F *hs_minus = new TH1F("hs_minus", "hs_minus", 20, -1, 1);
    tinV->Project("hs_minus", "costhetastar");
    ymax_hs = hs_minus->GetMaximum() > ymax_hs ? hs_minus->GetMaximum() : ymax_hs;
    
    if ( drawa ) {
      dataA.plotOn(hsframe, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
      myPDFA->plotOn(hsframe, LineColor(kRed),LineWidth(2), Normalization(rescale));
    }
    if ( drawv ) {
      //dataV.plotOn(hsframe, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
      //myPDFV->plotOn(hsframe, LineColor(kBlue),LineWidth(2), Normalization(rescale));
      dataV.plotOn(hsframe, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale*.95823), DataError(RooAbsData::None));
      myPDFV->plotOn(hsframe, LineColor(kBlue),LineWidth(2), Normalization(rescale*.95823));
    }
    if ( rescale != 1. ) 
      hsframe->GetYaxis()->SetRangeUser(0, ymax_hs / 1000. * 1.3);

    
    //
    // Phi1
    // 
    RooPlot* Phi1frame =  Phi1->frame(20);
 
    Phi1frame->GetXaxis()->CenterTitle();
    Phi1frame->GetYaxis()->CenterTitle();
    Phi1frame->GetYaxis()->SetTitle(" ");

    double ymax_Phi1;
    TH1F *Phi1a = new TH1F("Phi1a", "Phi1a", 20, -TMath::Pi(), TMath::Pi());
    tinA->Project("Phi1a", "phistar1");
    ymax_Phi1 = Phi1a->GetMaximum();

    TH1F *Phi1_minus = new TH1F("Phi1_minus", "Phi1_minus", 20, -TMath::Pi(), TMath::Pi());
    tinV->Project("Phi1_minus", "phistar1");
    ymax_Phi1 = Phi1_minus->GetMaximum() > ymax_Phi1 ? Phi1_minus->GetMaximum() : ymax_Phi1;
    
    if ( drawa ) {
      dataA.plotOn(Phi1frame, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
      myPDFA->plotOn(Phi1frame, LineColor(kRed),LineWidth(2), Normalization(rescale));
    }
    if ( drawv ) {
      // dataV.plotOn(Phi1frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
      // myPDFV->plotOn(Phi1frame, LineColor(kBlue),LineWidth(2), Normalization(rescale));
      dataV.plotOn(Phi1frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale*.95823), DataError(RooAbsData::None));
      myPDFV->plotOn(Phi1frame, LineColor(kBlue),LineWidth(2), Normalization(rescale*.95823));
    }
    if ( rescale != 1. ) 
      Phi1frame->GetYaxis()->SetRangeUser(0, ymax_Phi1 / 1000. * 1.3);


    if ( offshell ) {
      RooPlot* w1frame =  wplusmass->frame(50);
      w1frame->GetXaxis()->CenterTitle();
      w1frame->GetYaxis()->CenterTitle();
      w1frame->GetYaxis()->SetTitle(" ");
      
      double ymax_w1;
      TH1F *w1a = new TH1F("w1a", "w1a", 50, 1e-09, 120);
      tinA->Project("w1a", "wplusmass");
      ymax_w1 = w1a->GetMaximum();
      
      TH1F *w1_minus = new TH1F("w1_minus", "w1_minus", 50, 1e-09, 120);
      tinV->Project("w1_minus", "wplusmass")
      ymax_w1 = w1_minus->GetMaximum() > ymax_w1 ? w1_minus->GetMaximum() : ymax_w1;
      
      if ( drawa ) {
	dataA.plotOn(w1frame, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDFA->plotOn(w1frame, LineColor(kRed),LineWidth(2), Normalization(rescale));
      }
      if ( drawv ) {
	// dataV.plotOn(w1frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	// myPDFV->plotOn(w1frame, LineColor(kBlue),LineWidth(2), Normalization(rescale));
	dataV.plotOn(w1frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale*.95823), DataError(RooAbsData::None));
	myPDFV->plotOn(w1frame, LineColor(kBlue),LineWidth(2), Normalization(rescale*.95823));
      }
      if ( rescale != 1. )
      w1frame->GetYaxis()->SetRangeUser(0, ymax_w1 / 1000. * 1.5);

      // 
      //  wminus
      // 
      RooPlot* w2frame =  wminusmass->frame(50);

      w2frame->GetXaxis()->CenterTitle();
      w2frame->GetYaxis()->CenterTitle();
      w2frame->GetYaxis()->SetTitle(" ");
      
      double ymax_w2;
      TH1F *w2a = new TH1F("w2a", "w2a", 50, 1e-09, 120);
      tinA->Project("w2a", "wminusmass");
      ymax_w2 = w2a->GetMaximum();
      
      TH1F *w2_minus = new TH1F("w2_minus", "w2_minus", 50, 1e-09, 120);
      tinV->Project("w2_minus", "wminusmass")
      ymax_w2 = w2_minus->GetMaximum() > ymax_w2 ? w2_minus->GetMaximum() : ymax_w2;
      
      if ( drawa ) {
	dataA.plotOn(w2frame, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDFA->plotOn(w2frame, LineColor(kRed),LineWidth(2), Normalization(rescale));
      }
      if ( drawv ) {
	//dataV.plotOn(w2frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	//myPDFV->plotOn(w2frame, LineColor(kBlue),LineWidth(2), Normalization(rescale));
	dataV.plotOn(w2frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale*.95823), DataError(RooAbsData::None));
	myPDFV->plotOn(w2frame, LineColor(kBlue),LineWidth(2), Normalization(rescale*.95823));
      }
      if ( rescale != 1. ) 
	w2frame->GetYaxis()->SetRangeUser(0, ymax_w2 / 1000. * 1.5);
    }
    if ( drawpaper ) {
      TCanvas* can =new TCanvas("can","can",600,600);

      if ( offshell ) {
	w1frame->GetXaxis()->SetTitle("m_{l#nu} [GeV]");
	w1frame->Draw();
	can->Print(Form("paperplots/wplusmass_%.0fGeV_spin1_2in1_ww.eps", mH));
	can->SaveAs(Form("paperplots/wplusmass_%.0fGeV_spin1_2in1_ww.C", mH));
      }
      
      can->Clear();
      hsframe->Draw();
      can->Print(Form("paperplots/costhetastar_%.0fGeV_spin1_2in1_ww.eps", mH));      
      can->SaveAs(Form("paperplots/costhetastar_%.0fGeV_spin1_2in1_ww.C", mH));      
      
      can->Clear();
      Phi1frame->Draw();
      can->Print(Form("paperplots/phistar1_%.0fGeV_spin1_2in1_ww.eps", mH));      
      can->SaveAs(Form("paperplots/phistar1_%.0fGeV_spin1_2in1_ww.C", mH));      

      can->Clear();
      h1frame->GetXaxis()->SetTitle("cos#theta_{1} or cos#theta_{2}");
      h1frame->Draw();
      can->Print(Form("paperplots/costheta1_%.0fGeV_spin1_2in1_ww.eps", mH));
      can->SaveAs(Form("paperplots/costheta1_%.0fGeV_spin1_2in1_ww.C", mH));

      can->Clear();
      Phiframe->Draw();
      can->Print(Form("paperplots/phi_%.0fGeV_spin1_2in1_ww.eps", mH));      
      can->SaveAs(Form("paperplots/phi_%.0fGeV_spin1_2in1_ww.C", mH));      


    }

    else {
      
      TCanvas* cww = new TCanvas( "cww", "cww", 1000, 600 );
      cww->Divide(4,2);
      if ( offshell ) {
	cww->cd(1);
	w1frame->Draw();
	cww->cd(2);
	w2frame->Draw();
      }
      cww->cd(3);
      hsframe->Draw();
      cww->cd(4);
      box3->Draw();
      cww->cd(5);
      Phi1frame->Draw();
      cww->cd(6);
      h1frame->Draw();
      cww->cd(7);
      h2frame->Draw();
      cww->cd(8);
      Phiframe->Draw();
      
      cww->Print(Form("epsfiles/angles_VWW%.0f_JHU_7D.eps", mH));
      cww->Print(Form("pngfiles/angles_VWW%.0f_JHU_7D.png", mH));
      delete cww;
    }

}
int WPtCorrFitDetUnfCalc(const TString BaseName)
{
  TString resultDir = "ResultsFitDetUnf";
  
  gSystem->mkdir(resultDir,kTRUE);

  char tmpName[30];
  
  //double WptLogBins[14] = {1.0,7.5,12.5,17.5,24,30,40,50,70,110,150,190,250,600};
  double WptLogBins[27] = {1.0,3.75,7.5,10,12.5,15,17.5,20.75,24,27,30,35,40,45,50,60,70,90,110,130,150,170,190,220,250,425,600};
  const TString format("png"); 
  
  ofstream Fout;
  Fout.open(resultDir+"/"+BaseName+"_WpMN.txt");

  TFile *fWpMN_MCNom;
  TFile *fWmMN_MCNom;
  TFile *fWpEN_MCNom;
  TFile *fWmEN_MCNom;
  fWpMN_MCNom = new TFile("../Unfolding/Nominal/Muon2012LoPU/WpToMuNu_S8_Unfold.root");
  fWmMN_MCNom = new TFile("../Unfolding/Nominal/Muon2012LoPU/WmToMuNu_S8_Unfold.root");
  fWpEN_MCNom = new TFile("../Unfolding/Nominal/Electron2012LoPU/WpToEleNu_S8_Unfold.root");
  fWmEN_MCNom = new TFile("../Unfolding/Nominal/Electron2012LoPU/WmToEleNu_S8_Unfold.root");

  TFile *fWpMN_RDNom;
  TFile *fWmMN_RDNom;
  TFile *fWpEN_RDNom;
  TFile *fWmEN_RDNom;
  fWpMN_RDNom = new TFile("../Unfolding/WpToMuNuDet/Fit.root");
  fWmMN_RDNom = new TFile("../Unfolding/WmToMuNuDet/Fit.root");
  fWpEN_RDNom = new TFile("../Unfolding/WpToEleNuDet/Fit.root");
  fWmEN_RDNom = new TFile("../Unfolding/WmToEleNuDet/Fit.root");

  TH1D* h1_WpT_WpToMN_MCNom;
  TH1D* h1_WpT_WpToMN_MC_NormToRD;
  TH1D* h1_WpT_WpToMN_RDNom;
  TH1D* h1_WpT_WpToMN_ratio;
  TH1D* h1_WpT_WpToMN_MCNom_Log;

  TH1D* h1_WpT_WmToMN_MCNom;
  TH1D* h1_WpT_WmToMN_MC_NormToRD;
  TH1D* h1_WpT_WmToMN_RDNom;
  TH1D* h1_WpT_WmToMN_ratio;
  TH1D* h1_WpT_WmToMN_MCNom_Log;

  TH1D* h1_WpT_WpToEN_MCNom;
  TH1D* h1_WpT_WpToEN_MC_NormToRD;
  TH1D* h1_WpT_WpToEN_RDNom;
  TH1D* h1_WpT_WpToEN_ratio;
  TH1D* h1_WpT_WpToEN_MCNom_Log;

  TH1D* h1_WpT_WmToEN_MCNom;
  TH1D* h1_WpT_WmToEN_MC_NormToRD;
  TH1D* h1_WpT_WmToEN_RDNom;
  TH1D* h1_WpT_WmToEN_ratio;
  TH1D* h1_WpT_WmToEN_MCNom_Log;
  
  // Plot
  CPlot *pltWpMN, *pltWpMN_ratio;
  CPlot *pltWmMN, *pltWmMN_ratio;
  CPlot *pltWpEN, *pltWpEN_ratio;
  CPlot *pltWmEN, *pltWmEN_ratio;
  TCanvas *myCan;
  myCan = MakeCanvas("myCan","myCan",800,800);
  gStyle->SetEndErrorSize(10);
  gStyle->SetTextFont(132);
  gStyle->SetLegendFont(132);
cout << "check1" << endl;
  //======================
  // Histo from root
  //======================
  h1_WpT_WpToMN_MCNom = (TH1D*)fWpMN_MCNom->Get("h1_Truth_Post")->Clone("h1_WpT_WpToMN_MCNom");
  h1_WpT_WpToMN_MCNom_Log = new TH1D("h1_WpT_WpToMN_MCNom_Log","h1_WpT_WpToMN_MCNom_Log",13,WptLogBins);
  
  h1_WpT_WmToMN_MCNom = (TH1D*)fWmMN_MCNom->Get("h1_Truth_Post")->Clone("h1_WpT_WmToMN_MCNom");
  h1_WpT_WmToMN_MCNom_Log = new TH1D("h1_WpT_WmToMN_MCNom_Log","h1_WpT_WmToMN_MCNom_Log",13,WptLogBins);
  
  h1_WpT_WpToEN_MCNom = (TH1D*)fWpEN_MCNom->Get("h1_Truth_Post")->Clone("h1_WpT_WpToEN_MCNom");
  h1_WpT_WpToEN_MCNom_Log = new TH1D("h1_WpT_WpToEN_MCNom_Log","h1_WpT_WpToEN_MCNom_Log",13,WptLogBins);
  
  h1_WpT_WmToEN_MCNom = (TH1D*)fWmEN_MCNom->Get("h1_Truth_Post")->Clone("h1_WpT_WmToEN_MCNom");
  h1_WpT_WmToEN_MCNom_Log = new TH1D("h1_WpT_WmToEN_MCNom_Log","h1_WpT_WmToEN_MCNom_Log",13,WptLogBins);
  
  //h1_WpT_WpToMN_MCNom = (TH1D*)fWpMN_MCNom->Get("h1_Truth_Post_DoubleBin")->Clone("h1_WpT_WpToMN_MCNom");
  //h1_WpT_WpToMN_MCNom_Log = new TH1D("h1_WpT_WpToMN_MCNom_Log","h1_WpT_WpToMN_MCNom_Log",13,WptLogBins);
 

  //h1_WpT_WmToMN_MCNom = (TH1D*)fWmMN_MCNom->Get("h1_Truth_Post_DoubleBin")->Clone("h1_WpT_WmToMN_MCNom");
  //h1_WpT_WmToMN_MCNom_Log = new TH1D("h1_WpT_WmToMN_MCNom_Log","h1_WpT_WmToMN_MCNom_Log",13,WptLogBins);
  //
  //h1_WpT_WpToEN_MCNom = (TH1D*)fWpEN_MCNom->Get("h1_Truth_Post_DoubleBin")->Clone("h1_WpT_WpToEN_MCNom");
  //h1_WpT_WpToEN_MCNom_Log = new TH1D("h1_WpT_WpToEN_MCNom_Log","h1_WpT_WpToEN_MCNom_Log",13,WptLogBins);
  //
  //h1_WpT_WmToEN_MCNom = (TH1D*)fWmEN_MCNom->Get("h1_Truth_Post_DoubleBin")->Clone("h1_WpT_WmToEN_MCNom");
  //h1_WpT_WmToEN_MCNom_Log = new TH1D("h1_WpT_WmToEN_MCNom_Log","h1_WpT_WmToEN_MCNom_Log",13,WptLogBins);
  
  h1_WpT_WpToMN_MCNom->Sumw2();
  h1_WpT_WmToMN_MCNom->Sumw2();
  h1_WpT_WpToEN_MCNom->Sumw2();
  h1_WpT_WmToEN_MCNom->Sumw2();
 
  h1_WpT_WpToMN_MCNom->Scale(18.429*1*7322.0/935446);
  h1_WpT_WmToMN_MCNom->Scale(18.429*1*5181.0/1.97346e6);
  h1_WpT_WpToEN_MCNom->Scale(18.429*1*7322.0/2401905);
  h1_WpT_WmToEN_MCNom->Scale(18.429*1*5181.0/2127666);
 
  h1_WpT_WpToMN_RDNom = (TH1D*)fWpMN_RDNom->Get("h1_Fit__x")->Clone("h1_WpT_WpToMN_RDNom");
  h1_WpT_WmToMN_RDNom = (TH1D*)fWmMN_RDNom->Get("h1_Fit__x")->Clone("h1_WpT_WmToMN_RDNom");
  h1_WpT_WpToEN_RDNom = (TH1D*)fWpEN_RDNom->Get("h1_Fit__x")->Clone("h1_WpT_WpToEN_RDNom");
  h1_WpT_WmToEN_RDNom = (TH1D*)fWmEN_RDNom->Get("h1_Fit__x")->Clone("h1_WpT_WmToEN_RDNom");
  //h1_WpT_WpToMN_RDNom->Sumw2();
  //h1_WpT_WmToMN_RDNom->Sumw2();
  //h1_WpT_WpToEN_RDNom->Sumw2();
  //h1_WpT_WmToEN_RDNom->Sumw2();

  h1_WpT_WpToMN_RDNom->Scale(h1_WpT_WpToMN_MCNom->Integral()/h1_WpT_WpToMN_RDNom->Integral());
  h1_WpT_WmToMN_RDNom->Scale(h1_WpT_WmToMN_MCNom->Integral()/h1_WpT_WmToMN_RDNom->Integral());
  h1_WpT_WpToEN_RDNom->Scale(h1_WpT_WpToEN_MCNom->Integral()/h1_WpT_WpToEN_RDNom->Integral());
  h1_WpT_WmToEN_RDNom->Scale(h1_WpT_WmToEN_MCNom->Integral()/h1_WpT_WmToEN_RDNom->Integral());

  cout << "===W+ Mu Yield (Truth_Post) (Fit)===" <<endl;
  for(int i(1);i<14;i++){
    cout<<"bin "<<i<<"\t" << h1_WpT_WpToMN_MCNom->GetBinContent(i) << "\t\t"<< h1_WpT_WpToMN_RDNom->GetBinContent(i) << endl;
  }
  
  cout << "===W- Mu Yield (Truth_Post) (Fit)===" <<endl;
  for(int i(1);i<14;i++){
    cout<<"bin "<<i<<"\t" << h1_WpT_WmToMN_MCNom->GetBinContent(i) << "\t\t"<< h1_WpT_WmToMN_RDNom->GetBinContent(i) << endl;
  }
  
  cout << "===W+ Ele Yield (Truth_Post) (Fit)===" <<endl;
  for(int i(1);i<14;i++){
    cout<<"bin "<<i<<"\t" << h1_WpT_WpToEN_MCNom->GetBinContent(i) << "\t\t"<< h1_WpT_WpToEN_RDNom->GetBinContent(i) << endl;
  }
  
  cout << "===W- Ele Yield (Truth_Post) (Fit)===" <<endl;
  for(int i(1);i<14;i++){
    cout<<"bin "<<i<<"\t" << h1_WpT_WmToEN_MCNom->GetBinContent(i) << "\t\t"<< h1_WpT_WmToEN_RDNom->GetBinContent(i) << endl;
  }
  h1_WpT_WpToMN_ratio = (TH1D*)h1_WpT_WpToMN_RDNom->Clone("h1_WpT_WpToMN_ratio");
  h1_WpT_WmToMN_ratio = (TH1D*)h1_WpT_WmToMN_RDNom->Clone("h1_WpT_WmToMN_ratio");
  h1_WpT_WpToEN_ratio = (TH1D*)h1_WpT_WpToEN_RDNom->Clone("h1_WpT_WpToEN_ratio");
  h1_WpT_WmToEN_ratio = (TH1D*)h1_WpT_WmToEN_RDNom->Clone("h1_WpT_WmToEN_ratio");
  //cout<<"number h1_WpT_WpToMN_ratio: "<<h1_WpT_WpToMN_ratio->Integral()<<endl;
  h1_WpT_WpToMN_MC_NormToRD = (TH1D*)h1_WpT_WpToMN_MCNom->Clone("h1_WpT_WpToMN_MC_NormToRD");
  h1_WpT_WmToMN_MC_NormToRD = (TH1D*)h1_WpT_WmToMN_MCNom->Clone("h1_WpT_WmToMN_MC_NormToRD");
  h1_WpT_WpToEN_MC_NormToRD = (TH1D*)h1_WpT_WpToEN_MCNom->Clone("h1_WpT_WpToEN_MC_NormToRD");
  h1_WpT_WmToEN_MC_NormToRD = (TH1D*)h1_WpT_WmToEN_MCNom->Clone("h1_WpT_WmToEN_MC_NormToRD");
  //cout<<"Number h1_WpT_WpToMN_MC: "<<h1_WpT_WpToMN_MC_NormToRD->Integral()<<endl;
  h1_WpT_WpToMN_MC_NormToRD->Scale(h1_WpT_WpToMN_ratio->Integral()/h1_WpT_WpToMN_MC_NormToRD->Integral());
  h1_WpT_WmToMN_MC_NormToRD->Scale(h1_WpT_WmToMN_ratio->Integral()/h1_WpT_WmToMN_MC_NormToRD->Integral());
  h1_WpT_WpToEN_MC_NormToRD->Scale(h1_WpT_WpToEN_ratio->Integral()/h1_WpT_WpToEN_MC_NormToRD->Integral());
  h1_WpT_WmToEN_MC_NormToRD->Scale(h1_WpT_WmToEN_ratio->Integral()/h1_WpT_WmToEN_MC_NormToRD->Integral());
  cout<<"Number h1_WpT_WpToMN_MC_NormToRD: "<<h1_WpT_WpToMN_MC_NormToRD->Integral()<<endl;
  h1_WpT_WpToMN_ratio->Divide(h1_WpT_WpToMN_MC_NormToRD);
  h1_WpT_WmToMN_ratio->Divide(h1_WpT_WmToMN_MC_NormToRD);
  h1_WpT_WpToEN_ratio->Divide(h1_WpT_WpToEN_MC_NormToRD);
  h1_WpT_WmToEN_ratio->Divide(h1_WpT_WmToEN_MC_NormToRD);
  
  for(int i(1);i<=13;i++)
  {
    cout<<"Bin "<<i<<" : " <<"Mu+:  "<< h1_WpT_WpToMN_ratio->GetBinContent(i) <<"\t"<<"Mu-:  "<<h1_WpT_WmToMN_ratio->GetBinContent(i)<< endl;
  } 
  for(int i(1);i<=13;i++)
  {
    cout<<"Bin "<<i<<" : "  <<"Ele+:  "<<h1_WpT_WpToEN_ratio->GetBinContent(i)<<"\t"<<"Ele-:  "<<h1_WpT_WmToEN_ratio->GetBinContent(i)<< endl;
  } 




  for(int ipt(1);ipt<=13;ipt++)
  {
    h1_WpT_WpToMN_MCNom_Log->SetBinContent(ipt,h1_WpT_WpToMN_MCNom->GetBinContent(ipt));
    h1_WpT_WmToMN_MCNom_Log->SetBinContent(ipt,h1_WpT_WmToMN_MCNom->GetBinContent(ipt));
    h1_WpT_WpToEN_MCNom_Log->SetBinContent(ipt,h1_WpT_WpToEN_MCNom->GetBinContent(ipt));
    h1_WpT_WmToEN_MCNom_Log->SetBinContent(ipt,h1_WpT_WmToEN_MCNom->GetBinContent(ipt));
  
  }
  sprintf(tmpName,"WpT_WpMN");
  pltWpMN= new CPlot(tmpName,"",tmpName,"events/bin");
  sprintf(tmpName,"WpT_WmMN");
  pltWmMN= new CPlot(tmpName,"",tmpName,"events/bin");
  sprintf(tmpName,"WpT_WpEN");
  pltWpEN= new CPlot(tmpName,"",tmpName,"events/bin");
  sprintf(tmpName,"WpT_WmEN");
  pltWmEN= new CPlot(tmpName,"",tmpName,"events/bin");
  //h1_WpT_WpToMN_MC->SetFillColor(2);
  //h1_WpT_WpToMN_MC->SetMarkerStyle(2);
  //h1_WpT_WpToMN_MC->SetMarkerSize(2);
  //h1_WpT_WpToMN_MC->SetMarkerColor(0);
  //h1_WpT_WpToMN_MC->Draw("h");
  pltWpMN->setOutDir(resultDir);
  pltWmMN->setOutDir(resultDir);
  pltWpEN->setOutDir(resultDir);
  pltWmEN->setOutDir(resultDir);
  //           // hist, drawopt, color, linesty, fillsty, mkerSty, mkerSize
  //pltWpMN->AddHist1D(h1_WpT_WpToMN_MCNom_Log,"hist",kGreen,1,0,0,0);
  //pltWmMN->AddHist1D(h1_WpT_WmToMN_MCNom_Log,"hist",kGreen,1,0,0,0);
  //pltWpMN->AddHist1D(h1_WpT_WpToMN_RDNom,"elp",kBlack,1,0,20,1);
  //pltWmMN->AddHist1D(h1_WpT_WmToMN_RDNom,"elp",kBlack,1,0,20,1);
  pltWpMN->AddHist1D(h1_WpT_WpToMN_MCNom_Log,"H",kGreen,1,1001,2,0);
  pltWmMN->AddHist1D(h1_WpT_WmToMN_MCNom_Log,"H",kGreen,1,1001,2,0);
  pltWpMN->AddHist1D(h1_WpT_WpToMN_RDNom,"elp",kBlack,1,0,21,1);
  pltWmMN->AddHist1D(h1_WpT_WmToMN_RDNom,"elp",kBlack,1,0,21,1);

  pltWpEN->AddHist1D(h1_WpT_WpToEN_MCNom_Log,"H",3,1,1001,2,0);
  pltWmEN->AddHist1D(h1_WpT_WmToEN_MCNom_Log,"H",3,1,1001,2,0);
  pltWpEN->AddHist1D(h1_WpT_WpToEN_RDNom,"E",kBlack,1,0,21,1);
  pltWmEN->AddHist1D(h1_WpT_WmToEN_RDNom,"E",kBlack,1,0,21,1);

  pltWpMN->SetLegend(0.53,0.7,0.7,0.8);
  pltWmMN->SetLegend(0.53,0.7,0.7,0.8);
  pltWpEN->SetLegend(0.53,0.7,0.7,0.8);
  pltWmEN->SetLegend(0.53,0.7,0.7,0.8);
  //cout << "check4" << endl;

  pltWpMN->GetLegend()->SetTextSize(0.03);
  pltWmMN->GetLegend()->SetTextSize(0.03);
  pltWpEN->GetLegend()->SetTextSize(0.03);
  pltWmEN->GetLegend()->SetTextSize(0.03);

  pltWpMN->GetLegend()->AddEntry(h1_WpT_WpToMN_MCNom_Log,"Nominal Truth Post","l");
  pltWmMN->GetLegend()->AddEntry(h1_WpT_WmToMN_MCNom_Log,"Nominal Truth Post","l");
  pltWpMN->GetLegend()->AddEntry(h1_WpT_WpToMN_RDNom,"DetUnf Fit Data ","p");
  pltWmMN->GetLegend()->AddEntry(h1_WpT_WmToMN_RDNom,"DetUnf Fit Data ","p");

  pltWpEN->GetLegend()->AddEntry(h1_WpT_WpToEN_MCNom_Log,"Nominal Truth Post","l");
  pltWmEN->GetLegend()->AddEntry(h1_WpT_WmToEN_MCNom_Log,"Nominal Truth Post","l");
  pltWpEN->GetLegend()->AddEntry(h1_WpT_WpToEN_RDNom,"DetUnf Fit Data","p");
  pltWmEN->GetLegend()->AddEntry(h1_WpT_WmToEN_RDNom,"DetUnf Fit Data","p");

  pltWpMN->SetLogx();
  pltWmMN->SetLogx();
  pltWpEN->SetLogx();
  pltWmEN->SetLogx();
  
  
  pltWpMN->Draw(myCan,kTRUE,format);
  pltWmMN->Draw(myCan,kTRUE,format);
  pltWpEN->Draw(myCan,kTRUE,format);
  pltWmEN->Draw(myCan,kTRUE,format);

  sprintf(tmpName,"WpT_WpMN_ratio");
  pltWpMN_ratio= new CPlot(tmpName,"",tmpName,"ratio/bin");
  sprintf(tmpName,"WpT_WmMN_ratio");
  pltWmMN_ratio= new CPlot(tmpName,"",tmpName,"ratio/bin");

  sprintf(tmpName,"WpT_WpEN_ratio");
  pltWpEN_ratio= new CPlot(tmpName,"",tmpName,"ratio/bin");
  sprintf(tmpName,"WpT_WmEN_ratio");
  pltWmEN_ratio= new CPlot(tmpName,"",tmpName,"ratio/bin");

  pltWpMN_ratio->setOutDir(resultDir);
  pltWmMN_ratio->setOutDir(resultDir);
  pltWpEN_ratio->setOutDir(resultDir);
  pltWmEN_ratio->setOutDir(resultDir);

  pltWpMN_ratio->AddHist1D(h1_WpT_WpToMN_ratio,"E",1,1,1001,21,1);
  pltWmMN_ratio->AddHist1D(h1_WpT_WmToMN_ratio,"E",1,1,1001,21,1);
  pltWpEN_ratio->AddHist1D(h1_WpT_WpToEN_ratio,"E",1,1,1001,21,1);
  pltWmEN_ratio->AddHist1D(h1_WpT_WmToEN_ratio,"E",1,1,1001,21,1);

  pltWpMN_ratio->SetLegend(0.7,0.8,0.9,0.9);
  pltWmMN_ratio->SetLegend(0.7,0.8,0.9,0.9);
  pltWpEN_ratio->SetLegend(0.7,0.8,0.9,0.9);
  pltWmEN_ratio->SetLegend(0.7,0.8,0.9,0.9);

  pltWpMN_ratio->GetLegend()->SetTextSize(0.03);
  pltWmMN_ratio->GetLegend()->SetTextSize(0.03);
  pltWpEN_ratio->GetLegend()->SetTextSize(0.03);
  pltWmEN_ratio->GetLegend()->SetTextSize(0.03);

  //pltWpMN_ratio->GetLegend()->AddEntry(h1_WpT_WpToMN_ratio,"WpToMN PostFSR Data/MC TruthPost");
  //pltWmMN_ratio->GetLegend()->AddEntry(h1_WpT_WmToMN_ratio,"WmToMN PostFSR Data/MC TruthPost");
  //pltWpEN_ratio->GetLegend()->AddEntry(h1_WpT_WpToEN_ratio,"WpToEN PostFSR Data/MC TruthPost");
  //pltWmEN_ratio->GetLegend()->AddEntry(h1_WpT_WmToEN_ratio,"WmToEN PostFSR Data/MC TruthPost");

  pltWpMN_ratio->GetLegend()->AddEntry(h1_WpT_WpToMN_ratio,"WpToMN DetUnfFit Data/MC TruthPost");
  pltWmMN_ratio->GetLegend()->AddEntry(h1_WpT_WmToMN_ratio,"WmToMN DetUnfFit Data/MC TruthPost");
  pltWpEN_ratio->GetLegend()->AddEntry(h1_WpT_WpToEN_ratio,"WpToEN DetUnfFit Data/MC TruthPost");
  pltWmEN_ratio->GetLegend()->AddEntry(h1_WpT_WmToEN_ratio,"WmToEN DetUnfFit Data/MC TruthPost");
  
  pltWpMN_ratio->SetLogx();
  pltWmMN_ratio->SetLogx();
  pltWpEN_ratio->SetLogx();
  pltWmEN_ratio->SetLogx();
  
  pltWpMN_ratio->Draw(myCan,kTRUE,format);
  pltWmMN_ratio->Draw(myCan,kTRUE,format);
  pltWpEN_ratio->Draw(myCan,kTRUE,format);
  pltWmEN_ratio->Draw(myCan,kTRUE,format);

  //TFile *RootOut= new TFile("./WpT_PostFSRData_MC_ratio.root","recreate");
  TFile *RootOut= new TFile("../RstSelection/WpT_FitDetUnfData_MC_ratio.root","recreate");
  h1_WpT_WpToMN_ratio->Write();
  h1_WpT_WmToMN_ratio->Write();
  h1_WpT_WpToEN_ratio->Write();
  h1_WpT_WmToEN_ratio->Write();
  RootOut->Close();
  
  Fout.close();
  myCan->Clear();

  return 0;
}
Esempio n. 3
0
int create_plots(const char* file = "/home/wagners/acqu/acqu_user/PHYS_CB_2014-06-06_completeSet.root")
{
	/* some initial stuff */
	const char* suffix = "pdf";  // file format for saving the histograms

	gStyle->SetCanvasColor(0);
	//gStyle->SetOptStat(0);

	// Color used for histograms
	Int_t color = TColor::GetColor("#014ED0");

	// enum for numbering of different cuts and cut combinations
	enum cut {
		protE,
		copl,
		balance,
		dAlpha,
		missM,
		invM,
		copl_balance,
		balance_missM,
		protE_copl,
		copl_missM,
		missM_invM,
		balance_dAlpha,
		copl_dAlpha,
		protE_copl_balance,
		copl_balance_dAlpha,
		all,
		unknown
	};

	IntCharMap cuts;
	cuts.insert(ICPair(protE, "protE"));
	cuts.insert(ICPair(copl, "copl"));
	cuts.insert(ICPair(balance, "balance"));
	cuts.insert(ICPair(dAlpha, "dAlpha"));
	cuts.insert(ICPair(missM, "missM"));
	cuts.insert(ICPair(invM, "invM"));
	cuts.insert(ICPair(copl_balance, "copl_balance"));
	cuts.insert(ICPair(balance_missM, "balance_missM"));
	cuts.insert(ICPair(protE_copl, "protE_copl"));
	cuts.insert(ICPair(copl_missM, "copl_missM"));
	cuts.insert(ICPair(missM_invM, "missM_invM"));
	cuts.insert(ICPair(balance_dAlpha, "balance_dAlpha"));
	cuts.insert(ICPair(copl_dAlpha, "copl_dAlpha"));
	cuts.insert(ICPair(protE_copl_balance, "protE_copl_balance"));
	cuts.insert(ICPair(copl_balance_dAlpha, "copl_balance_dAlpha"));
	cuts.insert(ICPair(all, "allCuts"));

	std::vector<const char*> props;
	props.push_back("invM");
	props.push_back("missM");

	const char* windows[2] = {"prompt", "random"};

	// connect to the file to read from
	TFile f(file, "READ");
	if (!f.IsOpen()) {
		printf("Error opening file %s!\n", file);
		return 1;
	}
	printf("Read ");
	f.Print();
	// load the desired folder from file (not needed in case the EndFileMacro was used)
	//TFolder *t = (TFolder*)f.Get("ROOT Memory");

	// Get the Prompt-Random-Ratio from the analysed root file
	TH1F *h_ratio = (TH1F*)f.FindObjectAny("PHYS_promptRandomRatio");
	const double ratio = h_ratio->GetMean();
	std::cout << "[INFO] Prompt-Random-Ratio: " << ratio << std::endl;

	// declare some temporary used variables
	TH1F* h[N_WINDOWS];
	char buffer[50];
	// create an empty canvas for histogram drawing
	TCanvas *c = new TCanvas("c", "plot", 20, 10, 700, 500);
	c->SetFillColor(0);
	c->SetBorderMode(0);
	c->SetBorderSize(2);
	//c->SetLogy();
	c->SetFrameBorderMode(0);
	c->SetLeftMargin(.14);
	c->SetRightMargin(.1);
	c->SetBottomMargin(.125);
	c->SetTopMargin(.05);

	for (std::vector<const char*>::iterator it_prop = props.begin(); it_prop != props.end(); ++it_prop) {
		for (ICIter it_cut = cuts.begin(); it_cut != cuts.end(); ++it_cut) {
			// skip the current combination if the cut contains the current variable, e. g. invM with some cut involving invM
			if (strstr(it_cut->second, *it_prop))
				continue;
			// get prompt and random histograms for every property cut combination
			for (unsigned int i = 0; i < N_WINDOWS; i++) {
				sprintf(buffer, "%s_%s_%s", *it_prop, it_cut->second, windows[i]);
				h[i] = (TH1F*)f.FindObjectAny(buffer);
				if (!h[i]) {
					std::cout << "[ERROR] Couldn't find histogram " << buffer << std::endl;
					exit(1);
				}
			}
			c->Clear();
			// subtract to chosen window size normalized random-background from events inside the prompt-window
			h[PROMPT]->Add(h[RANDOM], -1*ratio);
			prepare_hist(h[PROMPT]);
			/* Rebin histogram */
			int n = 50;
			h[PROMPT]->Rebin(n);  // combine n bins => n MeV binning
			/*char* label;
			if (label)
				free(label);
			char* label = malloc(strlen("#Events / ") + 5 + strlen(" MeV^{2}") + 1);
			//sprintf(label, "%s%.2f%s", "#Events / ", n/1000., " GeV^{2}");
			sprintf(label, "%s%d%s", "#Events / ", n, " MeV^{2}");
			h->GetYaxis()->SetTitle(label);*/
			/* set axes according to plotted values and prepare histogram for saving */
			sprintf(buffer, "%s%d%s", "#Events / ", n, " MeV");
			h[PROMPT]->GetYaxis()->SetTitle(buffer);
			h[PROMPT]->SetLineColor(color);
			sprintf(buffer, "%s [MeV]", *it_prop);
			h[PROMPT]->GetXaxis()->SetTitle(buffer);
			h[PROMPT]->Draw();
			sprintf(buffer, "%s_%s.%s", *it_prop, it_cut->second, suffix);
			c->Print(buffer);
		}
		std::cout << "[INFO] Created all random-subtracted plots for " << *it_prop << std::endl;
	}

	f.Close();

	return EXIT_SUCCESS;
}
Esempio n. 4
0
void
TestSPD(const TString& which, Double_t nVar=2)
{
  TFile* file = TFile::Open("forward.root", "READ");
  if (!file) return;

  Bool_t spd = which.EqualTo("spd", TString::kIgnoreCase);
  
  TList* l = 0;
  if (spd) l = static_cast<TList*>(file->Get("CentralSums"));
  else     l = static_cast<TList*>(file->Get("ForwardSums"));
  if (!l) { 
    Warning("", "%sSums not found", spd ? "Central" : "Forward");
    return;
  }

  TList* ei = static_cast<TList*>(l->FindObject("fmdEventInspector"));
  if (!l) { 
    Warning("", "fmdEventInspector not found");
    return;
  }
  
  TObject* run = ei->FindObject("runNo");
  if (!run) 
    Warning("", "No run number found");
  ULong_t runNo = run ? run->GetUniqueID() : 0;

  TH2* h = 0;
  if (spd) h = static_cast<TH2*>(l->FindObject("nClusterVsnTracklet"));
  else { 
    TList* den = static_cast<TList*>(l->FindObject("fmdDensityCalculator"));
    if (!den) { 
      Error("", "fmdDensityCalculator not found");
      return;
    }
    TList* rng = static_cast<TList*>(den->FindObject(which));
    if (!rng) { 
      Error("", "%s not found", which.Data());
      return;
    }
    h = static_cast<TH2*>(rng->FindObject("elossVsPoisson"));
  }
  if (!h) { 
    Warning("", "%s not found", spd ? nClusterVsnTracklet : "elossVsPoisson");
    return;
  }

  gStyle->SetOptFit(1111);
  gStyle->SetOptStat(0);
  TCanvas* c = new TCanvas("c", Form("Run %u", runNo));
  c->Divide(2,2);
  
  TVirtualPad* p = c->cd(1);
  if (spd) {
    p->SetLogx();
    p->SetLogy();
  }
  p->SetLogz();
  h->Draw("colz");

  TObjArray* fits = new TObjArray;
  h->FitSlicesY(0, 1, -1, 0, "QN", fits);

  TF1* mean = new TF1("mean", "pol1");
  TF1* var  = new TF1("var", "pol1");
  // mean->FixParameter(0, 0);
  // var->FixParameter(0, 0);
  for (Int_t i = 0; i < 3; i++) { 
    p = c->cd(2+i);
    if (spd) { 
      p->SetLogx();
      p->SetLogy();
    }
    TH1* hh = static_cast<TH1*>(fits->At(i));
    hh->Draw();

    if (i == 0) continue;
    
    hh->Fit((i == 1? mean : var), "+Q");
    
  }

  TGraphErrors* g1 = new TGraphErrors(h->GetNbinsX());
  g1->SetFillColor(kBlue-10);
  g1->SetFillStyle(3001);
  g1->SetLineStyle(1);
  TGraph* u1 = new TGraph(h->GetNbinsX());
  TGraph* l1 = new TGraph(h->GetNbinsX());
  u1->SetLineColor(kBlue+1);
  l1->SetLineColor(kBlue+1);
  u1->SetName("u1");
  l1->SetName("l1");
  TGraphErrors* g2 = new TGraphErrors(h->GetNbinsX());
  g2->SetFillColor(kRed-10);
  g2->SetFillStyle(3001);
  g2->SetLineStyle(2);
  TGraph* u2 = new TGraph(h->GetNbinsX());
  TGraph* l2 = new TGraph(h->GetNbinsX());
  u2->SetLineColor(kRed+1);
  l2->SetLineColor(kRed+1);
  u2->SetName("u2");
  l2->SetName("l2");
  for (Int_t i = 1; i <= h->GetNbinsX(); i++) {
    Double_t x  = hh->GetXaxis()->GetBinCenter(i);
    Double_t y  = mean->Eval(x);
    Double_t e  = var->Eval(y);
    Double_t e1 = nVar * e;
    if (spd) e1 *= TMath::Log10(e);
    // Printf("%10e -> %10e +/- %10e", x, y, ee);
    g1->SetPoint(i-1, x, y);
    g1->SetPointError(i-1, 0, e1);
    u1->SetPoint(i-1, x, y+e1);
    l1->SetPoint(i-1, x, y-e1);
    // Printf("%3d: %f -> %f +/- %f", i, x, y, ee);

    Double_t e2 = nVar*0.05*x;
    g2->SetPoint(i-1, x, x);
    g2->SetPointError(i-1, 0, e2);
    u2->SetPoint(i-1, x, x+e2);
    l2->SetPoint(i-1, x, x-e2);
  }

  p = c->cd(1);
  c->Clear();
  c->cd();
  c->SetLogz();
  h->Draw("colz");
  g1->Draw("3 same");
  u1->Draw("l same");
  l1->Draw("l same");
  g2->Draw("3 same");
  u2->Draw("l same");
  l2->Draw("l same");

  Double_t ly = 0.9;
  Double_t dy = 0.06;
  TLatex* ltx = new TLatex(0.15, ly, Form("#LTy#GT = %f + %f x",
					   mean->GetParameter(0),
					   mean->GetParameter(1)));
  ltx->SetNDC();
  ltx->SetTextSize(dy);
  ltx->SetTextAlign(13);
  ltx->Draw();

  ly -= dy + 0.01;
  ltx->DrawLatex(0.15, ly, Form("#sigma_{y} = %f + %f x", 
				var->GetParameter(0),
				var->GetParameter(1)));
  
  ly -= dy + 0.01;
  ltx->DrawLatex(0.15, ly, Form("#delta = %f #sigma %s", 
				nVar, (spd ? "log_{10}(#sigma" : "")));
	    
					   
}
void startCorrelation(int run,int eventNumber){

  //int entry=65000;
  char runRootDirectory[FILENAME_MAX];
  sprintf(runRootDirectory,"/unix/anita3/flight0809/root/");

  char headName[FILENAME_MAX];
  char eventName[FILENAME_MAX];
  char gpsName[FILENAME_MAX];
  RawAnitaEvent *evPtr = 0;
  RawAnitaHeader *hdPtr = 0;
  Adu5Pat *patPtr =0;

  sprintf(headName,"%s/run%d/headFile%d.root",runRootDirectory,run,run);
  sprintf(eventName,"%s/run%d/eventFile%d.root",runRootDirectory,run,run);
  sprintf(gpsName,"%s/run%d/gpsFile%d.root",runRootDirectory,run,run);

  TFile *eventFile = new TFile(eventName);
  TFile *headFile = new TFile(headName);
  TFile *fpGps = new TFile(gpsName);

  if(!fpGps){
    std::cout << "no GPS file\n";
    return;
  }

  TTree *adu5PatTree = (TTree*) fpGps->Get("adu5PatTree");
  TTree *eventTree = (TTree*)eventFile->Get("eventTree");
  TTree *headTree = (TTree*)headFile->Get("headTree");

  eventTree->SetBranchAddress("event",&evPtr);
  headTree->SetBranchAddress("header",&hdPtr);
  headTree->BuildIndex("eventNumber");
  adu5PatTree->SetBranchAddress("pat",&patPtr);
  adu5PatTree->BuildIndex("realTime");

  int entry=headTree->GetEntryNumberWithBestIndex(eventNumber);

  eventTree->GetEntry(entry);
  headTree->GetEntry(entry);



  /*
  //for(int phi=0;phi<16;phi++){
    while(hdPtr->triggerTimeNs<349.99e6 || hdPtr->triggerTimeNs>350.005e6 || hdPtr->l3TrigPattern==0){
      if(lastEvent==hdPtr->eventNumber){
	std::cout << "no more entries in run" << std::endl;
	return;
      }
      std::cout << "opened entry " << entry << " (event " << hdPtr->eventNumber << ") with triggerTimeNs " << hdPtr->triggerTimeNs << std::endl;
      lastEvent=hdPtr->eventNumber;
      entry++;
      eventTree->GetEntry(entry);
      headTree->GetEntry(entry);
      adu5PatTree->GetEntry(entry);
    }
    //}
    */

  std::cout << "opened entry " << entry << " (event " << hdPtr->eventNumber << ") with triggerTimeNs " << hdPtr->triggerTimeNs << std::endl;

  //get the pat ptr that corresponds to the timing of the event
  Int_t patEntry;
  patEntry = adu5PatTree->GetEntryNumberWithBestIndex(hdPtr->realTime);
  adu5PatTree->GetEntry(patEntry);

  std::cout << patPtr->realTime << " " << hdPtr->realTime << std::endl;

  if(patPtr->realTime != hdPtr->realTime){
    std:: cout << "pat time doesn't match head time, pat realTime: " << patPtr->realTime << " head realTime: " << hdPtr->realTime << std::endl;
    //return;
  }


  for(int chan=0;chan<90;chan++){
    if(evPtr->xMax[chan]>130 || evPtr->xMin[chan]<-130){
      saturatedChannel[chan]=1;
      std::cout << "saturated " << chan << std::endl;
    }
    else saturatedChannel[chan]=0;
  }


  //entry++;
  TH2D *crossCorrelation = crossCorrelate(evPtr,hdPtr,patPtr);
 
  sprintf(headName,"crossCorrCan");
  TCanvas *crossCorrCan = (TCanvas*)gROOT->FindObject(headName);
  if(!crossCorrCan)
    crossCorrCan = new TCanvas(headName,headName,800,400);
  crossCorrCan->Clear();
  //sumCrossCorrs->Draw("aitoff");
  crossCorrelation->Draw("colz");
  TAxis *phiSectors = new TAxis(16,1,16);
  phiSectors->Draw();

  //std::cout << "event " << hdPtr->eventNumber << " time " << 

  double theta,phi;

  getSignalDirection(crossCorrelation,phi,theta);

  std::cout << "phi " << phi << " theta " << theta << std::endl;

  plotAnitaEventMap(patPtr,phi,theta);

}
Esempio n. 6
0
void danss_calc_ratio(void)
{
#ifdef STRONG_CUTS
	const char fname[] = "danss_report_strong.root";
	const char pname[] = "danss_ratio_strong.pdf";
#else
	const char fname[] = "danss_report.root";
	const char pname[] = "danss_ratio.pdf";
#endif
	const struct {
		char name[32];
		int first;
		int last;
	} positions[] = {
		{ "down_21.04.16",   2307, 2361},	// [0] - 0-
		{ "up_22.04.16",     2366, 2387},	// [1] - 0+
		{ "down_23.04.16",   2399, 2445},	// [2] - 0-
		{ "mid_24.04.16",    2449, 2512},
		{ "up_25.04.16",     2514, 2562},	// [4] - 1+
		{ "down_26.04.16",   2564, 2609},	// [5] - 1-
		{ "mid_27.04.16",    2620, 2685},
		{ "up_28.04.16",     2687, 2730},	// [7] - 2+
		{ "down_29.04.16",   2733, 2788},	// [8] - 2-
		{ "mid_30.04.16",    2791, 2832},
		{ "stuck_01.05.16",  2836, 3399},
		{ "stuck_10.05.16",  3400, 3788},
		{ "up_03.06.16",     4261, 4400},	// [12] - 3+
		{ "down_06.06.16",   4403, 4439},	// [13] - 3-
		{ "up_08.06.16",     4508, 4601},	// [14] - 3+
		{ "raised_30.09.16", 5540, 5807},
		{ "raised_04.10.16", 5808, 5903},	// veto corners on
		{ "mid_05.10.16",    5907, 5995},	// [17]
		{ "up_10.10.16",     6007, 6130},	// [18] - 5+
//		{ "mid_12.10.16",    6136, 6275},
//		{ "down_14.10.16",   6278, 6467},
//		{ "up_17.10.16",     6469, 6570},
//		{ "mid_21.10.16",    6573, 6582},
//		{ "down_21.10.16",   6587, 6745},
//		{ "up_24.10.16",     6757, 6815},
//		{ "mid_27.10.16",    6842, 6923},
//		{ "down_28.10.16",   6926, 7095},
		{ "up_31.10.16",     7106, 7364},	// [19] - 5+
		{ "mid_11.11.16",    7387, 7406},	// [20]
		{ "down_11.11.16",   7418, 7458},	// [21] - 5-
		{ "up_14.11.16",     7478, 7579},	// [22] - 6+
//		{ "mid_16.11.16",    7581, 7717},
		{ "down_18.11.16",   7727, 7913},	// [23] - 6-
		{ "up_21.11.16",     7922, 8042},	// [24] - 7+
		{ "mid_23.11.16",    8048, 8179},	// [25]
		{ "down_25.11.16",   8185, 8353},	// [26] - 7-
		{ "up_28.11.16",     8357, 8430},	// [27] - 8+
		{ "mid_01.12.16",    8470, 8571},	// [28]
		{ "down_02.12.16",   8574, 8738},	// [29] - 8-
		{ "up_05.12.16",     8741, 8869},	// [30] - 8+
		{ "mid_07.12.16",    8873, 9009},	// [31]
		{ "up_12.12.16",     9012, 9112},	// [32] - 9+
		{ "mid_14.12.16",    9116, 9245},	// [33]
		{ "down_16.12.16",   9253, 9470},	// [34] - 9-
//		{ "up_19.12.16",     9475, 9600},
//		{ "mid_21.12.16",    9603, 9712},
//		{ "down_23.12.16",   9715, 9869},
//		{ "up_26.12.16",     9871, 10019}
//		{ "mid_28.12.16",    10021, 10171},
//		{ "down_30.12.16",   10175, 10307},
//		{ "down_02.01.17",   10308, 10356},
//		{ "down_03.01.17",   10357, 10424},
		{ "up_04.01.17",     10433, 10832},	// [35] - 10+
		{ "mid_11.01.17",    10834, 10973},	// [36]
		{ "down_13.01.17",   10979, 11147},	// [37] - 10-
		{ "up_16.01.17",     11150, 11267},	// [38] - 11+
		{ "mid_18.01.17",    11271, 11401},	// [39]
		{ "down_20.01.17",   11404, 11563},	// [40] - 11-
		{ "up_23.01.17",     11570, 11619}	// [41] - 11+
	};
	int i, j;
	int N;
	TCanvas *cv;
	TFile *f;
	TH1 *h[sizeof(positions) / sizeof(positions[0])];
	TH1 *hSum[12];
	TH1 *hRatio[7];
	TH1 *hTmp[3];
	char str[1024];
	TLatex *txt;
	double val, err;
	TVirtualPad *pd;
	const char periods[3][30] = {"April-June", "October-November", "December-January"};
	
	gStyle->SetOptStat(0);
	gStyle->SetOptFit(1);
	N = sizeof(positions) / sizeof(positions[0]);
	cv = new TCanvas("CV", "Results", 2400, 1200);
	f = new TFile(fname, "UPDATE");
	if (!f->IsOpen()) return;
	sprintf(str, "%s[", pname);
	cv->Print(str);
	txt = new TLatex();
	
	for (i=0; i<N; i++) {
		sprintf(str, "%s_hRes", positions[i].name);
		h[i] = (TH1 *) f->Get(str);
		if (!h[i]) {
			printf("%s not found in %s\n", positions[i].name, fname);
			return;
		}
		h[i]->SetBit(TH1::kIsAverage);
	}
	
	hSum[0] = (TH1 *) h[0]->Clone("hUp");
	hSum[1] = (TH1 *) h[0]->Clone("hDown");
	hSum[2] = (TH1 *) h[0]->Clone("hMid");
	hSum[3] = (TH1 *) h[0]->Clone("hSum");
	hSum[4] = (TH1 *) h[0]->Clone("hSum_first");
	hSum[5] = (TH1 *) h[0]->Clone("hSum_last");
	hSum[6] = (TH1 *) h[0]->Clone("hUpAprilJune");
	hSum[7] = (TH1 *) h[0]->Clone("hDownAprilJune");
	hSum[8] = (TH1 *) h[0]->Clone("hUpOctoberNovember");
	hSum[9] = (TH1 *) h[0]->Clone("hDownOctoberNovember");
	hSum[10] = (TH1 *) h[0]->Clone("hUpDecemberJanuary");
	hSum[11] = (TH1 *) h[0]->Clone("hDownDecemberJanuary");
	hRatio[0] = (TH1 *) h[0]->Clone("hRatio");
	hRatio[1] = (TH1 *) h[0]->Clone("hMix");
	hRatio[2] = (TH1 *) h[0]->Clone("hRatio2");
	hRatio[3] = (TH1 *) h[0]->Clone("hRatioMidUp");
	hRatio[4] = (TH1 *) h[0]->Clone("hRatioAprilJune");
	hRatio[5] = (TH1 *) h[0]->Clone("hRatioOctoberNovember");
	hRatio[6] = (TH1 *) h[0]->Clone("hRatioDecemberJanuary");
	hTmp[0] = (TH1 *) h[0]->Clone("hTmpUp");
	hTmp[1] = (TH1 *) h[0]->Clone("hTmpDown");
	hTmp[2] = (TH1 *) h[0]->Clone("hTmpRatio");
	for (i=0; i<12; i++) hSum[i]->Reset();
	for (i=0; i<12; i++) hSum[i]->SetLineWidth(2);
	
	for (i=0; i<N; i++) {
		switch (positions[i].name[0]) {
			case 'u' : j = 0; break;
			case 'd' : j = 1; break;
			case 'm' : j = 2; break;
			default : j = -1; break;
		}
		if (j >= 0) hSum[j]->Add(h[i]);
		hSum[(i < N/2) ? 4 : 5]->Add(h[i]);
		hSum[3]->Add(h[i]);
	}
//	for (i=0; i<3; i++) hSum[3]->Add(hSum[i]);
	hRatio[0]->Divide(hSum[1], hSum[0]);
	hRatio[1]->Divide(hSum[5], hSum[4]);
	hRatio[3]->Divide(hSum[2], hSum[0]);
//	Ratio from short ratios
	hRatio[2]->Reset();
	hRatio[2]->SetBit(TH1::kIsAverage);
//	0+2 / 1
	hTmp[0]->Add(h[0], h[2]);
	hTmp[2]->Divide(hTmp[0], h[1]);
	hRatio[2]->Add(hTmp[2]);
//	5 / 4
	hTmp[2]->Divide(h[5], h[4]);
	hRatio[2]->Add(hTmp[2]);
//	8 / 7
	hTmp[2]->Divide(h[8], h[7]);
	hRatio[2]->Add(hTmp[2]);
//	13 / 12 + 14
	hTmp[0]->Add(h[12], h[14]);
	hTmp[2]->Divide(h[13], hTmp[0]);
	hRatio[2]->Add(hTmp[2]);
//	21 / 18+19
	hTmp[0]->Add(h[18], h[19]);
	hTmp[2]->Divide(h[21], hTmp[0]);
	hRatio[2]->Add(hTmp[2]);
//	23 / 22
	hTmp[2]->Divide(h[23], h[22]);
	hRatio[2]->Add(hTmp[2]);
//	26 / 24
	hTmp[2]->Divide(h[26], h[24]);
	hRatio[2]->Add(hTmp[2]);
//	29 / 27 + 30
	hTmp[0]->Add(h[27], h[30]);
	hTmp[2]->Divide(h[29], hTmp[0]);
	hRatio[2]->Add(hTmp[2]);
//	34 / 32
	hTmp[2]->Divide(h[34], h[32]);
	hRatio[2]->Add(hTmp[2]);
//	37 / 35
	hTmp[2]->Divide(h[37], h[35]);
	hRatio[2]->Add(hTmp[2]);
//	40 / 38 + 41
	hTmp[0]->Add(h[38], h[41]);
	hTmp[2]->Divide(h[40], hTmp[0]);
	hRatio[2]->Add(hTmp[2]);
//	AprilJune (0 + 2 + 5 + 8 + 13) / (1 + 4 + 7 + 12 + 14)
	hSum[6]->Add(h[1]);
	hSum[6]->Add(h[4]);
	hSum[6]->Add(h[7]);
	hSum[6]->Add(h[12]);
	hSum[6]->Add(h[14]);
	hSum[7]->Add(h[0]);
	hSum[7]->Add(h[2]);
	hSum[7]->Add(h[5]);
	hSum[7]->Add(h[8]);
	hSum[7]->Add(h[13]);
	hRatio[4]->Divide(hSum[7], hSum[6]);
//	OctoberNovember (21 + 23 + 26 + 29) / (18 + 19 + 22 + 24 + 27 + 30)
	hSum[8]->Add(h[18]);
	hSum[8]->Add(h[19]);
	hSum[8]->Add(h[22]);
	hSum[8]->Add(h[24]);
	hSum[8]->Add(h[27]);
	hSum[8]->Add(h[30]);
	hSum[9]->Add(h[21]);
	hSum[9]->Add(h[23]);
	hSum[9]->Add(h[26]);
	hSum[9]->Add(h[29]);
	hRatio[5]->Divide(hSum[9], hSum[8]);
//	DecemberJanuary (34 + 37 + 40) / (32 + 35 + 38 + 41)
	hSum[10]->Add(h[32]);
	hSum[10]->Add(h[35]);
	hSum[10]->Add(h[38]);
	hSum[10]->Add(h[41]);
	hSum[11]->Add(h[34]);
	hSum[11]->Add(h[37]);
	hSum[11]->Add(h[40]);
	hRatio[6]->Divide(hSum[11], hSum[10]);
	cv->Divide(2, 1);

	pd = cv->cd(1);
	pd->Divide(1, 2);
	pd->cd(1);
	hSum[0]->SetTitle("Up - Middle - Down;MeV;mHz");
	hSum[0]->SetLineColor(kRed);
	hSum[2]->SetLineColor(kGreen);
	hSum[1]->SetLineColor(kBlue);
	for (i=0; i<4; i++) hSum[i]->SetLineWidth(2);
	hSum[0]->Draw();
	hSum[2]->Draw("same");
	hSum[1]->Draw("same");
	val = hSum[0]->IntegralAndError(1, 35, err);
	sprintf(str, "Up = %5.2f+-%4.2f", val, err);
	txt->SetTextColor(kRed);
	txt->DrawTextNDC(0.4, 0.85, str);
	val = hSum[2]->IntegralAndError(1, 35, err);
	sprintf(str, "Mid = %5.2f+-%4.2f", val, err);
	txt->SetTextColor(kGreen);
	txt->DrawTextNDC(0.4, 0.8, str);
	val = hSum[1]->IntegralAndError(1, 35, err);
	sprintf(str, "Down = %5.2f+-%4.2f", val, err);
	txt->SetTextColor(kBlue);
	txt->DrawTextNDC(0.4, 0.75, str);
	
	pd->cd(2);
	hSum[3]->SetTitle("Average of all positions;MeV;mHz");
	hSum[3]->SetLineColor(kBlack);
	hSum[3]->Draw();
	val = hSum[3]->IntegralAndError(1, 35, err);
	sprintf(str, "Avr = %5.2f+-%4.2f", val, err);
	txt->SetTextColor(kBlack);
	txt->DrawTextNDC(0.4, 0.8, str);

	pd = cv->cd(2);
	pd->Divide(1, 4);
	pd->cd(1);
	hRatio[0]->SetTitle("Down/Up all by all;MeV;");
	hRatio[0]->SetLineColor(kBlack);
	hRatio[0]->SetLineWidth(2);
	hRatio[0]->SetMinimum(0.5);
	hRatio[0]->SetMaximum(1.0);
	hRatio[0]->Fit("pol0", "", "", 1, 7);
	
	pd->cd(2);
	hRatio[2]->SetTitle("Down/Up pair by pair;MeV;");
	hRatio[2]->SetLineColor(kBlack);
	hRatio[2]->SetLineWidth(2);
	hRatio[2]->SetMinimum(0.5);
	hRatio[2]->SetMaximum(1.0);
	hRatio[2]->Fit("pol0", "", "", 1, 7);

	pd->cd(3);
	hRatio[3]->SetTitle("Mid/Up all by all;MeV;");
	hRatio[3]->SetLineColor(kBlack);
	hRatio[3]->SetLineWidth(2);
	hRatio[3]->SetMinimum(0.65);
	hRatio[3]->SetMaximum(1.15);
	hRatio[3]->Fit("pol0", "", "", 1, 7);

	pd->cd(4);
	hRatio[1]->SetTitle("First half/Last half;MeV;");
	hRatio[1]->SetLineColor(kBlack);
	hRatio[1]->SetLineWidth(2);
	hRatio[1]->SetMinimum(0.75);
	hRatio[1]->SetMaximum(1.25);
	hRatio[1]->Fit("pol0", "", "", 1, 7);

	cv->Update();
	cv->Print(pname);

	cv->Clear();
	cv->Divide(2, 2);
	for (i=0; i<3; i++) {
		cv->cd(i+1);
		sprintf(str, "Down/Up all by all for %s;MeV;", periods[i]);
		hRatio[4+i]->SetTitle(str);
		hRatio[4+i]->SetLineColor(kBlack);
		hRatio[4+i]->SetLineWidth(2);
		hRatio[4+i]->SetMinimum(0.5);
		hRatio[4+i]->SetMaximum(1.0);
		hRatio[4+i]->Fit("pol0", "", "", 1, 7);
	}
	cv->Update();
	cv->Print(pname);

	sprintf(str, "%s]", pname);
	cv->Print(str);
	for (i=0; i<12; i++) hSum[i]->Write();
	for (i=0; i<7; i++) hRatio[i]->Write();
	f->Close();
	delete cv;
}
TObjArray getDistributionFromPlotter(TString plot,TString baseURL="~/scratch0/top-nosyst/plotter.root")
{
  using namespace std;

  setStyle();
  
  //the relevant processes
  TString procs[]={"Di-bosons","Single top", "W+jets", "Z-#gamma^{*}+jets#rightarrow ll", "other t#bar{t}", "t#bar{t} dileptons", "data"};
  const size_t nprocs=sizeof(procs)/sizeof(TString);

  //containers for the histos
  TList *data     = new TList;
  TH1F *totalData=0;
  TList *mc       = new TList;
  TH1F *totalMC=0;
  TH1F *ttbarMC=0;
  TList *spimpose = new TList;
  
  //open file with histograms
  TFile *f=TFile::Open(baseURL);
  for(size_t iproc=0; iproc<nprocs; iproc++)
    {
      TH1F *histo = (TH1F *) f->Get(procs[iproc]+"/"+plot);
      if(histo==0) { cout << "[Warning] " << plot << " not found for " << procs[iproc] << " ...skipping" << endl; continue; }
      histo->SetDirectory(0);
      if(procs[iproc].Contains("data")) 
	{
	  data->Add(histo);
	  if(totalData==0) { totalData = (TH1F *) histo->Clone(plot+"totaldata"); totalData->SetDirectory(0); }
	  else             { totalData->Add(histo); }
	}
      else
	{
	  mc->Add(histo);
	  if(totalMC==0) { totalMC = (TH1F *) histo->Clone(plot+"totalmc"); totalMC->SetDirectory(0); }
	  else           { totalMC->Add(histo); }
	  if(procs[iproc]=="t#bar{t} dileptons") { ttbarMC = (TH1F *)histo->Clone(plot+"ttbar"); ttbarMC->SetDirectory(0); }
	}
    }
  f->Close();

  cout << "Drawing now" << endl;
  
  //draw
  TCanvas *cnv = getNewCanvas(plot+"c",plot+"c",false);
  cnv->Clear();
  cnv->SetWindowSize(600,600);
  cnv->cd(); 
  TLegend *leg=showPlotsAndMCtoDataComparison(cnv,*mc,*spimpose,*data,false);
  formatForCmsPublic(cnv,leg,"CMS preliminary", 4);
  cnv->SaveAs(plot+".C");

  cout << "Stat comparison for " << plot << endl
       << "Sample \t Average \t\t RMS " << endl
       << "----------------------------------------" << endl;
  if(totalData) cout << "Data \t " << totalData->GetMean() << " +/- " << totalData->GetMeanError() << " \t " << totalData->GetRMS() << " +/- " << totalData->GetRMSError() << endl;
  if(totalMC)   cout << "MC \t "   << totalMC->GetMean() << " +/- " << totalMC->GetMeanError() << " \t " << totalMC->GetRMS() << " +/- " << totalMC->GetRMSError() << endl;
  if(ttbarMC)   cout << "Signal \t "   << ttbarMC->GetMean() << " +/- " << ttbarMC->GetMeanError() << " \t " << ttbarMC->GetRMS() << " +/- " << ttbarMC->GetRMSError() << endl;

  TObjArray res;
  res.Add(totalData);
  res.Add(totalMC);
  res.Add(ttbarMC);
  res.Add(mc);
  return res;
}
Esempio n. 8
0
TCanvas *PlotDataMCs(TChain *data, std::vector<TChain *> mc_vec, TString branchname, TString binning, 
		     TString category,  TString selection, 
		     TString dataLabel, std::vector<TString> mcLabel_vec, TString xLabel, TString yLabelUnit, TString outputPath, TString label4Print,
		     bool logy=false, bool usePU=true, bool ratio=true,bool smear=false, bool scale=false, bool useR9Weight=false, TString pdfIndex=""){
  std::cout<<"Using macro/PlotDataMC.C:: PlotDataMCs"<<std::endl;
  TStopwatch watch;
  watch.Start();
  //gStyle->SetOptStat(11);

  int nHist= mc_vec.size();
  int colors[4]={kRed,kGreen,kBlue,kCyan};
  int fillstyle[4]={0,0,0,0}; //3003,3004,3005,3006};
  if(nHist>4) return NULL;
  TString yLabel; 
  
  TCanvas *c = new TCanvas("c","");
  TPad * pad1 = new TPad("pad1", "pad1",0.01,0.13,0.75,1.);  
  TPad * pad2 = new TPad("pad2", "pad2",0.01,0.001,0.75,0.2);  
  TPad * pad3 = new TPad("pad3", "pad3",0.68,0.001,1.,0.2);
  
  pad1->SetRightMargin(0.1);
  pad1->SetLogy();
  pad1->Draw();
  pad1->cd();
  
  pad2->SetGrid();
  pad2->SetBottomMargin(0.4);
  pad2->SetRightMargin(0.1);
  pad2->Draw();
  pad2->cd();
  
  pad3->SetGrid();    
  //pad2->SetTopMargin(0.01);
  pad3->SetBottomMargin(0.4);
  pad3->SetRightMargin(0.1);
  pad3->Draw();
  pad3->cd();
    
  pad1->cd();
  
  TString branchNameData=branchname;
  TString branchNameMC=branchname;

  ElectronCategory_class cutter;
  data->SetBranchStatus("*",0);
  std::set<TString> branchList = cutter.GetBranchNameNtuple(category);
   for(std::set<TString>::const_iterator itr = branchList.begin();
       itr != branchList.end();
       itr++){
     std::cout << "[STATUS] Enabling branch: " << *itr << std::endl;
     data->SetBranchStatus(*itr, 1);
   }
   data->SetBranchStatus(branchname, 1);
   data->SetBranchStatus("scaleEle", 1);

  if(branchNameData.Contains("energySCEle_regrCorrSemiParV5_pho")) cutter.energyBranchName="energySCEle_regrCorrSemiParV5_pho";
  else if(branchNameData.Contains("energySCEle_regrCorrSemiParV5_ele")) cutter.energyBranchName="energySCEle_regrCorrSemiParV5_ele";
  else if (branchNameData.Contains("energySCEle")) cutter.energyBranchName="energySCEle";

  TCut selection_data="";
  if(category.Sizeof()>1) selection_data = cutter.GetCut(category, false,0,scale);
  selection_data+=selection;
  TCut selection_MC="";
  if(category.Sizeof()>1) selection_MC = cutter.GetCut(category, false,0);
  selection_MC+=selection;

  if(smear){
    std::cout<<"Apply smear to the MC"<<std::endl;
    branchNameMC.ReplaceAll("invMass_SC_corr","(invMass_SC_corr*sqrt(smearEle[0]*smearEle[1]))");
    branchNameMC.ReplaceAll("invMass_SC_regrCorr_pho","(invMass_SC_regrCorr_pho*sqrt(smearEle[0]*smearEle[1]))");
    branchNameMC.ReplaceAll("invMass_SC_regrCorrSemiParV5_pho","(invMass_SC_regrCorrSemiParV5_pho*sqrt(smearEle[0]*smearEle[1]))");
    branchNameMC.ReplaceAll("energySCEle_regrCorr_pho","(energySCEle_regrCorr_pho*smearEle) ");
    branchNameMC.ReplaceAll("energySCEle_corr[0]","(energySCEle_corr[0]*smearEle[0])");
    branchNameMC.ReplaceAll("energySCEle_corr[1]","(energySCEle_corr[1]*smearEle[1])");
    branchNameMC.ReplaceAll("energySCEle_regrCorr_pho[0]","(energySCEle_regrCorr_pho[0]*smearEle[0])");
    branchNameMC.ReplaceAll("energySCEle_regrCorr_pho[1]","(energySCEle_regrCorr_pho[1]*smearEle[1])");
    branchNameMC.ReplaceAll("energySCEle_regrCorrSemiParV5_ele[0]","(energySCEle_regrCorrSemiParV5_ele[0]*smearEle[0])");
    branchNameMC.ReplaceAll("energySCEle_regrCorrSemiParV5_ele[1]","(energySCEle_regrCorrSemiParV5_ele[1]*smearEle[1])");
    if(!branchNameMC.Contains("smear")) branchNameMC.ReplaceAll("energySCEle_regrCorrSemiParV5_ele","(energySCEle_regrCorrSemiParV5_ele*smearEle)");

  }
  if(scale){
    std::cout << "Apply scale to the data" << std::endl;
    branchNameData.ReplaceAll("invMass_SC_corr","(invMass_SC_corr*sqrt(scaleEle[0]*scaleEle[1]))");
    branchNameData.ReplaceAll("invMass_SC_regrCorr_pho","(invMass_SC_regrCorr_pho*sqrt(scaleEle[0]*scaleEle[1]))");
    branchNameData.ReplaceAll("invMass_SC_regrCorrSemiParV5_pho","(invMass_SC_regrCorrSemiParV5_pho*sqrt(scaleEle[0]*scaleEle[1]))");
    branchNameData.ReplaceAll("energySCEle_regrCorrSemiParV5_pho ","(energySCEle_regrCorrSemiParV5_pho*scaleEle)");
    branchNameData.ReplaceAll("energySCEle_corr[0]","(energySCEle_corr*scaleEle[0])");
    branchNameData.ReplaceAll("energySCEle_corr[1]","(energySCEle_corr*scaleEle[1])");
    branchNameData.ReplaceAll("energySCEle_regrCorrSemiParV5_pho[0]","(energySCEle_regrCorrSemiParV5_pho[0]*scaleEle[0])");
    branchNameData.ReplaceAll("energySCEle_regrCorrSemiParV5_pho[1]","(energySCEle_regrCorrSemiParV5_pho[1]*scaleEle[1])");
    branchNameData.ReplaceAll("energySCEle_regrCorrSemiParV5_ele[0]","(energySCEle_regrCorrSemiParV5_ele[0]*scaleEle[0])");
    branchNameData.ReplaceAll("energySCEle_regrCorrSemiParV5_ele[1]","(energySCEle_regrCorrSemiParV5_ele[1]*scaleEle[1])");
    if(!branchNameData.Contains("scale"))    branchNameData.ReplaceAll("energySCEle_regrCorrSemiParV5_ele","(energySCEle_regrCorrSemiParV5_ele*scaleEle)");
  }    

  std::cout <<"For data you are plotting: "<<branchNameData <<std::endl;
  std::cout <<"For MC your are plotting:  " << branchNameMC << std::endl;
  std::cout << "Selection for data is "<<selection_data<<std::endl;
  std::cout << "binning is "<<binning<<std::endl;
  
  // Draw histograms
    data->Draw(branchNameData+">>data_hist"+binning, selection_data);
    if(nHist > 0){//for MC
      for(std::vector<TChain *>::const_iterator mc_itr = mc_vec.begin();
	  mc_itr != mc_vec.end();
	  mc_itr++){
	TChain *mc = *mc_itr;
 	mc->SetBranchStatus("*",0);
 	for(std::set<TString>::const_iterator itr = branchList.begin();
 	    itr != branchList.end();
 	    itr++){
 	  //std::cout << "[STATUS] Enabling branch: " << *itr << std::endl;
 	  mc->SetBranchStatus(*itr, 1);
 	}
	mc->SetBranchStatus(branchname, 1);
	mc->SetBranchStatus("smearEle", 1);
	mc->SetBranchStatus("puWeight",1);
	mc->SetBranchStatus("mcGenWeight", 1);
	mc->SetBranchStatus("r9Weight", 1);
 	

	TString mcHistName;  mcHistName+="hist_"; mcHistName+=mc_itr-mc_vec.begin();//better for .C generation
	//TString mcHistName; mcHistName+=mc_itr-mc_vec.begin(); mcHistName+="_hist";//better for .C generation
	
	//decide this for MC
	//TString weights="mcGenWeight";
	//if(pdfIndex!="") weights+="*(pdfWeights_cteq66["+pdfIndex+"]/pdfWeights_cteq66[0])";
	//if(usePU) weights+="*puWeight";
	//if(useR9Weight) weights+="*r9Weight";
	//std::cout<<"Complete selection for MC is "<<selection_MC *weights.Data()<<std::endl;
	//mc->Draw(branchNameMC+">>"+mcHistName+binning, selection_MC *weights.Data());
	mc->Draw(branchNameMC+">>"+mcHistName+binning, selection_MC);
      }
    }


  c->Clear();
  TLegend *leg = new TLegend(0.5,0.7,0.7,0.85);
  leg->SetBorderSize(1);
  leg->SetFillColor(0);
  leg->SetTextSize(0.04);
//   if(dataLabel !="" && mcLabel !="") leg->Draw();
//   //c->GetListOfPrimitives()->Add(leg,"");


  TH1F *d = (TH1F *) gROOT->FindObject("data_hist");
  if(dataLabel !="") leg->AddEntry(d,dataLabel,"p");
  d->SetStats(0);
  d->SetTitle("");

  d->SetMarkerStyle(20);
  d->SetMarkerSize(1);

  if(d->GetEntries()==0 || d->Integral()==0){
    //d=(TH1F *) gROOT->FindObject("0_hist");
    d=(TH1F *) gROOT->FindObject("hist_0");
    d->SetMarkerSize(0);
  }
  //d->SaveAs("tmp/d_hist.root");
  //s->SaveAs("tmp/s_hist.root");

  yLabel.Form("Events /(%.2f %s)", d->GetBinWidth(2), yLabelUnit.Data());
  
  std::cout << "nEvents data: " << d->Integral() << "\t" << d->GetEntries() << std::endl;
  std::cout << "Now normalizing data to 1: "<<std::endl;
  std::cout << "80 is in bin "<<d->FindBin(80)<<std::endl;
  std::cout << "100 is in bin "<<d->FindBin(100)<<std::endl;
  std::cout << "d integral is "<<d->Integral()<<std::endl;
  std::cout << "d integral(1,100) is "<<d->Integral(1,100)<<std::endl;
  d->Scale(1./d->Integral());
  float max = 0;
  max=1.2*d->GetMaximum();
  std::cout << "max = " << max << std::endl;  

  d->GetYaxis()->SetTitle(yLabel);
  d->GetXaxis()->SetTitle(xLabel);
  if(logy){
    max*=10;
    d->GetYaxis()->SetRangeUser(0.1,max);
    c->SetLogy();
  } else {
      d->GetYaxis()->SetRangeUser(0,max);
  }

  for(int i=0; i < nHist; i++){
    //TString mcHistName; mcHistName+=i; mcHistName+="_hist";
    TString mcHistName; mcHistName+="hist_";mcHistName+=i;
    TH1F *s = (TH1F *) gROOT->FindObject(mcHistName);
    s->SetStats(0);
    s->SetTitle("");
    if(s==NULL) continue;
    std::cout << "nEvents signal: " << s->Integral() << "\t" << s->GetEntries() << std::endl;
    if(d->Integral()==0 && s->Integral()==0){
      delete c;
      return NULL;
    }
    if(logy){
      s->GetYaxis()->SetRangeUser(0.1,max);
    } else {
      s->GetYaxis()->SetRangeUser(0,max);
    }
    s->GetYaxis()->SetTitle(yLabel);
    s->GetXaxis()->SetTitle(xLabel);

    s->SetMarkerStyle(20);
    s->SetMarkerSize(1);
    s->SetMarkerColor(colors[i]);
    s->SetFillStyle(fillstyle[i]);
    s->SetFillColor(colors[i]);
    s->SetLineColor(colors[i]);
    s->SetLineWidth(2);

    TH1F* s_norm = NULL;
    if(i==0) s_norm = (TH1F *) (s->DrawNormalized("hist", d->Integral()));
    else s_norm = (TH1F *) (s->DrawNormalized("hist same", d->Integral()));
    if(logy){
      //d_norm->GetYaxis()->SetRangeUser(0.1,max);
      s_norm->GetYaxis()->SetRangeUser(0.1,max);
    } else {
      //d_norm->GetYaxis()->SetRangeUser(0,max);  
      s_norm->GetYaxis()->SetRangeUser(0,max);  
    }

    if(mcLabel_vec[i] !="") leg->AddEntry(s,mcLabel_vec[i], "lf");

//     TH1F *sRatio = (TH1F *) s->Clone(mcHistName+"_ratio");
//     sRatio->Divide(d);
//     if(ratio){
//       pad2->cd();
//       if(i==0) sRatio->Draw();
//       else sRatio->Draw("same");
//     }
//     pad1->cd();
  }

  //TH1F* d_norm = s_norm;
  //if(d!=s) d_norm = (TH1F *) (d->DrawNormalized("p same", d->Integral()));
  std::cout<<"After normalization "<<std::endl;
  //std::cout<<"s_norm" <<s_norm->Integral()<<std::endl;
  std::cout<<"data Integral " <<d->Integral()<<std::endl;
  if(nHist>0) d->Draw("p same");
  else d->Draw("p");

//   std::cout << "Variable  & Data & Simulation \\" << std::endl;
//   std::cout << "Mean      & " << d->GetMean() << " " << d->GetMeanError() 
// 	    << " & " << s_norm->GetMean() <<  " " << s_norm->GetMeanError() << " \\" << std::endl;
//   std::cout << "Std. dev. & " << d->GetRMS() << " " << d->GetRMSError() 
// 	    << " & " << s_norm->GetRMS() << " " << s_norm->GetRMSError() << " \\" << std::endl;
//   std::cout << "\\hline" << std::endl;
//   std::cout << "$\\Chi^2$ " <<  d->Chi2Test(s_norm, "UW CHI2/NDF NORM") << std::endl;
  
  if(mcLabel_vec.size()!=0) leg->Draw();

  TPaveText *pv = new TPaveText(0.25,0.95,0.65,1,"NDC");
  pv->AddText("CMS Preliminary 2016");
  pv->SetFillColor(0);
  pv->SetBorderSize(0);
  pv->Draw();

  watch.Stop();
  watch.Print();

  c->SaveAs(outputPath+label4Print+".png","png");
  c->SaveAs(outputPath+label4Print+".pdf","pdf");
  c->SaveAs(outputPath+label4Print+".eps","eps");
  c->SaveAs(outputPath+label4Print+".C","C");

  return c;

}
Esempio n. 9
0
void plotpurity()
{

 Bool_t dolines = kFALSE;
 //Bool_t dolines = kTRUE;
 TString lines = "";

 TString xn = "";
 //TString xn = "_onlyQCD";
 //TString xn = "_onlyGJ";
 //TString xn = "_denominator";
 if(dolines){lines="/lines";}

 std::vector<TString> rebins;
 rebins.push_back("");
// rebins.push_back("rebin1");
// rebins.push_back("rebin2");
// rebins.push_back("rebin3");
// rebins.push_back("rebin4");
// rebins.push_back("rebin5");

 std::vector<TString> ptranges;
// ptranges.push_back("90to120");
// ptranges.push_back("120to155");
// ptranges.push_back("155to175");
 ptranges.push_back("175to190");
 ptranges.push_back("190to250");
 ptranges.push_back("250to400");
 ptranges.push_back("400to700");
 ptranges.push_back("700to1000");
 ptranges.push_back("175to1000");
 //ptranges.push_back("250to1000");
 //ptranges.push_back("400to1000");

 std::vector<TString> isovars;
 //isovars.push_back("wchiso");
 isovars.push_back("chiso");
// isovars.push_back("sieieF5x5");
// isovars.push_back("sieipF5x5");
// isovars.push_back("sipipF5x5");
// isovars.push_back("rho");
// isovars.push_back("nVtx");
// isovars.push_back("phoet");
// isovars.push_back("pfMET");

 std::vector<TString> cuts;
 cuts.push_back("a_idnc");
 cuts.push_back("b_idnc_mL30");
 cuts.push_back("c_idnc_trig");
 cuts.push_back("d_idnc_mL30_trig");
 cuts.push_back("e_idnc_t175");
 cuts.push_back("f_idnc_mL30_t175");
 cuts.push_back("g_idnc_t250");
 cuts.push_back("h_idnc_mL30_t250");
 cuts.push_back("i_idnc_mL30_allt");
// cuts.push_back("oldj");

 TString inpath = "/afs/hep.wisc.edu/cms/tperry/LoneG_slc6_491_CMSSW_7_4_14/src/LoneGamma/qcdStudy/gitignore/Lire/analyzed";
 TString outpath = "/afs/hep.wisc.edu/cms/tperry/LoneG_slc6_491_CMSSW_7_4_14/src/LoneGamma/qcdStudy/gitignore/Lire/plots";
 TString wwwpath = "/afs/hep.wisc.edu/home/tperry/www/MonoPhoton/qcdPlots/Lire/purity";

 TString inname_GJ  = inpath+"/purity_GJets_Merged.root";
 TString inname_QCD = inpath+"/purity_QCD_Merged.root";
// TString inname_GJ  = inpath+"/purity_mrg4bins_GJets.root";
// TString inname_QCD = inpath+"/purity_mrg4bins_QCD.root";
 //TString inname_GJ  = inpath+"/purity_mrg3bins_GJets.root";
 //TString inname_QCD = inpath+"/purity_mrg3bins_QCD.root";
 
 TFile *infile_GJ  = new TFile(inname_GJ);
 TFile *infile_QCD = new TFile(inname_QCD);
 
 ofstream log;
 ofstream log_latex;
 log.open (outpath+"/Purity_log"+xn+".txt");
 log_latex.open (outpath+"/Purity_log_latex"+xn+".txt");

 Int_t fillcolor = 3;
 gStyle->SetOptStat(0);
 gStyle->SetOptTitle(0);
 gStyle->SetFrameLineWidth(3);
 gStyle->SetLineWidth(2);

 TCanvas* canvas = new TCanvas("canvas","canvas",900,100,500,500);
 gStyle->SetOptStat(0);
 gPad->SetTickx();
 gPad->SetTicky();
 gStyle->SetLineWidth(3);


 TText* title = new TText(1,1,"") ;
 title->SetTextSize(0.07);
 title->SetTextColor(kBlack);
 title->SetTextAlign(13);
 title->SetTextFont(62);

 TText* extra = new TText(1,1,"") ;
 extra->SetTextSize(0.05);
 extra->SetTextColor(kBlack);
 extra->SetTextAlign(13);
 extra->SetTextFont(52);

 TText* lumi = new TText(1,1,"") ;
 lumi->SetTextSize(0.05);
 lumi->SetTextColor(kBlack);
 lumi->SetTextAlign(31);
 lumi->SetTextFont(42);

 int c_sig = 4;
 int c_bkg = 2;
 int c_den = 8;
 int ls_cmb = 1;
 int ls_gj  = 2;
 int ls_qcd = 3;

 //for(std::vector<TString>::iterator it = ptranges.begin(); it != ptranges.end(); ++it) {
 for(unsigned i=0; i<ptranges.size(); i++) {
  for(unsigned j=0; j<isovars.size(); j++) {
   for(unsigned k=0; k<cuts.size(); k++) {
    for(unsigned l=0; l<rebins.size(); l++) {

     TString ptrange = ptranges.at(i);
     TString isovar = isovars.at(j);
     TString cut = cuts.at(k);
     TString rebin = rebins.at(l);

     TString cutname;
     if(cut=="idnc"){cutname="ID";}
     if(cut=="idnc_mL30"){cutname="ID+MET";}
     if(cut=="idnc_trig"){cutname="ID+Trigger";}
     if(cut=="idnc_mL30_trig"){cutname="ID+MET+Trigger";}

     TString bwidth;
     if(rebin=="rebin1"){bwidth="width=0.5";}
     if(rebin=="rebin2"){bwidth="width=1.0";}
     if(rebin=="rebin3"){bwidth="width=1.5";}
     if(rebin=="rebin4"){bwidth="width=2.0";}
     if(rebin=="rebin5"){bwidth="width=2.5";}

     std::cout<<boost::format("%8s %15s %7s %7s ") % ptrange % cut % isovar % rebin<<std::endl;

     //Signal purity
     TH1F* h_Nsig_GJ  = (TH1F*)infile_GJ->Get("h_Nsig_"+isovar+"_"+ptrange+"_"+cut);
     TH1F* h_Nsig_QCD = (TH1F*)infile_QCD->Get("h_Nsig_"+isovar+"_"+ptrange+"_"+cut);
     h_Nsig_GJ->Rebin(3); h_Nsig_QCD->Rebin(3); //h_Nsig_GJ->Rebin(l+1); h_Nsig_QCD->Rebin(l+1);
             //TH1F* h_Nsig  = (TH1F*)h_Nsig_QCD->Clone("h_Nsig");
     TH1F* h_Nsig  = (TH1F*)h_Nsig_GJ->Clone("h_Nsig");
     h_Nsig->Add(h_Nsig_QCD);
     h_Nsig->SetLineColor(c_sig); h_Nsig_GJ->SetLineColor(c_sig); h_Nsig_QCD->SetLineColor(c_sig);
     h_Nsig->SetLineStyle(ls_cmb); h_Nsig_GJ->SetLineStyle(ls_gj); h_Nsig_QCD->SetLineStyle(ls_qcd);
     h_Nsig->SetLineWidth(2); h_Nsig_GJ->SetLineWidth(2); h_Nsig_QCD->SetLineWidth(2);
     //Background purity
     TH1F* h_Nbkg_GJ  = (TH1F*)infile_GJ->Get("h_Nbkg_"+isovar+"_"+ptrange+"_"+cut);
     TH1F* h_Nbkg_QCD = (TH1F*)infile_QCD->Get("h_Nbkg_"+isovar+"_"+ptrange+"_"+cut);
     h_Nbkg_GJ->Rebin(3); h_Nbkg_QCD->Rebin(3);
             //TH1F* h_Nbkg  = (TH1F*)h_Nbkg_QCD->Clone("h_Nbkg");
     TH1F* h_Nbkg  = (TH1F*)h_Nbkg_GJ->Clone("h_Nbkg");
     h_Nbkg->Add(h_Nbkg_QCD);
     h_Nbkg->SetLineColor(c_bkg); h_Nbkg_GJ->SetLineColor(c_bkg); h_Nbkg_QCD->SetLineColor(c_bkg);
     h_Nbkg->SetLineStyle(ls_cmb); h_Nbkg_GJ->SetLineStyle(ls_gj); h_Nbkg_QCD->SetLineStyle(ls_qcd);
     h_Nbkg->SetLineWidth(2); h_Nbkg_GJ->SetLineWidth(2); h_Nbkg_QCD->SetLineWidth(2);

     //Denominator
     TH1F* h_Deno_GJ  = (TH1F*)h_Nsig_GJ->Clone("h_Deno_GJ");
     h_Deno_GJ->Add(h_Nbkg_GJ);

     TH1F* h_Deno_QCD  = (TH1F*)h_Nsig_QCD->Clone("h_Deno_QCD");
     h_Deno_QCD->Add(h_Nbkg_QCD);

//     TH1F* h_Deno_GJ  = (TH1F*)infile_GJ->Get("h_Deno_"+isovar+"_"+ptrange+"_"+cut);
//     TH1F* h_Deno_QCD = (TH1F*)infile_QCD->Get("h_Deno_"+isovar+"_"+ptrange+"_"+cut);
//     h_Deno_GJ->Rebin(3); h_Deno_QCD->Rebin(3);
//             //TH1F* h_Deno  = (TH1F*)h_Deno_QCD->Clone("h_Deno");
     TH1F* h_Deno  = (TH1F*)h_Deno_GJ->Clone("h_Deno");
     h_Deno->Add(h_Deno_QCD);

     h_Deno->SetLineColor(c_den); h_Deno_GJ->SetLineColor(c_den); h_Deno_QCD->SetLineColor(c_den);
     h_Deno->SetLineStyle(ls_cmb); h_Deno_GJ->SetLineStyle(ls_gj); h_Deno_QCD->SetLineStyle(ls_qcd);
     h_Deno->SetLineWidth(1); h_Deno_GJ->SetLineWidth(1); h_Deno_QCD->SetLineWidth(1);

     // should probably add these as last bin..
     h_Nsig->ClearUnderflowAndOverflow();
     h_Nbkg->ClearUnderflowAndOverflow();
     h_Deno->ClearUnderflowAndOverflow();
     
     //Define purity
     TGraphAsymmErrors *purity_signal     = new TGraphAsymmErrors(h_Nsig,h_Deno,"n");
     purity_signal->SetLineWidth(2);
     purity_signal->SetLineColor(4);
     purity_signal->SetMarkerColor(4);
     purity_signal->SetMarkerStyle(20);
     
     TGraphAsymmErrors *purity_background = new TGraphAsymmErrors(h_Nbkg,h_Deno,"n");
     purity_background->SetLineWidth(2);
     purity_background->SetLineColor(2);
     purity_background->SetMarkerColor(2);
     purity_background->SetMarkerStyle(24);

     //-----------------------------------------------------
     // Calculations
     log<<boost::format("%8s %15s %7s %7s ") % ptrange % cut % isovar % rebin  ;

     // Start lower bound calculation
     Int_t nbins;
     nbins = purity_background->GetN();
     log<<boost::format("(%2i bins) \n") % nbins ; 

     std::vector<Double_t> thresholds, xsatthresh, ysatthresh, xsatqt, avgpur;
     std::vector<Int_t> batthresh, batqt;

     thresholds.clear(); // purity thresholds
     xsatthresh.clear(); // x st. f(x) > thresh
     ysatthresh.clear(); // y = f(x)x at thresh
     batthresh.clear();  // bin corresponding to x

     batqt.clear();      // bin at upper threshold
     xsatqt.clear();     // x value at upper thresh

     avgpur.clear();     // average purity over range

     thresholds.push_back(0.50);
     thresholds.push_back(0.55);
     thresholds.push_back(0.60);
     thresholds.push_back(0.65);
     thresholds.push_back(0.70);
     Int_t nthreshs;
     nthreshs = thresholds.size();

     // find purity lower bounds = x st. f(x)>thresh
     Double_t pointx, pointy;     
     for(int m=0; m<nbins; ++m){
      purity_background->GetPoint(m, pointx, pointy);
      //log<<boost::format(" %2i %2.2f %2.2f \n") % i % pointx % pointy;
      
      for(int n=0; n<nthreshs; ++n){
       if(pointy > thresholds.at(n) && ysatthresh.size()==n ){
        ysatthresh.push_back(pointy);
        xsatthresh.push_back(pointx);
        batthresh.push_back(h_Nsig->FindBin(pointx));
       }
      }
     }

     // for thresholds never reached, fill with content of xmax
     purity_background->GetPoint(nbins-1,pointx,pointy);
     Int_t nrnpassthresh = 0;
     nrnpassthresh = nthreshs - ysatthresh.size();
     for(int n=0; n<nrnpassthresh; ++n){
       ysatthresh.push_back(pointy);
       xsatthresh.push_back(pointx);
       batthresh.push_back(h_Nsig->FindBin(pointx));
     }

     //// dump lower bound threshold info
     //for(int n=0; n<nthreshs; ++n){
     // log<<boost::format("  Threshold: %.2f  %2i (%2.2f, %0.2f)\n")
     //  % thresholds.at(n) % batthresh.at(n) % xsatthresh.at(n) % ysatthresh.at(n) ;
     //}

     log<<boost::format("   Threshold bin (xx.x,yy.y) TotalSize   above|below\n");
     // Start upper bound calculation
     Double_t fullsize = h_Nbkg->Integral(0,-1);
     for(int n=0; n<nthreshs; ++n){
      Double_t sizedown = h_Nbkg->Integral(0,batthresh.at(n)-1);
      Double_t sizeup =   h_Nbkg->Integral(batthresh.at(n),-1);
      log<<boost::format("    %7.2f %3i (%2.1f,%1.2f)    %4.1f  %6.1f|%6.1f \n")
       % thresholds.at(n) % batthresh.at(n) % xsatthresh.at(n) % ysatthresh.at(n)    
       % fullsize % sizeup % sizedown ;
     }

     // upper bound calculation 
     // keep adding contents of bins starting at threshbin 
      // until sum > fraction (1/4) of full integral
     Double_t goalsize = fullsize / 4.;

     for(int n=0; n<nthreshs; ++n){
      Double_t thissize = 0.;
      int thisbin = batthresh.at(n);
      while( thisbin < nbins+1 ){
       thissize += h_Nbkg->GetBinContent(thisbin); 
       if(thissize > goalsize){
        break;
        }
       thisbin++;
      }
      batqt.push_back(thisbin);
      xsatqt.push_back(h_Nbkg->GetBinCenter(thisbin));
     }

    log<<"       Target Eventcount: "<<goalsize<<" = fullsize/4 = "<<fullsize<<"/4 \n";
     log<<boost::format("   Threshold blo bhi (xlo,xhi) Int(blo,bhi) Int(blo,bhi+1) Int(blo,bhi-1)\n");

    // find average purity over range
    // must weight each purity bin by nr. events in bin
    for(int n=0; n<nthreshs; ++n){
     int nbins = batqt.at(n) - batthresh.at(n);
     //std::cout<<nbins<<" "<<batthresh.at(n)<<" "<<batqt.at(n)<<std::endl;
     Double_t sumpurs, sumweights;
     sumpurs = 0.;
     sumweights = 0.;
     for(int o=0; o<nbins+1; ++o){
      int thisbin = batthresh.at(n) + o;
      int thispoint = thisbin - 1;  // bin nr = point nr + 1
      purity_background->GetPoint(thispoint, pointx,pointy);
      sumpurs += pointy*h_Nbkg->GetBinContent(thisbin);
      sumweights += h_Nbkg->GetBinContent(thisbin);
      //std::cout<<" "<<thispoint<<"|"<<pointy<<"|"<<h_Nbkg->GetBinContent(thisbin)<<" "<<std::endl;;
     }
     //std::cout<<std::endl;
     //std::cout<<sumpurs/sumweights<<std::endl<<std::endl;;
     avgpur.push_back( sumpurs/sumweights );
    }
     log_latex<<"\\begin{tabular}{r|r|r|r|r|r|r|r}\n";
     log_latex<<boost::format("\\multicolumn{2}{c|}{%8s} & \\multicolumn{2}{c|}{%15s} & \\multicolumn{2}{c|}{%7s} & \\multicolumn{2}{c|}{%7s} \\\\ \\hline \\hline  \n") % ptrange % cutname % isovar % bwidth  ;
     log_latex<<boost::format("   %10s & %5s & %5s & %10s & %5s & %8s & %15s & %10s  \\\\  \\hline \n")
      % "Threshold" 
      % "x lo" % "x hi" 
      % "avg purity"
      % "err \\%" 
      % "evts. tot." 
      % "evts. > x lo" 
      % "evts in rng." ;

     ///log_latex<<"\\begin{tabular}{r|r|r|r|r}\n";
     ///log_latex<<boost::format("%8s & \\multicolumn{2}{c}{%15s} & %7s & %7s \\\\  \n \\hline \\hline \n") % ptrange % cutname % isovar % bwidth  ;
     ///log_latex<<boost::format("   %10s & %5s & %5s & %10s & %5s \\\\ \n \\hline \n")
     /// % "Threshold" 
     /// % "x lo" % "x hi" 
     /// % "avg purity"
     /// % "err \\%" ;
    for(int n=0; n<nthreshs; ++n){
     log<<boost::format("    %7.2f %3i %3i (%2.1f,%1.2f) %10.2f %10.2f %10.2f  \n")
      % thresholds.at(n) % batthresh.at(n) %batqt.at(n)
      % xsatthresh.at(n) % xsatqt.at(n) 
      % h_Nbkg->Integral(batthresh.at(n),batqt.at(n))
      % h_Nbkg->Integral(batthresh.at(n),batqt.at(n)+1)
      % h_Nbkg->Integral(batthresh.at(n),batqt.at(n)-1) ;

     Double_t nrevents, errevents, pcterr;
     nrevents = h_Nbkg->IntegralAndError(batthresh.at(n),batqt.at(n),errevents);
     pcterr = errevents/nrevents;
     log_latex<<boost::format("   %10.2f & %5.2f & %5.2f & %10.4f &  %5.2f &  %8.1f & %15.1f & %10.1f  \\\\  \n")
      % thresholds.at(n) 
      % h_Nbkg->GetBinLowEdge(h_Nbkg->FindBin(xsatthresh.at(n))) % h_Nbkg->GetBinLowEdge(h_Nbkg->FindBin(xsatqt.at(n) ))
      //% xsatthresh.at(n) % xsatqt.at(n) 
      % avgpur.at(n)
      % (pcterr*100) 
      % fullsize 
      % h_Nbkg->Integral(batthresh.at(n),-1)
      % h_Nbkg->Integral(batthresh.at(n),batqt.at(n));

     ///log_latex<<boost::format("   %10.2f & %5.2f & %5.2f & %7.3f &  %5.2f  \\\\  \n")
     /// % thresholds.at(n) 
     /// % xsatthresh.at(n) % xsatqt.at(n) 
     /// % avgpur.at(n)
     /// % (pcterr*100) ;
    }
     log_latex<<"\\hline \n  \\end{tabular}\n";

     //-----------------------------------------------------
     // all set, now to start thinking about plotting
     //Make lower bound lines (purity)
     Double_t frac = 1./nthreshs;
     TLine *lgb_lo0 = new TLine(xsatthresh.at(0), 0*frac, xsatthresh.at(0), 1*frac);
     TLine *lgb_lo1 = new TLine(xsatthresh.at(1), 1*frac, xsatthresh.at(1), 2*frac);
     TLine *lgb_lo2 = new TLine(xsatthresh.at(2), 2*frac, xsatthresh.at(2), 3*frac);
     TLine *lgb_lo3 = new TLine(xsatthresh.at(3), 3*frac, xsatthresh.at(3), 4*frac);
     TLine *lgb_lo4 = new TLine(xsatthresh.at(4), 4*frac, xsatthresh.at(4), 5*frac);
     TLine *lgc_lo0 = new TLine(xsatthresh.at(0), 0*frac, xsatthresh.at(0), 1*frac);
     TLine *lgc_lo1 = new TLine(xsatthresh.at(1), 1*frac, xsatthresh.at(1), 2*frac);
     TLine *lgc_lo2 = new TLine(xsatthresh.at(2), 2*frac, xsatthresh.at(2), 3*frac);
     TLine *lgc_lo3 = new TLine(xsatthresh.at(3), 3*frac, xsatthresh.at(3), 4*frac);
     TLine *lgc_lo4 = new TLine(xsatthresh.at(4), 4*frac, xsatthresh.at(4), 5*frac);

     lgb_lo0->SetLineColor(1);
     lgb_lo1->SetLineColor(1);
     lgb_lo2->SetLineColor(1);
     lgb_lo3->SetLineColor(1);
     lgb_lo4->SetLineColor(1);
     lgc_lo0->SetLineColor(2);
     lgc_lo1->SetLineColor(3);
     lgc_lo2->SetLineColor(4);
     lgc_lo3->SetLineColor(5);
     lgc_lo4->SetLineColor(6);

     lgb_lo0->SetLineWidth(4);
     lgb_lo1->SetLineWidth(4);
     lgb_lo2->SetLineWidth(4);
     lgb_lo3->SetLineWidth(4);
     lgb_lo4->SetLineWidth(4);
     lgc_lo0->SetLineWidth(2);
     lgc_lo1->SetLineWidth(2);
     lgc_lo2->SetLineWidth(2);
     lgc_lo3->SetLineWidth(2);
     lgc_lo4->SetLineWidth(2);

     //Make upper bound lines (purity)
     TLine *lgb_hi0 = new TLine(xsatqt.at(0), 0*frac, xsatqt.at(0), 1*frac);
     TLine *lgb_hi1 = new TLine(xsatqt.at(1), 1*frac, xsatqt.at(1), 2*frac);
     TLine *lgb_hi2 = new TLine(xsatqt.at(2), 2*frac, xsatqt.at(2), 3*frac);
     TLine *lgb_hi3 = new TLine(xsatqt.at(3), 3*frac, xsatqt.at(3), 4*frac);
     TLine *lgb_hi4 = new TLine(xsatqt.at(4), 4*frac, xsatqt.at(4), 5*frac);
     TLine *lgc_hi0 = new TLine(xsatqt.at(0), 0*frac, xsatqt.at(0), 1*frac);
     TLine *lgc_hi1 = new TLine(xsatqt.at(1), 1*frac, xsatqt.at(1), 2*frac);
     TLine *lgc_hi2 = new TLine(xsatqt.at(2), 2*frac, xsatqt.at(2), 3*frac);
     TLine *lgc_hi3 = new TLine(xsatqt.at(3), 3*frac, xsatqt.at(3), 4*frac);
     TLine *lgc_hi4 = new TLine(xsatqt.at(4), 4*frac, xsatqt.at(4), 5*frac);

     lgb_hi0->SetLineColor(1);
     lgb_hi1->SetLineColor(1);
     lgb_hi2->SetLineColor(1);
     lgb_hi3->SetLineColor(1);
     lgb_hi4->SetLineColor(1);
     lgc_hi0->SetLineColor(2);
     lgc_hi1->SetLineColor(3);
     lgc_hi2->SetLineColor(4);
     lgc_hi3->SetLineColor(5);
     lgc_hi4->SetLineColor(6);

     lgb_hi0->SetLineWidth(4);
     lgb_hi1->SetLineWidth(4);
     lgb_hi2->SetLineWidth(4);
     lgb_hi3->SetLineWidth(4);
     lgb_hi4->SetLineWidth(4);
     lgc_hi0->SetLineWidth(2);
     lgc_hi1->SetLineWidth(2);
     lgc_hi2->SetLineWidth(2);
     lgc_hi3->SetLineWidth(2);
     lgc_hi4->SetLineWidth(2);

     lgc_hi0->SetLineStyle(2);
     lgc_hi1->SetLineStyle(2);
     lgc_hi2->SetLineStyle(2);
     lgc_hi3->SetLineStyle(2);
     lgc_hi4->SetLineStyle(2);

     //Make avg purity horizontal lines
     TLine *lgb_pur0 = new TLine(xsatthresh.at(0), avgpur.at(0), xsatqt.at(0), avgpur.at(0));
     TLine *lgb_pur1 = new TLine(xsatthresh.at(1), avgpur.at(1), xsatqt.at(1), avgpur.at(1));
     TLine *lgb_pur2 = new TLine(xsatthresh.at(2), avgpur.at(2), xsatqt.at(2), avgpur.at(2));
     TLine *lgb_pur3 = new TLine(xsatthresh.at(3), avgpur.at(3), xsatqt.at(3), avgpur.at(3));
     TLine *lgb_pur4 = new TLine(xsatthresh.at(4), avgpur.at(4), xsatqt.at(4), avgpur.at(4));
     TLine *lgc_pur0 = new TLine(xsatthresh.at(0), avgpur.at(0), xsatqt.at(0), avgpur.at(0));
     TLine *lgc_pur1 = new TLine(xsatthresh.at(1), avgpur.at(1), xsatqt.at(1), avgpur.at(1));
     TLine *lgc_pur2 = new TLine(xsatthresh.at(2), avgpur.at(2), xsatqt.at(2), avgpur.at(2));
     TLine *lgc_pur3 = new TLine(xsatthresh.at(3), avgpur.at(3), xsatqt.at(3), avgpur.at(3));
     TLine *lgc_pur4 = new TLine(xsatthresh.at(4), avgpur.at(4), xsatqt.at(4), avgpur.at(4));

     lgb_pur0->SetLineColor(1);
     lgb_pur1->SetLineColor(1);
     lgb_pur2->SetLineColor(1);
     lgb_pur3->SetLineColor(1);
     lgb_pur4->SetLineColor(1);
     //lgb_pur0->SetLineColor(2);
     //lgb_pur1->SetLineColor(3);
     //lgb_pur2->SetLineColor(4);
     //lgb_pur3->SetLineColor(5);
     //lgb_pur4->SetLineColor(6);
     lgc_pur0->SetLineColor(2);
     lgc_pur1->SetLineColor(3);
     lgc_pur2->SetLineColor(4);
     lgc_pur3->SetLineColor(5);
     lgc_pur4->SetLineColor(6);

     lgb_pur0->SetLineWidth(4);
     lgb_pur1->SetLineWidth(4);
     lgb_pur2->SetLineWidth(4);
     lgb_pur3->SetLineWidth(4);
     lgb_pur4->SetLineWidth(4);
     lgc_pur0->SetLineWidth(2);
     lgc_pur1->SetLineWidth(2);
     lgc_pur2->SetLineWidth(2);
     lgc_pur3->SetLineWidth(2);
     lgc_pur4->SetLineWidth(2);

     //lgc_pur0->SetLineStyle(2);
     //lgc_pur1->SetLineStyle(2);
     //lgc_pur2->SetLineStyle(2);
     //lgc_pur3->SetLineStyle(2);
     //lgc_pur4->SetLineStyle(2);

     //-----------------------------------------------------
     Double_t themax = 0 ;
     themax = std::max(themax, h_Nsig->GetMaximum());
     themax = std::max(themax, h_Nbkg->GetMaximum());
     themax = std::max(themax, h_Deno->GetMaximum());

     //Make lower bound lines (hist)
     Double_t logmax;
     Double_t logmin;
     logmax = std::log(themax);
     logmin = std::log(1);
     Double_t spacing = (logmax-logmin)/nthreshs;
     //std::cout<<spacing<<std::endl;

     //Double_t fifmax = themax/5.;
     TLine *lhb_lo0 = new TLine(xsatthresh.at(0), exp(logmin+0*spacing), xsatthresh.at(0), exp(logmin+1*spacing));
     TLine *lhb_lo1 = new TLine(xsatthresh.at(1), exp(logmin+1*spacing), xsatthresh.at(1), exp(logmin+2*spacing));
     TLine *lhb_lo2 = new TLine(xsatthresh.at(2), exp(logmin+2*spacing), xsatthresh.at(2), exp(logmin+3*spacing));
     TLine *lhb_lo3 = new TLine(xsatthresh.at(3), exp(logmin+3*spacing), xsatthresh.at(3), exp(logmin+4*spacing));
     TLine *lhb_lo4 = new TLine(xsatthresh.at(4), exp(logmin+4*spacing), xsatthresh.at(4), exp(logmin+5*spacing));
     TLine *lhc_lo0 = new TLine(xsatthresh.at(0), exp(logmin+0*spacing), xsatthresh.at(0), exp(logmin+1*spacing));
     TLine *lhc_lo1 = new TLine(xsatthresh.at(1), exp(logmin+1*spacing), xsatthresh.at(1), exp(logmin+2*spacing));
     TLine *lhc_lo2 = new TLine(xsatthresh.at(2), exp(logmin+2*spacing), xsatthresh.at(2), exp(logmin+3*spacing));
     TLine *lhc_lo3 = new TLine(xsatthresh.at(3), exp(logmin+3*spacing), xsatthresh.at(3), exp(logmin+4*spacing));
     TLine *lhc_lo4 = new TLine(xsatthresh.at(4), exp(logmin+4*spacing), xsatthresh.at(4), exp(logmin+5*spacing));

     lhb_lo0->SetLineColor(1);
     lhb_lo1->SetLineColor(1);
     lhb_lo2->SetLineColor(1);
     lhb_lo3->SetLineColor(1);
     lhb_lo4->SetLineColor(1);
     lhc_lo0->SetLineColor(2);
     lhc_lo1->SetLineColor(3);
     lhc_lo2->SetLineColor(4);
     lhc_lo3->SetLineColor(5);
     lhc_lo4->SetLineColor(6);

     lhb_lo0->SetLineWidth(4);
     lhb_lo1->SetLineWidth(4);
     lhb_lo2->SetLineWidth(4);
     lhb_lo3->SetLineWidth(4);
     lhb_lo4->SetLineWidth(4);
     lhc_lo0->SetLineWidth(2);
     lhc_lo1->SetLineWidth(2);
     lhc_lo2->SetLineWidth(2);
     lhc_lo3->SetLineWidth(2);
     lhc_lo4->SetLineWidth(2);

     //Make upper bound lines (hist)
     TLine *lhb_hi0 = new TLine(xsatqt.at(0), exp(logmin+0*spacing), xsatqt.at(0), exp(logmin+1*spacing));
     TLine *lhb_hi1 = new TLine(xsatqt.at(1), exp(logmin+1*spacing), xsatqt.at(1), exp(logmin+2*spacing));
     TLine *lhb_hi2 = new TLine(xsatqt.at(2), exp(logmin+2*spacing), xsatqt.at(2), exp(logmin+3*spacing));
     TLine *lhb_hi3 = new TLine(xsatqt.at(3), exp(logmin+3*spacing), xsatqt.at(3), exp(logmin+4*spacing));
     TLine *lhb_hi4 = new TLine(xsatqt.at(4), exp(logmin+4*spacing), xsatqt.at(4), exp(logmin+5*spacing));
     TLine *lhc_hi0 = new TLine(xsatqt.at(0), exp(logmin+0*spacing), xsatqt.at(0), exp(logmin+1*spacing));
     TLine *lhc_hi1 = new TLine(xsatqt.at(1), exp(logmin+1*spacing), xsatqt.at(1), exp(logmin+2*spacing));
     TLine *lhc_hi2 = new TLine(xsatqt.at(2), exp(logmin+2*spacing), xsatqt.at(2), exp(logmin+3*spacing));
     TLine *lhc_hi3 = new TLine(xsatqt.at(3), exp(logmin+3*spacing), xsatqt.at(3), exp(logmin+4*spacing));
     TLine *lhc_hi4 = new TLine(xsatqt.at(4), exp(logmin+4*spacing), xsatqt.at(4), exp(logmin+5*spacing));

     lhb_hi0->SetLineColor(1);
     lhb_hi1->SetLineColor(1);
     lhb_hi2->SetLineColor(1);
     lhb_hi3->SetLineColor(1);
     lhb_hi4->SetLineColor(1);
     lhc_hi0->SetLineColor(2);
     lhc_hi1->SetLineColor(3);
     lhc_hi2->SetLineColor(4);
     lhc_hi3->SetLineColor(5);
     lhc_hi4->SetLineColor(6);

     lhb_hi0->SetLineWidth(4);
     lhb_hi1->SetLineWidth(4);
     lhb_hi2->SetLineWidth(4);
     lhb_hi3->SetLineWidth(4);
     lhb_hi4->SetLineWidth(4);
     lhc_hi0->SetLineWidth(2);
     lhc_hi1->SetLineWidth(2);
     lhc_hi2->SetLineWidth(2);
     lhc_hi3->SetLineWidth(2);
     lhc_hi4->SetLineWidth(2);

     lhc_hi0->SetLineStyle(2);
     lhc_hi1->SetLineStyle(2);
     lhc_hi2->SetLineStyle(2);
     lhc_hi3->SetLineStyle(2);
     lhc_hi4->SetLineStyle(2);
     //-----------------------------------------------------


     //-----------------------------------------------------
     //Draw Histograms
     TLegend *meg = new TLegend(0.4,0.6,0.88,0.88);
     //meg->SetTextSize(0.04) ;
     meg->SetFillColor(0); meg->SetShadowColor(0);meg->SetBorderSize(2);
     meg->SetTextFont(22.);
     meg->AddEntry(h_Nsig,"Signal","l");
     meg->AddEntry(h_Nsig_GJ,"Signal (GJ MC)","l");
     meg->AddEntry(h_Nsig_QCD,"Signal (QCD MC)","l");
     meg->AddEntry(h_Nbkg,"Background","l");
     meg->AddEntry(h_Nbkg_GJ,"Background (GJ MC)","l");
     meg->AddEntry(h_Nbkg_QCD,"Background (QCD MC)","l");
     meg->AddEntry(h_Deno,"Denominator","l");
     meg->AddEntry(h_Deno_GJ,"Denominator (GJ MC)","l");
     meg->AddEntry(h_Deno_QCD,"Denominator (QCD MC)","l");
     
     TString leg_h0;  leg_h0.Form("Purity > %0.2f (%2.1f-%2.1f)", thresholds.at(0), xsatthresh.at(0), xsatqt.at(0));
     TString leg_h1;  leg_h1.Form("Purity > %0.2f (%2.1f-%2.1f)", thresholds.at(1), xsatthresh.at(1), xsatqt.at(1));
     TString leg_h2;  leg_h2.Form("Purity > %0.2f (%2.1f-%2.1f)", thresholds.at(2), xsatthresh.at(2), xsatqt.at(2));
     TString leg_h3;  leg_h3.Form("Purity > %0.2f (%2.1f-%2.1f)", thresholds.at(3), xsatthresh.at(3), xsatqt.at(3));
     TString leg_h4;  leg_h4.Form("Purity > %0.2f (%2.1f-%2.1f)", thresholds.at(4), xsatthresh.at(4), xsatqt.at(4));

     TLegend *neg = new TLegend(0.15,0.5,0.4,0.75);
     //meg->SetTextSize(0.04) ;
     neg->SetFillColor(0); neg->SetShadowColor(0);neg->SetBorderSize(2);
     neg->SetTextFont(22.);
     neg->AddEntry(lhc_lo0,leg_h0,"l");
     neg->AddEntry(lhc_lo1,leg_h1,"l");
     neg->AddEntry(lhc_lo2,leg_h2,"l");
     neg->AddEntry(lhc_lo3,leg_h3,"l");
     neg->AddEntry(lhc_lo4,leg_h4,"l");

     h_Nsig->SetTitle(cut);
     h_Nsig->SetXTitle(h_Nsig->GetTitle());
     h_Nsig->SetYTitle("Events ");
     h_Nsig->SetMaximum(1000*themax);
     h_Nsig->SetMinimum(1);

     h_Nsig->Draw("hist");
     h_Nsig_GJ->Draw("hist,same");
     h_Nsig_QCD->Draw("hist,same");
     h_Nbkg->Draw("hist,same");
     h_Nbkg_GJ->Draw("hist,same");
     h_Nbkg_QCD->Draw("hist,same");
     h_Deno->Draw("hist,same");
     h_Deno_GJ->Draw("hist,same");
     h_Deno_QCD->Draw("hist,same");

     meg->SetHeader("photon p_{T}: "+ptrange);
     meg->Draw();
     if(dolines){
      neg->Draw();
     }
     title->DrawTextNDC(0.17,0.87,"CMS");
     extra->DrawTextNDC(0.17,0.81,"Preliminary");
     lumi->DrawTextNDC(0.9,0.91,"2.32 /fb (13 TeV)");

     if(dolines){
      lhb_lo0->Draw();
      lhb_lo1->Draw();
      lhb_lo2->Draw();
      lhb_lo3->Draw();
      lhb_lo4->Draw();
      
      lhb_hi0->Draw();
      lhb_hi1->Draw();
      lhb_hi2->Draw();
      lhb_hi3->Draw();
      lhb_hi4->Draw();

      lhc_lo0->Draw();
      lhc_lo1->Draw();
      lhc_lo2->Draw();
      lhc_lo3->Draw();
      lhc_lo4->Draw();
      
      lhc_hi0->Draw();
      lhc_hi1->Draw();
      lhc_hi2->Draw();
      lhc_hi3->Draw();
      lhc_hi4->Draw();
     }

     gPad->SetLogy();

     canvas->SaveAs(outpath+"/Histos_"+isovar+"_"+ptrange+"_"+cut+rebin+xn+".pdf");
     canvas->SaveAs(wwwpath+"/pdf/"+ptrange+"/"+isovar+"/"+cut+lines+"/Histos_"+isovar+"_"+ptrange+"_"+cut+rebin+xn+".pdf");
     canvas->SaveAs(wwwpath+"/png/"+ptrange+"/"+isovar+"/"+cut+lines+"/Histos_"+isovar+"_"+ptrange+"_"+cut+rebin+xn+".png");
     canvas->Clear();
     gPad->SetLogy(kFALSE);
     //-----------------------------------------------------
     //-----------------------------------------------------
     //Draw Purity
     TLegend *leg = new TLegend(0.5,0.75,0.88,0.88);
     leg->SetTextSize(0.04) ;
     leg->SetFillColor(0); leg->SetShadowColor(0);leg->SetBorderSize(0);
     leg->SetTextFont(22.);
     leg->AddEntry(purity_signal,"Signal","lep");
     leg->AddEntry(purity_background,"Background","lep");

     float xmin ; //= 0.;
     float xmax ; //= 25.;
     xmin = h_Nsig->GetXaxis()->GetXmin();
     xmax = h_Nsig->GetXaxis()->GetXmax();
     TLine *lowline = new TLine(xmin,0,xmax,0);
     TLine *hiline = new TLine(xmin,1,xmax,1);
     lowline->SetLineWidth(1); lowline->SetLineColor(1); lowline->SetLineStyle(3);         
     hiline->SetLineWidth(1); hiline->SetLineColor(1); hiline->SetLineStyle(3);         

     TH1F *hframe = canvas->DrawFrame(xmin,-0.05,xmax,1.4,"");
     lowline->Draw();
     hiline->Draw();
     title->DrawTextNDC(0.17,0.87,"CMS");
     extra->DrawTextNDC(0.17,0.81,"Preliminary");
     lumi->DrawTextNDC(0.9,0.91,"2.32 /fb (13 TeV)");
     hframe->SetTitle(cut);
     hframe->SetXTitle(isovar);
     hframe->SetYTitle("Purity");
     
     // draw points
     purity_signal->Draw("P");
     purity_background->Draw("P");
     leg->SetHeader("photon p_{T}: "+ptrange);
     leg->Draw();

     //canvas->SaveAs(outpath+"/Purity_"+isovar+"_"+ptrange+"_"+cut+"_"+rebin+xn+".pdf");

     if(dolines){
      lgb_lo0->Draw();
      lgb_lo1->Draw();
      lgb_lo2->Draw();
      lgb_lo3->Draw();
      lgb_lo4->Draw();
      
      lgb_hi0->Draw();
      lgb_hi1->Draw();
      lgb_hi2->Draw();
      lgb_hi3->Draw();
      lgb_hi4->Draw();
      
      lgc_lo0->Draw();
      lgc_lo1->Draw();
      lgc_lo2->Draw();
      lgc_lo3->Draw();
      lgc_lo4->Draw();
      
      lgc_hi0->Draw();
      lgc_hi1->Draw();
      lgc_hi2->Draw();
      lgc_hi3->Draw();
      lgc_hi4->Draw();

      lgb_pur0->Draw();
      lgb_pur1->Draw();
      lgb_pur2->Draw();
      lgb_pur3->Draw();
      lgb_pur4->Draw();
      lgc_pur0->Draw();
      lgc_pur1->Draw();
      lgc_pur2->Draw();
      lgc_pur3->Draw();
      lgc_pur4->Draw();
     }
     
     canvas->SaveAs(outpath+"/Purity_"+isovar+"_"+ptrange+"_"+cut+rebin+xn+".pdf");
     canvas->SaveAs(wwwpath+"/pdf/"+ptrange+"/"+isovar+"/"+cut+lines+"/Purity_"+isovar+"_"+ptrange+"_"+cut+rebin+xn+".pdf");
     canvas->SaveAs(wwwpath+"/png/"+ptrange+"/"+isovar+"/"+cut+lines+"/Purity_"+isovar+"_"+ptrange+"_"+cut+rebin+xn+".png");

     canvas->Clear();
     //-----------------------------------------------------

     // clean your room!
     h_Nsig->Delete();
     h_Nsig_GJ->Delete();
     h_Nsig_QCD->Delete();
     h_Nbkg->Delete();
     h_Nbkg_GJ->Delete();
     h_Nbkg_QCD->Delete();
     h_Deno->Delete();
     h_Deno_GJ->Delete();
     h_Deno_QCD->Delete();
    }
   log<<"--------------------------------------\n";
   log_latex<<"--------------------------------------\n";
   }
  }
 }
 log.close();
 log_latex.close();
}
Esempio n. 10
0
TCanvas *PlotDataMC(TChain *data, TChain *mc, TString branchname, TString binning, 
		    TString category, TString selection, 
		    TString dataLabel, TString mcLabel, TString xLabel, TString yLabelUnit, 
		    bool logy=false, bool usePU=true, bool smear=false, bool scale=false){
  
  TString yLabel; 
  std::cout<<"entering"<<std::endl;
  
  TCanvas *c = new TCanvas("c","");
  TString branchNameData=branchname;
  TString branchNameMC=branchname;

  ElectronCategory_class cutter;

  std::cout<<"entering2"<<std::endl;

  TCut selection_data="";
  if(category.Sizeof()>1) selection_data = cutter.GetCut(category, false,0,true);
  selection_data.Print();
  //  return NULL;
  selection_data+=selection;
  TCut selection_MC="";
  if(category.Sizeof()>1) selection_MC = cutter.GetCut(category, false,0);
  selection_MC+=selection;

  std::cout<<"qui"<<std::endl;

  if(smear){
    branchNameMC.ReplaceAll("invMass_SC_regrCorr_pho ","(invMass_SC_regrCorr_pho*sqrt(smearEle[0]*smearEle[1]))");
    branchNameMC.ReplaceAll("energySCEle_regrCorr_pho ","(energySCEle_regrCorr_pho*smearEle) ");
    branchNameMC.ReplaceAll("energySCEle_regrCorr_pho[0]","(energySCEle_regrCorr_pho[0]*smearEle[0])");
    branchNameMC.ReplaceAll("energySCEle_regrCorr_pho[1]","(energySCEle_regrCorr_pho[1]*smearEle[1])");

  }
  if(scale){
    branchNameData.ReplaceAll("invMass_SC_regrCorr_pho ","(invMass_SC_regrCorr_pho*sqrt(corrEle[0]*corrEle[1]))");
    branchNameData.ReplaceAll("energySCEle_regrCorr_pho ","(energySCEle_regrCorr_pho*corrEle)");
    branchNameData.ReplaceAll("energySCEle_regrCorr_pho[0]","(energySCEle_regrCorr_pho[0]*corrEle[0])");
    branchNameData.ReplaceAll("energySCEle_regrCorr_pho[1]","(energySCEle_regrCorr_pho[1]*corrEle[1])");
    branchNameData.ReplaceAll("energySCEle_regrCorr_ele ","(energySCEle_regrCorr_ele*corrEle)");
    branchNameData.ReplaceAll("energySCEle_regrCorr_ele[0]","(energySCEle_regrCorr_ele[0]*corrEle[0])");
    branchNameData.ReplaceAll("energySCEle_regrCorr_ele[1]","(energySCEle_regrCorr_ele[1]*corrEle[1])");

  }
  //std::cout << branchNameData << "\t" << branchNameMC << std::endl;


  if(branchname=="HLT"){
    TH1F *hlt_data = new TH1F("data_hist","",500,0,500);
    TH1F *hlt_mc = new TH1F("mc_hist","",500,0,500);
    
    
    std::vector< std::string > *HLTNames = new std::vector<std::string>; ///< List of HLT names
    std::vector<Bool_t> *HLTResults = new std::vector<Bool_t>;      ///< 0=fail, 1=fire
    
    data->SetBranchAddress("HLTNames", &HLTNames);
    data->SetBranchAddress("HLTResults", &HLTResults);
    
    data->GetEntries();
    for(Long64_t jentry=0; jentry < data->GetEntriesFast(); jentry++){
      data->GetEntry(jentry);
      std::vector<Bool_t>::const_iterator hltRes_itr=HLTResults->begin();
      for(std::vector<std::string>::const_iterator hlt_itr=HLTNames->begin();
	  hlt_itr!=HLTNames->end();
	  hlt_itr++,hltRes_itr++){
	std::cout << *hlt_itr << std::endl;
	hlt_data->Fill(hlt_itr-HLTNames->begin(),*hltRes_itr);
      }
    }
    data->ResetBranchAddresses();

    mc->SetBranchAddress("HLTNames", &HLTNames);
    mc->SetBranchAddress("HLTResults", &HLTResults);
    
    mc->GetEntries();
    for(Long64_t jentry=0; jentry < mc->GetEntriesFast(); jentry++){
      mc->GetEntry(jentry);
      std::vector<Bool_t>::const_iterator hltRes_itr=HLTResults->begin();
      for(std::vector<std::string>::const_iterator hlt_itr=HLTNames->begin();
	  hlt_itr!=HLTNames->end();
	  hlt_itr++,hltRes_itr++){
	std::cout << *hlt_itr << std::endl;
	hlt_mc->Fill(hlt_itr-HLTNames->begin(),*hltRes_itr);
      }
    }

    for(std::vector<std::string>::const_iterator hlt_itr=HLTNames->begin();
	hlt_itr!=HLTNames->end();
	hlt_itr++){
      int index=hlt_itr-HLTNames->begin()+1;
      if(hlt_mc->GetBinContent(index)>0)
      hlt_mc->GetXaxis()->SetBinLabel(index,(*hlt_itr).c_str());
    }
  } else {

  std::cout<<"qui"<<std::endl;
    data->Draw(branchNameData+">>data_hist"+binning, selection_data);
    if(mc!=NULL){
      if(usePU)  mc->Draw(branchNameMC+">>mc_hist"+binning, selection_MC *"puWeight");
    else  mc->Draw(branchNameMC+">>mc_hist"+binning, selection_MC);
  std::cout<<"qui"<<std::endl;
    }
  }

  c->Clear();
  TH1F *d = (TH1F *) gROOT->FindObject("data_hist");
  TH1F *s = (TH1F *) gROOT->FindObject("mc_hist");
  if(s==NULL) s=d;
  //d->SaveAs("tmp/d_hist.root");
  s->SaveAs("tmp/s_hist.root");
  std::cout<<"qui"<<std::endl;

  yLabel.Form("Events /(%.2f %s)", s->GetBinWidth(2), yLabelUnit.Data());
  float max = 1.1 * std::max(
			     d->GetMaximum(),///d->Integral(),
			     s->GetMaximum() ///s->Integral()
			     );
  max=1.1*d->GetMaximum();
  std::cout << "max = " << max << std::endl;
  std::cout << "nEvents data: " << d->Integral() << "\t" << d->GetEntries() << std::endl;
  std::cout << "nEvents signal: " << s->Integral() << "\t" << s->GetEntries() << std::endl;
  if(logy){
    max*=10;
    d->GetYaxis()->SetRangeUser(0.1,max);
    s->GetYaxis()->SetRangeUser(0.1,max);
    c->SetLogy();
  } else {
    d->GetYaxis()->SetRangeUser(0,max);
    s->GetYaxis()->SetRangeUser(0,max);
  }
  s->GetYaxis()->SetTitle(yLabel);
  s->GetXaxis()->SetTitle(xLabel);
  d->GetYaxis()->SetTitle(yLabel);
  d->GetXaxis()->SetTitle(xLabel);


  d->SetMarkerStyle(20);
  d->SetMarkerSize(1);
  if(d != s){
    s->SetMarkerStyle(20);
    s->SetMarkerSize(1);
    s->SetFillStyle(3001);
    s->SetFillColor(kRed);
  }

  TH1F* s_norm = (TH1F *) (s->DrawNormalized("hist", d->Integral()));
  //TH1F* d_norm = s_norm;
  //if(d!=s) d_norm = (TH1F *) (d->DrawNormalized("p same", d->Integral()));
  if(d!=s) d->Draw("p same");

  if(logy){
    //d_norm->GetYaxis()->SetRangeUser(0.1,max);
    s_norm->GetYaxis()->SetRangeUser(0.1,max);
    c->SetLogy();
  } else {
    //d_norm->GetYaxis()->SetRangeUser(0,max);  
    s_norm->GetYaxis()->SetRangeUser(0,max);  
  }
  std::cout << "Variable  & Data & Simulation \\" << std::endl;
  std::cout << "Mean      & " << d->GetMean() << " " << d->GetMeanError() 
	    << " & " << s_norm->GetMean() <<  " " << s_norm->GetMeanError() << " \\" << std::endl;
  std::cout << "Std. dev. & " << d->GetRMS() << " " << d->GetRMSError() 
	    << " & " << s_norm->GetRMS() << " " << s_norm->GetRMSError() << " \\" << std::endl;
  std::cout << "\\hline" << std::endl;
  std::cout << "$\\Chi^2$ " <<  d->Chi2Test(s_norm, "UW CHI2/NDF NORM") << std::endl;
  

  TLegend *leg = new TLegend(0.6,0.8,1,1);
  if(dataLabel !="") leg->AddEntry(d,dataLabel,"p");
  if(mcLabel   !="") leg->AddEntry(s,mcLabel, "lf");
  leg->SetBorderSize(1);
  leg->SetFillColor(0);
  leg->SetTextSize(0.04);
  if(dataLabel !="" && mcLabel !="") leg->Draw();
  //c->GetListOfPrimitives()->Add(leg,"");

  TPaveText *pv = new TPaveText(0.2,0.95,0.7,1,"NDC");
  pv->AddText("CMS Preliminary 2016");
  pv->SetFillColor(0);
  pv->SetBorderSize(0);
  pv->Draw();


  return c;

}
Esempio n. 11
0
TCanvas *PlotDataMCMC(TChain *data, TChain *mc, TChain *mc2,
		      TString branchname, TString binning, 
		      TString category, TString selection, 
		      TString dataLabel, TString mcLabel, TString mc2Label,
		      TString xLabel, TString yLabelUnit, 
		      bool logy=false, bool usePU=true, bool smear=false, bool scale=false){
  
  TString yLabel; 
  
  TCanvas *c = new TCanvas("c","");
  TString branchNameData=branchname;
  TString branchNameMC=branchname;

  ElectronCategory_class cutter;
  TCut selection_data="";
  if(category.Sizeof()>1) selection_data = cutter.GetCut(category, false,0);
  selection_data+=selection;
  TCut selection_MC="";
  if(category.Sizeof()>1) selection_MC = cutter.GetCut(category, true,0);
  selection_MC+=selection;

  if(smear){
    branchNameMC.ReplaceAll("invMass_SC_regrCorr_pho ","(invMass_SC_regrCorr_pho*sqrt(smearEle[0]*smearEle[1]))");
    branchNameMC.ReplaceAll("energySCEle_regrCorr_pho ","(energySCEle_regrCorr_pho*smearEle) ");
    branchNameMC.ReplaceAll("energySCEle_regrCorr_pho[0]","(energySCEle_regrCorr_pho[0]*smearEle[0])");
    branchNameMC.ReplaceAll("energySCEle_regrCorr_pho[1]","(energySCEle_regrCorr_pho[1]*smearEle[1])");

  }
  if(scale){
    branchNameData.ReplaceAll("invMass_SC_regrCorr_pho ","(invMass_SC_regrCorr_pho*sqrt(corrEle[0]*corrEle[1]))");
    branchNameData.ReplaceAll("energySCEle_regrCorr_pho ","(energySCEle_regrCorr_pho*corrEle)");
    branchNameData.ReplaceAll("energySCEle_regrCorr_pho[0]","(energySCEle_regrCorr_pho[0]*corrEle[0])");
    branchNameData.ReplaceAll("energySCEle_regrCorr_pho[1]","(energySCEle_regrCorr_pho[1]*corrEle[1])");
  }
  //std::cout << branchNameData << "\t" << branchNameMC << std::endl;


  data->Draw(branchNameData+">>data_hist"+binning, selection_data);
  if(mc!=NULL){
    if(usePU)  mc->Draw(branchNameMC+">>mc_hist"+binning, selection_MC *"puWeight");
    else  mc->Draw(branchNameMC+">>mc_hist"+binning, selection_MC);
  }
  if(mc2!=NULL){
    if(usePU)  mc2->Draw(branchNameMC+">>mc2_hist"+binning, selection_data *"puWeight");
    else  mc2->Draw(branchNameMC+">>mc2_hist"+binning, selection_data);
  }
  

  c->Clear();
  TH1F *d = (TH1F *) gROOT->FindObject("data_hist");
  TH1F *s = (TH1F *) gROOT->FindObject("mc_hist");
  TH1F *s2 = (TH1F *) gROOT->FindObject("mc2_hist");
  if(s==NULL){
    std::cerr << "[WARNING] no mc" << std::endl;
    s=d;
  }
  if(s2==NULL){
    std::cerr << "[WARNING] no mc2" << std::endl;
    s2=s;
  }
  std::cout << s->GetEntries() << "\t" << s2->GetEntries() << "\t" << d->GetEntries() << std::endl;

  //d->SaveAs("tmp/d_hist.root");
  s->SaveAs("tmp/s_hist.root");
  s2->SaveAs("tmp/s2_hist.root");


  yLabel.Form("Events /(%.2f %s)", s->GetBinWidth(2), yLabelUnit.Data());
  float max = 1.1 * std::max(
			     d->GetMaximum(),///d->Integral(),
			     s->GetMaximum() ///s->Integral()
			     );
  max=1.1*d->GetMaximum();
  std::cout << "max = " << max << std::endl;
  std::cout << "nEvents data: " << d->Integral() << "\t" << d->GetEntries() << std::endl;
  std::cout << "nEvents signal: " << s->Integral() << "\t" << s->GetEntries() << std::endl;
  std::cout << "nEvents signal2: " << s2->Integral() << "\t" << s2->GetEntries() << std::endl;
  if(logy){
    max*=10;
    d->GetYaxis()->SetRangeUser(0.1,max);
    s->GetYaxis()->SetRangeUser(0.1,max);
    s2->GetYaxis()->SetRangeUser(0.1,max);
    c->SetLogy();
  } else {
    d->GetYaxis()->SetRangeUser(0,max);
    s->GetYaxis()->SetRangeUser(0,max);
    s2->GetYaxis()->SetRangeUser(0,max);
  }
  s->GetYaxis()->SetTitle(yLabel);
  s->GetXaxis()->SetTitle(xLabel);
  s2->GetYaxis()->SetTitle(yLabel);
  s2->GetXaxis()->SetTitle(xLabel);
  d->GetYaxis()->SetTitle(yLabel);
  d->GetXaxis()->SetTitle(xLabel);


  d->SetMarkerStyle(20);
  d->SetMarkerSize(1);
  if(d != s){
    s->SetMarkerStyle(20);
    s->SetMarkerSize(1);
    s->SetFillStyle(3001);
    s->SetFillColor(kRed);
  }
  if(s2 != s){
    //s2->SetMarkerStyle(1);
    //s2->SetMarkerSize(0);
    //s->SetFillStyle(0);
    //s->SetFillColor(kB);
    s2->SetLineWidth(3);
    s2->SetLineColor(kBlack);
  }


  TH1F* s_norm = (TH1F *) (s->DrawNormalized("hist", d->Integral()));
  TH1F* s2_norm = (TH1F *) (s2->DrawNormalized("hist same", d->Integral()));
  //TH1F* d_norm = s_norm;
  //if(d!=s) d_norm = (TH1F *) (d->DrawNormalized("p same", d->Integral()));
  if(d!=s) d->Draw("p same");

  if(logy){
    //d_norm->GetYaxis()->SetRangeUser(0.1,max);
    s_norm->GetYaxis()->SetRangeUser(0.1,max);
    c->SetLogy();
  } else {
    //d_norm->GetYaxis()->SetRangeUser(0,max);  
    s_norm->GetYaxis()->SetRangeUser(0,max);  
  }
  std::cout << "Variable  & Data & Simulation & Simulation2 \\" << std::endl;
  std::cout << "Mean      & " << d->GetMean() << " " << d->GetMeanError() 
	    << " & " << s_norm->GetMean() <<  " " << s_norm->GetMeanError() 
	    << " & " << s2_norm->GetMean() <<  " " << s2_norm->GetMeanError() 
	    << " \\" << std::endl;
  std::cout << "Std. dev. & " << d->GetRMS() << " " << d->GetRMSError() 
	    << " & " << s_norm->GetRMS() << " " << s_norm->GetRMSError() 
	    << " & " << s2_norm->GetRMS() << " " << s2_norm->GetRMSError() 
	    << " \\" << std::endl;
  std::cout << "\\hline" << std::endl;
  std::cout << "$\\Chi^2$ " <<  d->Chi2Test(s_norm, "UW CHI2/NDF NORM") << std::endl;
  

  TLegend *leg = new TLegend(0.6,0.8,1,1);
  if(dataLabel !="") leg->AddEntry(d,dataLabel,"p");
  if(mcLabel   !="") leg->AddEntry(s,mcLabel, "lf");
  if(mc2Label   !="") leg->AddEntry(s2,mc2Label, "l");
  leg->SetBorderSize(1);
  leg->SetFillColor(0);
  leg->SetTextSize(0.04);
  if(dataLabel !="" && mcLabel !="") leg->Draw();
  //c->GetListOfPrimitives()->Add(leg,"");

  TPaveText *pv = new TPaveText(0.23,0.95,0.6,1,"NDC");
  pv->AddText("CMS Preliminary 2016");
  pv->SetFillColor(0);
  pv->SetBorderSize(0);
  pv->Draw();


  return c;

}
Esempio n. 12
0
void MakePlots(TString filename, TString energy="8TeV", TString lumi=""){
  TString outDir=filename; outDir.ReplaceAll("fitres","img");
  outDir="tmp/";
  //std::map<TString, TH2F *> deltaNLL_map;
  
  /*------------------------------ Plotto */
  TCanvas *c = new TCanvas("c","c");
  
  TFile f_in(filename, "read");
  if(f_in.IsZombie()){
    std::cerr << "File opening error: " << filename << std::endl;
    return;
  }
  
  TList *KeyList = f_in.GetListOfKeys();
  std::cout << KeyList->GetEntries() << std::endl;
  for(int i =0; i <  KeyList->GetEntries(); i++){
    c->Clear();
    TKey *key = (TKey *)KeyList->At(i);
    if(TString(key->GetClassName())!="RooDataSet") continue;
    RooDataSet *dataset = (RooDataSet *) key->ReadObj();
    
    TString constTermName = dataset->GetName();
    TString alphaName=constTermName; alphaName.ReplaceAll("constTerm","alpha");

    TTree *tree = dataset2tree(dataset);
    TGraphErrors bestFit_ = bestFit(tree, alphaName, constTermName);
    TH2F *hist = prof2d(tree, alphaName, constTermName, "nll", "(12,-0.0005,0.0115,29,-0.0025,0.1425)",true);

//     //    deltaNLL_map.insert(std::pair <TString, TH2F *>(keyName,hist));
    hist->SaveAs(outDir+"/deltaNLL-"+constTermName+".root");
    hist->Draw("colz");
    bestFit_.Draw("P same");
    bestFit_.SetMarkerSize(2);

    Int_t iBinX, iBinY;
    Double_t x,y;
    hist->GetBinWithContent2(0,iBinX,iBinY);
    x= hist->GetXaxis()->GetBinCenter(iBinX);
    y= hist->GetYaxis()->GetBinCenter(iBinY);
    TGraph nllBestFit(1,&x,&y);

    nllBestFit.SetMarkerStyle(3);
    nllBestFit.SetMarkerColor(kRed);
    TList* contour68 = contourFromTH2(hist, 0.68);

    hist->Draw("colz");
    hist->GetZaxis()->SetRangeUser(0,50);
    bestFit_.Draw("P same");
    nllBestFit.Draw("P same");
    //contour68->Draw("same");
    c->SaveAs(outDir+"/deltaNLL-"+constTermName+".png");
    hist->SaveAs("tmp/hist-"+constTermName+".root");
    nllBestFit.SaveAs("tmp/nllBestFit.root");
    contour68->SaveAs("tmp/contour68.root");
    delete hist;
    hist = prof2d(tree, alphaName, constTermName, "nll", "(12,-0.0005,0.0115,29,-0.0025,0.1425)");
    RooHistPdf *histPdf = nllToL(hist);
    delete hist;
    RooDataSet *gen_dataset=histPdf->generate(*histPdf->getVariables(),1000000,kTRUE,kFALSE);
    TTree *genTree = dataset2tree(gen_dataset);
    genTree->SaveAs("tmp/genTree-"+constTermName+".root");
    delete gen_dataset;
    delete histPdf;
    
    TGraphErrors toyGraph = g(genTree, constTermName);
    TGraphErrors bestFitGraph = g(tree,alphaName, constTermName);
    TGraphErrors bestFitScanGraph = g(y, x);
    delete genTree;
    delete tree;
    toyGraph.SetFillColor(kGreen);
    toyGraph.SetLineColor(kBlue);
    toyGraph.SetLineStyle(2);
    bestFitGraph.SetLineColor(kBlack);
    bestFitScanGraph.SetLineColor(kRed);
    bestFitScanGraph.SetLineWidth(2);


    
    TMultiGraph g_multi("multigraph","");
    g_multi.Add(&toyGraph,"L3");
    g_multi.Add(&toyGraph,"L");
    g_multi.Add(&bestFitGraph, "L");
    g_multi.Add(&bestFitScanGraph, "L");
   
    g_multi.Draw("A");

    c->Clear();
    g_multi.Draw("A");
    c->SaveAs(outDir+"/smearing_vs_energy-"+constTermName+".png");

    //    TPaveText *pv = new TPaveText(0.7,0.7,1, 0.8);    
//     TLegend *legend = new TLegend(0.7,0.8,0.95,0.92);
//     legend->SetFillStyle(3001);
//     legend->SetFillColor(1);
//     legend->SetTextFont(22); // 132
//     legend->SetTextSize(0.04); // l'ho preso mettendo i punti con l'editor e poi ho ricavato il valore con il metodo GetTextSize()
//   //  legend->SetFillColor(0); // colore di riempimento bianco
//     legend->SetMargin(0.4);  // percentuale della larghezza del simbolo
    //    SetLegendStyle(legend);
	
    //Plot(c, data,mc,mcSmeared,legend, region, filename, energy, lumi);
  }
  
  f_in.Close();
  
  return;
}
Esempio n. 13
0
   void miplots2sig_18fb( bool doLogy=false ) {

       int fillStyle1sig = 1 ;
       int fillStyle2sig = 1 ;
       int fillColor1sig = kBlue-9 ;
       int fillColor2sig = kBlue-10 ;

       gStyle->SetOptStat(0) ;
       gStyle->SetLabelSize(0.12,"x") ;
       gStyle->SetLabelSize(0.08,"y") ;
       gStyle->SetTitleW(0.8) ;
       gStyle->SetTitleH(0.08) ;
       gStyle->SetTitleAlign(13) ;
       gStyle->SetPadLeftMargin(0.14) ;
       gStyle->SetPadRightMargin(0.02) ;
       gStyle->SetLabelOffset(0.02,"y") ;
       gStyle->SetPadGridY(1) ;

       if ( doLogy ) {
          gStyle->SetOptLogy(1) ;
       } else {
          gStyle->SetOptLogy(0) ;
       }

       gDirectory->Delete("h*") ;

       double xvals[4] = { 1.05, 2.05, 3.05, 4.05 } ;
       double xel[4] = {0.5, 0.5, 0.5, 0.5} ;
       double xeh[4] = {0.5, 0.5, 0.5, 0.5} ;


       TCanvas* cmip = (TCanvas*) gDirectory->FindObject("cmip") ;
       if ( cmip == 0x0 ) {
          cmip = new TCanvas("cmip", "MIP", 800, 600) ;
       }
       cmip->Clear() ;

       cmip->Divide(4,1) ;



    //--------

       cmip->cd(1) ;

       TH1F* h_data_nb2_m4 = new TH1F( "h_data_nb2_m4", "Data, nB=2, MET4", 4, 0.5, 4.5 ) ;

       h_data_nb2_m4 -> GetXaxis() -> SetBinLabel( 1, "HT1" ) ;
       h_data_nb2_m4 -> GetXaxis() -> SetBinLabel( 2, "HT2" ) ;
       h_data_nb2_m4 -> GetXaxis() -> SetBinLabel( 3, "HT3" ) ;
       h_data_nb2_m4 -> GetXaxis() -> SetBinLabel( 4, "HT4" ) ;

       h_data_nb2_m4 -> SetBinContent( 1, 0 ) ;
       h_data_nb2_m4 -> SetBinContent( 2, 57 ) ;
       h_data_nb2_m4 -> SetBinContent( 3, 17 ) ;
       h_data_nb2_m4 -> SetBinContent( 4, 19 ) ;

       h_data_nb2_m4 -> SetMarkerStyle(20) ;
       h_data_nb2_m4 -> SetMarkerSize(1.2) ;
       h_data_nb2_m4 -> SetLineWidth(2) ;
       if ( doLogy) h_data_nb2_m4 -> SetMinimum( 10 ) ;
       h_data_nb2_m4 -> SetMaximum( 100 ) ;


       h_data_nb2_m4 -> Draw("e") ;


       double nb2_m4_yvals[4] = { -99., 72.2, 20.0, 18.4 } ;
       double nb2_m4_yerrh[4] = { 0.0, 10.0, 4.4, 4.7 } ;
       double nb2_m4_yerrl[4] = { 0.0, 9.0, 3.8, 3.8 } ;
       double nb2_m4_yerrh_2s[4] = { 0.0, 21.3, 9.6, 10.5 } ;
       double nb2_m4_yerrl_2s[4] = { 0.0, 17.0, 7.0, 6.9 } ;

       TGraphAsymmErrors* gr_nb2_m4 = new TGraphAsymmErrors( 4, xvals, nb2_m4_yvals, xel, xeh,
            nb2_m4_yerrl, nb2_m4_yerrh ) ;

       TGraphAsymmErrors* gr_nb2_m4_2s = new TGraphAsymmErrors( 4, xvals, nb2_m4_yvals, xel, xeh,
            nb2_m4_yerrl_2s, nb2_m4_yerrh_2s ) ;

       gr_nb2_m4 -> SetFillStyle(fillStyle1sig) ;
       gr_nb2_m4 -> SetFillColor(fillColor1sig) ;
       gr_nb2_m4 -> SetLineColor(4) ;
       gr_nb2_m4 -> SetLineWidth(1) ;
       gr_nb2_m4 -> SetMarkerColor(4) ;
       //gr_nb2_m4 -> SetMarkerStyle(24) ;

       gr_nb2_m4_2s -> SetFillStyle(fillStyle2sig) ;
       gr_nb2_m4_2s -> SetFillColor(fillColor2sig) ;
       gr_nb2_m4_2s -> SetLineColor(4) ;
       gr_nb2_m4_2s -> SetMarkerColor(4) ;
       //gr_nb2_m4_2s -> SetMarkerStyle(24) ;

       gr_nb2_m4_2s -> Draw("p2") ;
       gr_nb2_m4_2s -> Draw("p") ;
       gr_nb2_m4 -> Draw("p2") ;
       gr_nb2_m4 -> Draw("p") ;
       h_data_nb2_m4 -> Draw("same e") ;



    //--------

       cmip->cd(2) ;

       TH1F* h_data_nb3_m2 = new TH1F( "h_data_nb3_m2", "Data, nB=3, MET2", 4, 0.5, 4.5 ) ;

       h_data_nb3_m2 -> GetXaxis() -> SetBinLabel( 1, "HT1" ) ;
       h_data_nb3_m2 -> GetXaxis() -> SetBinLabel( 2, "HT2" ) ;
       h_data_nb3_m2 -> GetXaxis() -> SetBinLabel( 3, "HT3" ) ;
       h_data_nb3_m2 -> GetXaxis() -> SetBinLabel( 4, "HT4" ) ;

       h_data_nb3_m2 -> SetBinContent( 1, 149 ) ;
       h_data_nb3_m2 -> SetBinContent( 2, 168 ) ;
       h_data_nb3_m2 -> SetBinContent( 3, 16 ) ;
       h_data_nb3_m2 -> SetBinContent( 4, 14 ) ;

       h_data_nb3_m2 -> SetMarkerStyle(20) ;
       h_data_nb3_m2 -> SetMarkerSize(1.2) ;
       h_data_nb3_m2 -> SetLineWidth(2) ;
       if ( doLogy) h_data_nb3_m2 -> SetMinimum( 4 ) ;
       h_data_nb3_m2 -> SetMaximum( 370 ) ;


       h_data_nb3_m2 -> Draw("e") ;


       double nb3_m2_yvals[4] = { 106.7, 147.3, 25.3, 9.8 } ;
       double nb3_m2_yerrh[4] = { 27, 59, 7.4, 3.6  } ;
       double nb3_m2_yerrl[4] = { 18, 32, 5.9, 2.8} ;
       double nb3_m2_yerrh_2s[4] = { 82, 193, 17, 8.0 } ;
       double nb3_m2_yerrl_2s[4] = { 33, 56, 11, 4.9 } ;

       TGraphAsymmErrors* gr_nb3_m2 = new TGraphAsymmErrors( 4, xvals, nb3_m2_yvals, xel, xeh,
            nb3_m2_yerrl, nb3_m2_yerrh ) ;

       TGraphAsymmErrors* gr_nb3_m2_2s = new TGraphAsymmErrors( 4, xvals, nb3_m2_yvals, xel, xeh,
            nb3_m2_yerrl_2s, nb3_m2_yerrh_2s ) ;


       gr_nb3_m2 -> SetFillStyle(fillStyle1sig) ;
       gr_nb3_m2 -> SetFillColor(fillColor1sig) ;
       gr_nb3_m2 -> SetLineColor(4) ;
       gr_nb3_m2 -> SetLineWidth(1) ;
       gr_nb3_m2 -> SetMarkerColor(4) ;
       //gr_nb3_m2 -> SetMarkerStyle(24) ;

       gr_nb3_m2_2s -> SetFillStyle(fillStyle2sig) ;
       gr_nb3_m2_2s -> SetFillColor(fillColor2sig) ;
       gr_nb3_m2_2s -> SetLineColor(4) ;
       gr_nb3_m2_2s -> SetMarkerColor(4) ;
       //gr_nb3_m2_2s -> SetMarkerStyle(24) ;


       gr_nb3_m2_2s -> Draw("p2") ;
       gr_nb3_m2_2s -> Draw("p") ;
       gr_nb3_m2 -> Draw("p2") ;
       gr_nb3_m2 -> Draw("p") ;
       h_data_nb3_m2 -> Draw("same e") ;



    //--------

       cmip->cd(3) ;

       TH1F* h_data_nb3_m3 = new TH1F( "h_data_nb3_m3", "Data, nB=3, MET3", 4, 0.5, 4.5 ) ;

       h_data_nb3_m3 -> GetXaxis() -> SetBinLabel( 1, "HT1" ) ;
       h_data_nb3_m3 -> GetXaxis() -> SetBinLabel( 2, "HT2" ) ;
       h_data_nb3_m3 -> GetXaxis() -> SetBinLabel( 3, "HT3" ) ;
       h_data_nb3_m3 -> GetXaxis() -> SetBinLabel( 4, "HT4" ) ;

       h_data_nb3_m3 -> SetBinContent( 1, 13 ) ;
       h_data_nb3_m3 -> SetBinContent( 2, 34 ) ;
       h_data_nb3_m3 -> SetBinContent( 3, 5 ) ;
       h_data_nb3_m3 -> SetBinContent( 4, 4 ) ;

       h_data_nb3_m3 -> SetMarkerStyle(20) ;
       h_data_nb3_m3 -> SetMarkerSize(1.2) ;
       h_data_nb3_m3 -> SetLineWidth(2) ;
       if ( doLogy) h_data_nb3_m3 -> SetMinimum( 0.3 ) ;
       h_data_nb3_m3 -> SetMaximum( 45 ) ;


       h_data_nb3_m3 -> Draw("e") ;


       double nb3_m3_yvals[4] = { 11.3, 23.3, 5.8, 1.9 } ;
       double nb3_m3_yerrh[4] = { 3.6, 6.9, 2.6, 1.6 } ;
       double nb3_m3_yerrl[4] = { 2.8, 5.3, 2.0, 0.9 } ;
       double nb3_m3_yerrh_2s[4] = { 9.1, 16.1, 6.2, 4.2 } ;
       double nb3_m3_yerrl_2s[4] = { 5.1, 9.4, 3.3, 1.4 } ;

       TGraphAsymmErrors* gr_nb3_m3 = new TGraphAsymmErrors( 4, xvals, nb3_m3_yvals, xel, xeh,
            nb3_m3_yerrl, nb3_m3_yerrh ) ;

       TGraphAsymmErrors* gr_nb3_m3_2s = new TGraphAsymmErrors( 4, xvals, nb3_m3_yvals, xel, xeh,
            nb3_m3_yerrl_2s, nb3_m3_yerrh_2s ) ;

       gr_nb3_m3 -> SetFillStyle(fillStyle1sig) ;
       gr_nb3_m3 -> SetFillColor(fillColor1sig) ;
       gr_nb3_m3 -> SetLineColor(4) ;
       gr_nb3_m3 -> SetLineWidth(1) ;
       gr_nb3_m3 -> SetMarkerColor(4) ;
       //gr_nb3_m3 -> SetMarkerStyle(24) ;

       gr_nb3_m3_2s -> SetFillStyle(fillStyle2sig) ;
       gr_nb3_m3_2s -> SetFillColor(fillColor2sig) ;
       gr_nb3_m3_2s -> SetLineColor(4) ;
       gr_nb3_m3_2s -> SetMarkerColor(4) ;
       //gr_nb3_m3_2s -> SetMarkerStyle(24) ;

       gr_nb3_m3_2s -> Draw("p2") ;
       gr_nb3_m3_2s -> Draw("p") ;
       gr_nb3_m3 -> Draw("p2") ;
       gr_nb3_m3 -> Draw("p") ;
       h_data_nb3_m3 -> Draw("same e") ;




    //--------

       cmip->cd(4) ;

       TH1F* h_data_nb3_m4 = new TH1F( "h_data_nb3_m4", "Data, nB=3, MET4", 4, 0.5, 4.5 ) ;

       h_data_nb3_m4 -> GetXaxis() -> SetBinLabel( 1, "HT1" ) ;
       h_data_nb3_m4 -> GetXaxis() -> SetBinLabel( 2, "HT2" ) ;
       h_data_nb3_m4 -> GetXaxis() -> SetBinLabel( 3, "HT3" ) ;
       h_data_nb3_m4 -> GetXaxis() -> SetBinLabel( 4, "HT4" ) ;

       h_data_nb3_m4 -> SetBinContent( 1, 0 ) ;
       h_data_nb3_m4 -> SetBinContent( 2, 8 ) ;
       h_data_nb3_m4 -> SetBinContent( 3, 2 ) ;
       h_data_nb3_m4 -> SetBinContent( 4, 4 ) ;

       h_data_nb3_m4 -> SetMarkerStyle(20) ;
       h_data_nb3_m4 -> SetMarkerSize(1.2) ;
       h_data_nb3_m4 -> SetLineWidth(2) ;
       if ( doLogy) h_data_nb3_m4 -> SetMinimum( 0.1 ) ;
       h_data_nb3_m4 -> SetMaximum( 16 ) ;


       h_data_nb3_m4 -> Draw("e") ;


       double nb3_m4_yvals[4] = { -99., 8.2, 1.6, 0.3 } ;
       double nb3_m4_yerrh[4] = { 0.0, 2.9, 1.2, 0.4 } ;
       double nb3_m4_yerrl[4] = { 0.0, 2.2, 0.7, 0.1 } ;
       double nb3_m4_yerrh_2s[4] = { 0.0, 6.6, 3.1, 1.4 } ;
       double nb3_m4_yerrl_2s[4] = { 0.0, 3.9, 1.1, 0.2 } ;

       TGraphAsymmErrors* gr_nb3_m4 = new TGraphAsymmErrors( 4, xvals, nb3_m4_yvals, xel, xeh,
            nb3_m4_yerrl, nb3_m4_yerrh ) ;

       TGraphAsymmErrors* gr_nb3_m4_2s = new TGraphAsymmErrors( 4, xvals, nb3_m4_yvals, xel, xeh,
            nb3_m4_yerrl_2s, nb3_m4_yerrh_2s ) ;

       gr_nb3_m4 -> SetFillStyle(fillStyle1sig) ;
       gr_nb3_m4 -> SetFillColor(fillColor1sig) ;
       gr_nb3_m4 -> SetLineColor(4) ;
       gr_nb3_m4 -> SetLineWidth(1) ;
       gr_nb3_m4 -> SetMarkerColor(4) ;
       //gr_nb3_m4 -> SetMarkerStyle(24) ;

       gr_nb3_m4_2s -> SetFillStyle(fillStyle2sig) ;
       gr_nb3_m4_2s -> SetFillColor(fillColor2sig) ;
       gr_nb3_m4_2s -> SetLineColor(4) ;
       gr_nb3_m4_2s -> SetMarkerColor(4) ;
       //gr_nb3_m4_2s -> SetMarkerStyle(24) ;

       gr_nb3_m4_2s -> Draw("p2") ;
       gr_nb3_m4_2s -> Draw("p") ;
       gr_nb3_m4 -> Draw("p2") ;
       gr_nb3_m4 -> Draw("p") ;
       h_data_nb3_m4 -> Draw("same e") ;

       cmip->Update() ;
       cmip->Draw() ;

       cmip->SaveAs("outputfiles/fitresult-unbiased-hsbins-18fb.pdf" ) ;


   }
void Plotter(TString plots="2btag", bool LogScale=false, TString cat = "ttbb", TString nSyst = "btagcfI"){
 
  TString files  = "../" + dirnameIn + fl;

  /****************
        Style
  ****************/
  setTDRStyle();
  gROOT->SetStyle("Plain");
  gStyle->SetOptFit(1000);
  gStyle->SetOptStat("emruo");
  gStyle->SetOptStat(kFALSE);
  gStyle->SetPadTickY(1);
  gStyle->SetPadTickX(1);
  
  int col_Nom  = 1;
  int col_Up   = 2;
  int col_Down = 4;
  
  /****************
       Channel
  ****************/
  TString channel[3];
  channel[0] = "mujets";
  channel[1] = "ejets";  
  channel[2] = "lepjet"; 
 
  /****************
    ttbar Signal
  ****************/ 
  std::vector<histos> ttbar_Nom;
  std::vector<histos> ttbar_Up;
  std::vector<histos> ttbar_Down;

  ttbar_Nom  = loadhistogramsSys(plots, files + "_ttbar_LepJetsPowhegPythia" + cat,"central");
  ttbar_Up   = loadhistogramsSys(plots, files + "_ttbar_LepJetsPowhegPythia" + cat, nSyst + "Up");
  ttbar_Down = loadhistogramsSys(plots, files + "_ttbar_LepJetsPowhegPythia" + cat, nSyst + "Down");
  setuphistograms(ttbar_Nom,  col_Nom,   1);
  setuphistograms(ttbar_Up,   col_Up,    2);
  setuphistograms(ttbar_Down, col_Down,  3);

  
  /****************
     Draw Histos
  ****************/ 
  TCanvas *histocanvas;
  histocanvas = new TCanvas("plots", "Plots");

  for(unsigned int h=0; h<ttbar_Nom.size(); h++){
    for(int ch=0; ch<3; ch++){
      
      histocanvas->cd();
      if(LogScale) histocanvas->cd()->SetLogy();

      ttbar_Nom[h].hist[ch]->GetXaxis()->SetRange(ttbar_Nom[h].hist[ch]->GetXaxis()->GetFirst(), 
  						ttbar_Nom[h].hist[ch]->GetXaxis()->GetLast());
      //ttbar_Nom[h].hist[ch]->GetYaxis()->SetTitle("Events");
      ttbar_Nom[h].hist[ch]->GetYaxis()->SetTitleOffset(1.2);
      ttbar_Nom[h].hist[ch]->GetYaxis()->SetTitleSize(0.07);
      ttbar_Nom[h].hist[ch]->GetYaxis()->SetLabelSize(0.055);
      ttbar_Nom[h].hist[ch]->GetYaxis()->SetNdivisions(607);
      //ttbar_Nom[h].hist[ch]->GetYaxis()->SetLabelSize(0.05);
      TGaxis *hYaxis = (TGaxis*)ttbar_Nom[h].hist[ch]->GetYaxis();
      //hYaxis->SetMaxDigits(3);
      //ttbar_Nom[h].hist[ch]->GetXaxis()->SetLabelSize(0.0);
      //ttbar_Nom[h].hist[ch]->GetXaxis()->SetTitle("");
      ttbar_Nom[h].hist[ch]->GetXaxis()->SetNdivisions(509); //(402)
      ttbar_Nom[h].hist[ch]->GetXaxis()->SetTitleOffset(1.1);

      // Produce enough vertical space for the legend 
      float MaxHisto;
      if(LogScale) MaxHisto = 8.0;
      else MaxHisto = 1.4;
            float maxh;
  	    maxh = ttbar_Nom[h].hist[ch]->GetMaximum();
  	    if (maxh < ttbar_Up[h].hist[ch]->GetMaximum()) maxh = ttbar_Up[h].hist[ch]->GetMaximum();
  	    if (maxh < ttbar_Down[h].hist[ch]->GetMaximum()) maxh = ttbar_Down[h].hist[ch]->GetMaximum();
	    
      ttbar_Nom[h].hist[ch]->SetMaximum(MaxHisto*maxh);
      
      //ttbar_Nom[h].hist[ch]->SetMinimum(0.1);
      
      ttbar_Nom[h].hist[ch]->Draw("hist");
      ttbar_Up[h].hist[ch]->Draw("histSAME");
      ttbar_Down[h].hist[ch]->Draw("histSAME");
      

      //ttbar_1[h].hist[ch]->Draw("histoSAME");

      /***********************
             Legends
      ***********************/
      TLegend *leg;
      float legx1=0.70;
      float legy1=0.75;
      float legx2=0.93;
      float legy2=0.93;
      leg = new TLegend(legx1,legy1,legx2,legy2);
      leg->SetFillColor(0);
      leg->SetLineColor(1);
      leg->SetTextFont(62);
      leg->SetTextSize(0.03);

      leg->AddEntry((TObject*)0, cat + ": " + nSyst,"");
      leg->AddEntry((TObject*)0,"","");
      leg->AddEntry(ttbar_Nom[h].hist[ch],"Nom","l");
      leg->AddEntry(ttbar_Up[h].hist[ch],"Up","l");
      leg->AddEntry(ttbar_Down[h].hist[ch],"Down","l");
      //leg->AddEntry((TObject*)0,"","");
      leg->Draw("SAME");

      //-------------------------------------------------------
      // CMS Legend
      //-------------------------------------------------------
      TString htitleCMSChannel[3];
      htitleCMSChannel[0] = "#mu^{#pm}+jets channel";
      htitleCMSChannel[1] = "e^{#pm}+jets channel";
      htitleCMSChannel[2] = "l^{#pm}+jets channel";
      
      TLatex *titlePr;
      titlePr  = new TLatex(-20.,50.,"Preliminary");
      titlePr->SetNDC();
      titlePr->SetTextAlign(12);
      titlePr->SetX(0.25);
      titlePr->SetY(0.97);
      titlePr->SetTextColor(2);
      titlePr->SetTextFont(42);
      titlePr->SetTextSize(0.05);
      titlePr->SetTextSizePixels(24);
      titlePr->Draw("SAME");

      TLatex *title;
      title  = new TLatex(-20.,50.,"CMS #sqrt{s} = 13TeV, L = 36.5 fb^{-1}");
      title->SetNDC();
      title->SetTextAlign(12);
      title->SetX(0.20);
      title->SetY(0.80);
      title->SetTextFont(42);
      title->SetTextSize(0.03);
      title->SetTextSizePixels(24);
      title->Draw("SAME");
      
      TLatex *chtitle;
      chtitle  = new TLatex(-20.,50.,htitleCMSChannel[ch]);
      chtitle->SetNDC();
      chtitle->SetTextAlign(12);
      chtitle->SetX(0.20);
      chtitle->SetY(0.86);
      chtitle->SetTextFont(42);
      chtitle->SetTextSize(0.03);
      chtitle->SetTextSizePixels(24);
      chtitle->Draw("SAME");

            
      /***********************
            Save Histos
      ***********************/    
      TString dirfigname_log;
      if(LogScale) dirfigname_log = "_log";
      else dirfigname_log = "";
      TString dirfigname_pdf;
      TString dirfigname_png;
      dirfigname_pdf = "../" + dirnameIn + "figuresNomUpDown_" + fl + "/ttbbNomUpDown_" + cat + "/pdf" + dirfigname_log + "/";
      //dirfigname_png = dirnameIn + "figuresSystComp_" + fl + "/ttbb/png" + dirfigname_log + "/";
      // make a dir if it does not exist!!
      gSystem->mkdir(dirfigname_pdf,       kTRUE);
      histocanvas->SaveAs(dirfigname_pdf + nSyst + "_" + ttbar_Nom[h].hist[ch]->GetName() + ".pdf");
      //gSystem->mkdir(dirfigname_png,       kTRUE);
      //histocanvas->SaveAs(dirfigname_png + WJets[h].hist[ch]->GetName() + ".png");
      
      // clear Canvas
      histocanvas->Clear();    

    }
  }
  
} //end Plots.C
Esempio n. 15
0
   void mcclosure3( const char* infile = "rootfiles/gi-plots-met4-ht4.root",
                    const char* datfile = "Input-met4-ht4-wsyst1.dat",
                    bool doQCDCorrection = true,
                    bool doQCDSyst = true,
                    bool doTTWJCorrection = true,
                    bool doTTWJSyst = true
                    ) {

      int nBinsMET(0), nBinsHT(0) ;

      TString infileStr( infile ) ;

      gSystem->Exec("mkdir -p outputfiles") ;

      gStyle->SetOptStat(0) ;
      gStyle->SetPadTopMargin(0.03) ;
      gStyle->SetPadBottomMargin(0.30) ;
      gStyle->SetPadRightMargin(0.05) ;
      gStyle->SetPadLeftMargin(0.15) ;
      gStyle->SetTitleX(0.98) ;
      gStyle->SetTitleAlign(33) ;


      gStyle->SetPadGridY(1) ;

      TLine* line = new TLine() ;
      line->SetLineStyle(1) ;
      line->SetLineWidth(2) ;
      line->SetLineColor(2) ;

      gDirectory->Delete("h*") ;

      loadHist( infile ) ;

      TH1F* hmctruth_ttwj_0lep_1b = (TH1F*) gDirectory->FindObject("hmctruth_ttwj_0lep_1b") ;
      if ( hmctruth_ttwj_0lep_1b == 0x0 ) { printf("\n\n\n *** can't find hmctruth_ttwj_0lep_1b.\n\n") ; return ; }
      TH1F* hmctruth_ttwj_1lep_1b = (TH1F*) gDirectory->FindObject("hmctruth_ttwj_1lep_1b") ;
      if ( hmctruth_ttwj_1lep_1b == 0x0 ) { printf("\n\n\n *** can't find hmctruth_ttwj_1lep_1b.\n\n") ; return ; }

      TH1F* hmctruth_ttwj_0over1ratio_1b = (TH1F*) hmctruth_ttwj_0lep_1b->Clone("hmctruth_ttwj_0over1ratio_1b") ;
      hmctruth_ttwj_0over1ratio_1b->Divide( hmctruth_ttwj_1lep_1b ) ;


      TH1F* hmctruth_ttwj_0lep_2b = (TH1F*) gDirectory->FindObject("hmctruth_ttwj_0lep_2b") ;
      if ( hmctruth_ttwj_0lep_2b == 0x0 ) { printf("\n\n\n *** can't find hmctruth_ttwj_0lep_2b.\n\n") ; return ; }
      TH1F* hmctruth_ttwj_1lep_2b = (TH1F*) gDirectory->FindObject("hmctruth_ttwj_1lep_2b") ;
      if ( hmctruth_ttwj_1lep_2b == 0x0 ) { printf("\n\n\n *** can't find hmctruth_ttwj_1lep_2b.\n\n") ; return ; }

      TH1F* hmctruth_ttwj_0over1ratio_2b = (TH1F*) hmctruth_ttwj_0lep_2b->Clone("hmctruth_ttwj_0over1ratio_2b") ;
      hmctruth_ttwj_0over1ratio_2b->Divide( hmctruth_ttwj_1lep_2b ) ;


      TH1F* hmctruth_ttwj_0lep_3b = (TH1F*) gDirectory->FindObject("hmctruth_ttwj_0lep_3b") ;
      if ( hmctruth_ttwj_0lep_3b == 0x0 ) { printf("\n\n\n *** can't find hmctruth_ttwj_0lep_3b.\n\n") ; return ; }
      TH1F* hmctruth_ttwj_1lep_3b = (TH1F*) gDirectory->FindObject("hmctruth_ttwj_1lep_3b") ;
      if ( hmctruth_ttwj_1lep_3b == 0x0 ) { printf("\n\n\n *** can't find hmctruth_ttwj_1lep_3b.\n\n") ; return ; }

      TH1F* hmctruth_ttwj_0over1ratio_3b = (TH1F*) hmctruth_ttwj_0lep_3b->Clone("hmctruth_ttwj_0over1ratio_3b") ;
      hmctruth_ttwj_0over1ratio_3b->Divide( hmctruth_ttwj_1lep_3b ) ;

      hmctruth_ttwj_0over1ratio_1b->SetLineColor(2) ;
      hmctruth_ttwj_0over1ratio_2b->SetLineColor(6) ;
      hmctruth_ttwj_0over1ratio_3b->SetLineColor(4) ;

      hmctruth_ttwj_0over1ratio_1b->SetMarkerStyle(20) ;
      hmctruth_ttwj_0over1ratio_2b->SetMarkerStyle(25) ;
      hmctruth_ttwj_0over1ratio_3b->SetMarkerStyle(30) ;


      char binlabel[1000] ;
      sprintf( binlabel, "%s", hmctruth_ttwj_0lep_1b -> GetXaxis() -> GetBinLabel( hmctruth_ttwj_0lep_1b->GetNbinsX() - 1 ) ) ;
      sscanf( binlabel, "0lep_M%d_H%d_1b", &nBinsMET, &nBinsHT ) ;
      printf("\n\n Bin label: %s,  nmet=%d, nht=%d\n\n", binlabel, nBinsMET, nBinsHT ) ;




      //-- compute dumb ave ratio

      int nBins = hmctruth_ttwj_0over1ratio_1b->GetNbinsX() ;

      double total0lep(0.) ;
      double total1lep(0.) ;
      double sumw20lep(0.) ;
      double sumw21lep(0.) ;

      for ( int bi=1; bi<=nBins; bi++ ) {

         total0lep += hmctruth_ttwj_0lep_1b->GetBinContent( bi ) ;
         total0lep += hmctruth_ttwj_0lep_2b->GetBinContent( bi ) ;
         total0lep += hmctruth_ttwj_0lep_3b->GetBinContent( bi ) ;

         total1lep += hmctruth_ttwj_1lep_1b->GetBinContent( bi ) ;
         total1lep += hmctruth_ttwj_1lep_2b->GetBinContent( bi ) ;
         total1lep += hmctruth_ttwj_1lep_3b->GetBinContent( bi ) ;

         sumw20lep += pow( hmctruth_ttwj_0lep_1b->GetBinError( bi ), 2 ) ;
         sumw20lep += pow( hmctruth_ttwj_0lep_2b->GetBinError( bi ), 2 ) ;
         sumw20lep += pow( hmctruth_ttwj_0lep_3b->GetBinError( bi ), 2 ) ;

         sumw21lep += pow( hmctruth_ttwj_1lep_1b->GetBinError( bi ), 2 ) ;
         sumw21lep += pow( hmctruth_ttwj_1lep_2b->GetBinError( bi ), 2 ) ;
         sumw21lep += pow( hmctruth_ttwj_1lep_3b->GetBinError( bi ), 2 ) ;

      } // bi.

      double simpleAveR_0over1 = total0lep / total1lep ;
      double simpleAveR_0over1_err = simpleAveR_0over1 * sqrt( sumw20lep/(total0lep*total0lep) + sumw21lep/(total1lep*total1lep)  ) ;

      printf("\n\n Simple average 0lep/1lep = %5.3f +/- %5.3f\n\n", simpleAveR_0over1, simpleAveR_0over1_err ) ;


      TH1F* hscalefactor_ttwj_0over1ratio_1b = (TH1F*) hmctruth_ttwj_0over1ratio_1b->Clone("hscalefactor_ttwj_0lep_1b") ;
      TH1F* hscalefactor_ttwj_0over1ratio_2b = (TH1F*) hmctruth_ttwj_0over1ratio_2b->Clone("hscalefactor_ttwj_0lep_2b") ;
      TH1F* hscalefactor_ttwj_0over1ratio_3b = (TH1F*) hmctruth_ttwj_0over1ratio_3b->Clone("hscalefactor_ttwj_0lep_3b") ;

      hscalefactor_ttwj_0over1ratio_1b->Scale(1./simpleAveR_0over1) ;
      hscalefactor_ttwj_0over1ratio_2b->Scale(1./simpleAveR_0over1) ;
      hscalefactor_ttwj_0over1ratio_3b->Scale(1./simpleAveR_0over1) ;


      hmctruth_ttwj_0over1ratio_1b->SetMinimum(0.) ;
      hmctruth_ttwj_0over1ratio_2b->SetMinimum(0.) ;
      hmctruth_ttwj_0over1ratio_3b->SetMinimum(0.) ;
      hmctruth_ttwj_0over1ratio_1b->SetMaximum(3.) ;
      hmctruth_ttwj_0over1ratio_2b->SetMaximum(3.) ;
      hmctruth_ttwj_0over1ratio_3b->SetMaximum(3.) ;

      hscalefactor_ttwj_0over1ratio_1b->SetMinimum(0.) ;
      hscalefactor_ttwj_0over1ratio_2b->SetMinimum(0.) ;
      hscalefactor_ttwj_0over1ratio_3b->SetMinimum(0.) ;
      hscalefactor_ttwj_0over1ratio_1b->SetMaximum(2.5) ;
      hscalefactor_ttwj_0over1ratio_2b->SetMaximum(2.5) ;
      hscalefactor_ttwj_0over1ratio_3b->SetMaximum(2.5) ;



      gStyle->SetPadRightMargin(0.08) ;
      TCanvas* cttwj = (TCanvas*) gDirectory->FindObject("cttwj") ;
      if ( cttwj == 0x0 ) {
         cttwj = new TCanvas("cttwj","ttwj closure", 700, 950) ;
      }
      cttwj->Clear() ;
      cttwj->Divide(1,2) ;

      TLegend* legend_ttwj = new TLegend( 0.91, 0.77,  0.99, 0.93 ) ;
      legend_ttwj->SetFillColor(kWhite) ;
      legend_ttwj->AddEntry( hmctruth_ttwj_0over1ratio_1b, "=1b") ;
      legend_ttwj->AddEntry( hmctruth_ttwj_0over1ratio_2b, "=2b") ;
      legend_ttwj->AddEntry( hmctruth_ttwj_0over1ratio_3b, ">=3b") ;

      cttwj->cd(1) ;
      hmctruth_ttwj_0over1ratio_1b->SetTitle("ttwj: 0 Lepton / 1 Lepton, Ratio") ;
      hmctruth_ttwj_0over1ratio_1b->Draw() ;
      hmctruth_ttwj_0over1ratio_2b->Draw("same") ;
      hmctruth_ttwj_0over1ratio_3b->Draw("same") ;
      legend_ttwj->Draw() ;

      cttwj->cd(2) ;
      hscalefactor_ttwj_0over1ratio_1b->SetTitle("ttwj: 0 Lepton / 1 Lepton, Scale Factor") ;
      hscalefactor_ttwj_0over1ratio_1b->Draw() ;
      hscalefactor_ttwj_0over1ratio_2b->Draw("same") ;
      hscalefactor_ttwj_0over1ratio_3b->Draw("same") ;
      line->DrawLine(0.5,1.,hscalefactor_ttwj_0over1ratio_1b->GetNbinsX()+0.5,1.) ;
      legend_ttwj->Draw() ;

      TString outttwj( infileStr ) ;
      outttwj.ReplaceAll("rootfiles","outputfiles") ;
      outttwj.ReplaceAll(".root","-mcclosure-ttwj1.pdf") ;
      cttwj->SaveAs( outttwj ) ;




   //----


      TCanvas* cttwj3 = (TCanvas*) gDirectory->FindObject("cttwj3") ;
      if ( cttwj3 == 0x0 ) {
         cttwj3 = new TCanvas("cttwj3","ttwj closure", 1200, 950) ;
      }
      cttwj3->Clear() ;
      cttwj3->Divide(3,2) ;

      cttwj3->cd(1) ;
      hmctruth_ttwj_0over1ratio_1b->SetTitle("ttwj =1b: 0 Lepton / 1 Lepton, Ratio") ;
      hmctruth_ttwj_0over1ratio_1b->Draw() ;
      cttwj3->cd(2) ;
      hmctruth_ttwj_0over1ratio_2b->SetTitle("ttwj =2b: 0 Lepton / 1 Lepton, Ratio") ;
      hmctruth_ttwj_0over1ratio_2b->Draw() ;
      cttwj3->cd(3) ;
      hmctruth_ttwj_0over1ratio_3b->SetTitle("ttwj >=3b: 0 Lepton / 1 Lepton, Ratio") ;
      hmctruth_ttwj_0over1ratio_3b->Draw() ;

      cttwj3->cd(4) ;
      hscalefactor_ttwj_0over1ratio_1b->SetTitle("ttwj =1b: 0 Lepton / 1 Lepton, Scale Factor") ;
      hscalefactor_ttwj_0over1ratio_1b->Draw() ;
      line->DrawLine(0.5,1.,hscalefactor_ttwj_0over1ratio_1b->GetNbinsX()+0.5,1.) ;
      hscalefactor_ttwj_0over1ratio_1b->Draw("same") ;
      cttwj3->cd(5) ;
      hscalefactor_ttwj_0over1ratio_2b->SetTitle("ttwj =2b: 0 Lepton / 1 Lepton, Scale Factor") ;
      hscalefactor_ttwj_0over1ratio_2b->Draw() ;
      line->DrawLine(0.5,1.,hscalefactor_ttwj_0over1ratio_1b->GetNbinsX()+0.5,1.) ;
      hscalefactor_ttwj_0over1ratio_2b->Draw("same") ;
      cttwj3->cd(6) ;
      hscalefactor_ttwj_0over1ratio_3b->SetTitle("ttwj >=3b: 0 Lepton / 1 Lepton, Scale Factor") ;
      hscalefactor_ttwj_0over1ratio_3b->Draw() ;
      line->DrawLine(0.5,1.,hscalefactor_ttwj_0over1ratio_1b->GetNbinsX()+0.5,1.) ;
      hscalefactor_ttwj_0over1ratio_3b->Draw("same") ;


      TString outttwj3( infileStr ) ;
      outttwj3.ReplaceAll("rootfiles","outputfiles") ;
      outttwj3.ReplaceAll(".root","-mcclosure-ttwj3.pdf") ;
      cttwj3->SaveAs( outttwj3 ) ;

   //----
   

      hmctruth_ttwj_0lep_1b->SetFillColor(kBlue-9) ;
      hmctruth_ttwj_0lep_2b->SetFillColor(kBlue-9) ;
      hmctruth_ttwj_0lep_3b->SetFillColor(kBlue-9) ;

      hmctruth_ttwj_1lep_1b->SetFillColor(kBlue-9) ;
      hmctruth_ttwj_1lep_2b->SetFillColor(kBlue-9) ;
      hmctruth_ttwj_1lep_3b->SetFillColor(kBlue-9) ;

      hmctruth_ttwj_0lep_1b->SetLineWidth(2) ;
      hmctruth_ttwj_0lep_2b->SetLineWidth(2) ;
      hmctruth_ttwj_0lep_3b->SetLineWidth(2) ;

      hmctruth_ttwj_1lep_1b->SetLineWidth(2) ;
      hmctruth_ttwj_1lep_2b->SetLineWidth(2) ;
      hmctruth_ttwj_1lep_3b->SetLineWidth(2) ;

      TCanvas* cttwj3b = (TCanvas*) gDirectory->FindObject("cttwj3b") ;
      if ( cttwj3b == 0x0 ) {
         cttwj3b = new TCanvas("cttwj3b","ttwj closure", 1200, 950) ;
      }
      cttwj3b->Clear() ;
      cttwj3b->Divide(3,2) ;

      cttwj3b->cd(1) ;
      hmctruth_ttwj_0lep_1b->SetTitle("ttwj =1b: 0 Lepton") ;
      hmctruth_ttwj_0lep_1b->Draw() ;
      hmctruth_ttwj_0lep_1b->Draw("histsame") ;
      hmctruth_ttwj_0lep_1b->Draw("esame") ;
      cttwj3b->cd(2) ;
      hmctruth_ttwj_0lep_2b->SetTitle("ttwj =2b: 0 Lepton") ;
      hmctruth_ttwj_0lep_2b->Draw() ;
      hmctruth_ttwj_0lep_2b->Draw("histsame") ;
      hmctruth_ttwj_0lep_2b->Draw("esame") ;
      cttwj3b->cd(3) ;
      hmctruth_ttwj_0lep_3b->SetTitle("ttwj >=3b: 0 Lepton") ;
      hmctruth_ttwj_0lep_3b->Draw() ;
      hmctruth_ttwj_0lep_3b->Draw("histsame") ;
      hmctruth_ttwj_0lep_3b->Draw("esame") ;

      cttwj3b->cd(4) ;
      hmctruth_ttwj_1lep_1b->SetTitle("ttwj =1b: 1 Lepton") ;
      hmctruth_ttwj_1lep_1b->Draw() ;
      hmctruth_ttwj_1lep_1b->Draw("histsame") ;
      hmctruth_ttwj_1lep_1b->Draw("esame") ;
      cttwj3b->cd(5) ;
      hmctruth_ttwj_1lep_2b->SetTitle("ttwj =2b: 1 Lepton") ;
      hmctruth_ttwj_1lep_2b->Draw() ;
      hmctruth_ttwj_1lep_2b->Draw("histsame") ;
      hmctruth_ttwj_1lep_2b->Draw("esame") ;
      cttwj3b->cd(6) ;
      hmctruth_ttwj_1lep_3b->SetTitle("ttwj >=3b: 1 Lepton") ;
      hmctruth_ttwj_1lep_3b->Draw() ;
      hmctruth_ttwj_1lep_3b->Draw("histsame") ;
      hmctruth_ttwj_1lep_3b->Draw("esame") ;



      TString outttwj3b( infileStr ) ;
      outttwj3b.ReplaceAll("rootfiles","outputfiles") ;
      outttwj3b.ReplaceAll(".root","-mcclosure-ttwj3b.pdf") ;
      cttwj3b->SaveAs( outttwj3b ) ;

   //----



    //--- insert ttwj numbers into file.

      for ( int mbi=0; mbi<nBinsMET ; mbi++ ) {
         for ( int hbi=0; hbi<nBinsHT ; hbi++ ) {

            int hbin = 1 + (nBinsHT+1)*mbi + hbi + 1 ;

            char parameterName[1000] ;
            double err, diff, systValue, correction ;


            sprintf( parameterName, "sf_ttwj_M%d_H%d_1b_err", mbi+1, hbi+1 ) ;
            printf( "met=%d, ht=%d : %s %s\n", mbi+1, hbi+1,
                  parameterName,
                  hmctruth_ttwj_0lep_1b -> GetXaxis() -> GetBinLabel( hbin ) ) ;
            err  = hscalefactor_ttwj_0over1ratio_1b->GetBinError(hbin)  ;
            correction = hscalefactor_ttwj_0over1ratio_1b->GetBinContent(hbin)  ;
            diff = correction - 1. ;
            if ( err > 0. ) {
               systValue = sqrt( pow(err,2) + pow(0.5*diff,2) ) ;
            } else {
               systValue = 3.0 ;
            }
            if ( doTTWJSyst ) {
               updateFileValue( datfile, parameterName, systValue ) ;
            } else {
               updateFileValue( datfile, parameterName, 0.0 ) ;
            }
            sprintf( parameterName, "sf_ttwj_M%d_H%d_1b", mbi+1, hbi+1 ) ;
            if ( doTTWJCorrection ) {
               updateFileValue( datfile, parameterName, correction ) ;
            } else {
               updateFileValue( datfile, parameterName, 1.0 ) ;
            }

            sprintf( parameterName, "sf_ttwj_M%d_H%d_2b_err", mbi+1, hbi+1 ) ;
            err  = hscalefactor_ttwj_0over1ratio_2b->GetBinError(hbin)  ;
            correction = hscalefactor_ttwj_0over1ratio_2b->GetBinContent(hbin) ;
            diff = correction - 1. ;
            if ( err > 0. ) {
               systValue = sqrt( pow(err,2) + pow(0.5*diff,2) ) ;
            } else {
               systValue = 3.0 ;
            }
            if ( doTTWJSyst ) {
               updateFileValue( datfile, parameterName, systValue ) ;
            } else {
               updateFileValue( datfile, parameterName, 0.0 ) ;
            }
            sprintf( parameterName, "sf_ttwj_M%d_H%d_2b", mbi+1, hbi+1 ) ;
            if ( doTTWJCorrection ) {
               updateFileValue( datfile, parameterName, correction ) ;
            } else {
               updateFileValue( datfile, parameterName, 1.0 ) ;
            }

            sprintf( parameterName, "sf_ttwj_M%d_H%d_3b_err", mbi+1, hbi+1 ) ;
            err  = hscalefactor_ttwj_0over1ratio_3b->GetBinError(hbin)  ;
            correction = hscalefactor_ttwj_0over1ratio_3b->GetBinContent(hbin)  ;
            diff = correction - 1. ;
            if ( err > 0. ) {
               systValue = sqrt( pow(err,2) + pow(0.5*diff,2) ) ;
            } else {
               systValue = 3.0 ;
            }
            if ( doTTWJSyst ) {
               updateFileValue( datfile, parameterName, systValue ) ;
            } else {
               updateFileValue( datfile, parameterName, 0.0 ) ;
            }
            sprintf( parameterName, "sf_ttwj_M%d_H%d_3b", mbi+1, hbi+1 ) ;
            if ( doTTWJCorrection ) {
               updateFileValue( datfile, parameterName, correction ) ;
            } else {
               updateFileValue( datfile, parameterName, 1.0 ) ;
            }

         } // hbi.
      } // mbi.



















     //---   Q C D  Part   --------------

     //---  This is written to go with QCD model 3, which is a single ZL/LDP floating scale factor.




      TH1F* hmctruth_qcd_0lep_1b = (TH1F*) gDirectory->FindObject("hmctruth_qcd_0lep_1b") ;
      if ( hmctruth_qcd_0lep_1b == 0x0 ) { printf("\n\n *** Can't find hmctruth_qcd_0lep_1b.\n\n") ; return ; }
      TH1F* hmctruth_qcd_ldp_1b = (TH1F*) gDirectory->FindObject("hmctruth_qcd_ldp_1b") ;
      if ( hmctruth_qcd_ldp_1b == 0x0 ) { printf("\n\n *** Can't find hmctruth_qcd_ldp_1b.\n\n") ; return ; }

      TH1F* hmctruth_qcd_0lep_2b = (TH1F*) gDirectory->FindObject("hmctruth_qcd_0lep_2b") ;
      if ( hmctruth_qcd_0lep_2b == 0x0 ) { printf("\n\n *** Can't find hmctruth_qcd_0lep_2b.\n\n") ; return ; }
      TH1F* hmctruth_qcd_ldp_2b = (TH1F*) gDirectory->FindObject("hmctruth_qcd_ldp_2b") ;
      if ( hmctruth_qcd_ldp_2b == 0x0 ) { printf("\n\n *** Can't find hmctruth_qcd_ldp_2b.\n\n") ; return ; }

      TH1F* hmctruth_qcd_0lep_3b = (TH1F*) gDirectory->FindObject("hmctruth_qcd_0lep_3b") ;
      if ( hmctruth_qcd_0lep_3b == 0x0 ) { printf("\n\n *** Can't find hmctruth_qcd_0lep_3b.\n\n") ; return ; }
      TH1F* hmctruth_qcd_ldp_3b = (TH1F*) gDirectory->FindObject("hmctruth_qcd_ldp_3b") ;
      if ( hmctruth_qcd_ldp_3b == 0x0 ) { printf("\n\n *** Can't find hmctruth_qcd_ldp_3b.\n\n") ; return ; }

      TH1F* hmctruth_qcd_0lepoverldpratio_1b = (TH1F*) hmctruth_qcd_0lep_1b->Clone("hmctruth_qcd_0lepoverldpratio_1b") ;
      TH1F* hmctruth_qcd_0lepoverldpratio_2b = (TH1F*) hmctruth_qcd_0lep_2b->Clone("hmctruth_qcd_0lepoverldpratio_2b") ;
      TH1F* hmctruth_qcd_0lepoverldpratio_3b = (TH1F*) hmctruth_qcd_0lep_3b->Clone("hmctruth_qcd_0lepoverldpratio_3b") ;

      hmctruth_qcd_0lepoverldpratio_1b->Divide( hmctruth_qcd_ldp_1b ) ;
      hmctruth_qcd_0lepoverldpratio_2b->Divide( hmctruth_qcd_ldp_2b ) ;
      hmctruth_qcd_0lepoverldpratio_3b->Divide( hmctruth_qcd_ldp_3b ) ;

      hmctruth_qcd_0lepoverldpratio_1b->SetLineColor(2) ;
      hmctruth_qcd_0lepoverldpratio_2b->SetLineColor(6) ;
      hmctruth_qcd_0lepoverldpratio_3b->SetLineColor(4) ;

      hmctruth_qcd_0lepoverldpratio_1b->SetMarkerStyle(20) ;
      hmctruth_qcd_0lepoverldpratio_2b->SetMarkerStyle(25) ;
      hmctruth_qcd_0lepoverldpratio_3b->SetMarkerStyle(30) ;










      double zlsum[100] ;
      double ldpsum[100] ;

      double zlsumw2[100] ;
      double ldpsumw2[100] ;

      for ( int hbi=0; hbi<nBinsHT; hbi++ ) {
         zlsum[hbi] = 0. ;
         zlsumw2[hbi] = 0. ;
         ldpsum[hbi] = 0. ;
         ldpsumw2[hbi] = 0. ;
      }

      for ( int mbi=0; mbi<nBinsMET ; mbi++ ) {
         for ( int hbi=0; hbi<nBinsHT ; hbi++ ) {

            int hbinin = 1 + (nBinsHT+1)*mbi + hbi + 1 ;

            zlsum[hbi] += hmctruth_qcd_0lep_1b->GetBinContent( hbinin ) ;
            zlsum[hbi] += hmctruth_qcd_0lep_2b->GetBinContent( hbinin ) ;
            zlsum[hbi] += hmctruth_qcd_0lep_3b->GetBinContent( hbinin ) ;

            zlsumw2[hbi] += pow( hmctruth_qcd_0lep_1b->GetBinError( hbinin ), 2 ) ;
            zlsumw2[hbi] += pow( hmctruth_qcd_0lep_2b->GetBinError( hbinin ), 2 ) ;
            zlsumw2[hbi] += pow( hmctruth_qcd_0lep_3b->GetBinError( hbinin ), 2 ) ;


            ldpsum[hbi] += hmctruth_qcd_ldp_1b->GetBinContent( hbinin ) ;
            ldpsum[hbi] += hmctruth_qcd_ldp_2b->GetBinContent( hbinin ) ;
            ldpsum[hbi] += hmctruth_qcd_ldp_3b->GetBinContent( hbinin ) ;

            ldpsumw2[hbi] += pow( hmctruth_qcd_ldp_1b->GetBinError( hbinin ), 2 ) ;
            ldpsumw2[hbi] += pow( hmctruth_qcd_ldp_2b->GetBinError( hbinin ), 2 ) ;
            ldpsumw2[hbi] += pow( hmctruth_qcd_ldp_3b->GetBinError( hbinin ), 2 ) ;


         } // hbi
      } // mbi




      printf("\n\n") ;

      double qcd_0lepoverldpratio[100] ;
      double qcd_0lepoverldpratio_err[100] ;

      for ( int hbi=0; hbi<nBinsHT ; hbi++ ) {

          qcd_0lepoverldpratio[hbi] = 0. ;
          if ( ldpsum[hbi] > 0. ) {
             qcd_0lepoverldpratio[hbi] =  zlsum[hbi] / ldpsum[hbi] ;
          }
          qcd_0lepoverldpratio_err[hbi] = 0. ;
          if ( ldpsum[hbi] > 0. && zlsum[hbi] > 0. ) {
             qcd_0lepoverldpratio_err[hbi] = qcd_0lepoverldpratio[hbi] * sqrt(
                    zlsumw2[hbi] / pow( zlsum[hbi],2)
                  + ldpsumw2[hbi] / pow( ldpsum[hbi],2)
                    ) ;
          }

          printf(" HT bin %d : 0lep/LDP ratio = %5.3f +/- %5.3f\n", hbi+1, qcd_0lepoverldpratio[hbi], qcd_0lepoverldpratio_err[hbi] ) ;

      } // hbi.

      printf("\n\n") ;





      float zlsum_all(0.) ;
      float ldpsum_all(0.) ;

      float zlsumw2_all(0.) ;
      float ldpsumw2_all(0.) ;

      for ( int hbi=0; hbi<nBinsHT ; hbi++ ) {

         zlsum_all += zlsum[hbi] ;
         ldpsum_all += ldpsum[hbi] ;

         zlsumw2_all += zlsumw2[hbi] ;
         ldpsumw2_all += ldpsumw2[hbi] ;


      } // hbi.

      float qcd_0lepoverldpratio_all(0.) ;
      float qcd_0lepoverldpratio_all_err(0.) ;

      if ( ldpsum_all > 0 && zlsum_all > 0 ) {
         qcd_0lepoverldpratio_all = zlsum_all / ldpsum_all ;
         qcd_0lepoverldpratio_all_err = qcd_0lepoverldpratio_all * sqrt( zlsumw2_all / pow( zlsum_all,2) + ldpsumw2_all / pow( ldpsum_all, 2) ) ;
      }
      printf(" Average QCD 0lep/LDP ratio = %5.3f +/- %5.3f\n", qcd_0lepoverldpratio_all, qcd_0lepoverldpratio_all_err ) ;

      printf("\n\n") ;



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

      TH1F* hscalefactor_qcd_0lepoverldpratio_1b = (TH1F*)  hmctruth_qcd_0lepoverldpratio_1b->Clone( "hscalefactor_qcd_0lepoverldpratio_1b" ) ;
      TH1F* hscalefactor_qcd_0lepoverldpratio_2b = (TH1F*)  hmctruth_qcd_0lepoverldpratio_2b->Clone( "hscalefactor_qcd_0lepoverldpratio_2b" ) ;
      TH1F* hscalefactor_qcd_0lepoverldpratio_3b = (TH1F*)  hmctruth_qcd_0lepoverldpratio_3b->Clone( "hscalefactor_qcd_0lepoverldpratio_3b" ) ;

      hscalefactor_qcd_0lepoverldpratio_1b -> Scale( 1./ qcd_0lepoverldpratio_all ) ;
      hscalefactor_qcd_0lepoverldpratio_2b -> Scale( 1./ qcd_0lepoverldpratio_all ) ;
      hscalefactor_qcd_0lepoverldpratio_3b -> Scale( 1./ qcd_0lepoverldpratio_all ) ;





      TCanvas* cqcd = (TCanvas*) gDirectory->FindObject("cqcd") ;
      if ( cqcd == 0x0 ) {
         cqcd = new TCanvas("cqcd","qcd closure", 700, 950) ;
      }
      cqcd->Clear() ;
      cqcd->Divide(1,2) ;

      TLegend* legend_qcd = new TLegend( 0.91, 0.77,  0.99, 0.93 ) ;
      legend_qcd->SetFillColor(kWhite) ;
      legend_qcd->AddEntry( hmctruth_qcd_0lepoverldpratio_1b, "=1b") ;
      legend_qcd->AddEntry( hmctruth_qcd_0lepoverldpratio_2b, "=2b") ;
      legend_qcd->AddEntry( hmctruth_qcd_0lepoverldpratio_3b, ">=3b") ;

      cqcd->cd(1) ;
      hmctruth_qcd_0lepoverldpratio_1b->SetTitle("qcd: 0 Lepton / LDP, Ratio") ;
      hmctruth_qcd_0lepoverldpratio_1b->Draw() ;
      hmctruth_qcd_0lepoverldpratio_2b->Draw("same") ;
      hmctruth_qcd_0lepoverldpratio_3b->Draw("same") ;
      legend_qcd->Draw() ;

      cqcd->cd(2) ;
      hscalefactor_qcd_0lepoverldpratio_1b->SetTitle("qcd: 0 Lepton / LDP, Scale Factor") ;
      hscalefactor_qcd_0lepoverldpratio_1b->Draw() ;
      hscalefactor_qcd_0lepoverldpratio_2b->Draw("same") ;
      hscalefactor_qcd_0lepoverldpratio_3b->Draw("same") ;
      line->DrawLine(0.5,1.,hscalefactor_qcd_0lepoverldpratio_1b->GetNbinsX()+0.5,1.) ;
      legend_qcd->Draw() ;

      TString outqcd( infileStr ) ;
      outqcd.ReplaceAll("rootfiles","outputfiles") ;
      outqcd.ReplaceAll(".root","-mcclosure-qcd1.pdf") ;
      cqcd->SaveAs( outqcd ) ;







    //--- insert numbers into file.

      for ( int mbi=0; mbi<nBinsMET ; mbi++ ) {
         for ( int hbi=0; hbi<nBinsHT ; hbi++ ) {

            int hbin = 1 + (nBinsHT+1)*mbi + hbi + 1 ;

            char parameterName[1000] ;
            double sf_val, sf_err ;

            if ( doQCDCorrection ) {

               sprintf( parameterName, "sf_qcd_M%d_H%d_1b", mbi+1, hbi+1 ) ;
               sf_val = hscalefactor_qcd_0lepoverldpratio_1b -> GetBinContent( hbin ) ;
               if ( sf_val == 0. ) { sf_val = 1.0 ; }
               updateFileValue( datfile, parameterName, sf_val ) ;

               sprintf( parameterName, "sf_qcd_M%d_H%d_2b", mbi+1, hbi+1 ) ;
               sf_val = hscalefactor_qcd_0lepoverldpratio_2b -> GetBinContent( hbin ) ;
               if ( sf_val == 0. ) { sf_val = 1.0 ; }
               updateFileValue( datfile, parameterName, sf_val ) ;

               sprintf( parameterName, "sf_qcd_M%d_H%d_3b", mbi+1, hbi+1 ) ;
               sf_val = hscalefactor_qcd_0lepoverldpratio_3b -> GetBinContent( hbin ) ;
               if ( sf_val == 0. ) { sf_val = 1.0 ; }
               updateFileValue( datfile, parameterName, sf_val ) ;

            } else {

               sprintf( parameterName, "sf_qcd_M%d_H%d_1b", mbi+1, hbi+1 ) ;
               updateFileValue( datfile, parameterName, 1.0 ) ;

               sprintf( parameterName, "sf_qcd_M%d_H%d_2b", mbi+1, hbi+1 ) ;
               updateFileValue( datfile, parameterName, 1.0 ) ;

               sprintf( parameterName, "sf_qcd_M%d_H%d_3b", mbi+1, hbi+1 ) ;
               updateFileValue( datfile, parameterName, 1.0 ) ;


            }

            if ( doQCDSyst ) {

               sprintf( parameterName, "sf_qcd_M%d_H%d_1b_err", mbi+1, hbi+1 ) ;
               sf_err = hscalefactor_qcd_0lepoverldpratio_1b -> GetBinError( hbin ) ;
               printf(" bin check : %s  ,  %s\n", parameterName, hscalefactor_qcd_0lepoverldpratio_1b -> GetXaxis() -> GetBinLabel( hbin ) ) ;
               if ( sf_err == 0. ) { sf_err = 3.0 ; }
               updateFileValue( datfile, parameterName, sf_err ) ;

               sprintf( parameterName, "sf_qcd_M%d_H%d_2b_err", mbi+1, hbi+1 ) ;
               sf_err = hscalefactor_qcd_0lepoverldpratio_2b -> GetBinError( hbin ) ;
               printf(" bin check : %s  ,  %s\n", parameterName, hscalefactor_qcd_0lepoverldpratio_2b -> GetXaxis() -> GetBinLabel( hbin ) ) ;
               if ( sf_err == 0. ) { sf_err = 3.0 ; }
               updateFileValue( datfile, parameterName, sf_err ) ;

               sprintf( parameterName, "sf_qcd_M%d_H%d_3b_err", mbi+1, hbi+1 ) ;
               sf_err = hscalefactor_qcd_0lepoverldpratio_3b -> GetBinError( hbin ) ;
               printf(" bin check : %s  ,  %s\n", parameterName, hscalefactor_qcd_0lepoverldpratio_3b -> GetXaxis() -> GetBinLabel( hbin ) ) ;
               if ( sf_err == 0. ) { sf_err = 3.0 ; }
               updateFileValue( datfile, parameterName, sf_err ) ;

            } else {

               sprintf( parameterName, "sf_qcd_M%d_H%d_1b_err", mbi+1, hbi+1 ) ;
               updateFileValue( datfile, parameterName, 0.0 ) ;

               sprintf( parameterName, "sf_qcd_M%d_H%d_2b_err", mbi+1, hbi+1 ) ;
               updateFileValue( datfile, parameterName, 0.0 ) ;

               sprintf( parameterName, "sf_qcd_M%d_H%d_3b_err", mbi+1, hbi+1 ) ;
               updateFileValue( datfile, parameterName, 0.0 ) ;

            }


         } // hbi.
      } // mbi.












     //--- ttwj MC LDP / 0lep ratios

      TH1F* hmctruth_ttwj_ldp_1b = (TH1F*) gDirectory->FindObject("hmctruth_ttwj_ldp_1b") ;
      if ( hmctruth_ttwj_ldp_1b == 0x0 ) { printf("\n\n\n *** can't find hmctruth_ttwj_ldp_1b.\n\n") ; return ; }

      TH1F* hmctruth_ttwj_ldpover0lep_ratio_1b = (TH1F*) hmctruth_ttwj_ldp_1b->Clone("hmctruth_ttwj_ldpover0lep_ratio_1b") ;
      hmctruth_ttwj_ldpover0lep_ratio_1b->Divide( hmctruth_ttwj_0lep_1b ) ;


      TH1F* hmctruth_ttwj_ldp_2b = (TH1F*) gDirectory->FindObject("hmctruth_ttwj_ldp_2b") ;
      if ( hmctruth_ttwj_ldp_2b == 0x0 ) { printf("\n\n\n *** can't find hmctruth_ttwj_ldp_2b.\n\n") ; return ; }

      TH1F* hmctruth_ttwj_ldpover0lep_ratio_2b = (TH1F*) hmctruth_ttwj_ldp_2b->Clone("hmctruth_ttwj_ldpover0lep_ratio_2b") ;
      hmctruth_ttwj_ldpover0lep_ratio_2b->Divide( hmctruth_ttwj_0lep_2b ) ;


      TH1F* hmctruth_ttwj_ldp_3b = (TH1F*) gDirectory->FindObject("hmctruth_ttwj_ldp_3b") ;
      if ( hmctruth_ttwj_ldp_3b == 0x0 ) { printf("\n\n\n *** can't find hmctruth_ttwj_ldp_3b.\n\n") ; return ; }

      TH1F* hmctruth_ttwj_ldpover0lep_ratio_3b = (TH1F*) hmctruth_ttwj_ldp_3b->Clone("hmctruth_ttwj_ldpover0lep_ratio_3b") ;
      hmctruth_ttwj_ldpover0lep_ratio_3b->Divide( hmctruth_ttwj_0lep_3b ) ;

      hmctruth_ttwj_ldpover0lep_ratio_1b->SetLineColor(2) ;
      hmctruth_ttwj_ldpover0lep_ratio_2b->SetLineColor(6) ;
      hmctruth_ttwj_ldpover0lep_ratio_3b->SetLineColor(4) ;

      hmctruth_ttwj_ldpover0lep_ratio_1b->SetMarkerStyle(20) ;
      hmctruth_ttwj_ldpover0lep_ratio_2b->SetMarkerStyle(25) ;
      hmctruth_ttwj_ldpover0lep_ratio_3b->SetMarkerStyle(30) ;



      gStyle->SetPadRightMargin(0.08) ;
      TCanvas* cttwjmcr = (TCanvas*) gDirectory->FindObject("cttwjmcr") ;
      if ( cttwjmcr == 0x0 ) {
         cttwjmcr = new TCanvas("cttwjmcr","ttwjmcr closure", 700, 475) ;
      }
      cttwjmcr->Clear() ;

      hmctruth_ttwj_ldpover0lep_ratio_1b->Draw() ;
      hmctruth_ttwj_ldpover0lep_ratio_2b->Draw("same") ;
      hmctruth_ttwj_ldpover0lep_ratio_3b->Draw("same") ;


      //--- write to file

      for ( int mbi=0; mbi<nBinsMET ; mbi++ ) {
         for ( int hbi=0; hbi<nBinsHT ; hbi++ ) {

            int hbin = 1 + (nBinsHT+1)*mbi + hbi + 1 ;

            char parameterName[1000] ;
            double err, value ;


            err   = hmctruth_ttwj_ldpover0lep_ratio_1b->GetBinError(hbin)  ;
            value = hmctruth_ttwj_ldpover0lep_ratio_1b->GetBinContent(hbin)  ;
            sprintf( parameterName, "ttwj_mc_ldpover0lep_ratio_M%d_H%d_1b", mbi+1, hbi+1 ) ;
            printf( "met=%d, ht=%d : %s %s  %6.3f +/- %5.3f\n", mbi+1, hbi+1,
                  parameterName,
                  hmctruth_ttwj_ldpover0lep_ratio_1b -> GetXaxis() -> GetBinLabel( hbin ), value, err ) ;
            updateFileValue( datfile, parameterName, value ) ;
            sprintf( parameterName, "ttwj_mc_ldpover0lep_ratio_M%d_H%d_1b_err", mbi+1, hbi+1 ) ;
            updateFileValue( datfile, parameterName, err ) ;

            err   = hmctruth_ttwj_ldpover0lep_ratio_2b->GetBinError(hbin)  ;
            value = hmctruth_ttwj_ldpover0lep_ratio_2b->GetBinContent(hbin)  ;
            sprintf( parameterName, "ttwj_mc_ldpover0lep_ratio_M%d_H%d_2b", mbi+1, hbi+1 ) ;
            printf( "met=%d, ht=%d : %s %s  %6.3f +/- %5.3f\n", mbi+1, hbi+1,
                  parameterName,
                  hmctruth_ttwj_ldpover0lep_ratio_2b -> GetXaxis() -> GetBinLabel( hbin ), value, err ) ;
            updateFileValue( datfile, parameterName, value ) ;
            sprintf( parameterName, "ttwj_mc_ldpover0lep_ratio_M%d_H%d_2b_err", mbi+1, hbi+1 ) ;
            updateFileValue( datfile, parameterName, err ) ;

            err   = hmctruth_ttwj_ldpover0lep_ratio_3b->GetBinError(hbin)  ;
            value = hmctruth_ttwj_ldpover0lep_ratio_3b->GetBinContent(hbin)  ;
            sprintf( parameterName, "ttwj_mc_ldpover0lep_ratio_M%d_H%d_3b", mbi+1, hbi+1 ) ;
            printf( "met=%d, ht=%d : %s %s  %6.3f +/- %5.3f\n", mbi+1, hbi+1,
                  parameterName,
                  hmctruth_ttwj_ldpover0lep_ratio_3b -> GetXaxis() -> GetBinLabel( hbin ), value, err ) ;
            updateFileValue( datfile, parameterName, value ) ;
            sprintf( parameterName, "ttwj_mc_ldpover0lep_ratio_M%d_H%d_3b_err", mbi+1, hbi+1 ) ;
            updateFileValue( datfile, parameterName, err ) ;

            printf("\n") ;


         } // hbi.
      } // mbi.










     //--- znn MC LDP / 0lep ratios

      TH1F* hmctruth_znn_0lep_1b = (TH1F*) gDirectory->FindObject("hmctruth_znn_0lep_1b") ;
      if ( hmctruth_znn_0lep_1b == 0x0 ) { printf("\n\n\n *** can't find hmctruth_znn_0lep_1b.\n\n") ; return ; }
      TH1F* hmctruth_znn_ldp_1b = (TH1F*) gDirectory->FindObject("hmctruth_znn_ldp_1b") ;
      if ( hmctruth_znn_ldp_1b == 0x0 ) { printf("\n\n\n *** can't find hmctruth_znn_ldp_1b.\n\n") ; return ; }

      TH1F* hmctruth_znn_ldpover0lep_ratio_1b = (TH1F*) hmctruth_znn_ldp_1b->Clone("hmctruth_znn_ldpover0lep_ratio_1b") ;
      hmctruth_znn_ldpover0lep_ratio_1b->Divide( hmctruth_znn_0lep_1b ) ;


      TH1F* hmctruth_znn_0lep_2b = (TH1F*) gDirectory->FindObject("hmctruth_znn_0lep_2b") ;
      if ( hmctruth_znn_0lep_2b == 0x0 ) { printf("\n\n\n *** can't find hmctruth_znn_0lep_2b.\n\n") ; return ; }
      TH1F* hmctruth_znn_ldp_2b = (TH1F*) gDirectory->FindObject("hmctruth_znn_ldp_2b") ;
      if ( hmctruth_znn_ldp_2b == 0x0 ) { printf("\n\n\n *** can't find hmctruth_znn_ldp_2b.\n\n") ; return ; }

      TH1F* hmctruth_znn_ldpover0lep_ratio_2b = (TH1F*) hmctruth_znn_ldp_2b->Clone("hmctruth_znn_ldpover0lep_ratio_2b") ;
      hmctruth_znn_ldpover0lep_ratio_2b->Divide( hmctruth_znn_0lep_2b ) ;


      TH1F* hmctruth_znn_0lep_3b = (TH1F*) gDirectory->FindObject("hmctruth_znn_0lep_3b") ;
      if ( hmctruth_znn_0lep_3b == 0x0 ) { printf("\n\n\n *** can't find hmctruth_znn_0lep_3b.\n\n") ; return ; }
      TH1F* hmctruth_znn_ldp_3b = (TH1F*) gDirectory->FindObject("hmctruth_znn_ldp_3b") ;
      if ( hmctruth_znn_ldp_3b == 0x0 ) { printf("\n\n\n *** can't find hmctruth_znn_ldp_3b.\n\n") ; return ; }

      TH1F* hmctruth_znn_ldpover0lep_ratio_3b = (TH1F*) hmctruth_znn_ldp_3b->Clone("hmctruth_znn_ldpover0lep_ratio_3b") ;
      hmctruth_znn_ldpover0lep_ratio_3b->Divide( hmctruth_znn_0lep_3b ) ;

      hmctruth_znn_ldpover0lep_ratio_1b->SetLineColor(2) ;
      hmctruth_znn_ldpover0lep_ratio_2b->SetLineColor(6) ;
      hmctruth_znn_ldpover0lep_ratio_3b->SetLineColor(4) ;

      hmctruth_znn_ldpover0lep_ratio_1b->SetMarkerStyle(20) ;
      hmctruth_znn_ldpover0lep_ratio_2b->SetMarkerStyle(25) ;
      hmctruth_znn_ldpover0lep_ratio_3b->SetMarkerStyle(30) ;



      gStyle->SetPadRightMargin(0.08) ;
      TCanvas* cznnmcr = (TCanvas*) gDirectory->FindObject("cznnmcr") ;
      if ( cznnmcr == 0x0 ) {
         cznnmcr = new TCanvas("cznnmcr","znnmcr closure", 700, 475) ;
      }
      cznnmcr->Clear() ;

      hmctruth_znn_ldpover0lep_ratio_1b->Draw() ;
      hmctruth_znn_ldpover0lep_ratio_2b->Draw("same") ;
      hmctruth_znn_ldpover0lep_ratio_3b->Draw("same") ;


      //--- MC stats are too low for 2b and >=3b cases.  Use 1b values for all three.

      //--- write to file

      for ( int mbi=0; mbi<nBinsMET ; mbi++ ) {
         for ( int hbi=0; hbi<nBinsHT ; hbi++ ) {

            int hbin = 1 + (nBinsHT+1)*mbi + hbi + 1 ;

            char parameterName[1000] ;
            double err, value ;


            err   = hmctruth_znn_ldpover0lep_ratio_1b->GetBinError(hbin)  ;
            value = hmctruth_znn_ldpover0lep_ratio_1b->GetBinContent(hbin)  ;
            sprintf( parameterName, "znn_mc_ldpover0lep_ratio_M%d_H%d_1b", mbi+1, hbi+1 ) ;
            printf( "met=%d, ht=%d : %s %s  %6.3f +/- %5.3f\n", mbi+1, hbi+1,
                  parameterName,
                  hmctruth_znn_ldpover0lep_ratio_1b -> GetXaxis() -> GetBinLabel( hbin ), value, err ) ;
            updateFileValue( datfile, parameterName, value ) ;
            sprintf( parameterName, "znn_mc_ldpover0lep_ratio_M%d_H%d_1b_err", mbi+1, hbi+1 ) ;
            updateFileValue( datfile, parameterName, err ) ;
            sprintf( parameterName, "znn_mc_ldpover0lep_ratio_M%d_H%d_2b", mbi+1, hbi+1 ) ;
            updateFileValue( datfile, parameterName, value ) ;
            sprintf( parameterName, "znn_mc_ldpover0lep_ratio_M%d_H%d_2b_err", mbi+1, hbi+1 ) ;
            updateFileValue( datfile, parameterName, err ) ;
            sprintf( parameterName, "znn_mc_ldpover0lep_ratio_M%d_H%d_3b", mbi+1, hbi+1 ) ;
            updateFileValue( datfile, parameterName, value ) ;
            sprintf( parameterName, "znn_mc_ldpover0lep_ratio_M%d_H%d_3b_err", mbi+1, hbi+1 ) ;
            updateFileValue( datfile, parameterName, err ) ;

      ///   err   = hmctruth_znn_ldpover0lep_ratio_2b->GetBinError(hbin)  ;
      ///   value = hmctruth_znn_ldpover0lep_ratio_2b->GetBinContent(hbin)  ;
      ///   sprintf( parameterName, "znn_mc_ldpover0lep_ratio_M%d_H%d_2b", mbi+1, hbi+1 ) ;
      ///   printf( "met=%d, ht=%d : %s %s  %6.3f +/- %5.3f\n", mbi+1, hbi+1,
      ///         parameterName,
      ///         hmctruth_znn_ldpover0lep_ratio_2b -> GetXaxis() -> GetBinLabel( hbin ), value, err ) ;
      ///   updateFileValue( datfile, parameterName, value ) ;
      ///   sprintf( parameterName, "znn_mc_ldpover0lep_ratio_M%d_H%d_2b_err", mbi+1, hbi+1 ) ;
      ///   updateFileValue( datfile, parameterName, err ) ;

      ///   err   = hmctruth_znn_ldpover0lep_ratio_3b->GetBinError(hbin)  ;
      ///   value = hmctruth_znn_ldpover0lep_ratio_3b->GetBinContent(hbin)  ;
      ///   sprintf( parameterName, "znn_mc_ldpover0lep_ratio_M%d_H%d_3b", mbi+1, hbi+1 ) ;
      ///   printf( "met=%d, ht=%d : %s %s  %6.3f +/- %5.3f\n", mbi+1, hbi+1,
      ///         parameterName,
      ///         hmctruth_znn_ldpover0lep_ratio_3b -> GetXaxis() -> GetBinLabel( hbin ), value, err ) ;
      ///   updateFileValue( datfile, parameterName, value ) ;
      ///   sprintf( parameterName, "znn_mc_ldpover0lep_ratio_M%d_H%d_3b_err", mbi+1, hbi+1 ) ;
      ///   updateFileValue( datfile, parameterName, err ) ;

            printf("\n") ;


         } // hbi.
      } // mbi.









   } // mcclosure2
Esempio n. 16
0
void background_draw(const char *rootname = "background_plots2.root")
{
	char strs[128];
	char strl[1024];
	const char titles[NHISTS][16] = {"gtDiff", "R1", "R2", "RZ", "PX", "PY", "PZ", 
		"NX", "NY", "NZ", "NE", "NH", "PH", "AH", "AE", "AM", "AMO", "P2AZ", "AH1", "AE1", "P2AZ1"};
	const char suffix[4][10] = {"A-rand", "A-diff", "B-diff", "C-diff"};
	const Color_t color[4] = {kGreen+2, kBlue, kRed, kOrange};
	const int marker[4] = {kOpenCircle, kFullCircle, kOpenSquare, kOpenStar};
	TH1D *h[NHISTS][4];
	int i, j;
	double hMax;
	int iMax;
	char pdfname[1024];
	char *ptr;

	strcpy(pdfname, rootname);
	ptr = strstr(pdfname, ".root");
	if (ptr) {
		strcpy(ptr, ".pdf");
	} else {
		strcat(pdfname, ".pdf");
	}
	
	gROOT->SetStyle("Plain");
	gStyle->SetOptStat(0);
	gStyle->SetOptFit(1);
	
	gStyle->SetTitleXSize(0.05);
	gStyle->SetTitleYSize(0.05);
	gStyle->SetLabelSize(0.05);
	gStyle->SetPadLeftMargin(0.16);
	gStyle->SetPadBottomMargin(0.16);
	
	TFile *fRoot = new TFile(rootname);
	if (!fRoot->IsOpen()) {
		printf("root-file %s not found  - run background_calc() first!\n", rootname);
		return;
	}
	for (i=0; i<NHISTS; i++) {
		for (j=0; j<4; j++) {
			sprintf(strs, "h%s%s", titles[i], suffix[j]);
			h[i][j] = (TH1D*) fRoot->Get(strs);
			if (!h[i][j]) {
				printf("%s not found  - rerun background_calc() to create all hists!\n", strs);
				fRoot->Close();
				return;
			}
			h[i][j]->SetLineWidth(2);
			h[i][j]->SetLineColor(color[j]);
			h[i][j]->SetMarkerColor(color[j]);
			h[i][j]->SetMarkerStyle(marker[j]);
			h[i][j]->GetYaxis()->SetLabelSize(0.05);
			h[i][j]->SetMinimum(0);
			h[i][j]->GetYaxis()->SetTitle("");
		}
	}
	
	TCanvas *cv = new TCanvas("CV", "Background plots", 1200, 900);
	TLegend *lg = new TLegend(0.7, 0.8, 0.95, 0.95);
	lg->AddEntry(h[0][0], "Random", "LP");
	lg->AddEntry(h[0][1], "Neutrino", "LP");
	lg->AddEntry(h[0][2], "Cosmic-A", "LP");
	lg->AddEntry(h[0][3], "Cosmic-B", "LP");
	
	sprintf(strl, "%s[", pdfname);
	cv->SaveAs(strl);
	
	for (i=0; i<NHISTS; i++) {
		cv->Clear();

		hMax = 0;
		iMax = 0;
		for (j=0; j<3; j++) if (h[i][j]->GetMaximum() > hMax) {
			hMax = h[i][j]->GetMaximum();
			iMax = j;
		}
		h[i][iMax]->Draw();
		for (j=0; j<4; j++) if (j != iMax) h[i][j]->Draw("same");
		lg->Draw();
		cv->SaveAs(pdfname);
	}
	
	sprintf(strl, "%s]", pdfname);
	cv->SaveAs(strl);
	fRoot->Close();
}
Esempio n. 17
0
void plotPdf_7D_XWW(double mH = 125, bool draw=true) {

    gROOT->ProcessLine(".L tdrstyle.C");
    setTDRStyle();
    TGaxis::SetMaxDigits(3);
    gROOT->ForceStyle();
    
    // Declaration of the PDFs to use
    gROOT->ProcessLine(".L  PDFs/RooSpinTwo_7D.cxx+");

    // W/Z mass and decay width constants
    double mV = 80.399;
    double gamV = 2.085;
    bool offshell = false;
    if ( mH < 2 * mV ) offshell = true;

    
    // for the pole mass and decay width of W 
    RooRealVar* mX = new RooRealVar("mX","mX", mH);
    RooRealVar* mW = new RooRealVar("mW","mW", mV);
    RooRealVar* gamW = new RooRealVar("gamW","gamW",gamV);

    //
    // Observables (7D)
    // 
    RooRealVar* wplusmass = new RooRealVar("wplusmass","m(W+)",mV,1e-09,120);
    wplusmass->setBins(50);
    RooRealVar* wminusmass = new RooRealVar("wminusmass","m(W-)",mV,1e-09,120);
    wminusmass->setBins(50);
    RooRealVar* hs = new RooRealVar("costhetastar","cos#theta*",-1,1);
    hs->setBins(20);
    RooRealVar* Phi1 = new RooRealVar("phistar1","#Phi_{1}",-TMath::Pi(),TMath::Pi());
    Phi1->setBins(20);
    RooRealVar* h1 = new RooRealVar("costheta1","cos#theta_{1}",-1,1);
    h1->setBins(20);
    RooRealVar* h2 = new RooRealVar("costheta2","cos#theta_{2}",-1,1);
    h2->setBins(20);
    RooRealVar* Phi = new RooRealVar("phi","#Phi",-TMath::Pi(),TMath::Pi());
    Phi->setBins(20);
    
    //
    // coupling constants for 2m+
    // See equation 5,6,7 in PRD 91, 075022
    //
    double s = (mH*mH-2*mV*mV)/2.;
    double c1 = 2*(1+mV*mV/s);
    c1 = c1 * 2.0; // scale up to be consistent with the generator
    // std::cout << "c1 = " << c1 << "\n"; 

    RooRealVar* c1Val = new RooRealVar("c1Val", "c1Val", c1);
    RooRealVar* c2Val = new RooRealVar("c2Val", "c2Val", -0.5);
    RooRealVar* c3Val = new RooRealVar("c3Val", "c3Val", 0.);
    RooRealVar* c4Val = new RooRealVar("c4Val", "c4Val", -1.);
    RooRealVar* c5Val = new RooRealVar("c5Val", "c5Val", 0.);
    RooRealVar* c6Val = new RooRealVar("c6Val", "c6Val", 0.);
    RooRealVar* c7Val = new RooRealVar("c7Val", "c7Val", 0.);
    
    // 
    // Alternative definition in terms of g1->g10
    // 
    RooRealVar* useGTerm = new RooRealVar("useGTerm", "useGTerm",1.); // set to 1 if using g couplings
    RooRealVar* g1Val = new RooRealVar("g1Val", "g1Val", 1);
    RooRealVar* g2Val = new RooRealVar("g2Val", "g2Val", 0.);
    RooRealVar* g3Val = new RooRealVar("g3Val", "g3Val", 0.);
    RooRealVar* g4Val = new RooRealVar("g4Val", "g4Val", 0.);
    RooRealVar* g5Val = new RooRealVar("g5Val", "g5Val", 1.);
    RooRealVar* g6Val = new RooRealVar("g6Val", "g6Val", 0.);
    RooRealVar* g7Val = new RooRealVar("g7Val", "g7Val", 0.);
    RooRealVar* g8Val = new RooRealVar("g8Val", "g8Val", 0.);
    RooRealVar* g9Val = new RooRealVar("g9Val", "g9Val", 0.);
    RooRealVar* g10Val = new RooRealVar("g10Val", "g10Val", 0.);

    // related to the gg/qq productions 
    RooRealVar* fz1Val = new RooRealVar("fz1Val", "fz1Val", 0);
    RooRealVar* fz2Val = new RooRealVar("fz2Val", "fz2Val", 1.0);

    // Even more parameters, do not have to touch, based on Z couplings
    RooRealVar* R1Val = new RooRealVar("R1Val","R1Val",1);
    RooRealVar* R2Val = new RooRealVar("R2Val","R2Val",1);
    
      
    // PDF definition SM Higgs (JP = 2+)
    RooSpinTwo_7D *myPDF;
    if ( offshell )
      myPDF = new RooSpinTwo_7D("myPDF","myPDF", *mX, *wplusmass, *wminusmass, *hs, *h1,*h2, *Phi, *Phi1, 
				  *c1Val, *c2Val, *c3Val, *c4Val, *c5Val, *c6Val, *c7Val, 
				  *useGTerm, *g1Val, *g2Val, *g3Val, *g4Val, *g5Val, *g6Val, *g7Val, *g8Val, *g9Val, *g10Val,
				  *fz1Val, *fz2Val, *R1Val, *R2Val, *mW, *gamW);
    else 
      myPDF = new RooSpinTwo_7D("myPDF","myPDF", *mX, *mW, *mW, *hs, *h1,*h2, *Phi, *Phi1, 
				  *c1Val, *c2Val, *c3Val, *c4Val, *c5Val, *c6Val, *c7Val, 
				  *useGTerm, *g1Val, *g2Val, *g3Val, *g4Val, *g5Val, *g6Val, *g7Val, *g8Val, *g9Val, *g10Val,
				  *fz1Val, *fz2Val, *R1Val, *R2Val, *mW, *gamW);
    // dataset for (JP = 2+)
    TString fileName;
    if ( useGTerm->getVal() > 0.) {
      fileName = Form("TWW_2mplus_%.0f_JHU.root", mH);
    }
    else {
      fileName = Form("TWW_%.0f_JHU_GenFromC.root", mH);
    }
    std::cout << "Opening " << fileName << "\n";
    TFile* fin = new TFile(fileName);
    TTree* tin = (TTree*) fin->Get("angles");

    if ( offshell) 
      RooDataSet data("data","data",tin,RooArgSet(*wplusmass, *wminusmass, *hs, *h1, *h2, *Phi, *Phi1));
    else 
      RooDataSet data("data","data",tin,RooArgSet(*hs, *h1, *h2, *Phi, *Phi1));

    // 
    //  2h-
    // 
    RooRealVar* g1ValMinus = new RooRealVar("g1ValMinus", "g1ValMinus", 0);
    RooRealVar* g2ValMinus = new RooRealVar("g2ValMinus", "g2ValMinus", 0.);
    RooRealVar* g3ValMinus = new RooRealVar("g3ValMinus", "g3ValMinus", 0.);
    RooRealVar* g4ValMinus = new RooRealVar("g4ValMinus", "g4ValMinus", 0.);
    RooRealVar* g5ValMinus = new RooRealVar("g5ValMinus", "g5ValMinus", 0.);
    RooRealVar* g6ValMinus = new RooRealVar("g6ValMinus", "g6ValMinus", 0.);
    RooRealVar* g7ValMinus = new RooRealVar("g7ValMinus", "g7ValMinus", 0.);
    RooRealVar* g8ValMinus = new RooRealVar("g8ValMinus", "g8ValMinus", 1.);
    RooRealVar* g9ValMinus = new RooRealVar("g9ValMinus", "g9ValMinus", 0.);
    RooRealVar* g10ValMinus = new RooRealVar("g10ValMinus", "g10ValMinus", 0.);
    RooRealVar* fz1ValMinus = new RooRealVar("fz1ValMinus", "fz1ValMinus", 0.0);
    RooRealVar* fz2ValMinus = new RooRealVar("fz2ValMinus", "fz2ValMinus", 0.0);

    RooSpinTwo_7D *myPDFMinus;
    if ( offshell )
      myPDFMinus = new RooSpinTwo_7D("myPDFMinus","myPDFMinus", *mX, *wplusmass, *wminusmass, *hs, *h1,*h2, *Phi, *Phi1, 
				       *c1Val, *c2Val, *c3Val, *c4Val, *c5Val, *c6Val, *c7Val, 
				       *useGTerm, *g1ValMinus, *g2ValMinus, *g3ValMinus, *g4ValMinus, 
				       *g5ValMinus, *g6ValMinus, *g7ValMinus, *g8ValMinus, *g9ValMinus, *g10ValMinus,
				       *fz1ValMinus, *fz2ValMinus, *R1Val, *R2Val, *mW, *gamW);
    else 
      myPDFMinus = new RooSpinTwo_7D("myPDFMinus","myPDFMinus", *mX, *mW, *mW, *hs, *h1,*h2, *Phi, *Phi1, 
				       *c1Val, *c2Val, *c3Val, *c4Val, *c5Val, *c6Val, *c7Val, 
				       *useGTerm, *g1ValMinus, *g2ValMinus, *g3ValMinus, *g4ValMinus, 
				       *g5ValMinus, *g6ValMinus, *g7ValMinus, *g8ValMinus, *g9ValMinus, *g10ValMinus,
				       *fz1ValMinus, *fz2ValMinus, *R1Val, *R2Val, *mW, *gamW);

    // dataset for (JP = 2-)
    TString fileNameMinus;
    if ( useGTerm->getVal() > 0.) {
      fileNameMinus = Form("TWW_2hminus_%.0f_JHU.root", mH);
    }
    
    std::cout << "Opening " << fileNameMinus << "\n";
    TFile* finMinus = new TFile(fileNameMinus);
    TTree* tinMinus = (TTree*) finMinus->Get("angles");

    if ( offshell) 
      RooDataSet dataMinus("dataMinus","dataMinus",tinMinus,RooArgSet(*wplusmass, *wminusmass, *hs, *h1, *h2, *Phi, *Phi1));
    else 
      RooDataSet dataMinus("dataMinus","dataMinus",tinMinus,RooArgSet(*hs, *h1, *h2, *Phi, *Phi1));

    // 
    //  2h+
    // 
    RooRealVar* g1ValHPlus = new RooRealVar("g1ValHPlus", "g1ValHPlus", 0);
    RooRealVar* g2ValHPlus = new RooRealVar("g2ValHPlus", "g2ValHPlus", 0.);
    RooRealVar* g3ValHPlus = new RooRealVar("g3ValHPlus", "g3ValHPlus", 0.);
    RooRealVar* g4ValHPlus = new RooRealVar("g4ValHPlus", "g4ValHPlus", 1.);
    RooRealVar* g5ValHPlus = new RooRealVar("g5ValHPlus", "g5ValHPlus", 0.);
    RooRealVar* g6ValHPlus = new RooRealVar("g6ValHPlus", "g6ValHPlus", 0.);
    RooRealVar* g7ValHPlus = new RooRealVar("g7ValHPlus", "g7ValHPlus", 0.);
    RooRealVar* g8ValHPlus = new RooRealVar("g8ValHPlus", "g8ValHPlus", 0.);
    RooRealVar* g9ValHPlus = new RooRealVar("g9ValHPlus", "g9ValHPlus", 0.);
    RooRealVar* g10ValHPlus = new RooRealVar("g10ValHPlus", "g10ValHPlus", 0.);
    RooRealVar* fz1ValHPlus = new RooRealVar("fz1ValHPlus", "fz1ValHPlus", 0.0);
    RooRealVar* fz2ValHPlus = new RooRealVar("fz2ValHPlus", "fz2ValHPlus", 0.0);

    RooSpinTwo_7D *myPDFHPlus;
    if ( offshell )
      myPDFHPlus = new RooSpinTwo_7D("myPDFHPlus","myPDFHPlus", *mX, *wplusmass, *wminusmass, *hs, *h1,*h2, *Phi, *Phi1, 
				       *c1Val, *c2Val, *c3Val, *c4Val, *c5Val, *c6Val, *c7Val, 
				       *useGTerm, *g1ValHPlus, *g2ValHPlus, *g3ValHPlus, *g4ValHPlus, 
				       *g5ValHPlus, *g6ValHPlus, *g7ValHPlus, *g8ValHPlus, *g9ValHPlus, *g10ValHPlus,
				       *fz1ValHPlus, *fz2ValHPlus, *R1Val, *R2Val, *mW, *gamW);
    else 
      myPDFHPlus = new RooSpinTwo_7D("myPDFHPlus","myPDFHPlus", *mX, *mW, *mW, *hs, *h1,*h2, *Phi, *Phi1, 
				       *c1Val, *c2Val, *c3Val, *c4Val, *c5Val, *c6Val, *c7Val, 
				       *useGTerm, *g1ValHPlus, *g2ValHPlus, *g3ValHPlus, *g4ValHPlus, 
				       *g5ValHPlus, *g6ValHPlus, *g7ValHPlus, *g8ValHPlus, *g9ValHPlus, *g10ValHPlus,
				       *fz1ValHPlus, *fz2ValHPlus, *R1Val, *R2Val, *mW, *gamW);
    TString fileNameHPlus;
    if ( useGTerm->getVal() > 0.) {
      fileNameHPlus = Form("TWW_2hplus_%.0f_JHU.root", mH);
    }
    
    std::cout << "Opening " << fileNameHPlus << "\n";
    TFile* finHPlus = new TFile(fileNameHPlus);
    TTree* tinHPlus = (TTree*) finHPlus->Get("angles");

    if ( offshell) 
      RooDataSet dataHPlus("dataHPlus","dataHPlus",tinHPlus,RooArgSet(*wplusmass, *wminusmass, *hs, *h1, *h2, *Phi, *Phi1));
    else 
      RooDataSet dataHPlus("dataHPlus","dataHPlus",tinHPlus,RooArgSet(*hs, *h1, *h2, *Phi, *Phi1));



    
    // P L O T   . . .  
    // (All parameters fixed, no fitting, just looking at the shape of the PDFs w.r.t. the data)
    if ( draw ) {

      bool drawmplus = true;
      bool drawhminus = true;
      bool drawhplus = true;
      bool drawpaper = true;
      double rescale = 1.0;
      if ( drawpaper ) 
	rescale = .001;

      TH1F* dum0 = new TH1F("dum0","dum0",1,0,1); dum0->SetLineColor(kRed); dum0->SetMarkerColor(kBlack); dum0->SetLineWidth(3);
      TH1F* dum1 = new TH1F("dum1","dum1",1,0,1); dum1->SetLineColor(kBlue); dum1->SetMarkerColor(kBlack); dum1->SetMarkerStyle(24), dum1->SetLineWidth(3);  
      TH1F* dum2 = new TH1F("dum2","dum2",1,0,1); dum2->SetLineColor(kGreen); dum2->SetMarkerColor(kBlack); dum2->SetMarkerStyle(21), dum2->SetLineWidth(3); // 2L+
      
      TLegend * box3 = new TLegend(0.1,0.1,0.9,0.92);
      box3->SetFillColor(0);
      box3->SetBorderSize(0);

      if ( drawmplus ) 
	box3->AddEntry(dum0,Form("X(%.0f)#rightarrow WW JP = 2m+", mH),"lp");
      if ( drawhminus )
	box3->AddEntry(dum1,Form("X(%.0f)#rightarrow WW JP = 2h-", mH),"lp");
      if ( drawhplus ) 
	box3->AddEntry(dum2,Form("X(%.0f)#rightarrow WW JP = 2h+,", mH),"lp");
  
      
      // 
      //  h1
      // 
      RooPlot* h1frame =  h1->frame(20);
      h1frame->GetXaxis()->CenterTitle();
      h1frame->GetYaxis()->CenterTitle();
      h1frame->GetYaxis()->SetTitle(" ");
      
      double ymax_h1;
      TH1F *h1_mplus = new TH1F("h1_mplus", "h1_mplus", 20, -1, 1);
      tin->Project("h1_mplus", "costheta1");
      ymax_h1 = h1_mplus->GetMaximum();
      
      TH1F *h1_hminus = new TH1F("h1_hminus", "h1_hminus", 20, -1, 1);
      tinMinus->Project("h1_hminus", "costheta1");
      ymax_h1 = h1_hminus->GetMaximum() > ymax_h1 ? h1_hminus->GetMaximum() : ymax_h1;
      
      TH1F *h1_hplus = new TH1F("h1_hplus", "h1_hplus", 20, -1, 1);
      tinHPlus->Project("h1_hplus", "costheta1");
      ymax_h1 = h1_hplus->GetMaximum() > ymax_h1 ? h1_hplus->GetMaximum() : ymax_h1;
      
      if ( drawmplus ) {
	data.plotOn(h1frame, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDF->plotOn(h1frame, LineColor(kRed),LineWidth(2), Normalization(rescale));
      }
      if ( drawhminus ) {
	dataMinus.plotOn(h1frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDFMinus->plotOn(h1frame, LineColor(kBlue),LineWidth(2), Normalization(rescale));
      }
      if ( drawhplus ) {
	dataHPlus.plotOn(h1frame, MarkerColor(kGreen+3),MarkerStyle(25),MarkerSize(1.5),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDFHPlus->plotOn(h1frame, LineColor(kGreen+3),LineWidth(2), Normalization(rescale));
      }
      if ( rescale != 1. )
	h1frame->GetYaxis()->SetRangeUser(0, ymax_h1  * rescale * 1.3);
      
      
      // 
      //  h2
      // 
      
      RooPlot* h2frame =  h2->frame(20);
      h2frame->GetXaxis()->CenterTitle();
      h2frame->GetYaxis()->CenterTitle();
      h2frame->GetYaxis()->SetTitle(" ");
      
      double ymax_h2;
      TH1F *h2_mplus = new TH1F("h2_mplus", "h2_mplus", 20, -1, 1);
      tin->Project("h2_mplus", "costheta2");
      ymax_h2 = h2_mplus->GetMaximum();
      
      TH1F *h2_hminus = new TH1F("h2_hminus", "h2_hminus", 20, -1, 1);
      tinMinus->Project("h2_hminus", "costheta2");
      ymax_h2 = h2_hminus->GetMaximum() > ymax_h2 ? h2_hminus->GetMaximum() : ymax_h2;
      
      TH1F *h2_hplus = new TH1F("h2_hplus", "h2_hplus", 20, -1, 1);
      tinHPlus->Project("h2_hplus", "costheta2");
      ymax_h2 = h2_hplus->GetMaximum() > ymax_h2 ? h2_hplus->GetMaximum() : ymax_h2;
      
      
      if ( drawmplus ) {
	data.plotOn(h2frame, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDF->plotOn(h2frame, LineColor(kRed),LineWidth(2), Normalization(rescale));
      }
      if ( drawhminus ) {
	dataMinus.plotOn(h2frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDFMinus->plotOn(h2frame, LineColor(kBlue),LineWidth(2), Normalization(rescale));
      }
      if ( drawhplus ) {
	dataHPlus.plotOn(h2frame, MarkerColor(kGreen+3),MarkerStyle(25),MarkerSize(1.5),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDFHPlus->plotOn(h1frame, LineColor(kGreen+3),LineWidth(2), Normalization(rescale));
      }
      if ( rescale != 1. ) 
	h2frame->GetYaxis()->SetRangeUser(0, ymax_h2  * rescale * 1.3);
      
      //
      // Phi
      // 
      RooPlot* Phiframe =  Phi->frame(20);
      
      Phiframe->GetXaxis()->CenterTitle();
      Phiframe->GetYaxis()->CenterTitle();
      Phiframe->GetYaxis()->SetTitle(" ");
      
      double ymax_Phi;
      TH1F *Phi_mplus = new TH1F("Phi_mplus", "Phi_mplus", 20,  -TMath::Pi(), TMath::Pi());
      tin->Project("Phi_mplus", "phi");
      ymax_Phi = Phi_mplus->GetMaximum();
      
      TH1F *Phi_hminus = new TH1F("Phi_hminus", "Phi_hminus", 20,  -TMath::Pi(), TMath::Pi());
      tinMinus->Project("Phi_hminus", "phi");
      ymax_Phi = Phi_hminus->GetMaximum() > ymax_Phi ? Phi_hminus->GetMaximum() : ymax_Phi;
      
      TH1F *Phi_hplus = new TH1F("Phi_hplus", "Phi_hplus", 20,  -TMath::Pi(), TMath::Pi());
      tinHPlus->Project("Phi_hplus", "phi");
      ymax_Phi = Phi_hplus->GetMaximum() > ymax_Phi ? Phi_hplus->GetMaximum() : ymax_Phi;
      
      if ( drawmplus ) {
	data.plotOn(Phiframe, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDF->plotOn(Phiframe, LineColor(kRed),LineWidth(2), Normalization(rescale));
      }
      if ( drawhminus ) {
	dataMinus.plotOn(Phiframe, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDFMinus->plotOn(Phiframe, LineColor(kBlue),LineWidth(2), Normalization(rescale));
      }
      if ( drawhplus ) {
	dataHPlus.plotOn(Phiframe, MarkerColor(kGreen+3),MarkerStyle(25),MarkerSize(1.5),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDFHPlus->plotOn(Phiframe, LineColor(kGreen+3),LineWidth(2), Normalization(rescale));
      }
      if ( rescale != 1. ) 
	Phiframe->GetYaxis()->SetRangeUser(0, ymax_Phi  * rescale * 1.3);
      
      // 
      //  hs 
      // 
      RooPlot* hsframe =  hs->frame(20);
      
      hsframe->GetXaxis()->CenterTitle();
      hsframe->GetYaxis()->CenterTitle();
      hsframe->GetYaxis()->SetTitle(" ");
      
      double ymax_hs;
      TH1F *hs_mplus = new TH1F("hs_mplus", "hs_mplus", 20, -1, 1);
      tin->Project("hs_mplus", "costhetastar");
      ymax_hs = hs_mplus->GetMaximum();
      
      TH1F *hs_hminus = new TH1F("hs_hminus", "hs_hminus", 20, -1, 1);
      tinMinus->Project("hs_hminus", "costhetastar");
      ymax_hs = hs_hminus->GetMaximum() > ymax_hs ? hs_hminus->GetMaximum() : ymax_hs;
      
      TH1F *hs_hplus = new TH1F("hs_hplus", "hs_hplus", 20, -1, 1);
      tinHPlus->Project("hs_hplus", "costhetastar");
      ymax_hs = hs_hplus->GetMaximum() > ymax_hs ? hs_hplus->GetMaximum() : ymax_hs;
      
      if ( drawmplus ) {
	data.plotOn(hsframe, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDF->plotOn(hsframe, LineColor(kRed),LineWidth(2), Normalization(rescale));
      }
      if ( drawhminus ) {
	dataMinus.plotOn(hsframe, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDFMinus->plotOn(hsframe, LineColor(kBlue),LineWidth(2), Normalization(rescale));
      }
      if ( drawhplus ) {
	dataHPlus.plotOn(hsframe, MarkerColor(kGreen+3),MarkerStyle(25),MarkerSize(1.5),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDFHPlus->plotOn(hsframe, LineColor(kGreen+3),LineWidth(2), Normalization(rescale));
      }
      if ( rescale != 1. )
	hsframe->GetYaxis()->SetRangeUser(0, ymax_hs  * rescale * 1.3);
      
      
      //
      // Phi1
      // 
      RooPlot* Phi1frame =  Phi1->frame(20);
      
      Phi1frame->GetXaxis()->CenterTitle();
      Phi1frame->GetYaxis()->CenterTitle();
      Phi1frame->GetYaxis()->SetTitle(" ");
      
      double ymax_Phi1;
      TH1F *Phi1_mplus = new TH1F("Phi1_mplus", "Phi1_mplus", 20, -TMath::Pi(), TMath::Pi());
      tin->Project("Phi1_mplus", "phistar1");
      ymax_Phi1 = Phi1_mplus->GetMaximum();
      
      TH1F *Phi1_hminus = new TH1F("Phi1_hminus", "Phi1_hminus", 20, -TMath::Pi(), TMath::Pi());
      tinMinus->Project("Phi1_hminus", "phistar1");
      ymax_Phi1 = Phi1_hminus->GetMaximum() > ymax_Phi1 ? Phi1_hminus->GetMaximum() : ymax_Phi1;
      
      TH1F *Phi1_hplus = new TH1F("Phi1_hplus", "Phi1_hplus", 20, -TMath::Pi(), TMath::Pi());
      tinHPlus->Project("Phi1_hplus", "phistar1");
      ymax_Phi1 = Phi1_hplus->GetMaximum() > ymax_Phi1 ? Phi1_hplus->GetMaximum() : ymax_Phi1;
      
      if ( drawmplus ) {
	data.plotOn(Phi1frame, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDF->plotOn(Phi1frame, LineColor(kRed),LineWidth(2), Normalization(rescale));
      }
      if ( drawhminus ) {
	dataMinus.plotOn(Phi1frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDFMinus->plotOn(Phi1frame, LineColor(kBlue),LineWidth(2), Normalization(rescale));
      }
      if ( drawhplus ) {
	dataHPlus.plotOn(Phi1frame, MarkerColor(kGreen+3),MarkerStyle(25),MarkerSize(1.5),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDFHPlus->plotOn(Phi1frame, LineColor(kGreen+3),LineWidth(2), Normalization(rescale));
      }
      if ( rescale != 1. ) 
	Phi1frame->GetYaxis()->SetRangeUser(0, ymax_Phi1  * rescale * 1.3);
      
      
      
      if ( offshell ) {
	RooPlot* w1frame =  wplusmass->frame(50);
	w1frame->GetXaxis()->CenterTitle();
	w1frame->GetYaxis()->CenterTitle();
	w1frame->GetYaxis()->SetTitle(" ");
	
	double ymax_w1;
	TH1F *w1_mplus = new TH1F("w1_mplus", "w1_mplus", 50, 1e-09, 120);
	tin->Project("w1_mplus", "wplusmass");
	ymax_w1 = w1_mplus->GetMaximum();
	
	TH1F *w1_hminus = new TH1F("w1_hminus", "w1_hminus", 50, 1e-09, 120);
	tinMinus->Project("w1_hminus", "wplusmass");
	ymax_w1 = w1_hminus->GetMaximum() > ymax_w1 ? w1_hminus->GetMaximum() : ymax_w1;
	
	TH1F *w1_hplus = new TH1F("w1_hplus", "w1_hplus", 50, 1e-09, 120);
	tinHPlus->Project("w1_hplus", "wplusmass");
	ymax_w1 = w1_hplus->GetMaximum() > ymax_w1 ? w1_hplus->GetMaximum() : ymax_w1;
	
	if ( drawmplus ) {
	  data.plotOn(w1frame, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	  myPDF->plotOn(w1frame, LineColor(kRed),LineWidth(2), Normalization(rescale));
	}
	if ( drawhminus ) {
	  dataMinus.plotOn(w1frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	  myPDFMinus->plotOn(w1frame, LineColor(kBlue),LineWidth(2), Normalization(rescale));
	}
	if ( drawhplus ) {
	  dataHPlus.plotOn(w1frame, MarkerColor(kGreen+3),MarkerStyle(25),MarkerSize(1.5),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	  myPDFHPlus->plotOn(w1frame, LineColor(kGreen+3),LineWidth(2), Normalization(rescale));
	}
	if ( rescale != 1. ) 
	  w1frame->GetYaxis()->SetRangeUser(0, ymax_w1  * rescale * 1.5);
	
	// 
	//  wminus
	// 
	RooPlot* w2frame =  wminusmass->frame(50);
	
	w2frame->GetXaxis()->CenterTitle();
	w2frame->GetYaxis()->CenterTitle();
	w2frame->GetYaxis()->SetTitle(" ");
	
	double ymax_w2;
	TH1F *w2_mplus = new TH1F("w2_mplus", "w2_mplus", 50, 1e-09, 120);
	tin->Project("w2_mplus", "wminusmass");
	ymax_w2 = w2_mplus->GetMaximum();
	
	TH1F *w2_hminus = new TH1F("w2_hminus", "w2_hminus", 50, 1e-09, 120);
	tinMinus->Project("w2_hminus", "wminusmass");
	ymax_w2 = w2_hminus->GetMaximum() > ymax_w2 ? w2_hminus->GetMaximum() : ymax_w2;
	
	TH1F *w2_hplus = new TH1F("w2_hplus", "w2_hplus", 50, 1e-09, 120);
	tinHPlus->Project("w2_hplus", "wminusmass");
	ymax_w2 = w2_hplus->GetMaximum() > ymax_w2 ? w2_hplus->GetMaximum() : ymax_w2;
	
	if ( drawmplus ) {
	  data.plotOn(w2frame, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	  myPDF->plotOn(w2frame, LineColor(kRed),LineWidth(2), Normalization(rescale));
	}
	if ( drawhminus ) {
	  dataMinus.plotOn(w2frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	  myPDFMinus->plotOn(w2frame, LineColor(kBlue),LineWidth(2), Normalization(rescale));
	}
	if ( drawhplus ) {
	  dataHPlus.plotOn(w2frame, MarkerColor(kGreen+3),MarkerStyle(25),MarkerSize(1.5),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	  myPDFHPlus->plotOn(w2frame, LineColor(kGreen+3),LineWidth(2), Normalization(rescale));
	}
	if ( rescale != 1. ) 
	  w2frame->GetYaxis()->SetRangeUser(0, ymax_w2  * rescale * 1.5);
      }
    }
    if ( drawpaper ) {
      TCanvas* can =new TCanvas("can","can",600,600);
      
      if ( offshell ) {
	w1frame->GetXaxis()->SetTitle("m_{l#nu} [GeV]");
	w1frame->Draw();
	can->Print(Form("paperplots/wplusmass_%.0fGeV_spin2_3in1_ww.eps", mH));
	can->SaveAs(Form("paperplots/wplusmass_%.0fGeV_spin2_3in1_ww.C", mH));
      }
      
      can->Clear();
      hsframe->Draw();
      can->Print(Form("paperplots/costhetastar_%.0fGeV_spin2_3in1_ww.eps", mH));      
      can->SaveAs(Form("paperplots/costhetastar_%.0fGeV_spin2_3in1_ww.C", mH));      
      
      can->Clear();
      Phi1frame->Draw();
      can->Print(Form("paperplots/phistar1_%.0fGeV_spin2_3in1_ww.eps", mH));      
      can->SaveAs(Form("paperplots/phistar1_%.0fGeV_spin2_3in1_ww.C", mH));      

      can->Clear();
      h1frame->GetXaxis()->SetTitle("cos#theta_{1} or cos#theta_{2}");
      h1frame->Draw();
      can->Print(Form("paperplots/costheta1_%.0fGeV_spin2_3in1_ww.eps", mH));
      can->SaveAs(Form("paperplots/costheta1_%.0fGeV_spin2_3in1_ww.C", mH));

      can->Clear();
      Phiframe->Draw();
      can->Print(Form("paperplots/phi_%.0fGeV_spin2_3in1_ww.eps", mH));      
      can->SaveAs(Form("paperplots/phi_%.0fGeV_spin2_3in1_ww.C", mH));      

      }      else {
      
      TCanvas* czz = new TCanvas( "czz", "czz", 1000, 600 );
      czz->Divide(4,2);
      
      if ( offshell ) {
	czz->cd(1);
	w1frame->Draw();
	
	czz->cd(2);
	w2frame->Draw();
      }
      
      czz->cd(3);
      hsframe->Draw();
      
      czz->cd(4);
      box3->Draw();
      
      czz->cd(5);
      Phi1frame->Draw();
      
      czz->cd(6);
      h1frame->Draw();
      
      czz->cd(7);
      h2frame->Draw();
      
      czz->cd(8);
      Phiframe->Draw();
      
      if ( useGTerm->getVal() > 0.) {
	czz->SaveAs(Form("epsfiles/angles_TWW%.0f_JHU_7D.eps", mH));
	czz->SaveAs(Form("pngfiles/angles_TWW%.0f_JHU_7D.png", mH));
      } else {
	czz->SaveAs(Form("epsfiles/angles_TWW%.0f_JHU_7D_GenFromC.eps", mH));
	czz->SaveAs(Form("pngfiles/angles_TWW%.0f_JHU_7D_GenFromC.png", mH));
      }
    }
}
Esempio n. 18
0
void drawCtauMass2DPlot(RooWorkspace& myws,   // Local workspace
                        string outputDir,     // Output directory
                        struct KinCuts cut,   // Variable with current kinematic cuts
                        string plotLabel,     // The label used to define the output file name
                        // Select the type of datasets to fit
                        string DSTAG,         // Specifies the type of datasets: i.e, DATA, MCJPSINP, ...
                        bool isPbPb,          // Define if it is PbPb (True) or PP (False)\
                        // Select the drawing options
                        map<string, double> binWidth={} // User-defined Location of the fit results
                        ) 
{

  gStyle->SetOptStat(0);

  if (DSTAG.find("_")!=std::string::npos) DSTAG.erase(DSTAG.find("_"));

  double minRangeCtau = -0.5;
  double maxRangeCtau = 2.0;
  int nBinsCtau = min(int( round((maxRangeCtau - minRangeCtau)/binWidth["CTAU"]*2) ), 1000);
  //  myws.var("ctau")->setBin(nBinsCtau, Binning(nBinsCtau, minRangeCtau, maxRangeCtau));

  double minRangeMass = cut.dMuon.M.Min;
  double maxRangeMass = cut.dMuon.M.Max;
  int nBinsMass = min(int( round((maxRangeMass - minRangeMass)/binWidth["MASS"]) ), 1000);
  //  myws.var("invMass")->setBin(nBinsCtau, Binning(nBinsCtau, minRangeCtau, maxRangeCtau));
  string pdfTotName  = Form("pdfCTAUMASS_Tot_%s", (isPbPb?"PbPb":"PP"));
  TH1* hPDF = ((RooAbsReal*)myws.pdf(pdfTotName.c_str()))->createHistogram("PDF 2D",*myws.var("ctau"), Extended(kTRUE), Binning(nBinsCtau, minRangeCtau, maxRangeCtau), YVar(*myws.var("invMass"), Binning(nBinsMass, minRangeMass, maxRangeMass)));

  string dsOSName = Form("dOS_%s_%s", DSTAG.c_str(), (isPbPb?"PbPb":"PP"));
  TH1* hDATA = ((RooDataSet*)myws.data(dsOSName.c_str()))->createHistogram("DATA 2D",*myws.var("ctau"), Binning(nBinsCtau, minRangeCtau, maxRangeCtau), YVar(*myws.var("invMass"), Binning(nBinsMass, minRangeMass, maxRangeMass)));
  
  // Create the main canvas
  TCanvas *cFigPDF   = new TCanvas(Form("cCtauMassPDF_%s", (isPbPb?"PbPb":"PP")), "cCtauMassPDF",2000,2000);
  cFigPDF->cd();

  hPDF->GetYaxis()->CenterTitle(kTRUE);
  hPDF->GetYaxis()->SetTitleOffset(2.1);
  hPDF->GetYaxis()->SetTitleSize(0.035);
  hPDF->GetYaxis()->SetLabelSize(0.025);
  hPDF->GetYaxis()->SetTitle("Mass [GeV/c]");
  hPDF->GetXaxis()->CenterTitle(kTRUE);
  hPDF->GetXaxis()->SetTitleOffset(2.1);
  hPDF->GetXaxis()->SetTitleSize(0.035);
  hPDF->GetXaxis()->SetLabelSize(0.025);
  hPDF->GetXaxis()->SetTitle("#font[12]{l}_{J/#psi} (mm)");
  hPDF->GetZaxis()->SetTitleOffset(2.0);
  hPDF->GetZaxis()->SetTitleSize(0.035);
  hPDF->GetZaxis()->SetLabelSize(0.025);
  hPDF->GetYaxis()->SetRangeUser(minRangeMass, maxRangeMass);
  hPDF->GetXaxis()->SetRangeUser(minRangeCtau, maxRangeCtau);
  cFigPDF->SetLogz(kTRUE);

  hPDF->Draw("LEGO2");

  gSystem->mkdir(Form("%sctauMass/%s/plot/pdf2D/", outputDir.c_str(), DSTAG.c_str()), kTRUE); 
  cFigPDF->SaveAs(Form("%sctauMass/%s/plot/pdf2D/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.pdf", outputDir.c_str(), DSTAG.c_str(), "CTAUMASSPDF", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));

  cFigPDF->Clear();
  cFigPDF->Close();

  // Create the main canvas
  TCanvas *cFigDATA   = new TCanvas(Form("cCtauMassPDF_%s", (isPbPb?"PbPb":"PP")), "cCtauMassPDF",2000,2000);
  cFigDATA->cd();

  hDATA->GetYaxis()->CenterTitle(kTRUE);
  hDATA->GetYaxis()->SetTitleOffset(2.1);
  hDATA->GetYaxis()->SetTitleSize(0.035);
  hDATA->GetYaxis()->SetLabelSize(0.025);
  hDATA->GetYaxis()->SetTitle("Mass [GeV/c]");
  hDATA->GetXaxis()->CenterTitle(kTRUE);
  hDATA->GetXaxis()->SetTitleOffset(2.1);
  hDATA->GetXaxis()->SetTitleSize(0.035);
  hDATA->GetXaxis()->SetLabelSize(0.025);
  hDATA->GetXaxis()->SetTitle("#font[12]{l}_{J/#psi} (mm)");
  hDATA->GetZaxis()->SetTitleOffset(2.0);
  hDATA->GetZaxis()->SetTitleSize(0.035);
  hDATA->GetZaxis()->SetLabelSize(0.025);
  hDATA->GetYaxis()->SetRangeUser(minRangeMass, maxRangeMass);
  hDATA->GetXaxis()->SetRangeUser(minRangeCtau, maxRangeCtau);
  cFigDATA->SetLogz(kTRUE);

  hDATA->Draw("LEGO2");

  gSystem->mkdir(Form("%sctauMass/%s/plot/pdf2D/", outputDir.c_str(), DSTAG.c_str()), kTRUE); 
  cFigDATA->SaveAs(Form("%sctauMass/%s/plot/pdf2D/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.pdf", outputDir.c_str(), DSTAG.c_str(), "CTAUMASSDATA", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));

  cFigDATA->Clear();
  cFigDATA->Close();
  
  delete hPDF;
  delete hDATA;

};
void determineWorkingPoint(TString algo="csv",TString baseURL="~/scratch0/top-nosyst/plotter.root")
{
  float workPoint(0.244);
  float sfb(1.020),    sfberr(0.04);      //from BTV-11-003
  float sflight(1.08), sflighterr(0.13);  //from BTV-11-002
  //  float sfb(0.99),        sfberr(0.099);      //from BTV-11-001
  //  float sflight(1.07882), sflighterr(0.244);  //from BTV-11-001
  if(algo=="tche")
    {
      workPoint=1.7;
      sfb=0.95; sfberr=0.095;
      sflight=1.08018; sflighterr=0.1125;
    }

  TObjArray bjets=getDistributionFromPlotter(algo+"b",baseURL);
  TObjArray lightjets=getDistributionFromPlotter(algo+"light",baseURL);
  
  TH1F *bDisc=(TH1F *) bjets.At(1);
  TH1F *lightDisc=(TH1F *) lightjets.At(1);
  
  setStyle();
  gStyle->SetOptFit(0);

  TCanvas *cnv = getNewCanvas("c","c",false);
  cnv->Clear();
  cnv->SetCanvasSize(1200,1200);
  cnv->SetWindowSize(1200,1200);
  cnv->Divide(2,2);

  //draw the discriminator
  TPad *p = (TPad *)cnv->cd(1); 
  bDisc->SetTitle("b");
  bDisc->SetLineColor(1);
  bDisc->SetMarkerColor(1);
  bDisc->SetMarkerStyle(20);
  bDisc->SetFillStyle(0);
  bDisc->DrawNormalized("histe1");
  lightDisc->SetLineColor(1);
  lightDisc->SetMarkerColor(1);
  lightDisc->SetMarkerStyle(24);
  lightDisc->SetFillStyle(0);
  lightDisc->SetTitle("udcsg");
  lightDisc->DrawNormalized("histe1same");
  TLegend *leg=p->BuildLegend();
  formatForCmsPublic(p,leg,"CMS simulation",2);

  //draw the b/light efficiencies
  p=(TPad *)cnv->cd(2);
  p->SetLogy();
  TGraphAsymmErrors *bEff     = getEfficiencyFrom(bDisc);
  TGraphAsymmErrors *lightEff = getEfficiencyFrom(lightDisc);
  bEff->SetMarkerStyle(20);
  bEff->SetFillStyle(0);
  bEff->Draw("ap");
  bEff->GetXaxis()->SetTitle(bDisc->GetXaxis()->GetTitle());
  bEff->GetYaxis()->SetTitle("Efficiency");
  lightEff->SetMarkerStyle(24);
  lightEff->SetFillStyle(0);
  lightEff->Draw("p");

  //draw relatively to a given working point
  p=(TPad *)cnv->cd(3);
  Double_t baseBEff=bEff->Eval(workPoint);
  TGraphAsymmErrors *relBEff=new TGraphAsymmErrors;
  relBEff->SetMarkerStyle(20);
  relBEff->SetFillStyle(0);
  Double_t baseLightEff=lightEff->Eval(workPoint);
  TGraphAsymmErrors *relLightEff=new TGraphAsymmErrors;
  relLightEff->SetMarkerStyle(24);
  relLightEff->SetFillStyle(0);
  for(int ip=0; ip<bEff->GetN(); ip++)
    {
      Double_t cut, y,ey; 
      bEff->GetPoint(ip,cut,y);     ey = bEff->GetErrorY(ip);
      Double_t relEff(y/baseBEff);
      if(relEff<sfb+2*sfberr && relEff>sfb-2*sfberr)
	{
	  int ipt=relBEff->GetN();
	  relBEff->SetPoint(ipt,cut,relEff);
	  relBEff->SetPointError(ipt,0,0,ey/baseBEff,ey/baseBEff);
	}

      lightEff->GetPoint(ip,cut,y);     ey = lightEff->GetErrorY(ip);
      relEff=y/baseLightEff;
      //      if(relEff<sflight+7*sflighterr && relEff>sflight-7*sflighterr)
      if(relEff<sflight+3*sflighterr && relEff>sflight-3*sflighterr)
	{
	  int ipt=relLightEff->GetN();
	  relLightEff->SetPoint(ipt,cut,relEff);
	  relLightEff->SetPointError(ipt,0,0,ey/baseLightEff,ey/baseLightEff);
	}
    }

  relLightEff->Draw("ap");
  relLightEff->GetXaxis()->SetTitle( bDisc->GetXaxis()->GetTitle() );
  relLightEff->GetYaxis()->SetTitle( "#varepsilon/#varepsilon_{0}" );
  relLightEff->Fit("expo","Q+");
  TF1 *ffunc=relLightEff->GetFunction("expo");
  float newLightCut=(TMath::Log(sflight)-ffunc->GetParameter(0))/ffunc->GetParameter(1);
  float newLightCutErrPlus=(TMath::Log(sflight+sflighterr)-ffunc->GetParameter(0))/ffunc->GetParameter(1)-newLightCut;
  float newLightCutErrMinus=(TMath::Log(sflight-sflighterr)-ffunc->GetParameter(0))/ffunc->GetParameter(1)-newLightCut;
  TArrow *lightArrow = new TArrow(newLightCut, sflight-3*sflighterr, newLightCut, sflight-3*sflighterr*0.8, 0.02, "<|");
  lightArrow->SetLineColor(kGray+2);
  lightArrow->SetFillColor(kGray+2);
  lightArrow->Draw("SAME <|");

  relBEff->Draw("p");
  relBEff->Fit("expo","Q+");
  ffunc=relBEff->GetFunction("expo");
  float newBCut=(TMath::Log(sfb)-ffunc->GetParameter(0))/ffunc->GetParameter(1);
  float newBCutErrPlus=(TMath::Log(sfb+sfberr)-ffunc->GetParameter(0))/ffunc->GetParameter(1)-newBCut;
  float newBCutErrMinus=(TMath::Log(sfb-sfberr)-ffunc->GetParameter(0))/ffunc->GetParameter(1)-newBCut;
  cout <<  sfb << " " << sfb+sfberr << " " << sfb-sfberr << endl;
  TArrow *bArrow    = new TArrow(newBCut, sflight-3*sflighterr, newBCut, sflight-3*sflighterr*0.8, 0.02, "<|");
  bArrow->Draw("SAME <|");

  //draw epsilon_b vs epsilon_q
  p=(TPad *)cnv->cd(4);
  p->SetLogy();

  TGraphAsymmErrors *perf=new TGraphAsymmErrors;
  perf->SetName("algoperformance");
  perf->SetMarkerStyle(20);
  perf->SetFillStyle(0);
  for(int ip=0; ip<bEff->GetN(); ip++)
    {
      Double_t cut;
      Double_t x,ex; bEff->GetPoint(ip,cut,x);     ex = bEff->GetErrorY(ip);
      Double_t y,ey; lightEff->GetPoint(ip,cut,y); ey = lightEff->GetErrorY(ip);
      perf->SetPoint(ip,x,y);
      perf->SetPointError(ip,ex,ex,ey,ey);
    }
  perf->Draw("ap");
  perf->GetXaxis()->SetTitle( bEff->GetTitle() );
  perf->GetYaxis()->SetTitle( lightEff->GetTitle() );

  //new performance expected after applying the new cuts
  TGraphAsymmErrors *newperf=new TGraphAsymmErrors;
  newperf->SetName("newalgoperformance");
  newperf->SetMarkerStyle(24);
  newperf->SetFillStyle(0);
  newperf->SetLineWidth(2);
  newperf->SetLineColor(kRed);
  newperf->SetLineColor(kRed);
  newperf->SetPoint(0,baseBEff*sfb,baseLightEff*sflight);
  newperf->SetPointError(0,baseBEff*sfberr,baseBEff*sfberr,baseLightEff*sflighterr,baseLightEff*sflighterr);
  newperf->Draw("p");

  cnv->Modified();
  cnv->Update();
  cnv->SaveAs("discFlavor.C");  
  cnv->SaveAs("discFlavor.png");  


  cout << "[determineWorkingPoint]" << endl
       << "To emulate the measured scale-factors you can use the following new cuts per jet flavor" << endl
       << "SF-b : "     << newBCut << " +" << newBCutErrPlus << " " << newBCutErrMinus << endl
       << "SF-light : " << newLightCut << " +" << newLightCutErrPlus << " " << newLightCutErrMinus << endl;
}
void KKpiFlatDalitzFractions(){

  Float_t M=1.9686;
  Float_t m1=.49368;
  Float_t m2=.49368;
  Float_t m3=.13957;
  

  //Define the Histogram with the boundaries
  Float_t XMin=.8;
  Float_t XMax=3.5;
  Float_t YMin=.3;
  Float_t YMax=2.3;
  TH2F HTop("HTop","",Npoints,XMin,XMax,Npoints,YMin,YMax); 
  HTop.SetStats(0);
  TH2F HBot("HBot","",Npoints,XMin,XMax,Npoints,YMin,YMax);
  HBot.SetStats(0);
  Double_t x=0;
  Double_t y=0;
  Float_t xmin=(m1+m2)*(m1+m2);
  Float_t xmax=(M-m3)*(M-m3);
  Float_t xstep=(xmax-xmin)/Npoints;
  Float_t x0=0;
  Float_t y0=0;

  Float_t E2,E3;
  
  //First do the top points from left to right
  for(Int_t p=0;p<Npoints;p++){
    x=xmin+p*xstep;
    E2=(x-m1*m1+m2*m2)/(2*sqrt(x));
    E3=(M*M-x-m3*m3)/(2*sqrt(x));
    y=(E2+E3)*(E2+E3)-pow((sqrt(E2*E2-m2*m2)-sqrt(E3*E3-m3*m3)),2);      
    HTop.Fill(x,y,1);
  }

  //Now do the bottom points from right to left
  for(Int_t p=0;p<Npoints;p++){
    x=xmax-p*xstep;//move backwards to draw with line   
    E2=(x-m1*m1+m2*m2)/(2*sqrt(x));
    E3=(M*M-x-m3*m3)/(2*sqrt(x));
    y=(E2+E3)*(E2+E3)-pow((sqrt(E2*E2-m2*m2)+sqrt(E3*E3-m3*m3)),2);  
    HBot.Fill(x,y,1);
  }
  
  for(Int_t bx=1;bx<=Npoints;bx++)
    for(Int_t by=1;by<=Npoints;by++){
      if(HTop.GetBinContent(bx,by)>0)HTop.SetBinContent(bx,by,1);
      if(HBot.GetBinContent(bx,by)>0)HBot.SetBinContent(bx,by,1);
    }
 
  TCanvas C;
  C.Print("KKpiFlatDalitzFractions.ps[");

  C.Clear();
  HTop.Draw("col");
  C.Print("KKpiFlatDalitzFractions.ps");
  C.Clear();
  HBot.Draw("col");
  C.Print("KKpiFlatDalitzFractions.ps");

  C.Clear();
  HTop.Draw("col");
  HBot.Draw("col same");
  C.Print("KKpiFlatDalitzFractions.ps");



  ////////////////////////////////
  //Create the arrays which map the y bin for each x bin
  Int_t TopBound[Npoints];
  Int_t BotBound[Npoints];
  for(Int_t bx=0;bx<Npoints;bx++){
    TopBound[bx]=0;
    BotBound[bx]=Npoints;
    for(Int_t by=0;by<Npoints;by++){
      if(HTop.GetBinContent(bx+1,by+1)>0)TopBound[bx]=by;
      if(HBot.GetBinContent(bx+1,by+1)>0)BotBound[bx]=by;
    }
  }
  
  //Dalitz1 Bounds
  Float_t xwidth=(XMax-XMin)/Npoints;
  Float_t ywidth=(YMax-YMin)/Npoints;
  
  Int_t Dalitz1Xmin=(int)((.95-XMin)/xwidth);
  Int_t Dalitz1Xmax=(int)((1.15-XMin)/xwidth);

  Int_t Dalitz2Ymin=(int)((.6-YMin)/ywidth);
  Int_t Dalitz2Ymax=(int)((1.-YMin)/ywidth);


  ////////////Throw random points on the full range and determine if it is inside  the physical region
  TH2F HDalitzSig("HDalitzSig","",Npoints,XMin,XMax,Npoints,YMin,YMax); 
  HDalitzSig.SetStats(0);
  TH2F HDalitz1("HDalitz1","",Npoints,XMin,XMax,Npoints,YMin,YMax); 
  HDalitz1.SetStats(0);
  TH2F HDalitz2("HDalitz2","",Npoints,XMin,XMax,Npoints,YMin,YMax); 
  HDalitz2.SetStats(0);
  TH2F HDalitz3("HDalitz3","",Npoints,XMin,XMax,Npoints,YMin,YMax); 
  HDalitz3.SetStats(0);
  TRandom rand;
  for(Int_t i=0;i<Npoints*Npoints*2;i++){
    Int_t xr=(int)rand.Uniform(1,Npoints+1);
    Int_t yr=(int)rand.Uniform(1,Npoints+1);
    if(BotBound[xr]<=yr&&yr<=TopBound[xr]){
      HDalitzSig.SetBinContent(xr,yr,HDalitzSig.GetBinContent(xr,yr)+1);
      
      if(Dalitz1Xmin<=xr&&xr<=Dalitz1Xmax){
	HDalitz1.SetBinContent(xr,yr,HDalitz1.GetBinContent(xr,yr)+1);
      }
      else if(Dalitz2Ymin<=yr&&yr<=Dalitz2Ymax){
	HDalitz2.SetBinContent(xr,yr,HDalitz2.GetBinContent(xr,yr)+1);
      }else HDalitz3.SetBinContent(xr,yr,HDalitz3.GetBinContent(xr,yr)+1);

      
    }
  }

  C.Clear();
  //HTop.Draw("col");
  //HBot.Draw("col same");
  HDalitzSig.Draw("col");
  C.Print("KKpiFlatDalitzFractions.ps");

  C.Clear();
  //HTop.Draw("col");
  //HBot.Draw("col same");
  HDalitz1.Draw("col ");
  C.Print("KKpiFlatDalitzFractions.ps");

  C.Clear();
  //HTop.Draw("col");
  //HBot.Draw("col same");
  HDalitz2.Draw("col");
  C.Print("KKpiFlatDalitzFractions.ps");

  C.Clear();
  //HTop.Draw("col");
  //HBot.Draw("col same");
  HDalitz3.Draw("col");
  C.Print("KKpiFlatDalitzFractions.ps");

  cout<<"Fraction1 = "<<HDalitz1.Integral()/(float)HDalitzSig.Integral()<<endl;
  cout<<"Fraction2 = "<<HDalitz2.Integral()/(float)HDalitzSig.Integral()<<endl;
  cout<<"Fraction3 = "<<HDalitz3.Integral()/(float)HDalitzSig.Integral()<<endl;


  C.Print("KKpiFlatDalitzFractions.ps]");
  

}
Esempio n. 21
0
int singleMu_plots() {

  // Parameters  
  FLAG *flag = new FLAG;
  flag->doSta = true;
  flag->doGlb = false;
  
  string data2010  = "/castor/cern.ch/user/m/miheejo/openHLT/cms442p5/HICorePhysics_Skim_MinimumBias_RAW/openhlt_2010HICorePhysicsMB.root";
  string data2011  = "/castor/cern.ch/user/m/miheejo/openHLT/RD2011/HIDiMuon_HIRun2011-PromptReco-v1_RECO/openhlt_PromptReco_181611_181778.root";
    //"/castor/cern.ch/user/m/miheejo/openHLT/RD2011/HIData2011_rawToRecoV3_LSF/openhlt_HIData2011_rawToRecoV3_LSF.root";

  // Check trigger list
  vector<string> triglist;
  triglist.push_back("HLT_HIL1DoubleMu0_HighQ_v1");
  triglist.push_back("HLT_HIL2DoubleMu3_v1");
  triglist.push_back("HLT_HIL3DoubleMuOpen_v1");
  triglist.push_back("HLT_HIL3DoubleMuOpen_Mgt2_OS_NoCowboy_v1");
  triglist.push_back("HLT_HIL2Mu3_v1");
  triglist.push_back("HLT_HIL2Mu7_v1");
  triglist.push_back("HLT_HIL2Mu15_v1");
  triglist.push_back("HLT_HIL2Mu3_NHitQ_v1");
  triglist.push_back("HLT_HIL3Mu3_v1");

  // Histograms
  TH2F *SingleGlb_Etapt_2010 = new TH2F("SingleGlb_etapt_2010","SingleGlb_etapt_2010;single mu #eta;single mu p_{T}",ETA,-2.4,2.4,PT,0,20);
  TH2F *SingleGlb_Etapt_2011 = new TH2F("SingleGlb_etapt_2011","SingleGlb_etapt_2011;single mu #eta;single mu p_{T}",ETA,-2.4,2.4,PT,0,20);
  TH2F *SingleGlb_Etaphi_2010 = new TH2F("SingleGlb_etaphi_2010","SingleGlb_etaphi_2010;single mu #eta;single mu #phi",ETA,-2.4,2.4,20,-PI,PI);
  TH2F *SingleGlb_Etaphi_2011 = new TH2F("SingleGlb_etaphi_2011","SingleGlb_etaphi_2011;single mu #eta;single mu #phi",ETA,-2.4,2.4,20,-PI,PI);

  TH1F *SingleGlb_Eta_2010 = new TH1F("SingleGlb_eta_2010","SingleGlb_eta_2010;single mu #eta",ETA,-2.4,2.4);
  TH1F *SingleGlb_Eta_2011 = new TH1F("SingleGlb_eta_2011","SingleGlb_eta_2011;single mu #eta",ETA,-2.4,2.4);
  TH1F *SingleGlb_Phi_2010 = new TH1F("SingleGlb_phi_2010","SingleGlb_phi_2010;single mu #phi",20,-PI,PI);
  TH1F *SingleGlb_Phi_2011 = new TH1F("SingleGlb_phi_2011","SingleGlb_phi_2011;single mu #phi",20,-PI,PI);
  TH1F *SingleGlb_Pt_2010 = new TH1F("SingleGlb_pt_2010","SingleGlb_pt_2010;single mu p_{T}",PT,0,20);
  TH1F *SingleGlb_Pt_2011 = new TH1F("SingleGlb_pt_2011","SingleGlb_pt_2011;single mu p_{T}",PT,0,20);

  TH2F *SingleGlb_Etapt_2010_qual = new TH2F("SingleGlb_etapt_2010_qual","SingleGlb_etapt_2010_qual;single mu #eta;single mu p_{T}",ETA,-2.4,2.4,PT,0,20);
  TH2F *SingleGlb_Etapt_2011_qual = new TH2F("SingleGlb_etapt_2011_qual","SingleGlb_etapt_2011_qual;single mu #eta;single mu p_{T}",ETA,-2.4,2.4,PT,0,20);
  TH2F *SingleGlb_Etaphi_2010_qual = new TH2F("SingleGlb_etaphi_2010_qual","SingleGlb_etaphi_2010_qual;single mu #eta;single mu #phi",ETA,-2.4,2.4,20,-PI,PI);
  TH2F *SingleGlb_Etaphi_2011_qual = new TH2F("SingleGlb_etaphi_2011_qual","SingleGlb_etaphi_2011_qual;single mu #eta;single mu #phi",ETA,-2.4,2.4,20,-PI,PI);

  TH1F *SingleGlb_Eta_2010_qual = new TH1F("SingleGlb_eta_2010_qual","SingleGlb_eta_2010_qual;single mu #eta",ETA,-2.4,2.4);
  TH1F *SingleGlb_Eta_2011_qual = new TH1F("SingleGlb_eta_2011_qual","SingleGlb_eta_2011_qual;single mu #eta",ETA,-2.4,2.4);
  TH1F *SingleGlb_Phi_2010_qual = new TH1F("SingleGlb_phi_2010_qual","SingleGlb_phi_2010_qual;single mu #phi",20,-PI,PI);
  TH1F *SingleGlb_Phi_2011_qual = new TH1F("SingleGlb_phi_2011_qual","SingleGlb_phi_2011_qual;single mu #phi",20,-PI,PI);
  TH1F *SingleGlb_Pt_2010_qual = new TH1F("SingleGlb_pt_2010_qual","SingleGlb_pt_2010_qual;single mu p_{T}",PT,0,20);
  TH1F *SingleGlb_Pt_2011_qual = new TH1F("SingleGlb_pt_2011_qual","SingleGlb_pt_2011_qual;single mu p_{T}",PT,0,20);


  // Input files
  // 2010 datafile
  TCastorFile   *input_2010 = new TCastorFile(data2010.c_str());
  FriendMuTree  *mutree_2010 = new FriendMuTree(input_2010,true); // Load HLTMuTree
  HltTree       *ohTree_2010 = new HltTree(input_2010,true,"hltana/HltTree");      // Load HltTree

  TTree         *muon_tree_2010;                             // Hold HLTMuTree
  TTree         *open_tree_2010;                             // Hold HltTree
  MUTREE        *muTree_2010 = new MUTREE;

  // 2011 datafile
  TCastorFile   *input_2011 = new TCastorFile(data2011.c_str());
  FriendMuTree  *mutree_2011 = new FriendMuTree(input_2011,true); // Load HLTMuTree
  HltTree       *ohTree_2011 = new HltTree(input_2011,true,"hltanalysis/HltTree");      // Load HltTree

  TTree         *muon_tree_2011;                             // Hold HLTMuTree
  TTree         *open_tree_2011;                             // Hold HltTree
  MUTREE        *muTree_2011 = new MUTREE;


  const unsigned int ntrig = triglist.size();
  int trig_2010[ntrig];                                // Trigger bits for muons
  int trig_2011[ntrig];                                // Trigger bits for muons
  open_tree_2010 = ohTree_2010->fChain;                           // Get TTree for trigger bits
  open_tree_2011 = ohTree_2011->fChain;                           // Get TTree for trigger bits
  for (unsigned int i=0; i < ntrig; i++) {
    string tmptrig = triglist[i];
    open_tree_2010->SetBranchAddress(tmptrig.c_str(),&trig_2010[i]);    // SetBranchAddress for trigger bits
    open_tree_2011->SetBranchAddress(tmptrig.c_str(),&trig_2011[i]);    // SetBranchAddress for trigger bits
  }

  muon_tree_2010 = mutree_2010->fChain;                           // Get TTree for muon objects
  muon_tree_2010->SetBranchAddress("Run",&muTree_2010->run);
  muon_tree_2010->SetBranchAddress("Event",&muTree_2010->event);
  muon_tree_2011 = mutree_2011->fChain;                           // Get TTree for muon objects
  muon_tree_2011->SetBranchAddress("Run",&muTree_2011->run);
  muon_tree_2011->SetBranchAddress("Event",&muTree_2011->event);
  if (flag->doSta && !flag->doGlb) {
   muon_tree_2010->SetBranchAddress("Sta_eta",muTree_2010->eta);
   muon_tree_2010->SetBranchAddress("Sta_pt",muTree_2010->pt);
   muon_tree_2010->SetBranchAddress("Sta_phi",muTree_2010->phi);
   muon_tree_2010->SetBranchAddress("Sta_nptl",&muTree_2010->nptl);
   muon_tree_2010->SetBranchAddress("Sta_charge",muTree_2010->charge);
   muon_tree_2011->SetBranchAddress("Sta_eta",muTree_2011->eta);
   muon_tree_2011->SetBranchAddress("Sta_pt",muTree_2011->pt);
   muon_tree_2011->SetBranchAddress("Sta_phi",muTree_2011->phi);
   muon_tree_2011->SetBranchAddress("Sta_nptl",&muTree_2011->nptl);
   muon_tree_2011->SetBranchAddress("Sta_charge",muTree_2011->charge);
  } else if (flag->doGlb && !flag->doSta) {
   muon_tree_2011->SetBranchAddress("Glb_eta",muTree_2011->eta);
   muon_tree_2011->SetBranchAddress("Glb_pt",muTree_2011->pt);
   muon_tree_2011->SetBranchAddress("Glb_phi",muTree_2011->phi);
   muon_tree_2011->SetBranchAddress("Glb_nptl",&muTree_2011->nptl);
   muon_tree_2011->SetBranchAddress("Glb_charge",muTree_2011->charge);
   muon_tree_2011->SetBranchAddress("Glb_nValMuHits",muTree_2011->nValMuHits);
   muon_tree_2011->SetBranchAddress("Glb_nValTrkHits",muTree_2011->nValTrkHits);
   muon_tree_2011->SetBranchAddress("Glb_nTrkFound",muTree_2011->nTrkFound);
   muon_tree_2011->SetBranchAddress("Glb_glbChi2_ndof",muTree_2011->glbChi2_ndof);
   muon_tree_2011->SetBranchAddress("Glb_trkChi2_ndof",muTree_2011->trkChi2_ndof);
   muon_tree_2011->SetBranchAddress("Glb_pixLayerWMeas",muTree_2011->pixLayerWMeas);
   muon_tree_2011->SetBranchAddress("Glb_trkDxy",muTree_2011->trkDxy);
   muon_tree_2011->SetBranchAddress("Glb_trkDz",muTree_2011->trkDz);

   muon_tree_2010->SetBranchAddress("Glb_eta",muTree_2010->eta);
   muon_tree_2010->SetBranchAddress("Glb_pt",muTree_2010->pt);
   muon_tree_2010->SetBranchAddress("Glb_phi",muTree_2010->phi);
   muon_tree_2010->SetBranchAddress("Glb_nptl",&muTree_2010->nptl);
   muon_tree_2010->SetBranchAddress("Glb_charge",muTree_2010->charge);
   muon_tree_2010->SetBranchAddress("Glb_nValMuHits",muTree_2010->nValMuHits);
   muon_tree_2010->SetBranchAddress("Glb_nValTrkHits",muTree_2010->nValTrkHits);
   muon_tree_2010->SetBranchAddress("Glb_nTrkFound",muTree_2010->nTrkFound);
   muon_tree_2010->SetBranchAddress("Glb_glbChi2_ndof",muTree_2010->glbChi2_ndof);
   muon_tree_2010->SetBranchAddress("Glb_trkChi2_ndof",muTree_2010->trkChi2_ndof);
   muon_tree_2010->SetBranchAddress("Glb_pixLayerWMeas",muTree_2010->pixLayerWMeas);
   muon_tree_2010->SetBranchAddress("Glb_trkDxy",muTree_2010->trkDxy);
   muon_tree_2010->SetBranchAddress("Glb_trkDz",muTree_2010->trkDz);
  } else {
    cout << "Choose doSta or doGlb or doGen!\n";
    return -1;
  }


  int nevt_2010=0;                  // # of events that has at least 1 muon trigger fired
  int nevt_2010_qual=0;                  // # of events that has at least 1 muon trigger fired
  // Loop over trees over 2010 trees
  for (int i=0; i<muon_tree_2010->GetEntries(); i++) {
    muon_tree_2010->GetEntry(i);
    ohTree_2010->GetEntry(i);
    open_tree_2010->GetEntry(i);

    ////////// Check muon trigger list
/*    flag->trig = false;
    for (unsigned int tidx=0; tidx<ntrig; tidx++) {
      if (trig_2010[tidx]) {         // At least one of the muon trigger is fired.
        flag->trig = true;
        break;
      }
    }
    if (!flag->trig) continue;  // If no muon triggers fired, go to the next event!
*/    
    nevt_2010++;
    bool qual=false;
    ////////// Load muons and fill up histograms
    for (int a=0; a < muTree_2010->nptl; a++) {

      SingleGlb_Etapt_2010->Fill(muTree_2010->eta[a],muTree_2010->pt[a]);
      SingleGlb_Etaphi_2010->Fill(muTree_2010->eta[a],muTree_2010->phi[a]);
      SingleGlb_Eta_2010->Fill(muTree_2010->eta[a]);
      SingleGlb_Pt_2010->Fill(muTree_2010->pt[a]);
      SingleGlb_Phi_2010->Fill(muTree_2010->phi[a]);

      if (flag->doGlb) {
        if(!isValidMu(flag, muTree_2010, a)) continue;    //Check glb muons are within acceptance range
      } else if (flag->doSta) {
        if(!isMuInAcc(flag, muTree_2010->eta[a], muTree_2010->pt[a])) continue;    //Check sta muons are within acceptance range
      }
      
      qual = true;

      SingleGlb_Etapt_2010_qual->Fill(muTree_2010->eta[a],muTree_2010->pt[a]);
      SingleGlb_Etaphi_2010_qual->Fill(muTree_2010->eta[a],muTree_2010->phi[a]);
      SingleGlb_Eta_2010_qual->Fill(muTree_2010->eta[a]);
      SingleGlb_Pt_2010_qual->Fill(muTree_2010->pt[a]);
      SingleGlb_Phi_2010_qual->Fill(muTree_2010->phi[a]);

    }
    if (qual) nevt_2010_qual++;

    if (i%1000 ==0)
    cout << "Event in 2010 datasets: " << i+1 << endl;
  }

  int nevt_2011=0;                  // # of events that has at least 1 muon trigger fired
  int nevt_2011_qual=0;                  // # of events that has at least 1 muon trigger fired
  // Loop over trees over 2011 trees
  for (int i=0; i<muon_tree_2011->GetEntries(); i++) {
    muon_tree_2011->GetEntry(i);
    ohTree_2011->GetEntry(i);
    open_tree_2011->GetEntry(i);

    ////////// Check muon trigger list
    flag->trig = false;
    for (unsigned int tidx=0; tidx<ntrig; tidx++) {
      if (trig_2011[tidx]) {         // At least one of the muon trigger is fired.
        flag->trig = true;
        break;
      }
    }
    if (!flag->trig) continue;  // If no muon triggers fired, go to the next event!

    nevt_2011++;
    bool qual=false;
    ////////// Load muons and fill up histograms
    for (int a=0; a < muTree_2011->nptl; a++) {
      SingleGlb_Etapt_2011->Fill(muTree_2011->eta[a],muTree_2011->pt[a]);
      SingleGlb_Etaphi_2011->Fill(muTree_2011->eta[a],muTree_2011->phi[a]);
      SingleGlb_Eta_2011->Fill(muTree_2011->eta[a]);
      SingleGlb_Pt_2011->Fill(muTree_2011->pt[a]);
      SingleGlb_Phi_2011->Fill(muTree_2011->phi[a]);

      if (flag->doGlb) {
        if(!isValidMu(flag, muTree_2011, a)) continue;    //Check glb muons are within acceptance range
      } else if (flag->doSta) {
        if(!isMuInAcc(flag, muTree_2011->eta[a], muTree_2011->pt[a])) continue;    //Check sta muons are within acceptance range
      }
      qual = true;
      
      SingleGlb_Etapt_2011_qual->Fill(muTree_2011->eta[a],muTree_2011->pt[a]);
      SingleGlb_Etaphi_2011_qual->Fill(muTree_2011->eta[a],muTree_2011->phi[a]);
      SingleGlb_Eta_2011_qual->Fill(muTree_2011->eta[a]);
      SingleGlb_Pt_2011_qual->Fill(muTree_2011->pt[a]);
      SingleGlb_Phi_2011_qual->Fill(muTree_2011->phi[a]);

    }
    if (qual) nevt_2011_qual++;

    if (i%1000 ==0)
    cout << "Event in 2011 datasets: " << i+1 << endl;

  }

  double ratio_2010 = SingleGlb_Eta_2010->GetEntries()/nevt_2010;
  double ratio_2011 = SingleGlb_Eta_2011->GetEntries()/nevt_2011;
  double ratio_2010_qual = SingleGlb_Eta_2010_qual->GetEntries()/nevt_2010_qual;
  double ratio_2011_qual = SingleGlb_Eta_2011_qual->GetEntries()/nevt_2011_qual;
  
  // Draw final histograms and save it into .png files
  gROOT->Macro("~miheejo/public/HIMuTrig/TrigStyle.C");    //For plot style
  TCanvas *canv = new TCanvas("canv","canv",800,600);
  canv->Draw();
  SingleGlb_Etapt_2010->DrawNormalized("colz",ratio_2010);
  canv->SaveAs("SingleGlb_Etapt_2010.png");
  canv->Clear();  canv->Draw();
  SingleGlb_Etapt_2011->DrawNormalized("colz",ratio_2011);
  canv->SaveAs("SingleGlb_Etapt_2011.png");
  canv->Clear();  canv->Draw();
  SingleGlb_Etaphi_2010->DrawNormalized("colz",ratio_2010);
  canv->SaveAs("SingleGlb_Etaphi_2010.png");
  canv->Clear();  canv->Draw();
  SingleGlb_Etaphi_2011->DrawNormalized("colz",ratio_2011);
  canv->SaveAs("SingleGlb_Etaphi_2011.png");
  canv->Clear();  canv->Draw();
  SingleGlb_Etapt_2010_qual->DrawNormalized("colz",ratio_2010_qual);
  canv->SaveAs("SingleGlb_Etapt_2010_qual.png");
  canv->Clear();  canv->Draw();
  SingleGlb_Etapt_2011_qual->DrawNormalized("colz",ratio_2011_qual);
  canv->SaveAs("SingleGlb_Etapt_2011_qual.png");
  canv->Clear();  canv->Draw();
  SingleGlb_Etaphi_2010_qual->DrawNormalized("colz",ratio_2010_qual);
  canv->SaveAs("SingleGlb_Etaphi_2010_qual.png");
  canv->Clear();  canv->Draw();
  SingleGlb_Etaphi_2011_qual->DrawNormalized("colz",ratio_2011_qual);
  canv->SaveAs("SingleGlb_Etaphi_2011_qual.png");
  delete canv;


  TLegend *leg = new TLegend(0.5,0.70,0.65,0.83);
  leg->SetFillColor(0);
  leg->SetBorderSize(0);
  leg->SetTextSize(0.05);

  TLegend *leg2 = new TLegend(0.35,0.50,0.45,0.63);
  leg2->SetFillColor(0);
  leg2->SetBorderSize(0);
  leg2->SetTextSize(0.05);

  TLatex *lax = new TLatex();
  lax->SetTextSize(0.04);

  canv = new TCanvas("canv","canv",1300,1000);
  canv->Divide(2,2);
  canv->cd(1);
  SingleGlb_Eta_2010_qual->Sumw2();
  SingleGlb_Eta_2010_qual->SetMarkerStyle(20);
  SingleGlb_Eta_2010_qual->DrawNormalized("p e",ratio_2010_qual);
  SingleGlb_Eta_2011_qual->Sumw2();
  SingleGlb_Eta_2011_qual->SetMarkerColor(kRed);
  SingleGlb_Eta_2011_qual->SetMarkerStyle(20);
  SingleGlb_Eta_2011_qual->DrawNormalized("p e same",ratio_2011_qual);
  leg->AddEntry(SingleGlb_Eta_2010_qual,"2010 data","lp");
  leg->AddEntry(SingleGlb_Eta_2011_qual,"2011 data","lp");
  leg2->AddEntry(SingleGlb_Eta_2010_qual,"2010 data","lp");
  leg2->AddEntry(SingleGlb_Eta_2011_qual,"2011 data","lp");
  leg->Draw();
  canv->cd(2);
  SingleGlb_Pt_2010_qual->Sumw2();
  SingleGlb_Pt_2010_qual->SetMarkerStyle(20);
  SingleGlb_Pt_2010_qual->DrawNormalized("p e",ratio_2010_qual);
  SingleGlb_Pt_2011_qual->Sumw2();
  SingleGlb_Pt_2011_qual->SetMarkerColor(kRed);
  SingleGlb_Pt_2011_qual->SetMarkerStyle(20);
  SingleGlb_Pt_2011_qual->DrawNormalized("p e same",ratio_2011_qual);
  leg->Draw();
  canv->cd(3);
  SingleGlb_Phi_2011_qual->Sumw2();
  SingleGlb_Phi_2011_qual->SetMarkerColor(kRed);
  SingleGlb_Phi_2011_qual->SetMarkerStyle(20);
  SingleGlb_Phi_2011_qual->DrawNormalized("p e",ratio_2011_qual);
  SingleGlb_Phi_2010_qual->Sumw2();
  SingleGlb_Phi_2010_qual->SetMarkerStyle(20);
  SingleGlb_Phi_2010_qual->DrawNormalized("p e same",ratio_2010_qual);
  leg->Draw();
  canv->cd(4);
  stringstream title;
  title.str("");
  title << "2010 # muons (mu trig fired + quality cuts): " << SingleGlb_Eta_2010_qual->GetEntries();
  lax->DrawLatex(0.0,0.95,title.str().c_str());
  title.str("");
  title << "2010 # events (mu trig fired + quality cuts): " << nevt_2010_qual;
  lax->DrawLatex(0.0,0.90,title.str().c_str());
  title.str("");
  title << "2011 # muons (mu trig fired + quality cuts): " << SingleGlb_Eta_2011_qual->GetEntries();
  lax->DrawLatex(0.0,0.85,title.str().c_str());
  title.str("");
  title << "2011 # events (mu trig fired + quality cuts): " << nevt_2011_qual;
  lax->DrawLatex(0.0,0.80,title.str().c_str());
  canv->SaveAs("SingleGlb_qual.png");

  canv->Clear();  canv->Divide(2,2);
  canv->cd(1);

  SingleGlb_Eta_2011->Sumw2();
  SingleGlb_Eta_2011->SetMarkerColor(kRed);
  SingleGlb_Eta_2011->SetMarkerStyle(20);
  SingleGlb_Eta_2011->DrawNormalized("p e",ratio_2011);
  SingleGlb_Eta_2010->Sumw2();
  SingleGlb_Eta_2010->SetMarkerStyle(20);
  SingleGlb_Eta_2010->DrawNormalized("p e same",ratio_2010);
  leg->Draw();

  canv->cd(2);
  SingleGlb_Pt_2011->Sumw2();
  SingleGlb_Pt_2011->SetMarkerColor(kRed);
  SingleGlb_Pt_2011->SetMarkerStyle(20);
  SingleGlb_Pt_2011->DrawNormalized("p e",ratio_2011);
  SingleGlb_Pt_2010->Sumw2();
  SingleGlb_Pt_2010->SetMarkerStyle(20);
  SingleGlb_Pt_2010->DrawNormalized("p e same",ratio_2010);
  leg->Draw();

  canv->cd(3);
  SingleGlb_Phi_2011->Sumw2();
  SingleGlb_Phi_2011->SetMarkerColor(kRed);
  SingleGlb_Phi_2011->SetMarkerStyle(20);
  SingleGlb_Phi_2011->DrawNormalized("p e",ratio_2011);
  SingleGlb_Phi_2010->Sumw2();
  SingleGlb_Phi_2010->SetMarkerStyle(20);
  SingleGlb_Phi_2010->DrawNormalized("p e same",ratio_2010);
  leg2->Draw();
  canv->cd(4);
  title.str("");
  title << "2010 # muons (mu trig fired): " << SingleGlb_Eta_2010->GetEntries();
  lax->DrawLatex(0.0,0.95,title.str().c_str());
  title.str("");
  title << "2010 # events (mu trig fired): " << nevt_2010;
  lax->DrawLatex(0.0,0.90,title.str().c_str());
  title.str("");
  title << "2011 # muons (mu trig fired): " << SingleGlb_Eta_2011->GetEntries();
  lax->DrawLatex(0.0,0.85,title.str().c_str());
  title.str("");
  title << "2011 # events (mu trig fired): " << nevt_2011;
  lax->DrawLatex(0.0,0.80,title.str().c_str());
  canv->SaveAs("SingleGlb_noqual.png");

  
  return 0;
}
Esempio n. 22
0
void EfficiencyLxy(){

  TString fname = "mGamma_0250_ctau1";
  TFile *f = new TFile(fname+".root");

  f->cd("Analysis");
  f->ls();

  Int_t ev;
  Int_t run;
  Int_t lumi;
  Int_t   genm;
  Int_t   trig;
  Float_t ptgenm[20];
  Float_t etagenm[20];
  Int_t recm;
  Float_t ptrecm[20];
  Float_t etarecm[20];
  Float_t phirecm[20];
  Int_t mjets;
  Int_t mj1mu;
  Int_t mj2mu;
  Float_t ptmumj1[20];
  Float_t ptmumj2[20];
  Float_t etamumj1[20];
  Float_t etamumj2[20];
  Int_t vtx;
  Float_t gen_dzmj1_0;
  Float_t gen_dzmj1_1;
  Float_t gen_mj1_0_pt;
  Float_t gen_mj1_1_pt;
  Float_t gen_mj1_0_eta;
  Float_t gen_mj1_1_eta;
  Float_t gen_mj1_0_phi;
  Float_t gen_mj1_1_phi;
  Float_t gen_dzmj2_0;
  Float_t gen_dzmj2_1;
  Float_t gen_mj2_0_pt;
  Float_t gen_mj2_1_pt;
  Float_t gen_mj2_0_eta;
  Float_t gen_mj2_1_eta;
  Float_t gen_mj2_0_phi;
  Float_t gen_mj2_1_phi;
  Float_t lxy_ge_1_0;
  Float_t lxy_ge_1_1;
  Float_t lxy_ge_2_0;
  Float_t lxy_ge_2_1;

  TTree *t = (TTree*)f->Get("Analysis/Events");

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

  c1->SetFillColor(0);
  gStyle->SetPalette(1);
  gStyle->SetOptStat(0);  
  // SetPlotStyle();

  t->SetBranchAddress("lxy_ge_1_0", &lxy_ge_1_0);
  t->SetBranchAddress("lxy_ge_1_1", &lxy_ge_1_1);
  t->SetBranchAddress("lxy_ge_2_0", &lxy_ge_2_0);
  t->SetBranchAddress("lxy_ge_2_1", &lxy_ge_2_1);

  t->SetBranchAddress("gen_dzmj1_0", &gen_dzmj1_0);
  t->SetBranchAddress("gen_dzmj1_1", &gen_dzmj1_1);
  t->SetBranchAddress("gen_mj1_0_pt", &gen_mj1_0_pt);
  t->SetBranchAddress("gen_mj1_1_pt", &gen_mj1_1_pt);
  t->SetBranchAddress("gen_mj1_0_eta", &gen_mj1_0_eta);
  t->SetBranchAddress("gen_mj1_1_eta", &gen_mj1_1_eta);

  t->SetBranchAddress("gen_mj1_0_phi", &gen_mj1_0_phi);
  t->SetBranchAddress("gen_mj1_1_phi", &gen_mj1_1_phi);

  t->SetBranchAddress("gen_dzmj2_0", &gen_dzmj2_0);
  t->SetBranchAddress("gen_dzmj2_1", &gen_dzmj2_1);
  t->SetBranchAddress("gen_mj2_0_pt", &gen_mj2_0_pt);
  t->SetBranchAddress("gen_mj2_1_pt", &gen_mj2_1_pt);
  t->SetBranchAddress("gen_mj2_0_eta", &gen_mj2_0_eta);
  t->SetBranchAddress("gen_mj2_1_eta", &gen_mj2_1_eta);
  t->SetBranchAddress("gen_mj2_0_phi", &gen_mj2_0_phi);
  t->SetBranchAddress("gen_mj2_1_phi", &gen_mj2_1_phi);

  t->SetBranchAddress("event",&ev);
  t->SetBranchAddress("run",&run);
  t->SetBranchAddress("lumi",&lumi);
  t->SetBranchAddress("trigger",&trig);
  t->SetBranchAddress("isVtx",&vtx);

  t->SetBranchAddress("genmuons",&genm);
  t->SetBranchAddress("ptgenMuons",&ptgenm);
  t->SetBranchAddress("etagenMuons",&etagenm);
  
  t->SetBranchAddress("recmuons",&recm);
  t->SetBranchAddress("ptrecMuons",&ptrecm);
  t->SetBranchAddress("etarecMuons",&etarecm);
  t->SetBranchAddress("phirecMuons",&phirecm);

  t->SetBranchAddress("recmujets",&mjets);
  t->SetBranchAddress("mj1muons",&mj1mu);
  t->SetBranchAddress("mj2muons",&mj2mu);

  t->SetBranchAddress("ptmj1muons",&ptmumj1);
  t->SetBranchAddress("ptmj2muons",&ptmumj2);
  t->SetBranchAddress("etamj1muons",&etamumj1);
  t->SetBranchAddress("etamj2muons",&etamumj2);

  Float_t bin_edges[19]={0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36};
  Float_t bin_center[18];
  Float_t errbin_center[18];
  Float_t erry[18];

  Float_t bin_edges_lxy[19]={0,2,4,6,8,10,12,14,16,18,20,25,30,35,40,45,50,60,80};
  Float_t bin_center_lxy[18];
  Float_t errbin_center_lxy[18];
  Float_t erry_lxy[18];


  for(int k=0;k<18;k++){
    bin_center[k] = bin_edges[k] + ( (bin_edges[k+1]-bin_edges[k])/2.0);
    errbin_center[k] = ( (bin_edges[k+1]-bin_edges[k])/2.0);
    erry[k] = 0.0;
    bin_center_lxy[k] = bin_edges_lxy[k] + ( (bin_edges_lxy[k+1]-bin_edges_lxy[k])/2.0);
    errbin_center_lxy[k] = ( (bin_edges_lxy[k+1]-bin_edges_lxy[k])/2.0);
    erry_lxy[k] = 0.0;
  }


  //===============================================
  Float_t count_barrel_muonPair_1_0[18]={0.0};
  Float_t count_rec_barrel_muonPair_1_0[18]={0.0};
  Float_t count_barrel_muonPair_1_1[18]={0.0};
  Float_t count_rec_barrel_muonPair_1_1[18]={0.0};
  Float_t count_endcap_muonPair_1_0[18]={0.0};
  Float_t count_rec_endcap_muonPair_1_0[18]={0.0};
  Float_t count_endcap_muonPair_1_1[18]={0.0};
  Float_t count_rec_endcap_muonPair_1_1[18]={0.0};

  Float_t count_barrel_muonPair_2_0[18]={0.0};
  Float_t count_rec_barrel_muonPair_2_0[18]={0.0};
  Float_t count_barrel_muonPair_2_1[18]={0.0};
  Float_t count_rec_barrel_muonPair_2_1[18]={0.0};
  Float_t count_endcap_muonPair_2_0[18]={0.0};
  Float_t count_rec_endcap_muonPair_2_0[18]={0.0};
  Float_t count_endcap_muonPair_2_1[18]={0.0};
  Float_t count_rec_endcap_muonPair_2_1[18]={0.0};

  Float_t count_lxy_barrel_muonPair_1_0[18]={0.0};
  Float_t count_lxy_rec_barrel_muonPair_1_0[18]={0.0};
  Float_t count_lxy_barrel_muonPair_1_1[18]={0.0};
  Float_t count_lxy_rec_barrel_muonPair_1_1[18]={0.0};
  Float_t count_lxy_endcap_muonPair_1_0[18]={0.0};
  Float_t count_lxy_rec_endcap_muonPair_1_0[18]={0.0};
  Float_t count_lxy_endcap_muonPair_1_1[18]={0.0};
  Float_t count_lxy_rec_endcap_muonPair_1_1[18]={0.0};

  Float_t count_lxy_barrel_muonPair_2_0[18]={0.0};
  Float_t count_lxy_rec_barrel_muonPair_2_0[18]={0.0};
  Float_t count_lxy_barrel_muonPair_2_1[18]={0.0};
  Float_t count_lxy_rec_barrel_muonPair_2_1[18]={0.0};
  Float_t count_lxy_endcap_muonPair_2_0[18]={0.0};
  Float_t count_lxy_rec_endcap_muonPair_2_0[18]={0.0};
  Float_t count_lxy_endcap_muonPair_2_1[18]={0.0};
  Float_t count_lxy_rec_endcap_muonPair_2_1[18]={0.0};



  Int_t nentries = t->GetEntries();

  Int_t mcount[4]={0};
  Int_t rmcount[4]={0};


  bool verbose = false;
  int entries = 0;
  for(int k=0;k<nentries;k++){
    t->GetEntry(k);
    entries++;
    if (entries % 500 == 0) std::cout << "entries: " << entries << ", " << (entries*1.0/80000.0)*100.0 << " % " << std::endl;

    verbose = false;
    

    Int_t hptm_count=0;
    Int_t m_count=0;
    for(int j=0;j<genm;j++){
      if(ptgenm[j]>17.0 && fabs(etagenm[j])<0.9) hptm_count++;
      if(ptgenm[j]>8.0 && fabs(etagenm[j])<2.4) m_count++;
      if (verbose) std::cout << "ptgenm[j]: " << ptgenm[j] << ", fabs(etagenm[j]): " << fabs(etagenm[j]) << std::endl;
    }

    if(hptm_count>0){
      mcount[0]++;
      if(m_count>1) mcount[1]++;
      if(m_count>2) mcount[2]++;
      if(m_count>3) mcount[3]++;
    }

    if(hptm_count>0 && mcount>3){

      bool lxy = true;
      bool dz = false;

      if (gen_mj1_0_pt > 8 && gen_mj1_1_pt > 8 && gen_mj2_1_pt > 8 && gen_mj2_1_pt > 8){

        bool matchRec11 = false;
        double dphi11 = 1000.0;
        double deta11 = 1000.0;
        double dR11 = 1000.0;
        int match11 = 100;

        bool matchRec12 = false;
        double dphi12 = 1000.0;
        double deta12 = 1000.0;
        double dR12 = 1000.0;
        int match12 = 100;

        bool matchRec21 = false;
        double dphi21 = 1000.0;
        double deta21 = 1000.0;
        double dR21 = 1000.0;
        int match21 = 100;

        bool matchRec22 = false;
        double dphi22 = 1000.0;
        double deta22 = 1000.0;
        double dR22 = 1000.0;
        int match22 = 100;

        for(int j=0;j<recm;j++){

          if(ptrecm[j]<8.0 || fabs(etarecm[j])>2.4) continue;
    
          dphi11 = My_dPhi(phirecm[j], gen_mj1_0_phi); 
          dphi12 = My_dPhi(phirecm[j], gen_mj1_1_phi); 
          deta11 = (etarecm[j] - gen_mj1_0_eta); 
          deta12 = (etarecm[j] - gen_mj1_1_eta); 
          dR11 = sqrt(dphi11*dphi11+deta11*deta11);
          dR12 = sqrt(dphi12*dphi12+deta12*deta12);
          if(dR11<0.5){
            matchRec11 = true;
            match11 = j;
          }
          if(dR12<0.5){
            matchRec12 = true;
            match12 = j;
          }

          dphi21 = My_dPhi(phirecm[j], gen_mj2_0_phi); 
          dphi22 = My_dPhi(phirecm[j], gen_mj2_1_phi); 
          deta21 = (etarecm[j] - gen_mj2_0_eta); 
          deta22 = (etarecm[j] - gen_mj2_1_eta); 
          dR21 = sqrt(dphi21*dphi21+deta21*deta21);
          dR22 = sqrt(dphi22*dphi22+deta22*deta22);
          if(dR21<0.5){
            matchRec21 = true;
            match21 = j;
          }
          if(dR22<0.5){
            matchRec22 = true;
            match22 = j;
          }

        }

        for(int m=0;m<18;m++){

          if(fabs(lxy_ge_1_0)>bin_edges_lxy[m] && fabs(lxy_ge_1_0)<bin_edges_lxy[m+1]){
            if (fabs(gen_mj1_0_eta) < 0.8){
              count_lxy_barrel_muonPair_1_0[m]++;
            }
            if (fabs(gen_mj1_0_eta) > 0.8) count_lxy_endcap_muonPair_1_0[m]++;
            if (matchRec11){
              if (fabs(gen_mj1_0_eta) < 0.8){
                count_lxy_rec_barrel_muonPair_1_0[m]++;
              }
              if (fabs(gen_mj1_0_eta) > 0.8) count_lxy_rec_endcap_muonPair_1_0[m]++;
              if (verbose) std::cout << "event: " << ev << " gen1 pt: " << gen_mj1_0_pt << ", gen1 eta: " << gen_mj1_0_eta << ", rec match pt: " << ptrecm[match11] << ", rec match eta " << etarecm[match11] << ", lxy: " << lxy_ge_1_0 << std::endl; 
            }
          }
          if(fabs(lxy_ge_1_1)>bin_edges_lxy[m] && fabs(lxy_ge_1_1)<bin_edges_lxy[m+1]){
            if (fabs(gen_mj1_1_eta) < 0.8) count_lxy_barrel_muonPair_1_1[m]++;
            if (fabs(gen_mj1_1_eta) > 0.8) count_lxy_endcap_muonPair_1_1[m]++;
            if (matchRec12){
              if (fabs(gen_mj1_1_eta) < 0.8) count_lxy_rec_barrel_muonPair_1_1[m]++;
              if (fabs(gen_mj1_1_eta) > 0.8) count_lxy_rec_endcap_muonPair_1_1[m]++;
              if (verbose) std::cout << "event: " << ev << " gen1 pt: " << gen_mj1_1_pt << ", gen1 eta: " << gen_mj1_1_eta << ", rec match pt: " << ptrecm[match12] << ", rec match eta " << etarecm[match12] << ", lxy: " << lxy_ge_1_1 << std::endl; 
            }
          }
          if(fabs(lxy_ge_2_0)>bin_edges_lxy[m] && fabs(lxy_ge_2_0)<bin_edges_lxy[m+1]){
            if (fabs(gen_mj2_0_eta) < 0.8){
              count_lxy_barrel_muonPair_2_0[m]++;
            }
            if (fabs(gen_mj2_0_eta) > 0.8) count_lxy_endcap_muonPair_2_0[m]++;
            if (matchRec21){
              if (fabs(gen_mj2_0_eta) < 0.8){
                count_lxy_rec_barrel_muonPair_2_0[m]++;
              }
              if (fabs(gen_mj2_0_eta) > 0.8) count_lxy_rec_endcap_muonPair_2_0[m]++;
              if (verbose) std::cout << "event: " << ev << " gen1 pt: " << gen_mj2_0_pt << ", gen1 eta: " << gen_mj2_0_eta << ", rec match pt: " << ptrecm[match21] << ", rec match eta " << etarecm[match21] << ", lxy: " << lxy_ge_2_0 << std::endl; 
            }
          }
          if(fabs(lxy_ge_2_1)>bin_edges_lxy[m] && fabs(lxy_ge_2_1)<bin_edges_lxy[m+1]){
            if (fabs(gen_mj2_1_eta) < 0.8){
              count_lxy_barrel_muonPair_2_1[m]++;
            }
            if (fabs(gen_mj2_1_eta) > 0.8) count_lxy_endcap_muonPair_2_1[m]++;
            if (matchRec22){
              if (fabs(gen_mj2_1_eta) < 0.8){
                count_lxy_rec_barrel_muonPair_2_1[m]++;
              }
              if (fabs(gen_mj2_1_eta) > 0.8) count_lxy_rec_endcap_muonPair_2_1[m]++;
              if (verbose) std::cout << "event: " << ev << " gen1 pt: " << gen_mj2_1_pt << ", gen1 eta: " << gen_mj2_1_eta << ", rec match pt: " << ptrecm[match22] << ", rec match eta " << etarecm[match22] << ", lxy: " << lxy_ge_2_1 << std::endl; 
            }
          }
        }
      }
    }
  }
      

  std::cout << "entries: " << entries << std::endl;

  std::cout << "Entries loop finished" << std::endl;

  Float_t rval_barrel_lxy_muonPair_1_0[30]={0.0};
  Float_t rval_endcap_lxy_muonPair_1_0[30]={0.0};
  Float_t rval_barrel_lxy_muonPair_1_1[30]={0.0};
  Float_t rval_endcap_lxy_muonPair_1_1[30]={0.0};

  Float_t erval_barrel_lxy_muonPair_1_0[30]={0.0};
  Float_t erval_endcap_lxy_muonPair_1_0[30]={0.0};
  Float_t erval_barrel_lxy_muonPair_1_1[30]={0.0};
  Float_t erval_endcap_lxy_muonPair_1_1[30]={0.0};

  Float_t rval_barrel_lxy_muonPair_2_0[30]={0.0};
  Float_t rval_endcap_lxy_muonPair_2_0[30]={0.0};
  Float_t rval_barrel_lxy_muonPair_2_1[30]={0.0};
  Float_t rval_endcap_lxy_muonPair_2_1[30]={0.0};

  Float_t erval_barrel_lxy_muonPair_2_0[30]={0.0};
  Float_t erval_endcap_lxy_muonPair_2_0[30]={0.0};
  Float_t erval_barrel_lxy_muonPair_2_1[30]={0.0};
  Float_t erval_endcap_lxy_muonPair_2_1[30]={0.0};



  std::cout << "Starting fill" << std::endl;
  for(int k=0;k<18;k++) {

    if(count_lxy_barrel_muonPair_1_0[k]!=0) rval_barrel_lxy_muonPair_1_0[k] = count_lxy_rec_barrel_muonPair_1_0[k]/count_lxy_barrel_muonPair_1_0[k];
    if(count_lxy_endcap_muonPair_1_0[k]!=0) rval_endcap_lxy_muonPair_1_0[k] = count_lxy_rec_endcap_muonPair_1_0[k]/count_lxy_endcap_muonPair_1_0[k];

    if(count_lxy_barrel_muonPair_1_1[k]!=0) rval_barrel_lxy_muonPair_1_1[k] = count_lxy_rec_barrel_muonPair_1_1[k]/count_lxy_barrel_muonPair_1_1[k];
    if(count_lxy_endcap_muonPair_1_1[k]!=0) rval_endcap_lxy_muonPair_1_1[k] = count_lxy_rec_endcap_muonPair_1_1[k]/count_lxy_endcap_muonPair_1_1[k];

    if(count_lxy_barrel_muonPair_1_0[k]!=0 ) erval_barrel_lxy_muonPair_1_0[k] = sqrt( (rval_barrel_lxy_muonPair_1_0[k]*(1-rval_barrel_lxy_muonPair_1_0[k]))/count_lxy_barrel_muonPair_1_0[k]);
    if(count_lxy_endcap_muonPair_1_0[k]!=0) erval_endcap_lxy_muonPair_1_0[k] = sqrt( (rval_endcap_lxy_muonPair_1_0[k]*(1-rval_endcap_lxy_muonPair_1_0[k]))/count_lxy_endcap_muonPair_1_0[k]);

    if(count_lxy_barrel_muonPair_1_1[k]!=0 ) erval_barrel_lxy_muonPair_1_1[k] = sqrt( (rval_barrel_lxy_muonPair_1_1[k]*(1-rval_barrel_lxy_muonPair_1_1[k]))/count_lxy_barrel_muonPair_1_1[k]);
    if(count_lxy_endcap_muonPair_1_1[k]!=0) erval_endcap_lxy_muonPair_1_1[k] = sqrt( (rval_endcap_lxy_muonPair_1_1[k]*(1-rval_endcap_lxy_muonPair_1_1[k]))/count_lxy_endcap_muonPair_1_1[k]);


    if(count_lxy_barrel_muonPair_2_0[k]!=0) rval_barrel_lxy_muonPair_2_0[k] = count_lxy_rec_barrel_muonPair_2_0[k]/count_lxy_barrel_muonPair_2_0[k];
    if(count_lxy_endcap_muonPair_2_0[k]!=0) rval_endcap_lxy_muonPair_2_0[k] = count_lxy_rec_endcap_muonPair_2_0[k]/count_lxy_endcap_muonPair_2_0[k];

    if(count_lxy_barrel_muonPair_2_1[k]!=0) rval_barrel_lxy_muonPair_2_1[k] = count_lxy_rec_barrel_muonPair_2_1[k]/count_lxy_barrel_muonPair_2_1[k];
    if(count_lxy_endcap_muonPair_2_1[k]!=0) rval_endcap_lxy_muonPair_2_1[k] = count_lxy_rec_endcap_muonPair_2_1[k]/count_lxy_endcap_muonPair_2_1[k];

    if(count_lxy_barrel_muonPair_2_0[k]!=0 ) erval_barrel_lxy_muonPair_2_0[k] = sqrt( (rval_barrel_lxy_muonPair_2_0[k]*(1-rval_barrel_lxy_muonPair_2_0[k]))/count_lxy_barrel_muonPair_2_0[k]);
    if(count_lxy_endcap_muonPair_2_0[k]!=0) erval_endcap_lxy_muonPair_2_0[k] = sqrt( (rval_endcap_lxy_muonPair_2_0[k]*(1-rval_endcap_lxy_muonPair_2_0[k]))/count_lxy_endcap_muonPair_2_0[k]);

    if(count_lxy_barrel_muonPair_2_1[k]!=0 ) erval_barrel_lxy_muonPair_2_1[k] = sqrt( (rval_barrel_lxy_muonPair_2_1[k]*(1-rval_barrel_lxy_muonPair_2_1[k]))/count_lxy_barrel_muonPair_2_1[k]);
    if(count_lxy_endcap_muonPair_2_1[k]!=0) erval_endcap_lxy_muonPair_2_1[k] = sqrt( (rval_endcap_lxy_muonPair_2_1[k]*(1-rval_endcap_lxy_muonPair_2_1[k]))/count_lxy_endcap_muonPair_2_1[k]);

  }


  std::cout << "Starting TGraphs:" << std::endl;

  TGraphErrors *gr_r_barrel_lxy_muonPair_1_0 = new TGraphErrors(18,bin_center_lxy,rval_barrel_lxy_muonPair_1_0,errbin_center_lxy,erval_barrel_lxy_muonPair_1_0);
  TGraphErrors *gr_r_endcap_lxy_muonPair_1_0 = new TGraphErrors(18,bin_center_lxy,rval_endcap_lxy_muonPair_1_0,errbin_center_lxy,erval_endcap_lxy_muonPair_1_0);
  TGraphErrors *gr_r_barrel_lxy_muonPair_1_1 = new TGraphErrors(18,bin_center_lxy,rval_barrel_lxy_muonPair_1_1,errbin_center_lxy,erval_barrel_lxy_muonPair_1_1);
  TGraphErrors *gr_r_endcap_lxy_muonPair_1_1 = new TGraphErrors(18,bin_center_lxy,rval_endcap_lxy_muonPair_1_1,errbin_center_lxy,erval_endcap_lxy_muonPair_1_1);

  TGraphErrors *gr_r_barrel_lxy_muonPair_2_0 = new TGraphErrors(18,bin_center_lxy,rval_barrel_lxy_muonPair_2_0,errbin_center_lxy,erval_barrel_lxy_muonPair_2_0);
  TGraphErrors *gr_r_endcap_lxy_muonPair_2_0 = new TGraphErrors(18,bin_center_lxy,rval_endcap_lxy_muonPair_2_0,errbin_center_lxy,erval_endcap_lxy_muonPair_2_0);
  TGraphErrors *gr_r_barrel_lxy_muonPair_2_1 = new TGraphErrors(18,bin_center_lxy,rval_barrel_lxy_muonPair_2_1,errbin_center_lxy,erval_barrel_lxy_muonPair_2_1);
  TGraphErrors *gr_r_endcap_lxy_muonPair_2_1 = new TGraphErrors(18,bin_center_lxy,rval_endcap_lxy_muonPair_2_1,errbin_center_lxy,erval_endcap_lxy_muonPair_2_1);



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

  TLegend *leg3 = new TLegend(0.7,0.65,0.825,0.85);

  gr_r_barrel_lxy_muonPair_2_0->GetXaxis()->SetTitle("Lxy [cm]");
  gr_r_barrel_lxy_muonPair_2_0->GetYaxis()->SetTitle("efficiency");
  gr_r_barrel_lxy_muonPair_2_0->SetTitle("");

  gr_r_barrel_lxy_muonPair_2_0->SetLineColor(kRed);
  gr_r_barrel_lxy_muonPair_2_0->SetMarkerColor(kRed);
  gr_r_barrel_lxy_muonPair_2_0->Draw("APL");
  gr_r_barrel_lxy_muonPair_2_0->GetYaxis()->SetRangeUser(0.0,1.0);
  gr_r_barrel_lxy_muonPair_2_1->GetYaxis()->SetRangeUser(0.0,1.0);
  // gr_r_barrel_lxy_muonPair_2_0->GetXaxis()->SetRangeUser(0.0,30.0);
  // gr_r_barrel_lxy_muonPair_2_0->GetXaxis()->SetRangeUser(0.0,30.0);

  gr_r_endcap_lxy_muonPair_2_0->SetLineColor(kRed);
  gr_r_endcap_lxy_muonPair_2_0->SetMarkerColor(kRed);
  gr_r_endcap_lxy_muonPair_2_0->SetLineStyle(2);
  gr_r_endcap_lxy_muonPair_2_0->Draw("PLsame");

  gr_r_barrel_lxy_muonPair_2_1->SetLineColor(kBlack);
  gr_r_barrel_lxy_muonPair_2_1->SetMarkerColor(kBlack);
  gr_r_endcap_lxy_muonPair_2_1->SetLineColor(kBlack);
  gr_r_endcap_lxy_muonPair_2_1->SetMarkerColor(kBlack);
  gr_r_endcap_lxy_muonPair_2_1->SetLineStyle(2);
  gr_r_endcap_lxy_muonPair_2_1->Draw("PLsame");
  gr_r_barrel_lxy_muonPair_2_1->Draw("PLsame");


  TLine pix1(4.4, 1e-8, 4.4,1.0);
  pix1.SetLineStyle(2); pix1.SetLineWidth(1); pix1.SetLineColor(kBlue);
  pix1.Draw("same");
  TLine pix2(7.3, 1e-8, 7.3,1.0);
  pix2.SetLineStyle(2); pix2.SetLineWidth(1); pix2.SetLineColor(kBlue);
  pix2.Draw("same");
  TLine pix3(10.2, 1e-8, 10.2,1.0);
  pix3.SetLineStyle(2); pix3.SetLineWidth(1); pix3.SetLineColor(kBlue);
  pix3.Draw("same");
  TLine trk1(22,1e-8,22,1.0);
  trk1.SetLineStyle(2); trk1.SetLineWidth(1); trk1.SetLineColor(kGreen);
  trk1.Draw("same");
  TLine trk2(60, 1e-8, 60,1.0);
  trk2.SetLineStyle(2); trk2.SetLineWidth(1); trk2.SetLineColor(kGreen);
  trk2.Draw("same");



  leg3->SetBorderSize(0);
  leg3->SetFillColor(0);
  leg3->SetTextSize(0.036);
  leg3->AddEntry(gr_r_barrel_lxy_muonPair_2_0,"|#eta_{#gamma D}|<0.8 A1 #mu_{0}","PL");
  leg3->AddEntry(gr_r_endcap_lxy_muonPair_2_0,"|#eta_{#gamma D}|>0.8 A1 #mu_{0}","PL");
  leg3->AddEntry(gr_r_barrel_lxy_muonPair_2_1,"|#eta_{#gamma D}|<0.8 A1 #mu_{1}","PL");
  leg3->AddEntry(gr_r_endcap_lxy_muonPair_2_1,"|#eta_{#gamma D}|>0.8 A1 #mu_{1}","PL");

  leg3->Draw("same");
  c->SaveAs(fname+"_eff_eta_lxy_1D_A1.pdf","recreate");
  c->Clear();

  TLegend *leg4 = new TLegend(0.7,0.65,0.825,0.85);

  gr_r_barrel_lxy_muonPair_1_0->GetXaxis()->SetTitle("Lxy [cm]");
  gr_r_barrel_lxy_muonPair_1_0->GetYaxis()->SetTitle("efficiency");
  gr_r_barrel_lxy_muonPair_1_0->SetTitle("");

  gr_r_barrel_lxy_muonPair_1_0->SetLineColor(kRed);
  gr_r_barrel_lxy_muonPair_1_0->SetMarkerColor(kRed);
  gr_r_barrel_lxy_muonPair_1_0->Draw("APL");
  gr_r_barrel_lxy_muonPair_1_0->GetYaxis()->SetRangeUser(0.0,1.0);
  gr_r_barrel_lxy_muonPair_1_1->GetYaxis()->SetRangeUser(0.0,1.0);
  // gr_r_barrel_lxy_muonPair_1_0->GetXaxis()->SetRangeUser(0.0,30.0);
  // gr_r_barrel_lxy_muonPair_1_0->GetXaxis()->SetRangeUser(0.0,30.0);

  gr_r_endcap_lxy_muonPair_1_0->SetLineColor(kRed);
  gr_r_endcap_lxy_muonPair_1_0->SetMarkerColor(kRed);
  gr_r_endcap_lxy_muonPair_1_0->SetLineStyle(2);
  gr_r_endcap_lxy_muonPair_1_0->Draw("PLsame");

  gr_r_barrel_lxy_muonPair_1_1->SetLineColor(kBlack);
  gr_r_barrel_lxy_muonPair_1_1->SetMarkerColor(kBlack);
  gr_r_endcap_lxy_muonPair_1_1->SetLineColor(kBlack);
  gr_r_endcap_lxy_muonPair_1_1->SetMarkerColor(kBlack);
  gr_r_endcap_lxy_muonPair_1_1->SetLineStyle(2);
  gr_r_endcap_lxy_muonPair_1_1->Draw("PLsame");
  gr_r_barrel_lxy_muonPair_1_1->Draw("PLsame");

  pix1.Draw("same");
  pix2.Draw("same");
  pix3.Draw("same");
  trk1.Draw("same");
  trk2.Draw("same");

  leg4->SetBorderSize(0);
  leg4->SetFillColor(0);
  leg4->SetTextSize(0.036);
  leg4->AddEntry(gr_r_barrel_lxy_muonPair_1_0,"|#eta_{#gamma D}|<0.8 A0 #mu_{0}","PL");
  leg4->AddEntry(gr_r_endcap_lxy_muonPair_1_0,"|#eta_{#gamma D}|>0.8 A0 #mu_{0}","PL");
  leg4->AddEntry(gr_r_barrel_lxy_muonPair_1_1,"|#eta_{#gamma D}|<0.8 A0 #mu_{1}","PL");
  leg4->AddEntry(gr_r_endcap_lxy_muonPair_1_1,"|#eta_{#gamma D}|>0.8 A0 #mu_{1}","PL");

  leg4->Draw("same");
  c->SaveAs(fname+"_eff_eta_lxy_1D_A0.pdf","recreate");
  c->Clear();



}
Esempio n. 23
0
void drawMassFrom2DPlot(RooWorkspace& myws,   // Local workspace
                  string outputDir,     // Output directory
                  struct InputOpt opt,  // Variable with run information (kept for legacy purpose)
                  struct KinCuts cut,   // Variable with current kinematic cuts
                  map<string, string>  parIni,   // Variable containing all initial parameters
                  string plotLabel,     // The label used to define the output file name
                  // Select the type of datasets to fit
                  string DSTAG,         // Specifies the type of datasets: i.e, DATA, MCJPSINP, ...
                  bool isPbPb,          // Define if it is PbPb (True) or PP (False)
                  // Select the type of object to fit
                  bool incJpsi,         // Includes Jpsi model
                  bool incPsi2S,        // Includes Psi(2S) model
                  bool incBkg,          // Includes Background model                  
                  // Select the fitting options
                  // Select the drawing options
                  bool setLogScale,     // Draw plot with log scale
                  bool incSS,           // Include Same Sign data
                  double  binWidth,     // Bin width
                  bool paperStyle=false // if true, print less info
                  ) 
{

  RooMsgService::instance().getStream(0).removeTopic(Caching);  
  RooMsgService::instance().getStream(1).removeTopic(Caching);
  RooMsgService::instance().getStream(0).removeTopic(Plotting);
  RooMsgService::instance().getStream(1).removeTopic(Plotting);
  RooMsgService::instance().getStream(0).removeTopic(Integration);
  RooMsgService::instance().getStream(1).removeTopic(Integration);
  RooMsgService::instance().setGlobalKillBelow(RooFit::WARNING) ;
  
  if (DSTAG.find("_")!=std::string::npos) DSTAG.erase(DSTAG.find("_"));
  int nBins = min(int( round((cut.dMuon.M.Max - cut.dMuon.M.Min)/binWidth) ), 1000);
  
  string pdfTotName  = Form("pdfCTAUMASS_Tot_%s", (isPbPb?"PbPb":"PP"));
  string pdfJpsiPRName  = Form("pdfCTAUMASS_JpsiPR_%s", (isPbPb?"PbPb":"PP"));
  string pdfJpsiNoPRName  = Form("pdfCTAUMASS_JpsiNoPR_%s", (isPbPb?"PbPb":"PP"));
  string pdfPsi2SPRName  = Form("pdfCTAUMASS_Psi2SPR_%s", (isPbPb?"PbPb":"PP"));
  string pdfPsi2SNoPRName  = Form("pdfCTAUMASS_Psi2SNoPR_%s", (isPbPb?"PbPb":"PP"));
  string dsOSName = Form("dOS_%s_%s", DSTAG.c_str(), (isPbPb?"PbPb":"PP"));
  string dsOSNameCut = dsOSName+"_CTAUCUT";
  string dsSSName = Form("dSS_%s_%s", DSTAG.c_str(), (isPbPb?"PbPb":"PP"));

  bool isWeighted = myws.data(dsOSName.c_str())->isWeighted();
  bool isMC = (DSTAG.find("MC")!=std::string::npos);

  double normDSTot   = 1.0;  if (myws.data(dsOSNameCut.c_str()))  { normDSTot   = myws.data(dsOSName.c_str())->sumEntries()/myws.data(dsOSNameCut.c_str())->sumEntries();  }
  
  // Create the main plot of the fit
  RooPlot*   frame     = myws.var("invMass")->frame(Bins(nBins), Range(cut.dMuon.M.Min, cut.dMuon.M.Max));
  myws.data(dsOSName.c_str())->plotOn(frame, Name("dOS"), DataError(RooAbsData::SumW2), XErrorSize(0), MarkerColor(kBlack), LineColor(kBlack), MarkerSize(1.2));

 
  if (paperStyle) TGaxis::SetMaxDigits(3); // to display powers of 10
 
  myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("BKG"),Components(RooArgSet(*myws.pdf(Form("pdfMASS_Bkg_%s", (isPbPb?"PbPb":"PP"))))),
                                       FillStyle(paperStyle ? 0 : 1001), FillColor(kAzure-9), VLines(), DrawOption("LCF"), LineColor(kBlue), LineStyle(kDashed)
                                       );
  if (!paperStyle) {
    if (incJpsi) {
      if ( myws.pdf(Form("pdfCTAUMASS_JpsiPR_%s", (isPbPb?"PbPb":"PP"))) ) {
        myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("JPSIPR"),Components(RooArgSet(*myws.pdf(Form("pdfCTAUMASS_JpsiPR_%s", (isPbPb?"PbPb":"PP"))), *myws.pdf(Form("pdfCTAUMASS_Bkg_%s", (isPbPb?"PbPb":"PP"))))),
                                             ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                             Normalization(normDSTot, RooAbsReal::NumEvent),
                                             LineColor(kRed+3), LineStyle(1), Precision(1e-4), NumCPU(32)
                                             );
      }
      if ( myws.pdf(Form("pdfCTAUMASS_JpsiNoPR_%s", (isPbPb?"PbPb":"PP"))) ) {
        myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("JPSINOPR"),Components(RooArgSet(*myws.pdf(Form("pdfCTAUMASS_JpsiNoPR_%s", (isPbPb?"PbPb":"PP"))), *myws.pdf(Form("pdfCTAUMASS_Bkg_%s", (isPbPb?"PbPb":"PP"))))),
                                             ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                             Normalization(normDSTot, RooAbsReal::NumEvent),
                                             LineColor(kGreen+3), LineStyle(1), Precision(1e-4), NumCPU(32)
                                             );
      }
    }
    if (incPsi2S) {
      if ( myws.pdf(Form("pdfCTAUMASS_Psi2SPR_%s", (isPbPb?"PbPb":"PP"))) ) {
        myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PSI2SPR"),Components(RooArgSet(*myws.pdf(Form("pdfCTAUMASS_Psi2SPR_%s", (isPbPb?"PbPb":"PP"))))),
                                             ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                             Normalization(normDSTot, RooAbsReal::NumEvent),
                                             LineColor(kRed+3), LineStyle(1), Precision(1e-4), NumCPU(32)
                                             );
      }
      if ( myws.pdf(Form("pdfCTAUMASS_Psi2SNoPR_%s", (isPbPb?"PbPb":"PP"))) ) {
        myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PSI2SNOPR"),Components(RooArgSet(*myws.pdf(Form("pdfCTAUMASS_Psi2SNoPR_%s", (isPbPb?"PbPb":"PP"))))),
                                             ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                             Normalization(normDSTot, RooAbsReal::NumEvent),
                                             LineColor(kGreen+3), LineStyle(1), Precision(1e-4), NumCPU(32)
                                             );
      }      
    } 
  }
  if (incSS) { 
    myws.data(dsSSName.c_str())->plotOn(frame, Name("dSS"), MarkerColor(kRed), LineColor(kRed), MarkerSize(1.2)); 
  }
  myws.data(dsOSName.c_str())->plotOn(frame, Name("dOS"), DataError(RooAbsData::SumW2), XErrorSize(0), MarkerColor(kBlack), LineColor(kBlack), MarkerSize(1.2));
  myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PDF"),
                                       ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                       Normalization(normDSTot, RooAbsReal::NumEvent),
                                       LineColor(kBlack), NumCPU(32)
                                       );
  
  // Create the pull distribution of the fit 
  RooPlot* frameTMP = (RooPlot*)frame->Clone("TMP");
  int nBinsTMP = nBins;
  RooHist *hpull = frameTMP->pullHist(0, 0, true);
  hpull->SetName("hpull");
  RooPlot* frame2 = myws.var("invMass")->frame(Title("Pull Distribution"), Bins(nBins), Range(cut.dMuon.M.Min, cut.dMuon.M.Max));
  frame2->addPlotable(hpull, "PX"); 
  
  // set the CMS style
  setTDRStyle();
  
  // Create the main canvas
  TCanvas *cFig  = new TCanvas(Form("cMassFig_%s", (isPbPb?"PbPb":"PP")), "cMassFig",800,800);
  TPad    *pad1  = new TPad(Form("pad1_%s", (isPbPb?"PbPb":"PP")),"",0,paperStyle ? 0 : 0.23,1,1);
  TPad    *pad2  = new TPad(Form("pad2_%s", (isPbPb?"PbPb":"PP")),"",0,0,1,.228);
  TLine   *pline = new TLine(cut.dMuon.M.Min, 0.0, cut.dMuon.M.Max, 0.0);
  
  // TPad *pad4 = new TPad("pad4","This is pad4",0.55,0.46,0.97,0.87);
  TPad *pad4 = new TPad("pad4","This is pad4",0.55,paperStyle ? 0.29 : 0.36,0.97,paperStyle ? 0.70 : 0.77);
  pad4->SetFillStyle(0);
  pad4->SetLeftMargin(0.28);
  pad4->SetRightMargin(0.10);
  pad4->SetBottomMargin(0.21);
  pad4->SetTopMargin(0.072);

  frame->SetTitle("");
  frame->GetXaxis()->CenterTitle(kTRUE);
  if (!paperStyle) {
     frame->GetXaxis()->SetTitle("");
     frame->GetXaxis()->SetTitleSize(0.045);
     frame->GetXaxis()->SetTitleFont(42);
     frame->GetXaxis()->SetTitleOffset(3);
     frame->GetXaxis()->SetLabelOffset(3);
     frame->GetYaxis()->SetLabelSize(0.04);
     frame->GetYaxis()->SetTitleSize(0.04);
     frame->GetYaxis()->SetTitleOffset(1.7);
     frame->GetYaxis()->SetTitleFont(42);
  } else {
     frame->GetXaxis()->SetTitle("m_{#mu^{+}#mu^{-}} (GeV/c^{2})");
     frame->GetXaxis()->SetTitleOffset(1.1);
     frame->GetYaxis()->SetTitleOffset(1.45);
     frame->GetXaxis()->SetTitleSize(0.05);
     frame->GetYaxis()->SetTitleSize(0.05);
  }
  setMassFrom2DRange(myws, frame, dsOSName, setLogScale);
  if (paperStyle) {
     double Ydown = 0.;//frame->GetMinimum();
     double Yup = 0.9*frame->GetMaximum();
     frame->GetYaxis()->SetRangeUser(Ydown,Yup);
  }
 
  cFig->cd();
  pad2->SetTopMargin(0.02);
  pad2->SetBottomMargin(0.4);
  pad2->SetFillStyle(4000); 
  pad2->SetFrameFillStyle(4000); 
  if (!paperStyle) pad1->SetBottomMargin(0.015); 
  //plot fit
  pad1->Draw();
  pad1->cd(); 
  frame->Draw();

  printMassFrom2DParameters(myws, pad1, isPbPb, pdfTotName, isWeighted);
  pad1->SetLogy(setLogScale);

  // Drawing the text in the plot
  TLatex *t = new TLatex(); t->SetNDC(); t->SetTextSize(0.032);
  float dy = 0; 
  
  t->SetTextSize(0.03);
  if (!paperStyle) { // do not print selection details for paper style
     t->DrawLatex(0.20, 0.86-dy, "2015 HI Soft Muon ID"); dy+=0.045;
     if (isPbPb) {
        t->DrawLatex(0.20, 0.86-dy, "HLT_HIL1DoubleMu0_v1"); dy+=2.0*0.045;
     } else {
        t->DrawLatex(0.20, 0.86-dy, "HLT_HIL1DoubleMu0_v1"); dy+=2.0*0.045;
     } 
  }
  if (cut.dMuon.AbsRap.Min>0.1) {t->DrawLatex(0.5175, 0.86-dy, Form("%.1f < |y^{#mu#mu}| < %.1f",cut.dMuon.AbsRap.Min,cut.dMuon.AbsRap.Max)); dy+=0.045;}
  else {t->DrawLatex(0.5175, 0.86-dy, Form("|y^{#mu#mu}| < %.1f",cut.dMuon.AbsRap.Max)); dy+=0.045;}
  t->DrawLatex(0.5175, 0.86-dy, Form("%g < p_{T}^{#mu#mu} < %g GeV/c",cut.dMuon.Pt.Min,cut.dMuon.Pt.Max)); dy+=0.045;
  if (isPbPb) {t->DrawLatex(0.5175, 0.86-dy, Form("Cent. %d-%d%%", (int)(cut.Centrality.Start/2), (int)(cut.Centrality.End/2))); dy+=0.045;}

  // Drawing the Legend
  double ymin = 0.7602;
  if (incPsi2S && incJpsi && incSS)  { ymin = 0.7202; } 
  if (incPsi2S && incJpsi && !incSS) { ymin = 0.7452; }
  if (paperStyle) { ymin = 0.72; }
  TLegend* leg = new TLegend(0.5175, ymin, 0.7180, 0.8809); leg->SetTextSize(0.03);
  if (frame->findObject("dOS")) { leg->AddEntry(frame->findObject("dOS"), (incSS?"Opposite Charge":"Data"),"pe"); }
  if (incSS) { leg->AddEntry(frame->findObject("dSS"),"Same Charge","pe"); }
  if (frame->findObject("PDF")) { leg->AddEntry(frame->findObject("PDF"),"Total fit","l"); }
  if (frame->findObject("JPSIPR")) { leg->AddEntry(frame->findObject("JPSIPR"),"Prompt J/#psi","l"); }
  if (frame->findObject("JPSINOPR")) { leg->AddEntry(frame->findObject("JPSINOPR"),"Non-Prompt J/#psi","l"); }
  if (incBkg && frame->findObject("BKG")) { leg->AddEntry(frame->findObject("BKG"),"Background",paperStyle ? "l" : "fl"); }
  leg->Draw("same");

  //Drawing the title
  TString label;
  if (isPbPb) {
    if (opt.PbPb.RunNb.Start==opt.PbPb.RunNb.End){
      label = Form("PbPb Run %d", opt.PbPb.RunNb.Start);
    } else {
      label = Form("%s [%s %d-%d]", "PbPb", "HIOniaL1DoubleMu0", opt.PbPb.RunNb.Start, opt.PbPb.RunNb.End);
    }
  } else {
    if (opt.pp.RunNb.Start==opt.pp.RunNb.End){
      label = Form("PP Run %d", opt.pp.RunNb.Start);
    } else {
      label = Form("%s [%s %d-%d]", "PP", "DoubleMu0", opt.pp.RunNb.Start, opt.pp.RunNb.End);
    }
  }
  
  // CMS_lumi(pad1, isPbPb ? 105 : 104, 33, label);
  CMS_lumi(pad1, isPbPb ? 108 : 107, 33, "");
  if (!paperStyle) gStyle->SetTitleFontSize(0.05);
  
  pad1->Update();
  cFig->cd(); 

  if (!paperStyle) {
     //---plot pull
     pad2->Draw();
     pad2->cd();

     frame2->SetTitle("");
     frame2->GetYaxis()->CenterTitle(kTRUE);
     frame2->GetYaxis()->SetTitleOffset(0.4);
     frame2->GetYaxis()->SetTitleSize(0.1);
     frame2->GetYaxis()->SetLabelSize(0.1);
     frame2->GetYaxis()->SetTitle("Pull");
     frame2->GetXaxis()->CenterTitle(kTRUE);
     frame2->GetXaxis()->SetTitleOffset(1);
     frame2->GetXaxis()->SetTitleSize(0.12);
     frame2->GetXaxis()->SetLabelSize(0.1);
     frame2->GetXaxis()->SetTitle("m_{#mu^{+}#mu^{-}} (GeV/c^{2})");
     frame2->GetYaxis()->SetRangeUser(-7.0, 7.0);

     frame2->Draw(); 

     // *** Print chi2/ndof 
     printChi2(myws, pad2, frameTMP, "invMass", dsOSName.c_str(), pdfTotName.c_str(), nBinsTMP, false);

     pline->Draw("same");
     pad2->Update();
  }

  // Save the plot in different formats
  gSystem->mkdir(Form("%sctauMass/%s/plot/root/", outputDir.c_str(), DSTAG.c_str()), kTRUE); 
  cFig->SaveAs(Form("%sctauMass/%s/plot/root/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.root", outputDir.c_str(), DSTAG.c_str(), "MASS", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  gSystem->mkdir(Form("%sctauMass/%s/plot/png/", outputDir.c_str(), DSTAG.c_str()), kTRUE);
  cFig->SaveAs(Form("%sctauMass/%s/plot/png/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.png", outputDir.c_str(), DSTAG.c_str(), "MASS", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  gSystem->mkdir(Form("%sctauMass/%s/plot/pdf/", outputDir.c_str(), DSTAG.c_str()), kTRUE);
  cFig->SaveAs(Form("%sctauMass/%s/plot/pdf/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.pdf", outputDir.c_str(), DSTAG.c_str(), "MASS", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  
  cFig->Clear();
  cFig->Close();
};
void plotDavid(TH1F* bkgT, TH1F* sigT, TH1F* dataT, std::string name){
  
  gROOT->SetBatch();
  system("mkdir -p plots/ada/david");
  system("mkdir -p plots/grad/david");
  system("mkdir -p plots/ada/diff");
  system("mkdir -p plots/grad/diff");

  std::string bdt;
  TString str = dataT->GetName();
  if (str.Contains("ada")) bdt="ada";
  else if (str.Contains("grad")) bdt="grad";
  else std::cout << "Error find BDT type" << std::endl;
  assert (str.Contains("ada") || str.Contains("grad"));

  if (bkgT->GetNbinsX() != sigT->GetNbinsX() || sigT->GetNbinsX() != dataT->GetNbinsX()) std::cout << "Plot problem: calling plot for histograms with different number of bins" << std::endl;
  assert(bkgT->GetNbinsX() == sigT->GetNbinsX() || sigT->GetNbinsX() == dataT->GetNbinsX());
  
  TH1F *bkg = linearBin(bkgT);
  TH1F *sig2 = linearBin(sigT);
  TH1F *sig5 = (TH1F*)sig2->Clone();
  TH1F *sig10 = (TH1F*)sig2->Clone();
  TH1F *data = linearBin(dataT);
  TH1F *diff = (TH1F*)data->Clone();
  diff->Add(bkg,-1);

  gStyle->SetOptStat(0);
  gROOT->SetStyle("Plain");
  gROOT->ForceStyle();

  TCanvas *canv = new TCanvas();
  bkg->SetLineColor(kBlue);
  bkg->SetFillColor(kBlue-9);
  sig2->SetLineColor(kRed);
  sig2->SetLineStyle(3);
  sig2->Scale(1.);
  sig5->SetLineColor(kRed);
  sig5->SetLineStyle(7);
  sig5->Scale(3.);
  sig10->SetLineColor(kRed);
  sig10->Scale(5.);
  data->SetMarkerStyle(20);
  bkg->SetTitle(("Background, data and signal distributions for "+bdt+" "+name).c_str());
  sig2->SetTitle(("Background, data and signal distributions for "+bdt+" "+name).c_str());
  data->SetTitle(("Background, data and signal distributions for "+bdt+" "+name).c_str());
  bkg->GetXaxis()->SetTitle("");
  sig2->GetXaxis()->SetTitle("");
  data->GetXaxis()->SetTitle("");
  bkg->GetYaxis()->SetTitle("Events");
  sig2->GetYaxis()->SetTitle("Events");
  data->GetYaxis()->SetTitle("Events");

  TLegend *leg = new TLegend(0.45,0.6,0.85,0.85);
  leg->SetLineColor(0);
  leg->SetFillColor(0);
  leg->AddEntry(bkg,"Background","f");
  leg->AddEntry(data,"Data","lep");
  leg->AddEntry(sig10,"Signal (1, 3, 5 #times SM)","l");
  TPaveText *txt = new TPaveText(0.2,0.1,0.4,0.35,"NDC");
  txt->SetFillColor(0);
  txt->SetLineColor(0);
  txt->AddText("#int L = 4.76 fb^{-1}");

  bkg->GetYaxis()->SetRangeUser(1.0,2.*(data->GetMaximum()));

  bkg->Draw("e2");
  sig2->Draw("same hist");
  sig5->Draw("same hist");
  sig10->Draw("same hist");
  data->Draw("same e");
  leg->Draw("same");
  txt->Draw("same");

  canv->SetLogy();
  canv->Print(("plots/"+bdt+"/david/"+name+".png").c_str(),"png");
  canv->SetLogy(false);
  canv->Clear();
  TLegend *leg2 = new TLegend(0.45,0.6,0.85,0.85);
  leg2->SetFillColor(0);
  leg2->SetLineColor(0);
  sig10->GetYaxis()->SetRangeUser((-1*sig10->GetMaximum())+10,sig10->GetMaximum()+20);
  sig10->GetXaxis()->SetTitle("");
  sig10->GetYaxis()->SetTitle("Events");
  sig10->SetTitle(Form("Data, background difference compared to signal %s %s",bdt.c_str(),name.c_str()));
  diff->SetMarkerStyle(20);
  diff->GetXaxis()->SetTitle("");
  diff->GetYaxis()->SetTitle("Events");
  leg2->AddEntry(diff,"Data - background model","lep");
  leg2->AddEntry(sig10,"Signal (1, 3, 5 #times SM)","l");
  TF1 *line = new TF1("line","0.0",0.0,sig10->GetNbinsX()+1);
  line->SetLineColor(kBlue);
  sig10->Draw("hist");
  sig5->Draw("same hist");
  sig2->Draw("same hist");
  line->Draw("same");
  diff->Draw("p same");
  leg2->Draw("same");
  txt->Draw("same");
  canv->Print(("plots/"+bdt+"/diff/"+name+".png").c_str(),"png");

  delete canv;
  delete txt;
  delete leg;
  
  davidCalls++;
}
Esempio n. 25
0
void plotauto(TString infilename) {

  TString plname = infilename+".ps";
  TCanvas* cc = new TCanvas("validate","validate",500,370);
  cc->Print(plname+"[");

  TText tt;
  tt.SetTextColor(2);
  tt.SetTextSize(0.02);

  gStyle->SetMarkerSize(0.1);
  gStyle->SetTitleSize(0.15,"ff");
  gStyle->SetTitleTextColor(4);

  std::vector < TString > vnames;
  vnames.push_back("Sim_HitEn");
  vnames.push_back("Sim_HitTime");
  vnames.push_back("Sim_posXY");
  vnames.push_back("Sim_posXZ");
  vnames.push_back("Sim_posYZ");
  vnames.push_back("Sim_posRZ");

  std::vector <TString> exts;
  exts.push_back("");
  exts.push_back("_posZ");
  exts.push_back("_negZ");

  TH1F* h;
  TH2F* hh;
  TKey *key;
  TIter next;
  TKey *key2;
  TIter next2;

  TFile* infile = new TFile(infilename, "read");

  // overall geometry
  TDirectory* td = (TDirectory*) infile->Get("ALLCollections");
  cc->Clear();
  cc->Divide(3,3);
  cc->cd(1);
  hh = (TH2F*) td->Get("ALLCollections_overallhitZR");
  hh->Draw("box");
  cc->cd(2);
  int icol=1;
  bool first=true;
  TLegend* tl = new TLegend(0., 0., 1, 1);
  next = td->GetListOfKeys();
  while ((key = (TKey*)next())) {
    TClass *cll = gROOT->GetClass(key->GetClassName());
    if (cll->InheritsFrom("TH2F")) {
      hh = (TH2F*)key->ReadObj();
      TString hn = hh->GetName();
      if ( hn.Contains("ALL") ) continue;
      if ( hn.Contains("_Log") ) continue;
      hh->SetLineColor(icol);
      if ( first ) {hh->Draw("box"); first=false;}
      else hh->Draw("same;box");
      icol++;
      if (icol==10) icol=1;
      TString ss = hn.ReplaceAll( "_overallhitZR", "");
      tl->AddEntry(hh, ss , "l");
    }
  }
  // the legend
  cc->cd(3);
  tl->Draw();

  cc->cd(4);
  hh = (TH2F*) td->Get("ALLCollections_Log_overallhitZR");
  hh->Draw("box");
  cc->cd(5);
  icol=1;
  first=true;
  next = td->GetListOfKeys();
  while ((key = (TKey*)next())) {
    TClass *cll = gROOT->GetClass(key->GetClassName());
    if (cll->InheritsFrom("TH2F")) {
      hh = (TH2F*)key->ReadObj();
      TString hn = hh->GetName();
      if ( hn.Contains("ALL" ) ) continue;
      if ( ! hn.Contains("_Log_") ) continue;
      hh->SetLineColor(icol);
      if ( first ) {hh->Draw("box"); first=false;}
      else hh->Draw("same;box");
      icol++;
      if (icol==10) icol=1;
    }
  }

  cc->cd(7);
  hh = (TH2F*) td->Get("ALLCollections_LogLog_overallhitZR");
  hh->Draw("box");
  cc->cd(8);
  icol=1;
  first=true;
  next = td->GetListOfKeys();
  while ((key = (TKey*)next())) {
    TClass *cll = gROOT->GetClass(key->GetClassName());
    if (cll->InheritsFrom("TH2F")) {
      hh = (TH2F*)key->ReadObj();
      TString hn = hh->GetName();
      if ( hn.Contains("ALL" ) ) continue;
      if ( ! hn.Contains("_LogLog_") ) continue;
      hh->SetLineColor(icol);
      if ( first ) {hh->Draw("box"); first=false;}
      else hh->Draw("same;box");
      icol++;
      if (icol==10) icol=1;
    }
  }


  cc->Print(plname);

  // now collection-by-collection

  next = infile->GetListOfKeys();
  while ((key = (TKey*)next())) {
    TClass *cll = gROOT->GetClass(key->GetClassName());
    if (cll->InheritsFrom("TDirectory")) {
      td = (TDirectory*)key->ReadObj();
      TString dirname = td->GetName();
      if ( dirname=="ALLCollections" ) continue;

      // is it an endcap collection?
      bool isEndcap = td->Get(dirname+"_hitXY_posZ");

      // first overall geometry
      cc->Clear();
      cc->Divide(3,2);

	cc->cd(1);
	( (TH2F*) td->Get(dirname+"_hitEn"))->Draw("box");
	cc->cd(4)->SetLogy();
	( (TH2F*) td->Get(dirname+"_hitTime"))->Draw("box");

      if ( isEndcap ) {
	cc->cd(2);
	( (TH2F*) td->Get(dirname+"_hitXY_posZ"))->Draw("box");
	cc->cd(3);
	( (TH2F*) td->Get(dirname+"_hitXY_negZ"))->Draw("box");
	cc->cd(5);
	((TH2F*) td->Get(dirname+"_hitZR_posZ"))->Draw("box");
	cc->cd(6);
	((TH2F*) td->Get(dirname+"_hitZR_negZ"))->Draw("box");
      } else {
	cc->cd(2);
	( (TH2F*) td->Get(dirname+"_hitXY"))->Draw("box");
	cc->cd(3);
	( (TH2F*) td->Get(dirname+"_hitZR"))->Draw("box");
      }

      cc->Print(plname);


      // then the cell indices

      // work out how many indices/variables we're dealing with
      std::vector < TString > indices;
      std::vector < TString > variables;
      next2 = td->GetListOfKeys();
      while ((key2 = (TKey*)next2())) {
	cll = gROOT->GetClass(key2->GetClassName());
	if (cll->InheritsFrom("TH2F")) {
	  hh = (TH2F*) key2->ReadObj();
	  TString hn = hh->GetName();
	  if ( hn.Contains("Indx") ) {
	    TString ss = hn.ReplaceAll(dirname+"_", "");
	    TString asas = ((TObjString*) (ss.Tokenize("_") -> At(0)))->GetString();
	    if ( find( indices.begin(), indices.end(), asas )==indices.end() ) indices.push_back(asas);
	    asas = ((TObjString*) (ss.Tokenize("_") -> At(1)))->GetString();
	    if ( find( variables.begin(), variables.end(), asas )==variables.end() ) variables.push_back(asas);
	  }
	}
      }

      if ( indices.size()==0 || variables.size()==0 ) continue;


      for (int inp=0; inp<2; inp++) {
	if ( !isEndcap && inp==1 ) continue;
	cc->Clear();
	cc->Divide(indices.size(), variables.size());
	int ic=1;
	next2 = td->GetListOfKeys();
	while ((key2 = (TKey*)next2())) {
	  cll = gROOT->GetClass(key2->GetClassName());
	  if (cll->InheritsFrom("TH2F")) {
	    hh = (TH2F*) key2->ReadObj();
	    TString hn = hh->GetName();
	    if ( isEndcap ) {
	      if      ( inp==0 && ! hn.Contains("posZ") ) continue;
	      else if ( inp==1 && ! hn.Contains("negZ") ) continue;
	    }
	    if ( hn.Contains("Indx") ) {
	      TString asas = ((TObjString*) (hn.Tokenize("_") -> At(1)))->GetString();
	      asas = asas(4,asas.Length());
	      cc->cd(ic++);
	      hh->Draw("box");
	    }
	  }
	}

	cc->cd();
	for ( size_t k=0; k<variables.size(); k++) {
	  tt.DrawTextNDC( 0.0, 0.9 - (1.0*k)/(variables.size()), variables[k] );
	}

	for ( size_t k=0; k<indices.size(); k++) {
	  tt.DrawTextNDC( 0.05 + (1.0*k)/(indices.size()), 0.02, indices[k].ReplaceAll("Indx","Indx_") );
	}

	tt.DrawTextNDC( 0.1, 0.99, dirname);
	if ( isEndcap ) {
	  if (inp==0 ) tt.DrawTextNDC( 0.35, 0.99, "posZ");
	  else         tt.DrawTextNDC( 0.35, 0.99, "negZ");
	}

	cc->Print(plname);
      }
    }
  }

  infile->Close();

  cc->Print(plname+"]");
}
Esempio n. 26
0
void runEffRej() {	
	
	gROOT->LoadMacro("AtlasStyle.C");
	gROOT->LoadMacro("AtlasUtils.C");
	gROOT->LoadMacro("AtlasLabels.C");
	
	TString input("effrej_su4");

	TFile* r17 = new TFile(TString("input/btagval.su4.susy1049.root"),"READ");
	TFile* r16 = new TFile(TString("input/btagval.su4.susy1004.root"),"READ");
	
	TString prefix("btagwgt/");
	
	bool doLogY = true;
	//bool doLogY = false;
	
	vector<TString> cuts;

//	cuts.push_back("2jet_metmeff0.25");
	cuts.push_back("2jet_deltaphi0.4");
//	cuts.push_back("2jet_deltaphi0.4cr");
//	cuts.push_back("2jet_nbtag1");
//	cuts.push_back("2jet_qcdcontrol");
//	cuts.push_back("2jet_nbtag2");
//	cuts.push_back("2jet_metphi");
//	cuts.push_back("2jet_mct100");
//	cuts.push_back("2jet_mct100cr");
//	cuts.push_back("2jet_mct150"); 
//	cuts.push_back("2jet_mct200"); 
	
//	cuts.push_back("2jetX_metmeff0.25");
//	cuts.push_back("2jetX_deltaphi0.4");
//	cuts.push_back("2jetX_deltaphi0.4cr");
//	cuts.push_back("2jetX_nbtag1");
//	cuts.push_back("2jetX_qcdcontrol"); 
//	cuts.push_back("2jetX_nbtag2");
//	cuts.push_back("2jetX_metphi");
//	cuts.push_back("2jetX_mct100");
//	cuts.push_back("2jetX_mct100cr");
//	cuts.push_back("2jetX_mct150"); 
//	cuts.push_back("2jetX_mct200"); 
	
//	cuts.push_back("3jet_metmeff0.25");
	cuts.push_back("3jet_deltaphi0.4");
//	cuts.push_back("3jet_nbtag1");
//	cuts.push_back("3jet_ewcontrol");
//	cuts.push_back("3jet_topcontrol");
//	cuts.push_back("3jet_topcontrol_2");
/*	cuts.push_back("3jet_meff500_qcdcontrol");
	cuts.push_back("3jet_meff500_2_qcdcontrol");
	cuts.push_back("3jet_meff700_qcdcontrol");
	cuts.push_back("3jet_meff700_2_qcdcontrol");
	cuts.push_back("3jet_meff900_qcdcontrol");
	cuts.push_back("3jet_meff900_2_qcdcontrol"); */
/*	cuts.push_back("3jet_meff500");
	cuts.push_back("3jet_meff500_2");
	cuts.push_back("3jet_meff700");
	cuts.push_back("3jet_meff700_2");
	cuts.push_back("3jet_meff900");
	cuts.push_back("3jet_meff900_2");
*/	
	vector<TString> plottype;
	plottype.push_back("jjfitNN0jfitNN");
	plottype.push_back("jjfitNN1jfitNN");
	plottype.push_back("jjfitNN2jfitNN");
	plottype.push_back("jsv00sv0");		
	plottype.push_back("jsv01sv0");		
	plottype.push_back("jsv02sv0");	

	TString logstring = "";
	if(doLogY) logstring = "_logy";
	
	TCanvas* canvas = new TCanvas();
	canvas->Print(TString::Format("output/%s_2jet%s.ps[",input.Data(),logstring.Data()),"Portrait");
	canvas->Print(TString::Format("output/%s_2jetX%s.ps[",input.Data(),logstring.Data()),"Portrait");
	canvas->Print(TString::Format("output/%s_3jet%s.ps[",input.Data(),logstring.Data()),"Portrait");
	
	gStyle->SetPaperSize(100,20);
	
	vector<TString>::iterator cut = cuts.begin();
	for(; cut!=cuts.end(); cut++) {
	
		vector<TString>::iterator type = plottype.begin();
		for(; type!=plottype.end(); type++) {
		
			canvas->Clear();
			canvas->SetLogy(doLogY);

			TString histo_l = TString::Format("%s%s_%s_l",prefix.Data(),cut->Data(),type->Data());
			TString histo_c = TString::Format("%s%s_%s_c",prefix.Data(),cut->Data(),type->Data());
			TString histo_b = TString::Format("%s%s_%s_b",prefix.Data(),cut->Data(),type->Data());
			
			TH1F* R17_l = (TH1F*)r17->Get(histo_l);
			TH1F* R17_c = (TH1F*)r17->Get(histo_c);
			TH1F* R17_b = (TH1F*)r17->Get(histo_b);
			
			TH1F* R16_l = (TH1F*)r16->Get(histo_l);
			TH1F* R16_c = (TH1F*)r16->Get(histo_c);
			TH1F* R16_b = (TH1F*)r16->Get(histo_b);
			
			map<TString, float> op; //op, eff
			map<TString, float> r17op; //op, eff
			map<TString, float> newop; //oldop, newop			
			//Find current efficiency operating points
			if(histo_b.Contains("sv0")) {
				op["5.85"] = R16_b->Integral(R16_b->FindBin(5.85),-1)/R16_b->Integral(0,-1);
				r17op["5.85"] = R17_b->Integral(R17_b->FindBin(5.85),-1)/R17_b->Integral(0,-1);
				
				for(int i = 0; i<100; i++) {
					float eff = R17_b->Integral(i,-1)/R17_b->Integral(0,-1);
					//cout << eff << " " << op["5.85"] << endl;
					if(eff>op["5.85"]) continue;
					else {
						//float slope = (R17_b->GetBinCenter(i)-R17_b->GetBinCenter(i-1))/(eff-R17_b->Integral(i-1,-1)/R17_b->Integral(0,-1));
						//newop["5.85"] = R17_b->GetBinCenter(i-1)+slope*(op["5.85"]-R17_b->Integral(i-1,-1)/R17_b->Integral(0,-1));
						newop["5.85"] = (R17_b->GetBinCenter(i-1)+R17_b->GetBinCenter(i))/2.;
						break;
					}
				}
				cout << "5.85: "<< op["5.85"] << ", " << newop["5.85"] << ": " << R17_b->Integral(R17_b->FindBin(newop["5.85"]),-1)/R17_b->Integral(0,-1) << endl;
			}
			else {
				op["2.00"] = R16_b->Integral(R16_b->FindBin(2.00),-1)/R16_b->Integral(0,-1);
				op["0.35"] = R16_b->Integral(R16_b->FindBin(0.35),-1)/R16_b->Integral(0,-1);
				op["-1.25"] = R16_b->Integral(R16_b->FindBin(-1.25),-1)/R16_b->Integral(0,-1);	
				
				r17op["2.00"] = R17_b->Integral(R16_b->FindBin(2.00),-1)/R17_b->Integral(0,-1);
				r17op["0.35"] = R17_b->Integral(R16_b->FindBin(0.35),-1)/R17_b->Integral(0,-1);
				r17op["-1.25"] = R17_b->Integral(R16_b->FindBin(-1.25),-1)/R17_b->Integral(0,-1);	
				
				for(int i = 0; i<100; i++) {
					float eff = R17_b->Integral(i,-1)/R17_b->Integral(0,-1);
					//cout << eff << " " << op["2.00"] << endl;
					if(eff>op["2.00"]) continue;
					else {
						//float slope = (R17_b->GetBinCenter(i)-R17_b->GetBinCenter(i-1))/(eff-R17_b->Integral(i-1,-1)/R17_b->Integral(0,-1));
						//newop["2.00"] = R17_b->GetBinCenter(i-1)+slope*(op["2.00"]-R17_b->Integral(i-1,-1)/R17_b->Integral(0,-1));
						newop["2.00"] = (R17_b->GetBinCenter(i-1)+R17_b->GetBinCenter(i))/2.;
						break;
					}
				}
				cout << "2.00: "<< op["2.00"] << ", " << newop["2.00"] << ": " << R17_b->Integral(R17_b->FindBin(newop["2.00"]),-1)/R17_b->Integral(0,-1) << endl;

				for(int i = 0; i<100; i++) {
					float eff = R17_b->Integral(i,-1)/R17_b->Integral(0,-1);
					//cout << eff << " " << op["0.35"] << endl;
					if(eff>op["0.35"]) continue;
					else {
						//float slope = (R17_b->GetBinCenter(i)-R17_b->GetBinCenter(i-1))/(eff-R17_b->Integral(i-1,-1)/R17_b->Integral(0,-1));
						//newop["0.35"] = R17_b->GetBinCenter(i-1)+slope*(op["0.35"]-R17_b->Integral(i-1,-1)/R17_b->Integral(0,-1));
						newop["0.35"] = (R17_b->GetBinCenter(i-1)+R17_b->GetBinCenter(i))/2.;
						break;
					}
				}
				cout << "0.35: "<< op["0.35"] << ", " << newop["0.35"] << ": " << R17_b->Integral(R17_b->FindBin(newop["0.35"]),-1)/R17_b->Integral(0,-1) << endl;

				for(int i = 0; i<100; i++) {
					float eff = R17_b->Integral(i,-1)/R17_b->Integral(0,-1);
					//cout << eff << " " << op["0.35"] << endl;
					if(eff>op["-1.25"]) continue;
					else {
						//float slope = (R17_b->GetBinCenter(i)-R17_b->GetBinCenter(i-1))/(eff-R17_b->Integral(i-1,-1)/R17_b->Integral(0,-1));
						//newop["-1.25"] = R17_b->GetBinCenter(i-1)+slope*(op["-1.25"]-R17_b->Integral(i-1,-1)/R17_b->Integral(0,-1));
						newop["-1.25"] = (R17_b->GetBinCenter(i-1)+R17_b->GetBinCenter(i))/2.;
						break;
					}
				}
				cout << "-1.25: "<< op["-1.25"] << ", " << newop["-1.25"] << ": " << R17_b->Integral(R17_b->FindBin(newop["-1.25"]),-1)/R17_b->Integral(0,-1) << endl;

			}

			R17_l->Rebin(5);
			R17_c->Rebin(5);
			R17_b->Rebin(5);
			
			R16_l->Rebin(5);
			R16_c->Rebin(5);
			R16_b->Rebin(5);
			
			TH2F* grid = new TH2F("grid","grid",2,0.,1.,2,1.,1000.);
			TString num;
			if(histo_b.Contains("2")) num = "3 tags";
			else if(histo_b.Contains("1")) num = "2 tags";
			else if(histo_b.Contains("0")) num = "1 tag";
			
			grid->SetXTitle(TString("Efficiency ("+num+")"));
			grid->SetYTitle("l-jet Rejection");
			//grid->Reset();
			//grid->SetMinimum(0.);
			//grid->SetMaximum(1.);
			
			grid->Draw();
			
			TGraph* r16graph = MakeEffRej(R16_l,R16_c,R16_b);
			TGraph* r17graph = MakeEffRej(R17_l,R17_c,R17_b);
			
			r16graph->SetMarkerColor(kBlack);
			r16graph->SetLineColor(kBlack);
			r16graph->Draw("elp same");
			
			r17graph->SetMarkerColor(kRed);
			r17graph->SetLineColor(kRed);
			//r17graph->SetMarkerSize();
			r17graph->Draw("elp same");
			

			//stacked->SetATLASLabel("Preliminary");
			//if(input.Contains("JetTauEtmiss")) stacked->SetLumi("95.6 pb^{-1}");
			//else stacked->SetLumi("2.052 fb^{-1}");
			
			TString label(TString("#splitline{"+input+"}{"));
			label.Append(*cut);
			label.Append("}");
			TLatex n2;
			n2.SetNDC();
			n2.SetTextFont(42);
			n2.SetTextColor(kBlack);
			n2.DrawLatex(0.20,0.25,label.Data());
			
			float leg_ylower = 0.90-((float)(2+op.size()))*0.06;
			TLegend* legend = new TLegend(0.75,leg_ylower,0.95,0.95);
			legend->SetFillStyle(0);
			legend->SetBorderSize(0);
			TLegendEntry* entry = 0;
			
			entry = legend->AddEntry(r17graph,"Release 17","elp");
			entry->SetTextAlign(12);
			entry->SetTextColor(1);
			
			entry = legend->AddEntry(r16graph,"Release 16","elp");
			entry->SetTextAlign(12);
			entry->SetTextColor(1);
			
			map<TString, float>::iterator iter = op.begin();
			int color = 3;
			for(; iter!=op.end(); iter++) {
				TLine* line = new TLine(iter->second,0.,iter->second,1000.);
				line->SetLineColor(color);
				line->Draw("same");
			
				TH1F* histo = new TH1F();
				histo->SetLineColor(color);
				entry = legend->AddEntry(histo,TString("Release 16, "+iter->first+ " ("+TString::Format("R17 %0.2f",newop[iter->first])+")"),"l");
				entry->SetTextAlign(12);
				entry->SetTextColor(1);
				color++;
			}
			
			iter = r17op.begin();
			for(; iter!=r17op.end(); iter++) {
				TLine* line = new TLine(iter->second,0.,iter->second,1000.);
				line->SetLineColor(color);
				line->Draw("same");
			
				TH1F* histo = new TH1F();
				histo->SetLineColor(color);
				entry = legend->AddEntry(histo,TString("Release 17, "+iter->first),"l");
				entry->SetTextAlign(12);
				entry->SetTextColor(1);
				color++;
			}
			
			legend->Draw();
			canvas->Update();
			
			if(cut->Contains("2jet_")) canvas->Print(TString::Format("output/%s_2jet%s.ps",input.Data(),logstring.Data()));
			else if(cut->Contains("2jetX_")) canvas->Print(TString::Format("output/%s_2jetX%s.ps",input.Data(),logstring.Data()));
			else if(cut->Contains("3jet_")) canvas->Print(TString::Format("output/%s_3jet%s.ps",input.Data(),logstring.Data()));
			canvas->Print(TString::Format("output/%s_%s_%s%s.eps",input.Data(),cut->Data(),type->Data(),logstring.Data()));
			
			delete r16graph;
			delete r17graph;
			delete grid;
		}
	}
	
	canvas->Print(TString::Format("output/%s_2jet%s.ps]",input.Data(),logstring.Data()),"Portrait");
	canvas->Print(TString::Format("output/%s_2jetX%s.ps]",input.Data(),logstring.Data()),"Portrait");
	canvas->Print(TString::Format("output/%s_3jet%s.ps]",input.Data(),logstring.Data()),"Portrait");
}
Esempio n. 27
0
int muQual_simple() {

  // Parameters  
  FLAG *flag = new FLAG;
  flag->doSta = true;
  flag->doGlb = false;
  
  string data2010  = "/castor/cern.ch/user/m/miheejo/openHLT/cms442p5/HICorePhysics_Skim_MinimumBias_RAW/openhlt_2010HICorePhysicsMB.root";
  // 2011 file will be updated.
  string data2011  = "/castor/cern.ch/user/m/miheejo/openHLT/cms442p5/HICorePhysics_Skim_MinimumBias_RAW/openhlt_2010HICorePhysicsMB.root";

  // Check trigger list
  vector<string> triglist;
  triglist.push_back("HLT_HIL1DoubleMu0_HighQ_v1");
  triglist.push_back("HLT_HIL2DoubleMu3_v1");
  triglist.push_back("HLT_HIL3DoubleMuOpen_v1");
  triglist.push_back("HLT_HIL3DoubleMuOpen_Mgt2_OS_NoCowboy_v1");
  triglist.push_back("HLT_HIL2Mu3_v1");
  triglist.push_back("HLT_HIL2Mu7_v1");
  triglist.push_back("HLT_HIL2Mu15_v1");
  triglist.push_back("HLT_HIL2Mu3_NHitQ_v1");
  triglist.push_back("HLT_HIL3Mu3_v1");

  // Histograms
  TH2F *SingleGlb_Etapt_2010 = new TH2F("SingleGlb_etapt_2010","SingleGlb_etapt_2010;single mu #eta;single mu p_{T}",ETA,-2.4,2.4,PT,0,20);
  TH2F *SingleGlb_Etapt_2011 = new TH2F("SingleGlb_etapt_2011","SingleGlb_etapt_2011;single mu #eta;single mu p_{T}",ETA,-2.4,2.4,PT,0,20);


  // Input files
  // 2010 datafile
  TCastorFile   *input_2010 = new TCastorFile(data2010.c_str());
  FriendMuTree  *mutree_2010 = new FriendMuTree(input_2010,true); // Load HLTMuTree
  HltTree       *ohTree_2010 = new HltTree(input_2010,true);      // Load HltTree

  TTree         *muon_tree_2010;                             // Hold HLTMuTree
  TTree         *open_tree_2010;                             // Hold HltTree
  MUTREE        *muTree_2010 = new MUTREE;

  // 2011 datafile
  TCastorFile   *input_2011 = new TCastorFile(data2011.c_str());
  FriendMuTree  *mutree_2011 = new FriendMuTree(input_2011,true); // Load HLTMuTree
  HltTree       *ohTree_2011 = new HltTree(input_2011,true);      // Load HltTree

  TTree         *muon_tree_2011;                             // Hold HLTMuTree
  TTree         *open_tree_2011;                             // Hold HltTree
  MUTREE        *muTree_2011 = new MUTREE;


  const unsigned int ntrig = triglist.size();
  int trig_2010[ntrig];                                // Trigger bits for muons
  int trig_2011[ntrig];                                // Trigger bits for muons
  open_tree_2010 = ohTree_2010->fChain;                           // Get TTree for trigger bits
  open_tree_2011 = ohTree_2011->fChain;                           // Get TTree for trigger bits
  for (unsigned int i=0; i < ntrig; i++) {
    string tmptrig = triglist[i];
    open_tree_2010->SetBranchAddress(tmptrig.c_str(),&trig_2010[i]);    // SetBranchAddress for trigger bits
    open_tree_2011->SetBranchAddress(tmptrig.c_str(),&trig_2011[i]);    // SetBranchAddress for trigger bits
  }

  muon_tree_2010 = mutree_2010->fChain;                           // Get TTree for muon objects
  muon_tree_2010->SetBranchAddress("Run",&muTree_2010->run);
  muon_tree_2010->SetBranchAddress("Event",&muTree_2010->event);
  muon_tree_2011 = mutree_2011->fChain;                           // Get TTree for muon objects
  muon_tree_2011->SetBranchAddress("Run",&muTree_2011->run);
  muon_tree_2011->SetBranchAddress("Event",&muTree_2011->event);
  if (flag->doSta && !flag->doGlb) {
   muon_tree_2010->SetBranchAddress("Sta_eta",muTree_2010->eta);
   muon_tree_2010->SetBranchAddress("Sta_pt",muTree_2010->pt);
   muon_tree_2010->SetBranchAddress("Sta_phi",muTree_2010->phi);
   muon_tree_2010->SetBranchAddress("Sta_nptl",&muTree_2010->nptl);
   muon_tree_2010->SetBranchAddress("Sta_charge",muTree_2010->charge);
   muon_tree_2011->SetBranchAddress("Sta_eta",muTree_2011->eta);
   muon_tree_2011->SetBranchAddress("Sta_pt",muTree_2011->pt);
   muon_tree_2011->SetBranchAddress("Sta_phi",muTree_2011->phi);
   muon_tree_2011->SetBranchAddress("Sta_nptl",&muTree_2011->nptl);
   muon_tree_2011->SetBranchAddress("Sta_charge",muTree_2011->charge);
  } else if (flag->doGlb && !flag->doSta) {
   muon_tree_2011->SetBranchAddress("Glb_eta",muTree_2011->eta);
   muon_tree_2011->SetBranchAddress("Glb_pt",muTree_2011->pt);
   muon_tree_2011->SetBranchAddress("Glb_phi",muTree_2011->phi);
   muon_tree_2011->SetBranchAddress("Glb_nptl",&muTree_2011->nptl);
   muon_tree_2011->SetBranchAddress("Glb_charge",muTree_2011->charge);
   muon_tree_2011->SetBranchAddress("Glb_nValMuHits",muTree_2011->nValMuHits);
   muon_tree_2011->SetBranchAddress("Glb_nValTrkHits",muTree_2011->nValTrkHits);
   muon_tree_2011->SetBranchAddress("Glb_nTrkFound",muTree_2011->nTrkFound);
   muon_tree_2011->SetBranchAddress("Glb_glbChi2_ndof",muTree_2011->glbChi2_ndof);
   muon_tree_2011->SetBranchAddress("Glb_trkChi2_ndof",muTree_2011->trkChi2_ndof);
   muon_tree_2011->SetBranchAddress("Glb_pixLayerWMeas",muTree_2011->pixLayerWMeas);
   muon_tree_2011->SetBranchAddress("Glb_trkDxy",muTree_2011->trkDxy);
   muon_tree_2011->SetBranchAddress("Glb_trkDz",muTree_2011->trkDz);

   muon_tree_2010->SetBranchAddress("Glb_eta",muTree_2010->eta);
   muon_tree_2010->SetBranchAddress("Glb_pt",muTree_2010->pt);
   muon_tree_2010->SetBranchAddress("Glb_phi",muTree_2010->phi);
   muon_tree_2010->SetBranchAddress("Glb_nptl",&muTree_2010->nptl);
   muon_tree_2010->SetBranchAddress("Glb_charge",muTree_2010->charge);
   muon_tree_2010->SetBranchAddress("Glb_nValMuHits",muTree_2010->nValMuHits);
   muon_tree_2010->SetBranchAddress("Glb_nValTrkHits",muTree_2010->nValTrkHits);
   muon_tree_2010->SetBranchAddress("Glb_nTrkFound",muTree_2010->nTrkFound);
   muon_tree_2010->SetBranchAddress("Glb_glbChi2_ndof",muTree_2010->glbChi2_ndof);
   muon_tree_2010->SetBranchAddress("Glb_trkChi2_ndof",muTree_2010->trkChi2_ndof);
   muon_tree_2010->SetBranchAddress("Glb_pixLayerWMeas",muTree_2010->pixLayerWMeas);
   muon_tree_2010->SetBranchAddress("Glb_trkDxy",muTree_2010->trkDxy);
   muon_tree_2010->SetBranchAddress("Glb_trkDz",muTree_2010->trkDz);
  } else {
    cout << "Choose doSta or doGlb or doGen!\n";
    return -1;
  }


  // Loop over trees over 2010 trees
  for (int i=0; i<muon_tree_2010->GetEntries(); i++) {
    muon_tree_2010->GetEntry(i);
    ohTree_2010->GetEntry(i);
    open_tree_2010->GetEntry(i);

    ////////// Check muon trigger list
    flag->trig = false;
    for (unsigned int tidx=0; tidx<ntrig; tidx++) {
      if (trig_2010[tidx]) {         // At least one of the muon trigger is fired.
        flag->trig = true;
        break;
      }
    }
    if (!flag->trig) continue;  // If no muon triggers fired, go to the next event!
    
    ////////// Load muons and fill up histograms
    for (int a=0; a < muTree_2010->nptl; a++) {
      if (flag->doGlb) {
        if(!isValidMu(flag, muTree_2010, a)) continue;    //Check glb muons are within acceptance range
      } else if (flag->doSta) {
        if(!isMuInAcc(flag, muTree_2010->eta[a], muTree_2010->pt[a])) continue;    //Check sta muons are within acceptance range
      }
      
      SingleGlb_Etapt_2010->Fill(muTree_2010->eta[a],muTree_2010->pt[a]);

    }

    if (i%10000 ==0)
    cout << "Event in 2010 datasets: " << i+1 << endl;
  }

  // Loop over trees over 2011 trees
  for (int i=0; i<muon_tree_2011->GetEntries(); i++) {
    muon_tree_2011->GetEntry(i);
    ohTree_2011->GetEntry(i);
    open_tree_2011->GetEntry(i);

    ////////// Check muon trigger list
    flag->trig = false;
    for (unsigned int tidx=0; tidx<ntrig; tidx++) {
      if (trig_2011[tidx]) {         // At least one of the muon trigger is fired.
        flag->trig = true;
        break;
      }
    }
    if (!flag->trig) continue;  // If no muon triggers fired, go to the next event!
    
    ////////// Load muons and fill up histograms
    for (int a=0; a < muTree_2011->nptl; a++) {
      if (flag->doGlb) {
        if(!isValidMu(flag, muTree_2011, a)) continue;    //Check glb muons are within acceptance range
      } else if (flag->doSta) {
        if(!isMuInAcc(flag, muTree_2011->eta[a], muTree_2011->pt[a])) continue;    //Check sta muons are within acceptance range
      }
      
      SingleGlb_Etapt_2011->Fill(muTree_2011->eta[a],muTree_2011->pt[a]);

    }

    if (i%10000 ==0)
    cout << "Event in 2011 datasets: " << i+1 << endl;

  }

  // Draw final histograms and save it into .png files
  gROOT->Macro("~miheejo/public/HIMuTrig/JpsiStyle.C");    //For plot style
  TCanvas *canv = new TCanvas("canv","canv",800,600);
  canv->Draw();
  SingleGlb_Etapt_2010->Draw("colz");
  canv->SaveAs("SingleGlb_Etapt_2010.png");
  canv->Clear();  canv->Draw();
  SingleGlb_Etapt_2011->Draw("colz");
  canv->SaveAs("SingleGlb_Etapt_2011.png");

  return 0;
}
int main( int argc, char* argv[] ) {

  DrawTools::setStyle();

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

  NORDERS = 6;
  if( argc>2 ) {
    NORDERS = atoi(argv[2]);
    std::cout << "-> NORDER is set to: " << NORDERS << std::endl;
  }


  std::string fileName = "../PositionAnalysis/data/run_" + runName + ".root";
  TFile* file = TFile::Open(fileName.c_str());
  
  
  if( argc>1 ) {
    std::string runName_str(argv[1]);
    runName = runName_str;
  }
  if( file==0 ) {
    std::cout << "ERROR! Din't find file " << fileName << std::endl;
    std::cout << "Exiting." << std::endl;
    exit(11);
  }
  
  TTree* tree = (TTree*)file->Get("eventRawData");
  UInt_t evtNumber;
  tree->SetBranchAddress( "evtNumber", &evtNumber );
  UInt_t adcData[40];
  tree->SetBranchAddress( "adcData", adcData );
  UInt_t adcBoard[40];
  tree->SetBranchAddress( "adcBoard", adcBoard );
  UInt_t adcChannel[40];
  tree->SetBranchAddress( "adcChannel", adcChannel );
  
  int nentries = tree->GetEntries();

  std::string outfileName = "calibAn_" + runName + ".root";
  TFile* outFile = TFile::Open( outfileName.c_str(), "RECREATE" );

  TH1D* h1_cef3_0   = new TH1D("cef3_0",   "", 400, 0., 400.);
  TH1D* h1_cef3_1   = new TH1D("cef3_1",   "", 400, 0., 400.);
  TH1D* h1_cef3_2   = new TH1D("cef3_2",   "", 400, 0., 400.);
  TH1D* h1_cef3_3   = new TH1D("cef3_3",   "", 400, 0., 400.);
  TH1D* h1_cef3_tot = new TH1D("cef3_tot", "", 400, 0., 4.*400.);

  TH1D* h1_cef3_corr_0   = new TH1D("cef3_corr_0",   "", 400, 0., 400.);
  TH1D* h1_cef3_corr_1   = new TH1D("cef3_corr_1",   "", 385, 0., 400.4);
  TH1D* h1_cef3_corr_2   = new TH1D("cef3_corr_2",   "", 400, 0., 404.);
  TH1D* h1_cef3_corr_3   = new TH1D("cef3_corr_3",   "", 400, 0., 400.);
  TH1D* h1_cef3_corr_tot = new TH1D("cef3_corr_tot", "", 400, 0., 4.*400.);

  TH1D* h1_cef3_pedSubtracted_0   = new TH1D("cef3_pedSubtracted_0",   "", 400, 0., 400.);
  TH1D* h1_cef3_pedSubtracted_1   = new TH1D("cef3_pedSubtracted_1",   "", 400, 0., 400.);
  TH1D* h1_cef3_pedSubtracted_2   = new TH1D("cef3_pedSubtracted_2",   "", 400, 0., 400.);
  TH1D* h1_cef3_pedSubtracted_3   = new TH1D("cef3_pedSubtracted_3",   "", 400, 0., 400.);

  TH1D* h1_cef3_pedSubtracted_corr_0   = new TH1D("cef3_pedSubtracted_corr_0",   "", 400, 0., 400.*1.11228);
  TH1D* h1_cef3_pedSubtracted_corr_1   = new TH1D("cef3_pedSubtracted_corr_1",   "", 400, 0., 400.*0.855333);
  TH1D* h1_cef3_pedSubtracted_corr_2   = new TH1D("cef3_pedSubtracted_corr_2",   "", 400, 0., 400.*0.97973);
  TH1D* h1_cef3_pedSubtracted_corr_3   = new TH1D("cef3_pedSubtracted_corr_3",   "", 400, 0., 400.*1.08781); 

  TH1D* h1_cef3_pedSubtracted_corr_sum   = new TH1D("cef3_pedSubtracted_sum",   "", 400, 0., 400.);
  TH1D* h1_cef3_pedSubtracted_corr_sum_dummy   = new TH1D("cef3_pedSubtracted_sum",   "", 400, 0., 400.);

  TH1D* h1_cef3_pedSubtracted_corr_rebin_0   = new TH1D("cef3_pedSubtracted_corr_rebin_0",   "", 200, 0., 400.*1.11228);
  TH1D* h1_cef3_pedSubtracted_corr_rebin_1   = new TH1D("cef3_pedSubtracted_corr_rebin_1",   "", 200, 0., 400.*0.855333);
  TH1D* h1_cef3_pedSubtracted_corr_rebin_2   = new TH1D("cef3_pedSubtracted_corr_rebin_2",   "", 200, 0., 400.*0.97973);
  TH1D* h1_cef3_pedSubtracted_corr_rebin_3   = new TH1D("cef3_pedSubtracted_corr_rebin_3",   "", 200, 0., 400.*1.08781);



  TH1D* h1_cef3_pedSubtracted_corr_muQ_0   = new TH1D("cef3_pedSubtracted_corr_muQ_0",   "", 400, 0., 400.*1.19514);
  TH1D* h1_cef3_pedSubtracted_corr_muQ_1   = new TH1D("cef3_pedSubtracted_corr_muQ_1",   "", 400, 0., 400.*0.860177);
  TH1D* h1_cef3_pedSubtracted_corr_muQ_2   = new TH1D("cef3_pedSubtracted_corr_muQ_2",   "", 400, 0., 400.*0.952363);
  TH1D* h1_cef3_pedSubtracted_corr_muQ_3   = new TH1D("cef3_pedSubtracted_corr_muQ_3",   "", 400, 0., 400.*0.977169);

  TH1D* h1_cef3_pedSubtracted_corr_muMean_0   = new TH1D("cef3_pedSubtracted_corr_muMean_0",   "", 400, 0., 400.*1.09716);
  TH1D* h1_cef3_pedSubtracted_corr_muMean_1   = new TH1D("cef3_pedSubtracted_corr_muMean_1",   "", 400, 0., 400.*0.843707);
  TH1D* h1_cef3_pedSubtracted_corr_muMean_2   = new TH1D("cef3_pedSubtracted_corr_muMean_2",   "", 400, 0., 400.*0.966413);
  TH1D* h1_cef3_pedSubtracted_corr_muMean_3   = new TH1D("cef3_pedSubtracted_corr_muMean_3",   "", 400, 0., 400.*1.07241);


  // there is only one cosmic run
  unsigned int runNumber_;
  runNumber_=91;  


  std::string pedestalFileName = "../PositionAnalysis/pedestalFile.root";
  std::vector<std::pair<float, float> > pedestals = getPedestals( "cef3", pedestalFileName, runNumber_ );
  std::cout << std::endl;
  std::cout << "-> Got pedestals of CeF3: " << std::endl;
  for( unsigned i=0; i<CEF3_CHANNELS; ++i )
    std::cout << " CeF3 Channel " << i << ": " << pedestals[i].first << " (+- " << pedestals[i].second << ")" << std::endl;
  std::cout << std::endl;


  int nSigma=4;  

  for( unsigned iEntry=0; iEntry<nentries; ++iEntry ) {
    
    tree->GetEntry(iEntry);
    
    if( iEntry % 5000 == 0 ) std::cout << "Entry: " << iEntry << " / " << nentries << std::endl;
    
    for( unsigned i=0; i<40; ++i ) {
      
      int board  = adcBoard[i];
      int channel= adcChannel[i];
      
      float cef3=0;
      
      
      if( board==CEF3_ADC_BOARD ) {
	if( channel==(CEF3_ADC_START_CHANNEL  ) ){
	  h1_cef3_0->Fill(adcData[i]);
	  cef3+=adcData[i];
	  if(adcData[i]>(pedestals[0].first + nSigma*pedestals[0].second)) h1_cef3_pedSubtracted_0->Fill(adcData[i]-pedestals[0].first);
	}
        else if( channel==(CEF3_ADC_START_CHANNEL+1) ){
	  h1_cef3_1->Fill(adcData[i]);
	  cef3+=adcData[i];
	  if(adcData[i]>(pedestals[1].first + nSigma*pedestals[1].second))h1_cef3_pedSubtracted_1->Fill(adcData[i]-pedestals[1].first);
	}
        else if( channel==(CEF3_ADC_START_CHANNEL+2) ) {
	  h1_cef3_2->Fill(adcData[i]);
	  cef3+=adcData[i];
	  if(adcData[i]>(pedestals[2].first + nSigma*pedestals[2].second))h1_cef3_pedSubtracted_2->Fill(adcData[i]-pedestals[2].first);
	}
        else if( channel==(CEF3_ADC_START_CHANNEL+3) ) {
	  h1_cef3_3->Fill(adcData[i]);
	  cef3+=adcData[i];
	  if(adcData[i]>(pedestals[3].first + nSigma*pedestals[3].second))h1_cef3_pedSubtracted_3->Fill(adcData[i]-pedestals[3].first);
	}
	h1_cef3_tot->Fill(cef3);
      }
      
    }
  }




  h1_cef3_0->SetLineWidth(2);
  h1_cef3_1->SetLineWidth(2);
  h1_cef3_2->SetLineWidth(2);
  h1_cef3_3->SetLineWidth(2);

  h1_cef3_0->SetLineColor(kBlack);
  h1_cef3_1->SetLineColor(kRed);
  h1_cef3_2->SetLineColor(kBlue);
  h1_cef3_3->SetLineColor(kMagenta);

  h1_cef3_corr_0->SetLineWidth(2);
  h1_cef3_corr_1->SetLineWidth(2);
  h1_cef3_corr_2->SetLineWidth(2);
  h1_cef3_corr_3->SetLineWidth(2);

  h1_cef3_corr_0->SetLineColor(kBlack);
  h1_cef3_corr_1->SetLineColor(kRed);
  h1_cef3_corr_2->SetLineColor(kBlue);
  h1_cef3_corr_3->SetLineColor(kMagenta);

  h1_cef3_pedSubtracted_0->SetLineWidth(2);
  h1_cef3_pedSubtracted_1->SetLineWidth(2);
  h1_cef3_pedSubtracted_2->SetLineWidth(2);
  h1_cef3_pedSubtracted_3->SetLineWidth(2);

  h1_cef3_pedSubtracted_0->SetLineColor(kBlack);
  h1_cef3_pedSubtracted_1->SetLineColor(kRed);
  h1_cef3_pedSubtracted_2->SetLineColor(kBlue);
  h1_cef3_pedSubtracted_3->SetLineColor(kMagenta);

  h1_cef3_pedSubtracted_corr_0->SetLineWidth(2);
  h1_cef3_pedSubtracted_corr_1->SetLineWidth(2);
  h1_cef3_pedSubtracted_corr_2->SetLineWidth(2);
  h1_cef3_pedSubtracted_corr_3->SetLineWidth(2);

  h1_cef3_pedSubtracted_corr_0->SetLineColor(kBlack);
  h1_cef3_pedSubtracted_corr_1->SetLineColor(kRed);
  h1_cef3_pedSubtracted_corr_2->SetLineColor(kBlue);
  h1_cef3_pedSubtracted_corr_3->SetLineColor(kMagenta);

  h1_cef3_pedSubtracted_corr_muQ_0->SetLineWidth(2);
  h1_cef3_pedSubtracted_corr_muQ_1->SetLineWidth(2);
  h1_cef3_pedSubtracted_corr_muQ_2->SetLineWidth(2);
  h1_cef3_pedSubtracted_corr_muQ_3->SetLineWidth(2);
			     
  h1_cef3_pedSubtracted_corr_muQ_0->SetLineColor(kBlack);
  h1_cef3_pedSubtracted_corr_muQ_1->SetLineColor(kRed);
  h1_cef3_pedSubtracted_corr_muQ_2->SetLineColor(kBlue);
  h1_cef3_pedSubtracted_corr_muQ_3->SetLineColor(kMagenta);

  h1_cef3_pedSubtracted_corr_muMean_0->SetLineWidth(2);
  h1_cef3_pedSubtracted_corr_muMean_1->SetLineWidth(2);
  h1_cef3_pedSubtracted_corr_muMean_2->SetLineWidth(2);
  h1_cef3_pedSubtracted_corr_muMean_3->SetLineWidth(2);
			     
  h1_cef3_pedSubtracted_corr_muMean_0->SetLineColor(kBlack);
  h1_cef3_pedSubtracted_corr_muMean_1->SetLineColor(kRed);
  h1_cef3_pedSubtracted_corr_muMean_2->SetLineColor(kBlue);
  h1_cef3_pedSubtracted_corr_muMean_3->SetLineColor(kMagenta);


  //plot uncorr energy (before intercalibration)
  TCanvas* cuncorr = new TCanvas( "cuncorr", "", 600, 600 );



  cuncorr->cd();
  cuncorr->SetLogy();

  TH1D* histo_axes = new TH1D("cef3_0",   "", 400, 0., 350.);


  histo_axes->GetXaxis()->SetRangeUser(80.,350.);
  histo_axes->GetYaxis()->SetRangeUser(10.,h1_cef3_0->GetMaximum()+h1_cef3_0->GetMaximum()*0.10);
  histo_axes->SetXTitle( "ADC Counts" );
  histo_axes->Draw();

  TLegend* legend = new TLegend( 0.7, 0.7, 0.90, 0.9 );
  legend->SetLineColor(0);
  legend->SetFillColor(0);
  legend->SetFillStyle(0);
  legend->SetTextSize(0.038);
  legend->AddEntry( h1_cef3_0, "channel 0", "L" );
  legend->AddEntry( h1_cef3_1, "channel 1", "L" );
  legend->AddEntry( h1_cef3_2, "channel 2", "L" );
  legend->AddEntry( h1_cef3_3, "channel 3", "L" );
  legend->Draw("same");


  h1_cef3_0->Draw("same");
  h1_cef3_1->Draw("same");
  h1_cef3_2->Draw("same");
  h1_cef3_3->Draw("same");

  cuncorr->SaveAs("uncorrEnergyAllChannels.png");
  cuncorr->SaveAs("uncorrEnergyAllChannels.eps");

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

  cuncorr_2->cd();
  cuncorr_2->SetLogy();

  histo_axes->GetXaxis()->SetRangeUser(120.,200.);
  histo_axes->GetYaxis()->SetRangeUser(10.,h1_cef3_0->GetMaximum()+h1_cef3_0->GetMaximum()*0.10);
  histo_axes->SetXTitle( "ADC Counts" );
  histo_axes->Draw();


  h1_cef3_0->Draw("same");
  h1_cef3_1->Draw("same");
  h1_cef3_2->Draw("same");
  h1_cef3_3->Draw("same");

  legend->Draw("same");

  cuncorr_2->SaveAs("uncorrEnergyAllChannels_zoom.png");
  cuncorr_2->SaveAs("uncorrEnergyAllChannels_zoom.eps");

  //plot uncorr energy (before intercalibration) for pedSubtracted
  TCanvas* cuncorr_pedSubtracted = new TCanvas( "cuncorr_pedSubtracted", "", 600, 600 );


  cuncorr_pedSubtracted->cd();
  cuncorr_pedSubtracted->SetLogy();


  histo_axes->GetXaxis()->SetRangeUser(0.,250.);
  histo_axes->GetYaxis()->SetRangeUser(10.,h1_cef3_pedSubtracted_0->GetMaximum()+h1_cef3_pedSubtracted_0->GetMaximum()*0.10);
  histo_axes->SetXTitle( "ADC Counts" );
  histo_axes->Draw();

  legend->Draw("same");


  h1_cef3_pedSubtracted_0->Draw("same");
  h1_cef3_pedSubtracted_1->Draw("same");
  h1_cef3_pedSubtracted_2->Draw("same");
  h1_cef3_pedSubtracted_3->Draw("same");

  cuncorr_pedSubtracted->SaveAs("uncorrEnergyAllChannelspedSubtracted.png");
  cuncorr_pedSubtracted->SaveAs("uncorrEnergyAllChannelspedSubtracted.eps");


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

  cuncorr_pedSubtracted_2->cd();
  cuncorr_pedSubtracted_2->SetLogy();

  histo_axes->GetXaxis()->SetRangeUser(20.,100.);
  histo_axes->GetYaxis()->SetRangeUser(10.,h1_cef3_pedSubtracted_0->GetMaximum()+h1_cef3_pedSubtracted_0->GetMaximum()*0.10);
  histo_axes->SetXTitle( "ADC Counts" );
  histo_axes->Draw();


  h1_cef3_pedSubtracted_0->Draw("same");
  h1_cef3_pedSubtracted_1->Draw("same");
  h1_cef3_pedSubtracted_2->Draw("same");
  h1_cef3_pedSubtracted_3->Draw("same");

  legend->Draw("same");

  cuncorr_pedSubtracted_2->SaveAs("uncorrEnergyAllChannelspedSubtracted_zoom.png");
  cuncorr_pedSubtracted_2->SaveAs("uncorrEnergyAllChannelspedSubtracted_zoom.eps");



  //intercalibration of single fibers with photoelectrons
  FitResults fr_0 = fitSingleHisto( h1_cef3_0, 110., 135., 138., 185. );
  FitResults fr_1 = fitSingleHisto( h1_cef3_1, 100., 125., 125., 190. );
  FitResults fr_2 = fitSingleHisto( h1_cef3_2, 100., 125., 128., 190. );
  FitResults fr_3 = fitSingleHisto( h1_cef3_3, 100., 125., 137., 198. );

  std::vector<float> lowerFitBoundary;
  lowerFitBoundary.push_back(137.);
  lowerFitBoundary.push_back(125.);
  lowerFitBoundary.push_back(127.);
  lowerFitBoundary.push_back(137.);

  

  FitResults fr_pedSubtracted_0 = fitSingleHisto( h1_cef3_pedSubtracted_0, 0., 0., lowerFitBoundary[0]-pedestals[0].first, 185.-pedestals[0].first );
  FitResults fr_pedSubtracted_1 = fitSingleHisto( h1_cef3_pedSubtracted_1, 0., 0., lowerFitBoundary[1]-pedestals[1].first, 190.-pedestals[1].first );
  FitResults fr_pedSubtracted_2 = fitSingleHisto( h1_cef3_pedSubtracted_2, 0., 0., lowerFitBoundary[2]-pedestals[2].first, 190.-pedestals[2].first );
  FitResults fr_pedSubtracted_3 = fitSingleHisto( h1_cef3_pedSubtracted_3, 0., 0., lowerFitBoundary[3]-pedestals[3].first, 198.-pedestals[3].first );


  std::vector<float> correctionFactors = intercalibrateFibers(fr_0,fr_1,fr_2,fr_3,true);
  std::vector<float> correctionFactors_pedSubtracted = intercalibrateFibers(fr_pedSubtracted_0,fr_pedSubtracted_1,fr_pedSubtracted_2,fr_pedSubtracted_3,true);
  std::vector<float> correctionFactors_pedSubtracted_muQ = intercalibrateFibers(fr_pedSubtracted_0,fr_pedSubtracted_1,fr_pedSubtracted_2,fr_pedSubtracted_3,false);

  std::vector<float> mu;
  mu.push_back(fr_0.mu);
  mu.push_back(fr_1.mu);
  mu.push_back(fr_2.mu);
  mu.push_back(fr_3.mu);
  float mumean=0.;


  for(int i=0;i<4;i++){
    mumean+=mu[i];
  }

  mumean=mumean/4.;

  std::vector<float> correctionFactors_pedSubtracted_muMean= intercalibrateFibers(fr_pedSubtracted_0,fr_pedSubtracted_1,fr_pedSubtracted_2,fr_pedSubtracted_3,false,mumean);

  for(int i=0;i<4;i++){
    std::cout<<"correctionFactors "<<correctionFactors[i]<<std::endl;
    std::cout<<"correctionFactors pedSub "<<correctionFactors_pedSubtracted[i]<<std::endl;
    std::cout<<"correctionFactors pedSub muQ "<<correctionFactors_pedSubtracted_muQ[i]<<std::endl;
    std::cout<<"correctionFactors pedSub muMean "<<correctionFactors_pedSubtracted_muMean[i]<<std::endl;
  }
  TRandom a;
  a.SetSeed(100);

  for( unsigned iEntry=0; iEntry<nentries; ++iEntry ) {
    
    tree->GetEntry(iEntry);
    
    if( iEntry % 5000 == 0 ) std::cout << "Entry: " << iEntry << " / " << nentries << std::endl;
    
    for( unsigned i=0; i<40; ++i ) {
      
      int board  = adcBoard[i];
      int channel= adcChannel[i];
      
      
      float cef3_corr=0;

      
      if( board==CEF3_ADC_BOARD ) {
	if( channel==(CEF3_ADC_START_CHANNEL  ) ){
	  h1_cef3_corr_0->Fill(adcData[i]*correctionFactors[0]);
	  if(adcData[i]>(pedestals[0].first + nSigma*pedestals[0].second)){
	    h1_cef3_pedSubtracted_corr_0->Fill((adcData[i]-pedestals[0].first)*correctionFactors_pedSubtracted[0]);
	    h1_cef3_pedSubtracted_corr_rebin_0->Fill((adcData[i]-pedestals[0].first)*correctionFactors_pedSubtracted[0]);
	    h1_cef3_pedSubtracted_corr_muQ_0->Fill((adcData[i]-pedestals[0].first)*correctionFactors_pedSubtracted_muQ[0]);
	    h1_cef3_pedSubtracted_corr_muMean_0->Fill((adcData[i]-pedestals[0].first)*correctionFactors_pedSubtracted_muMean[0]);
	    h1_cef3_pedSubtracted_corr_sum->Fill(a.Uniform(adcData[i]-pedestals[0].first-0.5,adcData[i]-pedestals[0].first+0.5)*correctionFactors_pedSubtracted[0]);
	  }
	  cef3_corr+=adcData[i]*correctionFactors[0];
	}
        else if( channel==(CEF3_ADC_START_CHANNEL+1) ){
	  h1_cef3_corr_1->Fill(adcData[i]*correctionFactors[1]);
	  if(adcData[i]>(pedestals[1].first + nSigma*pedestals[1].second)) {
	    h1_cef3_pedSubtracted_corr_1->Fill((adcData[i]-pedestals[1].first)*correctionFactors_pedSubtracted[1]);
	    h1_cef3_pedSubtracted_corr_rebin_1->Fill((adcData[i]-pedestals[1].first)*correctionFactors_pedSubtracted[1]);
	    h1_cef3_pedSubtracted_corr_muQ_1->Fill((adcData[i]-pedestals[1].first)*correctionFactors_pedSubtracted_muQ[1]);
	    h1_cef3_pedSubtracted_corr_muMean_1->Fill((adcData[i]-pedestals[1].first)*correctionFactors_pedSubtracted_muMean[1]);
	    h1_cef3_pedSubtracted_corr_sum->Fill(a.Uniform(adcData[i]-pedestals[1].first-0.5,adcData[i]-pedestals[1].first+0.5)*correctionFactors_pedSubtracted[1]);
	  }
	  cef3_corr+=adcData[i]*correctionFactors[1];
	}
        else if( channel==(CEF3_ADC_START_CHANNEL+2) ) {
	  h1_cef3_corr_2->Fill(adcData[i]*correctionFactors[2]);
	  if(adcData[i]>(pedestals[2].first + nSigma*pedestals[2].second)) {
	    h1_cef3_pedSubtracted_corr_2->Fill((adcData[i]-pedestals[2].first)*correctionFactors_pedSubtracted[2]);
	    h1_cef3_pedSubtracted_corr_rebin_2->Fill((adcData[i]-pedestals[2].first)*correctionFactors_pedSubtracted[2]);
	    h1_cef3_pedSubtracted_corr_muQ_2->Fill((adcData[i]-pedestals[2].first)*correctionFactors_pedSubtracted_muQ[2]);
	    h1_cef3_pedSubtracted_corr_muMean_2->Fill((adcData[i]-pedestals[2].first)*correctionFactors_pedSubtracted_muMean[2]);
	    h1_cef3_pedSubtracted_corr_sum->Fill(a.Uniform(adcData[i]-pedestals[2].first-0.5,adcData[i]-pedestals[2].first+0.5)*correctionFactors_pedSubtracted[2]);
	  }
	  cef3_corr+=adcData[i]*correctionFactors[2];
	}
        else if( channel==(CEF3_ADC_START_CHANNEL+3) ) {
	  h1_cef3_corr_3->Fill(adcData[i]*correctionFactors[3]);
	  if(adcData[i]>(pedestals[3].first + nSigma*pedestals[3].second)){
	    h1_cef3_pedSubtracted_corr_3->Fill((adcData[i]-pedestals[3].first)*correctionFactors_pedSubtracted[3]);
	    h1_cef3_pedSubtracted_corr_rebin_3->Fill((adcData[i]-pedestals[3].first)*correctionFactors_pedSubtracted[3]);
	    h1_cef3_pedSubtracted_corr_muQ_3->Fill((adcData[i]-pedestals[3].first)*correctionFactors_pedSubtracted_muQ[3]);
	    h1_cef3_pedSubtracted_corr_muMean_3->Fill((adcData[i]-pedestals[3].first)*correctionFactors_pedSubtracted_muMean[3]);
	    h1_cef3_pedSubtracted_corr_sum->Fill(a.Uniform(adcData[i]-pedestals[3].first-0.5,adcData[i]-pedestals[3].first+0.5)*correctionFactors_pedSubtracted[3]);
	  }
	  cef3_corr+=adcData[i]*correctionFactors[3];
	}
	h1_cef3_tot->Fill(cef3_corr);
      }
      
    }
  }




  //plot corr energy (after intercalibration)
  TCanvas* ccorr = new TCanvas( "ccorr", "", 600, 600 );

  ccorr->cd();
  ccorr->SetLogy();

  TH2D* h2_axes_corr = new TH2D("axes_corr", "", 10, 0., 350., 10, 10., 1.1*h1_cef3_corr_0->GetMaximum() );
  h2_axes_corr->GetXaxis()->SetRangeUser(80.,350);
  h2_axes_corr->SetXTitle( "ADC Counts" );
  h2_axes_corr->Draw();


  h1_cef3_corr_0->Draw("same");
  h1_cef3_corr_1->Draw("same");
  h1_cef3_corr_2->Draw("same");
  h1_cef3_corr_3->Draw("same");

  legend->Draw("same");

  ccorr->SaveAs("corrEnergyAllChannels.png");
  ccorr->SaveAs("corrEnergyAllChannels.eps");

  //pedsubtracted plot
  ccorr->Clear();

  histo_axes->GetXaxis()->SetRangeUser(0.,250.);
  histo_axes->GetYaxis()->SetRangeUser(10.,h1_cef3_pedSubtracted_0->GetMaximum()+h1_cef3_pedSubtracted_0->GetMaximum()*0.10);
  histo_axes->SetXTitle( "ADC Counts" );
  histo_axes->Draw();

  histo_axes->Draw();

  h1_cef3_pedSubtracted_corr_0->Draw("same");
  h1_cef3_pedSubtracted_corr_1->Draw("same");
  h1_cef3_pedSubtracted_corr_2->Draw("same");
  h1_cef3_pedSubtracted_corr_3->Draw("same");

  legend->Draw("same");

  ccorr->SaveAs("corrEnergyAllChannelspedSubtracted.png");
  ccorr->SaveAs("corrEnergyAllChannelspedSubtracted.eps");

  h1_cef3_pedSubtracted_corr_sum->Rebin(2);
  FitResults fr_corr_sum = fitSingleHisto_sum( h1_cef3_pedSubtracted_corr_sum, 0., 0.,13.,68.,true );

  //plot for the paper. all corr channels sum and fit
  ccorr->Clear();
  ccorr->SetLogy(0);
  ccorr->cd();

  h1_cef3_pedSubtracted_corr_sum->SetLineWidth(2);
  
  h1_cef3_pedSubtracted_corr_sum->GetXaxis()->SetRangeUser(0.,150.);
  h1_cef3_pedSubtracted_corr_sum->GetYaxis()->SetRangeUser(50.,h1_cef3_pedSubtracted_corr_sum->GetMaximum()+h1_cef3_pedSubtracted_corr_sum->GetMaximum()*0.10);
  h1_cef3_pedSubtracted_corr_sum->SetYTitle( "Events / 2" );
  h1_cef3_pedSubtracted_corr_sum->SetXTitle( "ADC Counts" );

 
  h1_cef3_pedSubtracted_corr_sum->Draw();
  //  ccorr->SetLogy(1);
  TPaveText* labelTop = DrawTools::getLabelTop("Cosmic Data");
  labelTop->Draw("same");
  gPad->RedrawAxis(); 
  ccorr->SaveAs("sum_fitted.png");
  ccorr->SaveAs("sum_fitted.eps");
  ccorr->SaveAs("sum_fitted.C");
  //ccorr->SaveAs("sum_fitted_log.png");

  ccorr->Clear();
  h1_cef3_pedSubtracted_corr_sum->Draw();
  labelTop->Draw("same");
  ccorr->SetLogy(1);
  ccorr->SaveAs("sum_fitted_log.png");
  ccorr->SaveAs("sum_fitted_log.eps");
  ccorr->SaveAs("sum_fitted_log.C");


  //unconstrained fit
  FitResults fr_corr_unconstrained_sum = fitSingleHisto_sum( h1_cef3_pedSubtracted_corr_sum, 0., 0.,14.,69.,false );
  
  h1_cef3_pedSubtracted_corr_sum->GetXaxis()->SetRangeUser(0.,150.);
  h1_cef3_pedSubtracted_corr_sum->GetYaxis()->SetRangeUser(50.,h1_cef3_pedSubtracted_corr_sum->GetMaximum()+h1_cef3_pedSubtracted_corr_sum->GetMaximum()*0.10);
  h1_cef3_pedSubtracted_corr_sum->SetXTitle( "ADC Counts" );

 
  h1_cef3_pedSubtracted_corr_sum->Draw();
  ccorr->SetLogy(1);
  ccorr->SaveAs("sum_fitted_log_unc.png");

  ccorr->Clear();
  ccorr->cd();
  h1_cef3_pedSubtracted_corr_sum_dummy->Add(h1_cef3_pedSubtracted_corr_0);
  h1_cef3_pedSubtracted_corr_sum_dummy->Add(h1_cef3_pedSubtracted_corr_1);
  h1_cef3_pedSubtracted_corr_sum_dummy->Add(h1_cef3_pedSubtracted_corr_2);
  h1_cef3_pedSubtracted_corr_sum_dummy->Add(h1_cef3_pedSubtracted_corr_3);

  h1_cef3_pedSubtracted_corr_sum_dummy->Rebin(2);  
  FitResults fr_corr_sum_dummy = fitSingleHisto_sum( h1_cef3_pedSubtracted_corr_sum_dummy, 0., 0.,13.,68.,true );

  h1_cef3_pedSubtracted_corr_sum_dummy->GetXaxis()->SetRangeUser(0.,150.);
  h1_cef3_pedSubtracted_corr_sum_dummy->GetYaxis()->SetRangeUser(50.,h1_cef3_pedSubtracted_corr_sum->GetMaximum()+h1_cef3_pedSubtracted_corr_sum->GetMaximum()*0.10);
  h1_cef3_pedSubtracted_corr_sum_dummy->SetXTitle( "ADC Counts" );
  ccorr->SetLogy(0);

  h1_cef3_pedSubtracted_corr_sum_dummy->Draw();
  ccorr->SaveAs("sum_fitted_log_dummy.png");

  std::cout<<"######################## mean random:"<<h1_cef3_pedSubtracted_corr_sum->GetMean()<<"+-"<<h1_cef3_pedSubtracted_corr_sum->GetMeanError()<<std::endl;
  std::cout<<"######################## mean not random:"<<h1_cef3_pedSubtracted_corr_sum_dummy->GetMean()<<"+-"<<h1_cef3_pedSubtracted_corr_sum_dummy->GetMeanError()<<std::endl;


  cuncorr_pedSubtracted_2->Clear();
  cuncorr_pedSubtracted_2->cd();
  cuncorr_pedSubtracted_2->SetLogy();

  histo_axes->GetXaxis()->SetRangeUser(20.,100.);
  histo_axes->GetYaxis()->SetRangeUser(10.,h1_cef3_pedSubtracted_0->GetMaximum()+h1_cef3_pedSubtracted_0->GetMaximum()*0.10);
  histo_axes->SetXTitle( "ADC Counts" );
  histo_axes->Draw();


  h1_cef3_pedSubtracted_corr_0->Draw("same");
  h1_cef3_pedSubtracted_corr_1->Draw("same");
  h1_cef3_pedSubtracted_corr_2->Draw("same");
  h1_cef3_pedSubtracted_corr_3->Draw("same");

  legend->Draw("same");

  cuncorr_pedSubtracted_2->SaveAs("corrEnergyAllChannelspedSubtracted_zoom.png");
  cuncorr_pedSubtracted_2->SaveAs("corrEnergyAllChannelspedSubtracted_zoom.eps");


  //pedsubtracted plot
  ccorr->Clear();

  histo_axes->GetXaxis()->SetRangeUser(0.,250.);
  histo_axes->GetYaxis()->SetRangeUser(10.,h1_cef3_pedSubtracted_0->GetMaximum()+h1_cef3_pedSubtracted_0->GetMaximum()*0.10);
  histo_axes->SetXTitle( "ADC Counts" );
  histo_axes->Draw();

  histo_axes->Draw();

  h1_cef3_pedSubtracted_corr_muQ_0->Draw("same");
  h1_cef3_pedSubtracted_corr_muQ_1->Draw("same");
  h1_cef3_pedSubtracted_corr_muQ_2->Draw("same");
  h1_cef3_pedSubtracted_corr_muQ_3->Draw("same");

  legend->Draw("same");

  ccorr->SaveAs("corr_muQEnergyAllChannelspedSubtracted.png");
  ccorr->SaveAs("corr_muQEnergyAllChannelspedSubtracted.eps");

  cuncorr_pedSubtracted_2->Clear();
  cuncorr_pedSubtracted_2->cd();
  cuncorr_pedSubtracted_2->SetLogy();

  histo_axes->GetXaxis()->SetRangeUser(20.,100.);
  histo_axes->GetYaxis()->SetRangeUser(10.,h1_cef3_pedSubtracted_0->GetMaximum()+h1_cef3_pedSubtracted_0->GetMaximum()*0.10);
  histo_axes->SetXTitle( "ADC Counts" );
  histo_axes->Draw();


  h1_cef3_pedSubtracted_corr_muQ_0->Draw("same");
  h1_cef3_pedSubtracted_corr_muQ_1->Draw("same");
  h1_cef3_pedSubtracted_corr_muQ_2->Draw("same");
  h1_cef3_pedSubtracted_corr_muQ_3->Draw("same");

  legend->Draw("same");

  cuncorr_pedSubtracted_2->SaveAs("corr_muQEnergyAllChannelspedSubtracted_zoom.png");
  cuncorr_pedSubtracted_2->SaveAs("corr_muQEnergyAllChannelspedSubtracted_zoom.eps");

  //pedsubtracted muMean plot
  ccorr->Clear();

  histo_axes->GetXaxis()->SetRangeUser(0.,250.);
  histo_axes->GetYaxis()->SetRangeUser(10.,h1_cef3_pedSubtracted_0->GetMaximum()+h1_cef3_pedSubtracted_0->GetMaximum()*0.10);
  histo_axes->SetXTitle( "ADC Counts" );
  histo_axes->Draw();

  histo_axes->Draw();

  h1_cef3_pedSubtracted_corr_muMean_0->Draw("same");
  h1_cef3_pedSubtracted_corr_muMean_1->Draw("same");
  h1_cef3_pedSubtracted_corr_muMean_2->Draw("same");
  h1_cef3_pedSubtracted_corr_muMean_3->Draw("same");

  legend->Draw("same");

  ccorr->SaveAs("corr_muMeanEnergyAllChannelspedSubtracted.png");
  ccorr->SaveAs("corr_muMeanEnergyAllChannelspedSubtracted.eps");

  cuncorr_pedSubtracted_2->Clear();
  cuncorr_pedSubtracted_2->cd();
  cuncorr_pedSubtracted_2->SetLogy();

  histo_axes->GetXaxis()->SetRangeUser(20.,100.);
  histo_axes->GetYaxis()->SetRangeUser(10.,h1_cef3_pedSubtracted_0->GetMaximum()+h1_cef3_pedSubtracted_0->GetMaximum()*0.10);
  histo_axes->SetXTitle( "ADC Counts" );
  histo_axes->Draw();


  h1_cef3_pedSubtracted_corr_muMean_0->Draw("same");
  h1_cef3_pedSubtracted_corr_muMean_1->Draw("same");
  h1_cef3_pedSubtracted_corr_muMean_2->Draw("same");
  h1_cef3_pedSubtracted_corr_muMean_3->Draw("same");

  legend->Draw("same");

  cuncorr_pedSubtracted_2->SaveAs("corr_muMeanEnergyAllChannelspedSubtracted_zoom.png");
  cuncorr_pedSubtracted_2->SaveAs("corr_muMeanEnergyAllChannelspedSubtracted_zoom.eps");




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

  ccorr_2->cd();
  ccorr_2->SetLogy();

  h2_axes_corr->GetXaxis()->SetRangeUser(120.,200.);

  h2_axes_corr->Draw();
  h1_cef3_corr_0->Draw("same");
  h1_cef3_corr_1->Draw("same");
  h1_cef3_corr_2->Draw("same");
  h1_cef3_corr_3->Draw("same");

  legend->Draw("same");

  ccorr_2->SaveAs("corrEnergyAllChannels_zoom.png");
  ccorr_2->SaveAs("corrEnergyAllChannels_zoom.eps");


  //fit corrected histos
  FitResults fr_corr_0 = fitSingleHisto( h1_cef3_corr_0, 0.966779*120., 0.966779*130., 0.966779*138., 0.966779*185. );
  FitResults fr_corr_1 = fitSingleHisto( h1_cef3_corr_1, 1.04148*100., 1.04148*125., 1.04148*125., 1.04148*189. );
  FitResults fr_corr_2 = fitSingleHisto( h1_cef3_corr_2, 1.01311*100., 1.01311*125., 1.01311*128., 1.01311*189. );
  FitResults fr_corr_3 = fitSingleHisto( h1_cef3_corr_3, 0.984112*100., 0.984112*125., 0.984112*137., 0.984112*200. );

  FitResults fr_pedSubtracted_corr_0 = fitSingleHisto( h1_cef3_pedSubtracted_corr_0, 0., 0., lowerFitBoundary[0]+2-pedestals[0].first, 188.-pedestals[0].first );
  FitResults fr_pedSubtracted_corr_1 = fitSingleHisto( h1_cef3_pedSubtracted_corr_1, 0., 0., lowerFitBoundary[1]-3-pedestals[1].first, 182.-pedestals[1].first );
  FitResults fr_pedSubtracted_corr_2 = fitSingleHisto( h1_cef3_pedSubtracted_corr_2, 0., 0., lowerFitBoundary[2]+1-pedestals[2].first, 188.-pedestals[2].first );
  FitResults fr_pedSubtracted_corr_3 = fitSingleHisto( h1_cef3_pedSubtracted_corr_3, 0., 0., lowerFitBoundary[3]+1-pedestals[3].first, 198.-pedestals[3].first );



  FitResults fr_pedSubtracted_corr_rebin_0 = fitSingleHisto( h1_cef3_pedSubtracted_corr_rebin_0, 0., 0., lowerFitBoundary[0]+2-pedestals[0].first, 189.-pedestals[0].first );
  FitResults fr_pedSubtracted_corr_rebin_1 = fitSingleHisto( h1_cef3_pedSubtracted_corr_rebin_1, 0., 0., lowerFitBoundary[1]-3-pedestals[1].first, 177.-pedestals[1].first );
  FitResults fr_pedSubtracted_corr_rebin_2 = fitSingleHisto( h1_cef3_pedSubtracted_corr_rebin_2, 0., 0., lowerFitBoundary[2]+1-pedestals[2].first, 181.-pedestals[2].first );
  FitResults fr_pedSubtracted_corr_rebin_3 = fitSingleHisto( h1_cef3_pedSubtracted_corr_rebin_3, 0., 0., lowerFitBoundary[3]+1-pedestals[3].first, 196.-pedestals[3].first );





  h1_cef3_0->Write(); 
  h1_cef3_1->Write(); 
  h1_cef3_2->Write(); 
  h1_cef3_3->Write(); 
  h1_cef3_tot->Write(); 
                 
  h1_cef3_corr_0->Write();    
  h1_cef3_corr_1->Write();    
  h1_cef3_corr_2->Write();    
  h1_cef3_corr_3->Write();    
  h1_cef3_corr_tot->Write();  

  outFile->Write(); 


  doSummaryPlots(fr_pedSubtracted_0,fr_pedSubtracted_1,fr_pedSubtracted_2,fr_pedSubtracted_3,fr_pedSubtracted_corr_0,fr_pedSubtracted_corr_1,fr_pedSubtracted_corr_2,fr_pedSubtracted_corr_3);



  return 0;

}
Esempio n. 29
0
void Plots(TString plots="4Jets", TString sys="", bool EvtNorm=false){
  
  /****************
        Style
  ****************/
  gROOT->SetStyle("Plain");
  gStyle->SetOptFit(1000);
  gStyle->SetOptStat("emruo");
  gStyle->SetOptStat(kFALSE);
  gStyle->SetPadTickY(1);
  gStyle->SetPadTickX(1);
  
  gROOT->ProcessLine(".L /home/brochero/ttbar/TopCodeljets/tdrStyle.C");
  setTDRStyle();
  
  Int_t chatch = 1756;
  TColor *color = new TColor(chatch, 0.3, 0.5, 0.5, "", 0.45); // alpha = 0.5
  TString files  = dirnameIn + fl;  
  
  /****************
       Channel
  ****************/
  TString channel[3];
  channel[0] = "mujets";
  channel[1] = "ejets";  
  channel[2] = "lepjet"; 
  
 
  /****************
        Data
  ****************/ 
  std::vector<histos> DataMu;
  DataMu = loadhistograms(plots, files + "_DataSingleMu");
  std::vector<histos> DataEG;
  DataEG = loadhistograms(plots, files + "_DataSingleEG");
  std::vector<histos> Data;
  Data = addhistograms(DataMu, DataEG);
  setuphistograms(Data, kBlack);

  /****************
    ttbar Signal
  ****************/ 
  std::vector<histos> ttbar_0;
  ttbar_0 = loadhistograms(plots, files + "_ttbar-PowhegPythia");
  setuphistograms(ttbar_0, kRed+1);

  std::vector<histos> ttbar_1;
  ttbar_1 = loadhistograms(plots, files + "_ttbar-MCatNLO");
  setuphistograms(ttbar_1, kRed+2);

  std::vector<histos> ttbar_2;
  ttbar_2 = loadhistograms(plots, files + "_ttbar-Madgraph");
  setuphistograms(ttbar_2, kRed+3);

  /****************
       Z+Jets
  ****************/ 
  std::vector<histos> ZJets;
  ZJets = loadhistograms(plots, files + "_ZJets");
  setuphistograms(ZJets, kAzure-2);

  /****************
         VV
  ****************/ 
  std::vector<histos> WW;
  WW = loadhistograms(plots, files + "_WW");
  std::vector<histos> WZ;
  WZ = loadhistograms(plots, files + "_WZ");
  std::vector<histos> ZZ;
  ZZ = loadhistograms(plots, files + "_ZZ");
  std::vector<histos> VV;
  VV = addhistograms(WW, WZ);
  VV = addhistograms(VV, ZZ);
  setuphistograms(VV, kYellow-3);

  /****************
     Single Top
  ****************/ 
  std::vector<histos> tW;
  tW = loadhistograms(plots, files + "_tW");
  std::vector<histos> tbarW;
  tbarW = loadhistograms(plots, files + "_tbarW");
  std::vector<histos> t_tch;
  t_tch = loadhistograms(plots, files + "_t-tchannel");
  std::vector<histos> tbar_tch;
  tbar_tch = loadhistograms(plots, files + "_tbar-tchannel");
  std::vector<histos> Single_top;
  Single_top = addhistograms(tW, tbarW);
  Single_top = addhistograms(Single_top, t_tch);
  Single_top = addhistograms(Single_top, tbar_tch);
  setuphistograms(Single_top, kPink-3);

  /****************
       W+Jets
  ****************/ 
  std::vector<histos> WJets;
  WJets = loadhistograms(plots, files + "_WJets");
  setuphistograms(WJets, kGreen-3);

  /****************
     ttbar Bkg
  ****************/ 
  std::vector<histos> ttbar_bkg;
  ttbar_bkg = loadhistograms(plots, files + "_ttbar-PowhegPythiaBkg");
  setuphistograms(ttbar_bkg, kViolet-3);

  /****************
        QCD
  ****************/ 
  std::vector<histos> QCD;
  QCD = loadhistograms(plots, files + "_QCD-MuEnr");
  setuphistograms(QCD, kOrange-3);

  /****************
       Stacks
  ****************/ 
  std::vector<histos> Stack_bkg;
  std::vector<histos> Stack;
  histos st_bkg;
  histos st;
  for(unsigned int h=0; h<WJets.size(); h++){
    TString variable;
    for(int ch=0; ch<3; ch++){
      st.mc[ch]     = new THStack(variable, "");
      st_bkg.mc[ch] = new THStack(variable, "");
      st.mc[ch]->SetHistogram( (TH1F*)WJets[h].hist[ch]->Clone());
      st_bkg.mc[ch]->SetHistogram( (TH1F*)WJets[h].hist[ch]->Clone());
    }
    Stack.push_back(st);
    Stack_bkg.push_back(st_bkg);
  }
  
  //-------------------------------------------------------
  // Background Stack
  Stack_bkg = addstack(Stack_bkg, WJets);
  Stack_bkg = addstack(Stack_bkg, QCD);
  Stack_bkg = addstack(Stack_bkg, Single_top);
  Stack_bkg = addstack(Stack_bkg, VV);
  Stack_bkg = addstack(Stack_bkg, ttbar_bkg);
  Stack_bkg = addstack(Stack_bkg, ZJets);

  //-------------------------------------------------------
  // Stack
  Stack = addstack(Stack, WJets);
  Stack = addstack(Stack, QCD);
  Stack = addstack(Stack, Single_top);
  Stack = addstack(Stack, VV);
  Stack = addstack(Stack, ttbar_bkg);
  Stack = addstack(Stack, ZJets);
  Stack = addstack(Stack, ttbar_0);

  //-------------------------------------------------------
  // other ttbar Generators
  ttbar_1 = addhistograms(ttbar_1, Stack_bkg);
  ttbar_2 = addhistograms(ttbar_2, Stack_bkg);

  
  /****************
     Draw Histos
  ****************/ 
  TCanvas *histocanvas;
  histocanvas = new TCanvas("plots", "Plots");
  
  for(unsigned int h=0; h<WJets.size(); h++){
    for(int ch=0; ch<3; ch++){
      
      histocanvas->Divide(1,2);
      
      TPad    *pad[2];
      //Plot Pad
      pad[0] = (TPad*)histocanvas->GetPad(1);
      pad[0]->SetPad(0.01, 0.23, 0.99, 0.99);
      pad[0]->SetTopMargin(0.1);
      pad[0]->SetRightMargin(0.04);
      
      //Ratio Pad
      pad[1] = (TPad*)histocanvas->GetPad(2);
      pad[1]->SetPad(0.01, 0.02, 0.99, 0.3);
      gStyle->SetGridWidth(0.5);
      gStyle->SetGridColor(14);
      pad[1]->SetGridx();
      pad[1]->SetGridy();
      pad[1]->SetTopMargin(0.05);
      pad[1]->SetBottomMargin(0.4);
      pad[1]->SetRightMargin(0.04);
      
      //-------------------------------------------------------
      // Stack
      pad[0]->cd();

      Stack[h].mc[ch]->Draw("hist");

      Stack[h].mc[ch]->GetYaxis()->SetTitle("Events");
      Stack[h].mc[ch]->GetYaxis()->SetTitleOffset(1.2);
      Stack[h].mc[ch]->GetYaxis()->SetTitleSize(0.07);
      Stack[h].mc[ch]->GetYaxis()->SetLabelSize(0.055);
      Stack[h].mc[ch]->GetYaxis()->SetNdivisions(607);
      //Stack[h].mc[ch]->GetYaxis()->SetLabelSize(0.05);
      TGaxis *hYaxis = (TGaxis*)Stack[h].mc[ch]->GetYaxis();
      //hYaxis->SetMaxDigits(3);
      Stack[h].mc[ch]->GetXaxis()->SetLabelSize(0.0);
      Stack[h].mc[ch]->GetXaxis()->SetTitle("");

      float maxh = Data[h].hist[ch]->GetMaximum();
      if(maxh < Stack[h].mc[ch]->GetMaximum()) maxh = Stack[h].mc[ch]->GetMaximum();
      Stack[h].mc[ch]->SetMaximum(1.7*maxh);
      
      //-------------------------------------------------------
      // Band error
      TGraphErrors *thegraph = new TGraphErrors(Stack[h].hist[ch]);
      thegraph->SetName("thegraph");
      thegraph->SetFillStyle(1001);
      thegraph->SetFillColor(chatch);
      thegraph->SetLineColor(chatch);

      thegraph->Draw("e2SAME");

      //-------------------------------------------------------
      // Other ttbar generators
      ttbar_1[h].hist[ch]->SetLineColor(6);
      ttbar_1[h].hist[ch]->SetLineStyle(2);
      ttbar_1[h].hist[ch]->SetFillColor(0);
      ttbar_1[h].hist[ch]->Draw("histoSAME");

      ttbar_2[h].hist[ch]->SetLineColor(8);
      ttbar_2[h].hist[ch]->SetLineStyle(4);
      ttbar_2[h].hist[ch]->SetFillColor(0);
      ttbar_2[h].hist[ch]->Draw("histoSAME");
      //-------------------------------------------------------
      // Data Histogram
      Data[h].hist[ch]->SetMarkerStyle(20);
      Data[h].hist[ch]->SetMarkerSize(0.7);

      Data[h].hist[ch]->Draw("SAME");

      /***********************
             Legends
      ***********************/
      TLegend *leg;
      float legx1=0.76;
      float legy1=0.54;
      float legx2=0.90;
      float legy2=0.87;
      leg = new TLegend(legx1,legy1,legx2,legy2);
      leg->SetFillColor(0);
      leg->SetLineColor(1);
      leg->SetTextFont(62);
      leg->SetTextSize(0.03);

      leg->AddEntry(Data[h].hist[ch],"Data","PL");
      leg->AddEntry(ttbar_0[h].hist[ch],"t#bar{t} Signal","F");
      leg->AddEntry(ZJets[h].hist[ch],"Z+Jets","F");
      leg->AddEntry(ttbar_bkg[h].hist[ch],"t#bar{t} Bkg","F");
      leg->AddEntry(VV[h].hist[ch],"VV","F");
      leg->AddEntry(Single_top[h].hist[ch],"Single t","F");
      leg->AddEntry(QCD[h].hist[ch],"QCD","F");
      leg->AddEntry(WJets[h].hist[ch],"W+Jets","F");
      leg->AddEntry("thegraph","Uncertainty","F");
      leg->AddEntry((TObject*)0,"","");
      leg->AddEntry(ttbar_1[h].hist[ch],"MC@NLO","L");
      leg->AddEntry(ttbar_2[h].hist[ch],"Madgraph","L");

      leg->Draw("SAME");
      //-------------------------------------------------------
      // CMS
      TString htitleCMSChannel[3];
      htitleCMSChannel[0] = "#mu^{#pm}+jets channel";
      htitleCMSChannel[1] = "e^{#pm}+jets channel";
      htitleCMSChannel[2] = "l^{#pm}+jets channel";
      
      titlePr  = new TLatex(-20.,50.,"Preliminary");
      titlePr->SetNDC();
      titlePr->SetTextAlign(12);
      titlePr->SetX(0.25);
      titlePr->SetY(0.93);
      titlePr->SetTextColor(2);
      titlePr->SetTextFont(42);
      titlePr->SetTextSize(0.05);
      titlePr->SetTextSizePixels(24);
      titlePr->Draw("SAME");
      
      title  = new TLatex(-20.,50.,"CMS #sqrt{s} = 13TeV, L = 42 pb^{-1}(50ns)");
      title->SetNDC();
      title->SetTextAlign(12);
      title->SetX(0.20);
      title->SetY(0.83);
      title->SetTextFont(42);
      title->SetTextSize(0.05);
      title->SetTextSizePixels(24);
      title->Draw("SAME");
      
      chtitle  = new TLatex(-20.,50.,htitleCMSChannel[ch]);
      chtitle->SetNDC();
      chtitle->SetTextAlign(12);
      chtitle->SetX(0.20);
      chtitle->SetY(0.75);
      chtitle->SetTextFont(42);
      chtitle->SetTextSize(0.05);
      chtitle->SetTextSizePixels(24);
      chtitle->Draw("SAME");

      /***********************
               Ratio
      ***********************/    
      pad[1]->cd();
      
      //-------------------------------------------------------
      //Graph Ratio Clone
      TH1F *Ratio;
      Ratio = (TH1F*)Data[h].hist[ch]->Clone();
      Ratio->Divide(Stack[h].hist[ch]);

      TH1F *RatioSyst;
      RatioSyst = (TH1F*)Data[h].hist[ch]->Clone();
      RatioSyst->Divide(Stack[h].hist[ch]); // Should be the histogram with the Total Syst. Unc.
      std::vector<double> ratioContent;
      for(unsigned int b_r = 1; b_r <= RatioSyst->GetNbinsX(); b_r++){
	RatioSyst->SetBinContent(b_r,1.0);
	//RatioSyst->SetBinError(b_r,0.15); // Tempotal!!!
      }      

      Ratio->SetMarkerStyle(20);
      Ratio->SetMarkerSize(0.5);
      Ratio->SetMarkerColor(1);
      Ratio->SetLineColor(1);
      Ratio->SetLineWidth(1);
      Ratio->SetMaximum(2);
      Ratio->SetMinimum(0);
      Ratio->SetTitle("");
      
      Ratio->GetYaxis()->SetTitle("Obs/Exp");
      Ratio->GetYaxis()->CenterTitle();
      Ratio->GetYaxis()->SetTitleOffset(0.45);
      Ratio->GetYaxis()->SetTitleSize(0.16);
      Ratio->GetYaxis()->SetLabelSize(0.15);
      Ratio->GetYaxis()->SetNdivisions(402);
      Ratio->GetXaxis()->SetNdivisions(509);
      Ratio->GetXaxis()->SetTitleOffset(1.1);
      Ratio->GetXaxis()->SetLabelSize(0.20);
      Ratio->GetXaxis()->SetTitleSize(0.16);
      
      Ratio->SetMinimum(0.6);
      Ratio->SetMaximum(1.4);
      
      TGraphErrors *thegraphRatioSyst = new TGraphErrors(RatioSyst);
      thegraphRatioSyst->SetFillStyle(1001);
      thegraphRatioSyst->SetFillColor(chatch);
      thegraphRatioSyst->SetName("thegraphRatioSyst");
      
      //-------------------------------------------------------
      //Graph Ratio other ttbar generators
      TH1F *Ratio_1;
      Ratio_1 = (TH1F*)Data[h].hist[ch]->Clone();
      Ratio_1->Divide(ttbar_1[h].hist[ch]);
      Ratio_1->SetLineColor(6);
      Ratio_1->SetLineStyle(2);
      Ratio_1->SetLineWidth(2);
      Ratio_1->SetFillColor(0);

      TH1F *Ratio_2;
      Ratio_2 = (TH1F*)Data[h].hist[ch]->Clone();
      Ratio_2->Divide(ttbar_2[h].hist[ch]);
      Ratio_2->SetLineColor(8);
      Ratio_2->SetLineStyle(4);
      Ratio_2->SetLineWidth(2);
      Ratio_2->SetFillColor(0);

      //-------------------------------------------------------
      // Draw Ratios
      Ratio->Draw();
      thegraphRatioSyst->Draw("e2");
      Ratio->Draw("histpSAME");
      Ratio_1->Draw("histSAME");
      Ratio_2->Draw("histSAME");
            
      /***********************
            Save Histos
      ***********************/    
      TString dirfigname_pdf=dirnameIn + "figures_" + fl + "/pdf/";
      // make a dir if it does not exist!!
      gSystem->mkdir(dirfigname_pdf,       kTRUE);
      histocanvas->SaveAs(dirfigname_pdf + WJets[h].hist[ch]->GetName() + ".pdf");
      
      // clear Canvas
      histocanvas->Clear();    

    }
  }
  
} //end Plots.C
Esempio n. 30
0
void nbx_step_check(const char * filename="counts.root")
{
  TFile * infile = new TFile(filename,"READ");
  TTree * tr = (TTree*) infile->Get("sca");

  Int_t NRUNS_tmp = tr->GetMaximum("i");
  const Int_t NRUNS = NRUNS_tmp;
  TH1D * h[NRUNS];
  char h_n[NRUNS][256];
  char h_t[NRUNS][256];
  char cut[NRUNS][256];

  TCanvas * c = new TCanvas("c","c",1400,1000);

  Double_t max;

  Double_t step[NRUNS][120];
  Double_t step_e[NRUNS][120];
  Double_t bx_arr[120];
  Double_t bx_arr_e[120];
  for(Int_t b=0; b<120; b++)
  {
    bx_arr[b]=b;
    bx_arr_e[b]=0;
  };
  TGraphErrors * tg[NRUNS];

  for(Int_t i=0; i<NRUNS; i++)
  {
    printf("i=%d\n",i);

    sprintf(h_n[i],"nbx_bx_%d",i+1);
    sprintf(h_t[i],"N_{bx} vs. bXing for i=%d",i+1);
    h[i] = new TH1D(h_n[i],h_n[i],120,0,120);
    sprintf(cut[i],"tot_bx*(i==%d)",i+1);
    tr->Project(h_n[i],"bx",cut[i]);

    max = h[i]->GetMaximum();
    //h[i]->Scale(1/max);




    for(Int_t b=1; b<=119; b++)
    {
      step[i][b] = h[i]->GetBinContent(b) - h[i]->GetBinContent(b+1);
      step_e[i][b] = sqrt(step[i][b]);
    };
    tg[i] = new TGraphErrors(120,bx_arr,step[i],bx_arr_e,step_e[i]);

    c->Clear();
    c->SetGrid(1,1);
    tg[i]->SetMarkerStyle(kFullCircle); 
    tg[i]->Draw("ape");

    if(i==0) c->Print("nbx_step_check.pdf(","pdf");
    else if(i+1==NRUNS) c->Print("nbx_step_check.pdf)","pdf");
    else c->Print("nbx_step_check.pdf");

  };

};