Esempio n. 1
0
void MVA_allsrcComp()
{
  //InpFile = new TFile("../srcbatch/scTTMuon/TTsemiMuon.root");
  //InpFile = new TFile("../srcbatch/scTTElectron/TTsemiElectron.root");
  //InpFile = new TFile("../srcbatch/MonoJet_MET/MonoJet.root");
  InpFile = new TFile("../srcbatch/mSUGRA_MET/mSUGRA.root");
  //InpFile = new TFile("../srcbatch/scTT2Hadron/TT2Hadron.root");
  //InpFile = new TFile("../srcbatch/scWToENu/WToENu.root");
  //InpFile = new TFile("../srcbatch/scWToMuNu/WToMuNu.root");
  //InpFile = new TFile("../srcbatch/scDYElEl/DYElEl.root");
  //InpFile = new TFile("../srcbatch/scDYMuMu/DYMuMu.root");
  //InpFile = new TFile("../srcbatch/scZZ4Mu/ZZ4Mu.root");
  //InpFile = new TFile("../srcbatch/scZZ4El/ZZ4El.root");
  //InpFile = new TFile("../srcbatch/scZZMuEl/ZZMuEl.root");
  //InpFile = new TFile("../srcbatch/ZZ2Mu2Nu_MET/ZZ2Mu2Nu.root");
  //InpFile = new TFile("../srcbatch/ZZ2El2Nu_MET/ZZ2El2Nu.root");
  //InpFile = new TFile("../srcbatch/scWW/WW.root");
  //InpFile = new TFile("../srcbatch/scWZ/WZ.root");
  //InpFile = new TFile("../srcbatch/scMonoPhoton/MonoPhoton.root");
  
  //InpFileall = new TFile("../allbatch/TTsemiMuon_MET/TTsemiMuon.root");
  //InpFileall = new TFile("../allbatch/TTsemiElectron_MET/TTsemiElectron.root");
  //InpFileall = new TFile("../allbatch/MonoJet_MET/MonoJet.root");
  InpFileall = new TFile("../allbatch/mSUGRA_MET/mSUGRA.root");
  //InpFileall = new TFile("../allbatch/TT2Hadron_MET/TT2Hadron.root");
  //InpFileall = new TFile("../allbatch/WToENu_MET/WToENu.root");
  //InpFileall = new TFile("../allbatch/WToMuNu_MET/WToMuNu.root");
  //InpFileall = new TFile("../allbatch/DYElEl_MET/DYElEl.root");
  //InpFileall = new TFile("../allbatch/DYMuMu_MET/DYMuMu.root");
  //InpFileall = new TFile("../allbatch/ZZ4Mu_MET/ZZ4Mu.root");
  //InpFileall = new TFile("../allbatch/ZZ4El_MET/ZZ4El.root");
  //InpFileall = new TFile("../allbatch/ZZMuEl_MET/ZZMuEl.root");
  //InpFileall = new TFile("../allbatch/ZZ2Mu2Nu_MET/ZZ2Mu2Nu.root");
  //InpFileall = new TFile("../allbatch/ZZ2El2Nu_MET/ZZ2El2Nu.root");
  //InpFileall = new TFile("../allbatch/WW_MET/WW.root");
  //InpFileall = new TFile("../allbatch/WZ_MET/WZ.root");
  //InpFileall = new TFile("../allbatch/MonoPhoton_MET/MonoPhoton.root");

  char ylabel[100];
  char histName[100];
  char histName_org[100];
  
  TH1D *pfMet;
  TH1D *NoPUmet;
  TH1D *MVAmet;
  TH1D *NoPUmetall;
  TH1D *MVAmetall;
 
    sprintf(histName,"pfMet");
    sprintf(histName_org,"pfMET_0");
    pfMet =(TH1D*)InpFile->Get(histName_org)->Clone(histName);pfMet->Sumw2();
    
    sprintf(histName,"NoPUmet");
    sprintf(histName_org,"NoPuMET_0");
    NoPUmet =(TH1D*)InpFile->Get(histName_org)->Clone(histName);NoPUmet->Sumw2();
    
    sprintf(histName,"NoPUmetall");
    sprintf(histName_org,"NoPuMET_0");
    NoPUmetall =(TH1D*)InpFileall->Get(histName_org)->Clone(histName);NoPUmetall->Sumw2();
    
    sprintf(histName,"MVAmet");
    sprintf(histName_org,"MVaMET_0");
    MVAmet =(TH1D*)InpFile->Get(histName_org)->Clone(histName);MVAmet->Sumw2();

    sprintf(histName,"MVAmetall");
    sprintf(histName_org,"MVaMET_0");
    MVAmetall =(TH1D*)InpFileall->Get(histName_org)->Clone(histName);MVAmetall->Sumw2();

    pfMet->SetLineWidth(2);
    pfMet->SetLineColor(kBlack);
    pfMet->SetMarkerStyle(26);
    pfMet->SetMarkerColor(kBlack);
    NoPUmet->SetLineWidth(2);
    NoPUmet->SetLineColor(kRed);
    NoPUmet->SetMarkerStyle(kFullCircle);
    NoPUmet->SetMarkerColor(kRed);
    NoPUmetall->SetLineWidth(2);
    NoPUmetall->SetLineColor(kRed);
    NoPUmetall->SetMarkerStyle(kCircle);
    NoPUmetall->SetMarkerColor(kRed);
    MVAmet->SetLineWidth(2);
    MVAmet->SetLineColor(kBlue);
    MVAmet->SetMarkerStyle(kFullSquare);
    MVAmet->SetMarkerColor(kBlue);
    MVAmetall->SetLineWidth(2);
    MVAmetall->SetLineColor(kBlue);
    MVAmetall->SetMarkerStyle(25);
    MVAmetall->SetMarkerColor(kBlue);

    sprintf(ylabel,"MET-genMEtTrue",MVAmet->GetBinWidth(1));
    MVAmet->GetYaxis()->SetTitle(ylabel);
    MVAmet->GetYaxis()->SetTitleOffset(1.2);
    MVAmet->GetYaxis()->SetTitleSize(0.04);
    MVAmet->GetYaxis()->SetLabelSize(0.04);
    MVAmet->GetXaxis()->SetTitle("genMEt");
    MVAmet->GetXaxis()->SetTitleOffset(1.0);
    //MVAmet->GetXaxis()->SetTitleSize(0.13);
   
    //MVAmet->GetYaxis()->SetRangeUser(-15,30);//WJet TTsemiPU012
    //MVAmet->GetYaxis()->SetRangeUser(-25,30);// TTsemiPU3
    //MVAmet->GetYaxis()->SetRangeUser(-20,30);//WW
    
    //MVAmet->GetYaxis()->SetRangeUser(-5,20);//WZ   1
    //MVAmet->GetYaxis()->SetRangeUser(-15,25);//WZ  0,2
    //MVAmet->GetYaxis()->SetRangeUser(-20,35);//WZ  3
    
    //MVAmet->GetYaxis()->SetRangeUser(-15,30);//W
    //MVAmet->GetYaxis()->SetRangeUser(-20,30);//W muon3
    
    //MVAmet->GetYaxis()->SetRangeUser(-20,55);//ZZ4El
    
    //MVAmet->GetYaxis()->SetRangeUser(-25,55);//ZZ4Mu012
    //MVAmet->GetYaxis()->SetRangeUser(-25,65);//ZZ4Mu3
    
    //MVAmet->GetYaxis()->SetRangeUser(-70,70);//ZZMuEl 1
    //MVAmet->GetYaxis()->SetRangeUser(-30,40);//ZZMuEl 0 2
    //MVAmet->GetYaxis()->SetRangeUser(-50,50);//ZZMuEl 3
    
    //MVAmet->GetYaxis()->SetRangeUser(-30,30);//ZZ2El2Nu  0 2
    //MVAmet->GetYaxis()->SetRangeUser(-50,70);//ZZ2El2Nu  3
    //MVAmet->GetYaxis()->SetRangeUser(-30,60);//ZZ2El2Nu  1
    
    //MVAmet->GetYaxis()->SetRangeUser(-20,30);//DY 012
    //MVAmet->GetYaxis()->SetRangeUser(-30,60);//DYmuon1
    //MVAmet->GetYaxis()->SetRangeUser(-40,70);//DYele3
    //MVAmet->GetYaxis()->SetRangeUser(-50,85);//DYmuon3
    
    //MVAmet->GetYaxis()->SetRangeUser(-10,35);//TThadron
    //MVAmet->GetYaxis()->SetRangeUser(0,700);//monoJet
    
    MVAmet->GetYaxis()->SetRangeUser(-90,80);//mSUGRA 0
    //MVAmet->GetYaxis()->SetRangeUser(-130,110);//mSUGRA 1
    //MVAmet->GetYaxis()->SetRangeUser(-80,80);//mSUGRA 2
    //MVAmet->GetYaxis()->SetRangeUser(-140,130);//mSUGRA 3
    
    //MVAmet->GetYaxis()->SetRangeUser(-50,1000);//monoPhoton0
    //MVAmet->GetYaxis()->SetRangeUser(-50,1300);//monoPhoton2
    //MVAmet->GetYaxis()->SetRangeUser(-50,750);//monoPhoton13
    
    //MVAmet->GetXaxis()->SetRangeUser(0,75);//X-axis 80

    TCanvas c1("c1","c1",800,700);
    gStyle->SetOptTitle(0);

    MVAmet->Draw("E1");
    pfMet->Draw("E1 same");
    NoPUmet->Draw("E1 same");
    MVAmetall->Draw("E1 same");
    NoPUmetall->Draw("E1 same");
    
    TLegend *rL =new TLegend(0.55,0.68,0.99,0.95);
    rL->SetFillColor(0); rL->SetBorderSize(0);
    rL->AddEntry(pfMet,"pfMet","PL");
    rL->AddEntry(NoPUmet,"NoPU_wSrcLept","PL");
    rL->AddEntry(NoPUmetall,"NoPU_wAllSrcLept","PL");
    rL->AddEntry(MVAmet,"MVA_wSrcLept","PL");
    rL->AddEntry(MVAmetall,"MVA_wAllSrcLept","PL");
    rL->Draw();
 
    //midile line
    //TLine line(0,0,200,0);//TTsemi
    //TLine line(0,0,300,0);//ZZ2Lept2Nu
    //TLine line(0,0,100,0);
    TLine line(0,0,1500,0);//mSUGRA
    //TLine line(0,0,80,0);//ZZ4Mu ZZMuEl MonoPhoton
    line->Draw();
    
    //All 0To7 7To21 21To
    //sprintf(histName,"muonTTJetsemiLept_PURange_All.png");
    //sprintf(histName,"electronTTJetsemiLept_PURange_All.png");
    //sprintf(histName,"monoJet_PURange_All.png");
    sprintf(histName,"mSUGRA_PURange_All.png");
    //sprintf(histName,"hadronTT2hadron_PURange_All.png");
    //sprintf(histName,"electronWToENu_PURange_All.png");
    //sprintf(histName,"muonWToMuNu_PURange_All.png");
    //sprintf(histName,"electronDYElEl_PURange_All.png");
    //sprintf(histName,"muonDYMuNu_PURange_All.png");
    //sprintf(histName,"ZZ4Mu_PURange_All.png");
    //sprintf(histName,"ZZ4El_PURange_All.png");
    //sprintf(histName,"ZZ2Mu2El_PURange_All.png");
    //sprintf(histName,"ZZ2Mu2Nu_PURange_All.png");
    //sprintf(histName,"ZZ2El2Nu_PURange_All.png");
    //sprintf(histName,"WW_PURange_All.png");
    //sprintf(histName,"WZ_PURange_All.png");
    //sprintf(histName,"monoPhoton_PURange_All.png");
    c1.SaveAs(histName);

}
TCanvas *drawRatioPlot(TH1D *prediction, TH1D *sr, TString xTitle, TString filename){

  
  TCanvas *c = new TCanvas("c"+filename,"c",0,0,500,500);

  float y = 0.3;

  TPad *pad1     = new TPad("pad1", "Control Plots 1", 0.01, y, 0.99, 0.99);
  TPad *padRatio = new TPad("rp1", "Ratio1", 0.01, 0.01, 0.99, y-0.01);

  TH1D *ratio = 0;

  //ratio = (TH1D*) sr->Clone();
  //ratio->Divide(prediction);

  ratio = (TH1D*) prediction->Clone();
  ratio->Divide(sr);


  for(int i=1; i<=ratio->GetNbinsX();i++){

    cout<<"Scaling Factor in "<<i<<". bin ="<<ratio->GetBinContent(i)<<" +/- "<<ratio->GetBinError(i)<<endl; 

  }

  ratio->GetYaxis()->SetTitle("Pred/Bkg");
  ratio->SetTitle("");
  ratio->SetLabelSize(0.1,"X");
  ratio->SetLabelSize(0.1,"Y");
  ratio->SetTitleOffset(0.5,"Y");
  ratio->SetTitleSize(0.15,"Y");


  padRatio->cd();
  //ratio->GetYaxis()->SetRangeUser(0,2);
  ratio->Draw();

  // Draw line at one!
  float xmin = ratio->GetXaxis()->GetXmin();
  float xmax = ratio->GetXaxis()->GetXmax();
  TLine *line = new TLine(xmin,1,xmax,1);
  line->SetLineWidth(2);
  line->Draw("same");
  padRatio->Modified();

  TLegend *leg = new TLegend(0.6,0.8,0.9,0.9);
  leg->AddEntry(sr,"bkg","l"); 
  leg->AddEntry(prediction,"bkg prediction","pel"); 
  pad1->cd();
  pad1->SetLogy();

  sr->SetLineColor(kRed);
  sr->SetMarkerColor(kRed);
  sr->SetMarkerStyle(20);
  sr->SetTitle("");
  prediction->SetMarkerStyle(20);
  prediction->SetTitle("");
  prediction->GetXaxis()->SetTitle(xTitle);
  sr->GetXaxis()->SetTitle(xTitle);

  prediction->SetTitleSize(0.07,"X");
  prediction->GetXaxis()->SetTitleOffset(0.7);
  sr->SetTitleSize(0.07,"X");
  sr->GetXaxis()->SetTitleOffset(0.7);

  prediction->Draw("e");
  sr->Draw("e same");

  double maximum =prediction->GetMaximum()*2.5;
  double minimum = 0.00001;
  if(sr->GetMinimum()!=0) minimum=sr->GetMinimum()*0.5;
  if(prediction->GetMinimum()!=0) minimum=prediction->GetMinimum()*0.5;
  if(sr->GetMaximum()>prediction->GetMaximum()){

    maximum=sr->GetMaximum()*2.5;
  }

  prediction->GetYaxis()->SetRangeUser(minimum,maximum);

  leg->Draw("same");




  // Draw both pads to canvas
  c->cd();
  pad1->Draw();
  padRatio->SetGridy();
  padRatio->Draw();

  c->SaveAs(filename);

  return c;

}
void drawPtDependence_yeonju0815(bool drawPbPb=1, int xNorm = 1) {
    gStyle -> SetOptStat(0);
    const int nPtBin = 5;
    double ptBin[nPtBin+1] = {40, 50,60,80,120,9999}; 
    double AvePtBin[nPtBin+1] = { 45, 54.1479, 67.4204, 99.6956, 150, 9999};

    TH1D* hxjg[7][1000]; // [species][centrality] 
    TH1D* hxjgNorm[7][1000];
    TH1D* hdphi[7][1000];

    valPair meanX[7][1000];
    valPair rjg[7][1000];
    TGraphAsymmErrors* gr[7];
    TGraphAsymmErrors* gx[7];
    for (int i=0;i<7;i++) {  
        gr[i] = new TGraphAsymmErrors();
        gr[i]->SetName(Form("gr_%d",i));
        gx[i] = new TGraphAsymmErrors();
        gx[i]->SetName(Form("gx_%d",i));
    }
    TFile* fff[7][1000];
    
    for ( int ipt = 0 ; ipt<nPtBin  ; ipt++) { 
        for ( int iSpecies=0 ; iSpecies<=5 ; iSpecies++){ 
            if (  (iSpecies!=kPPDATA)&&(iSpecies!=kHIDATA) ) 
                continue;

            int iglb = ipt + iSpecies*50.;
            int icent = -1;

            if ( iSpecies == kPPDATA) { 
                icent = 7;
                fff[iSpecies][iglb] = new TFile(Form("ffFiles/photonTrackCorr_ppDATA_output_photonPtThr%d_to_%d_jetPtThr30_20130815.root",(int)ptBin[ipt],(int)ptBin[ipt+1]));
            }
            if ( iSpecies == kHIDATA) { 
                icent = 10030;
                fff[iSpecies][iglb] = new TFile(Form("ffFiles/photonTrackCorr_pbpbDATA_output_photonPtThr%d_to_%d_jetPtThr30_20130815.root",(int)ptBin[ipt],(int)ptBin[ipt+1]));
            }

            hdphi[iSpecies][iglb] = (TH1D*)fff[iSpecies][iglb]->Get(Form("jetDphi_icent%d_final",icent));

            hxjg[iSpecies][iglb] = (TH1D*)fff[iSpecies][iglb]->Get(Form("xjg_icent%d_final",icent));
            hxjgNorm[iSpecies][iglb] = (TH1D*)hxjg[iSpecies][iglb]->Clone(Form("norm_%s",hxjg[iSpecies][iglb]->GetName()) );

            meanX[iSpecies][iglb].val = hxjg[iSpecies][iglb]->GetMean();
            meanX[iSpecies][iglb].err = hxjg[iSpecies][iglb]->GetMeanError();
            gx[iSpecies]->SetPoint     (ipt+1, AvePtBin[ipt], meanX[iSpecies][iglb].val);
            gx[iSpecies]->SetPointError(ipt+1, 0.001,0.001, meanX[iSpecies][iglb].err, meanX[iSpecies][iglb].err);

            double rError;
            rjg[iSpecies][iglb].val = hxjg[iSpecies][iglb]->IntegralAndError(1, hxjg[iSpecies][iglb]->GetNbinsX(), rError, "width");
            rjg[iSpecies][iglb].err = rError;
            gr[iSpecies]->SetPoint     (ipt+1, AvePtBin[ipt], rjg[iSpecies][iglb].val);
            gr[iSpecies]->SetPointError(ipt+1, 0.001,0.001, rjg[iSpecies][iglb].err, rjg[iSpecies][iglb].err);


        }
    }

    // for PbPb 30-9999!!!!
    for ( int ipt = 0 ; ipt<nPtBin  ; ipt++) { 
        int iSpecies=6;
        int iglb = ipt + iSpecies*50.;
        int icent = 13099;
        fff[iSpecies][iglb] = new TFile(Form("photonTrackCorr_pbpbDATA_output_photonPtThr%d_to_%d_jetPtThr30_20130815.root",(int)ptBin[ipt],(int)ptBin[ipt+1]));

        hdphi[iSpecies][iglb] = (TH1D*)fff[iSpecies][iglb]->Get(Form("jetDphi_icent%d_final",icent));

        hxjg[iSpecies][iglb] = (TH1D*)fff[iSpecies][iglb]->Get(Form("xjg_icent%d_final",icent));
        hxjgNorm[iSpecies][iglb] = (TH1D*)hxjg[iSpecies][iglb]->Clone(Form("norm_%s",hxjg[iSpecies][iglb]->GetName()) );

        meanX[iSpecies][iglb].val = hxjg[iSpecies][iglb]->GetMean();
        meanX[iSpecies][iglb].err = hxjg[iSpecies][iglb]->GetMeanError();
        gx[iSpecies]->SetPoint     (ipt+1, AvePtBin[ipt], meanX[iSpecies][iglb].val);
        gx[iSpecies]->SetPointError(ipt+1, 0.001,0.001, meanX[iSpecies][iglb].err, meanX[iSpecies][iglb].err);

        double rError;
        rjg[iSpecies][iglb].val = hxjg[iSpecies][iglb]->IntegralAndError(1, hxjg[iSpecies][iglb]->GetNbinsX(), rError, "width");
        rjg[iSpecies][iglb].err = rError;
        gr[iSpecies]->SetPoint     (ipt+1, AvePtBin[ipt], rjg[iSpecies][iglb].val);
        gr[iSpecies]->SetPointError(ipt+1, 0.001,0.001, rjg[iSpecies][iglb].err, rjg[iSpecies][iglb].err);
    }

    TCanvas* c1 = new TCanvas("c1","",1350,350);
    makeMultiPanelCanvas(c1,nPtBin,1,0.0,0.0,0.2,0.15,0.02);
    for ( int ipt = 0 ; ipt<nPtBin  ; ipt++) {
        c1->cd(ipt+1);

        int iSpecies = kPPDATA;
        int iglb = ipt + iSpecies*50.;
        handsomeTH1(hxjgNorm[iSpecies][iglb],1);
        if (xNorm==1) scaleInt(hxjgNorm[iSpecies][iglb]);
        hxjgNorm[iSpecies][iglb]->SetXTitle("x_{J,#gamma}");
        hxjgNorm[iSpecies][iglb]->SetYTitle("#frac{dN}{dx} #frac{1}{N}");
        if (xNorm==1)     hxjgNorm[iSpecies][iglb]->SetAxisRange(-0.015,0.3,"Y");
        else              hxjgNorm[iSpecies][iglb]->SetAxisRange(-0.06,1.5,"Y");
        hxjgNorm[iSpecies][iglb]->SetMarkerStyle(24);
        hxjgNorm[iSpecies][iglb]->Draw();

        iSpecies = kHIDATA;
        iglb = ipt + iSpecies*50.;
        if (xNorm==1)  scaleInt(hxjgNorm[iSpecies][iglb]);
        handsomeTH1(hxjgNorm[iSpecies][iglb],2);
        if (drawPbPb) hxjgNorm[iSpecies][iglb]->Draw("same");
        
        //for PbPb 30-9999!!!!
        iSpecies = 6;
        iglb = ipt + iSpecies*50.;
        if (xNorm==1)  scaleInt(hxjgNorm[iSpecies][iglb]);
        handsomeTH1(hxjgNorm[iSpecies][iglb],2);
        hxjgNorm[iSpecies][iglb] -> SetMarkerStyle(24);
        if (drawPbPb) hxjgNorm[iSpecies][iglb]->Draw("same");
        
        onSun(0,0,2,0);

        //    onSun(meanX[iSpecies][iglb].val - meanX[iSpecies][iglb].err, 0, meanX[iSpecies][iglb].val+meanX[iSpecies][iglb].err,0,ycolor[ipt+1],2);

        float dx1;    
        (ipt==0)? dx1=0.15 : dx1=0 ;

        if ( ipt == nPtBin-1 ) 
            drawText(Form("p_{T}^{#gamma} > %dGeV,   p_{T}^{jet}>30GeV", (int)ptBin[ipt]), 0.12+dx1+0.25,0.889118,1,15);
        else 
            drawText(Form("%dGeV < p_{T}^{#gamma} < %dGeV,   p_{T}^{jet}>30GeV", (int)ptBin[ipt], (int)ptBin[ipt+1]), 0.12+dx1,0.889118,1,15);


        TLegend *l1 = new TLegend(0.6365615,0.6445304,0.9577623,0.846736,NULL,"brNDC");
        easyLeg(l1,"2.76TeV");
        l1->AddEntry(hxjgNorm[kPPDATA][ipt + kPPDATA*50],"pp ","p");
        if (drawPbPb)    l1->AddEntry(hxjgNorm[kHIDATA][iglb],"PbPb 0-30%","p");
        if (drawPbPb)    l1->AddEntry(hxjgNorm[6][iglb],"PbPb 30-100%","p");
        if ( ipt==0 )   l1->Draw();

    }
    c1->SaveAs(Form("gifs/xjg_ptDependence_drawPbPb%d_norm%d.pdf",drawPbPb,xNorm));

    TCanvas* cDphi = new TCanvas("cDphi","",1350,350);
    makeMultiPanelCanvas(cDphi,nPtBin,1,0.0,0.0,0.2,0.15,0.02);
    for ( int ipt = 0 ; ipt<nPtBin  ; ipt++) {
        cDphi->cd(ipt+1);

        int iSpecies = kPPDATA;
        int iglb = ipt + iSpecies*50.;
        handsomeTH1(hdphi[iSpecies][iglb],1);
        hdphi[iSpecies][iglb]->SetYTitle("x_{J,#gamma}");
        hdphi[iSpecies][iglb]->SetXTitle("#Delta#phi_{J,#gamma}");
        hdphi[iSpecies][iglb]->Scale(1./hdphi[iSpecies][iglb]->Integral("width"));
        hdphi[iSpecies][iglb]->SetAxisRange(0.01,30,"Y");
        hdphi[iSpecies][iglb]->SetMarkerStyle(24);
        hdphi[iSpecies][iglb]->Draw();
        
        iSpecies = kHIDATA;
        iglb = ipt + iSpecies*50.;
        hdphi[iSpecies][iglb]->Scale(1./hdphi[iSpecies][iglb]->Integral("width"));
        handsomeTH1(hdphi[iSpecies][iglb],2);
        if (drawPbPb)     hdphi[iSpecies][iglb]->Draw("same");
        
        //for PbPb 30-100!!!
        iSpecies = 6;
        iglb = ipt + iSpecies*50.;
        hdphi[iSpecies][iglb]->Scale(1./hdphi[iSpecies][iglb]->Integral("width"));
        handsomeTH1(hdphi[iSpecies][iglb],2);
        hdphi[iSpecies][iglb]->SetMarkerStyle(24);
        if (drawPbPb)     hdphi[iSpecies][iglb]->Draw("same");
        
        gPad->SetLogy();
        float dx1;    
        (ipt==0)? dx1=0.15 : dx1=0 ;

        if ( ipt == nPtBin-1 ) 
            drawText(Form("%dGeV<p_{T}^{#gamma},   p_{T}^{jet}>30GeV", (int)ptBin[ipt]), 0.15+dx1+0.25,0.889118,1,15);
        else 
            drawText(Form("%dGeV<p_{T}^{#gamma}<%dGeV,   p_{T}^{jet}>30GeV", (int)ptBin[ipt], (int)ptBin[ipt+1]), 0.15+dx1,0.889118,1,15);


        TLegend *l1 = new TLegend(0.6365615,0.6445304,0.9577623,0.846736,NULL,"brNDC");
        easyLeg(l1,"2.76TeV");
        l1->AddEntry(hdphi[kPPDATA][ipt + kPPDATA*50],"pp ","p");
        if (drawPbPb)    l1->AddEntry(hdphi[kHIDATA][iglb],"PbPb 0-30%","p");
        if (drawPbPb)    l1->AddEntry(hdphi[kHIDATA][iglb],"PbPb 30-100%","p");
        if ( ipt==0 )   l1->Draw();

    }


    cDphi->SaveAs(Form("gifs/dphi_ptDependence_drawPbPb%d_norm%d.pdf",drawPbPb,xNorm));

    TCanvas* c2 = new TCanvas("c2","",800,400);
    c2->Divide(2,1);
    c2->cd(2);
    TH1D* hr = new TH1D("hr",";p_{T}^{#gamma};r_{J,#gamma}",200,20,180);
    handsomeTH1(hr,1);
    hr->SetAxisRange(0.0,1.1,"Y");
    //  hr->SetNdivisions(5);
    hr->Draw();
    handsomeTGraph(gr[kPPDATA],1);
    handsomeTGraph(gr[kHIDATA],2);
    handsomeTGraph(gr[6],2);
    gr[kPPDATA]->SetMarkerStyle(24);
    gr[kPPDATA]->Draw("same p");
    gr[6]->SetMarkerStyle(24);
    if (drawPbPb)   gr[kHIDATA]->Draw("same p");
    if (drawPbPb)   gr[6]->Draw("same p");
    jumSun(20,1,180,1);

    gStyle->SetEndErrorSize(0);

    c2->cd(1);
    TH1D* hx = (TH1D*)hr->Clone("hx");
    handsomeTH1(hx,1);
    hx->SetYTitle("<x_{J,#gamma}>");
    hx->SetAxisRange(0.6,1.05,"Y");
    //  hx->SetNdivisions(5);
    hx->Draw();
    handsomeTGraph(gx[kPPDATA],1);
    handsomeTGraph(gx[kHIDATA],2);
    handsomeTGraph(gx[6],2);
    gx[kPPDATA]->SetMarkerStyle(24);
    gx[kPPDATA]->Draw("same p");
    gx[6]->SetMarkerStyle(24);
    if (drawPbPb)   gx[kHIDATA]->Draw("same p");
    if (drawPbPb)   gx[6]->Draw("same p");
    jumSun(20,1,180,1);

    c2->cd(2);
    TLegend *l1=   new TLegend(0.5226071,0.6300415,0.9597724,0.8332584,NULL,"brNDC");
    easyLeg(l1,"2.76TeV");
    l1->AddEntry(gr[kPPDATA],"pp ","p");
    if (drawPbPb)     l1->AddEntry(gr[kHIDATA],"PbPb 0-30%","p");
    if (drawPbPb)     l1->AddEntry(gr[6],"PbPb 30-100%","p");
    l1->Draw();

    c2->SaveAs(Form("gifs/summaryPlot_ptDependence_drawPbPb%d_norm%d.pdf",drawPbPb,xNorm));

}
void drawMixedEvent()
{
  gStyle->SetOptStat(0);
  gStyle->SetLabelFont(132, "x");
  gStyle->SetLabelFont(132, "y");
  gStyle->SetTitleFont(132, "x");
  gStyle->SetTitleFont(132, "y");
  gStyle->SetLegendFont(132);

  TFile *f = new TFile("mixedEventSeparatedByCharge.root");

  const float massFrom = 0;
  const float massTo = 3;
  const float fixedBinWidth = 0.01;
  const int massNBins = (massTo - massFrom) / fixedBinWidth;

  TCanvas *C = new TCanvas("C", "mass plot", 500, 500);
  TH1D* sig = new TH1D("sig", "", massNBins, massFrom, massTo);
  TH1D* bkgSELS = new TH1D("bkgSELS", "", massNBins, massFrom, massTo);
  TH1D* bkgMEUS = new TH1D("bkgMEUS", "", massNBins, massFrom, massTo);
  TH1D* bkgMELS = new TH1D("bkgMELS", "", massNBins, massFrom, massTo);

  //--------------------------------------------------
  for (int iCent = minCent; iCent < maxCent; ++iCent)
  {
    for (int iVz = 0; iVz < 10; ++iVz)
    {
      std::string baseName = Form("Cent_%i_Vz_%i",iCent,iVz);

      TH2F* hSE_LS = static_cast<TH2F*>(f->Get(Form("%s_se_ls_mass", baseName.data())));
      TH2F* hSE_US_plus = static_cast<TH2F*>(f->Get(Form("%s_se_us_plus_mass", baseName.data())));
      TH2F* hSE_US_minus = static_cast<TH2F*>(f->Get(Form("%s_se_us_minus_mass", baseName.data())));
      TH2F* hME_LS = static_cast<TH2F*>(f->Get(Form("%s_me_ls_mass", baseName.data())));
      TH2F* hME_US_plus = static_cast<TH2F*>(f->Get(Form("%s_me_us_plus_mass", baseName.data())));
      TH2F* hME_US_minus = static_cast<TH2F*>(f->Get(Form("%s_me_us_minus_mass", baseName.data())));

      const int firstPtBin = 10.*minPt + 1;
      cout << "first bin " << firstPtBin << endl;
      const int lastPtBin = 10.*maxPt;
      cout << "last bin " << lastPtBin << endl;

      TH1D* massProj_SE_LS = hSE_LS->ProjectionY(Form("%s_se_ls_mass_proj", baseName.data()), firstPtBin, lastPtBin);
      TH1D* massProj_SE_US_plus = hSE_US_plus->ProjectionY(Form("%s_se_us_plus_mass_proj", baseName.data()), firstPtBin, lastPtBin);
      TH1D* massProj_SE_US_minus = hSE_US_minus->ProjectionY(Form("%s_se_us_minus_mass_proj", baseName.data()), firstPtBin, lastPtBin);
      TH1D* massProj_ME_LS = hME_LS->ProjectionY(Form("%s_me_ls_mass_proj", baseName.data()), firstPtBin, lastPtBin);
      TH1D* massProj_ME_US_plus = hME_US_plus->ProjectionY(Form("%s_me_us_plus_mass_proj", baseName.data()), firstPtBin, lastPtBin);
      TH1D* massProj_ME_US_minus = hME_US_minus->ProjectionY(Form("%s_me_us_minus_mass_proj", baseName.data()), firstPtBin, lastPtBin);

      // add the bin content
      const int firstBin = massFrom / fixedBinWidth;
      for (int iBin = 0; iBin < massNBins; ++iBin)
      {
	const int histBin = iBin+1;
	const int movedBin = firstBin + iBin + 1;

	sig->SetBinContent(histBin, massProj_SE_US_plus->GetBinContent(movedBin) + sig->GetBinContent(histBin));
	sig->SetBinContent(histBin, massProj_SE_US_minus->GetBinContent(movedBin) + sig->GetBinContent(histBin));
	bkgSELS->SetBinContent(histBin, massProj_SE_LS->GetBinContent(movedBin) + bkgSELS->GetBinContent(histBin));
	bkgMEUS->SetBinContent(histBin, massProj_ME_US_plus->GetBinContent(movedBin) + bkgMEUS->GetBinContent(histBin));
	bkgMEUS->SetBinContent(histBin, massProj_ME_US_minus->GetBinContent(movedBin) + bkgMEUS->GetBinContent(histBin));
	bkgMELS->SetBinContent(histBin, massProj_ME_LS->GetBinContent(movedBin) + bkgMELS->GetBinContent(histBin));

	sig->SetBinError(histBin, addErrors(sig->GetBinError(histBin), massProj_SE_US_plus->GetBinError(movedBin)) );
	sig->SetBinError(histBin, addErrors(sig->GetBinError(histBin), massProj_SE_US_minus->GetBinError(movedBin)) );
	bkgSELS->SetBinError(histBin, addErrors(bkgSELS->GetBinError(histBin), massProj_SE_LS->GetBinError(movedBin)) );
	bkgMEUS->SetBinError(histBin, addErrors(bkgMEUS->GetBinError(histBin), massProj_ME_US_plus->GetBinError(movedBin)) );
	bkgMEUS->SetBinError(histBin, addErrors(bkgMEUS->GetBinError(histBin), massProj_ME_US_minus->GetBinError(movedBin)) );
	bkgMELS->SetBinError(histBin, addErrors(bkgMELS->GetBinError(histBin), massProj_ME_LS->GetBinError(movedBin)) );
      }
    }
  }
  //--------------------------------------------------
  const float sigma = 7.76446e-03; // taken from fit of the whole dataset +-3.64310e-03
  const float meanInclusive = 2.28359; // +-2.14540e-03
  const float nSigma = 8.;
  const float sideBandTo = roundToPreviousBin(meanInclusive - nSigma*sigma, massNBins, massFrom, massTo);
  const float sideBandFrom = roundToNextBin(meanInclusive + nSigma*sigma, massNBins, massFrom, massTo);

  const float sideBand = sig->Integral(massFrom, sideBandTo) + sig->Integral(sideBandFrom, massTo);
  cout << "Side-band yield = " << sideBand << endl;

  // scaling the mixed event BKG by the yield of the side-band
  float sideBandYield = 0;
  float mixedSideBandYield = 0;
  for (int i = 0; i < massNBins; ++i)
  {
    const float binCenter = sig->GetXaxis()->GetBinCenter(i+1);
    if(binCenter < sideBandTo || binCenter > sideBandFrom)
    {
      sideBandYield += sig->GetBinContent(i+1);
      mixedSideBandYield += bkgMEUS->GetBinContent(i+1);
    }

  }
  TH1D* sideBandMarker = new TH1D("sideBandMarker","marker for the sideband in the form of a histogram", massNBins, massFrom, massTo);
  const float binWidth = (massTo - massFrom) / static_cast<float>(massNBins);
  for(int i = 0; i < massNBins; ++i)
    sideBandMarker->SetBinContent(i+1, 1000);
  for(float bin = sideBandTo; bin < sideBandFrom; bin += binWidth)
  {
    // cout << bin << endl;
    sideBandMarker->Fill(bin + 0.5*binWidth, -1e6);
  }
  sideBandMarker->SetFillColor(kRed);
  sideBandMarker->SetFillStyle(3004);
  sideBandMarker->SetLineColorAlpha(kRed,0);

  bkgSELS->Scale(1./3.);
  cout << "Scaling mixed event bg by " << sideBandYield / mixedSideBandYield << endl;
  bkgMEUS->Scale(sideBandYield / (mixedSideBandYield) );

  TF1 *line = new TF1("line", "[0] + [1]*x");
  TF1 *gaussPlusLine = new TF1("gaussPlusLine", "[0] + [1]*x + [2]*TMath::Gaus(x,[3],[4],1)");

  bkgMEUS->Fit(line, "", "", 2.1, 2.5);
  double offset = line->GetParameter(0);
  double slope = line->GetParameter(1);
  const double LcMass = 2.28646;

  gaussPlusLine->FixParameter(0,offset);
  gaussPlusLine->FixParameter(1,slope);
  gaussPlusLine->SetParameter(3,LcMass);

  gaussPlusLine->SetParameter(2,1);
  gaussPlusLine->SetParameter(4,sigma);

  sig->Fit(gaussPlusLine, "", "", 2.1, 2.5);

  // -- Drawing
  sig->GetXaxis()->SetTitle("#font[12]{m}_{pK#pi} (GeV/#font[12]{c}^{2})");
  sig->GetXaxis()->CenterTitle();
  sig->GetXaxis()->SetLabelSize(0.04);
  sig->GetXaxis()->SetTitleSize(0.055);
  sig->GetXaxis()->SetTitleOffset(0.8);
  // sig->GetXaxis()->SetTickLength(0.001);
  sig->GetYaxis()->SetTitle("#font[12]{N}/(10 MeV/#font[12]{c}^{2})");
  sig->GetYaxis()->CenterTitle();
  sig->GetYaxis()->SetLabelSize(0.04);
  sig->GetYaxis()->SetTitleSize(0.055);
  sig->GetYaxis()->SetTitleOffset(0.8);
  // sig->GetYaxis()->SetRangeUser(17, 95);

  sig->SetMarkerStyle(20);
  sig->SetLineColor(kBlack);

  bkgMEUS->SetMarkerStyle(21);
  bkgMEUS->SetMarkerColor(kOrange+5);
  bkgMEUS->SetLineColor(kOrange+5);
  bkgMEUS->GetFunction("line")->SetLineColor(kRed);
  bkgMEUS->GetFunction("line")->SetLineStyle(2);
  bkgMEUS->GetFunction("line")->SetNpx(10000);

  bkgSELS->SetMarkerStyle(22);
  bkgSELS->SetMarkerColor(kBlue-7);
  bkgSELS->SetLineColor(kBlue-7);

  bkgMELS->SetMarkerStyle(23);
  bkgMELS->SetMarkerColor(kGreen+2);
  bkgMELS->SetLineColor(kGreen+2);
  
  sig->GetFunction("gaussPlusLine")->SetLineColor(kRed);
  sig->GetFunction("gaussPlusLine")->SetNpx(10000);

  sig->GetXaxis()->SetRangeUser(2.1,2.5);
  sig->Draw("E");
  bkgMEUS->Draw("Esame");
  bkgSELS->Draw("Esame");
  // bkgMELS->Draw("Esame");

  TLegend *leg = new TLegend(0.5,0.6,0.89,0.8);
  leg->SetFillStyle(0);
  leg->SetBorderSize(0);
  leg->AddEntry(sig, "Same event correct sign", "pl");
  leg->AddEntry(bkgSELS, "Same event wrong sign", "pl");
  leg->AddEntry(bkgMEUS, "Mixed event correct sign", "pl");
  // leg->AddEntry(bkgMELS, "Mixed event wrong sign", "pl");
  leg->Draw();
  // sideBandMarker->Draw("same BAR");

  TLegend *dataSet = new TLegend(0., 0.7, 0.4, 0.89);
  dataSet->SetFillStyle(0);
  dataSet->SetBorderSize(0);
  dataSet->AddEntry("", "#font[22]{Au+Au 200 GeV, 10-60%}","");
  dataSet->AddEntry("",Form("%1.0f GeV/#font[12]{c} < #font[12]{p}_{T} < %1.0f GeV/#font[12]{c}", minPt, maxPt),"");
  dataSet->Draw();

  // --  yield calculation
  const float min = 2.26;
  const float max = 2.31;

  // -- get part of the Gauss curve
  TF1 *normGaus = new TF1("normGaus", "TMath::Gaus(x,[0],[1],1)");
  double mean = gaussPlusLine->GetParameter(3);
  double width= gaussPlusLine->GetParameter(4);
  normGaus->SetParameter(0,mean);
  normGaus->SetParameter(1,width);
  double norm = normGaus->Integral(min, max);

  int minBin = sig->FindBin(min) + 1;
  int maxBin = sig->FindBin(max);
  cout << "integral from " << sig->GetBinCenter(minBin) - 0.005 << " to " << sig->GetBinCenter(maxBin) + 0.005 << endl;
  float NSig = sig->Integral(minBin,maxBin);
  float NBkg = bkgMEUS->Integral(minBin, maxBin);
  float Nlc = (NSig - NBkg)/norm;
  float error = std::sqrt(NSig/norm);

  cout << "N Sig = " << NSig << endl;
  cout << "N Bkg = " << NBkg << endl;
  cout << "norm = " << norm << endl;
  cout << "N Lambda_c = " << Nlc << endl;
  cout << "sigma = " << error << endl;
}
Esempio n. 5
0
//void drawBinsOfMet(const TString var = "minDeltaPhiN", const TString treestring = "/cu2/ra2b/reducedTrees/V00-02-25_fullpf2pat/reducedTree.SSVHPT_PF2PATjets_JES0_JER0_PFMET_METunc0_PUunc0_BTagEff0_HLTEff0.PythiaPUQCD.root")
void mdpBinsOfMet(const TString var = "min_delta_phi_met_N", const TString btag_cut="num_csvm_jets>=1", TString plotTitle="", bool logy = false, const TString treestring = "reduced_trees/QCD_Pt*v75*.root")
{ 
  const TCut btag(btag_cut);
  //const TCut btag = "nbjetsSSVHPT>=2";
  //const TCut btag = "nbjetsSSVHPT==0";
  //const TCut btag = "nbjetsSSV0>=1";

  //const TString var ="minDeltaPhiN";
  //const TString var ="minDeltaPhi";
  //  const TString var ="bestTopMass";
  //  const TString var ="MET/(MET+HT)";
  //  const TString var ="deltaPhiMPTcaloMET";

  const bool drawLSB = true;
  const bool drawMSB = true;
  const bool drawSB = true;
  const bool drawSIG = true;

  float customMax = 1;
  if(logy) customMax = 10;
  //const float customMax = -1;
  const bool doRatio=false; //hack for a specific ratio plot

  const  int nbins=10;
  float min=0;
  float max=0;
  if (var=="bestTopMass") max=800;
  else if (var=="min_delta_phi_met"||var=="min_delta_phi_met_loose_jets") max=TMath::Pi();
  else if (var.Contains("min_delta_phi_met_N")) max=20;
  else if (var.Contains("minDeltaPhiK")) max=20;
  else if (var=="deltaPhiMPTcaloMET")    max=TMath::Pi();
  else max = 0.6; 

  //updated to use reducedTrees

  bool addOverflow = true;
  if (var.Contains("min_delta_phi_met")) addOverflow=false;
  else  if (var=="bestTopMass") addOverflow=false;
  else  if (var=="deltaPhiMPTcaloMET") addOverflow=false;

  //  gROOT->SetStyle("CMS");
  gStyle->SetOptStat(0);

  TCut baseline ="ht40>=400&&jet1_pt>70&&jet2_pt>70&&jet3_pt>50"; //no mindp, no MET
  TString dp_cut(var);
  if (var.Contains("min_delta_phi_met_N")) dp_cut+=">4.";
  else if (var.Contains("min_delta_phi_met")) dp_cut+=">0.3";

  TCut minDPcut(dp_cut);
  //TCut minDPcut = "minDeltaPhi > 0.2"; cout<<"warning -- using special minDeltaPhi cut! "<<minDPcut.GetTitle()<<endl;
  if (!var.Contains("min_delta_phi_met")) baseline = baseline&&minDPcut;
  TCut LSB = "met<75";
  TCut MSB = "met>=75 && met<150";
  TCut SB = "met>=150 && met <225";
  TCut SIG = "met>225";

  TCut cut1=baseline && LSB && btag;
  TCut cut2=baseline && MSB && btag;
  TCut cut3=baseline && SB && btag;
  TCut cut4=baseline && SIG && btag;

  TString selection1 = TString("weightppb*(")+cut1.GetTitle()+")";
  TString selection2 = TString("weightppb*(")+cut2.GetTitle()+")";
  TString selection3 = TString("weightppb*(")+cut3.GetTitle()+")";
  TString selection4 = TString("weightppb*(")+cut4.GetTitle()+")";

//   TChain madgraph("reducedTree");
//   madgraph.Add("/cu2/joshmt/V00-03-01_6/reducedTree.Baseline0_PF_JERbias6_pfMEThigh_PFLepRA20e0mu_minDP_MuonCleaning.QCD.root");

  TChain * pypu = new TChain("reduced_tree");
  //pypu->Add("/cu2/ra2b/reducedTrees/V00-02-05_v2/reducedTree.SSVHPT.PythiaPUQCD.root");
  //pypu->Add("/cu2/ra2b/reducedTrees/V00-02-25_fullpf2pat/reducedTree.SSVHPT_PF2PATjets_JES0_JER0_PFMET_METunc0_PUunc0_BTagEff0_HLTEff0.PythiaPUQCD.root");
  pypu->Add(treestring);// treestring is passed as an argument
  
  
//   TChain py("reducedTree");
//   py.Add("/cu2/joshmt/V00-03-01_6/reducedTree.Baseline0_PF_JERbias6_pfMEThigh_PFLepRA20e0mu_minDP_MuonCleaning.PythiaQCD.root");

  TH1::SetDefaultSumw2(); //trick to turn on Sumw2 for all histos

  //constint nbins=6;
  //  const double varbins[]={0.,160.,180.,260.,400.,800.,2000};

  int height= doRatio ? 800 : 600;
  TCanvas * thecanvas= new TCanvas("thecanvas","the canvas",700,height);
  if (doRatio) {
    thecanvas->Divide(1,2);
    const float padding=0.01; const float ydivide=0.2;
    thecanvas->GetPad(1)->SetPad( padding, ydivide + padding, 1-padding, 1-padding);
    thecanvas->GetPad(2)->SetPad( padding, padding, 1-padding, ydivide-padding);
    thecanvas->cd(1);
  }
  
  TH1D * Hlow   = new TH1D("Hlow","",nbins,min,max);
  TH1D * Hmed   = new TH1D("Hmed","",nbins,min,max);
  TH1D * Hmh    = new TH1D("Hmh","",nbins,min,max);
  TH1D * Hhigh  = new TH1D("Hhigh","",nbins,min,max);
  TH1D * Hratio = new TH1D("Hratio","",nbins,min,max);
  /*
  TH1D Hlow("Hlow","",nbins,varbins);
  TH1D Hmed("Hmed","",nbins,varbins);
  TH1D Hmh("Hmh","",nbins,varbins);
  TH1D Hhigh("Hhigh","",nbins,varbins);
  */
  
  Hlow->SetLineColor(46);
  Hmed->SetLineColor(38);
  Hmh->SetLineColor(8);
  Hhigh->SetLineColor(kOrange);
 
  Hlow->SetMarkerColor(46);
  Hmed->SetMarkerColor(38);
  Hmh->SetMarkerColor(8);
  Hhigh->SetMarkerColor(kOrange);

  Hlow->SetMarkerStyle(23);
  Hmed->SetMarkerStyle(22);
  Hmh->SetMarkerStyle(21);
  Hhigh->SetMarkerStyle(20);

  Hlow->SetMarkerSize(1);
  Hmed->SetMarkerSize(1);
  Hmh->SetMarkerSize(1);
  Hhigh->SetMarkerSize(1);

  Width_t width=2;
  Hlow->SetLineWidth(width);
  Hmed->SetLineWidth(width);
  Hmh->SetLineWidth(width);
  Hhigh->SetLineWidth(width);

  if(logy){
    Hlow->SetMinimum(1E-2);
    Hmed->SetMinimum(1E-2);
    Hmh->SetMinimum(1E-2);
    Hhigh->SetMinimum(1E-2);
  }

  cout << "drawLSB" << endl;
  if (drawLSB) pypu->Draw(var+">>Hlow", selection1);
  cout << "drawMSB" << endl;
  if (drawMSB) pypu->Draw(var+">>Hmed", selection2);
  cout << "drawSB" << endl;
  if (drawSB)  pypu->Draw(var+">>Hmh",  selection3);
  cout << "drawSIG" << endl;
  if (drawSIG) pypu->Draw(var+">>Hhigh",selection4);
  gPad->SetRightMargin(0.1);
  gPad->SetLogy(logy);
  gPad->Modified();

  if (addOverflow) {
    Hlow->SetBinContent(nbins, Hlow->GetBinContent(nbins)+Hlow->GetBinContent(nbins+1));
    Hmed->SetBinContent(nbins, Hmed->GetBinContent(nbins)+Hmed->GetBinContent(nbins+1));
    Hmh->SetBinContent(nbins, Hmh->GetBinContent(nbins)+Hmh->GetBinContent(nbins+1));
    Hhigh->SetBinContent(nbins, Hhigh->GetBinContent(nbins)+Hhigh->GetBinContent(nbins+1));
  }
  
  if (Hlow->Integral()>0) Hlow->Scale( 1.0 / Hlow->Integral());
  if (Hmed->Integral()>0) Hmed->Scale( 1.0 / Hmed->Integral());
  if (Hmh->Integral()>0) Hmh->Scale( 1.0 / Hmh->Integral());
  if (Hhigh->Integral()>0) Hhigh->Scale( 1.0 / Hhigh->Integral());
  
  if (var=="min_delta_phi_met"||var=="min_delta_phi_met_loose_jets")  Hhigh->SetXTitle("#Delta #phi_{min} [rad.]");
  else if (var=="bestTopMass")  {
    TString title="best 3-jet mass (GeV)";
    Hhigh->SetXTitle(title);
    Hmh->SetXTitle(title);
    Hmed->SetXTitle(title);
    Hlow->SetXTitle(title);
  }
  else if (var.Contains("min_delta_phi_met_N")) {
    Hhigh->SetXTitle("#Delta #hat{#phi}_{N}^{min}");
  }
  else {
    Hhigh->SetXTitle(var);
  }
  TString ytitle="(a.u.)";
  Hhigh->SetYTitle(ytitle);
  Hmh->SetYTitle(ytitle);
  Hmed->SetYTitle(ytitle);
  Hlow->SetYTitle(ytitle);
  //TString thetitle=btag.GetTitle();
  TString thetitle="";
  //  thetitle += " (fail minDeltaPhi)";
  Hhigh->SetTitle(thetitle);
  Hmh->SetTitle(thetitle);
  Hmed->SetTitle(thetitle);
  Hlow->SetTitle(thetitle);

  TString drawopt="hist e";
  if (drawSIG)  {Hhigh->Draw(drawopt); drawopt="hist e SAME"; if (customMax>0) Hhigh->SetMaximum(customMax);}
  if (drawSB)   {Hmh->Draw(drawopt); drawopt="hist e SAME";   if (customMax>0) Hmh->SetMaximum(customMax);}
  if (drawMSB)  {Hmed->Draw(drawopt); drawopt="hist e SAME";  if (customMax>0) Hmed->SetMaximum(customMax);}
  if (drawLSB)  {Hlow->Draw(drawopt); drawopt="hist e SAME";  if (customMax>0) Hlow->SetMaximum(customMax);}

//   if (var=="minDeltaPhi") {
//     Hhigh->SetMinimum(0);
//     Hhigh->GetXaxis()->SetRangeUser(0,2);
//   }

  TLegend * leg = 0;
  if(logy) leg = new TLegend(0.38,0.65,0.8,0.85);
  else {leg = new TLegend(0.38,0.55,0.8,0.85);}
  leg->SetFillColor(0);
  leg->SetBorderSize(0);
  leg->SetLineStyle(0);
  leg->SetFillStyle(0);
  leg->SetTextFont(132);
  leg->SetTextSize(.04);
  if(logy) leg->SetTextSize(0.03);
  char label[100];
  if (drawLSB)  {
    sprintf(label,"E_{T}^{miss} < 75 GeV (#mu=%3.2f)",Hlow->GetMean());
    leg->AddEntry(Hlow,label);
  }
  if (drawMSB)  {
    sprintf(label,"75 < E_{T}^{miss} < 150 GeV (#mu=%3.2f)",Hmed->GetMean());
    leg->AddEntry(Hmed,label);
  } 
  if (drawSB)   {
    sprintf(label,"150 < E_{T}^{miss} < 225 Ge (#mu=%3.2f)",Hmh->GetMean());
    leg->AddEntry(Hmh,label);
  }
  if (drawSIG)  {
    sprintf(label,"E_{T}^{miss} > 225 GeV (#mu=%3.2f)",Hhigh->GetMean());
   leg->AddEntry(Hhigh,label);
  }
  leg->Draw();

  // TLatex* text1=0;
  // text1 = new TLatex(3.570061,23.08044,"CMS Simulation");
  // text1->SetNDC();
  // text1->SetTextAlign(13);
  // text1->SetX(0.45);
  // text1->SetY(.9);
  // text1->SetTextFont(132);
  // text1->SetTextSizePixels(24);
  // text1->Draw();

  if (doRatio) {
    Hratio->Divide(Hmh,Hlow);
    Hratio->SetLineWidth(2);
    thecanvas->cd(2);
    Hratio->Draw();
    Hratio->SetMinimum(0);
    Hratio->SetMaximum(3);
    TLine* l1 = new TLine(min,1,max,1);
    l1->SetLineColor(kMagenta);
    l1->SetLineWidth(2);
    l1->Draw();
    cout<<"KS test results = "<<Hmh->KolmogorovTest(Hlow)<<endl;
  }

//   double chi2=0;
//   for (int i=1; i<=nbins; i++) {
//     double denom=Hlow->GetBinError(i)*Hlow->GetBinError(i) + Hmh->GetBinError(i)*Hmh->GetBinError(i);
//     double c2= denom>0 ? pow( Hlow->GetBinContent(i) - Hmh->GetBinContent(i) ,2) / denom : 0;
//     chi2+=c2;
//   }

//   cout<<"Hand chi^2 = "<<chi2<<endl;
//   Hlow->Chi2Test(Hmh,"WW p");

  if (plotTitle=="") {
    if(logy) {thecanvas->Print("macros/qcd_control/plots/METcorrelation_"+var+"_logy.png");thecanvas->Print("macros/qcd_control/plots/METcorrelation_"+var+"_logy.pdf");}
    else {thecanvas->Print("macros/qcd_control/plots/METcorrelation_"+var+".png"); thecanvas->Print("macros/qcd_control/plots/METcorrelation_"+var+".pdf"); }
  }  
  else {
    if(logy) {thecanvas->Print("macros/qcd_control/plots/"+plotTitle+"_logy.png");thecanvas->Print("macros/qcd_control/plots/"+plotTitle+"_logy.pdf");}
    else {thecanvas->Print("macros/qcd_control/plots/"+plotTitle+".png"); thecanvas->Print("macros/qcd_control/plots/"+plotTitle+".pdf"); }
  }

  delete pypu;
  delete Hlow;
  delete Hmed;
  delete Hmh;
  delete Hhigh;
  delete Hratio;
  delete thecanvas;
}
Esempio n. 6
0
// -----------------------------------------------------------------------------
//  
int qcdBkgdEst_new() {

//   int nn = 100;
//   std::vector<float> xx;
//   std::vector<float> yy;
//   for ( uint i = 0; i < nn; ++i ) { xx.push_back( i*100. ); }
//   for ( uint ilumi = 0; ilumi < nn; ++ilumi ) { 
  
  bool plots = true;

  // 0 = false (force to gaussian), 1 = true, 2 = for prescales
  int use_sumw2 = 2; 
  
  std::string label = "";

  //int last_bin = 7;
  
  setTDRStyle();
  
  // Misc
  bool efficiency = false;

  enum choices { PLOT_NUMERATOR=1, PLOT_DENOMINATOR=2, PLOT_RATIO=5 };
  int choice = 5;
  bool min_max_with_errors = true;

  bool use_meff = false;
  
  double axis_offset = 2.;
  
  bool simulation = false; 
  
  // Some analysis defaults
  double offset = 0.;
  //double pt1_default = 100.;
  //double pt2_default = 100.;
  //double pt3_default = 50.;
  //double ht_default = 375. + offset;
  //double meff_default = ht_default + pt3_default;
  //double x1_default = pt1_default / meff_default;
  //double x2_default = pt2_default / meff_default;
  //double x3_default = pt3_default / meff_default ;
  //double x3_factor = ( 1. - x3_default ) / ( x3_default );

  std::string dir = "/vols/cms04/bainbrid/qcd/stable/SUSY2/results/";
  
  //std::string histo = "HtAfterAlphaT";
  //std::string histo = "HtAfterRecHit";
  std::string histo = "HtAfterBaby";
  
  std::vector<double> at;
  at.push_back(0.51);
  at.push_back(0.52);
  at.push_back(0.53);
  at.push_back(0.54);
  at.push_back(0.55);
  //at.push_back(0.60);
  const uint nat = at.size();

  std::vector<int> multi;
  multi.push_back(-2);
  const uint nmulti = multi.size();
  
  double ht_min = 0.;
  double ht_max = 0.;
  int nht = 20; //@@ number of bins
  std::vector<double> ht;
  std::vector<double> ht_step;
  
  // override histo binning
  if ( true ) { 
    ht.push_back(275.); 
    ht.push_back(325.); 
    for ( uint iht = 0; iht <= 6; ++iht ) { ht.push_back(375.+iht*100.); }
    //for ( uint iht = 0; iht <= 8; ++iht ) { ht.push_back(300.+iht*100.); }
    nht = ht.size() - 1; 
    ht_min = ht.front() + offset;
    ht_max = ht.back() + offset;
  }
  
  // -----------------------------------------------------------------------------
  // -----------------------------------------------------------------------------
  // -----------------------------------------------------------------------------

  StringVV files;
  
  bool test = true;
  if ( test ) {
    //std::string trunk = dir + "v02/Ratio__";
    //StringV q; q.push_back(trunk+"data.root"); files.push_back(q);
    //StringV q1; q1.push_back(dir + "v19/Ratio__data.root"); files.push_back(q1);
     StringV q3; q3.push_back(dir + "v21/Ratio__data.root"); files.push_back(q3);
     StringV q1; q1.push_back(dir + "v26/Ratio__data_1fb.root"); files.push_back(q1);
     StringV q2; q2.push_back(dir + "v22/Ratio__data.root"); files.push_back(q2);
    //StringV q; q.push_back("../python/Ratio_QCDPY.root"); 
    //StringV w(q); w.push_back(trunk+"wjets.root");
    //StringV z(q); z.push_back(trunk+"zinv.root");
    //StringV tt(q); tt.push_back(trunk+"ttbar.root");
  }
  
  bool results = false;
  if ( results ) {

    std::string trunk = dir + "v08/Ratio__";
    StringV q; q.push_back(trunk+"qcdmg.root"); 
    
    StringV sm(q); 
    sm.push_back(trunk+"wjets.root");
    sm.push_back(trunk+"zinv.root");
    sm.push_back(trunk+"ttbar.root");
    files.push_back(sm);

    StringV sm1(q); 
    sm1.push_back(trunk+"wjets_incl.root");
    sm1.push_back(trunk+"zinv.root");
    sm1.push_back(trunk+"ttbar.root");
    files.push_back(sm1);
    
    //StringV lm6(sm); lm6.push_back(trunk+"lm6.root"); files.push_back(lm6);
    StringV wi(q); wi.push_back(trunk+"wjets_incl.root"); files.push_back(wi);
    StringV w(q); w.push_back(trunk+"wjets.root"); files.push_back(w);
    StringV z(q); z.push_back(trunk+"zinv.root"); files.push_back(z);
    StringV tt(q); tt.push_back(trunk+"ttbar.root"); files.push_back(tt);
    //StringV t(q); t.push_back(trunk+"top.root"); files.push_back(t);
     
    files.push_back(StringV(1,dir+"v08/Ratio__data.root"));

//     std::string trunk = dir + "v36/Ratio__";
//     StringV sm1; 
//     sm1.push_back(trunk+"qcdpy.root");
//     //sm1.push_back(trunk+"wjets.root");
//     sm1.push_back(trunk+"zinv.root");
//     sm1.push_back(trunk+"ttbar.root");
//     sm1.push_back(trunk+"top.root");
//     trunk = dir + "v37/Ratio__";
//     StringV sm2; 
//     sm2.push_back(trunk+"qcdpy.root");
//     sm2.push_back(trunk+"wjets.root");
//     sm2.push_back(trunk+"zinv.root");
//     sm2.push_back(trunk+"ttbar.root");
//     trunk = dir + "v40/Ratio__";
//     StringV sm3; 
//     sm3.push_back(trunk+"qcdpy.root");
//     sm3.push_back(trunk+"wjets.root");
//     sm3.push_back(trunk+"zinv.root");
//     sm3.push_back(trunk+"ttbar.root");
//     files.push_back(sm1);
//     files.push_back(sm2);
//     files.push_back(sm3);

  }
  
  const uint nfile = files.size();
  
  std::vector<std::string> his;
  if ( his.size() < nfile ) { his.resize(nfile,histo); }
  
  std::vector<std::string> type;

  if ( test ) { 
//     type.push_back("1");
//     type.push_back("2");
    //type.push_back("Data");
    type.push_back("HT-aT cross triggers");
    type.push_back("HT-MHT cross triggers");
    type.push_back("HT prescaled triggers");
    //type.push_back("QcdMg");
    //type.push_back("Nominal");
    //type.push_back("Alternative");
  }

  if ( results ) {
    //type.push_back("SM + LM6 (Spring11)");
    //type.push_back("Spring11");
    //type.push_back("Summer11(Wincl)");
    //type.push_back("Summer11(W300)");
    type.push_back("SM (W+jets HT-binned)");
    type.push_back("SM (W+jets inclusive)");
//     type.push_back("SM   ");
    type.push_back("Wjets (incl)");
    type.push_back("Wjets (HT-binned)");
    type.push_back("Zinv ");
    type.push_back("TTbar");
    //type.push_back("Single top  ");
    type.push_back("Data ");
  }
  
  if ( type.size() < nfile ) { type.resize(nfile,"unknown"); }
  
  double lumi = 4650.;
  std::vector<double> lumis;

  if ( test ) {
    lumi = 4650;
    lumis.push_back(100.);
    //lumis.push_back(100.*lumi/1140.);
    lumis.push_back(100.);
    //lumis.push_back(lumi);
  }

  if ( results ) { 
    double tmp = 4650.;//xx[ilumi];
    lumi = tmp;
    lumis.push_back(tmp);
    lumis.push_back(tmp);
    lumis.push_back(tmp);
    lumis.push_back(tmp);
    lumis.push_back(tmp);
    lumis.push_back(tmp);
    lumis.push_back(100.);
  }

  if ( lumis.size() < nfile ) { lumis.resize(nfile,100.); }
  
  // Which file is the data file
  int data_file = -1;
  for ( uint itype = 0; itype < nfile; ++itype ) {
    if ( type[itype] == "data" || 
	 type[itype] == "Data" ) { 
      data_file = itype; 
      break;
    }
  }
//   if ( data_file == -1 ) { 
//     data_file = 0;
//     std::cout << "Problem identifying data file!" << std::endl;
//   }
  
  std::vector<int> style;

  if ( test ) {
    style.push_back(20);
    style.push_back(24);
    style.push_back(25);
  }

  if ( results ) {
    style.push_back(24);
    style.push_back(25);
    style.push_back(26);
    style.push_back(28);
    style.push_back(27);
    style.push_back(30);
    style.push_back(20);
  }

  if ( style.size() < nfile ) { style.resize(nfile,25); }
  
  std::vector<double> size;
  if ( size.size() < nfile ) { size.resize(nfile,1.5); }
  
  std::vector<int> col;

  if ( test ) {
    col.push_back(1);
    col.push_back(2);
    col.push_back(4);
  }

  if ( results ) {
    col.push_back(2);
    col.push_back(4);
    col.push_back(6);
    col.push_back(6);
    col.push_back(6);
    col.push_back(6);
    col.push_back(1);
  }

  if ( col.size() < nfile ) { col.resize(nfile,1); }

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

  DoubleVVVV numer; resize( numer, nfile, nmulti, nat, nht );
  DoubleVVVV numer_errh; resize( numer_errh, nfile, nmulti, nat, nht );
  DoubleVVVV numer_errl; resize( numer_errl, nfile, nmulti, nat, nht );
  DoubleVVVV denom; resize( denom, nfile, nmulti, nat, nht );
  DoubleVVVV denom_errh; resize( denom_errh, nfile, nmulti, nat, nht );
  DoubleVVVV denom_errl; resize( denom_errl, nfile, nmulti, nat, nht );
  DoubleVVVV ratio; resize( ratio, nfile, nmulti, nat, nht );
  DoubleVVVV errh; resize( errh, nfile, nmulti, nat, nht );
  DoubleVVVV errl; resize( errl, nfile, nmulti, nat, nht );
  IntVVV length; resize( length, nfile, nmulti, nat );
  
  // Min/max values for ratios
  DoubleVV min; min.resize( nmulti, DoubleV( nat, 0. ) );
  DoubleVV max; max.resize( nmulti, DoubleV( nat, 0. ) );
  
  std::cout << " nfile: " << nfile
	    << " nmulti: " << nmulti
	    << " nat: " << nat
	    << " nht: " << nht
	    << " total: " << nfile*nmulti*nat*nht
	    << std::endl;
  
  // Init arrays
  for ( uint imulti = 0; imulti < nmulti; ++imulti ) {
    for ( uint iat = 0; iat < nat; ++iat ) {
      for ( uint ifile = 0; ifile < nfile; ++ifile ) {
	for ( int iht = 0; iht < nht; ++iht ) {
	  numer[ifile][imulti][iat][iht] = 0.;
	  numer_errh[ifile][imulti][iat][iht] = 0.;
	  numer_errl[ifile][imulti][iat][iht] = 0.;
	  denom[ifile][imulti][iat][iht] = 0.;
	  denom_errh[ifile][imulti][iat][iht] = 0.;
	  denom_errl[ifile][imulti][iat][iht] = 0.;
	  ratio[ifile][imulti][iat][iht] = 0.;
	  errh[ifile][imulti][iat][iht] = 0.;
	  errl[ifile][imulti][iat][iht] = 0.;
	}
	length[ifile][imulti][iat] = 0;
      }
      min[imulti][iat] = 0.;
      max[imulti][iat] = 0.;
    }
  }
  
  std::cout << " CALCULATING RATIOS..." << std::endl;
  calcRatio( nfile, nmulti, nat, nht, 
	     his, files, lumis, 
	     multi, at, ht, ht_min, ht_max, 
	     numer, numer_errh, numer_errl, 
	     denom, denom_errh, denom_errl, 
	     ratio, errh, errl, length,
	     label,
	     efficiency, use_sumw2,
	     data_file );
  
  ht_step.clear();
  for ( int iht = 0; iht < nht; ++iht ) { ht_step.push_back( ht[iht+1] - ht[iht] ); }
  
//   std::cout << " size " << ht.size()
// 	    << " nbins " << nht 
// 	    << " htmin " << ht_min 
// 	    << " htmax " << ht_max
// 	    << std::endl;
//   for ( int iht = 0; iht <= nht; ++iht ) {
//     std::cout << " ibin " << iht
// 	      << " ht " << ht[iht]
// 	      << " htstep " << (iht<nht?ht_step[iht]:0.)
// 	      << std::endl;
//   }

//   // -----------------------------------------------------------------------------
//   // -----------------------------------------------------------------------------
//   // -----------------------------------------------------------------------------
  
  // Print numbers
  bool print = true;
  if (print) {
    for ( uint ifile = 0; ifile < nfile; ++ifile ) {
      for ( uint imulti = 0; imulti < nmulti; ++imulti ) {
	for ( uint iat = 0; iat < nat; ++iat ) {
	  for ( int iht = 0; iht < nht; ++iht ) {
	    double n = numer[ifile][imulti][iat][iht];
	    double neh = numer_errh[ifile][imulti][iat][iht];
	    double nel = numer_errl[ifile][imulti][iat][iht];
	    double d = denom[ifile][imulti][iat][iht];
	    double deh = denom_errh[ifile][imulti][iat][iht];
	    double del = denom_errl[ifile][imulti][iat][iht];
	    double r = ratio[ifile][imulti][iat][iht];
	    double eh = errh[ifile][imulti][iat][iht];
	    double el = errl[ifile][imulti][iat][iht];
	    std::cout
	      //<< " PRINT: "
	      << "" << type[ifile] << ""
	      //<< " njets: " << multi[imulti]
	      << " aT: " << at[iat]
	      << std::fixed << std::setprecision(0)
		      << " HT: " << ht[iht]
	      << std::scientific << std::setprecision(3)
 		      << ", pass: "******" + " << neh
  		      << " - " << nel
// 	      << ",pass," << n
// 	      << "," << neh
// 	      << "," << nel
	      //<< " (" << ( n > 0. ? sqrt(n)/n : -1. ) << ")" 
	      << ", fail: " << d
	      << " + " << deh
	      << " - " << del
// 	      << ",fail," << d
// 	      << "," << deh
// 	      << "," << del
	      //<< " (" << ( d > 0. ? sqrt(d)/d : -1. ) << ")" 
	      //<< " R: " << ( d > 0. ? n/d : -1. )
	      //<< " E: " << ( d > 0. ? sqrt(n*(n/(n+d))*(1-(n/(n+d)))) : -1. )
  	      << ", ratio: " << r
  	      << " + " << eh
  	      << " - " << el
// 	      << ", ratio ," << r
// 	      << "," << eh
// 	      << "," << el
	      //  		      << " (" << int(( r > 0. ? eh/r : -1. )*100.) << "," 
	      //  		      << int(( r > 0. ? el/r : -1. )*100.) << ")" 
		      << std::endl;
	  }
	}
      }
    }
  }

  // -----------------------------------------------------------------------------
  // For Ted
  
  bool print_ted = true;
  if (print_ted) {
    for ( uint ifile = 0; ifile < nfile; ++ifile ) {
      for ( uint imulti = 0; imulti < nmulti; ++imulti ) {
	for ( uint iat = 0; iat < nat; ++iat ) {
	  std::stringstream ted;
	  ted << " sample: \"" << type[ifile] << "\""
	      << " Multiplicity: " << multi[imulti]
	      << " AlphaT: " << at[iat] 
	      << std::endl;
	  ted << "\"had\":\t\t" << float(lumi) << ", #lumi" << std::endl;
	  ted << "\"hadBulk\":\t" << float(lumi) << ", #lumi" << std::endl;

	  // Bulk
	  ted << "\"nHadBulk\":\t(";
	  for ( int iht = 0; iht < nht; ++iht ) {
	    double d = denom[ifile][imulti][iat][iht];
	    ted << std::setw(9) << std::scientific << std::setprecision(3) << d << ", ";
	  }
	  ted << ")" << std::endl;

	  // Tail
	  ted << "\"nHad\":\t\t(";
	  for ( int iht = 0; iht < nht; ++iht ) {
	    double n = numer[ifile][imulti][iat][iht];
	    ted << std::setw(9) << std::scientific << std::setprecision(3) << n << ", ";
	  }
	  ted << ")" << std::endl;

	  // Mean HT
	  ted << "self._htMeans = (";
	  for ( int iht = 0; iht < nht; ++iht ) {
	    ted << std::setw(9) << std::scientific << std::setprecision(3) << ht[iht] << ", ";
	  }
	  ted << ")" << std::endl;
	  std::cout << ted.str() << std::endl;

	}
      }
    }
  }
  
  // -----------------------------------------------------------------------------
  if (!plots) return 0;
  
  // Variable to plot
  std::cout << " EXTRACTING VALUES TO PLOT..." << std::endl;
  double valx[nfile][nmulti][nat][nht];
  double errxh[nfile][nmulti][nat][nht];
  double errxl[nfile][nmulti][nat][nht];
  double valy[nfile][nmulti][nat][nht];
  double erryh[nfile][nmulti][nat][nht];
  double erryl[nfile][nmulti][nat][nht];
  for ( uint ifile = 0; ifile < nfile; ++ifile ) {
    for ( uint imulti = 0; imulti < nmulti; ++imulti ) {
      for ( uint iat = 0; iat < nat; ++iat ) {
	for ( int iht = 0; iht < nht; ++iht ) {
	  valx[ifile][imulti][iat][iht] = 0.;
	  errxh[ifile][imulti][iat][iht] = 0.;
	  errxl[ifile][imulti][iat][iht] = 0.;
	  valy[ifile][imulti][iat][iht] = 0.;
	  erryh[ifile][imulti][iat][iht] = 0.;
	  erryl[ifile][imulti][iat][iht] = 0.;
	  double width = (1.*ht_step[nht-1]) / (1.*ht_step[iht]);
	  //std::cout << " iht " << iht << " width " << width << std::endl;
	  if ( choice == PLOT_NUMERATOR ) {
	    valx[ifile][imulti][iat][iht] = ht[iht] + ht_step[iht]/2. + axis_offset*ifile;
	    errxh[ifile][imulti][iat][iht] = ht_step[iht]/2. + axis_offset*ifile;
	    errxl[ifile][imulti][iat][iht] = ht_step[iht]/2. - axis_offset*ifile;
	    valy[ifile][imulti][iat][iht] = numer[ifile][imulti][iat][iht] * width;
	    erryh[ifile][imulti][iat][iht] = numer_errh[ifile][imulti][iat][iht] * width;
	    erryl[ifile][imulti][iat][iht] = numer_errl[ifile][imulti][iat][iht] * width;
	  } else if ( choice == PLOT_DENOMINATOR ) {
	    valx[ifile][imulti][iat][iht] = ht[iht] + ht_step[iht]/2. + axis_offset*ifile;
	    errxh[ifile][imulti][iat][iht] = ht_step[iht]/2. + axis_offset*ifile;
	    errxl[ifile][imulti][iat][iht] = ht_step[iht]/2. - axis_offset*ifile;
	    valy[ifile][imulti][iat][iht] = denom[ifile][imulti][iat][iht] * width;
	    erryh[ifile][imulti][iat][iht] = denom_errh[ifile][imulti][iat][iht] * width;
	    erryl[ifile][imulti][iat][iht] = denom_errl[ifile][imulti][iat][iht] * width;
	  } else if ( choice == PLOT_RATIO ) {
	    //if ( iht < length[ifile][imulti][iat] ) {
	    valx[ifile][imulti][iat][iht] = ht[iht] + ht_step[iht]/2. + axis_offset*ifile;
	    errxh[ifile][imulti][iat][iht] = ht_step[iht]/2. + axis_offset*ifile;
	    errxl[ifile][imulti][iat][iht] = ht_step[iht]/2. - axis_offset*ifile;
	    valy[ifile][imulti][iat][iht] = ratio[ifile][imulti][iat][iht];
	    erryh[ifile][imulti][iat][iht] = errh[ifile][imulti][iat][iht];
	    erryl[ifile][imulti][iat][iht] = errl[ifile][imulti][iat][iht];
	    //}
	  }
	}
      }
    }
  }

  if ( choice == PLOT_NUMERATOR ) { 
    std::cout << "Plotting numerator..." << std::endl;
  } else if ( choice == PLOT_DENOMINATOR ) { 
    std::cout << "Plotting denominator..." << std::endl;
  } else if ( choice == PLOT_RATIO ) { 
    std::cout << "Plotting ratio..." << std::endl;
  } else { 
    std::cout << "Plotting unknown!!..." << std::endl;
  }
    
  // -----------------------------------------------------------------------------
  // Calculate min and max values for y-axis (ratio)
    
  for ( uint imulti = 0; imulti < nmulti; ++imulti ) {
    for ( uint iat = 0; iat < nat; ++iat ) {
      min[imulti][iat] = 1.e12;
      max[imulti][iat] = 1.e-12;
      for ( uint ifile = 0; ifile < nfile; ++ifile ) {
	for ( int iht = 0; iht < nht; ++iht ) {
	  if ( ht[iht] < ht_min && ht[iht] > ht_max ) { continue; }
	  double ymin = valy[ifile][imulti][iat][iht] - erryl[ifile][imulti][iat][iht];
	  double ymax = valy[ifile][imulti][iat][iht] + erryh[ifile][imulti][iat][iht];
	  if ( valy[ifile][imulti][iat][iht] > 0. &&
	       valy[ifile][imulti][iat][iht] < min[imulti][iat] ) {
	    if ( min_max_with_errors && ymin > 0. && ymin < min[imulti][iat] ) { min[imulti][iat] = ymin; }
	    else { min[imulti][iat] = valy[ifile][imulti][iat][iht]; }
	  }
	  if ( valy[ifile][imulti][iat][iht] > 0. &&
	       valy[ifile][imulti][iat][iht] > max[imulti][iat] ) {
	    if ( min_max_with_errors && ymax > 0. && ymax > max[imulti][iat] ) { max[imulti][iat] = ymax; }
	    else { max[imulti][iat] = valy[ifile][imulti][iat][iht]; }
	  }
	}
      }
    }
  }
    
  if (false) {
    for ( uint ifile = 0; ifile < nfile; ++ifile ) {
      for ( uint imulti = 0; imulti < nmulti; ++imulti ) {
	for ( uint iat = 0; iat < nat; ++iat ) {
	  std::cout << " sample:\"" << type[ifile] << "\""
		    << " multi: " << multi[imulti]
		    << " aT:" << at[iat]
		    << " min:" << min[imulti][iat]
		    << " max:" << max[imulti][iat]
		    << std::endl;
	}
      }
    }
  }
    
  if (false) {
    for ( uint ifile = 0; ifile < nfile; ++ifile ) {
      for ( uint imulti = 0; imulti < nmulti; ++imulti ) {
	for ( uint iat = 0; iat < nat; ++iat ) {
	  std::cout << " PLOTTING:"
		    << " sample:\"" << type[ifile] << "\""
		    << " multi: " << multi[imulti]
		    << " aT:" << at[iat]
		    << " valy: " << valy[ifile][imulti][iat]
		    << " erryh: " << erryh[ifile][imulti][iat]
		    << " erryl: " << erryl[ifile][imulti][iat]
		    << std::endl;
	}
      }
    }
  }

  // -----------------------------------------------------------------------------
  // Check number of pt and ht bins are the same
  std::cout << " CREATING PLOTS..." << std::endl;

  std::vector<double> rat;
  std::vector<float> fits;
      
  for ( uint imulti = 0; imulti < nmulti; ++imulti ) {
	
    for ( uint iat = 0; iat < nat; ++iat ) {
	  
      std::string name;
      if ( choice == PLOT_NUMERATOR ) { name = "Pass"; } 
      else if ( choice == PLOT_DENOMINATOR ) {
	if ( efficiency ) { name = "Total"; }
	else { name = "Fail"; }
      }
      else if ( choice == PLOT_RATIO ) { 
	if ( efficiency ) { name = "Eff"; }
	else { name = "Ratio"; }
      } 
      else { name = "Unknown"; } 
  
      std::stringstream ss_canvas;
      ss_canvas << "Multi";
      if ( multi[imulti] >= 0 ) { ss_canvas << multi[imulti]; }
      else { ss_canvas << abs(multi[imulti]) << "Incl"; }
      ss_canvas << "_AlphaT" << at[iat];

      gStyle->SetOptFit(111);
      TCanvas* canvas = 0;
      TLegend* legend = 0;
      TLatex* prelim = 0;
      TLatex* lumitxt = 0;
      TMultiGraph* mg = 0;

	canvas = new TCanvas(TString(name+"_"+ss_canvas.str()),
			     TString(name+"_"+ss_canvas.str()),800,600);
	    
	canvas->SetFillColor(0);
	canvas->SetLineColor(0); 
	    
	canvas->SetLeftMargin(0.17);
	    
	legend = new TLegend( 0.65, 0.7-(nfile*0.04), 0.85, 0.7, NULL, "brNDC" );
	legend->SetTextSize(0.035);
	legend->SetFillColor(0);
	legend->SetLineColor(0); 
	legend->SetShadowColor(0); 

	if (!simulation) {
	  prelim = new TLatex( 0.20, 0.88, "#scale[0.8]{CMS preliminary 2011}" );
	} else {
	  prelim = new TLatex( 0.20, 0.88, "#scale[0.8]{CMS simulation 2011}" );
	}
	prelim->SetTextSize(0.035);
	prelim->SetNDC();
	std::stringstream ssl; 
	ssl << "#scale[0.8]{#int L dt = " << std::setprecision(3) << lumi/1000. << " fb^{-1}, #sqrt{s} = 7 TeV}";
	lumitxt = new TLatex( 0.68, 0.88, ssl.str().c_str() );
	lumitxt->SetTextSize(0.035);
	lumitxt->SetNDC();
	    
	mg = new TMultiGraph();
	  
      std::stringstream ss_axis;
      if ( choice == PLOT_NUMERATOR ) { 
	ss_axis << "N(#alpha_{T}>" << at[iat] << ") / " << ht_step[nht-1] << " GeV"; 
      } else if ( choice == PLOT_DENOMINATOR ) { 
	if ( efficiency ) { ss_axis << "Total"; }
	else { ss_axis << "N(#alpha_{T}<" << at[iat] << ") / " << ht_step[nht-1] << " GeV"; }
      } else if ( choice == PLOT_RATIO ) { 
	if ( !efficiency ) { 
	  //ss_axis << "R_{#alpha_{T}}(" << at[iat] << ")"; 
	  if ( iat+1 < nat ) { 
	    ss_axis << "N(" << at[iat] << "<#alpha_{T}<" << at[iat+1] << ") / N(#alpha_{T}<" << at[iat] << ")"; 
	  } else { 
	    ss_axis << "N(#alpha_{T}>" << at[iat] << ") / N(#alpha_{T}<" << at[iat] << ")"; 
	  } 
	}
	else { ss_axis << "#varepsilon(#alpha_{T}=" << at[iat] << ")"; }
      } 
      else { ss_axis << "a.u."; }
	  
      std::stringstream ss_flat;
      std::stringstream ss_line;
      std::stringstream ss_expo;
	  
      for ( uint ifile = 0; ifile < nfile; ++ifile ) {
	  
	std::stringstream ss_histo;
	ss_histo << name << "_" << type[ifile] << "_" << ss_canvas.str();

	gStyle->SetOptFit(0);
	TGraphAsymmErrors* gr = new TGraphAsymmErrors(nht,
						      valx[ifile][imulti][iat],
						      valy[ifile][imulti][iat],
						      errxh[ifile][imulti][iat],
						      errxl[ifile][imulti][iat],
						      erryl[ifile][imulti][iat],
						      erryh[ifile][imulti][iat]);

	// Fitting
	if (true) {
	  TGraphAsymmErrors* tmp_gr = new TGraphAsymmErrors(*gr);

	  //tmp_gr->Fit("pol0","Q0","",valx[ifile][imulti][iat][0]-1.e-6,valx[ifile][imulti][iat][last_bin]+1.e-6);
	  tmp_gr->Fit("pol0","Q0","",ht_min-1.e-6,ht_max+1.e-6);
	  TF1* fit_c = (TF1*)tmp_gr->FindObject("pol0");
	  if ( fit_c ) {
	    if ( ifile == 0 ) { ss_flat << "Constant (y=A):" << std::endl; }
	    ss_flat << "" << type[ifile] << " "
		    << std::setprecision(3)
		    << fit_c->GetChisquare() << "/"
		    << std::setprecision(0)
		    << fit_c->GetNDF() << " ("
		    << std::setprecision(3)
		    << fit_c->GetProb() << ") "
		    << std::endl
		    << "" << type[ifile] << " "
		    << std::scientific << std::setprecision(3)
		    << "A: " << fit_c->GetParameter(0) << " +/- " << fit_c->GetParError(0)
		    << std::endl;
	    //yy.push_back( fit_c->GetProb() ); //@@ ADDED
	    if ( (int)ifile == data_file ) { fits.push_back( fit_c->GetProb() ); }
	    //rat.push_back( fit_c->GetParameter(0) );
	  } else {
	    //yy.push_back( 0. ); //@@ ADDED
	    std::cout << " NULL PTR! " << std::endl;
	  }

	  //tmp_gr->Fit("pol1","Q0","",valx[ifile][imulti][iat][0]-1.e-6,valx[ifile][imulti][iat][last_bin]+1.e-6);
	  tmp_gr->Fit("pol1","Q0","",ht_min-1.e-6,ht_max+1.e-6);
	  TF1* fit_l = (TF1*)tmp_gr->FindObject("pol1");
	  if ( fit_l ) {
	    if ( ifile == 0 ) { ss_line << "Linear (y=A+Bx):" << std::endl; }
	    ss_line << "" << type[ifile] << " "
		    << std::setprecision(3)
		    << fit_l->GetChisquare() << "/"
		    << std::setprecision(0)
		    << fit_l->GetNDF() << " ("
		    << std::setprecision(3)
		    << fit_l->GetProb() << ") "
		    << std::endl
		    << "" << type[ifile] << " "
		    << std::scientific << std::setprecision(3)
		    << "A: " << fit_l->GetParameter(0) << " +/- " << fit_l->GetParError(0)
		    << " B: " << fit_l->GetParameter(1) << " +/- " << fit_l->GetParError(1)
		    << std::endl;
	    if ( (int)ifile == data_file ) { fits.push_back( fit_l->GetProb() ); }
	    //rat.push_back( fit_l->GetParameter(0) );
	  } else {
	    std::cout << " NULL PTR! " << std::endl;
	  }

	  //tmp_gr->Fit("expo","Q0","",valx[ifile][imulti][iat][0]-1.e-6,valx[ifile][imulti][iat][last_bin]+1.e-6);
	  //TF1* fit_e = new TF1("expo+expo", tmp_gr->FindObject("expo");
	  //tmp_gr->Fit("expo","Q0","",ht_min-1.e-6,ht_max+1.e-6);
	  tmp_gr->Fit("expo","Q0","",325.-1.e-6,675.+1.e-6);
	  TF1* fit_e = (TF1*)tmp_gr->FindObject("expo");
	  if ( fit_e ) {
	    if ( ifile == 0 ) { ss_expo << "Exponential (y=e^{A+kx}):" << std::endl; }
	    ss_expo << "" << type[ifile] << " "
		    << std::fixed
		    << std::setprecision(3)
		    << fit_e->GetChisquare() << "/"
		    << std::setprecision(0)
		    << fit_e->GetNDF() << " ("
		    << std::setprecision(3)
		    << fit_e->GetProb() << ") "
		    << std::endl
		    << "" << type[ifile] << " "
		    << std::scientific << std::setprecision(3)
		    << "A: " << fit_e->GetParameter(0) << " +/- " << fit_e->GetParError(0)
		    << " k: " << fit_e->GetParameter(1) << " +/- " << fit_e->GetParError(1)
		    << std::endl;
	    if ( (int)ifile == data_file ) { fits.push_back( fit_e->GetProb() ); }
	    rat.push_back( fit_e->GetParameter(1) );
	  } else {
	    std::cout << " NULL PTR! " << std::endl;
	  }

	  //if (tmp_gr) delete tmp_gr;

	}

	for ( int ii = 0; ii < nht; ++ii ) {
	  double x = 0.;
	  double y = 0.;
	  gr->GetPoint(ii,x,y);
	  //if ( y == 0. ) { gr->SetPointEYhigh(ii,0.); gr->SetPointEYlow(ii,0.); }
	  if (false) {
	    std::cout << " sample:\"" << type[ifile] << "\""
		      << " multi: " << multi[imulti]
		      << " aT:" << at[iat]
		      << " HT:" << ht[ii]
		      << " ARRAY x: " << valx[ifile][imulti][iat][ii]
		      << " y: " << valy[ifile][imulti][iat][ii]
		      << " + " << erryh[ifile][imulti][iat][ii]
		      << " - " << erryl[ifile][imulti][iat][ii]
		      << " HISTO x: " << x
		      << " y: " << y
		      << " + " << gr->GetErrorYhigh(ii)
		      << " - " << gr->GetErrorYlow(ii)
		      << std::endl;
	  }
		
	}
	    
 	if ( nfile - ifile == 1 ) {
  	  //std::cout << ss_flat.str() << std::endl;
 	  //std::cout << ss_line.str() << std::endl;
 	  std::cout << ss_expo.str() << std::endl;
 	}

	mg->Add(gr,"p");
	
	std::stringstream ss_legend;
	ss_legend << type[ifile];
	legend->AddEntry( gr, TString(ss_legend.str()), "p" );
	
	gr->SetTitle(TString(ss_legend.str()));
	gr->SetMarkerStyle(style[ifile]);
	gr->SetMarkerSize(size[ifile]);
	gr->SetMarkerColor(col[ifile]);
	gr->SetLineColor(col[ifile]);
	
      } // ifile
	  
      mg->Draw("a");
      mg->GetXaxis()->SetTitle(label.c_str());
      if (!use_meff) mg->GetXaxis()->SetTitle("H_{T} (GeV)");
      else mg->GetXaxis()->SetTitle("M_{eff} (GeV)");
      mg->GetYaxis()->SetTitle(TString(ss_axis.str()));
      mg->GetYaxis()->SetTitleOffset(1.3);
      mg->GetXaxis()->SetRangeUser(ht_min+offset,ht_max+offset);
      mg->GetYaxis()->SetRangeUser(min[imulti][iat]/2.0,max[imulti][iat]*1.2);
      //else mg->GetYaxis()->SetRangeUser(0.,0.12e-3);
      //mg->GetYaxis()->SetNoExponent(true);
      
      //mg->GetXaxis()->SetRangeUser(250,450.);
      //mg->GetYaxis()->SetRangeUser(0.,25.e-6);
      //mg->GetYaxis()->SetRangeUser(0.,0.05e-3);
      //mg->GetYaxis()->SetRangeUser(0.,0.04e-3);
      canvas->SetLogy();
      
      //if      (choice==1) mg->GetYaxis()->SetRangeUser(0.1,1.e4);
      //else if (choice==2) mg->GetYaxis()->SetRangeUser(0.1,1.e8);
      
      legend->Draw("same");
      //prelim->Draw("same");
      //lumitxt->Draw("same");
      canvas->Update();
      
      std::stringstream ss_text;
      ss_text << "#alpha_{T} = " << at[iat];
      
      TLatex* text = new TLatex(0.5,0.92,TString(ss_text.str()));
      text->SetNDC(kTRUE);
      text->SetTextSize(0.04);
      //text->Draw();
      
      //canvas->SaveAs(TString(name+"_"+ss_canvas.str()+".C")); 
      //canvas->SaveAs(TString(name+"_"+ss_canvas.str()+".png")); 
      //canvas->SaveAs(TString(name+"_"+ss_canvas.str()+".pdf")); 

      //if (canvas) delete canvas;
      
    } // iat
  } // imulti
      
  int index = 0;
  std::vector<float> cuts;
  std::vector<float>::const_iterator ifit = fits.begin();
  std::vector<float>::const_iterator jfit = fits.end();
  for ( ; ifit != jfit; ++ifit ) { cuts.push_back(at[index]); index++; }
  //if ( !fits.empty() ) qcd(cuts,fits);
      
  // Draw RaT 
  if ( false && !rat.empty() ) {
    bool plot_ratio = false;
    setTDRStyle();
    gStyle->SetOptStat("emr");
    TCanvas* c2 = new TCanvas("RaTvsEwkComposition","RaTvsEwkComposition");
    c2->SetFillColor(0);
    c2->SetLineColor(0); 
    TH1D* diff = 0;
    if ( !plot_ratio ) { 
      diff = new TH1D("RaTvsEwkComposition","",1000,0.,1e-3); 
      //diff = new TH1D("RaTvsEwkComposition","",1000,-20.,0.); 
      for ( uint ifile = 0; ifile < nfile; ++ifile ) { 
	std::cout << "sample: " << type[ifile] << " fit: " << rat[ifile] << std::endl;
	diff->Fill( rat[ifile], 1. ); 
      }
    } else {
      diff = new TH1D("RaTvsEwkComposition","",200,0.6,1.4); 
      for ( uint ifile = 1; ifile < nfile; ++ifile ) { 
	std::cout << "sample: " << type[ifile] << " nominal: " << rat[0] << " ratio: " << rat[ifile]/rat[0] << std::endl;
	diff->Fill( rat[ifile]/rat[0], 1. ); 
      }
    }
    c2->cd();
    c2->SetRightMargin(0.12);
    c2->SetBottomMargin(0.15);
    diff->Draw("h");
    if (!plot_ratio) diff->GetXaxis()->SetTitle("Best fit value");
    else { 
      //diff->GetXaxis()->SetTitle("Best fit value relative to nominal");
      diff->GetXaxis()->SetTitle("R_{#alpha_{T}}^{(#pm15%)} / R_{#alpha_{T}}^{(nominal)}");
      diff->GetXaxis()->SetTitleOffset(1.1);
    }
    diff->GetYaxis()->SetTitle("Number of tests with #pm15%");
    if (!plot_ratio) c2->SaveAs("RaTvsEwkComposition.pdf"); 
    else c2->SaveAs("RaTvsEwkComposition_ratio.pdf"); 
  }


//   }

//   yy.resize(xx.size(),0.);

//   TCanvas* c1 = new TCanvas();
//   TGraph* gr = new TGraph(nn, &(xx.front()), &(yy.front()) );
//   c1->cd();
//   gr->Draw("ap");
//   //gr->SetBorderSize(0);
//   gr->SetTitle("Fit range: 325 < HT < 985");
//   gr->GetXaxis()->SetTitle("Integrated Lumi (pb^{-1})");
//   gr->GetYaxis()->SetTitle("p-value");
//   c1->SaveAs("tmp.C");
//   delete c1;

//   std::cout << std::endl;
//   for ( uint i = 0; i < nn; ++i ) { std::cout << xx[i] << std::endl; }
//   std::cout << std::endl;
//   for ( uint i = 0; i < nn; ++i ) { std::cout << yy[i] << std::endl; }
//   std::cout << std::endl;
  
  return 0;
  
}
Esempio n. 7
0
int QA_calm_plots_diff(const char* filename1, const char* filename2, const char* type = "PipPip", const char* type2 = "PipPip", bool ifSave = false)
{
  
  TFile* f1 = new TFile(filename1,"READ");
 
  TH2F* hevmultPID = ((TH2F*) f1->Get(Form("hevmultPID%s",type)));
  TH1D* heta  =  ((TH1D*) f1->Get(Form("heta%s",type)));
  TH1D* hpt   =  ((TH1D*) f1->Get(Form("hpt%s",type)));
  TH1D* hphiS =  ((TH1D*) f1->Get(Form("hphiS%s",type)));
  TH1D* hphiP =  ((TH1D*) f1->Get(Form("hphiP%s",type)));
  TH1D* hpid1 =  ((TH1D*) f1->Get(Form("hpid1%s",type)));
  TH1D* hpid2 =  ((TH1D*) f1->Get(Form("hpid2%s",type)));
  TH1D* hevmultAll = ((TH1D*) f1->Get(Form("hevmultAll%s",type)));
  TH1D* hevmult = ((TH1D*) f1->Get(Form("hevmult%s",type)));
  TH1D* hevweight = ((TH1D*) f1->Get(Form("hevweight%s",type)));
  TH1D* hevweighttaken = ((TH1D*) f1->Get(Form("hevweighttaken%s",type)));
  TH1D* hevweightdensity= ((TH1D*) f1->Get(Form("hevweightdensity%s",type)));
  TH1D* hptTotal   =  ((TH1D*) f1->Get(Form("hptTotal%s",type)));


  TFile* f2 = new TFile(filename2,"READ");
  TH2F* hevmultPID2 = ((TH2F*) f2->Get(Form("hevmultPID%s",type2)));
  TH1D* heta2  =  ((TH1D*) f2->Get(Form("heta%s",type2)));
  TH1D* hpt2   =  ((TH1D*) f2->Get(Form("hpt%s",type2)));
  TH1D* hphiS2 =  ((TH1D*) f2->Get(Form("hphiS%s",type2)));
  TH1D* hphiP2 =  ((TH1D*) f2->Get(Form("hphiP%s",type2)));
  TH1D* hpid12 =  ((TH1D*) f2->Get(Form("hpid1%s",type2)));
  TH1D* hpid22 =  ((TH1D*) f2->Get(Form("hpid2%s",type2)));
  TH1D* hevmultAll2 = ((TH1D*) f2->Get(Form("hevmultAll%s",type2)));
  TH1D* hevmult2 = ((TH1D*) f2->Get(Form("hevmult%s",type2)));
  TH1D* hevweight2 = ((TH1D*) f2->Get(Form("hevweight%s",type2)));
  TH1D* hevweighttaken2 = ((TH1D*) f2->Get(Form("hevweighttaken%s",type2)));
  TH1D* hevweightdensity2= ((TH1D*) f2->Get(Form("hevweightdensity%s",type2)));
  TH1D* hptTotal2   =  ((TH1D*) f2->Get(Form("hptTotal%s",type)));


  int rebin = 2;

  double eta = 1.1;
  gStyle->SetOptStat(000);//111);

  const char* first = "";//Cons. laws only";
  const char* second = "";//Minijets";

  if(rebin>0)
    {
      heta->Rebin(rebin);
      hpt->Rebin(rebin);
      hphiS->Rebin(rebin);
      hphiP->Rebin(rebin);
      
      heta2->Rebin(rebin);
      hpt2->Rebin(rebin);
      hphiS2->Rebin(rebin);
      hphiP2->Rebin(rebin);  
    }

  heta2->SetLineColor(kGreen+2);
  hpt2->SetLineColor(kGreen+2);
  hphiS2->SetLineColor(kGreen+1);
  hphiP2->SetLineColor(kGreen+2);
  hpid12->SetLineColor(kGreen+2);
  hpid22->SetLineColor(kGreen+2);
  hevmultAll2->SetLineColor(kGreen+2);
  hevmult2->SetLineColor(kGreen+2);

  heta->Scale(1./heta->Integral());
  heta2->Scale(1./heta2->Integral());
  hpt->Scale(1./hpt->Integral());
  hpt2->Scale(1./hpt2->Integral());
  hevmult->Scale(1./hevmult->Integral());
  hevmult2->Scale(1./hevmult2->Integral());
  hevmultAll->Scale(1./hevmultAll->Integral());
  hevmultAll2->Scale(1./hevmultAll2->Integral());
  hpid1->Scale(1./hpid1->Integral());
  hpid2->Scale(1./hpid2->Integral());
  hpid12->Scale(1./hpid12->Integral());
  hpid22->Scale(1./hpid22->Integral());
  hphiP->Scale(1./hphiP->Integral());
  hphiS->Scale(1./hphiS->Integral());
  hphiP2->Scale(1./hphiP2->Integral());
  hphiS2->Scale(1./hphiS2->Integral());
  hptTotal->Scale(1./hptTotal->Integral());
  hptTotal2->Scale(1./hptTotal2->Integral());

  TCanvas* canv = new TCanvas("canv", "GENBOD results", 10,10,3*550,2*400);
  canv->Divide(3,3);

  canv->cd(1);
  heta->Draw();
  heta2->Draw("same");
  canv->cd(2);
  hpt->GetXaxis()->SetRangeUser(0,5);
  hpt->Draw();
  hpt2->Draw("same");
  hptTotal->SetLineColor(kMagenta);
  hptTotal->Draw("same");

  canv->cd(3);
  hphiS->Draw();
  hphiP->SetLineColor(kRed);
  hphiP->Draw("same");
  hphiP2->Draw("same");
  hphiS2->Draw("same");

  canv->cd(4);
  hpid1->Draw();
  hpid12->Draw("same");
  canv->cd(5);
  hpid2->Draw();
  hpid22->Draw("same");

  canv->cd(6);
  hevmultAll->GetXaxis()->SetRangeUser(5,41);
  hevmultAll->Draw();
  hevmultAll2->Draw("same");

  canv->cd(7);
  hevmult->GetXaxis()->SetRangeUser(0,41);
  hevmult->Draw();
  hevmult2->Draw("same");

  canv->cd(8);
  hevweight->Draw();
  hevweight->Draw("same");

  canv->cd(9);
  //hevweightdensity->SetLineColor(kRed);
  //hevweightdensity->Draw();
  //hevweightdensity2->Draw("same");
  hptTotal->Draw();
  hptTotal2->SetLineColor(kGreen+2);
  hptTotal2->Draw("same");
  TF1* Ptot = new TF1("Ptot","4.33538e-02*TMath::Landau(x,3.24886e+00,2.17010e+00)*exp(8.34570e-03*x)",0,30);
  Ptot->Draw("same");

  TCanvas* canv2 = new TCanvas("canv2", "GENBOD results", 10,10,550,400);
  //canv->Divide(3,3);
  canv2->cd();
  hevmultPID->Draw("colz");

  double counter[11];
  double counttrue[] = {1.493,1.493, 1.493,0.183, 0.183,0.083,0.083, 0.048, 0.048,0.183,0.183};

  for(int i=1;i<12;i++)
      counter[i-1] = ((TH1F*)hevmultPID->ProjectionY("_py",i,i))->GetMean();


  for(int i=1;i<12;i++)
    {
      TLatex *part = new TLatex(0.072*i+0.05,0.7,Form("%.2f",counter[i-1]));
      part->SetNDC();
      //part->SetTextColor(kRed+2);
      part->SetTextFont(42);
      part->SetTextSize(0.04);
      part->SetLineWidth(2);
      part->Draw();

      TLatex *part1 = new TLatex(0.072*i+0.05,0.6,Form("%.1f%%",counter[i-1]/counter[0]*100.));
      cout<<Form("%.1f%%",counter[i-1]/counter[0]*100.)<<endl;
      part1->SetNDC();
      part1->SetTextColor(kRed+2);
      part1->SetTextFont(42);
      part1->SetTextSize(0.03);
      part1->SetLineWidth(2);
      part1->Draw();

      TLatex *part2 = new TLatex(0.072*i+0.05,0.5,Form("%.1f%%",counttrue[i-1]/counttrue[0]*100.));
      cout<<Form("%.1f%%",counttrue[i-1]/counttrue[0]*100.)<<endl;
      part2->SetNDC();
      part2->SetTextColor(kBlue+2);
      part2->SetTextFont(42);
      part2->SetTextSize(0.03);
      part2->SetLineWidth(2);
      part2->Draw();

    }
 }
void limit() {
//This program demonstrates the computation of 95 % C.L. limits.
//It uses a set of randomly created histograms.
//
//Author:  [email protected] on 21.08.02

// Create a new canvas.
  TCanvas *c1 = new TCanvas("c1","Dynamic Filling Example",200,10,700,500);
  c1->SetFillColor(42);
  
// Create some histograms
  TH1D* background = new TH1D("background","The expected background",30,-4,4);
  TH1D* signal     = new TH1D("signal","the expected signal",30,-4,4);
  TH1D* data       = new TH1D("data","some fake data points",30,-4,4);
  background->SetFillColor(48);
  signal->SetFillColor(41);
  data->SetMarkerStyle(21);
  data->SetMarkerColor(kBlue);
  background->Sumw2(); // needed for stat uncertainty
  signal->Sumw2(); // needed for stat uncertainty
  
// Fill histograms randomly
  TRandom2 r;
  Float_t bg,sig,dt;
  for (Int_t i = 0; i < 25000; i++) {
     bg  = r.Gaus(0,1);
     sig = r.Gaus(1,.2);
     background->Fill(bg,0.02);
     signal->Fill(sig,0.001);
  }
  for (Int_t i = 0; i < 500; i++) {
     dt = r.Gaus(0,1);
     data->Fill(dt);
  }
  THStack *hs = new THStack("hs","Signal and background compared to data...");
  hs->Add(background);
  hs->Add(signal);
  hs->Draw("hist");
  data->Draw("PE1,Same");
  c1->Modified();
  c1->Update();
  c1->GetFrame()->SetFillColor(21);
  c1->GetFrame()->SetBorderSize(6);
  c1->GetFrame()->SetBorderMode(-1);
  c1->Modified();
  c1->Update();
  gSystem->ProcessEvents();

// Compute the limits
  cout << "Computing limits... " << endl;
  TLimitDataSource* mydatasource = new TLimitDataSource(signal,background,data);
  TConfidenceLevel *myconfidence = TLimit::ComputeLimit(mydatasource,50000);
  cout << "CLs    : "   << myconfidence->CLs()  << endl;
  cout << "CLsb   : "   << myconfidence->CLsb() << endl;
  cout << "CLb    : "   << myconfidence->CLb()  << endl;
  cout << "< CLs >  : " << myconfidence->GetExpectedCLs_b()  << endl;
  cout << "< CLsb > : " << myconfidence->GetExpectedCLsb_b() << endl;
  cout << "< CLb >  : " << myconfidence->GetExpectedCLb_b()  << endl;

// Add stat uncertainty
  cout << endl << "Computing limits with stat systematics... " << endl;
  TConfidenceLevel *mystatconfidence = TLimit::ComputeLimit(mydatasource,50000,true);
  cout << "CLs    : "   << mystatconfidence->CLs()  << endl;
  cout << "CLsb   : "   << mystatconfidence->CLsb() << endl;
  cout << "CLb    : "   << mystatconfidence->CLb()  << endl;
  cout << "< CLs >  : " << mystatconfidence->GetExpectedCLs_b()  << endl;
  cout << "< CLsb > : " << mystatconfidence->GetExpectedCLsb_b() << endl;
  cout << "< CLb >  : " << mystatconfidence->GetExpectedCLb_b()  << endl;

// Add some systematics
  cout << endl << "Computing limits with systematics... " << endl;
  TVectorD errorb(2);
  TVectorD errors(2);
  TObjArray* names = new TObjArray();
  TObjString name1("bg uncertainty");
  TObjString name2("sig uncertainty");
  names->AddLast(&name1);
  names->AddLast(&name2);
  errorb[0]=0.05; // error source 1: 5%
  errorb[1]=0;    // error source 2: 0%
  errors[0]=0;    // error source 1: 0%
  errors[1]=0.01; // error source 2: 1%
  TLimitDataSource* mynewdatasource  = new TLimitDataSource();
  mynewdatasource->AddChannel(signal,background,data,&errors,&errorb,names);
  TConfidenceLevel *mynewconfidence = TLimit::ComputeLimit(mynewdatasource,50000,true);
  cout << "CLs    : " << mynewconfidence->CLs()  << endl;
  cout << "CLsb   : " << mynewconfidence->CLsb() << endl;
  cout << "CLb    : " << mynewconfidence->CLb()  << endl;
  cout << "< CLs >  : " << mynewconfidence->GetExpectedCLs_b()  << endl;
  cout << "< CLsb > : " << mynewconfidence->GetExpectedCLsb_b() << endl;
  cout << "< CLb >  : " << mynewconfidence->GetExpectedCLb_b()  << endl;

// show canonical -2lnQ plots in a new canvas
// - The histogram of -2lnQ for background hypothesis (full)
// - The histogram of -2lnQ for signal and background hypothesis (dashed)
  TCanvas *c2 = new TCanvas("c2");
  myconfidence->Draw();
  
// clean up (except histograms and canvas)
  delete myconfidence;
  delete mydatasource;
  delete mystatconfidence;
  delete mynewconfidence;
  delete mynewdatasource;
}
Esempio n. 9
0
void metStudy( TString sampleName, TString CutName){

  TString OutDir = "CtrPlots_metStudy";
  gSystem->mkdir(OutDir);

  TString ChannelName[4];
  ChannelName[0] = "of0j";
  ChannelName[1] = "of1j";
  ChannelName[2] = "of2j";
  ChannelName[3] = "Incl";

  TString LgdTitle[4];
  LgdTitle[0] = "njet = 0, e#mu";
  LgdTitle[1] = "njet = 1, e#mu";
  LgdTitle[2] = "njet #geq 2, e#mu";
  LgdTitle[3] = "Incl.jet, e#mu";
  
  TString fileName  = sampleName+"/"+sampleName+"_"+CutName+".root";
  cout<<"File used: "<<fileName<<endl;
  TFile *fname  = new TFile(fileName);

  char tmpName[30];
  char histName[30];
  char histNameOrg[30];

  TH1D *h1_genMet[4];
  TH1D *h1_pupMet[4];
  TH1D *h1_pfMet[4];
  TH1D *h1_trkMet[4];
  TH2D* h2_pfGenResol[4];
  TH2D* h2_pupGenResol[4];
  TH2D* h2_trkGenResol[4];
  
  TProfile* pr_pfGenResol[4];
  TProfile* pr_pupGenResol[4];
  TProfile* pr_trkGenResol[4];

  //=====================================
  //Looping for each Channel
  //=====================================

  for (int i(0);i<4;i++) {
    TCanvas *myCan = new TCanvas("myCan","Can",800,800);
    
      sprintf(histNameOrg,"h1_genMet_%d",i);
      h1_genMet[i]= (TH1D*)fname->Get(histNameOrg)->Clone(histNameOrg); h1_genMet[i]->Sumw2();
      sprintf(histNameOrg,"h1_pfMet_%d",i);
      h1_pfMet[i]= (TH1D*)fname->Get(histNameOrg)->Clone(histNameOrg); h1_pfMet[i]->Sumw2();
      sprintf(histNameOrg,"h1_pupMet_%d",i);
      h1_pupMet[i]= (TH1D*)fname->Get(histNameOrg)->Clone(histNameOrg); h1_pupMet[i]->Sumw2();
      sprintf(histNameOrg,"h1_trkMet_%d",i);
      h1_trkMet[i]= (TH1D*)fname->Get(histNameOrg)->Clone(histNameOrg); h1_trkMet[i]->Sumw2();
   
      char fileName[30];
      char Ytitle[30];
      sprintf(fileName,sampleName+"_Met_%djet",i);
      sprintf(Ytitle,"Events / %.1f",h1_genMet[i]->GetBinWidth(1));
      CPlot* Plot_MET = new CPlot(fileName,sampleName,"MET[GeV]",Ytitle);
      Plot_MET->setOutDir(OutDir);
      Plot_MET->AddHist1D(h1_genMet[i],"HIST",kBlack);
      Plot_MET->AddHist1D(h1_pfMet[i],"HIST",kRed);
      Plot_MET->AddHist1D(h1_pupMet[i],"HIST",kBlue);
      Plot_MET->AddHist1D(h1_trkMet[i],"HIST",kGreen);
      //Plot_MET->AddTextBox(LgdTitle[i],0.7,0.92,0.9,0.97,0,kBlack,-1);
      Plot_MET->SetLegend(0.65,0.7,0.92,0.85);
      Plot_MET->GetLegend()->AddEntry(h1_genMet[i],"gen","l");
      Plot_MET->GetLegend()->AddEntry(h1_pfMet[i],"pf","l");
      Plot_MET->GetLegend()->AddEntry(h1_pupMet[i],"pup","l");
      Plot_MET->GetLegend()->AddEntry(h1_trkMet[i],"trk","l");
      if(sampleName == "DYJetsToLL")Plot_MET->SetLogy();
      
      Plot_MET->Draw(myCan,kTRUE,"png");


      // 2D plot party===================
      //
      sprintf(histNameOrg,"h2_pup_gen_MetResol_%d",i);
      sprintf(histName,"h2_pupGenResol_%d",i);
      h2_pupGenResol[i] = (TH2D*)fname->Get(histNameOrg)->Clone(histName);
      h2_pupGenResol[i] -> SetMarkerSize(0.4);

      sprintf(histNameOrg,"h2_pf_gen_MetResol_%d",i);
      sprintf(histName,"h2_pfGenResol_%d",i);
      h2_pfGenResol[i] = (TH2D*)fname->Get(histNameOrg)->Clone(histName);
      h2_pfGenResol[i] -> SetMarkerSize(0.4);

      sprintf(histNameOrg,"h2_trk_gen_MetResol_%d",i);
      sprintf(histName,"h2_trkGenResol_%d",i);
      h2_trkGenResol[i] = (TH2D*)fname->Get(histNameOrg)->Clone(histName);
      h2_trkGenResol[i] -> SetMarkerSize(0.4);

      myCan->Clear();
      h2_pupGenResol[i]->GetYaxis()->SetTitle("(met-gen)/gen");
      h2_pupGenResol[i]->Draw();
      sprintf(tmpName,OutDir+"/"+sampleName+"_metGenRes2d_%dj.png",i);
      //myCan->SaveAs(tmpName);
      
      // Making profile ======================
      sprintf(histName,"pr_pupGenResol_%d",i);
      //                                           name , first, last , option
      //pr_pupGenResol[i] = h2_pupGenResol[i]->ProfileX(histName);
      pr_pupGenResol[i] = h2_pupGenResol[i]->ProfileX(histName,1,-1,"s");

      sprintf(histName,"pr_trkGenResol_%d",i);
      pr_trkGenResol[i] = h2_trkGenResol[i]->ProfileX(histName,1,-1,"s");
      sprintf(histName,"pr_pfGenResol_%d",i);
      pr_pfGenResol[i] = h2_pfGenResol[i]->ProfileX(histName,1,-1,"s");

      //pr_trkGenResol[i]->GetXaxis()->SetTitle("genMet");
      //pr_trkGenResol[i]->GetYaxis()->SetTitle("trkmet");
      //pr_trkGenResol[i]->SetTitle("");

      //Leg_met->Draw();
      //sprintf(tmpName,OutDir+"/"+sampleName+"_trkGenResol_%djet.png",i);
      //myCan->SaveAs(tmpName);

      //Each Profiles and 2D

      //pr_pfGenResol[i]->GetXaxis()->SetTitle("genMet");
      //pr_pfGenResol[i]->GetYaxis()->SetTitle("pfmet");
      //pr_pfGenResol[i]->SetTitle("");

      //Leg_met->SetHeader(LgdTitle[i]+" "+sampleName);

      //pr_pfGenResol[i]->Draw();
      //h2_pfGenResol[i]->Draw("same");
      //pr_pfGenResol[i]->Draw("E1same");
      //Leg_met->Draw();
      //sprintf(tmpName,OutDir+"/"+sampleName+"_pfGenResol_%djet.png",i);
      //myCan->SaveAs(tmpName);
      //
      //
      //
      pr_pupGenResol[i]->GetXaxis()->SetTitle("genMet[GeV]");
      pr_pupGenResol[i]->GetYaxis()->SetTitle("(met-gen)/gen");
      pr_pupGenResol[i]->SetTitle("");
      pr_pupGenResol[i]->SetLineColor(kBlue);
      pr_pupGenResol[i]->SetMarkerColor(kBlue);
      pr_trkGenResol[i]->SetLineColor(kGreen);
      pr_trkGenResol[i]->SetMarkerColor(kGreen);
      pr_pfGenResol[i]->SetLineColor(kRed);
      pr_pfGenResol[i]->SetMarkerColor(kRed);

      pr_pupGenResol[i]->Draw("p");
      //pr_pupGenResol[i]->Draw("E1");
      pr_trkGenResol[i]->Draw("psame");
      pr_pfGenResol[i]->Draw("psame");

      TLegend *Leg_met =new TLegend(0.6,0.7,0.9,0.9); Leg_met->SetFillColor(0); Leg_met->SetBorderSize(0);
      Leg_met->SetHeader(sampleName);
      Leg_met->AddEntry(pr_pupGenResol[i],"pupMet","PL");
      Leg_met->AddEntry(pr_trkGenResol[i],"trkMet","PL");
      Leg_met->AddEntry(pr_pfGenResol[i],"pfMet","PL");
      myCan->SetLogy(0);
      Leg_met->Draw();
      TLine myLine(0,0,120,0);
      myLine.Draw();

      sprintf(tmpName,OutDir+"/"+sampleName+"_metGenResol_%djet.png",i);
      myCan->SaveAs(tmpName);

      // RMS Draw
      TH1D pupRMS("pupRMS","RMS",50,0,51);
      TH1D trkRMS("trkRMS","RMS",50,0,51);
      TH1D pfRMS ("pfRMS", "RMS" ,50,0,51);
      for ( int j(0);j<50; j++)
      {
	pupRMS.SetBinContent(j,pr_pupGenResol[i]->GetBinError(j));
	trkRMS.SetBinContent(j,pr_trkGenResol[i]->GetBinError(j));
	pfRMS.SetBinContent(j,pr_pfGenResol[i]->GetBinError(j));
      }
      pupRMS.GetXaxis()->SetTitle("genMet[GeV]");
      pupRMS.GetYaxis()->SetTitle("Resolution");
      pupRMS.SetLineColor(kBlue);
      trkRMS.SetLineColor(kGreen);
      pfRMS.SetLineColor(kRed);
      pupRMS.Draw();
      trkRMS.Draw("same");
      pfRMS.Draw("same");

      TLegend *Leg_RMS =new TLegend(0.6,0.7,0.9,0.9);
      Leg_RMS->SetFillColor(0);
      Leg_RMS->SetBorderSize(0);
      Leg_RMS->SetHeader(sampleName);
      Leg_RMS->AddEntry(&pupRMS,"pupMet","L");
      Leg_RMS->AddEntry(&trkRMS,"trkMet","L");
      Leg_RMS->AddEntry(& pfRMS,"pfMet" ,"L");
      Leg_RMS->Draw();
      sprintf(tmpName,OutDir+"/"+sampleName+"_metGenRMS_%djet.png",i);
      myCan->SaveAs(tmpName);

      //h2_pupGenResol[i]->SetMaximum(10);
      //h2_pupGenResol[i]->SetMinimum(-10);
      //h2_trkGenResol[i]->Draw("same");
      //h2_pfGenResol[i]->Draw("same");
  }
}
Esempio n. 10
0
void msquared() {

  double yPos, xPos, theta, energy = 0.;  // NOTE: theta comes in degrees
  int numHit, pID = 0;


  // Initialize histograms
  double nEnergyMin = 10; // MeV
  double nEnergyMax = 510; // MeV
  int nEnergyBins = 50;
  double dEnergyBinSize = (double)(nEnergyMax - nEnergyMin) / (double)nEnergyBins;

  double nThetaMin = 34; // mrad
  double nThetaMax = 88; // mrad
  int nThetaBins = 50;
  double dThetaBinSize = (nThetaMax - nThetaMin) / nThetaBins;

  double nM2Min = -5000; // MeV
  double nM2Max = 5000; // MeV
  int nM2Bins = 100;
  double dM2BinSize = (nM2Max - nM2Min)/nM2Bins;


  THStack *hs = new THStack("hs","Stacked M^2");

  TFile* file = new TFile("e+e-2yyGUN.root");

  TTree* Hits_Info = (TTree *)file->Get("Signal");

  Hits_Info->SetBranchAddress("numHits", &numHit);
  Hits_Info->SetBranchAddress("energyTot", &energy);
  Hits_Info->SetBranchAddress("XPosition", &xPos);
  Hits_Info->SetBranchAddress("YPosition", &yPos);
  Hits_Info->SetBranchAddress("Particle_ID", &pID);
  Hits_Info->SetBranchAddress("Theta", &theta);

  TH1D* hmyy = new TH1D("M_{A'}^{2}" ,             // plot label
                       "e+e- > yy",    // title
                       nM2Bins,                   // x number of bins
                       nM2Min,                    // x lower bound
                       nM2Max);                   // x upper bound

  // go through all entries and fill the histograms
  int nentries = Hits_Info->GetEntries();
  for (int i=0; i<nentries; i++) {
    Hits_Info->GetEntry(i);
    if (pID == 22) { // gammas only
      theta*= TMath::Pi()/180; //radians
      cout << "M^2 is: " << mSquared(energy, theta) << endl;
      cout << "Energy is: " << energy << endl;
           
      hmyy->Fill(mSquared(energy, theta), XSECyy * BINNING_WEIGHT / dM2BinSize);
    }
  }
  cout << "DM2binsize is:" << dM2BinSize << endl;




  hmyy->SetFillColor(kBlue);
  hmyy->SetFillStyle(3001);
  hmyy->GetXaxis()->SetTitle("M_{A'}^{2} (MeV^{2})");
  hmyy->GetYaxis()->SetTitle("Photons per MeV^{2} per Second (MeV^{-2} s^{-1})");
  hmyy->GetXaxis()->CenterTitle();
  hmyy->GetYaxis()->CenterTitle();


  TFile* fileyyy = new TFile("e+e-2yyyGUN.root");
  TTree* Hits_Infoyyy = (TTree *)fileyyy->Get("Signal");

  Hits_Infoyyy->SetBranchAddress("numHits", &numHit);
  Hits_Infoyyy->SetBranchAddress("energyTot", &energy);
  Hits_Infoyyy->SetBranchAddress("XPosition", &xPos);
  Hits_Infoyyy->SetBranchAddress("YPosition", &yPos);
  Hits_Infoyyy->SetBranchAddress("Particle_ID", &pID);
  Hits_Infoyyy->SetBranchAddress("Theta", &theta);

  TH1D* hmyyy = new TH1D("M_{A'}^{2}" ,             // plot label
                       "e+e- > yyy",    // title
                       nM2Bins,                   // x number of bins
                       nM2Min,                    // x lower bound
                       nM2Max);                   // x upper bound
  // go through all entries and fill the histograms
  nentries = Hits_Infoyyy->GetEntries();
  for (int i=0; i<nentries; i++) {
    Hits_Infoyyy->GetEntry(i);
    if (pID == 22) { // gammas only
      theta*= TMath::Pi()/180; //radians
      cout << "M^2 is: " << mSquared(energy, theta) << endl;
      cout << "Energy is: " << energy << endl;
           
      hmyyy->Fill(mSquared(energy, theta), XSECyyy * BINNING_WEIGHT / dM2BinSize);
    }
  }
  cout << "DM2binsize is:" << dM2BinSize << endl;


  hmyyy->SetFillColor(kRed);
  hmyyy->SetFillStyle(3001);
  hmyyy->GetXaxis()->SetTitle("M_{A'}^{2} (MeV^{2})");
  hmyyy->GetYaxis()->SetTitle("Photons per MeV^{2} per Second (MeV^{-2} s^{-1})");
  hmyyy->GetXaxis()->CenterTitle();
  hmyyy->GetYaxis()->CenterTitle();



  
  TFile* fileepluseminusy = new TFile("e+e-2e+e-yECUT0.3NOPT_2_5_1000000.root");
  //This is 1000000 events so DOWNEIGHT IT:
  XSECepluseminusy = 0.1 * XSECepluseminusy;
  TTree* Hits_Infoepluseminusy = (TTree *)fileepluseminusy->Get("Signal");

  Hits_Infoepluseminusy->SetBranchAddress("numHits", &numHit);
  Hits_Infoepluseminusy->SetBranchAddress("energyTot", &energy);
  Hits_Infoepluseminusy->SetBranchAddress("XPosition", &xPos);
  Hits_Infoepluseminusy->SetBranchAddress("YPosition", &yPos);
  Hits_Infoepluseminusy->SetBranchAddress("Particle_ID", &pID);
  Hits_Infoepluseminusy->SetBranchAddress("Theta", &theta);

  TH1D* hmepluseminusy = new TH1D("M_{A'}^{2}" ,             // plot label
                       "e+e- > e+e-y (only registering gammas)",    // title
                       nM2Bins,                   // x number of bins
                       nM2Min,                    // x lower bound
                       nM2Max);                   // x upper bound
  // go through all entries and fill the histograms
  nentries = Hits_Infoepluseminusy->GetEntries();
  for (int i=0; i<nentries; i++) {
    Hits_Infoepluseminusy->GetEntry(i);
    if (pID == 22) { // gammas only
      theta*= TMath::Pi()/180; //radians
      cout << "M^2 is: " << mSquared(energy, theta) << endl;
      cout << "Energy is: " << energy << endl;
           
      hmepluseminusy->Fill(mSquared(energy, theta), XSECepluseminusy * BINNING_WEIGHT / dM2BinSize);
    }
  }
  cout << "DM2binsize is:" << dM2BinSize << endl;


  hmepluseminusy->SetFillColor(7);
  hmepluseminusy->SetFillStyle(3001);
  hmepluseminusy->GetXaxis()->SetTitle("M_{A'}^{2} (MeV^{2})");
  hmepluseminusy->GetYaxis()->SetTitle("Photons per MeV^{2} per Second (MeV^{-2} s^{-1})");
  hmepluseminusy->GetXaxis()->CenterTitle();
  hmepluseminusy->GetYaxis()->CenterTitle();


  

  

  //ADD YIMIN'S PLOT

  TFile *f = new TFile("YIMINPLOTBREM.root"); 

  f->ls(); 
  
  TH1F * hYIMIN = (TH1F*)f->Get("M^2"); 
  hYIMIN->SetFillColor(kOrange);
  hYIMIN->SetTitle("Bremsstrahlung");
  hYIMIN->SetFillStyle(3001);
  hYIMIN->GetXaxis()->SetTitle("M_{A'}^{2} (MeV^{2})");
  hYIMIN->GetYaxis()->SetTitle("Photons per MeV^{2} per Second (MeV^{-2} s^{-1})");
  hYIMIN->GetXaxis()->CenterTitle();
  hYIMIN->GetYaxis()->CenterTitle();




  /**********************
      ADD BRIANS PLOT
    ********************/

  NUM_TOT_POSITRONS = 1e+07; 
  BIAS = 1e+04; 
  BINNING_WEIGHT = POSITRONS_PER_SEC/(BIAS*NUM_TOT_POSITRONS);
  B = pow(1-pow(GAMMA_PLUS, -2.), .5);

  TFile* fileinelastic = new TFile("brian_1e7_pos_1e4_bias.root");
  TTree* Hits_Infoinelastic = (TTree *)fileinelastic->Get("Signal");

  Hits_Infoinelastic->SetBranchAddress("numHits", &numHit);
  Hits_Infoinelastic->SetBranchAddress("energyTot", &energy);
  Hits_Infoinelastic->SetBranchAddress("XPosition", &xPos);
  Hits_Infoinelastic->SetBranchAddress("YPosition", &yPos);
  Hits_Infoinelastic->SetBranchAddress("Particle_ID", &pID);
  Hits_Infoinelastic->SetBranchAddress("Theta", &theta);

  TH1D* hminelastic = new TH1D("M_{A'}^{2}" ,             // plot label
                       "Inelastic (only registering gammas)",    // title
                       nM2Bins,                   // x number of bins
                       nM2Min,                    // x lower bound
                       nM2Max);                   // x upper bound
  // go through all entries and fill the histograms
  nentries = Hits_Infoinelastic->GetEntries();
  for (int i=0; i<nentries; i++) {
    Hits_Infoinelastic->GetEntry(i);
    if (pID == 22) { // gammas only
      theta*= TMath::Pi()/180; //radians
      cout << "M^2 is: " << mSquared(energy, theta) << endl;
      cout << "Energy is: " << energy << endl;
           
      hminelastic->Fill(mSquared(energy, theta), BINNING_WEIGHT / dM2BinSize);
    }
  }
  cout << "DM2binsize is:" << dM2BinSize << endl;


  hminelastic->SetFillColor(kGreen);
  hminelastic->SetFillStyle(3001);
  hminelastic->GetXaxis()->SetTitle("M_{A'}^{2} (MeV^{2})");
  hminelastic->GetYaxis()->SetTitle("Photons per MeV^{2} per Second (MeV^{-2} s^{-1})");
  hminelastic->GetXaxis()->CenterTitle();
  hminelastic->GetYaxis()->CenterTitle();



 hs->Add(hminelastic);
  hs->Add(hYIMIN);
      hs->Add(hmyyy);
  hs->Add(hmepluseminusy);
    hs->Add(hmyy);



  // create canvas and draw histogram
  TCanvas* canvas = new TCanvas("canvas", "canvas", 700, 700);
  canvas->Divide(3,2);
  TPad* p;

  p = (TPad*)canvas->cd(1);
  //p->SetGrid();
  p->SetLogy();

 


  hs->Draw();

    hs->GetXaxis()->SetTitle("M_{A'}^{2} (MeV^{2})");
  hs->GetYaxis()->SetTitle("Photons per MeV^{2} per Second (MeV^{-2} s^{-1})");
  hs->GetXaxis()->CenterTitle();
  hs->GetYaxis()->CenterTitle();
  
  p = (TPad*)canvas->cd(4);
  hmepluseminusy->Draw();
  
  p = (TPad*)canvas->cd(3);
  hmyyy->Draw();
  p = (TPad*)canvas->cd(2);
  hmyy->Draw();

  p = (TPad*)canvas->cd(5);
  hYIMIN->Draw();

  p = (TPad*)canvas->cd(6);
  hminelastic->Draw();

/*
  p = (TPad*)canvas->cd(4);
  p->SetLogy();
  p->SetGrid();
  hm2->Draw();*/


}
Esempio n. 11
0
int main(int ac, char *av[]) { 
  try {
    double fMin, fMax;
    string ext;
    po::options_description desc("Allowed options");
    desc.add_options()
      ("help", "produce help message")
      ("include-path,I", po::value< vector<string> >(), 
       "include path")
      ("input-file", po::value< vector<string> >(), "input file")
      ("min,m", po::value<double>(&fMin)->default_value(60), "minimum value for fit range")
      ("max,M", po::value<double>(&fMax)->default_value(120), "maximum value for fit range")
      ("convbwintgamg", 
       "fit to the convolution of a breit-wigner plus interference term and gamma propagator and a gaussian")
      ("convexpbwintgamg", 
       "fit to the convolution of the product between an exponential and a breit-wigner plus interference term and gamma propagator with a gaussian")
      ("convbwintgam2gf", 
       "fit to the convolution of the breit-wigner plus interference term and gamma propagator with a linear combination of fixed gaussians")
      ("output-file,O", po::value<string>(&ext)->default_value(".ps"), 
       "output file format")
      ;
    
    po::positional_options_description p;
    p.add("input-file", -1);
    
    po::variables_map vm;
    po::store(po::command_line_parser(ac, av).
	    options(desc).positional(p).run(), vm);
    po::notify(vm);
    
    if (vm.count("help")) {
      cout << "Usage: options_description [options]\n";
      cout << desc;
      return 0;
      }
    
    if (vm.count("include-path")) {
      cout << "Include paths are: " 
	   << vm["include-path"].as< vector<string> >() << "\n";
    }
    
    vector<string> v_file;
    vector<TH1D*> v_ZMassHistos;
    vector<string> v_eps;
    
    if (vm.count("input-file"))	{
      cout << "Input files are: " 
	   << vm["input-file"].as< vector<string> >() << "\n";
      v_file = vm["input-file"].as< vector<string> >();
      for(vector<string>::const_iterator it = v_file.begin(); 
	  it != v_file.end(); ++it) { 
	TFile * root_file = new TFile(it->c_str(),"read");
	TDirectory *Histos = (TDirectory*) root_file->GetDirectory("ZHisto");
	TDirectory *RecoHistos = (TDirectory*) Histos->GetDirectory("ZRecoHisto");
	TH1D * zMass = (TH1D*) RecoHistos->Get("ZMass");
	zMass->Rebin(4); //remember...
	zMass->GetXaxis()->SetTitle("#mu #mu invariant mass (GeV/c^{2})");
	v_ZMassHistos.push_back(zMass);
	gROOT->SetStyle("Plain");
	//gStyle->SetOptFit(1111);
	string f_string = *it;
	replace(f_string.begin(), f_string.end(), '.', '_');
	string eps_string = f_string + ext;
	v_eps.push_back(eps_string);
	cout << ">>> histogram loaded\n";
      }
      cout << v_file.size() << ", " << v_ZMassHistos.size() << ", " << v_eps.size() << endl;
      cout <<">>> Input files loaded\n";
    }

    IntegratorConv integratorConv(1.e-5);
    //Values for Z mass and width
    funct::Parameter mass("Mass", 91.364);
    funct::Parameter gamma("Gamma", 4.11);
    //Parameters for Z Line Shape
    funct::Parameter f_gamma("Photon factor", 0.838);
    funct::Parameter f_int("Interference factor", -0.00197);
    //Parameters for fits with gaussians
    funct::Parameter yield("Yield", 283000);
    funct::Parameter alpha("Alpha", 0.771); //the first gaussian is narrow
    funct::Parameter mean("Mean", 0); //0.229
    funct::Parameter sigma1("Sigma 1", 0.76); 
    funct::Parameter sigma2("Sigma 2", 2.94);
    //Parameter for exponential
    funct::Parameter lambda("Lambda", 0);
    
    if (vm.count("convbwintgamg")) {
      cout << "Fitting histograms in input files to the convolution of the Breit-Wigner plus Z/photon interference and photon propagator with a Gaussian\n";
      cout << ">>> set pars: " << endl;
      cout << yield << endl; 
      cout << mass  << endl; 
      cout << gamma << endl; 
      cout << f_gamma << endl; 
      cout << f_int << endl; 
      cout << mean  << endl; 
      cout << sigma1 << endl;
      for(unsigned int i = 0; i < v_ZMassHistos.size(); ++i) { 
	TH1D * zMass = v_ZMassHistos[i]; 
	funct::ZLineShape zls(mass, gamma, f_gamma, f_int);
	funct::Gaussian gauss(mean, sigma1);
	double range = 3 * sigma1.value();
	funct::Convolution<funct::ZLineShape, funct::Gaussian, IntegratorConv>::type 
	  czg(zls, gauss, -range , range, integratorConv);
	funct::Constant c(yield);
	typedef funct::Product<funct::Constant, 
	  funct::Convolution<funct::ZLineShape, funct::Gaussian, IntegratorConv>::type >::type FitFunction;
	FitFunction f = c * czg;
	cout << "set functions" << endl;
	typedef fit::HistoChiSquare<FitFunction> ChiSquared;
	ChiSquared chi2(f, zMass, fMin, fMax);
	int fullBins = chi2.numberOfBins();
	cout << "N. deg. of freedom: " << fullBins << endl;
	fit::RootMinuit<ChiSquared> minuit(chi2, true);
	minuit.addParameter(yield, 10, 100, 10000000);
	minuit.addParameter(mass, .1, 70., 110);
	minuit.addParameter(gamma, 1, 1, 10);
	minuit.addParameter(f_gamma, 0.1, -100, 1000);
	minuit.addParameter(f_int, .0001, -1000000, 1000000);
	minuit.addParameter(mean, 0.001, -0.5, 0.5);
	minuit.fixParameter(mean.name());
	minuit.addParameter(sigma1, 0.1, -5., 5.);
	minuit.minimize();
	minuit.printFitResults();
	vector<shared_ptr<double> > pars;
	pars.push_back(yield.ptr());
	pars.push_back(mass.ptr());
	pars.push_back(gamma.ptr());
	pars.push_back(f_gamma.ptr());
	pars.push_back(f_int.ptr());
	pars.push_back(mean.ptr());
	pars.push_back(sigma1.ptr());
	TF1 fun = root::tf1("fun", f, fMin, fMax, pars);
	fun.SetParNames(yield.name().c_str(), mass.name().c_str(), gamma.name().c_str(), 
			f_gamma.name().c_str(), f_int.name().c_str(), 
			mean.name().c_str(), sigma1.name().c_str());
	fun.SetLineColor(kRed);
	fun.SetNpx(100000);
	TCanvas *canvas = new TCanvas("canvas");
	zMass->Draw("e");
	fun.Draw("same");
	string epsFilename = "ZMassFitCoBwInGaG_" + v_eps[i];
	canvas->SaveAs(epsFilename.c_str());
	canvas->SetLogy();
	string epsLogFilename = "ZMassFitCoBwInGaG_Log_" + v_eps[i];
	canvas->SaveAs(epsLogFilename.c_str());
      }
    }
    
    if (vm.count("convexpbwintgamg")) {
      cout << "Fitting histograms in input files to the convolution of the product between an exponential and a breit-wigner plus interference term and gamma propagator with a gaussian" 
	   << endl;
      cout << ">>> set pars: " << endl;
      cout << yield << endl; 
      cout << lambda << endl;
      cout << mass << endl; 
      cout << gamma << endl; 
      cout << f_gamma << endl; 
      cout << f_int  << endl; 
      cout << mean  << endl; 
      cout << sigma1 << endl;
      for(unsigned int i = 0; i < v_ZMassHistos.size(); ++i) { 
	TH1D * zMass = v_ZMassHistos[i]; 
	funct::Exponential expo(lambda);
	funct::ZLineShape zls(mass, gamma, f_gamma, f_int);
	funct::Gaussian gauss(mean, sigma1);
	typedef funct::Product<funct::Exponential, funct::ZLineShape>::type ExpZLS;
	ExpZLS expz = expo * zls;
	double range = 3 * sigma1.value();
	funct::Convolution<ExpZLS, funct::Gaussian, IntegratorConv>::type cezg(expz, gauss, -range , range, integratorConv);
	funct::Constant c(yield);
	typedef funct::Product<funct::Constant, funct::Convolution<ExpZLS, funct::Gaussian, IntegratorConv>::type >::type FitFunction;
	FitFunction f = c * cezg;
	cout << "set functions" << endl;
	typedef fit::HistoChiSquare<FitFunction> ChiSquared;
	ChiSquared chi2(f, zMass, fMin, fMax);
	int fullBins = chi2.numberOfBins();
	cout << "N. deg. of freedom: " << fullBins << endl;
	fit::RootMinuit<ChiSquared> minuit(chi2, true);
	minuit.addParameter(yield, 10, 100, 10000000);
	minuit.addParameter(lambda, 0.1, -100, 100);
	minuit.fixParameter(lambda.name());
	minuit.addParameter(mass, .1, 70., 110);
	minuit.addParameter(gamma, 1, 1, 10);
	minuit.addParameter(f_gamma, 0.1, -100, 1000);
	minuit.addParameter(f_int, .0001, -1000000, 1000000);
	minuit.addParameter(mean, 0.001, -0.5, 0.5);
	minuit.fixParameter(mean.name());
	minuit.addParameter(sigma1, 0.1, -5., 5.);
	minuit.minimize();
	minuit.printFitResults();
	minuit.releaseParameter(lambda.name());
	minuit.minimize();
	minuit.printFitResults();
	vector<shared_ptr<double> > pars;
	pars.push_back(yield.ptr());
	pars.push_back(lambda.ptr());
	pars.push_back(mass.ptr());
	pars.push_back(gamma.ptr());
	pars.push_back(f_gamma.ptr());
	pars.push_back(f_int.ptr());
	pars.push_back(mean.ptr());
	pars.push_back(sigma1.ptr());
	TF1 fun = root::tf1("fun", f, fMin, fMax, pars);
	fun.SetParNames(yield.name().c_str(), lambda.name().c_str(),
			mass.name().c_str(), gamma.name().c_str(), 
			f_gamma.name().c_str(), f_int.name().c_str(), 
			mean.name().c_str(), sigma1.name().c_str());
	fun.SetLineColor(kRed);
	fun.SetNpx(100000);
	TCanvas *canvas = new TCanvas("canvas");
	zMass->Draw("e");
	fun.Draw("same");
	string epsFilename = "ZMassFitCoExBwInGaG_" + v_eps[i];
	canvas->SaveAs(epsFilename.c_str());
	canvas->SetLogy();
	string epsLogFilename = "ZMassFitCoExBwInGaG_Log_" + v_eps[i];
	canvas->SaveAs(epsLogFilename.c_str());
      }
    }
    
    if (vm.count("convbwintgam2gf")) { 
      cout << "Fitting histograms in input files to the convolution of the Breit-Wigner plus Z/photon interference and photon propagator with a linear combination of fixed Gaussians\n";
      cout << ">>> set pars: " << endl;
      cout << yield << endl; 
      cout << alpha << endl; 
      cout << mass  << endl; 
      cout << gamma << endl; 
      cout << f_gamma << endl; 
      cout << f_int  << endl; 
      cout << mean  << endl; 
      cout << sigma1 << endl; 
      cout << sigma2 << endl;
      for(unsigned int i = 0; i < v_ZMassHistos.size(); ++i) { 
	TH1D * zMass = v_ZMassHistos[i];
	funct::ZLineShape zls(mass, gamma, f_gamma, f_int);
	funct::Gaussian gaus1(mean, sigma1);
	funct::Gaussian gaus2(mean, sigma2);
	funct::Number _1(1);
	typedef funct::Product<funct::Constant, funct::Gaussian>::type G1;
	typedef funct::Product<funct::Difference<funct::Number, funct::Constant>::type, 
	  funct::Gaussian>::type G2;
	typedef funct::Product<funct::Constant, funct::Sum<G1, G2>::type>::type GaussComb;
	funct::Constant c_alpha(alpha), c_yield(yield);
	GaussComb gc = c_yield*(c_alpha*gaus1 + (_1 - c_alpha)*gaus2);
	typedef funct::Convolution<funct::ZLineShape, GaussComb, IntegratorConv>::type FitFunction;
	double range = 3 * max(sigma1.value(), sigma2.value());
	FitFunction f(zls, gc, -range , range, integratorConv);
	cout << "set functions" << endl;
	typedef fit::HistoChiSquare<FitFunction> ChiSquared;
	ChiSquared chi2(f, zMass, fMin, fMax);
	int fullBins = chi2.numberOfBins();
	cout << "N. deg. of freedom: " << fullBins << endl;
	fit::RootMinuit<ChiSquared> minuit(chi2, true);
	minuit.addParameter(yield, 10, 100, 10000000);
	minuit.addParameter(alpha, 0.1, -1., 1.);
	minuit.addParameter(mass, .1, 70., 110);
	minuit.addParameter(gamma, 1, 1, 10);
	minuit.addParameter(f_gamma, 0.1, -100, 1000);
	minuit.addParameter(f_int, .0001, -1000000, 1000000);
	minuit.addParameter(mean, 0.001, -0.5, 0.5);
	minuit.fixParameter(mean.name());
	minuit.addParameter(sigma1, 0.1, -5., 5.);
	minuit.addParameter(sigma2, 0.1, -5., 5.);
	minuit.minimize();
	minuit.printFitResults();
	vector<shared_ptr<double> > pars;
	pars.push_back(yield.ptr());
	pars.push_back(alpha.ptr());
	pars.push_back(mass.ptr());
	pars.push_back(gamma.ptr());
	pars.push_back(f_gamma.ptr());
	pars.push_back(f_int.ptr());
	pars.push_back(mean.ptr());
	pars.push_back(sigma1.ptr());
	pars.push_back(sigma2.ptr());
	TF1 fun = root::tf1("fun", f, fMin, fMax, pars);
	fun.SetParNames(yield.name().c_str(), alpha.name().c_str(), 
			mass.name().c_str(), gamma.name().c_str(), 
			f_gamma.name().c_str(), f_int.name().c_str(), 
			mean.name().c_str(), sigma1.name().c_str(), sigma2.name().c_str());
	fun.SetLineColor(kRed);
	TCanvas *canvas = new TCanvas("canvas");
	zMass->Draw("e");
	fun.Draw("same");
	string epsFilename = "ZMassFitCoBwInGaGGf_" + v_eps[i];
	canvas->SaveAs(epsFilename.c_str());
	canvas->SetLogy();
	string epsLogFilename = "ZMassFitCoBwInGaGGf_Log_" + v_eps[i];
	canvas->SaveAs(epsLogFilename.c_str());
      }
    }
    
    cout << "It works!\n";
  }
  catch(std::exception& e) {
    cerr << "error: " << e.what() << "\n";
    return 1;
  }
  catch(...) {
    cerr << "Exception of unknown type!\n";
  }
  return 0;
}
Esempio n. 12
0
void fitD(TString inputdata="/data/dmeson2015/DataDntuple/nt_20160112_DfinderData_pp_20160111_dPt0tkPt1_D0Dstar3p5p_DCSJSON_v2.root", TString inputmc="/afs/cern.ch/work/w/wangj/public/Dmeson/ntD_20151110_DfinderMC_20151110_EvtMatching_Pythia_D0pt15p0_Pthat15_TuneZ2_5020GeV_GENSIM_75x_1015_20151110_ppGlobaTrackingPPmenuHFlowpuv11_MBseed_twang-Pythia_1107.root", TString trgselection="((HLT_DmesonPPTrackingGlobal_Dpt15_v1&&Dpt>25&&Dpt<40)||(HLT_DmesonPPTrackingGlobal_Dpt30_v1&&Dpt>40&&Dpt<60)||(HLT_DmesonPPTrackingGlobal_Dpt50_v1&&Dpt>60))",  TString cut="Dy>-1.&&Dy<1.&&(Dtrk1highPurity&&Dtrk2highPurity)&&(DsvpvDistance/DsvpvDisErr)>3.5&&Dchi2cl>0.05&&Dalpha<0.12&&Dtrk1Pt>1.5&&Dtrk2Pt>1.5", TString selmcgen="((GisSignal==1||GisSignal==2)&&(Gy>-1&&Gy<1))", int isMC=0, Double_t luminosity=26., int doweight=0, TString collsyst="PbPb", TString outputfile="mytest.root")
{
  collisionsystem=collsyst;
  seldata = Form("%s&&%s",trgselection.Data(),cut.Data());
  selmc = Form("%s",cut.Data());

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

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

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

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

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

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

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

  TH1D* hPtSigma= (TH1D*)hPtCor->Clone("hPtSigma");
  hPtSigma->SetTitle(";D^{0} p_{T} (GeV/c);d#sigma(D^{0})/dp_{T} (pb/GeV)");
  hPtSigma->Scale(1./(2*luminosity*BRchain));
  TCanvas* cPtSigma=  new TCanvas("cPtSigma","",600,600);
  cPtSigma->SetLogy();
  hPtSigma->Draw();
  
  TFile* outf = new TFile(outputfile.Data(),"recreate");
  outf->cd();
  hPt->Write();
  hEff->Write();
  hPtGen->Write();
  hPtMC->Write();
  hPtCor->Write();
  hPtSigma->Write();
  hMean->Write();
  hSigmaGaus1->Write();
  hSigmaGaus2->Write();
  hRelMagnGaus1Gaus2->Write();
  outf->Close();
}
Esempio n. 13
0
TF1* fit(TTree* nt, TTree* ntMC, Double_t ptmin, Double_t ptmax, int isMC)
{
  static int count=0;
  count++;

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

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

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

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

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

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

  TLatex* tex;

  tex = new TLatex(0.22,0.78,Form("%.1f < p_{T} < %.1f GeV/c",ptmin,ptmax));
  tex->SetNDC();
  tex->SetTextFont(42);
  tex->SetTextSize(0.04);
  tex->SetLineWidth(2);
  tex->Draw();

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

  h->GetFunction(Form("f%d",count))->Delete();
  TH1F* histo_copy_nofitfun = ( TH1F * ) h->Clone("histo_copy_nofitfun");
  histo_copy_nofitfun->Draw("esame");
//
  if(nBins==1) c->SaveAs(Form("DMass-inclusive%s_%d.pdf",collisionsystem.Data(),count));
  else c->SaveAs(Form("DMass%s_%d.pdf",collisionsystem.Data(),count));
  
  return mass;
}
Esempio n. 14
0
void PlotMacro_Core(string input, string input2, string moduleName, string output)
{
   FILE* pFile;
   TCanvas* c1;
   TObject** Histos = new TObject*[10];                
   std::vector<string> legend;

   unsigned int  tree1_Index;
   unsigned int  tree1_DetId;
   unsigned char tree1_APVId;
   unsigned char tree1_SubDet;
   float         tree1_x;
   float         tree1_y;
   float         tree1_z;
   float         tree1_Eta;
   float         tree1_R;
   float         tree1_Phi;
   float         tree1_Thickness;
   float         tree1_FitMPV;
   float         tree1_FitMPVErr;
   float         tree1_FitWidth;
   float         tree1_FitWidthErr;
   float         tree1_FitChi2NDF;
   double        tree1_Gain;
   double        tree1_PrevGain;
   double        tree1_NEntries;
   bool          tree1_isMasked;


   unsigned int  tree2_Index;
   unsigned int  tree2_DetId;
   unsigned char tree2_APVId;
   unsigned char tree2_SubDet;
   float         tree2_x;
   float         tree2_y;
   float         tree2_z;
   float         tree2_Eta;
   float         tree2_R;
   float         tree2_Phi;
   float         tree2_Thickness;
   float         tree2_FitMPV;
   float         tree2_FitMPVErr;
   float         tree2_FitWidth;
   float         tree2_FitWidthErr;
   float         tree2_FitChi2NDF;
   double        tree2_Gain;
   double        tree2_PrevGain;
   double        tree2_NEntries;
   bool          tree2_isMasked;


   TFile* f1     = new TFile(input.c_str());
   TTree *t1     = (TTree*)GetObjectFromPath(f1,moduleName+"/APVGain");
   TH2D* ChargeDistrib1  = (TH2D*)GetObjectFromPath(f1,moduleName+"/Charge_Vs_Index");
   t1->SetBranchAddress("Index"             ,&tree1_Index      );
   t1->SetBranchAddress("DetId"             ,&tree1_DetId      );
   t1->SetBranchAddress("APVId"             ,&tree1_APVId      );
   t1->SetBranchAddress("SubDet"            ,&tree1_SubDet     );
   t1->SetBranchAddress("x"                 ,&tree1_x          );
   t1->SetBranchAddress("y"                 ,&tree1_y          );
   t1->SetBranchAddress("z"                 ,&tree1_z          );
   t1->SetBranchAddress("Eta"               ,&tree1_Eta        );
   t1->SetBranchAddress("R"                 ,&tree1_R          );
   t1->SetBranchAddress("Phi"               ,&tree1_Phi        );
   t1->SetBranchAddress("Thickness"         ,&tree1_Thickness  );
   t1->SetBranchAddress("FitMPV"            ,&tree1_FitMPV     );
   t1->SetBranchAddress("FitMPVErr"         ,&tree1_FitMPVErr  );
   t1->SetBranchAddress("FitWidth"          ,&tree1_FitWidth   );
   t1->SetBranchAddress("FitWidthErr"       ,&tree1_FitWidthErr);
   t1->SetBranchAddress("FitChi2NDF"        ,&tree1_FitChi2NDF );
   t1->SetBranchAddress("Gain"              ,&tree1_Gain       );
   t1->SetBranchAddress("PrevGain"          ,&tree1_PrevGain   );
   t1->SetBranchAddress("NEntries"          ,&tree1_NEntries   );
   t1->SetBranchAddress("isMasked"          ,&tree1_isMasked   );


   TFile* f2     = new TFile(input2.c_str());
   TTree *t2     = (TTree*)GetObjectFromPath(f2,moduleName+"/APVGain");
   TH2D* ChargeDistrib2  = (TH2D*)GetObjectFromPath(f2,moduleName+"/Charge_Vs_Index");
   t2->SetBranchAddress("Index"             ,&tree2_Index      );
   t2->SetBranchAddress("DetId"             ,&tree2_DetId      );
   t2->SetBranchAddress("APVId"             ,&tree2_APVId      ); 
   t2->SetBranchAddress("SubDet"            ,&tree2_SubDet     );
   t2->SetBranchAddress("x"                 ,&tree2_x          ); 
   t2->SetBranchAddress("y"                 ,&tree2_y          );
   t2->SetBranchAddress("z"                 ,&tree2_z          );
   t2->SetBranchAddress("Eta"               ,&tree2_Eta        ); 
   t2->SetBranchAddress("R"                 ,&tree2_R          ); 
   t2->SetBranchAddress("Phi"               ,&tree2_Phi        );
   t2->SetBranchAddress("Thickness"         ,&tree2_Thickness  ); 
   t2->SetBranchAddress("FitMPV"            ,&tree2_FitMPV     ); 
   t2->SetBranchAddress("FitMPVErr"         ,&tree2_FitMPVErr  ); 
   t2->SetBranchAddress("FitWidth"          ,&tree2_FitWidth   );
   t2->SetBranchAddress("FitWidthErr"       ,&tree2_FitWidthErr);
   t2->SetBranchAddress("FitChi2NDF"        ,&tree2_FitChi2NDF ); 
   t2->SetBranchAddress("Gain"              ,&tree2_Gain       );
   t2->SetBranchAddress("PrevGain"          ,&tree2_PrevGain   );
   t2->SetBranchAddress("NEntries"          ,&tree2_NEntries   );
   t2->SetBranchAddress("isMasked"          ,&tree2_isMasked   ); 

   pFile = fopen("GainDiff.txt","w");

   unsigned int PreviousId = 0;
   unsigned int NAPV       = 0;
   double       MPV1       = 0;
   double       MPV2       = 0;

   double Min = 10000;
   double Max =-10000;

   printf("Progressing Bar              :0%%       20%%       40%%       60%%       80%%       100%%\n");
   printf("Looping on the Tree          :");
   int TreeStep = t1->GetEntries()/50;if(TreeStep==0)TreeStep=1;
   cout<<t1->GetEntries()<<" - "<<t2->GetEntries()<<endl;
   for (unsigned int ientry = 0; ientry < t1->GetEntries(); ientry++) {
      if(ientry%TreeStep==0){printf(".");fflush(stdout);}
      t1->GetEntry(ientry);
      t2->GetEntry(ientry);


       if(tree2_FitMPV>0 and tree2_FitMPV<150){
          TH1D* Proj1         = ChargeDistrib1 ->ProjectionY("proj1" ,tree1_Index, tree1_Index, "e");
          TH1D* Proj2         = ChargeDistrib2 ->ProjectionY("proj2" ,tree2_Index, tree2_Index, "e");

          TCanvas* c1 = new TCanvas("c1", "c1", 600,600);
//          c1->SetLogy(true);


          TH1D* frame = new TH1D("frame", "frame", 1,0, 1000);
          frame->GetXaxis()->SetNdivisions(505);
          frame->SetTitle("");
          frame->SetStats(kFALSE);
          frame->GetXaxis()->SetTitle("charge/path-length (ADC/mm)");
          frame->GetYaxis()->SetTitle("#clusters");
          frame->SetMaximum(std::max(tree1_NEntries, tree2_NEntries)*0.04);
          frame->SetMinimum(0.0);
          frame->GetYaxis()->SetTitleOffset(1.50);
          frame->Draw();

          //Proj1->Scale(1.0/Proj1->Integral());
          Proj1->SetLineColor(2);
          Proj1->SetLineWidth(2);          
          Proj1->Draw("H same"); 

          TF1* Fit1 = new TF1("MyLandau1","landau", 0, 2000);
          Fit1->SetParameters(tree1_NEntries/tree1_FitWidth, tree1_FitMPV, tree1_FitWidth);
          Fit1->SetLineColor(2);
          Fit1->SetLineWidth(2);
          Fit1->Draw("L same");
         
          
          TF1* Fit1b = getPeakOfLandau(Proj1, "MyLandau1bis");
          Fit1b->SetLineColor(8);
          Fit1b->SetLineWidth(2);
          Fit1b->Draw("L same");

          printf("period1 MPV vs new MPV --> %6.2f  vs %6.2f\n", tree1_FitMPV, Fit1b->GetParameter(1));


          //Proj2->Scale(1.0/Proj2->Integral());
          Proj2->SetLineColor(4);
          Proj2->SetLineWidth(2);
          Proj2->Draw("H same");

          TF1* Fit2 = new TF1("MyLandau2","landau", 0, 2000);
          Fit2->SetParameters(tree2_NEntries/tree2_FitWidth, tree2_FitMPV, tree2_FitWidth);
          Fit2->SetLineColor(4);
          Fit2->SetLineWidth(2);
          Fit2->Draw("L same");


          TF1* Fit2b = getPeakOfLandau(Proj2, "MyLandau2bis");
          Fit2b->SetLineColor(8);
          Fit2b->SetLineWidth(2);
          Fit2b->Draw("L same");

          printf("period2 MPV vs new MPV --> %6.2f  vs %6.2f\n", tree2_FitMPV, Fit2b->GetParameter(1));

          char buffer[256];
          sprintf(buffer, "Pictures/Charge/SubDet%i_Id%i_Apv%i_N%i.png",tree1_SubDet, tree1_DetId, tree1_APVId, (int)tree1_NEntries);
          c1->SaveAs(buffer);
       }




      if(tree1_APVId==0 && PreviousId>0){
         double Mean = (MPV2/NAPV) / (MPV1/NAPV);
         if(Mean<Min)Min=Mean;
         if(Mean>Max)Max=Mean;
         if(NAPV>0) fprintf(pFile,"%i  %f\n",PreviousId,Mean);
         NAPV=0; MPV1=0; MPV2=0;
      }
      PreviousId = tree1_DetId;
      if(tree1_FitMPV<=0 || tree2_FitMPV<=0)continue;
      NAPV++;
      MPV1+=tree1_FitMPV;
      MPV2+=tree2_FitMPV;
   }printf("\n");
   fclose(pFile);

   printf("Min=%f - Max=%f\n",Min,Max);
}
void plotTurnOn()
{
  const Int_t INPUTFILES = 4;


  // TString outFileTag = "MBData_200Hz";
  // TString inFileName[INPUTFILES] = {"hist_MBData_zeroWalls.root",
  // 				    "hist_MBData_sigmaSubtraction.root",
  // 				    "hist_MBData_oneByOneAndzeroWalls.root",
  // 				    "hist_MBData_twoByTwoANDzeroWalls.root"
  // };
  // TString labels[INPUTFILES] = {"zeroWalls, L1_40, 206Hz",
  // 				"sigma subtracted, L1_24, 187Hz",
  // 				"1x1 jets +ZW, L1_16, 191Hz",
  // 				"2x2 jets +ZW, L1_52, 228Hz"};
  // const Double_t L1_THRESHOLD[INPUTFILES] = {40, 24, 16, 32};
  // // TString labels[INPUTFILES] = {"zeroWalls, L1_44, 550Hz",
  // // 				"sigma subtracted, L1_20, 505Hz",
  // // 				"1x1 jets +ZW, L1_20, 441Hz",
  // // 				"2x2 jets +ZW, L1_36, 444Hz"};
  // // const Double_t L1_THRESHOLD[INPUTFILES] = {44, 20, 20, 36};

  // TString outFileTag = "Hydjet276_270Hz";
  // TString inFileName[INPUTFILES] = {"hist_Hydjet276_zeroWalls.root",
  // 				    "hist_Hydjet276_sigmaSubtraction.root",
  // 				    "hist_Hydjet276_oneByOneAndzeroWalls.root",
  // 				    "hist_Hydjet276_twoByTwoANDzeroWalls.root"};
  // // const TString labels[INPUTFILES] = {"zeroWalls, L1_60, 104Hz",
  // // 				      "sigma subtracted, L1_28, 102Hz",
  // // 				      "1x1 jets, L1_28, 112Hz",
  // // 				      "2x2 jets, L1_48, 107Hz"};
  // // const Double_t L1_THRESHOLD[INPUTFILES] = {60, 28, 28, 48};
  // const TString labels[INPUTFILES] = {"zeroWalls, L1_40, 276Hz",
  // 				      "sigma subtracted, L1_24, 280Hz",
  // 				      "1x1 jets +ZW, L1_20, 270Hz",
  // 				      "2x2 jets +ZW, L1_32, 272Hz"};
  // const Double_t L1_THRESHOLD[INPUTFILES] = {40, 24, 20, 32};


  // TString outFileTag = "Hydjet502_200Hz";
  // TString inFileName[INPUTFILES] = {"hist_Hydjet502_zeroWalls.root",
  // 				    "hist_Hydjet502_sigmaSubtraction.root",
  // 				    "hist_Hydjet502_oneByOneAndzeroWalls.root",
  // 				    "hist_Hydjet502_twoByTwoANDzeroWalls.root"
  // };
  // // TString labels[INPUTFILES] = {"zeroWalls, L1_80, 150Hz",
  // // 				"sigma subtracted, L1_36, 163Hz",
  // // 				"1x1 jets, L1_36, 167Hz",
  // // 				"2x2 jets, L1_88, 155Hz"};
  // // const Double_t L1_THRESHOLD[INPUTFILES] = {80, 36, 36, 64};

  // TString outFileTag = "Photon502_60GeV";
  // TString inFileName[INPUTFILES] = {"hist_Photon502_isophoton_regions.root",
  // 				    "hist_Photon502_isophotons_eta1.44_2x2jets.root",
  // 				    "hist_Photon502_isophotons_eta1.44_3x3jets.root",
  // 				    "hist_Photon502_isophotons_noHoEorFG_emcands.root"};
  // TString labels[INPUTFILES] = {"Single Regions 50GeV, |#eta| < 1.74",
  // 				"2x2 Jets 48GeV, |#eta| < 1.74",
  // 				"3x3 Jets 48GeV, |#eta| < 1.74",
  // 				"EG cands 50GeV"};
  // const Double_t L1_THRESHOLD[INPUTFILES] = {50, 48, 48,50};

  TString outFileTag = "Photon502_40GeV";
  TString inFileName[INPUTFILES] = {"hist_Photon502_isophoton_regions.root",
  				    "hist_Photon502_isophotons_eta1.44_2x2jets.root",
  				    "hist_Photon502_isophotons_eta1.44_3x3jets.root",
				    "hist_Photon502_isophotons_noHoEorFG_emcands.root"};
  TString labels[INPUTFILES] = {"Single Regions 20GeV, |#eta| < 1.74",
  				"2x2 Jets 24GeV, |#eta| < 1.74",
  				"3x3 Jets 28GeV, |#eta| < 1.74",
  				"EG cands 32GeV"};
  const Double_t L1_THRESHOLD[INPUTFILES] = {20, 24, 28,32};

  TFile *inFile[INPUTFILES];
  const Int_t COLORS[INPUTFILES] = {kBlack, kRed, kBlue, kGreen+3};//, kMagenta+3};
  TGraphAsymmErrors *asymm[INPUTFILES];//[2];

  for(int i = 0; i < INPUTFILES; i++)
  {
    //for(int j = 0; j < 2; j++)
    {
      inFile[i] = TFile::Open(inFileName[i]);
      asymm[i] = (TGraphAsymmErrors*)inFile[i]->Get(Form("asymm_pt_%d_0",(int)L1_THRESHOLD[i]));
      asymm[i]->SetMarkerColor(COLORS[i]);
      asymm[i]->SetLineColor(COLORS[i]);
    }
    //asymm[i][1]->SetMarkerStyle(25);
  }

  // these values MUST MATCH those used in makeTurnOn.C
  const int nBins = 75;
  const double maxPt = 200;

  TH1D *hEmpty = new TH1D("hEmpty",Form(";Isolated Photon p_{T} (GeV);Efficiency"),nBins,0,maxPt);

  TCanvas *c1 = new TCanvas();
  hEmpty->SetMinimum(0);
  hEmpty->SetMaximum(1.2);
  hEmpty->Draw();
  //c1->SetLogy();

  TLine *line = new TLine(0,1,maxPt,1);
  line->Draw();

  for(int i = 0; i < INPUTFILES; i++)
  {
    //for(int j = 0; j < 2; j++)
    {
      asymm[i]->Draw("p");
    }
  }

  TLegend *leg = new TLegend(0.55,0.2,0.9,0.5,"|#eta| < 1.44");
  leg->SetFillColor(0);
  leg->SetTextFont(42);
  leg->SetTextSizePixels(18);

  for(int i = 0; i < INPUTFILES; i++)
  {
    //for(int j = 0; j < 2; j++)
    {
      leg->AddEntry(asymm[i], Form("%s", labels[i].Data()), "lp");
    }
  }

  leg->Draw();

  c1->SaveAs(Form("%s_turnon.pdf",outFileTag.Data()));

}
void PtSpectraCombination_StagedNormalization_EtaCM_P08_P13_NoOLDAlignmentRuns_CombpPbPbp()
{
   gROOT->Reset();
   gROOT->ProcessLine(".x rootlogonChristof.C");
   gROOT->ForceStyle();
   gStyle->SetPalette(1);
   gStyle->SetTitleYOffset(1.27);
   gStyle->SetOptFit(0000);
//   gStyle->SetPadRightMargin(0.16);

   bool doSave = true;

   TFile *f_minbias_pPb = new TFile("CombineSpectra_minbias_EtaCM_P08_P13_NoOLDAlignmentRuns.root");
   TFile *f_FullTrack_12_pPb = new TFile("CombineSpectra_FullTrackTrigger_Track12_EtaCM_P08_P13_NoOLDAlignmentRuns.root");
   TFile *f_FullTrack_20_pPb = new TFile("CombineSpectra_FullTrackTrigger_Track20_EtaCM_P08_P13_NoOLDAlignmentRuns.root");
   TFile *f_FullTrack_30_pPb = new TFile("CombineSpectra_FullTrackTrigger_Track30_EtaCM_P08_P13_NoOLDAlignmentRuns.root");

   TFile *f_minbias_Pbp = new TFile("ReverseBeam/CombineSpectra_minbias_EtaCM_M08_M13.root");
   TFile *f_FullTrack_12_Pbp = new TFile("ReverseBeam/CombineSpectra_FullTrackTrigger_Track12_EtaCM_M08_M13.root");
   TFile *f_FullTrack_20_Pbp = new TFile("ReverseBeam/CombineSpectra_FullTrackTrigger_Track20_EtaCM_M08_M13.root");
   TFile *f_FullTrack_30_Pbp = new TFile("ReverseBeam/CombineSpectra_FullTrackTrigger_Track30_Track50_EtaCM_M08_M13.root");

   TFile *f_out = new TFile("PtSpectraCombination_StagedNormalization_EtaCM_P08_P13_NoOLDAlignmentRuns_CombpPbPbp_TrackTrigger.root","recreate");

   //Get spectra
   TH1D* hPartPt_minbias_corrected_pPb = (TH1D*)f_minbias_pPb->Get("hPartPt_minbias_trkCorr_trigCorr");
   TH1D* hPartPt_0_14_minbias_corrected_pPb = (TH1D*)f_minbias_pPb->Get("hPartPt_0_14_minbias_trkCorr_trigCorr");
   TH1D* hPartPt_14_22_FullTrack12_corrected_pPb = (TH1D*)f_FullTrack_12_pPb->Get("hPartPt_FullTrack12_14_22_trkCorr_trigCorr");
   TH1D* hPartPt_22_32_FullTrack20_corrected_pPb = (TH1D*)f_FullTrack_20_pPb->Get("hPartPt_FullTrack20_22_32_trkCorr_trigCorr");
   TH1D* hPartPt_32_X_FullTrack30_corrected_pPb = (TH1D*)f_FullTrack_30_pPb->Get("hPartPt_FullTrack30_SpectComb_trkCorr_trigCorr");

   TH1D* hPartPt_minbias_corrected_Pbp = (TH1D*)f_minbias_Pbp->Get("hPartPt_minbias_trkCorr_trigCorr");
   TH1D* hPartPt_0_14_minbias_corrected_Pbp = (TH1D*)f_minbias_Pbp->Get("hPartPt_0_14_minbias_trkCorr_trigCorr");
   TH1D* hPartPt_14_22_FullTrack12_corrected_Pbp = (TH1D*)f_FullTrack_12_Pbp->Get("hPartPt_FullTrack12_14_22_trkCorr_trigCorr");
   TH1D* hPartPt_22_32_FullTrack20_corrected_Pbp = (TH1D*)f_FullTrack_20_Pbp->Get("hPartPt_FullTrack20_22_32_trkCorr_trigCorr");
   TH1D* hPartPt_32_X_FullTrack30_corrected_Pbp = (TH1D*)f_FullTrack_30_Pbp->Get("hPartPt_FullTrack30_SpectComb_trkCorr_trigCorr");

   TH1D* hPartPt_minbias_corrected = (TH1D*)hPartPt_minbias_corrected_pPb->Clone("hPartPt_minbias_corrected"); hPartPt_minbias_corrected->Add(hPartPt_minbias_corrected_Pbp);
   TH1D* hPartPt_0_14_minbias_corrected = (TH1D*)hPartPt_0_14_minbias_corrected_pPb->Clone("hPartPt_0_14_minbias_corrected"); hPartPt_0_14_minbias_corrected->Add(hPartPt_0_14_minbias_corrected_Pbp);
   TH1D* hPartPt_14_22_FullTrack12_corrected = (TH1D*)hPartPt_14_22_FullTrack12_corrected_pPb->Clone("hPartPt_14_22_FullTrack12_corrected"); hPartPt_14_22_FullTrack12_corrected->Add(hPartPt_14_22_FullTrack12_corrected_Pbp);
   TH1D* hPartPt_22_32_FullTrack20_corrected = (TH1D*)hPartPt_22_32_FullTrack20_corrected_pPb->Clone("hPartPt_22_32_FullTrack20_corrected"); hPartPt_22_32_FullTrack20_corrected->Add(hPartPt_22_32_FullTrack20_corrected_Pbp);
   TH1D* hPartPt_32_X_FullTrack30_corrected = (TH1D*)hPartPt_32_X_FullTrack30_corrected_pPb->Clone("hPartPt_32_X_FullTrack30_corrected"); hPartPt_32_X_FullTrack30_corrected->Add(hPartPt_32_X_FullTrack30_corrected_Pbp);
/*
   hPartPt_0_14_minbias_corrected_pPb->SetBinContent(hPartPt_0_14_minbias_corrected_pPb->FindBin(103.24),0);//Remove muon event
   hPartPt_0_14_minbias_corrected_pPb->SetBinError(hPartPt_0_14_minbias_corrected_pPb->FindBin(103.24),0);//Remove muon event
   hPartPt_minbias_corrected_pPb->SetBinContent(hPartPt_minbias_corrected_pPb->FindBin(103.24),0);//Remove muon event
   hPartPt_minbias_corrected_pPb->SetBinError(hPartPt_minbias_corrected_pPb->FindBin(103.24),0);//Remove muon event
*/
   //Get number of events
   TH1D* hNumEv_minbias_pPb = (TH1D*)f_minbias_pPb->Get("hNumEv_minbias_trigCorr");
   TH1D* hNumEv_0_14_minbias_pPb = (TH1D*)f_minbias_pPb->Get("hNumEv_0_14_minbias_trigCorr");
   TH1D* hNumEv_14_22_minbias_pPb = (TH1D*)f_minbias_pPb->Get("hNumEv_14_22_minbias_trigCorr");
   TH1D* hNumEv_14_22_FullTrack12_pPb = (TH1D*)f_FullTrack_12_pPb->Get("hNumEv_FullTrack12_14_22_trigCorr");
   TH1D* hNumEv_22_32_FullTrack12_pPb = (TH1D*)f_FullTrack_12_pPb->Get("hNumEv_FullTrack12_22_32_trigCorr");
   TH1D* hNumEv_22_32_FullTrack20_pPb = (TH1D*)f_FullTrack_20_pPb->Get("hNumEv_FullTrack20_22_32_trigCorr");
   TH1D* hNumEv_32_X_FullTrack20_pPb = (TH1D*)f_FullTrack_20_pPb->Get("hNumEv_FullTrack20_32_X_trigCorr");
   TH1D* hNumEv_32_X_FullTrack30_pPb = (TH1D*)f_FullTrack_30_pPb->Get("hNumEv_FullTrack30_32_X_trigCorr");

   TH1D* hNumEv_minbias_Pbp = (TH1D*)f_minbias_Pbp->Get("hNumEv_minbias_trigCorr");
   TH1D* hNumEv_0_14_minbias_Pbp = (TH1D*)f_minbias_Pbp->Get("hNumEv_0_14_minbias_trigCorr");
   TH1D* hNumEv_14_22_minbias_Pbp = (TH1D*)f_minbias_Pbp->Get("hNumEv_14_22_minbias_trigCorr");
   TH1D* hNumEv_14_22_FullTrack12_Pbp = (TH1D*)f_FullTrack_12_Pbp->Get("hNumEv_FullTrack12_14_22_trigCorr");
   TH1D* hNumEv_22_32_FullTrack12_Pbp = (TH1D*)f_FullTrack_12_Pbp->Get("hNumEv_FullTrack12_22_32_trigCorr");
   TH1D* hNumEv_22_32_FullTrack20_Pbp = (TH1D*)f_FullTrack_20_Pbp->Get("hNumEv_FullTrack20_22_32_trigCorr");
   TH1D* hNumEv_32_X_FullTrack20_Pbp = (TH1D*)f_FullTrack_20_Pbp->Get("hNumEv_FullTrack20_32_X_trigCorr");
   TH1D* hNumEv_32_X_FullTrack30_Pbp = (TH1D*)f_FullTrack_30_Pbp->Get("hNumEv_FullTrack30_32_X_trigCorr");

   TH1D* hNumEv_minbias = (TH1D*)hNumEv_minbias_pPb->Clone("hNumEv_minbias"); hNumEv_minbias->Add(hNumEv_minbias_Pbp);
   TH1D* hNumEv_0_14_minbias = (TH1D*)hNumEv_0_14_minbias_pPb->Clone("hNumEv_0_14_minbias"); hNumEv_0_14_minbias->Add(hNumEv_0_14_minbias_Pbp);
   TH1D* hNumEv_14_22_minbias = (TH1D*)hNumEv_14_22_minbias_pPb->Clone("hNumEv_14_22_minbias"); hNumEv_14_22_minbias->Add(hNumEv_14_22_minbias_Pbp);
   TH1D* hNumEv_14_22_FullTrack12 = (TH1D*)hNumEv_14_22_FullTrack12_pPb->Clone("hNumEv_14_22_FullTrack12"); hNumEv_14_22_FullTrack12->Add(hNumEv_14_22_FullTrack12_Pbp);
   TH1D* hNumEv_22_32_FullTrack12 = (TH1D*)hNumEv_22_32_FullTrack12_pPb->Clone("hNumEv_22_32_FullTrack12"); hNumEv_22_32_FullTrack12->Add(hNumEv_22_32_FullTrack12_Pbp);
   TH1D* hNumEv_22_32_FullTrack20 = (TH1D*)hNumEv_22_32_FullTrack20_pPb->Clone("hNumEv_22_32_FullTrack20"); hNumEv_22_32_FullTrack20->Add(hNumEv_22_32_FullTrack20_Pbp);
   TH1D* hNumEv_32_X_FullTrack20 = (TH1D*)hNumEv_32_X_FullTrack20_pPb->Clone("hNumEv_32_X_FullTrack20"); hNumEv_32_X_FullTrack20->Add(hNumEv_32_X_FullTrack20_Pbp);
   TH1D* hNumEv_32_X_FullTrack30 = (TH1D*)hNumEv_32_X_FullTrack30_pPb->Clone("hNumEv_32_X_FullTrack30"); hNumEv_32_X_FullTrack30->Add(hNumEv_32_X_FullTrack30_Pbp);

   float numev_minbias = hNumEv_minbias->GetBinContent(1);
   float numev_0_14_minbias = hNumEv_0_14_minbias->GetBinContent(1);
   float numev_14_22_minbias = hNumEv_14_22_minbias->GetBinContent(1);
   float numev_14_22_FullTrack12 = hNumEv_14_22_FullTrack12->GetBinContent(1);
   float numev_22_32_FullTrack12 = hNumEv_22_32_FullTrack12->GetBinContent(1);
   float numev_22_32_FullTrack20 = hNumEv_22_32_FullTrack20->GetBinContent(1);
   float numev_32_X_FullTrack20 = hNumEv_32_X_FullTrack20->GetBinContent(1);
   float numev_32_X_FullTrack30 = hNumEv_32_X_FullTrack30->GetBinContent(1);

   std::cerr<<" Number of minbias events in the normalization classes:" << std::endl;
   std::cerr<<"   All      : " << numev_minbias << std::endl;
   std::cerr<<"    0-14 MB : " << numev_0_14_minbias << std::endl;
   std::cerr<<"   14-22 MB : " << numev_14_22_minbias << std::endl;
   std::cerr<<"   14-22 T12: " << numev_14_22_FullTrack12 << std::endl;
   std::cerr<<"   22-32 T12: " << numev_22_32_FullTrack12 << std::endl;
   std::cerr<<"   22-32 T20: " << numev_22_32_FullTrack20 << std::endl;
   std::cerr<<"   32-X  T20: " << numev_32_X_FullTrack20 << std::endl;
   std::cerr<<"   32-X  T30: " << numev_32_X_FullTrack30 << std::endl;

   std::cerr<<" numev_minbias/numev_0_14_minbias: " << 100.*numev_minbias/numev_0_14_minbias << "%" << std::endl;
   std::cerr<<" numev_14_22_minbias/numev_0_14_minbias: " << 100.*numev_14_22_minbias/numev_0_14_minbias << "%" << std::endl;
   std::cerr<<" numev_14_22_FullTrack12/numev_22_32_FullTrack12: " << 100.*numev_14_22_FullTrack12/numev_22_32_FullTrack12 << std::endl;

   //Prepare the individual normalizations
   float norm_0_14_minbias = numev_minbias;
   float norm_14_22_FullTrack12 = norm_0_14_minbias*numev_14_22_FullTrack12/numev_14_22_minbias;
//   float norm_14_22_FullTrack12 = numev_14_22_FullTrack12*2466.480;
   float norm_22_32_FullTrack20 = norm_14_22_FullTrack12*numev_22_32_FullTrack20/numev_22_32_FullTrack12;
   float norm_32_X_FullTrack30 = norm_22_32_FullTrack20*numev_32_X_FullTrack30/numev_32_X_FullTrack20;

   std::cerr<<"Normalization factors:" << std::endl;
   std::cerr<<"      norm_0_14_minbias     : " << norm_0_14_minbias << std::endl;
   std::cerr<<"      norm_14_22_FullTrack12: " << norm_14_22_FullTrack12 << std::endl;
   std::cerr<<"      norm_22_32_FullTrack20: " << norm_22_32_FullTrack20 << std::endl;
   std::cerr<<"      norm_32_X_FullTrack30 : " << norm_32_X_FullTrack30 << std::endl;

   hPartPt_minbias_corrected->Scale(1./numev_minbias);
   hPartPt_0_14_minbias_corrected->Scale(1./norm_0_14_minbias);
   hPartPt_14_22_FullTrack12_corrected->Scale(1./norm_14_22_FullTrack12);
   hPartPt_22_32_FullTrack20_corrected->Scale(1./norm_22_32_FullTrack20);
   hPartPt_32_X_FullTrack30_corrected->Scale(1./norm_32_X_FullTrack30);

   TCanvas *c1 = new TCanvas("c1","c1");
   c1->cd();
   c1->SetLogy();
   hPartPt_0_14_minbias_corrected->GetXaxis()->CenterTitle();
   hPartPt_0_14_minbias_corrected->GetYaxis()->CenterTitle();
   hPartPt_0_14_minbias_corrected->GetXaxis()->SetTitle("p_{T} [GeV/c]");
   hPartPt_0_14_minbias_corrected->GetYaxis()->SetTitle("1/N_{ev} dN/dp_{T} (|#eta_{CM}|<1)");
//   hPartPt_0_14_minbias_corrected->SetNdivisions(505);
   hPartPt_0_14_minbias_corrected->SetMarkerColor(42);
   hPartPt_0_14_minbias_corrected->SetLineColor(42);
   hPartPt_0_14_minbias_corrected->SetMarkerStyle(34);
   hPartPt_0_14_minbias_corrected->SetMinimum(1e-11);
   hPartPt_0_14_minbias_corrected->SetFillColor(42);
//   hPartPt_0_14_minbias_corrected->SetFillStyle(3305);
   hPartPt_0_14_minbias_corrected->Draw("hist");

   hPartPt_minbias_corrected->SetMarkerStyle(20);
   hPartPt_minbias_corrected->Draw("same");

   hPartPt_14_22_FullTrack12_corrected->SetMarkerColor(2);
   hPartPt_14_22_FullTrack12_corrected->SetLineColor(2);
   hPartPt_14_22_FullTrack12_corrected->SetMarkerStyle(20);
   hPartPt_14_22_FullTrack12_corrected->SetFillColor(2);
   hPartPt_14_22_FullTrack12_corrected->SetFillStyle(3002);
   hPartPt_14_22_FullTrack12_corrected->Draw("same");

   hPartPt_22_32_FullTrack20_corrected->SetMarkerColor(4);
   hPartPt_22_32_FullTrack20_corrected->SetLineColor(4);
   hPartPt_22_32_FullTrack20_corrected->SetMarkerStyle(20);
//   hPartPt_22_32_FullTrack20_corrected->SetFillColor(2);
//   hPartPt_22_32_FullTrack20_corrected->SetFillStyle(3002);
   hPartPt_22_32_FullTrack20_corrected->Draw("samehist");

   hPartPt_32_X_FullTrack30_corrected->SetMarkerColor(2);
   hPartPt_32_X_FullTrack30_corrected->SetLineColor(2);
   hPartPt_32_X_FullTrack30_corrected->SetMarkerStyle(20);
//   hPartPt_32_X_FullTrack30_corrected->SetFillColor(2);
//   hPartPt_32_X_FullTrack30_corrected->SetFillStyle(3002);
   hPartPt_32_X_FullTrack30_corrected->Draw("samehist");

   //Sum
   TH1D * hSumPartPt = (TH1D*)hPartPt_0_14_minbias_corrected->Clone("hSumPartPt");
   hSumPartPt->Add(hPartPt_14_22_FullTrack12_corrected);
   hSumPartPt->Add(hPartPt_22_32_FullTrack20_corrected);
   hSumPartPt->Add(hPartPt_32_X_FullTrack30_corrected);
   hSumPartPt->SetMarkerStyle(25);
   hSumPartPt->SetMarkerColor(1);
   hSumPartPt->SetLineColor(1);
   hSumPartPt->Draw("same");

   TLegend *leg1 = new TLegend(0.48,0.47,0.93,0.95,NULL,"brNDC");
   leg1->AddEntry(hPartPt_minbias_corrected,"MinBias, inclusive","pl");
   leg1->AddEntry(hPartPt_0_14_minbias_corrected,"MinBias, p_{T}<14 GeV/c","f");
   leg1->AddEntry(hPartPt_14_22_FullTrack12_corrected,"FullTrack12, 14<p_{T}<22 GeV/c","pl");
   leg1->AddEntry(hPartPt_22_32_FullTrack20_corrected,"FullTrack20, 22<p_{T}<32 GeV/c","l");
   leg1->AddEntry(hPartPt_32_X_FullTrack30_corrected,"FullTrack30, 32<p_{T} GeV/c","l");
   leg1->AddEntry(hSumPartPt,"Combined spectrum","pl");
   leg1->SetFillStyle(0);
   leg1->SetFillColor(0);
   leg1->SetBorderSize(0);
   leg1->Draw();
   if(doSave) {
      c1->SaveAs("Figs/PtSpectraCombination_StagedNormalization_EtaCM_P08_P13_NoOLDAlignmentRuns_CombpPbPbp_c1.gif");
      c1->SaveAs("Figs/PtSpectraCombination_StagedNormalization_EtaCM_P08_P13_NoOLDAlignmentRuns_CombpPbPbp_c1.eps");
      c1->SaveAs("Figs/PtSpectraCombination_StagedNormalization_EtaCM_P08_P13_NoOLDAlignmentRuns_CombpPbPbp_c1.C");
   }


   TCanvas *c2 = new TCanvas("c2","c2");
   c2->cd();
   TH1D *hSumPartPt_copy1 = (TH1D*)hSumPartPt->Clone("hSumPartPt_copy1");
   hSumPartPt_copy1->Divide(hPartPt_minbias_corrected);
   hSumPartPt_copy1->GetYaxis()->SetTitle("Combined spectrum / MB inclusive");
   hSumPartPt_copy1->Draw();

   TLatex *inf1 = new TLatex(0.33,0.17,"Combined spectrum: from track triggers");
   inf1->SetNDC();
   inf1->SetTextSize(0.035);
   inf1->Draw();

   TPad *c2_zoom = new TPad("c2_zoom","c2_zoom",0.56,0.56,0.94,0.93);
   c2_zoom->SetFillStyle(0);
   c2_zoom->SetLogx();
   c2_zoom->Draw();
   c2_zoom->cd();
   TH1D *hSumPartPt_copy2 = (TH1D*)hSumPartPt_copy1->Clone("hSumPartPt_copy2");
   hSumPartPt_copy2->GetXaxis()->CenterTitle();
   hSumPartPt_copy2->GetYaxis()->CenterTitle();
   hSumPartPt_copy2->GetXaxis()->SetTitle("p_{T} [GeV/c]");
   hSumPartPt_copy2->GetYaxis()->SetTitle("Combined spectrum / MB inclusive ");
   hSumPartPt_copy2->GetXaxis()->SetRangeUser(0.,18.);
   hSumPartPt_copy2->SetMinimum(0.95);
   hSumPartPt_copy2->SetMaximum(1.05);
   hSumPartPt_copy2->Draw();
   if(doSave) {
      c2->SaveAs("Figs/PtSpectraCombination_StagedNormalization_EtaCM_P08_P13_NoOLDAlignmentRuns_CombpPbPbp_c2.gif");
      c2->SaveAs("Figs/PtSpectraCombination_StagedNormalization_EtaCM_P08_P13_NoOLDAlignmentRuns_CombpPbPbp_c2.eps");
      c2->SaveAs("Figs/PtSpectraCombination_StagedNormalization_EtaCM_P08_P13_NoOLDAlignmentRuns_CombpPbPbp_c2.C");
   }

/*
   TLegend *leg2 = new TLegend(0.80,0.75,0.95,0.95,NULL,"brNDC");
   leg2->AddEntry(hPartPt_Jet40_copy1,"Jet40","pl");
   leg2->AddEntry(hPartPt_Jet60_copy1,"Jet60","pl");
   leg2->AddEntry(hPartPt_Jet80_copy1,"Jet80","pl");
   leg2->AddEntry(hPartPt_Jet100_copy1,"Jet100","pl");
   leg2->SetFillStyle(0);
   leg2->SetFillColor(0);
   leg2->SetBorderSize(0);
   leg2->Draw();
*/
   
  f_out->cd();
  hSumPartPt->Write();
  f_out->Close();

}
Esempio n. 17
0
void dumpStg6Results(string inFile,string outFile, int nEvents = 0,bool useRBM = 1,double theta2Cut = 0.03, bool NoFromStg5 = true,string Stg5Path = "/data/veritas/bzitzer/bootes_1/data/root/")
{
  gROOT->SetBatch(true);
  TH1D* hSigRF = new TH1D("SigDistRF","Significance Distrbution RF",50,-5,5);
  TH1D* hSigCBG = new TH1D("SigDistCBG","Significance Distrbution CBG",50,-5,5);
  
  // Opening files and getting VEGAS objects:
  TFile* f = new TFile(inFile.c_str(),"READ");
  if(!f->IsOpen() )
    {
      cerr << "Problem opening ROOT file!" << endl;
      return;
    }
  TTree* EventTree = (TTree*)gDirectory->Get("EventStatsTree");
  if( EventTree == NULL )
    {
      cout << "No Event Tree!" << endl;
      return;
    }
  TTree* RunTree = (TTree*)gDirectory->Get("RunStatsTree");
  if( RunTree == NULL )
    {
      cout << "No Run Tree!" << endl;
      return;
    }
  VASkyMap* vaMapOn = (VASkyMap*)gDirectory->Get("RingBackgroundModelAnalysis/SkyMapOn");
  VASkyMap* vaMapAlpha = (VASkyMap*)gDirectory->Get("RingBackgroundModelAnalysis/fAlphaMap");
  VACoordinatePair onCenter = vaMapOn->GetCenter();
  VACoordinatePair eventCoord;
  VACoordinatePair trackCoord;
  VACoordinatePair fRootCoord;
  VACoordinatePair sourceCoord;

  // --------------------
  //  Exclusion regions:
  // --------------------
    
  TDirectory* RBMExclusion = (TDirectory*)gDirectory->Get("RingBackgroundModelAnalysis/ExclusionRegions");

  if( RBMExclusion == NULL )
    {
      cerr << "Problem loading the RBM exclusion directory!" << endl;
      return;
    }
  int nRegions = RBMExclusion->GetNkeys();
  VASkyMapExclusionRegion* hSourceExclusion;
  const int tmp = nRegions;
  VASkyMapExclusionRegion* exclList[tmp];
  vector<VASkyMapExclusionRegion*> vaSourceExcl;

  TIter next(RBMExclusion->GetListOfKeys());
  TKey *key;
  int i=0;
  while(key=(TKey*)next())
    {
      hSourceExclusion = (VASkyMapExclusionRegion*)RBMExclusion->FindObjectAny(key->GetName())->Clone();
      if( hSourceExclusion != NULL)
	{
	  if( hSourceExclusion->wasUsed() )
	    {
	      cout << i << endl;
	      exclList[i] = hSourceExclusion;
	      vaSourceExcl.push_back(hSourceExclusion);
	      cout << hSourceExclusion->GetName() << endl;
	      //cout << "Exclusion Center RA: " << hSourceExclusion->center().getRA_J2000_Deg() << endl;
	      cout << "Exclusion Center RA: " << exclList[i]->center().getRA_J2000_Deg() << endl;
	      
	      cout << "Exclusion Center Dec: " << hSourceExclusion->center().getDec_J2000_Deg() << endl;	  
	      cout << "Exclusion Radius: " << hSourceExclusion->radius_Deg() << endl;
	      i++;
	    }
	}
    }
  nRegions = i;
  dumpExcl(exclList,nRegions,outFile);


  double TelLatRad = 5.52828386357865242e-01;
  double TelLongRad = -1.93649167430676461e+00;
  Float_t EffArea,EnergyGeV,El,Az;
  double RA,Dec;
  double RATrack,DecTrack;
  double DayNS;
  UInt_t MJD;
  UInt_t RunID;
  Float_t El_track,Az_track;
  Float_t El_check,Az_check;
  double MJDDbl;
  Double_t W;
  Double_t liveTime;
  Double_t PsiEventTree;

  int NumRuns = RunTree->GetEntries(); 
  Bool_t IsOn,IsOff;
  double Noise;
  Float_t RA_fRoot,Dec_fRoot;

  EventTree->SetBranchAddress("RunNum",&RunID);
  EventTree->SetBranchAddress("Azimuth",&Az);
  EventTree->SetBranchAddress("Elevation",&El);
  EventTree->SetBranchAddress("Noise",&Noise);
  EventTree->SetBranchAddress("EnergyGeV",&EnergyGeV);
  
  EventTree->SetBranchAddress("TrackingAzimuth",&Az_track);
  EventTree->SetBranchAddress("TrackingElevation",&El_track);
  EventTree->SetBranchAddress("OnEvent",&IsOn);  
  EventTree->SetBranchAddress("OffEvent",&IsOff);    
  EventTree->SetBranchAddress("Weight",&W);
  EventTree->SetBranchAddress("Psi",&PsiEventTree);

  // EventTree->SetBranchAddress("RA",&RA_fRoot);    
  // EventTree->SetBranchAddress("Dec",&Dec_fRoot);
  
  EventTree->SetBranchAddress("MJDDbl",&MJDDbl);
  EventTree->SetBranchAddress("DayNSDbl",&DayNS);
  EventTree->SetBranchAddress("EffectiveArea",&EffArea);

  double RASource,DecSource,RAOffset,DecOffset;
  double RAError,DecError;
  double fSigRF,fSigCBG;
  int RunNumRunTree;
  RunTree->SetBranchAddress("faLiveTime",&liveTime);
  RunTree->SetBranchAddress("fSourceDecDeg",&DecSource);
  RunTree->SetBranchAddress("fSourceRADeg",&RASource);
  RunTree->SetBranchAddress("fOffsetDecDeg",&DecOffset);
  RunTree->SetBranchAddress("fOffsetRADeg",&RAOffset);
  RunTree->SetBranchAddress("fSignificance",&fSigRF);
  RunTree->SetBranchAddress("faRunNumber",&RunNumRunTree);
  // Signficance distributions:
 
  VAAzElRADecXY coord(TelLongRad,TelLatRad);
  VATime time;
  TGraph* map = new TGraph();
  TGraph* trackError = new TGraph();
  TH2D* map2 = new TH2D("skymap","raw counts map",100,65,115,100,10,30);
  double X,Y;
  double XRot,YRot;
  double theta;

  double RunIDOld = 0;
  int j = 0;
  int k = 0;

  filebuf fb;
  fb.open(outFile.c_str(),ios::out);
  ostream os(&fb);

  TGraph* geffAreaVTime = new TGraph();

  if( nEvents == 0 ){ nEvents = EventTree->GetEntries(); }
  
  int NumOnEvents = 0;
  int NumOffEvents = 0;
  // Stuff to make RBM work;
  double upperRadRBM = 0.8;
  double lowerRadRBM = 0.6;
  double angularSep,psi;
  bool IsInExcl;

  // Stuff to make zCresent work:
  double areaBgRegion = DBL_EPSILON;
  double upperRadCres = 0.4;
  double lowerRadCres = 0.6;
  double areaOnRegion = TMath::TwoPi()*(1.0 - TMath::Cos(TMath::Sqrt(theta2Cut)*TMath::DegToRad())); // rad^2
  areaOnRegion *= pow(TMath::RadToDeg(),2.0); // deg^2
  //double areaOnRegion = TMath::Pi()*theta2Cut;

  double wobOffset;

  // vaStage6 Generalized LiMa calc stuff:
  vector<double> Non;
  vector<double> Noff;
  vector<double> Alpha;
  vector<double> ExpOn;
  vector<double> ExpOff;
  vector<int> RunIDVec;
  vector<double> SigmaVec;
  int NumRuns = 0;
  // header

  os << "RunID LiveTime(min) Time(MJD) RA       Dec       RA_track        Dec_track    Energy(GeV)  IsOn Weight Elevation Azimuth Noise Offset" << endl;
  os << "----------------------------------------------------------------------------------------------------------" << endl;
  cout.precision(12);
  os.precision(7);
  
  double AvgNoiseFromStg5;
  
  for(int i=0; i<nEvents; i++)
    {
      
      EventTree->GetEntry(i);
     
      if(i%1000==0)
	cout << "On Event: " << i << " of " << nEvents <<endl;

      if(RunID != RunIDOld)
	{
	  // A new run has started:
	  if(RunIDOld != 0)
	    {
	      Non.push_back(NumOnEvents);
	      Noff.push_back(NumOffEvents);
	      ExpOn.push_back(liveTime/60);
	      ExpOff.push_back(liveTime/60);
	      Alpha.push_back(areaOnRegion/areaBgRegion);
	      cout << RunIDOld << " Non: " << NumOnEvents << " Noff: " << NumOffEvents << " Alpha: " << areaOnRegion/areaBgRegion << " Exp: " << liveTime/60 << endl;
	      fSigCBG = lima(NumOnEvents,NumOffEvents,areaOnRegion/areaBgRegion);
	      SigmaVec.push_back(fSigCBG);
	      RunIDVec.push_back(RunIDOld);
	      hSigCBG->Fill(fSigCBG);
	     
	      NumOnEvents = 0;
	      NumOffEvents = 0;
	      
	    }
      
	  RunTree->GetEntry(j);	
	  if(RunID != RunNumRunTree)
	    {
	      cout << "Run mis-match! " << endl;
	      cout << " Event Tree thinks it is run number: " << RunID << endl;
	      cout << " Run Tree thinks it is run number: " << RunNumRunTree << endl;

	    }
	  j++;
	  hSigRF->Fill(fSigRF);
	  cout << fSigRF << endl;
	  // RASource, RAOffset in Deg
	  if(NoFromStg5 == true)
	    AvgNoiseFromStg5 = getAvgPedVar(RunID,Stg5Path);
	   
	 
	  // I confess to a bit of a Kludge here:
	  coord.setRASource2000((RASource + RAOffset)*TMath::DegToRad());
	  coord.setDecSource2000((DecSource + DecOffset)*TMath::DegToRad());
	  sourceCoord.setCoordinates_Deg(RASource,DecSource,2);
	  cout << RunID << " " << liveTime << " " << RASource << " " << DecSource << " " << RAOffset << " " << DecOffset << endl; 
	}
  
      time.setFromMJDDbl(MJDDbl);
      // --------------------
      //  Coordinate transforms:
      // --------------------

      // Az,El already in radians
      coord.AzEl2RADec2000(Az,El,time,RA,Dec); // RA,Dec in radians
      // Az_track, El_track in degrees
      coord.AzEl2RADec2000(Az_track*TMath::DegToRad(),El_track*TMath::DegToRad(),time,RATrack,DecTrack); // RATrack,DecTrack in radians
      coord.AzElToXY(Az,El,time,RASource*TMath::DegToRad(),DecSource*TMath::DegToRad(),X,Y); 
      coord.AzElToXY(Az,El,time,X,Y); 
      // coord.XY2RADec2000(X,Y,time,RA,Dec);
      coord.Derotate(time,X,Y,RATrack*TMath::DegToRad(),DecTrack*TMath::DegToRad(),XRot,YRot);
      // Flip axis:
      //XRot = -1.0*XRot;
      // RA Dec in Degrees now
      RA *= TMath::RadToDeg();
      Dec *= TMath::RadToDeg();
      RATrack *= TMath::RadToDeg();
      DecTrack *= TMath::RadToDeg();
          
      // RA_fRoot *= TMath::RadToDeg();
      // Dec_fRoot *= TMath::RadToDeg();
      // RA = XRot + RATrack - RAOffset;
      //Dec = YRot + DecTrack - DecOffset;
      // RAError = RA - RA_fRoot;
      // DecError = Dec - Dec_fRoot;
      RAError = RASource - (RATrack - RAOffset);
      DecError = DecSource - (DecTrack - DecOffset);
      // error corrections:
      //      RA += RAError;
      //      Dec += DecError;
      RAError *= 3600; //arc sec
      DecError *= 3600; // arc sec
  	  
      coord.RADec2000ToAzEl(RATrack*TMath::DegToRad(),DecTrack*TMath::DegToRad(),time,Az_check,El_check);
      // checks in Deg
      Az_check*=TMath::RadToDeg();
      El_check*=TMath::RadToDeg();

      eventCoord.setCoordinates_Deg(RA,Dec,2);   
      //trackCoord.setCoordinates_Deg(RATrack,DecTrack,2);
      trackCoord.setCoordinates_Deg(RASource+RAOffset,DecSource+DecOffset,2);
      fRootCoord.setCoordinates_Deg(RA_fRoot,Dec_fRoot,2);

      angularSep = onCenter.angularSeparation_Deg(eventCoord);
      //psi = trackCoord.angularSeparation_Deg(eventCoord);
      theta =  sourceCoord.angularSeparation_Deg(eventCoord);
      psi = PsiEventTree;
      //      cout << "dPsi: " << psi - PsiEventTree << endl;
      //-------------------------	  
      // Stuff for RBM analysis:
      //-------------------------
      if(useRBM)
	{
	  IsOff = 0;
	  IsInExcl = 0;
	  if(RunID != RunIDOld)
	    {
	      //wobOffset = sqrt(pow(DecOffset,2.0)+pow(RAOffset,2.0));
	      wobOffset = sourceCoord.angularSeparation_Deg(trackCoord);
	      upperRadCres = wobOffset + sqrt(theta2Cut);
	      lowerRadCres = wobOffset - sqrt(theta2Cut);
	      // Segue North Kludge/Hack:
	      /*
	      if(TMath::Abs(trackCoord.getRA_J2000_Deg()-151.767) < 0.1 && TMath::Abs(trackCoord.getDec_J2000_Deg()-16.582) < 0.1)
		{
		  cout << "Warning! I think this is a Segue North Run!" << endl;
		  upperRadCres = 0.5;
		}
	      */
	      VASkyMap* vaMapCustom = new VASkyMap("h","h1",sourceCoord,6.0,0.01);
	      //VASkyMap* vaMapCustom = new VASkyMap("h","h1",trackCoord,6.0,0.01);
	      vaMapCustom->MakeBinAreaMap();
	      areaBgRegion = IntegrateBgArea(vaMapCustom,exclList,trackCoord,lowerRadCres,upperRadCres,nRegions);
	      vaMapCustom->Delete();

	      cout << "Alpha for Run# " << RunID << " is: " << areaOnRegion/areaBgRegion << endl; 
	     
	    }
	  //if( lowerRadRBM < angularSep && angularSep < upperRadRBM )
	  if( lowerRadCres < psi && psi < upperRadCres )   
	    {	      
	      for(int m=0; m<nRegions; m++)
		{
		  if( exclList[m]->isWithinRegion(eventCoord) )
		    IsInExcl = 1;
		}
	      if(!IsInExcl)
		{
		  IsOff = 1;
		  W = areaOnRegion/areaBgRegion;
		}
	    }
	}
      //      IsOn = reDefOnFlag(sourceCoord,eventCoord,theta2Cut);
      
      if(IsOff || IsOn)
	{

	  map->SetPoint(k,RA,Dec);
	  trackError->SetPoint(k,RAError,DecError); 
	  if(TMath::Abs(RAError) > 40.0 || TMath::Abs(DecError) > 40.0)
	    cout << "Warning! Tracking Error large for for: " << RunID << " RA Error: " << RAError << " Dec Error: " << DecError << endl;
	  k++;
	 
	  if(IsOn)
	    {
	      // if( sqrt((RA - RASource)**2.0 + (Dec - DecSource)**2.0) > sqrt(theta2Cut))
	      if( theta > sqrt(theta2Cut) )
		{
		  cout << "Theta: " << theta << endl;
		}
	      NumOnEvents++;
	    }
	  if(IsOff){ NumOffEvents++; }

	  // putting needed output into ASCII file
	  os << RunID << " ";
	  os << liveTime << " ";

	  os.precision(12);
	  os << MJDDbl << " ";
	  os.precision(9);
	  os << RA << " ";
	  os << Dec << " ";
	  os << RATrack << " ";
	  os << DecTrack << " ";
	  os.precision(7);
	  os << EnergyGeV << "        ";
	  os << IsOn << "    ";
	  os << W << "       ";
	
	  os << El_track << " ";
	  os << Az_track << " ";
	  if(!NoFromStg5)
	    os << Noise << " ";
	  else
	    os << AvgNoiseFromStg5 << " ";
	  os << psi << " ";

	  os << endl;
	  
	}
      RunIDOld = RunID;
    }

  Non.push_back(NumOnEvents);
  Noff.push_back(NumOffEvents);
  ExpOn.push_back(liveTime/60);
  ExpOff.push_back(liveTime/60);
  Alpha.push_back(areaOnRegion/areaBgRegion);
  fSigCBG = lima(NumOnEvents,NumOffEvents,areaOnRegion/areaBgRegion);
  SigmaVec.push_back(fSigCBG);
  RunIDVec.push_back(RunIDOld);
 
  cout << RunIDOld << " Non: " << NumOnEvents << " Noff: " << NumOffEvents << " Alpha: " << areaOnRegion/areaBgRegion << " Exp: " << liveTime/60 << endl;
    
  VAStatisticsUtilitiesAnl* StatAnl = new VAStatisticsUtilitiesAnl(Non,Noff,ExpOn,ExpOff,Alpha);
  
  cout.precision(7);
  cout << "Number of ON events: " << sumVector(Non) << endl;
  cout << "Number of OFF events: " << sumVector(Noff) << endl;
  cout << "Mean Alpha: " << sumVector(Alpha)/Alpha.size() << endl;
  cout << "Total Exp Time: " << sumVector(ExpOn) << endl;
  cout << "Excess : " << StatAnl->ExcessRate() << " +/- " << StatAnl->ExcessRateError() << endl;
  cout << "Generalized LiMa Significance: " << StatAnl->GeneralisedLiMa() << endl;
  fb.close();
  fb.open("Results.txt",ios::out);
  ostream os(&fb);
  for(int i=0; i<Non.size(); i++)
    {
      os << "Results for run# " << RunIDVec.at(i) << endl;
      os << "  Number of ON events: " << Non.at(i) << endl;
      os << "  Number of OFF events: " << Noff.at(i) << endl;
      os << "  Alpha: " << Alpha.at(i) << endl;
      os << "  Exp Time: " << ExpOn.at(i) << endl;
      os << "  Significance: " << SigmaVec.at(i) << endl;
      os << "  " << endl;
    }
  os << "---------------------------" << endl;
  os << "Final Results for all runs:" << endl;
  os << "  Number of ON events: " << sumVector(Non) << endl;
  os << "  Number of OFF events: " << sumVector(Noff) << endl;
  os << "  Mean Alpha: " << calcWeightAvgVector(Alpha,ExpOn) << endl;
  os << "  Total Exp Time: " << sumVector(ExpOn) << endl;
  os << "  Excess : " << StatAnl->ExcessRate() << " +/- " << StatAnl->ExcessRateError() << endl;
  os << "  Generalized LiMa Significance: " << StatAnl->GeneralisedLiMa() << endl;
  fb.close();
  
  TCanvas* c1 = new TCanvas();
  map->Draw("A*");
  TEllipse* drawBg[tmp];
  for(int k=0; k<nRegions; k++)
    {
      drawBg[k] = new TEllipse(exclList[k]->center().getRA_J2000_Deg(),exclList[k]->center().getDec_J2000_Deg(), exclList[k]->radius_Deg(),exclList[k]->radius_Deg());
      drawBg[k]->SetLineColor(kBlue);
      drawBg[k]->SetFillColor(0);
      drawBg[k]->SetFillStyle(0);
      
      drawBg[k]->Draw("same");
    }
  // ON region:
  TEllipse* drawONregion = new TEllipse(RASource,DecSource,sqrt(theta2Cut),sqrt(theta2Cut));
 
  drawONregion->SetLineColor(kRed);
  drawONregion->SetFillColor(0);
  drawONregion->SetFillStyle(0);     
  drawONregion->Draw("same");

  TCanvas* c2 = new TCanvas();
  trackError->GetXaxis()->SetTitle("#delta RA (asec)");
  trackError->GetYaxis()->SetTitle("#delta Dec (asec)");
  
  trackError->Draw("A*");

 
  fSigCBG = lima(NumOnEvents,NumOffEvents,areaOnRegion/areaBgRegion);
  hSigCBG->Fill(fSigCBG);
  TCanvas* c3 = new TCanvas();
  TH1F* hSigRBM = (TH1F*)gDirectory->Get("RingBackgroundModelAnalysis/SigDistributionMinusAllExcl");

  TLegend* l = new TLegend(0.7,0.7,0.9,0.9);

  //hSigRBM->SetDirectory(0);
  hSigRF->SetDirectory(0);
  hSigCBG->SetDirectory(0);
  hSigRF->Scale(1.0/hSigRF->GetEntries());
  //hSigRBM->Scale(1.0/hSigRBM->GetEntries());
  hSigCBG->Scale(1.0/hSigCBG->GetEntries());
 
  hSigCBG->Draw();
  hSigCBG->SetLineColor(kBlue);
 
  hSigRF->Draw("same");
  hSigRF->SetLineColor(kBlack);
 
  //hSigRBM->SetLineColor(kRed);
  //hSigRBM->Draw("same");

  //l->AddEntry(hSigRBM,"Ring Background Model");
  l->AddEntry(hSigRF,"Reflected Ring Model");
  l->AddEntry(hSigCBG,"Cresent Background Model");
  l->Draw("same");
    
  hSigRF->Fit("gaus","LLN");
  hSigCBG->Fit("gaus","LLN");
  //hSigRBM->Fit("gaus","LLN");
  /*
  TF1* hFitRF = hSigRF->GetFunction("gaus");
  TF1* hFitCBG = hSigRF->GetFunction("gaus");
  TF1* hFitRBM = hSigRF->GetFunction("gaus");
  
  hFitRF->Draw("same"); 
  hFitRF->SetLineColor(kBlue);
  hFitCBG->Draw("same");
  
  hFitRBM->Draw("same");
  hFitRBM->SetLineColor(kRed);
  */
  cout << "Number of RF entries: " << hSigRF->GetEntries() << endl;
  cout << "Number of CBG entries: " << hSigCBG->GetEntries() << endl;
  cout << "CBG Results in Results.txt and Results.root. Remember to rename them!" << endl;
  f->Close();
  TFile* fOut = new TFile("Results.root","RECREATE");
  if(!fOut->IsOpen())
    {
      cerr << "Problem with output root file!" << endl;
      return;
    }
  //hSigRBM->Write();
  hSigRF->Write();
  hSigCBG->Write();
  c1->Write();
  c2->Write();
  c3->Write();
  fOut->Close();
}
Esempio n. 18
0
void control(TString var,TString bin, TCut cuts, TCut cutsA, TString cutpoint,bool log,Double_t ymax){
setstyle();
 TH1::SetDefaultSumw2(true);
TCanvas *c2 = new TCanvas("canvas"+var+cutpoint,"canname"+var+cutpoint,700,800);

  TPad *mainPad = new TPad("","",0.01,0.25,0.99,0.99);
   mainPad->SetNumber(1);
   mainPad->Draw();
    TPad *ratioPad = new TPad("","",0.01,0.01,0.99,0.25);
   ratioPad->SetNumber(2);
   ratioPad->Draw();
 c2->cd(1);

 TCut lo = cuts && mu_pt_lo;
 TCut hi = cuts && mu_pt_hi;

 // TH1D *Ctrl_lo = GetHist("AS",kBlack,var,lo,bin,astQCD,cutpoint);
 // TH1D *Sig_lo = GetHist("S",kRed,var,lo,bin,stQCD,cutpoint);
  TH1D *Ctrl_hi = GetHist("AS",kBlack,var,cuts,bin,astQCD,cutpoint);
  TH1D *Sig_hi = GetHist("S",kRed,var,cuts,bin,stQCD,cutpoint);
  //  Ctrl_lo->Scale(1.94);
  //  Sig_lo->Scale(1.94);
  TH1D *Ctrl = Ctrl_hi->Clone();
  TH1D *Sig = Sig_hi->Clone();
  //  Ctrl->Add(Ctrl_hi);
  // Sig->Add(Sig_hi);

  Sig->Scale(intlumi);
  // TH1D *Ctrl = GetHist("AS",kBlack,var,cuts,bin,astQCD,cutpoint);
  if(Ctrl->Integral()!=0){
  Ctrl->Scale(Sig->Integral()/Ctrl->Integral());
  }
  
  if(log){ c2->cd(1)->SetLogy();}
  
 TLegend *leg = new TLegend(0.564,0.719,0.775,0.875);
 leg->SetTextSize(0.054);
  leg->SetFillColor(0);
  leg->SetLineColor(0);
  //  leg->AddEntry(Ctrl,"Anti-Selected","LF");
  leg->AddEntry(Sig,"Selected","LF");
    leg->AddEntry(Ctrl,"Anti-Selected","LF");

  Ctrl->Draw("EHIST9");
  Sig->Draw("E9same");

  Sig->SetMarkerStyle(20); Sig->SetMarkerColor(kRed);
  leg->Draw("same");
  Ctrl->SetTitle();
  Ctrl->GetXaxis()->SetTitle(var);
  if(log){
  Ctrl->GetYaxis()->SetRangeUser(0.001,ymax);
  }
  else{
    ymax=(Ctrl->GetMaximum()*1.6);
     Ctrl->GetYaxis()->SetRangeUser(0.,ymax);
  }
   TH1D *RatioBottom = (TH1D*)Ctrl->Clone("Ratiob");
   TH1D *RatioTop = (TH1D*)Sig->Clone("Ratiot");

  RatioTop->GetYaxis()->SetTitle("Selected / Anti-Selected");
 RatioTop->GetXaxis()->SetTitle();
 RatioTop->SetTitle();
      RatioTop->Divide(RatioBottom);

      c2->cd(2);
  gPad->SetGridx(); gPad->SetGridy();
   RatioTop->SetTitleSize(0.1, "XYZ");
    RatioTop->SetTitleOffset(0.55, "X");
    RatioTop->SetTitleOffset(0.3, "Y");
    RatioTop->SetLabelSize(0.06,"XY");
    RatioTop->GetYaxis()->SetRangeUser(-2.,5.0);
    RatioTop->SetLineColor(kBlack);
    RatioTop->Draw();
  TBox *unity = new TBox(RatioTop->GetXaxis()->GetBinLowEdge(RatioTop->GetXaxis()->GetFirst()), 0.79,RatioTop->GetXaxis()->GetBinLowEdge(RatioTop->GetXaxis()->GetLast()), 1.21);
			   unity->SetLineWidth(2);
unity->SetLineColor(2);
    unity->SetFillColor(2);
			   unity->SetFillStyle(3002);
			   unity->Draw();
  c2->Update();
  c2->SaveAs(plots+"SAS_Muon_10to25"+var+"_"+cutpoint+".png");
  // c2->Close();
}
Esempio n. 19
0
void sillyMacro(){

  char headerName[1000];
  char gpsName[1000];
  char corName[1000];

  RawAnitaHeader *header =0;
  Adu5Pat *pat =0;
  Adu5Pat *pat2 =0;
  CorrelationSummaryAnita3 *cor=0;

  TChain *gpsChain = new TChain("adu5PatTree");
  TChain *gpsChain2 = new TChain("adu5PatTree");
  TChain *headChain = new TChain("headTree");
  TChain *corChain = new TChain("corTree");

  for (unsigned int run=331;run<355;++run){
    sprintf(headerName,"/unix/anita3/flight1415/root/run%d/timedHeadFile%d.root",run,run);
    sprintf(gpsName,"/unix/anita3/flight1415/root/run%d/gpsEvent%d.root",run,run);
    sprintf(corName, "/unix/anita3/linda/corTrees/corRun_NEW11_HPOL_%d.root", run);
    headChain->Add(headerName);
    gpsChain->Add(gpsName);
    gpsChain2->Add(gpsName);
    corChain->Add(corName);
  }
  headChain->SetBranchAddress("header",&header);
  gpsChain->SetBranchAddress("pat",&pat);
  gpsChain2->SetBranchAddress("pat",&pat2);
  corChain->SetBranchAddress("cor",&cor);

  UInt_t gps_eventNumber;
  gpsChain->SetBranchAddress("eventNumber", &gps_eventNumber);
  UInt_t gps2_eventNumber;
  gpsChain2->SetBranchAddress("eventNumber", &gps2_eventNumber);

  headChain->BuildIndex("header->eventNumber");
  gpsChain->BuildIndex("eventNumber");
  gpsChain2->BuildIndex("pat->realTime");


  int maxEntry=corChain->GetEntries();

  // AnitaPol::AnitaPol_t pol = AnitaPol::kHorizontal;                                                    
  AnitaPol::AnitaPol_t pol = AnitaPol::kVertical;
  Double_t sourceLat, sourceLon, sourceAlt, timeOffset;
  char cpol[100];

  Double_t phiWave, thetaWave, lower, upper;
  Double_t maxCorrTime, deltaTExpected;
  int ant1, ant2;
  headChain->GetEntry(0);
  double firstTS = header->triggerTime;
  headChain->GetEntry(headChain->GetEntries()-1);
  double lastTS = header->triggerTime;

  Double_t additionalPhi = 22.5*TMath::DegToRad();
  Double_t TwoPi = TMath::Pi()*2.;
  //  TH2D *h1 = new TH2D("h1", "", 100, firstTS, lastTS, 100, 0, 3600*24);                               
  TH2D *h1 = new TH2D("h1", "", 100, firstTS, lastTS, 100, -49.5, 50.5);
  TH1D *dHeading = new TH1D("dHeading", "", 100, -5, 5);

  for(Long64_t entry=0;entry<maxEntry;++entry) {
    corChain->GetEntry(entry);

    Long64_t headEntry = headChain->GetEntryNumberWithIndex(cor->eventNumber);
    if(headEntry < 0 ) continue;
    headChain->GetEntry(headEntry);

    Long64_t gpsEntry = gpsChain->GetEntryNumberWithIndex(cor->eventNumber);
    if(gpsEntry < 0 ) continue;
    gpsChain->GetEntry(gpsEntry);

    Long64_t gpsEntry2 = gpsChain2->GetEntryNumberWithIndex(header->triggerTime);
    if(gpsEntry2 < 0 ) continue;
    gpsChain2->GetEntry(gpsEntry2);

    if(gps_eventNumber!=gps2_eventNumber) cout << header->eventNumber <<  " " << gps2_eventNumber << endl;

    //    if ((header->triggerTime%(3600*24))!=(pat->timeOfDay/1e3)) cout << header->triggerTime%(3600*24) << " " << pat->timeOfDay/1e3 << endl;
    double tday = (header->triggerTime%(3600*24));
    h1->Fill(header->triggerTime, (tday - pat->timeOfDay/1e3) );

    dHeading->Fill((pat->heading-pat2->heading));

  }

  h1->Draw("colz");


  TCanvas *c1 = new TCanvas("c1");
  gStyle->SetOptStat(1);
  dHeading->SetTitle("Heading(eventNumber)-heading(realTime);Heading(eventNumber)-heading(realTime) [degrees];Number of events");
  dHeading->Draw();
  c1->Print("dheading.png");

}
Esempio n. 20
0
void plotEfficiency_barrelEta() {
  TString fbrem = "(Trk_P_Vtx - Trk_P_Out)/Trk_P_Vtx";

  TCut PtCut="Pt>10";
  TCut EtaCut ="abs(Eta)<2.5";
  TCut Signal ="MatchedGen && MatchedGenFromWZ";
  TCut Bkg ="(!MatchedGen || (MatchedGen && !MatchedGenFromWZ ))";
  TCut barr = "abs(Eta)<1.479";
  TCut endc = "abs(Eta)>1.550&&abs(Eta)<2.5";
  TCut qcd ="(processID==11 || processID==12 || processID==13 || processID==28 || processID==53 || processID==68)";
  
  TFile *_file2 = TFile::Open("Data/Gumbo/New/Gumbo_All.root"); 
  TTree* g = _file2->Get("ElTree");
  TFile *_file1 = TFile::Open("Data/WZ_3l/New/WZCSA07-WZ.root");    
  TTree* s = _file1->Get("ElTree");

  TH1D* h1  = new TH1D("h1", "",50,0,1.5);
  TH1D* h2  = new TH1D("h2", "",50,0,1.5);
  TH1D* sig = new TH1D("sig","",50,0,1.5);
  h1->Sumw2();
  h2->Sumw2();

  TH1D* b1  = new TH1D("b1", "",50,0,1.5);
  TH1D* b2  = new TH1D("b2", "",50,0,1.5);
  TH1D* bkg = new TH1D("bkg","",50,0,1.5);
  b1->Sumw2();
  b2->Sumw2();
  
  TCut sig_preselection = PtCut && Signal && barr;
  TCut bkg_preselection = PtCut && Bkg && qcd && barr;

  // Barrel- Loose Id
  TCut eb_deta = "DeltaEtaVtx <  0.009"; 
  TCut eb_dphi = "DeltaPhiVtx < 0.05";  
  TCut eb_sEE = "sqrt(CovEtaEta)<0.012";
  TCut eb_trkIso = "(IsoKFTrackDR030 - IsoKFTrackDR005)/Pt<0.1";
  TCut eb_EseedPout = "ESeed/Trk_P_Out>0.9";
  // additional cut for Tight criteria
  TCut eb_EmHadIso = "(IsoEmCaloRecHitDR030 + IsoHadCaloRecHitDR030 - ESC)/ESC<0.18";   

  TCut eb_id = eb_deta && eb_dphi && eb_sEE && eb_trkIso && eb_EseedPout; // && eb_EmHadIso; 


  s->Draw("Eta>>h1", sig_preselection);
  s->Draw("Eta>>h2", sig_preselection && eb_id);

  g->Draw("Eta>>b1", "weight"*(bkg_preselection));
  g->Draw("Eta>>b2", "weight"*(bkg_preselection && eb_id));


  sig->Divide(h2, h1, 1, 1, "B");
  bkg->Divide(b2, b1, 1, 1, "B");

  sig->SetMarkerColor(2);
  sig->SetMarkerStyle(21);
  sig->SetMarkerSize(1);

  bkg->SetMarkerColor(4);
  bkg->SetMarkerStyle(22);
  bkg->SetMarkerSize(1);
  
  gStyle->SetOptStat(0);
  TH2F* f = new TH2F("f","",1000,0,1.5,1000,0,1);
  f->Draw();
  f->GetXaxis()->SetTitle("|#eta|");
  f->GetYaxis()->SetTitle("Efficiency");
  sig->Draw("SAMEE");
  bkg->Draw("SAMEE");

  TLegend* leg = new TLegend(0.5,0.5,0.8,0.8);
  leg->AddEntry(sig, "Signal electron");
  leg->AddEntry(bkg, "mis-identified jet (Gumbo)");
  leg->SetLineColor(0);
  leg->SetBorderSize(0);
  leg->Draw();
}
Esempio n. 21
0
void DrawEfficiency(const char* channel, Int_t selection = 0, Int_t ieff = 7){

	gROOT->SetStyle("Plain");
	gStyle->SetPalette(1);
	gStyle->SetOptStat(0);
	gStyle->SetPalette(1);
	gStyle->SetCanvasColor(0);
	gStyle->SetFrameFillColor(0);
	gStyle->SetOptTitle(0);
	
	gSystem->SetIncludePath("-I. -I$ALICE_ROOT/include  -I$ROOTSYS/include");
	gSystem->Load("libANALYSIS");
	gSystem->Load("libANALYSISalice");
	gSystem->Load("$ALICE_ROOT/CORRFW/libCORRFW") ;
	gSystem->Load("libPWGHFbase");
	gSystem->Load("libPWGHFvertexingHF");
		
	Int_t mcAcc_over_mcLimAcc = 0x001;
	Int_t recPPR_over_mcAcc = 0x002;
	Int_t recPID_over_mcAcc = 0x004;

	// pt index
	Int_t ipt =0;

	Int_t stepNum = -1;
	Int_t stepDen = -1;
	
	// Read the  container from file
	TFile* f = new TFile("AnalysisResults.root");	
	TString directoryName;
	TString containerName;
	TString cutName;
	TString outfileName;

	if (channel == "D0") {
		if (selection == 0){
			directoryName = "PWG3_D2H_CFtaskD0toKpi";
			containerName = "CFHFccontainer0";
			cutName = "Cuts";
			outfileName = "fileEff_D0_from_c.root";
		}
		else if (selection == 1){
			directoryName = "PWG3_D2H_CFtaskD0toKpiKeepD0fromBOnly";
			containerName = "CFHFccontainer0D0fromB";
			cutName = "Cuts";
			outfileName = "fileEff_D0_from_b.root";
		}
		else if (selection == 2){
			directoryName = "PWG3_D2H_CFtaskD0toKpiKeepD0fromB";
			containerName = "CFHFccontainer0allD0";
			cutName = "Cuts";
			outfileName = "fileEff_D0_from_c_and_b.root";
		}
		else {
			Printf("not a valid selection, return");
			return;
		}
	}
	else if (channel == "D0_New"){
		if (selection == 0){
			directoryName = "PWG3_D2H_CFtaskD0toKpi_NEW";
			containerName = "CFHFccontainer0_New";
			cutName = "Cuts_New";
			//directoryName = "PWG3_D2H_CFtaskD0toKpi_CommonFramework";
			//containerName = "CFHFccontainer0_CommonFramework";
			//cutName = "Cuts_CommonFramework";
			outfileName = "fileEff_D0_CommonFramework_from_c.root";
		}
		else if (selection == 1){
			directoryName = "PWG3_D2H_CFtaskD0toKpiKeepDfromBOnly";
			containerName = "CFHFccontainer0DfromB_New";
			cutName = "Cuts_New";
			//directoryName = "PWG3_D2H_CFtaskD0toKpiKeepDfromBOnly_CommonFramework";
			//containerName = "CFHFccontainer0DfromB_CommonFramework";	
			//cutName = "Cuts_CommonFramework";
			outfileName = "fileEff_D0_CommonFramework_from_b.root";
		}
		else if (selection == 2){
			directoryName = "PWG3_D2H_CFtaskD0toKpiKeepDfromB_NEW";
			containerName = "CFHFccontainer0allD_New";
			cutName = "Cuts_New";
			//directoryName = "PWG3_D2H_CFtaskD0toKpiKeepDfromB_CommonFramework";
			//containerName = "CFHFccontainer0allD_CommonFramework";
			//cutName = "Cuts_CommonFramework";
			outfileName = "fileEff_D0_CommonFramework_from_c_and_b.root";
		}
		else {
			Printf("not a valid selection, return");
			return;
		}
	}
	else if (channel == "Dplus_New"){
		if (selection == 0){
			directoryName = "PWG3_D2H_CFtaskDplustoKpipi_NEW";
			containerName = "CFHFccontainer0_New_3Prong";
			cutName = "Cuts_3Prong";
			//directoryName = "PWG3_D2H_CFtaskDplustoKpipi_CommonFramework";
			//containerName = "CFHFccontainer0_3Prong_CommonFramework";
			//cutName =  "Cuts_3Prong_CommonFramework";
			outfileName = "fileEff_Dplus_CommonFramework_from_c.root";
		}
		else if (selection == 1){
			directoryName = "PWG3_D2H_CFtaskDplustoKpipiKeepDfromBOnly";
			containerName = "CFHFccontainer0DfromB_New_3Prong";
			cutName = "Cuts_3Prong";
			//directoryName = "PWG3_D2H_CFtaskDplustoKpipiKeepDfromBOnly_CommonFramework";
			//containerName = "CFHFccontainer0DfromB_3Prong_CommonFramework";
			//cutName =  "Cuts_3Prong_CommonFramework";
			outfileName = "fileEff_Dplus_CommonFramework_from_b.root";
		}
		else if (selection == 2){
			directoryName = "PWG3_D2H_CFtaskDplustoKpipiKeepDfromB_NEW";
			containerName = "CFHFccontainer0allD_New_3Prong";
			cutName = "Cuts_3Prong";
			//directoryName = "PWG3_D2H_CFtaskDplustoKpipiKeepDfromB_CommonFramework";
			//containerName = "CFHFccontainer0allD_3Prong_CommonFramework";
			//cutName =  "Cuts_3Prong_CommonFramework";
			outfileName = "fileEff_Dplus_CommonFramework_from_c_and_b.root";
		}
		else {
			Printf("not a valid selection, return");
			return;
		}
	}
	else {
		Printf("not a valid channel, return");
		return;
	}

	Printf("Opening file Analysisresults.root");
	Printf("Reading Directory \"%s\"",directoryName.Data());
	Printf("Getting CF Container \"%s\"",containerName.Data());
	Printf("Getting Cut Object \"%s\"",cutName.Data());


	TDirectoryFile* d = (TDirectoryFile*)f->Get(directoryName.Data());
	if (!d){
		Printf("Directory does not exist! Check directory name (%s) in file AnalysisResults.root - returning...", directoryName.Data());
		return;
	}
	AliCFContainer *data = (AliCFContainer*) (d->Get(containerName.Data()));
	AliRDHFCuts *cutsRDHF = (AliRDHFCuts*)(d->Get(cutName.Data()));

	if (!data){
		Printf("Container does not exist! Check container name (%s) in directory %s - returning...", containerName.Data(), directoryName.Data());
		return;
	}
	
	TFile* fileEff = new TFile(outfileName.Data(), "RECREATE");
	TString plotDir(Form("EffPlots/%s",channel));
	gSystem->Exec(Form("mkdir EffPlots"));
	gSystem->Exec(Form("mkdir %s",plotDir.Data()));
	
	//construct the efficiency grid from the data container 
	AliCFEffGrid *eff = new AliCFEffGrid("eff"," The efficiency",*data);

	TCanvas *ceffpt = new TCanvas("ceffpt","Efficiency vs pt",50,50,550,550);
	ceffpt->cd();
	ceffpt->SetLeftMargin(0.15);
	ceffpt->SetRightMargin(0.05);
	TH1D *hpteffCF = 0x0; //the efficiency vs pt

	if (ieff & mcAcc_over_mcLimAcc){
		AliCFEffGrid *eff = new AliCFEffGrid("eff"," The efficiency",*data);
		stepDen = (Int_t)(AliCFTaskVertexingHF::kStepGeneratedLimAcc);	
		stepNum = (Int_t)(AliCFTaskVertexingHF::kStepAcceptance);	
		printf("Calculating efficiency for mcAcc_over_mcLimAcc: stepDen = %d, stepNum = %d\n",stepDen,stepNum);	
		eff->CalculateEfficiency(stepNum,stepDen); //eff= step1/step0
		
		//canvas
		ceffpt->cd();

		//The efficiency along the variables
		hpteffCF = eff->Project(ipt); 
		SetHistoEff(hpteffCF,8,20,"mcAcc_over_mcLimAcc");
		hpteffCF->Draw("hist");
		hpteffCF->Draw("err same");
		fileEff->cd();
		hpteffCF->Write("hpteffCF_mcAcc_over_mcLimAcc");
		
		// printing png files
		ceffpt->Print(Form("%s/effpt_mcAcc_over_mcLimAcc.png", plotDir.Data()));
		ceffpt->Print(Form("%s/effpt_mcAcc_over_mcLimAcc.eps", plotDir.Data()));
		ceffpt->Print(Form("%s/effpt_mcAcc_over_mcLimAcc.gif", plotDir.Data()));
		delete eff;
		eff = 0x0;
	}

	if (ieff & recPPR_over_mcAcc){
		AliCFEffGrid *eff = new AliCFEffGrid("eff"," The efficiency",*data);
		stepDen = (Int_t)(AliCFTaskVertexingHF::kStepAcceptance);	
		stepNum = (Int_t)(AliCFTaskVertexingHF::kStepRecoPPR);	
		printf("Calculating efficiency for RecPPR_over_mcAcc: stepDen = %d, stepNum = %d\n",stepDen,stepNum);	
		eff->CalculateEfficiency(stepNum,stepDen); //eff= step1/step0
		
		//canvas
		ceffpt->cd();
		
		//The efficiency along the variables
		hpteffCF = eff->Project(ipt); 
		SetHistoEff(hpteffCF,8,20, "recAnCuts_over_mcAcc");
		hpteffCF->Draw("hist");
		hpteffCF->Draw("err same");
		fileEff->cd();
		hpteffCF->Write("hpteffCF_RecAnCut_over_mcAcc");
		
		// printing png files
		ceffpt->Print(Form("%s/effpt_RecAnCut_over_mcAcc.png", plotDir.Data()));
		ceffpt->Print(Form("%s/effpt_RecAnCut_over_mcAcc.eps", plotDir.Data()));
		ceffpt->Print(Form("%s/effpt_RecAnCut_over_mcAcc.gif", plotDir.Data()));
		delete eff;
		eff = 0x0;
	}

	if (ieff & recPID_over_mcAcc){
		AliCFEffGrid *eff = new AliCFEffGrid("eff"," The efficiency",*data);
		stepDen = (Int_t)(AliCFTaskVertexingHF::kStepAcceptance);	
		stepNum = (Int_t)(AliCFTaskVertexingHF::kStepRecoPID);	
		printf("Calculating efficiency for RecPID_over_mcAcc: stepDen = %d, stepNum = %d\n",stepDen,stepNum);	
		eff->CalculateEfficiency(stepNum,stepDen); //eff= step1/step0
		
		//canvas
		ceffpt->cd();
		
		//The efficiency along the variables
		hpteffCF = eff->Project(ipt); 
		SetHistoEff(hpteffCF,8,20,"recPID_over_mcAcc");
		hpteffCF->Draw("hist");
		hpteffCF->Draw("err same");
		fileEff->cd();
		hpteffCF->Write("hpteffCF_RecPID_over_mcAcc");
		
		// printing png files
		ceffpt->Print(Form("%s/effpt_RecPID_over_mcAcc.png", plotDir.Data()));
		ceffpt->Print(Form("%s/effpt_RecPID_over_mcAcc.eps", plotDir.Data()));
		ceffpt->Print(Form("%s/effpt_RecPID_over_mcAcc.gif", plotDir.Data()));
		delete eff;
		eff = 0x0;
	}
	
	cutsRDHF->Write("Cuts");

	// writing single distributions
	TH1D *hMCAccpt = data->ShowProjection(ipt, AliCFTaskVertexingHF::kStepAcceptance);
	SetHistoDistribution(hMCAccpt, 1, 20);
	hMCAccpt->Draw();
	TH1D *hMCLimAccpt = data->ShowProjection(ipt, AliCFHeavyFlavourTaskMultiVarMultiStep::kStepGeneratedLimAcc);
	SetHistoDistribution(hMCLimAccpt, 4, 20);
	TH1D *hRecoAnCutspt = data->ShowProjection(ipt, AliCFTaskVertexingHF::kStepRecoPPR);
	SetHistoDistribution(hRecoAnCutspt, 8, 20);
	TH1D *hRecoPIDpt = data->ShowProjection(ipt, AliCFTaskVertexingHF::kStepRecoPID);
	SetHistoDistribution(hRecoPIDpt, 6, 20);
	hMCAccpt->Write("hMCAccpt");
	hMCLimAccpt->Write("hMCLimAccpt");
	hRecoAnCutspt->Write("hRecoAnCutspt");
	hRecoPIDpt->Write("hRecoPIDpt");

	//	fileEff->Close(); // commented out to see the canvas on the screen....

}
Esempio n. 22
0
void analyzeEventsSlice(double onDelta = 100.0) {
  gStyle->SetOptFit(1);
  initialize();

  int decodedTDC;
  for (Long64_t iEvent=0; iEvent<myTree->GetEntries();iEvent++) {
    std::cout << "Processing Event " << iEvent << std::endl;
    myTree->GetEntry(iEvent);
    decodedTDC = TDC-4;
    if (decodedTDC<0) continue;
    if (decodedTDC>8) {
      std::cerr << "Help, this should not happen" << std::endl;
      continue;
    }
    if (nHits>0) myHistoIntegral[decodedTDC]->Fill(thresh, 1 /* nHits*/ );
    //myHistoIntegral[decodedTDC]->Fill(thresh, nHits );
  }


  TH1D* antani = new TH1D("diff", Form("diffTDC_%f", onDelta), 10, -0.5, 9.5);
  bool gotTDC[13];
  for (int i=0; i<13; ++i) { gotTDC[i]=false; }
  for (int iTDC=0; iTDC<9; ++iTDC) {
    double thisVal, prevVal;
    double thisX, prevX;
    prevVal=0;
    prevX=-9999;
    bool firstVal = true;
    for (int iBin=1; iBin<myHistoIntegral[iTDC]->GetNbinsX(); ++iBin) {
      thisVal = myHistoIntegral[iTDC]->GetBinContent(iBin);
      thisX = myHistoIntegral[iTDC]->GetXaxis()->GetBinCenter(iBin);
      if (thisVal==0) continue;

      if (!firstVal) {
	addPoint(myGraphDifferential[iTDC],
		 (thisX+prevX)/2., prevVal-thisVal
		 , fabs(thisX-prevX)/2., sqrt(prevVal+thisVal));	
        if (((thisX+prevX)/2.>onDelta)&&(!gotTDC[iTDC])) {
            gotTDC[iTDC]=true;
            antani->Fill(iTDC, (prevVal-thisVal)/(thisX-prevX));
        } 
      } else firstVal=false;
      // myHistoDifferential[iTDC]->SetBinContent(iBin, prevVal-thisVal);
      prevVal = thisVal;
      prevX = thisX;
    }

    TCanvas* myCanvas;
    
    //myCanvas = new TCanvas();
    //myCanvas->cd();
    //myCanvas->SetLogy();

    myGraphDifferential[iTDC]->SetMarkerStyle(8);
    // myGraphDifferential[iTDC]->Draw("ap");

		//edit G. Auzinger: fit distribution for every TDC with a landau in range 30 to 200
//		TF1* myLandau = new TF1("fit", "TMath::Landau(x)", 30, 200);
//		myGraphDifferential[iTDC]->Fit("landau", "RM+","same", 50, 250);

    // myGraphDifferential[iTDC]->Fit(
    
    // myHistoDifferential[iTDC]->Rebin(2);
    // myHistoDifferential[iTDC]->Draw();
    
    // myCanvas = new TCanvas();
    // myCanvas->SetLogy();
    // myHistoIntegral[iTDC]->Draw();
    
  }

  new TCanvas();
  antani->Draw();
}
Esempio n. 23
0
void drawRAA(bool doInclusiveJet=0, bool useUnfolded=1, bool drawTheory=1){

  bool drawPowheg = 0;
  
  float etalo=-2;
  float etahi=2;

  TH1D *dEta80To110 = new TH1D("dEta80To110","",4,-2.465,1.535);
  TH1D *dEta110To150 = new TH1D("dEta110To150","",4,-2.365,1.635);
  TH1D *dEta70To80 = new TH1D("dEta70To80","",4,-2.565,1.435);
  TH1D *dEta150To190 = new TH1D("dEta150To190","",4,-2.265,1.735);

  int nbins = 3;
  double xbins[4] = {0,20,50,100};
  double xbins2[4] = {2,22,52,102};
  double xbins3[4] = {-2,18,48,98};
  double xbins4[4] = {4,24,54,104};
  TH1D *dCent70To80 = new TH1D("dCent70To80","",nbins,xbins3);
  TH1D *dCent80To110 = new TH1D("dCent80To110","",nbins,xbins);
  TH1D *dCent110To150 = new TH1D("dCent110To150","",nbins,xbins2);
  TH1D *dCent150To190 = new TH1D("dCent150To190","",nbins,xbins4);
  
  //for(int ieta=-2; ieta<2; ieta++){
  //  etalo=(float)(ieta+0.5);
  //  etahi=(float)(ieta+1.5);

  int binLo, binHi;
  //for(int icent=0; icent<3; icent++){
  //  if(icent==0){ binLo = 0; binHi=20; }
  //  if(icent==1){ binLo = 20; binHi=50; }
  //  if(icent==2){ binLo = 50; binHi=100; }
  
    TH1D *h = new TH1D();
    TH1D *h2 = new TH1D();
    TH1D *h_den = new TH1D();
    h->Sumw2();
    h2->Sumw2();
    h_den->Sumw2();
    TH1D *he1 = new TH1D();
    TH1D *he2 = new TH1D();
    TH1D *he3 = new TH1D();
    TH1D *he4 = new TH1D();
    he1->Sumw2(); he2->Sumw2(); he3->Sumw2(); he4->Sumw2();

    //grab unfolded histograms from the unfolding output (inclusive)
    TFile *f0, *f2, *f5,*f6,*f7,*f8;
    TFile *fIncl = new TFile("~/bTagTrees/pPb/raa_pPb_numerator-inc_eta-1.0To1.0.root");
    TFile *fInclB = new TFile("~/bTagTrees/pPb/raa_pp_denomForpA-inc_eta-1.0To1.0.root");
    TH1D *hinclTop = (TH1D*)fIncl->Get("hReco0")->Clone("hinclTop");
    TH1D *hinclBot = (TH1D*)fInclB->Get("hGen_cent1")->Clone("hinclBot");
    for(int i=1; i<=hinclTop->GetNbinsX(); i++){
      hinclTop->SetBinError(i,hinclTop->GetBinError(i)/hinclTop->GetBinWidth(i));
      hinclTop->SetBinContent(i,hinclTop->GetBinContent(i)/hinclTop->GetBinWidth(i));
      hinclBot->SetBinError(i,hinclBot->GetBinError(i)/hinclBot->GetBinWidth(i));
      hinclBot->SetBinContent(i,hinclBot->GetBinContent(i)/hinclBot->GetBinWidth(i));
    }
    hinclTop->Scale(1./6.9);
    hinclTop->Divide(hinclBot);
    hinclTop->SetMarkerColor(4);
    //hinclTop->Scale(0.689);

    //grab unfolded histograms from the unfolding output (bjet)
    if(doInclusiveJet) f0 = new TFile(Form("~/bTagTrees/pPb/raa_pPb_numerator-inc_eta%.1fTo%.1f.root",etalo,etahi));
    //else f0 = new TFile(Form("~/bTagTrees/pPb/raa_pPb_numerator-Incljet_FullDataset_ssvhe20_etaCM_v2_bin0_100_eta%.1fTo%.1f.root",etalo,etahi)); //incl jet unfolding
    else if(useUnfolded){
      f0 = new TFile(Form("~/bTagTrees/pPb/raa_pPb_numerator-Bjet_FullDataset_ssvhe20_etaCM_v2_bin0_100_eta%.1fTo%.1f.root",etalo,etahi)); //bjet unfolding
      f5 = new TFile("~/bTagTrees/pPb/raa_pPb_numerator-Bjet_FullDataset_ssvhe20_etaCM_eta-2.0To-1.0.root");
      f6 = new TFile("~/bTagTrees/pPb/raa_pPb_numerator-Bjet_FullDataset_ssvhe20_etaCM_eta-1.0To0.0.root");
      f7 = new TFile("~/bTagTrees/pPb/raa_pPb_numerator-Bjet_FullDataset_ssvhe20_etaCM_eta0.0To1.0.root");
      f8 = new TFile("~/bTagTrees/pPb/raa_pPb_numerator-Bjet_FullDataset_ssvhe20_etaCM_eta1.0To2.0.root");
    }
    else{
      f0 = new TFile(Form("~/bTagTrees/pPb/raa_pPb_numerator-Bjet_NoUnfolding_FullDataset_ssvhe20_etaCM_v2_bin0_100_eta%.1fTo%.1f.root",etalo,etahi));
    }

    if(useUnfolded){
      h = (TH1D*)(f0->Get("hReco0"));
      he1 = (TH1D*)(f5->Get("hReco0"));
      he2 = (TH1D*)(f6->Get("hReco0"));
      he3 = (TH1D*)(f7->Get("hReco0"));
      he4 = (TH1D*)(f8->Get("hReco0"));
    }
    else if(doInclusiveJet) h = (TH1D*)(f0->Get("hIncJetsData"));
    else h = (TH1D*)(f0->Get("hReco0"));

    //h = (TH1D*)he1->Clone("h");
    //he1->Add(he2);
    //he1->Add(he3);
    //he1->Add(he4);
    //h->Scale(1./6.9);

    /* for(int i=1; i<=h->GetNbinsX(); i++){
       h->SetBinError(i, h->GetBinError(i)/h->GetBinWidth(i));
       h->SetBinContent(i, h->GetBinContent(i)/h->GetBinWidth(i));
       }*/
    //h->Scale(1./6.9); //pPb total N coll (L*pp x-sec * A, sigma_pp = 70 mb @ CERN)  
  
    if(doInclusiveJet) f2 = new TFile(Form("~/bTagTrees/pPb/raa_pp_denomForpA-inc_eta%.1fTo%.1f.root",etalo,etahi),"OLD");
    else f2 = new TFile(Form("~/bTagTrees/pPb/raa_pp_denomForpA-Bjet_etaCM_v2_bin0_100_eta%.1fTo%.1f.root",etalo,etahi),"OLD"); //incl jet unfolding
    //else f2 = new TFile(Form("raa_pp_denomForpA-Bjet_etaLab_eta%.1fTo%.1f.root",etalo,etahi),"OLD"); //bjet unfolding
    f2->cd();
    //h_den = (TH1D*)(f2->Get("hRawBMC"));
    if(useUnfolded) h_den = (TH1D*)f2->Get("hGen_cent1");
    else if(doInclusiveJet) h_den = (TH1D*)(f2->Get("hIncJetsMC"));
    else h_den = (TH1D*)(f2->Get("hGen_cent1"));

    TFile *xchk = new TFile("histos/ppMC_ppReco_akPu3PF_QCDjetTrig_etashift_Fix2Sample_MCWeightFinalWithVz_noTrgSelection_Full.root");
    TTree *nt1 = (TTree*)xchk->Get("nt");
    double xbinsXchk[19] = {0, 5, 10, 15, 20, 25, 30, 35, 40, 55, 70, 90, 110, 140, 170, 220, 400, 700, 1000};
    TH1D *hf = new TH1D("hf","",18,xbinsXchk); hf->Sumw2();
    nt1->Project("hf","refpt","weight*(abs(refparton_flavorForB)==5 && jteta<2 && jteta>-2 && jtpt>35 && rawpt>20)");
    for(int i=1; i<=hf->GetNbinsX(); i++){
      hf->SetBinError(i,hf->GetBinError(i)/hf->GetBinWidth(i));
      hf->SetBinContent(i,hf->GetBinContent(i)/hf->GetBinWidth(i));
    }
    hf->SetLineColor(kRed+2);
    //hf->Scale(1E9);
    //hf->Scale(1./70.);
    //hf->Scale(10.);
    //h_den = hf;

    TFile *ff = new TFile("pPb_Unfo_inCM_v31_officialMC_ak3PF_akPu3PF_noGplus_FirstHalfOnly_Converged_usedParameterizedUnfold0_jtpt35_bJets_clo0_chi100_v8_eta_-2.00To2.00_.root");
    TH1D *hfCheck2 = (TH1D*)ff->Get("hGen_cent1");
    TFile *ff2 = new TFile("pPb_Unfo_inCM_v31_officialMC_Reverse_WithResCorr_ak3PF_akPu3PF_noGplus_SecondHalfOnly_Converged_usedParameterizedUnfold0_jtpt35_bJets_clo0_chi100_v8_eta_-2.00To2.00_.root");
    TH1D *hfCheck3 = (TH1D*)ff2->Get("hGen_cent1");
    hfCheck2->Add(hfCheck3);
    //hfCheck2 = (TH1D*)hfCheck2->Rebin(16,hfCheck2->GetName(),xbinsXchk);
    
    //Fix raw B MC histogram to have 14 bins to be compatible with the unfolded nonsense
    /*const int fixNbin = h->GetNbinsX();
    Double_t binBoundaries[15];
    for(int ibin=0; ibin<fixNbin; ibin++){
      binBoundaries[ibin] = h->GetBinLowEdge(ibin+1);
    }
    binBoundaries[fixNbin] = h->GetBinLowEdge(fixNbin)+h->GetBinWidth(fixNbin);
    TH1D *h_den_fix = new TH1D("h_den_fix","",fixNbin,binBoundaries); h_den_fix->Sumw2();
    for(int ibin=0; ibin<fixNbin-h_den->GetNbinsX(); ibin++){
      h_den_fix->SetBinContent(ibin+1,0);
      h_den_fix->SetBinError(ibin+1,0);
    }
    for(int ibin=fixNbin-h_den->GetNbinsX(); ibin<fixNbin; ibin++){
      h_den_fix->SetBinContent(ibin+1,h_den->GetBinContent(ibin-(fixNbin-h_den->GetNbinsX())+1));
      h_den_fix->SetBinError(ibin+1,h_den->GetBinError(ibin-(fixNbin-h_den->GetNbinsX())+1));
      }*/
    //end fix

    //h->Draw();
    h->SetTitle("");
    //h_den->SetMarkerColor(2);
    //h_den->Draw("same");
    //h->Divide(h_den);
    h->SetYTitle("#frac{1}{T_{pA}} #frac{d#sigma}{dp_{T}} (1/GeV/c)");
    h->SetMaximum(1E-6);
    h->SetMinimum(1E-11);
    h->Draw();
    h_den->SetMarkerColor(4);
    h_den->Draw("same");
    hfCheck2->Scale(1./70.);
    hfCheck2->SetLineColor(kGreen+2);
    hf->Draw("same");
    he2->SetMarkerColor(kOrange+2);
    he2->Draw("same");
    //hfCheck2->Draw("same");
    //h_den = hfCheck2;
    //c1->SetLogy();

    for(int j=1; j<=h->GetNbinsX(); j++){
      cout << h->GetBinLowEdge(j) << " ";
    }
    cout << h->GetBinLowEdge(h->GetNbinsX())+h->GetBinWidth(h->GetNbinsX()) << endl;

    for(int j=1; j<=h_den->GetNbinsX(); j++){
      cout << h_den->GetBinLowEdge(j) << " ";
    }
    cout << h_den->GetBinLowEdge(h_den->GetNbinsX())+h_den->GetBinWidth(h_den->GetNbinsX()) << endl;

    TH1F *hpow, *hpow15;
    //if(drawPowheg){
      TFile *fpowheg50 = new TFile("Powheg/CMS-Dijet-Analysis-5tev-kt0-pt50Cut-mstwCL60PDF.root");
      hpow = (TH1F*)fpowheg50->Get("d05-x01-y01")->Clone("hpow"); //inclusive eta, ak3 jets
      TFile *fpowheg15 = new TFile("Powheg/CMS-Dijet-Analysis-5tev-kt0-pt20Cut-mstwCL60PDF.root");
      hpow15 = (TH1F*)fpowheg15->Get("d05-x01-y01")->Clone("hpow15");
      hpow15->Scale(25.4); //pthat20 relative (to pthat50) efficiency
      //hpow15->Scale(405.); //pthat 5 relative efficiency
      //hpow15->Scale(15.95);
      for(int i=1; i<=hpow->GetNbinsX(); i++){
	if(hpow->GetBinLowEdge(i)<100){
	  //cout << "edge: "<< hpow->GetBinLowEdge(i) << endl;
	  //cout << "hpow: "<< hpow->GetBinContent(i) << " hpow15: "<< hpow15->GetBinContent(i) << endl;
	  hpow->SetBinContent(i, hpow15->GetBinContent(i));
	  hpow->SetBinError(i, hpow15->GetBinError(i));
	}
      }
      hpow->SetMarkerStyle(20);
      hpow->SetMarkerColor(kOrange+2);
      hpow->SetLineColor(kOrange+2);
      hpow->Scale(2./10.); //fix eta selection
      hpow->Scale(1./70E-3); //correct for sigma_pp
      hpow->Scale(1.851e-3); //correct pthat50 efficiency (148086/80M)
      //hpow->Scale(4.7e-2);
      hpow->Scale(1e-9); //correct ncoll & translate to mb, not pb
      //hpow->Scale(1./50.);
      //hpow->Scale(0.85/(30.));
      if(drawPowheg) hpow->Draw("same");
      // }

    TLegend *t1 = new TLegend(0.5,0.697,0.879,0.906);
    t1->AddEntry(h,"pPb data b-jet spec.","p");
    t1->AddEntry(h2,"pPb MC b-jet spec.","p");
    t1->AddEntry(h_den,"pp MC b-jet spec.","p");
    if(drawPowheg) t1->AddEntry(hpow,"Powheg Spec.","p");
    t1->SetFillColor(0);
    t1->Draw("same");

    TCanvas *c2 = new TCanvas("c2","",600,600); //800,800
    //formatCanvas(c2);
    TH1D *hcln = (TH1D*)h->Clone("hcln");
    cout << "nbin: "<< hcln->GetNbinsX() << endl;
    //double xbinsrebin[17] = {0,5,10,15,20,25,30,35,40,55,70,90,110,140,170,220,400};
    //TH1D *hcln = new TH1D("hcln","",16,xbinsrebin);
    for(int ibin=1; ibin<=hcln->GetNbinsX(); ibin++){
      cout << "content bin " << ibin << " " << hcln->GetBinContent(ibin) << endl;
      cout << "powheg content bin " << ibin << " " << hpow->GetBinContent(ibin) << endl;
      //hcln->SetBinError(ibin,hcln_tmp->GetBinError(ibin));
      //hcln->SetBinContent(ibin,hcln_tmp->GetBinContent(ibin));
      }
    TH1D *hdencln = (TH1D*)h_den->Clone("hdencln");
    TH1D *hclnpow = (TH1D*)hcln->Clone("hclnpow");
    //cout << "WARNING! Scaling denominator for neutrinoless definition change!" << endl;
    //hdencln->Scale(1./1.243);
    if(!drawPowheg) hcln->Divide(hdencln);
    else{
      for(int ibin=1; ibin<=16; ibin++){
	int powbin=ibin;
	if(!useUnfolded) powbin+=8;
	if(!useUnfolded && ibin>8) continue;
	hcln->SetBinError(powbin,sqrt(pow(h_den->GetBinError(ibin)/h_den->GetBinContent(ibin),2)+pow(hpow->GetBinError(powbin)/hpow->GetBinContent(powbin),2)));
	hcln->SetBinContent(powbin,h_den->GetBinContent(ibin)/hpow->GetBinContent(powbin));
      }
    }
    //hcln->Divide(hcln);
    
    //Apply systematic errors to the inclusive eta plot
    TGraphErrors *systErr[7];
    TGraphErrors *unfoldErr[7];

    //set systematics
    const int nBins = 18;
    double xp[nBins], yp[nBins], xerr[nBins], yerr[nBins];
    //double yerrTot[nBins] = {0,0,0,0,0,0,0,0,0.13729, 0.1306, 0.1235, 0.146166, 0.16266, 0.1437,0.1816,0.23813}; //before recalibration
    double yerrTot[nBins] = {0,0,0,0,0,0,0,0,0,0.131694,0.0976, 0.0957, 0.1139, 0.1209, 0.1773, 0.2162,0,0}; //after recalibration
    double unfoldErrTot[nBins] = {0,0,0,0,0,0,0,0,0,0.05,0.05,0.05,0.05,0.05,0.05,0.06,0,0};
    double unfoldErrTotEta1[nBins] = {0,0,0,0,0,0,0,0,0,0.15,0.08,0.06,0.06,0.08,0.04,0.04,0,0};
    //double pythiaSysErr[nBins+1] = {0,0,0,0,0,0,0,0.136,0.138,0.140,0.142,0.148,0.152,0.157,0.164,0.174,0.182}; //option B
    // double optionBExtra[nBins+1] = {0,0,0,0,0,0,0,0,0,0.10,0.111,0.078,0.119,0.108,0.053,0.122,0.168};
    double pythiaSysErr[1] = {0.22}; //option A
    double pythiaYpoints[1] = {1};
    double pythiaXpoints[1] = {10};
    double pythiaXerr[1] = {10};
    for(int i=0; i<nBins; i++){ yerrTot[i] = sqrt(pow(yerrTot[i],2)+pow(unfoldErrTot[i],2)); }
    int j=0;
    if(!doInclusiveJet){
      for(int i=1; i<=hcln->GetNbinsX(); i++){
	xp[i-1] = hcln->GetBinLowEdge(i)+hcln->GetBinWidth(i)/2.;
	yp[i-1] = hcln->GetBinContent(i);
	xerr[i-1] = hcln->GetBinWidth(i)*0.495;
	yerr[i-1] = yerrTot[i-1];
	//pythiaXpoints[i-1] = xp[i-1];
	//pythiaXerr[i-1] = xerr[i-1];

	if(yerr[i-1]>0.001 && yp[i-1]>-1){ 
	  systErr[j] = new TGraphErrors(1,&xp[i-1],&yp[i-1],&xerr[i-1],&yerrTot[i-1]);
	  unfoldErr[j] = new TGraphErrors(1,&xp[i-1],&yp[i-1],&xerr[i-1],&unfoldErrTot[i-1]);
	  systErr[j]->SetName(Form("RpA_SystErr_bin%d",j));
	  j++;
	}
      }
      //pythiaXerr[16] = 0.;
      //pythiaXpoints[16] = 400.;
      /*for(int jj=0; jj<nBins+1; jj++){
	pythiaSysErr[jj]*=(1+optionBExtra[jj]);
	}*/
      TGraphErrors *pythiaErr = new TGraphErrors(1,pythiaXpoints,pythiaYpoints,pythiaXerr,pythiaSysErr);
    }
    //TGraphErrors *systErr = new TGraphErrors(nBins,xp,yp,xerr,yerr);
    double jesx[1]={2.365};
    double jesy[1]={1};
    double jesxerr[1]={.1};
    double jesyerr[1]={0.035};
    TGraphErrors *JESNorm = new TGraphErrors(1,jesx,jesy,jesxerr,jesyerr);
    JESNorm->SetFillColor(kGreen+3);

    hcln->SetMaximum(2.5);
    hcln->SetMinimum(0);
    if(doInclusiveJet) hcln->SetYTitle("Inclusive Jet R_{pA}");
    else hcln->SetYTitle("Nuclear Modification Factor");
    //else hcln->SetYTitle("b-jet R_{pA}^{PYTHIA}");
    hcln->SetXTitle("b-jet p_{T} [GeV/c]");
    hcln->GetXaxis()->SetRangeUser(0,400);
    hcln->GetXaxis()->CenterTitle(0);
    hcln->GetYaxis()->CenterTitle(0);
    hcln->SetMarkerStyle(20);
    hcln->SetMarkerColor(1);
    hcln->SetMarkerSize(1.2);
    for(int i=1; i<hcln->GetNbinsX(); i++){
      if(hcln->GetBinLowEdge(i) < 55){
	hcln->SetBinContent(i,-1);
	hcln->SetBinError(i,0.0001);
      }
    }
    hcln->Draw();
    hclnpow->SetMarkerColor(kOrange+2);
    hclnpow->SetLineColor(kOrange+2);
    if(drawPowheg) hclnpow->Draw("same");
    TLine *at2 = new TLine(0,1,400,1);
    at2->SetLineStyle(7);
    at2->SetLineWidth(1);
    pythiaErr->SetFillColor(kRed-7);
    //pythiaErr->SetFillStyle(1); //3844
    if(!doInclusiveJet){
      for(int i=0; i<7; i++){
	unfoldErr[i]->SetFillColor(kCyan-7);
	systErr[i]->SetFillColor(kYellow-7);
	systErr[i]->SetMarkerStyle(20);
	systErr[i]->Draw("2,same");
	//unfoldErr[i]->Draw("2,same");
      }
    }
    pythiaErr->Draw("2,same");
    double lumix[1] = {10}; double lumiy[1] = {1}; double lumierrx[1] = {10}; double lumierry[1] = {0.035};
    TGraphErrors *lumiErr = new TGraphErrors(1,lumix,lumiy,lumierrx,lumierry);
    lumiErr->SetFillColor(kGreen+3);
    lumiErr->Draw("2,same");
    at2->Draw("same");
    //JESNorm->Draw("2,same");
    hcln->Draw("same");
    
    //JESNorm->Draw("2,same");
  TLine *phigh1 = new TLine(380,1.22,400,1.22);
  phigh1->SetLineColor(2);
  phigh1->SetLineStyle(4);
  phigh1->SetLineWidth(1);
  //phigh1->Draw("same");
  TLine *phigh2 = new TLine(380,0.78,400,0.78);
  phigh2->SetLineColor(2);
  phigh2->SetLineStyle(4);
  phigh2->SetLineWidth(1);
  //phigh2->Draw("same");
  double zeroTemp[1] = {0};
  TGraphErrors *inclJetSys = new TGraphErrors(1,zeroTemp,zeroTemp,zeroTemp,zeroTemp);
  inclJetSys->SetMarkerColor(2);
  inclJetSys->SetMarkerStyle(21);
  inclJetSys->SetFillColor(8);
  //gROOT->ProcessLine(".x ~/Downloads/UnfoldedakPu3PFIncJetRpAvsPtInterpolatedRefEtaBin7.C");
  //gROOT->ProcessLine(".x ~/Downloads/RAA_drawFinal.C");
  if(drawTheory){
    gROOT->ProcessLine(".x ~/Downloads/drawpPbTheory.C");
  }
  TGraph *raaErr = new TGraph();
  raaErr->SetFillColor(kMagenta+1);
  raaErr->SetMarkerStyle(20);
  raaErr->SetMarkerSize(1.2);

  TLegend *leg1 = new TLegend(0.41,0.729,0.88,0.886);
  leg1->SetFillColor(0);
  //leg1->AddEntry(inclJetSys,"Inclusive-Jet R_{pA}, |#eta_{CM}|<0.5","fp");
  //leg1->AddEntry(raaErr,"b-jet R_{AA}, (0-100%), |#eta|<2","fp");
  leg1->AddEntry(systErr[0],"pPb Data, -2 < #eta_{CM} < 2","fp");
  leg1->AddEntry(grepPbtheory,"Ref. [32]","lp");
  //leg1->AddEntry(pythiaErr,"Reference Unc.","f");
  //leg1->AddEntry(lumiErr,"Luminosity Unc.","f");
  //leg1->AddEntry(systErr[0],"Total Systematic Error","f");
  //leg1->AddEntry(unfoldErr[0],"Unfolding Uncertainty","f");
  leg1->Draw("same");

  TLegend *leg3 = new TLegend(0.2,0.207,0.567,0.328);
  leg3->SetFillColor(0);
  leg3->AddEntry(lumiErr,"pPb Luminosity Unc.","f");
  leg3->AddEntry(pythiaErr,"pPb Reference Unc.","f");
  leg3->Draw("same");

  grepPbtheory->Draw("C,same");

  c2->SetTopMargin(0.0734);
  c2->RedrawAxis();

  TLatex *cmsP = new TLatex(16.7,2.25,"CMS ");
  cmsP->SetTextFont(62);
  cmsP->SetTextSize(0.0558);
  cmsP->Draw("same");
  TLatex *l1 = new TLatex(-0.5,0.18,Form("0-100%%",etalo,etahi));
  //l1->Draw("same");
  TLatex *l4 = new TLatex(236.8,2.56,"35 nb^{-1} (5.02 TeV)");//; PbPb L = 150 #mub^{-1}");
  l4->SetTextFont(43);
  l4->SetTextSize(25);
  l4->Draw("same");
  TLatex *l2 = new TLatex(20.77,0.175,"pPb #sqrt{s_{NN}} = 5.02 TeV #int L dt = 35 nb^{-1}"); //35, 20.7, 14
  l2->SetTextSize(0.035);
  //l2->Draw("same");
  TLatex *l3 = new TLatex(-2,0.22,"PbPb #sqrt{s_{NN}} = 2.76 TeV #int L dt = 150 #mub^{-1}");
  l3->SetTextSize(0.035);
  //l3->Draw("same");
  //TLatex *ltag = new TLatex(65,2.2,"CSV > 0.679");
  TLatex *ltag = new TLatex(65,2.2,"SSVHE > 2.0");
  //ltag->Draw("same");
  TFile *out = new TFile("RpA_BJet_Output.root","RECREATE");
  out->cd();
  hcln->SetName("RpA");//,"b jet RpA");
  hcln->Write();
  h->Write();
  h_den->Write();
  for(int i=0; i<7; i++){
    systErr[i]->Write();
  }
  out->Close();

  // hcln->Fit("pol0","","",45,250);
  //hcln->Fit("pol1","","",45,250);

  cout << "values: { ";
  for(int i=1; i<=hcln->GetNbinsX(); i++){
    cout << hcln->GetBinContent(i) << " ";
  }
  cout << " }" << endl;

  cout << "stat err: { ";
  for(int i=1; i<=hcln->GetNbinsX(); i++){
    cout << hcln->GetBinError(i) << " ";
  }
  cout << " }" << endl;

  cout << "syst err: { ";
  for(int i=1; i<=hcln->GetNbinsX(); i++){
    cout << yerrTot[i-1]+(yerrTot[i-1]*hcln->GetBinContent(i)) << " ";
  }
  cout << " }" << endl;
}
Esempio n. 24
0
void clusterGaussReso() {

  TFile* file = new TFile("complete.root");

  TTree* tree = (TTree *)file->Get("Signal");

  int nEvents = tree->GetEntries();

  double addresses[121] = {};
  for (int k=0; k<121; k++){
    std::stringstream ss2;
    ss2 << k; 
    string str = "Crystal_"+ss2.str();
    const char* charstr = str.c_str(); 
    tree->SetBranchAddress(charstr, &addresses[k]);
  }

  TH1D* energyResoG = new TH1D("energyResoG", "Gauss_Energy_Resolution",
			      100, -10, 10);

  TH2D* posResoG = new TH2D("posResoG", "Gauss_Pos_Resolution", 
			    11, -5, 5, 11, -5, 5);

  double energyThresHi = 50.; //set energy threshold to start looking for bumps
  double energyThresLo = .5; //energy lower bound


  //Going through each scan of the calorimeter
  for (int k=0; k<nEvents; k++)
    {
      tree->GetEntry(k);

      pair<int, double> bump(0, 0.); 
      vector<pair<int, double> > geant;
      vector<pair<int, double> > hitMap;

      for(int i=0; i<121; i++)
	{
	  pair<int, double> hit(i, addresses[i]);
	  geant.push_back(hit);
	  if (addresses[i] > energyThresHi)
	    { hitMap.push_back(hit);}
	  if (hit.second>bump.second)
	    { bump = hit;}
	}

      gaussFit(bump, geant, energyResoG, posResoG);


    } //end of event

 TCanvas* canvas = new TCanvas("canvas", "canvas", 700,700);
 canvas->Divide(2, 1);
 TF1* g1d = new TF1("g1d", "gaus", -10, 10);
 TF2* g2d2 = new TF2("g2d2", Gaus2D, -10, 10, -10, 10, 6);
 g2d2->SetParameters(0., 0., 1., 1., 0., 100000);
 g2d2->FixParameter(4, 0.);
 energyResoG->Fit(g1d);
canvas->cd(1); energyResoG->Draw();
 posResoG->Fit(g2d2);
canvas->cd(2); posResoG->Draw("BOX");

}
//_________________________________________________________________________________
void integratedSplinesV4b(double seed = 231) 
{

	//Load the data
	int nEvents = 1000; //number of times the data will be randomized
	int nPoints = 9;

	vector< vector<double> > xEvents, yEvents, yErrorEvents; //each of these is a vector of vectors (of randomized data points)
	for(int i = 0; i < nEvents; i++) 
	{
		vector <double> xData, yData, yErrorData; //temporary vectors that are only used to get random values from FillRand function
		FillRandVectors(nPoints, xData, yData, yErrorData, seed*(i+1)); //populates random vectors for y values and y error vector
		xEvents.push_back(xData);
		yEvents.push_back(yData);
		yErrorEvents.push_back(yErrorData);
	}

	//Intialization of the variables
	const int npar = nPoints;
	const int orderSpline = 4;
	const int nbreak = npar+2-orderSpline;
	double stepSpline = 0.01;
	double xminBSplineWorkspace = 0;
	double xmaxBSplineWorkspace = 9;
	double startCSplineWorkspace = 15.;
	double stepCSplineWorkspace = 1.5;

	acc_GLOB = gsl_interp_accel_alloc ();
	spline_GLOB = gsl_spline_alloc (gsl_interp_cspline, nPoints);	
	bw_GLOB = gsl_bspline_alloc(orderSpline, nbreak);
	
	//B- and C-splines
	clock_t tbstart, tbstop, tcstart, tcstop;
	vector <double> timeb, timec;

	vector< vector<double> > xBSplineValues, yBSplineValues;
	vector< vector<double> > xCSplineValues, yCSplineValues; 
	for(int i = 0; i < (int)xEvents.size(); i++)
	{
		tbstart = clock();
		vector< vector<double> > bSplineValues = bSpline(nPoints, npar, xEvents.at(i), yEvents.at(i), yErrorEvents.at(i), stepSpline, xminBSplineWorkspace, xmaxBSplineWorkspace);
		tbstop = clock();
		timeb.push_back(((float)tbstop-(float)tbstart)/ (CLOCKS_PER_SEC/1000.) );		

		xBSplineValues.push_back(bSplineValues.at(0));
		yBSplineValues.push_back(bSplineValues.at(1));

		tcstart = clock();
		vector< vector<double> > cSplineValues = cSpline(nPoints, npar, xEvents.at(i), yEvents.at(i), yErrorEvents.at(i), stepSpline, startCSplineWorkspace, stepCSplineWorkspace);
		tcstop = clock();
		timec.push_back(((float)tcstop-(float)tcstart)/ (CLOCKS_PER_SEC/1000.) );		

		xCSplineValues.push_back(cSplineValues.at(0));
		yCSplineValues.push_back(cSplineValues.at(1));
	}

	//Histograms______________________________________________________________________________________

	//Time
	int nbins = 100;
	double xlow = 0;
	double xup = 1.;

	TH1D *hTimeB = new TH1D("Time","; time [ms]; number of runs", nbins, xlow, xup); 
	hTimeB->SetStats(0);
	TH1D *hTimeC = new TH1D("TimeC","; time [ms]; number of runs", nbins, xlow, xup); 
	hTimeC->SetLineColor(kRed);
	hTimeC->SetStats(0);

	for(int i=0; i<(int)timec.size(); i++) 
	{
		hTimeB->Fill(timeb.at(i));
		hTimeC->Fill(timec.at(i));	
	}

	//Interpolation distance -> Should FIND THE RIGHT J FOR SPLINE
	vector <double> interpB, interpC;
	for(int i = 0; i < (int)yEvents.size(); i++)
	{
		for(int j = 0; j < (int)yEvents[i].size(); j++)
		{
			double key = xEvents[i][j];
			int indexForB = binarySearch(xBSplineValues[i], key);
			int indexForC = binarySearch(xCSplineValues[i], key);
			std::cout << "B: " << indexForB << " C: " << indexForC << endl;
			if(indexForB != -1) 
				interpB.push_back( (yEvents[i][j]-yBSplineValues[i][indexForB])/yErrorEvents[i][indexForB] );
			if(indexForC != -1)
				interpC.push_back( (yEvents[i][j]-yCSplineValues[i][indexForC])/yErrorEvents[i][indexForC] );
		}
	}	

	int nbinsI = 40;
	int xlowI = -4;
	int xupI = 4;
	TH1D *hInterpB = new TH1D("Interp B","; xAxis; yAxis", nbinsI, xlowI, xupI); 
	for(int i=0; i<(int)interpB.size(); i++) hInterpB->Fill(interpB.at(i));
	hInterpB->SetStats(0);

	TH1D *hInterpC = new TH1D("Interp C","; xAxis; yAxis", nbinsI, xlowI, xupI); 
	for (int i=0; i<(int)interpC.size(); i++) hInterpC->Fill(interpC.at(i));
	hInterpC->SetLineColor(kRed);
	hInterpC->SetStats(0);	

	//Draws______________________________________________________________________________________

	//Interpolation distance
	TCanvas *c1 = new TCanvas("c1", "Interpolation distance");
	c1->cd();
	hInterpB->Draw("");
	hInterpC->Draw("same");

	//Time
	TLegend *leg = new TLegend(0.75,0.70,0.4,0.85);
	leg->SetLineColor(kWhite); 
	leg->SetFillColor(kWhite);
	leg->SetMargin(0.3); 
	leg->AddEntry(hTimeB,"b-spline","l");
	leg->AddEntry(hTimeC,"c-spline","l");

	TCanvas *c2 = new TCanvas("c2", "Computation time");
	c2->cd();
	hTimeB->Draw("");
	hTimeC->Draw("same");
	leg-> Draw();

	//Free the memory for the spline
	gsl_spline_free (spline_GLOB); //frees the memory used by the spline
 	gsl_interp_accel_free (acc_GLOB);
	gsl_bspline_free(bw_GLOB);
}
void balanceMetVsAj(TString infname = "dj_HCPR-J50U-hiGoodMergedTracks_OfficialSelv2_Final0_120_50.root",
                    TCut myCut = "cent<30", char *title = "",bool drawLegend = false,
                    bool drawSys = true
		    )
{
   // ===========================================================
   // Get Input
   // ===========================================================
   TFile *inf = new TFile(infname);
   TTree *t = (TTree*)inf->Get("ntjt");


   t->SetAlias("metxMergedAll","(metConex0+metConex1+metConex2+metConex3+metConex4+metConex5)");
   t->SetAlias("metxMerged0","(metConex0)");
   t->SetAlias("metxMerged1","(metConex1)");
   t->SetAlias("metxMerged2","(metConex2)");
   t->SetAlias("metxMerged3","(metConex3)");
   t->SetAlias("metxMerged4","(metConex4+metConex5)");

   // ===========================================================
   // Analysis Setup
   // ===========================================================
   const int nBin = 5;
   double bins[nBin+1] = {0.5,1.0,1.5,4,8,1000};
   int colors[5] = {kBlue-10,kYellow-7, kOrange-2,kGreen-5,kRed-3};
   
   const int nBinAj = 4;
   double ajBins[nBinAj+1] = {0.0001,0.11,0.22,0.33,0.49999};
   // Selection cut
   TCut evtCut = "nljet>120&&abs(nljetacorr)<2&&aljet>50&&abs(aljetacorr)<2&&jdphi>2./3*TMath::Pi()&&!maskEvt";

   cout << "Sel evt: " << t->GetEntries(evtCut&&myCut) << endl;

   // ===========================================================
   // Find Average Weights
   // ===========================================================
   TH1D *hw[nBinAj];
   float meanWt[nBinAj];
   for ( int iaj = 0 ; iaj< nBinAj ; iaj++) {
      hw[iaj] = new TH1D(Form("hw_aj%d",iaj),"",1000,0,100);
      TCut ajCut = Form("Aj>%f && Aj<%f", ajBins[iaj],ajBins[iaj+1]);
      t->Draw(Form("weight>>hw_aj%d",iaj), evtCut&&myCut&&ajCut);
      meanWt[iaj] = hw[iaj]->GetMean();
      cout << " <Weight>: " << meanWt[iaj] << endl;
   }

   // ===========================================================
   // Draw Weighted Averages
   // ===========================================================
   TH1D *ppos[nBin];
   TH1D *pneg[nBin];
   TH1D *pe[nBin];
   for (int i=0;i<nBin;i++)
   {
      TH1D *h1 = new TH1D(Form("h1%d",i),"",nBinAj,ajBins);
      TH1D *h2 = new TH1D(Form("h2%d",i),"",nBinAj,ajBins);
      TH1D *he[nBinAj];
      
      // =================================
      // Get Weighted Mean for each Aj bin
      // =================================
      h1->Sumw2();
      h2->Sumw2();
      t->Draw(Form("Aj>>h1%d",i), "weight"*(evtCut&&myCut));
      t->Draw(Form("Aj>>h2%d",i), Form("((-weight*metxMerged%d))",i)*(evtCut&&myCut));
      
      pe[i]=(TH1D*)h2->Clone();
      pe[i]->SetName(Form("p%d",i));     
      pe[i]->Divide(h1);
      ppos[i] = new TH1D(Form("ppos%d",i),"",nBinAj,ajBins);
      ppos[i]->SetLineColor(1);     
      ppos[i]->SetMarkerColor(colors[i]);
      ppos[i]->SetFillColor(colors[i]);
      ppos[i]->SetFillStyle(1001);
      pneg[i] = new TH1D(Form("pneg%d",i),"",nBinAj,ajBins);
      pneg[i]->SetLineColor(1);     
      pneg[i]->SetMarkerColor(colors[i]);
      pneg[i]->SetFillColor(colors[i]);
      pneg[i]->SetFillStyle(1001);

      // =================================
      // Caculated Stat Error of the Mean
      // =================================
      cout << "Stat Error for pt bin " << i << ": ";
      for ( int iaj = 0 ; iaj< nBinAj ; iaj++) {
         he[iaj] = new TH1D(Form("he%d_aj%d",i,iaj),"",100,-200,200);
         TCut ajCut = Form("Aj>%f && Aj<%f", ajBins[iaj],ajBins[iaj+1]);
         t->Draw(Form("((metxMerged%d))>>he%d_aj%d",i,i,iaj), "weight" * evtCut&&myCut&&ajCut);
         float theError = he[iaj]->GetRMS()/ (sqrt(he[iaj]->GetEntries()));
	 cout << theError << " ";
	 pe[i]->SetBinError(iaj+1, theError);
      }
      cout << endl;
   }

   // Stack
   for (int i=nBin-1;i>=0;i--)
   {
      for(int iaj = 0 ; iaj< nBinAj ; iaj++) {
         double posVal=0, negVal=0;
         double posValErr=0, negValErr=0;
         if (i!=nBin-1) {
            posVal = ppos[i+1]->GetBinContent(iaj+1);
            posValErr = ppos[i+1]->GetBinError(iaj+1);
            negVal = pneg[i+1]->GetBinContent(iaj+1);
            negValErr = pneg[i+1]->GetBinError(iaj+1);
         }
         if (pe[i]->GetBinContent(iaj+1)<0) {
            negVal+=pe[i]->GetBinContent(iaj+1);
            negValErr=pe[i]->GetBinError(iaj+1);
            posValErr=0;
         } else if (pe[i]->GetBinContent(iaj+1)>0) {
            posVal+=pe[i]->GetBinContent(iaj+1);
            posValErr=pe[i]->GetBinError(iaj+1);
            negValErr=0;
         } 
         ppos[i]->SetBinContent(iaj+1,posVal);
         ppos[i]->SetBinError(iaj+1,posValErr);
         pneg[i]->SetBinContent(iaj+1,negVal);
         pneg[i]->SetBinError(iaj+1,negValErr);
      }
   }
   
   TH1D *pall;
   TH1D *pallE;
   TH1D *h1 = new TH1D(Form("hAll1"),"",nBinAj,ajBins);
   TH1D *h2 = new TH1D(Form("hAll2"),"",nBinAj,ajBins);

   h1->Sumw2();
   h2->Sumw2();
   t->Draw(Form("Aj>>hAll1"), "weight"*(evtCut&&myCut));
   t->Draw(Form("Aj>>hAll2"), Form("((-weight*metxMergedAll))")*(evtCut&&myCut));
   pall=(TH1D*)h2->Clone();
   pall->SetName("pall");
   pall->Divide(h1);

   // replace the sys error from pallE to pall 
   TH1D *he[nBinAj];
   cout << "Stat Error for All pt: ";
   for ( int iaj = 0 ; iaj< nBinAj ; iaj++) {
      he[iaj] = new TH1D(Form("heAll_aj%d",iaj),"",100,-200,200);
      TCut ajCut = Form("Aj>%f && Aj<%f", ajBins[iaj],ajBins[iaj+1]);
      t->Draw(Form("((metxMergedAll))>>heAll_aj%d",iaj), "weight" * evtCut&&myCut&&ajCut);
      float theError = he[iaj]->GetRMS()/ (sqrt(he[iaj]->GetEntries()));
      cout << theError << " ";
      pall->SetBinError(iaj+1,  theError);
   }
   cout << endl;

   pall->SetXTitle("A_{J}");
   pall->SetYTitle("<#slash{p}_{T}^{#parallel}> (GeV/c)");
   pall->GetXaxis()->CenterTitle();
   pall->GetYaxis()->CenterTitle();
   pall->GetXaxis()->SetLabelSize(22);
   pall->GetXaxis()->SetLabelFont(43);
   pall->GetXaxis()->SetTitleSize(24);
   pall->GetXaxis()->SetTitleFont(43);
   pall->GetYaxis()->SetLabelSize(22);
   pall->GetYaxis()->SetLabelFont(43);
   pall->GetYaxis()->SetTitleSize(24);
   pall->GetYaxis()->SetTitleFont(43);
   pall->GetXaxis()->SetTitleOffset(1.8);
   pall->GetYaxis()->SetTitleOffset(2.4);
   pall->SetNdivisions(505);
   pall->SetAxisRange(-59.9,59.9,"Y");
   pall->SetMarkerSize(1);
   pall->Draw("E");
   float addSys = 0;
   if ( drawSys==1)   addSys=0; // No sys error at this moment

   // ====================
   // Finally Draw
   // ====================
   for (int i=0;i<nBin;++i) {
      ppos[i]->SetLineWidth(1);
      ppos[i]->Draw("hist same");
      pneg[i]->SetLineWidth(1);
      pneg[i]->Draw("hist same");
   }
   
   // ====================
   // Draw Statistical Error bars
   // ====================
   for (int i=0;i<nBin;++i) {
      if ( i==0 )       drawErrorShift(ppos[i],-0.016, addSys);
      if ( i==1 )       drawErrorShift(ppos[i],-0.008,addSys);
      if ( i==2 )       drawErrorShift(ppos[i],0.008,addSys);
      if ( i==3 )       drawErrorShift(ppos[i],0.016,addSys);
      if ( i==4 )       drawErrorShift(ppos[i],0.024,addSys);
      if ( i==0 )       drawErrorShift(pneg[i],-0.016, addSys);
      if ( i==1 )       drawErrorShift(pneg[i],-0.008,addSys);
      if ( i==2 )       drawErrorShift(pneg[i],0.008,addSys);
      if ( i==3 )       drawErrorShift(pneg[i],0.016,addSys);
      if ( i==4 )       drawErrorShift(pneg[i],0.024,addSys);
   }
   pall->Draw("E same");
   
   // ====================
   // Draw Systematic Errors
   // ====================
   if (drawSys == 1) {
      for(int i = 0; i < nBinAj; ++i){
        double x = pall->GetBinCenter(i+1);
        double y = pall->GetBinContent(i+1);
        // Quote the difference between GEN and RECO in >8 Bin (20%) before adjusting eff as systematics
        double err = fabs(pe[nBin-1]->GetBinContent(i+1)*0.2);
        DrawTick(y,err,err,x,1,0.02,1);
      }
   }

   // ====================
   // Draw Legend
   // ====================
   TLegend *leg = new TLegend(0.10,0.68,0.70,0.96);
   leg->SetFillStyle(0);
   leg->SetBorderSize(0);
   leg->SetTextFont(63);
   leg->SetTextSize(16);
   leg->AddEntry(pall,Form("> %.1f GeV/c",bins[0]),"pl");
   for (int i=0;i<nBin;++i) {
      if (i!=nBin-1){
         leg->AddEntry(ppos[i],Form("%.1f - %.1f GeV/c",bins[i],bins[i+1]),"f");
      } else {
         leg->AddEntry(ppos[i],Form("> %.1f GeV/c",bins[i]),"f");
      }
   }

   if (drawLegend) leg->Draw();

   TLine * l0 = new TLine(0,0,0.5,0);
   l0->SetLineStyle(2);
   l0->Draw();


   TLine * l1 = new TLine(0.0001,-10,0.0001,10);
   l1->Draw();

   TText *titleText = new TText(0.3,30,title);
   titleText->Draw();
}
Esempio n. 27
0
void RPCSeedValidator(string FileName) {

    gStyle->SetOptStat("");
    gStyle->SetOptTitle(0);
    if(debug) cout << FileName << endl;
    string theFileName = "../" + FileName;
    TFile* RootFile = TFile::Open(theFileName.c_str());
    string OutputPlotNameFix = ".eps";
    string FinalOutput = FileName + "_";

    unsigned int EventNumber;
    int SimTrackId;
    int SimTrackType;
    double SimTrackMomentum;
    double SimTrackDirectionPhi;
    int SimTrackCharge;
    int SimTrackvalid;
    bool PassSegmentFilter;
    double SimMomentumPtatRef;
    double SimDirectionPhiatRef;
    double SimDirectionEtaatRef;
    double SimBendingPhi;
    double SimBendingEntryPositionX;
    double SimBendingEntryPositionY;
    double SimBendingEntryPositionZ;
    double SimBendingLeavePositionX;
    double SimBendingLeavePositionY;
    double SimBendingLeavePositionZ;
    unsigned int SeedNumber;
    int SeedCharge;
    double SeedPurity;
    double SeedQuality;
    double RecMomentumPtatRef;
    double RecDirectionPhiatRef;
    double RecDirectionEtaatRef;
    double RecBendingPhi;
    double RecBendingEntryPositionX;
    double RecBendingEntryPositionY;
    double RecBendingEntryPositionZ;
    double RecBendingLeavePositionX;
    double RecBendingLeavePositionY;
    double RecBendingLeavePositionZ;
    double RecBendingLastPhi;

    TTree* T0 = (TTree*)RootFile->Get("ExTree");
    T0->SetBranchAddress("EventNumber", &EventNumber);
    T0->SetBranchAddress("SimTrackId", &SimTrackId);
    T0->SetBranchAddress("SimTrackType", &SimTrackType);
    T0->SetBranchAddress("SimTrackMomentum", &SimTrackMomentum);
    T0->SetBranchAddress("SimTrackDirectionPhi", &SimTrackDirectionPhi);
    T0->SetBranchAddress("SimTrackCharge", &SimTrackCharge);
    T0->SetBranchAddress("SimTrackValid", &SimTrackvalid);
    T0->SetBranchAddress("PassSegmentFilter", &PassSegmentFilter);
    T0->SetBranchAddress("SimMomentumPtatRef", &SimMomentumPtatRef);
    T0->SetBranchAddress("SimDirectionPhiatRef", &SimDirectionPhiatRef);
    T0->SetBranchAddress("SimDirectionEtaatRef", &SimDirectionEtaatRef);
    T0->SetBranchAddress("SimBendingPhi", &SimBendingPhi);
    T0->SetBranchAddress("SimBendingEntryPositionX", &SimBendingEntryPositionX);
    T0->SetBranchAddress("SimBendingEntryPositionY", &SimBendingEntryPositionY);
    T0->SetBranchAddress("SimBendingEntryPositionZ", &SimBendingEntryPositionZ);
    T0->SetBranchAddress("SimBendingLeavePositionX", &SimBendingLeavePositionX);
    T0->SetBranchAddress("SimBendingLeavePositionY", &SimBendingLeavePositionY);
    T0->SetBranchAddress("SimBendingLeavePositionZ", &SimBendingLeavePositionZ);
    T0->SetBranchAddress("SeedNumber", &SeedNumber);
    T0->SetBranchAddress("SeedCharge", &SeedCharge);
    T0->SetBranchAddress("SeedPurity", &SeedPurity);
    T0->SetBranchAddress("SeedQuality", &SeedQuality);
    T0->SetBranchAddress("RecMomentumPtatRef", &RecMomentumPtatRef);
    T0->SetBranchAddress("RecDirectionPhiatRef", &RecDirectionPhiatRef);
    T0->SetBranchAddress("RecDirectionEtaatRef", &RecDirectionEtaatRef);
    T0->SetBranchAddress("RecBendingPhi", &RecBendingPhi);
    T0->SetBranchAddress("RecBendingEntryPositionX", &RecBendingEntryPositionX);
    T0->SetBranchAddress("RecBendingEntryPositionY", &RecBendingEntryPositionY);
    T0->SetBranchAddress("RecBendingEntryPositionZ", &RecBendingEntryPositionZ);
    T0->SetBranchAddress("RecBendingLeavePositionX", &RecBendingLeavePositionX);
    T0->SetBranchAddress("RecBendingLeavePositionY", &RecBendingLeavePositionY);
    T0->SetBranchAddress("RecBendingLeavePositionZ", &RecBendingLeavePositionZ);
    T0->SetBranchAddress("RecBendingLastPhi", &RecBendingLastPhi);

    TH1D* SimTrackvalidHist = (TH1D*) new TH1D("SimTrackvalidHist", "SimTrackvalidHist", 2, 0, 2);
    TH1D* SeedPtforSimTrackvalidHist = (TH1D*) new TH1D("SeedPtforSimTrackvalidHist", "SeedPtforSimTrackvalidHist", 100, 0, 100);
    TH1D* SeeddeltaPtforSimTrackvalidHist = (TH1D*) new TH1D("SeeddeltaPtforSimTrackvalidHist", "SeeddeltaPtforSimTrackvalidHist", 150, -3., 3.);
    TH1D* SeeddeltaPhiforSimTrackvalidHist = (TH1D*) new TH1D("SeeddeltaPhiforSimTrackvalidHist", "SeeddeltaPhiforSimTrackvalidHist", 628, -3.14/6, 3.14/6);
    TH1D* SeeddeltaEtaforSimTrackvalidHist = (TH1D*) new TH1D("SeeddeltaEtaforSimTrackvalidHist", "SeeddeltaEtaforSimTrackvalidHist", 200, -1., 1.);
    TH1D* SeedPurityforSimTrackvalidHist = (TH1D*) new TH1D("SeedPurityforSimTrackvalidHist", "SeedPurityforSimTrackvalidHist", 20, 0, 2);
    TH1D* ChargeCheckforSimTrackvalidHist = (TH1D*) new TH1D("ChargeCheckforSimTrackvalidHist", "ChargeCheckforSimTrackvalidHist", 5, -2.5, 2.5);
    TH1D* SeedNumberforSimTrackvalidHist = (TH1D*) new TH1D("SeedNumberforSimTrackvalidHist", "SeedNumberforSimTrackvalidHist", 30, 0, 30);
    TH1D* SeedEfficiencyforSimTrackvalidHist = (TH1D*) new TH1D("SeedEfficiencyforSimTrackvalidHist", "SeedEfficiencyforSimTrackvalidHist", 2, 0, 2);
    TH1D* SeedNumberforSimTrackinvalidHist = (TH1D*) new TH1D("SeedNumberforSimTrackinvalidHist", "SeedNumberforSimTrackinvalidHist", 20, 0, 20);
    TH1D* SeedEfficiencyforSimTrackinvalidHist = (TH1D*) new TH1D("SeedEfficiencyforSimTrackinvalidHist", "SeedEfficiencyforSimTrackinvalidHist", 2, 0, 2);
    TH1D* RecBendingLastPhiHist = (TH1D*) new TH1D("RecBendingLastPhiHist", "RecBendingLastPhiHist", 628, -3.14/2, 3.14/2);
    TH1D* SeedEfficiencyHist = (TH1D*) new TH1D("SeedEfficiency", "SeedEfficiency", 2, 0, 2);
    TH2D* RecBendingPhi2PtHist = new TH2D("RecBendingPhi2PtHist", "RecBendingPhi2PtHist", 2000, -100, 100, 628, -3.14/4, 3.14/4);
    TH2D* PtRatoofRecBendingPhiHist = new TH2D("", "", 628, -3.14/4, 3.14/4, 2000, -100, 100);
    TObjArray* SimReverseBending = (TObjArray*) new TObjArray();

    unsigned int LastSeedNumber = -1;
    unsigned int LastSimTrackvalid = 0;
    bool LastPassSegmentFilter = false;
    bool LastPurityFull = false;
    int Nentries = T0->GetEntries();
    for(int i = 0; i < Nentries; i++) {
        T0->GetEntry(i);

        if(debug) cout << "SimTrackId: " << SimTrackId << ", SimTrackType: " << SimTrackType << ", PassSegmentFilter: " << PassSegmentFilter << ", SeedNumber: " << SeedNumber << ", SeedPurity: " << SeedPurity << ", SeedCharge: " << SeedCharge << ", SimTrackCharge: " << SimTrackCharge << ", SimBendingPhi: " << SimBendingPhi << ", RecBendingPhi: " << RecBendingPhi << ", RecBendingLastPhi: " << RecBendingLastPhi << ", RecMomentumPtatRef: " << RecMomentumPtatRef << ", SimMomentumPtatRef: " << SimMomentumPtatRef << ", LastSeedNumber: " << LastSeedNumber << endl;

        //if(SimTrackMomentum > 20.0)
            //continue;

        if(SeedNumber != 0) {
            if(SimTrackvalid == 1 && SeedPurity == 1. && PassSegmentFilter == true) {
                SeedPtforSimTrackvalidHist->Fill(RecMomentumPtatRef);
                SeeddeltaPtforSimTrackvalidHist->Fill((RecMomentumPtatRef-SimMomentumPtatRef)/SimMomentumPtatRef);
                SeeddeltaPhiforSimTrackvalidHist->Fill(RecDirectionPhiatRef-SimDirectionPhiatRef);
                SeeddeltaEtaforSimTrackvalidHist->Fill(RecDirectionEtaatRef-SimDirectionEtaatRef);
                RecBendingPhi2PtHist->Fill(SimMomentumPtatRef*SimTrackCharge, RecBendingPhi);
                double PtRato = SimMomentumPtatRef / RecMomentumPtatRef;
                if(debug) cout << "PtRato: " << PtRato << ", at RecBendingPhi: " << RecBendingPhi << endl;
                PtRatoofRecBendingPhiHist->Fill(RecBendingPhi, PtRato);
                RecBendingLastPhiHist->Fill((RecBendingLastPhi == 0. ? 0 : RecBendingLastPhi/fabs(RecBendingLastPhi))*SimTrackCharge);
                SeedPurityforSimTrackvalidHist->Fill(SeedPurity);
                ChargeCheckforSimTrackvalidHist->Fill(SeedCharge*SimTrackCharge);
                /*
                if(SeedPurity == 1) {
                    //SeedPtforSimTrackvalidHist->Fill(RecMomentumPtatRef);
                    //SeeddeltaPtforSimTrackvalidHist->Fill(RecMomentumPtatRef-SimMomentumPtatRef);
                    RecBendingPhi2PtHist->Fill(SimMomentumPtatRef*SimTrackCharge, RecBendingPhi);
                    double PtRato = SimMomentumPtatRef / RecMomentumPtatRef;
                    if(debug) cout << "PtRato: " << PtRato << ", at RecBendingPhi: " << RecBendingPhi << endl;
                    PtRatoofRecBendingPhiHist->Fill(RecBendingPhi, PtRato);
                    RecBendingLastPhiHist->Fill((RecBendingLastPhi == 0. ? 0 : RecBendingLastPhi/fabs(RecBendingLastPhi))*SimTrackCharge);
                }
                */
                if(SeedCharge*SimTrackCharge == -1) {
                    if(debug) cout << "R1: " << sqrt(SimBendingEntryPositionX*SimBendingEntryPositionX+SimBendingEntryPositionY*SimBendingEntryPositionY) << ", R2: " << sqrt(SimBendingLeavePositionX*SimBendingLeavePositionX+SimBendingLeavePositionY*SimBendingLeavePositionY) << endl;
                    TLine* SimSegment = new TLine(SimBendingEntryPositionX, SimBendingEntryPositionY, SimBendingLeavePositionX, SimBendingLeavePositionY);
                    SimReverseBending->AddLast(SimSegment);
                }
                LastPurityFull = true;
            }
        }
        else {
            if(LastSeedNumber != -1) {
                if(LastSimTrackvalid == 1 && LastPassSegmentFilter == true) {
                    if(debug) cout << "Filling valid track efficiency " << LastSeedNumber << endl;
                    SeedNumberforSimTrackvalidHist->Fill(LastSeedNumber);
                    SeedEfficiencyforSimTrackvalidHist->Fill(LastPurityFull==true?1:0);
                }
                else {
                    SeedNumberforSimTrackinvalidHist->Fill(LastSeedNumber);
                    SeedEfficiencyforSimTrackinvalidHist->Fill(LastPurityFull==true?1:0);
                }
                LastPurityFull = false;
            }
        }
        LastPassSegmentFilter = PassSegmentFilter;
        LastSeedNumber = SeedNumber;
        LastSimTrackvalid = SimTrackvalid;
    }
    if(LastSeedNumber != -1) {
        if(LastSimTrackvalid == 1 && LastPassSegmentFilter == true) {
            SeedNumberforSimTrackvalidHist->Fill(LastSeedNumber);
            SeedEfficiencyforSimTrackvalidHist->Fill(LastPurityFull==true?1:0);
        }
        else {
            SeedNumberforSimTrackinvalidHist->Fill(LastSeedNumber);
            SeedEfficiencyforSimTrackinvalidHist->Fill(LastPurityFull == true?1:0);
        }
    }

    TCanvas* SimTrackvalidCanvas = new TCanvas("SimTrackvalidCanvas", "SimTrackvalidCanvas", 800, 600);
    SimTrackvalidCanvas->cd();
    SimTrackvalidHist->Draw();
    string SimTrackvalidCanvasName = FinalOutput + "SimTrackvalid" + OutputPlotNameFix;
    SimTrackvalidCanvas->SaveAs(SimTrackvalidCanvasName.c_str());

    TCanvas* SeedPtforSimTrackvalidCanvas = new TCanvas("SeedPtforSimTrackvalidCanvas", "SeedPtforSimTrackvalidCanvas", 800, 600);
    SeedPtforSimTrackvalidCanvas->cd();
    SeedPtforSimTrackvalidHist->Draw();
    string SeedPtforSimTrackvalidCanvasName = FinalOutput + "SeedPtforSimTrackvalid" + OutputPlotNameFix;
    SeedPtforSimTrackvalidCanvas->SaveAs(SeedPtforSimTrackvalidCanvasName.c_str());

    TCanvas* SeeddeltaPtforSimTrackvalidCanvas = new TCanvas("SeeddeltaPtforSimTrackvalidCanvas", "SeeddeltaPtforSimTrackvalidCanvas", 800, 600);
    SeeddeltaPtforSimTrackvalidCanvas->cd();
    SeeddeltaPtforSimTrackvalidHist->SetStats(1);
    gStyle->SetOptFit(0111);
    //SeeddeltaPtforSimTrackvalidHist->Fit("gaus", "", "", -1., 1.);
    SeeddeltaPtforSimTrackvalidHist->GetXaxis()->SetTitle("(recPt-simPt)/simPt");
    SeeddeltaPtforSimTrackvalidHist->GetXaxis()->CenterTitle();
    SeeddeltaPtforSimTrackvalidHist->Draw();
    string SeeddeltaPtforSimTrackvalidCanvasName = FinalOutput + "SeeddeltaPtforSimTrackvalid" + OutputPlotNameFix;
    SeeddeltaPtforSimTrackvalidCanvas->SaveAs(SeeddeltaPtforSimTrackvalidCanvasName.c_str());

    TCanvas* SeeddeltaPhiforSimTrackvalidCanvas = new TCanvas("SeeddeltaPhiforSimTrackvalidCanvas", "SeeddeltaPhiforSimTrackvalidCanvas", 800, 600);
    SeeddeltaPhiforSimTrackvalidCanvas->cd();
    SeeddeltaPhiforSimTrackvalidHist->SetStats(1);
    SeeddeltaPhiforSimTrackvalidHist->GetXaxis()->SetTitle("(recPhi-simPhi)");
    SeeddeltaPhiforSimTrackvalidHist->GetXaxis()->CenterTitle();
    SeeddeltaPhiforSimTrackvalidHist->Draw();
    string SeeddeltaPhiforSimTrackvalidCanvasName = FinalOutput + "SeeddeltaPhiforSimTrackvalid" + OutputPlotNameFix;
    SeeddeltaPhiforSimTrackvalidCanvas->SaveAs(SeeddeltaPhiforSimTrackvalidCanvasName.c_str());

    TCanvas* SeeddeltaEtaforSimTrackvalidCanvas = new TCanvas("SeeddeltaEtaforSimTrackvalidCanvas", "SeeddeltaEtaforSimTrackvalidCanvas", 800, 600);
    SeeddeltaEtaforSimTrackvalidCanvas->cd();
    SeeddeltaEtaforSimTrackvalidHist->SetStats(1);
    SeeddeltaEtaforSimTrackvalidHist->GetXaxis()->SetTitle("(recEta-simEta)");
    SeeddeltaEtaforSimTrackvalidHist->GetXaxis()->CenterTitle();
    SeeddeltaEtaforSimTrackvalidHist->Draw();
    string SeeddeltaEtaforSimTrackvalidCanvasName = FinalOutput + "SeeddeltaEtaforSimTrackvalid" + OutputPlotNameFix;
    SeeddeltaEtaforSimTrackvalidCanvas->SaveAs(SeeddeltaEtaforSimTrackvalidCanvasName.c_str());


    TCanvas* SeedPurityforSimTrackvalidCanvas = new TCanvas("SeedPurityforSimTrackvalidCanvas", "SeedPurityforSimTrackvalidCanvas", 800, 600);
    SeedPurityforSimTrackvalidCanvas->cd();
    SeedPurityforSimTrackvalidHist->Draw();
    string SeedPurityforSimTrackvalidCanvasName = FinalOutput + "SeedPurityforSimTrackvalid" + OutputPlotNameFix;
    SeedPurityforSimTrackvalidCanvas->SaveAs(SeedPurityforSimTrackvalidCanvasName.c_str());

    TCanvas* ChargeCheckforSimTrackvalidCanvas = new TCanvas("ChargeCheckforSimTrackvalidCanvas", "ChargeCheckforSimTrackvalidCanvas", 800, 600);
    ChargeCheckforSimTrackvalidCanvas->cd();
    double HistEntries = ChargeCheckforSimTrackvalidHist->GetEntries() / 100.;
    ChargeCheckforSimTrackvalidHist->Scale(1./HistEntries);
    ChargeCheckforSimTrackvalidHist->GetXaxis()->SetTitle("simCharge*recCharge");
    ChargeCheckforSimTrackvalidHist->GetXaxis()->CenterTitle(1);
    ChargeCheckforSimTrackvalidHist->GetYaxis()->SetTitle("fraction %");
    ChargeCheckforSimTrackvalidHist->GetYaxis()->CenterTitle(1);
    ChargeCheckforSimTrackvalidHist->Draw();
    string ChargeCheckforSimTrackvalidCanvasName = FinalOutput + "ChargeCheckforSimTrackvalid" + OutputPlotNameFix;
    ChargeCheckforSimTrackvalidCanvas->SaveAs(ChargeCheckforSimTrackvalidCanvasName.c_str());

    TCanvas* SeedNumberforSimTrackvalidCanvas = new TCanvas("SeedNumberforSimTrackvalidCanvas", "SeedNumberforSimTrackvalidCanvas", 800, 600);
    SeedNumberforSimTrackvalidCanvas->cd();
    SeedNumberforSimTrackvalidHist->Draw();
    string SeedNumberforSimTrackvalidCanvasName = FinalOutput + "SeedNumberforSimTrackvalid" + OutputPlotNameFix;
    SeedNumberforSimTrackvalidCanvas->SaveAs(SeedNumberforSimTrackvalidCanvasName.c_str());

    TCanvas* SeedEfficiencyforSimTrackvalidCanvas = new TCanvas("SeedEfficiencyforSimTrackvalidCanvas", "SeedEfficiencyforSimTrackvalidCanvas", 800, 600);
    SeedEfficiencyforSimTrackvalidCanvas->cd();
    SeedEfficiencyforSimTrackvalidHist->Draw();
    string SeedEfficiencyforSimTrackvalidCanvasName = FinalOutput + "SeedEfficiencyforSimTrackvalid" + OutputPlotNameFix;
    SeedEfficiencyforSimTrackvalidCanvas->SaveAs(SeedEfficiencyforSimTrackvalidCanvasName.c_str());

    TCanvas* SeedNumberforSimTrackinvalidCanvas = new TCanvas("SeedNumberforSimTrackinvalidCanvas", "SeedNumberforSimTrackinvalidCanvas", 800, 600);
    SeedNumberforSimTrackinvalidCanvas->cd();
    SeedNumberforSimTrackinvalidHist->Draw();
    string SeedNumberforSimTrackinvalidCanvasName = FinalOutput + "SeedNumberforSimTrackinvalid" + OutputPlotNameFix;
    SeedNumberforSimTrackinvalidCanvas->SaveAs(SeedNumberforSimTrackinvalidCanvasName.c_str());

    TCanvas* SeedEfficiencyforSimTrackinvalidCanvas = new TCanvas("SeedEfficiencyforSimTrackinvalidCanvas", "SeedEfficiencyforSimTrackinvalidCanvas", 800, 600);
    SeedEfficiencyforSimTrackinvalidCanvas->cd();
    SeedEfficiencyforSimTrackinvalidHist->Draw();
    string SeedEfficiencyforSimTrackinvalidCanvasName = FinalOutput + "SeedEfficiencyforSimTrackinvalid" + OutputPlotNameFix;
    SeedEfficiencyforSimTrackinvalidCanvas->SaveAs(SeedEfficiencyforSimTrackinvalidCanvasName.c_str());

    double SeedEfficiencyforSimTrackinvalid = 100. * SeedEfficiencyforSimTrackinvalidHist->GetMean();
    double SeedEfficiencyforSimTrackvalid = 100. * SeedEfficiencyforSimTrackvalidHist->GetMean();
    SeedEfficiencyHist->SetBinContent(1, SeedEfficiencyforSimTrackinvalid);
    SeedEfficiencyHist->SetBinContent(2, SeedEfficiencyforSimTrackvalid);
    SeedEfficiencyHist->GetXaxis()->SetBinLabel(1, "for invalid simTrack");
    SeedEfficiencyHist->GetXaxis()->SetBinLabel(2, "for valid simTrack");
    TCanvas* SeedEfficiencyCanvas = new TCanvas("SeedEfficiencyCanvas", "SeedEfficiencyCanvas", 800, 600);
    SeedEfficiencyCanvas->cd();
    SeedEfficiencyHist->GetYaxis()->SetTitle("Efficiency %");
    SeedEfficiencyHist->GetYaxis()->CenterTitle(1);
    SeedEfficiencyHist->SetMarkerStyle(3);
    SeedEfficiencyHist->SetMarkerSize(3);
    SeedEfficiencyHist->Draw("P");
    string SeedEfficiencyCanvasName = FinalOutput + "SeedEfficiency" + OutputPlotNameFix;
    SeedEfficiencyCanvas->SaveAs(SeedEfficiencyCanvasName.c_str());

    TCanvas* RecBendingPhi2PtCanvas = new TCanvas("RecBendingPhi2PtCanvas", "RecBendingPhi2PtCanvas", 800, 600);
    RecBendingPhi2PtCanvas->cd();
    RecBendingPhi2PtHist->Draw();
    string RecBendingPhi2PtCanvasName = FinalOutput + "RecBendingPhi2Pt" + OutputPlotNameFix;
    RecBendingPhi2PtCanvas->SaveAs(RecBendingPhi2PtCanvasName.c_str());

    TCanvas* PtRatoofRecBendingPhiCanvas = new TCanvas("PtRatoofRecBendingPhiCanvas", "PtRatoofRecBendingPhiCanvas", 800, 600);
    PtRatoofRecBendingPhiCanvas->cd();
    PtRatoofRecBendingPhiHist->Draw();
    string PtRatoofRecBendingPhiCanvasName = FinalOutput + "PtRatoofRecBendingPhi" + OutputPlotNameFix;
    PtRatoofRecBendingPhiCanvas->SaveAs(PtRatoofRecBendingPhiCanvasName.c_str());

    TCanvas* RecBendingLastPhiCanvas = new TCanvas("RecBendingLastPhiCanvas", "RecBendingLastPhiCanvas", 800, 600);
    RecBendingLastPhiCanvas->cd();
    RecBendingLastPhiHist->Draw();
    string RecBendingLastPhiCanvasName = FinalOutput + "RecBendingLastPhi" + OutputPlotNameFix;
    RecBendingLastPhiCanvas->SaveAs(RecBendingLastPhiCanvasName.c_str());

    Int_t linsav = gStyle->GetLineWidth();
    gStyle->SetLineWidth(2);
    TCanvas* SimReverseBendingCanvas = new TCanvas("SimReverseBendingCanvas", "SimReverseBendingCanvas", 800, 800);
    SimReverseBendingCanvas->cd();
    TPad* SimReverseBendingPad = new TPad("SimReverseBendingPad", "SimReverseBendingPad", 0, 0, 1, 1);
    SimReverseBendingPad->Draw();
    SimReverseBendingPad->cd();
    SimReverseBendingPad->Range(-800, -800, 800, 800);
    unsigned int segmentNumber = SimReverseBending->GetEntries();
    cout << "Number of segments: " << segmentNumber << endl;
    for(unsigned int j = 0; j < segmentNumber; j++) {
        ((TLine*)(SimReverseBending->At(j)))->Print();
        ((TLine*)(SimReverseBending->At(j)))->Draw("SAME");
    }
    string SimReverseBendingCanvasName = FinalOutput + "SimReverseBending" + OutputPlotNameFix;
    SimReverseBendingCanvas->SaveAs(SimReverseBendingCanvasName.c_str());
}
Esempio n. 28
0
//_________________________________________________________________________________
void integratedSplinesV5(double seed = 231)
{
    //Load the data
    int nEvents = 1000; //number of times the data will be randomized
    int nPoints = 9;
    double lowerBound = 10; //bounds for random vector function
    double upperBound = 20;
    double lowerErrorBound = 1;
    double upperErrorBound = 2;

    vector< vector<double> > xEvents, yEvents, yErrorEvents; //each of these is a vector of vectors (of randomized data points)
    for(int i = 0; i < nEvents; i++)
    {
        vector <double> xData, yData, yErrorData; //temporary vectors that are only used to get random values from FillRand function
        FillRandVectors(nPoints, xData, yData, yErrorData, seed*(i+1), lowerBound, upperBound, lowerErrorBound, upperErrorBound); //populates random vectors for y values and y error vector
        xEvents.push_back(xData);
        yEvents.push_back(yData);
        yErrorEvents.push_back(yErrorData);
        //Populate the global variables
        xData_GLOB = xData;
        yData_GLOB = yData;
        yErrorData_GLOB = yErrorData;
    }

    //Intialization of the variables
    const int npar = nPoints;
    const int orderSpline = 4;
    const int nbreak = npar+2-orderSpline;
    double stepSpline = 0.01;
    double xminBSplineWorkspace = 0;
    double xmaxBSplineWorkspace = 9;
    double startCSplineWorkspace = 15.;
    double stepCSplineWorkspace = 1.5;

    acc_GLOB = gsl_interp_accel_alloc ();
    spline_GLOB = gsl_spline_alloc (gsl_interp_cspline, nPoints);
    gsl_bspline_workspace *bw = gsl_bspline_alloc(orderSpline, nbreak);

//Setup for the C-spline_________________________________________________________________________

    //Setting up TMinuit for C-spline minimization
    TMinuit *myMinuit = new TMinuit(npar);  //initialize TMinuit with a maximum of npar
    myMinuit->SetFCN(fcn);
    myMinuit->SetPrintLevel(-1); //No output: -1, output:1

    double arglist[10];
    int ierflg = 0;
    arglist[0] = 1;
    myMinuit->mnexcm("SET ERR", arglist, 1, ierflg);

    vector<double> vstart, vstep;
    for(int i=0; i < npar; i++) 	//set starting values and step sizes for parameters
    {
        vstart.push_back(startCSplineWorkspace);
        vstep.push_back(stepCSplineWorkspace);
    }

    for (int i = 0; i < npar; i++)
    {
        stringstream ss;
        ss<<"a"<<i;
        myMinuit->mnparm(i, ss.str().c_str(), vstart.at(i), vstep.at(i), 0, 0, ierflg);
    }

    //Perform the Minuit fit
    arglist[0] = 500;
    arglist[1] = 1.;

//Setup for the B-spline_________________________________________________________________________
    //Declare and allocate memory to compose data set of control points
    gsl_vector *xControl = gsl_vector_alloc(nPoints);
    gsl_vector *yControl = gsl_vector_alloc(nPoints);
    gsl_vector *w = gsl_vector_alloc(nPoints);
    gsl_vector *B = gsl_vector_alloc(npar);
    gsl_matrix *X = gsl_matrix_alloc(nPoints, npar);

    //Create a b spline workspace and allocate its memory
    gsl_bspline_knots_uniform(xminBSplineWorkspace, xmaxBSplineWorkspace, bw);
    //Set up the variables for the fit matrix
    for (int i = 0; i < nPoints; ++i)
    {
        gsl_bspline_eval(gsl_vector_get(xControl, i), B, bw); //Compute B_j(xi) for all j
        for (int j = 0; j < npar; ++j)	gsl_matrix_set(X, i, j, gsl_vector_get(B, j)); //Fill in row i of X
    }

    gsl_vector *c = gsl_vector_alloc(npar);
    gsl_multifit_linear_workspace *mw = gsl_multifit_linear_alloc(nPoints, npar);
    gsl_matrix *cov = gsl_matrix_alloc(npar, npar);

//B and C spline loops__________________________________________________________________________
    clock_t tbstart, tbstop, tcstart, tcstop;
    vector <double> timeb, timec;

    vector< vector<double> > xBSplineValues, yBSplineValues;
    vector< vector<double> > xCSplineValues, yCSplineValues;

    for(int i = 0; i < (int)xEvents.size(); i++)
    {
        //Populate gsl vectors with the appropriate data
        for (int j = 0; j < nPoints; j++)
        {
            double xi = xEvents[i][j];
            double yi = yEvents[i][j];
            double sigma = yErrorEvents[i][j];
            gsl_vector_set(xControl, j, xi);
            gsl_vector_set(yControl, j, yi);
            gsl_vector_set(w, j, 1.0/(sigma*sigma));
        }

        tbstart = clock();
        vector< vector<double> > bSplineValues = bSpline(xEvents.at(i),stepSpline, bw, yControl, B, X, c, mw, cov);
        tbstop = clock();
        timeb.push_back(((float)tbstop-(float)tbstart)/ (CLOCKS_PER_SEC/1000.) );

        xBSplineValues.push_back(bSplineValues.at(0));
        yBSplineValues.push_back(bSplineValues.at(1));

        tcstart = clock();
        vector< vector<double> > cSplineValues = cSpline(nPoints, npar, xEvents.at(i), stepSpline, myMinuit, arglist, ierflg);
        tcstop = clock();
        timec.push_back(((float)tcstop-(float)tcstart)/ (CLOCKS_PER_SEC/1000.) );

        xCSplineValues.push_back(cSplineValues.at(0));
        yCSplineValues.push_back(cSplineValues.at(1));
    }

    //Histograms______________________________________________________________________________________

    //Time
    int nbins = 100;
    double xlow = 0;
    double xup = 1.;

    TH1D *hTimeB = new TH1D("Time","Timing; time [ms]; Number of Events", nbins, xlow, xup);
    hTimeB->SetStats(0);
    TH1D *hTimeC = new TH1D("TimeC","Timing; time [ms]; Number of Events", nbins, xlow, xup);
    hTimeC->SetLineColor(kRed);
    hTimeC->SetStats(0);

    for(int i=0; i<(int)timec.size(); i++)
    {
        hTimeB->Fill(timeb.at(i));
        hTimeC->Fill(timec.at(i));
    }

    //Interpolation distance
    vector <double> interpB, interpC;
    for(int i = 0; i < (int)yEvents.size(); i++)
    {
        for(int j = 0; j < (int)yEvents[i].size(); j++)
        {
            double key = xEvents[i][j];
            int indexForB = binarySearch(xBSplineValues[i], key);
            int indexForC = binarySearch(xCSplineValues[i], key);
            if(indexForB != -1)
                interpB.push_back( (yEvents[i][j]-yBSplineValues[i][indexForB])/yErrorEvents[i][indexForB] );
            if(indexForC != -1)
                interpC.push_back( (yEvents[i][j]-yCSplineValues[i][indexForC])/yErrorEvents[i][indexForC] );
        }
    }

    int nbinsI = 40;
    int xlowI = -4;
    int xupI = 4;
    TH1D *hInterpB = new TH1D("Interp B","Interpolation; Distance between spline and data normalized by error; Number of Events", nbinsI, xlowI, xupI);
    for(int i=0; i<(int)interpB.size(); i++) hInterpB->Fill(interpB.at(i));
    hInterpB->SetStats(0);


    TH1D *hInterpC = new TH1D("Interp C","Interpolation; Distance between spline and data normalized by error; Number of Events", nbinsI, xlowI, xupI);
    for (int i=0; i<(int)interpC.size(); i++) hInterpC->Fill(interpC.at(i));
    hInterpC->SetLineColor(kRed);
    hInterpC->SetStats(0);

    //Draws______________________________________________________________________________________

    //Interpolation
    TLegend *legInterp = new TLegend(0.9,0.70,0.75,0.85);
    legInterp->SetLineColor(kWhite);
    legInterp->SetFillColor(kWhite);
    legInterp->SetMargin(0.3);
    legInterp->AddEntry(hInterpB,"b-spline","l");
    legInterp->AddEntry(hInterpC,"c-spline","l");
    legInterp->SetTextSize(0.05);

    TCanvas *c1 = new TCanvas("c1", "Interpolation distance");
    c1->cd();
    hInterpB->Draw("");
    hInterpC->Draw("same");
    legInterp->Draw();

    //Time
    TLegend *legTime = new TLegend(0.9,0.70,0.75,0.85);
    legTime->SetLineColor(kWhite);
    legTime->SetFillColor(kWhite);
    legTime->SetMargin(0.3);
    legTime->AddEntry(hTimeB,"b-spline","l");
    legTime->AddEntry(hTimeC,"c-spline","l");
    legTime->SetTextSize(0.05);

    TCanvas *c2 = new TCanvas("c2", "Computation time");
    c2->cd();
    hTimeB->Draw("");
    hTimeC->Draw("same");
    legTime-> Draw();

    //Free the memory____________________________________________________________________________
    gsl_spline_free (spline_GLOB);
    gsl_interp_accel_free (acc_GLOB);
    gsl_bspline_free(bw);
    gsl_vector_free(xControl);
    gsl_vector_free(yControl);
    gsl_vector_free(B);
    gsl_matrix_free(X);
    gsl_vector_free(c);
    gsl_multifit_linear_free(mw);
    gsl_matrix_free(cov);
}
Esempio n. 29
0
void chipHistos(const char *filenames = "/export/data1/dambach/hardware/ntpls/gradeA/*.root")
{

  Init();      // do not forget to load the Utilities.C

  TH1D *gainH = new TH1D("gainH", "RMS(gain)/Mean(gain)", 100, 0., 0.2);
  TH1D *pedH = new TH1D("pedH", "RMS(pedestal)", 100, 0., 100.);
  TH1D *noiseH = new TH1D("noiseH", "RMS(trimmed threshold)", 100, 0., 8.);
  TH1D *tthrH = new TH1D("tthrH", "Mean (trimmed threshold)", 100, 50., 70.);
  
  TH1D *gainDist = new TH1D("gainDist", "gainR/gainM", 100, 0., 10.);
  TH1D *pedDist = new TH1D("pedDist", "pedR", 100, -1000., 1000.);
  
  TChain *c = new TChain("mod");
  c->Add(filenames);
  
  float ped[16][4160], gain[16][4160];
  int defects[16][4160];
  c->SetBranchAddress("ped", ped); 
  c->SetBranchAddress("gain", gain);
  c->SetBranchAddress("defects", defects);
  
  int nb(0), nbytes(0);
  
  for (int i = 0; i < c->GetEntries(); ++i)
    {
      nb = c->GetEntry(i);   nbytes += nb;
      
      
      for(int chipId = 0; chipId < 16; chipId++)
	{
	  gainDist->Reset();
	  pedDist->Reset();
	  
	  int allPix = 4160; 
	  for (int p = 0; p < allPix; p++)
	    {
	      if(defects[chipId][p] == 0)
		{
		  gainDist->Fill(gain[chipId][p]);
		  pedDist->Fill(ped[chipId][p]);	      
		}
	    }
	  double gainRMS = gainDist->GetRMS();
	  double pedRMS = pedDist->GetRMS();
	  double gainMean = gainDist->GetMean();
	  double pedMean = pedDist->GetMean();
	  
	  if (gainMean != 0) gainH->Fill(gainRMS/gainMean);
	  pedH->Fill(pedRMS);
	}
    }
  
  canvas->Clear();
  canvas->Divide(2,2);
  
  canvas->cd(1);
  InitPad("log");
  gainH->GetXaxis()->SetTitle("DAC units");
  gainH->GetYaxis()->SetTitle("# pixels");
  gainH->GetXaxis()->SetTitleSize(0.055);
  gainH->GetYaxis()->SetTitleSize(0.055);
  gainH->Draw();
  
  canvas->cd(2);
  InitPad("log");
  pedH->GetXaxis()->SetTitle("DAC units");
  pedH->GetYaxis()->SetTitle("# pixels");
  pedH->GetXaxis()->SetTitleSize(0.055);
  pedH->GetYaxis()->SetTitleSize(0.055);
  pedH->Draw();

  canvas->cd(3);
  InitPad("log");
  noiseH->GetXaxis()->SetTitle("DAC units");
  noiseH->GetYaxis()->SetTitle("# pixels");
  noiseH->GetXaxis()->SetTitleSize(0.055);
  noiseH->GetYaxis()->SetTitleSize(0.055);
  c->Draw("tthrR>>noiseH");

  canvas->cd(4);
  InitPad("log");
  tthrH->SetMinimum(0.5);
  tthrH->GetXaxis()->SetTitle("DAC units");
  tthrH->GetYaxis()->SetTitle("# pixels");
  tthrH->GetXaxis()->SetTitleSize(0.055);
  tthrH->GetYaxis()->SetTitleSize(0.055);
  c->Draw("tthrM>>tthrH");

}
Esempio n. 30
0
void mcClosure(bool  isFW=1, bool isPrompt=1) { 
  
  TString direction;   
  if (isFW) direction="FW";
  else direction     ="BW";
				    
  TH1::SetDefaultSumw2();

  TFile* f1;
  if ( isPrompt)  f1 = new TFile("/home/samba/songkyo/efficiency/PRMC_eff_rootFile/merged_PRMC_eff_Histos.root"); 
  else f1 = new TFile("/home/samba/songkyo/efficiency/NPMC_eff_rootFile/merged_NPMC_eff_Histos.root");
  
  //read-in tree
  TTree *mytree = (TTree*)f1->Get("myTree");
  
  TFile * fEff;
  if ( isPrompt) fEff = new TFile("EffAna_PRMC_boosted.root");
  else           fEff = new TFile("EffAna_NPMC_boosted.root");

  TH1D* hEff[10];
  hEff[0] = (TH1D*)fEff->Get(Form("h1D_EffDimu_pt_bin_%s",direction.Data()));
  hEff[1] = (TH1D*)fEff->Get(Form("h1D_EffDimu_pt_bin_%s_trig",direction.Data()));
  hEff[2] = (TH1D*)fEff->Get(Form("h1D_EffDimu_pt_bin_%s_mupl",direction.Data()));
  hEff[3] = (TH1D*)fEff->Get(Form("h1D_EffDimu_pt_bin_%s_mumi",direction.Data()));
  hEff[4] = (TH1D*)fEff->Get(Form("h1D_EffDimu_pt_bin_%s_jpsi",direction.Data()));
  hEff[5] = (TH1D*)fEff->Get(Form("h1D_EffDimu_pt_bin_%s_mass",direction.Data()));
  cout << "///////////////////////////////////////////////////////////////////////" << endl;
  cout << " Acceptance is calculated by YONGSUN's code not from Hyunchul's code" << endl;
  cout << "///////////////////////////////////////////////////////////////////////" << endl;
  TH1D* hAcc  = (TH1D*)fEff->Get(Form("h1D_Acc_pt_bin_%s",direction.Data()));
  
  
  for ( int i=0 ; i<=5 ;i++) {
    handsomeTH1(hEff[i],i+1);
  }

  /*
  TFile * fAcc;
  if ( isPrompt) fAcc = new TFile("AccAna_20131219_PromptJpsi_boosted_binCode_1.root");
  else fAcc = new TFile("AccAna_20131219_PromptJpsi_boosted_binCode_1.root");
  
  TH1D* hAcc  = (TH1D*)fAcc->Get(Form("h1D_Acc_pt_bin2_%s_20131219",direction.Data()));
  */
  
  TCanvas* c0 = new TCanvas("c0","",1000,500);
  c0->Divide(2,1);
  c0->cd(1);
  hEff[0]->SetXTitle("p_{T} (GeV)");
  hEff[0]->SetYTitle("Efficiency");
  hEff[0]->SetAxisRange(0,1.1,"Y");
  hEff[0]->Draw();
  for (int i=1; i<=4 ;i++) {
    hEff[i]->Draw("same");
  }
  jumSun(6.5,1,30,1);
  
  c0->cd(2);

  handsomeTH1(hAcc,1);
  hAcc->SetXTitle("p_{T} (GeV)");
  hAcc->SetYTitle("Acceptance");
 
  hAcc->SetAxisRange(0,1.1,"Y");
  hAcc->Draw();
  jumSun(6.5,1,30,1);
  

  TCanvas* c1 = new TCanvas("c1","",500,500);
  c1->cd();

  double ptBin[] = {6.5, 7.5, 8.5, 9.5, 10.5, 11.5, 13.0, 16.0, 20.0, 30.0};
  const int nPtBin = sizeof(ptBin)/sizeof(double) - 1;
  TH1D* hptGen = new TH1D("hptGen",";J/psi p_{T} (GeV)",nPtBin,ptBin);
  TH1D* hptReco = (TH1D*)hptGen->Clone("hptReco");

  // Cuts
  TCut genRapCut, recoRapCut; 
  if (isFW) {
    genRapCut = "(Gen_QQ_4mom[0].Rapidity()>-2.4) && (Gen_QQ_4mom[0].Rapidity()<-.47)";
    recoRapCut = "(Reco_QQ_4mom[0].Rapidity()>-2.4) && (Reco_QQ_4mom[0].Rapidity()<-.47) &&  (Reco_QQ_mupl_4mom[0].Rapidity()>-2.4) && (Reco_QQ_mupl_4mom[0].Rapidity()<-.47) && (Reco_QQ_mumi_4mom[0].Rapidity()>-2.4) && (Reco_QQ_mumi_4mom[0].Rapidity()<-.47) && (Reco_QQ_trig&1)==1"; 
  }
  else {
    genRapCut = "Gen_QQ_4mom[0].Rapidity()>-.47 && Gen_QQ_4mom[0].Rapidity()<1.47";
    recoRapCut = "(Reco_QQ_4mom[0].Rapidity()>-.47) && (Reco_QQ_4mom[0].Rapidity()<1.47) && (Reco_QQ_mupl_4mom[0].Rapidity()>-.47 && Reco_QQ_mupl_4mom[0].Rapidity()<1.47) && (Reco_QQ_mumi_4mom[0].Rapidity()>-.47 && Reco_QQ_mumi_4mom[0].Rapidity()<1.47) && (Reco_QQ_trig&1)==1";
  }
  TCut recoMassCut = "Reco_QQ_4mom[0].M()>2.95 && Reco_QQ_4mom[0].M()<3.25";
  TCut recoAccCutPlus  = ""; //" Reco_QQ_mupl_4mom[0].Eta()>-2.4 && Reco_QQ_mupl_4mom[0].Eta()<1.47 &&   (  ( abs(Reco_QQ_mupl_4mom[0].Eta())>2.2 && abs(Reco_QQ_mupl_4mom[0].Eta())<2.4 && Reco_QQ_mupl_4mom[0].Pt()>0.8 )   || ( abs(Reco_QQ_mupl_4mom[0].Eta())>1.3 && abs(Reco_QQ_mupl_4mom[0].Eta())<=2.2 && Reco_QQ_mupl_4mom[0].P()>2.9 )  || ( abs(Reco_QQ_mupl_4mom[0].Eta())<=1.3 && Reco_QQ_mupl_4mom[0].Pt()>3.3 ) )";
  TCut recoAccCutMinus  = ""; //" Reco_QQ_mumi_4mom[0].Eta()>-2.4 && Reco_QQ_mumi_4mom[0].Eta()<1.47 &&   (  ( abs(Reco_QQ_mumi_4mom[0].Eta())>2.2 && abs(Reco_QQ_mumi_4mom[0].Eta())<2.4 && Reco_QQ_mumi_4mom[0].Pt()>0.8 )   || ( abs(Reco_QQ_mumi_4mom[0].Eta())>1.3 && abs(Reco_QQ_mumi_4mom[0].Eta())<=2.2 && Reco_QQ_mumi_4mom[0].P()>2.9 )  || ( abs(Reco_QQ_mumi_4mom[0].Eta())<=1.3 && Reco_QQ_mumi_4mom[0].Pt()>3.3 ) )";
  TCut recoAccCut = recoAccCutPlus && recoAccCutMinus;
  
  Long64_t nEntry = 100000000;
  mytree->Draw(Form("Gen_QQ_4mom[0].Pt()>>%s",hptGen->GetName()), genRapCut, "",nEntry);
  mytree->Draw(Form("Reco_QQ_4mom[0].Pt()>>%s",hptReco->GetName()), recoRapCut && recoMassCut && recoAccCut, "",nEntry);

  TH1D* hptRecoCorr = (TH1D*)hptReco->Clone("hptRecoCorr");
  hptRecoCorr->Divide(hEff[0]);
  hptRecoCorr->Divide(hAcc);
  

  handsomeTH1(hptGen,1);
  hptGen->SetAxisRange(1,1.5e5,"Y");
  
  hptGen->Draw("hist");
  handsomeTH1(hptReco,2);
  hptReco->SetMarkerStyle(24);
  hptReco->Draw("same");
  handsomeTH1(hptRecoCorr,2);
  hptRecoCorr->Draw("same");
  
  TLegend *l = new TLegend(0.4233871,0.5042373,0.8689516,0.7521186,NULL,"brNDC");
  easyLeg(l,"Yield");
  l->AddEntry(hptGen,"Generated J/#psi","l");
  l->AddEntry(hptReco,"Reco yield","p");
  l->AddEntry(hptRecoCorr,"Reco/(Acc*Eff)","p");
  l->Draw();
}