Beispiel #1
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());
}
Beispiel #2
0
TF1 *fit(TTree *nt,TTree *ntMC,double ptmin,double ptmax, bool ispPb, int count){   
   //cout<<cut.Data()<<endl;
   //static int count=0;
   //count++;
   TCanvas *c= new TCanvas(Form("c%d",count),"",600,600);
   TH1D *h = new TH1D(Form("h%d",count),"",50,5,6);
   TH1D *hMC = new TH1D(Form("hMC%d",count),"",50,5,6);

   TString iNP="7.26667e+00*Gaus(x,5.10472e+00,2.63158e-02)/(sqrt(2*3.14159)*2.63158e-02)+4.99089e+01*Gaus(x,4.96473e+00,9.56645e-02)/(sqrt(2*3.14159)*9.56645e-02)+3.94417e-01*(3.74282e+01*Gaus(x,5.34796e+00,3.11510e-02)+1.14713e+01*Gaus(x,5.42190e+00,1.00544e-01))";
   TF1 *f = new TF1(Form("f%d",count),"[0]*([7]*Gaus(x,[1],[2])/(sqrt(2*3.14159)*[2])+(1-[7])*Gaus(x,[1],[8])/(sqrt(2*3.14159)*[8]))+[3]+[4]*x+[5]*("+iNP+")");
   nt->Project(Form("h%d",count),"mass",Form("%s&&pt>%f&&pt<%f",seldata_2y.Data(),ptmin,ptmax));   
   ntMC->Project(Form("hMC%d",count),"mass",Form("%s&&pt>%f&&pt<%f",seldata_2y.Data(),ptmin,ptmax));   
   clean0(h);

   TH1D *hraw = new TH1D(Form("hraw%d",count),"",50,5,6);
   clean0(hraw);
   hraw = (TH1D*)h->Clone(Form("hraw%d",count));


   h->Draw();
   f->SetParLimits(4,-1000,0);
   f->SetParLimits(2,0.01,0.05);
   f->SetParLimits(8,0.01,0.05);
   f->SetParLimits(7,0,1);
   f->SetParLimits(5,0,1000);

   f->SetParameter(0,setparam0);
   f->SetParameter(1,setparam1);
   f->SetParameter(2,setparam2);
   f->SetParameter(8,setparam3);
   f->FixParameter(1,fixparam1);
   h->GetEntries();

   hMC->Fit(Form("f%d",count),"q","",5,6);
   hMC->Fit(Form("f%d",count),"q","",5,6);
   f->ReleaseParameter(1);
   hMC->Fit(Form("f%d",count),"L q","",5,6);
   hMC->Fit(Form("f%d",count),"L q","",5,6);
   hMC->Fit(Form("f%d",count),"L q","",5,6);
   hMC->Fit(Form("f%d",count),"L m","",5,6);

   f->FixParameter(1,f->GetParameter(1));
   f->FixParameter(2,f->GetParameter(2));
   f->FixParameter(7,f->GetParameter(7));
   f->FixParameter(8,f->GetParameter(8));
   
   h->Fit(Form("f%d",count),"q","",5,6);
   h->Fit(Form("f%d",count),"q","",5,6);
   f->ReleaseParameter(1);
   h->Fit(Form("f%d",count),"L q","",5,6);
   h->Fit(Form("f%d",count),"L q","",5,6);
   h->Fit(Form("f%d",count),"L q","",5,6);
   h->Fit(Form("f%d",count),"L m","",5,6);
   h->SetMarkerSize(0.8);
   h->SetMarkerStyle(20);
   cout <<h->GetEntries()<<endl;

   // function for background shape plotting. take the fit result from f
   TF1 *background = new TF1(Form("background%d",count),"[0]+[1]*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(5,6);
   background->SetLineStyle(2);
   
   // function for signal shape plotting. take the fit result from f
   TF1 *Bkpi = new TF1(Form("fBkpi%d",count),"[0]*("+iNP+")");
   Bkpi->SetParameter(0,f->GetParameter(5));
   Bkpi->SetLineColor(kGreen+1);
   Bkpi->SetFillColor(kGreen+1);
//   Bkpi->SetRange(5.00,5.28);
   Bkpi->SetRange(5.00,6.00);
   Bkpi->SetLineStyle(1);
   Bkpi->SetFillStyle(3004);

   // function for signal shape plotting. take the fit result from f
   TF1 *mass = new TF1(Form("fmass%d",count),"[0]*([3]*Gaus(x,[1],[2])/(sqrt(2*3.14159)*[2])+(1-[3])*Gaus(x,[1],[4])/(sqrt(2*3.14159)*[4]))");
   mass->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(2),f->GetParameter(7),f->GetParameter(8));
   mass->SetParError(0,f->GetParError(0));
   mass->SetParError(1,f->GetParError(1));
   mass->SetParError(2,f->GetParError(2));
   mass->SetParError(7,f->GetParError(7));
   mass->SetParError(8,f->GetParError(8));
   mass->SetLineColor(2);
   mass->SetLineStyle(2);

//   cout <<mass->Integral(0,1.2)<<" "<<mass->IntegralError(0,1.2)<<endl;
   h->SetMarkerStyle(24);
   h->SetStats(0);
   h->Draw("e");
   h->SetXTitle("M_{B} (GeV/c^{2})");
   h->SetYTitle("Entries / (20 MeV/c^{2})");
   h->GetXaxis()->CenterTitle();
   h->GetYaxis()->CenterTitle();
   h->SetTitleOffset(1.5,"Y");
   h->SetAxisRange(0,h->GetMaximum()*1.2,"Y");
   Bkpi->Draw("same");
   background->Draw("same");   
   mass->SetRange(5,6);
   mass->Draw("same");
   mass->SetLineStyle(2);
   mass->SetFillStyle(3004);
   mass->SetFillColor(2);
   f->Draw("same");
   hraw->Draw("same");

   double yield = mass->Integral(5,6)/0.02;
   double yieldErr = mass->Integral(5,6)/0.02*mass->GetParError(0)/mass->GetParameter(0);


   // Draw the legend:)   
   TLegend *leg = myLegend(0.50,0.5,0.86,0.89);
   leg->AddEntry(h,"CMS Preliminary","");
   leg->AddEntry(h,"pPb #sqrt{s_{NN}} = 5.02 TeV","");
   leg->AddEntry(h,Form("%.0f < p_{T}^{B} < %.0f GeV/c",ptmin,ptmax),"");
   leg->AddEntry(h,"Data","pl");
   leg->AddEntry(f,"Fit","l");
   leg->AddEntry(mass,"Signal","f");
   leg->AddEntry(background,"Combinatorial Background","l");
   leg->AddEntry(Bkpi,"Non-prompt J/#psi","f");
   leg->Draw();
   TLegend *leg2 = myLegend(0.44,0.33,0.89,0.50);
   leg2->AddEntry(h,"B meson","");
   leg2->AddEntry(h,Form("M_{B} = %.2f #pm %.2f MeV/c^{2}",mass->GetParameter(1)*1000.,mass->GetParError(1)*1000.),"");
   leg2->AddEntry(h,Form("N_{B} = %.0f #pm %.0f", yield, yieldErr),"");
   leg2->Draw();

   if(ispPb)c->SaveAs(Form("../ResultsBplus/BMass-%d.pdf",count));
   else c->SaveAs(Form("../ResultsBplus_pp/BMass-%d.pdf",count));

   h->Write();
   hMC->Write();
   f->Write();
   background->Write();
   Bkpi->Write();
   mass->Write();
   hraw->Write();

   return mass;
}
Beispiel #3
0
void Zselection() {
  TLatex *tplus = labelLatex(0.20,0.80,"7 TeV Data");
  gROOT->SetStyle("Plain"); 
  gStyle->SetOptStat(0);
  gStyle->SetPalette(1);
  //the correct W x-sec to use is 31314, c.f. 24170, 30380
  double w_scale = 35.0;//(31314.0 / 24170.0) * 3.2;
  double z_scale = w_scale;
  double qcd_scale = 14./1000.0;
  double data_scale = 1.;
  unsigned int rbin = 5;
  unsigned int numPlots = 11;
  bool doPrint = false;

  TString folder = "hltmu15_goodevsel/Zselection";

  TFile *file0 = TFile::Open("results/" + folder + "/RecoRoutines_Z-selection_realdata.root");
  TFile *file1 = TFile::Open("results/" + folder + "/RecoRoutines_Z-selection_WJets_madgraph_June2010.root");
  //TFile *file1 = TFile::Open("results/" + folder + "/RecoRoutines_W-selection_WJets_sherpa.root");
  //TFile *file2 = TFile::Open("results/" + folder + "/RecoRoutines_W-selection_QCD_AllPtBins_7TeV_Pythia.root");
  TFile *file3 = TFile::Open("results/" + folder + "/RecoRoutines_Z-selection_ZJets_madgraph_June2010.root");
  //TFile *file4 = TFile::Open("results/MuPt10/RecoRoutines_W-selection_TTbarJets_tauola_madgraph_June2010.root");

  //dynamic array size not allowed in CINT hehe
  TCanvas *canvas [11] = {makeCanvas("reco_wpt_plus"), makeCanvas("reco_wpt_minus"), makeCanvas("reco_wpt"), makeCanvas("muon_pt_plus"), makeCanvas("muon_pt_minus"), makeCanvas("muon_pt"), makeCanvas("pf_mt_plus"), makeCanvas("pf_mt_minus"), makeCanvas("pf_mt"), makeCanvas("lpvar_plus"), makeCanvas("lpvar_minus")};
  TLegend *legend [11] = {makeLegend(), makeLegend(), makeLegend(), makeLegend(), makeLegend(), makeLegend(), makeLegend(), makeLegend(), makeLegend(), makeLegend(), makeLegend()};

  TString plotnames [11] = {"RECO_PolPlots_50toinf/RECO_pfMHTPlus",
                            "RECO_PolPlots_50toinf/RECO_pfMHTMinus",
                            "RECO_PolPlots_50toinf/RECO_pfMHT", 
                            "RECO_PolPlots_50toinf/RECO_MuonPtPlus", 
                            "RECO_PolPlots_50toinf/RECO_MuonPtMinus", 
                            "RECO_PolPlots_50toinf/RECO_MuonPt", 
                            "RECO_PolPlots_50toinf/RECO_pfMTPlus",
                            "RECO_PolPlots_50toinf/RECO_pfMTMinus",
                            "RECO_PolPlots_50toinf/RECO_pfMT", 
                            "RECO_PolPlots_50toinf/RECO_ICVarPlus", 
                            "RECO_PolPlots_50toinf/RECO_ICVarMinus"};
  TString plotlabels [11] = {"RECO P_{T}(W+) [GeV]", "RECO P_{T}(W-) [GeV]", "RECO P_{T}(W) [GeV]", "P_{T}(Muon+) [GeV]", "P_{T}(Muon-) [GeV]", "P_{T}(Muon) [GeV]", "M_{T}+ [GeV]", "M_{T}- [GeV]", "M_{T} [GeV]", "LP(+)", "LP(-)"};
  int rbinextra [11] = {2,2,2,4,4,4,2,2,2,4,4};
  double xmin [11] = {50., 50., 50., 0., 0., 0., 30., 30., 30., -0.5, -0.5};
  double xmax [11] = {120., 120., 120., 140., 140., 140., 90., 90., 90., 1.5, 1.5};
  double ymax [11] = {170., 150., 300., 150., 100., 250., 160., 130., 260., 150., 80.};
  int skip [11] = {0,0,0,0,0,0,0,0,0,0,0};


  for(unsigned int i=0; i<numPlots; i++) {
    if(skip[i] == 0) {
    TH1D * data = (TH1D*)file0->Get(plotnames[i]);
    TH1D * w = (TH1D*)file1->Get(plotnames[i]);
    //TH1D * qcd = (TH1D*)file2->Get(plotnames[i]);
    TH1D * z = (TH1D*)file3->Get(plotnames[i]);
    //TH1D * tt = (TH1D*)file4->Get(plotnames[i]);

    w->Rebin(rbin*rbinextra[i]);
    //qcd->Rebin(rbin*rbinextra[i]);
    z->Rebin(rbin*rbinextra[i]);
    //tt->Rebin(rbin);
    data->Scale(data_scale);
    data->Rebin(rbin*rbinextra[i]);

    w->Scale(w_scale);
    z->Scale(z_scale);
    //tt->Scale(lumi_scale);
    //qcd->Scale(qcd_scale);

    TH1D * mc = (TH1D*)w->Clone();
    //mc->Add(w);
    mc->Add(z);
    //mc->Add(tt);
    mc->SetLineWidth(3);
    //mc->SetLineStyle(9);
    mc->SetLineColor(kGray);
    //qcd->SetLineColor(kGreen);
    //qcd->SetLineWidth(2);
    //qcd->GetXaxis()->SetRangeUser(xmin[i],xmax[i]);
    //qcd->GetXaxis()->SetTitle(plotlabels[i]);
    //qcd->GetXaxis()->SetTitleSize(0.05);
    //qcd->GetYaxis()->SetRangeUser(0.1,ymax[i]);
    //qcd->GetYaxis()->SetTitle("Events / 2.8 pb^{-1}");
    //qcd->GetYaxis()->SetTitleSize(0.05);
    //qcd->GetYaxis()->SetTitleOffset(1.36);
    canvas[i]->cd(1);//->SetLogy();
    //qcd->DrawCopy("h");
    w->SetLineColor(kBlue);
    w->SetLineWidth(2);
    w->DrawCopy("h");
    z->SetLineColor(kRed);
    z->SetLineWidth(2);
    z->DrawCopy("sameh");
    //tt->SetLineColor(kGold);
    //tt->SetLineWidth(2);
    //tt->DrawCopy("sameh");

    mc->DrawCopy("sameh");
    data->SetMarkerStyle(20);
    data->DrawCopy("samep");
    //tplus->DrawClone("same");
    legend[i]->AddEntry(data, "7TeV Data", "p");
    legend[i]->AddEntry(mc, "All MC", "l");
    legend[i]->AddEntry(w, "W+Jets", "l");
    legend[i]->AddEntry(z, "Z+Jets", "l");
    //legend[i]->AddEntry(qcd, "QCD", "l");
    legend[i]->DrawClone();

    data->Divide(mc);
    canvas[i]->cd(2);
    data->GetXaxis()->SetRangeUser(xmin[i], xmax[i]);
    data->GetXaxis()->SetTitleSize(0.05);
    data->GetXaxis()->SetTitle(plotlabels[i]);
    data->GetYaxis()->SetTitle("Data / MC");
    data->GetYaxis()->SetTitleSize(0.05);
    data->GetYaxis()->SetTitleOffset(1.36);
    data->DrawCopy();

    if(doPrint) canvas[i]->Print(".png");
    }
  }
  //file2->Close();
  file1->Close();
  file0->Close();
  return;

}
Beispiel #4
0
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// drawFigures4and5
//
// Zpt
// LeadingJetPt
// Njets
//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void drawFigures4and5(TString var = "Zpt") 
{
  gSystem->mkdir("pdf", kTRUE);
  gSystem->mkdir("png", kTRUE);

  gInterpreter->ExecuteMacro("WZPaperStyle.C");

  Bool_t drawMcfm = (var.EqualTo("Zpt")) ? true : false;

  TString variable;
  TString xtitle;
  TString ytitle;

  if (var.EqualTo("Zpt"))          variable = "Z";
  if (var.EqualTo("LeadingJetPt")) variable = "leading jet";
  if (var.EqualTo("Njets"))        variable = "N_{jets}";

  if (var.EqualTo("Njets"))
    {
      xtitle = variable;
      ytitle = "d#sigma(WZ#rightarrow3l#nu)/d" + variable + " (pb)";
    }
  else
    {
      xtitle = "p_{T}^{" + variable + "} (GeV)";
      ytitle = "d#sigma(WZ#rightarrow3l#nu)/dp_{T}^{" + variable + "} (pb/GeV)";
    }

  TFile* file = new TFile("rootfiles/all_unfolding_" + var + ".root", "read");

  TH1D* xsValue          = (TH1D*)file->Get("hComb_diff");
  TH1D* xsValue_Madgraph = (TH1D*)file->Get("hGenXs" + var + "_1");
  TH1D* xsValue_MCnlo;

  if (drawMcfm) xsValue_MCnlo = (TH1D*)file->Get("mcfm_tot");


  // Data cosmetics
  //----------------------------------------------------------------------------
  xsValue->SetFillColor  (     kWhite);
  xsValue->SetFillStyle  (       1001);
  xsValue->SetLineColor  (     kBlack);
  xsValue->SetLineWidth  (          1);
  xsValue->SetMarkerColor(     kBlack);
  xsValue->SetMarkerSize (     _msize);
  xsValue->SetMarkerStyle(kFullCircle);


  // Madgraph cosmetics
  //----------------------------------------------------------------------------
  xsValue_Madgraph->SetFillColor  (    kOrange);
  xsValue_Madgraph->SetFillStyle  (       1001);
  xsValue_Madgraph->SetLineColor  (  kOrange+7);
  xsValue_Madgraph->SetLineWidth  (          1);
  xsValue_Madgraph->SetMarkerColor(  kOrange+7);
  xsValue_Madgraph->SetMarkerSize (     _msize);
  xsValue_Madgraph->SetMarkerStyle(kFullSquare);


  // MCNLO cosmetics
  //----------------------------------------------------------------------------
  if (drawMcfm)
    {
      xsValue_MCnlo->SetFillColor  (   kAzure-9);
      xsValue_MCnlo->SetFillStyle  (       1001);
      xsValue_MCnlo->SetLineColor  (     kAzure);
      xsValue_MCnlo->SetLineWidth  (          1);
      xsValue_MCnlo->SetMarkerColor(     kAzure);
      xsValue_MCnlo->SetMarkerSize (     _msize);
      xsValue_MCnlo->SetMarkerStyle(kOpenCircle);
    }


  // Set the canvas and pads
  //----------------------------------------------------------------------------
  TCanvas* canvas = new TCanvas(var, var);

  TPad* pad1;
  TPad* pad2;
  TPad* pad3;

  if (drawMcfm)
    {
      pad1 = new TPad("pad1" + var, "pad1" + var, 0, 0.49, 1, 1.000);
      pad2 = new TPad("pad2" + var, "pad2" + var, 0, 0.33, 1, 0.492);
      pad3 = new TPad("pad3" + var, "pad3" + var, 0, 0.00, 1, 0.332);
  
      pad1->SetTopMargin(0.09);
      pad2->SetTopMargin(0);
      pad3->SetTopMargin(0);

      pad1->SetBottomMargin(0);
      pad2->SetBottomMargin(0);
      pad3->SetBottomMargin(0.45);

      pad1->SetLeftMargin(0.16);
      pad2->SetLeftMargin(0.16);
      pad3->SetLeftMargin(0.16);
      
      pad1->SetRightMargin(0.06);
      pad2->SetRightMargin(0.06);
      pad3->SetRightMargin(0.06);
    }
  else
    {
      pad1 = new TPad("pad1" + var, "pad1" + var, 0, 0.33, 1, 1.000);
      pad2 = new TPad("pad2" + var, "pad2" + var, 0, 0.00, 1, 0.332);
  
      pad1->SetTopMargin(0.09);
      pad2->SetTopMargin(0);

      pad1->SetBottomMargin(0);
      pad2->SetBottomMargin(0.45);

      pad1->SetLeftMargin(0.16);
      pad2->SetLeftMargin(0.16);

      pad1->SetRightMargin(0.06);
      pad2->SetRightMargin(0.06);
    }


  // Draw pad1
  //----------------------------------------------------------------------------
  pad1->Draw();
  pad1->cd();
  pad1->SetLogy();

  AxisFonts(xsValue->GetXaxis(), xtitle);
  AxisFonts(xsValue->GetYaxis(), ytitle);
  
  xsValue->SetTitle("");

  xsValue->Draw("pe");

  xsValue_Madgraph->Draw("p,same");

  if (drawMcfm) xsValue_MCnlo->Draw("p,same");

  xsValue->Draw("pe,same");

  if (var.EqualTo("Zpt"))          xsValue->SetMinimum(1.1e-4);
  if (var.EqualTo("LeadingJetPt")) xsValue->SetMinimum(5e-4);
  if (var.EqualTo("Njets"))        xsValue->SetMinimum(2e-2);

  DrawLatex(_cmsTextFont,   0.173, 0.935, 0.065, 11, "CMS");
  DrawLatex(_lumiTextFont,  0.940, 0.935, 0.050, 31, "19.6 fb^{-1} (8 TeV)");


  // Legend
  //----------------------------------------------------------------------------
  if (drawMcfm)
    {
      DrawLegend(0.72, 0.80, xsValue,          " Data",     "lp");
      DrawLegend(0.72, 0.73, xsValue_Madgraph, " MadGraph", "flp");
      DrawLegend(0.72, 0.66, xsValue_MCnlo,    " MCFM",     "flp");
    }
  else
    {
      DrawLegend(0.68, 0.81, xsValue,          " Data",     "lp");
      DrawLegend(0.68, 0.74, xsValue_Madgraph, " MadGraph", "flp");
    }


  // Prepare the ratios
  //----------------------------------------------------------------------------
  TH1D* ratio_mad  = (TH1D*)xsValue_Madgraph->Clone("ratio_mad");
  TH1D* hratio_mad = (TH1D*)xsValue_Madgraph->Clone("hratio_mad");

  TH1D* ratio_mcnlo;
  TH1D* hratio_mcnlo;

  if (drawMcfm)
    {
      ratio_mcnlo  = (TH1D*)xsValue_MCnlo->Clone("ratio_mcnlo");
      hratio_mcnlo = (TH1D*)xsValue_MCnlo->Clone("hratio_mcnlo");
    }


  // Set the bin content
  //----------------------------------------------------------------------------
  for (UInt_t ibin=1; ibin<=ratio_mad->GetNbinsX(); ibin++) {
   
    Double_t madValue   = xsValue_Madgraph->GetBinContent(ibin);
    Double_t dataValue  = xsValue->GetBinContent(ibin);
    Double_t dataError  = xsValue->GetBinError(ibin);
   
    Double_t ratioValue_mad = (madValue > 0) ? madValue / dataValue : 0.0;
    Double_t ratioError_mad = madValue / pow(dataValue,2)*dataError;
   
    ratio_mad->SetBinContent(ibin, ratioValue_mad);
    ratio_mad->SetBinError  (ibin, 1e-9);

    hratio_mad->SetBinContent(ibin, ratioValue_mad);
    hratio_mad->SetBinError  (ibin, ratioError_mad);
   

    if (drawMcfm)
      {
	Double_t mcnloValue       = xsValue_MCnlo->GetBinContent(ibin);
	Double_t ratioValue_mcnlo = (mcnloValue > 0) ? mcnloValue / dataValue : 0.0;
	Double_t ratioError_mcnlo = mcnloValue / pow(dataValue,2)*dataError;

	ratio_mcnlo->SetBinContent(ibin, ratioValue_mcnlo);
	ratio_mcnlo->SetBinError  (ibin, 1e-9);

	hratio_mcnlo->SetBinContent(ibin, ratioValue_mcnlo);
	hratio_mcnlo->SetBinError  (ibin, ratioError_mcnlo);
      }
  }


  // Draw pad2
  //----------------------------------------------------------------------------
  AxisFontsRatio(ratio_mad->GetYaxis(), "y", "#frac{Theory}{Data}");
  AxisFontsRatio(ratio_mad->GetXaxis(), "x", xtitle);

  canvas->cd();
  pad2->Draw();
  pad2->cd();

  ratio_mad->SetTitle("");
  
  ratio_mad ->Draw("ep");
  hratio_mad->Draw("e2,same");
  ratio_mad ->Draw("ep,same");

  TLine* line2 = new TLine(ratio_mad->GetXaxis()->GetXmin(), 1.0, ratio_mad->GetXaxis()->GetXmax(), 1.0);
  line2->SetLineStyle(3);
  line2->Draw("same");

  ratio_mad->GetYaxis()->SetRangeUser(0.01, 2.3);  

  if (drawMcfm) DrawLatex(43, 0.20, 0.785, 15.0, 11, "MadGraph+Pythia normalized to #sigma_{NLO}");
  else          DrawLatex(43, 0.19, 0.845, 15.0, 11, "MadGraph+Pythia normalized to #sigma_{NLO}");


  // Draw pad3
  //----------------------------------------------------------------------------
  if (drawMcfm)
    {
      AxisFontsRatio(ratio_mcnlo->GetYaxis(), "y", "#frac{Theory}{Data}");
      AxisFontsRatio(ratio_mcnlo->GetXaxis(), "x", xtitle);

      canvas->cd();
      pad3->Draw();
      pad3->cd();
  
      ratio_mcnlo->SetTitle("");

      ratio_mcnlo ->Draw("ep");
      hratio_mcnlo->Draw("e2,same");
      ratio_mcnlo ->Draw("ep,same");

      TLine* line3 = new TLine(ratio_mcnlo->GetXaxis()->GetXmin(), 1.0, ratio_mcnlo->GetXaxis()->GetXmax(), 1.0);
      line3->SetLineStyle(3);
      line3->Draw("same");

      ratio_mcnlo->GetYaxis()->SetRangeUser(0.1, 2.3);  

      pad3->Modified();

      DrawLatex(43, 0.2, 0.885, 15.0, 11, "MCFM");
    }


  // Save
  //----------------------------------------------------------------------------
  pad1->cd();
  pad1->RedrawAxis();
  pad1->GetFrame()->DrawClone();
  
  pad2->cd();
  pad2->RedrawAxis();
  pad2->GetFrame()->DrawClone();

  if (drawMcfm)
    {
      pad3->cd();
      pad3->RedrawAxis();
      pad3->GetFrame()->DrawClone();
    }

  canvas->cd();
  canvas->Update();

  canvas->SaveAs("pdf/unfolded_" + var + ".pdf");
  canvas->SaveAs("png/unfolded_" + var + ".png");
}
void compareTrkCorrPt_pp(
                           TString outdir="fig"
)
{
   TH1::SetDefaultSumw2();
   gSystem->mkdir(outdir,kTRUE);
   float xmin=1,xmax=179.9;
   TString title="pp";
   TString reftitle="PbPb";

    const bool SaveFile=kTRUE ;
   /////////////////////////////////////////////////////////////////////////////////////
   // Load Histograms
   /////////////////////////////////////////////////////////////////////////////////////
 //  HiForest * cpp = new HiForest("/net/hisrv0001/home/zhukova/scratch/HIHighPt/forest/pthat200/mergedFile.root","forest",1);
   HiForest * cpp = new HiForest("/mnt/hadoop/cms/store/user/dgulhan/ppHiIterativeTrack/P01/prod24/Signal_Pythia_pt80/HiForest_v84_merged01/pt80_JEC_ppHiIterativeTrack_P01_prod24_v84_merged_forest_0.root","forest",1);
   cpp->doTrackCorrections = true;
   cpp->doTrackingSeparateLeadingSubleading = false;
   cpp->InitTree();   
   TrackingCorrections * trkCorr = cpp->trackCorrections[0];

   HiForest * cref = new HiForest("/net/hidsk0001/d00/scratch/yjlee/merge/v27/pthat200/Dijet200_HydjetDrum_v28_mergedV1.root","forestref",0);
   cref->doTrackCorrections = true;
   cref->doTrackingSeparateLeadingSubleading = false;
   cref->InitTree();
   TrackingCorrections * trkCorrRef = cref->trackCorrections[0];


   cout << endl << "========= plot =========" << endl;
   Int_t etaPM=5.; // 7+2,-3 for |eta|<1.2, 7+5,-6 for full eta
   Float_t jetPtMin=0;
   Float_t jetPtMax=500;
   Int_t jetBegBin = trkCorr->jetBin_->FindBin(jetPtMin);
 //  Int_t jetEndBin = trkCorr->numJEtBins_;
   Int_t jetEndBin = trkCorr->jetBin_->FindBin(jetPtMax);;
   cout << Form("jet pt %.0f bin: ",jetPtMin) << jetBegBin << " to " << jetEndBin << endl;
   cout << "========================" << endl;

    string infpath=trkCorr->sample_[0]->GetName();
    TString src0=infpath.substr(infpath.find_last_of('/')+1);
    TString src =src0(src0.First("Trk")+12,13);
    cout <<" src =" <<src <<endl ; 
 //   src.ReplaceAll(".root","");
    TString tag = src+"_"+trkCorr->trkCorrModule_+Form("_vs_Pt_%s_%s_jet%.0f_%.0f_ieta%d_wts%d",title.Data(),reftitle.Data(),jetPtMin,jetPtMax, etaPM,trkCorr->weightSamples_);

 //  TString tag = trkCorr->trkCorrModule_+Form("_vs_Pt_%s_%s_jet%.0f_ieta%d_wts%d",title.Data(),reftitle.Data(),jetPtMin,etaPM,trkCorr->weightSamples_);
   
   // Get Eff/fake histograms
   int numCentBin=trkCorr->numCentBins_;
   int numCentBinRef=trkCorrRef->numCentBins_;
    cout <<"ppncen=" << numCentBin <<"  ncen=" << numCentBinRef <<endl ;
	TH1D * vhCorrPtRef[2][5], *vhCorrPt[2][5];
	Int_t colors[10] = {kBlack,kRed,kYellow+2,kGreen+2,kBlue};
   Int_t styles[2] = {kFullCircle,kOpenCircle};

   int icent=0;
 //  int icentRef=numCentBinRef-1;

	for (Int_t lv=0; lv<2; ++lv) {
		for (Int_t c=0; c<numCentBin; ++c) {
			vhCorrPt[lv][c] = (TH1D*) trkCorr->InspectCorr(lv,c,c,jetBegBin,jetEndBin,2,7-etaPM-1,7+etaPM);
			handsomeTH1(vhCorrPt[lv][c],kBlue,1,kOpenCircle);
         vhCorrPt[lv][icent]->SetAxisRange(xmin,xmax,"X");
         vhCorrPt[lv][icent]->SetAxisRange(0,1,"Y");
		}
		for (Int_t c=0; c<numCentBinRef; ++c) {
			vhCorrPtRef[lv][c] = (TH1D*) trkCorrRef->InspectCorr(lv,c,c,jetBegBin,jetEndBin,2,7-etaPM-1,7+etaPM);
			handsomeTH1(vhCorrPtRef[lv][c],colors[c]);
         vhCorrPtRef[lv][icent]->SetAxisRange(xmin,xmax,"X");
         vhCorrPtRef[lv][icent]->SetAxisRange(0,1,"Y");
		}
	}
   
	TCanvas * cEff = new TCanvas("cEff","cEff",500,500);
   cEff->SetLogx();
   vhCorrPt[0][icent]->SetTitle(";Track p_{T} (GeV/c);A #times #epsilon");
   vhCorrPt[0][icent]->SetTitleOffset(1.2);
   vhCorrPt[0][icent]->SetTitleSize(0.055);
	vhCorrPt[0][icent]->Draw("E");
	vhCorrPt[1][icent]->Draw("sameE");
	vhCorrPtRef[0][0]->Draw("sameE");
	vhCorrPtRef[1][0]->Draw("sameE");
                for (Int_t c=0; c<numCentBinRef; ++c) {
	vhCorrPtRef[0][c]->Draw("sameE");
	vhCorrPtRef[1][c]->Draw("sameE");
}
   TLegend *leg0 = new TLegend(0.16,0.84,0.46,0.92);
   leg0->SetFillStyle(0);
   leg0->SetBorderSize(0);
   leg0->SetTextSize(0.04);
   leg0->AddEntry(vhCorrPt[0][0],"PYTHIA+HYDJET","");
   if (etaPM==5)   leg0->AddEntry(vhCorrPt[0][0],Form("Track |#eta|<2.4"),"");
   if (etaPM==2) leg0->AddEntry(vhCorrPt[0][0],Form("Track |#eta|<1.2"),"");
	leg0->Draw();
   TLine * l = new TLine(xmin,1,xmax,1);
   l->SetLineStyle(2);
   l->Draw();
	
   TLegend *leg = new TLegend(0.34,0.32,0.60,0.48);
   leg->SetFillStyle(0);
   leg->SetBorderSize(0);
   leg->SetTextSize(0.035);
   leg->AddEntry(vhCorrPt[0][icent],title,"p");
    if (numCentBinRef==2) {
        leg->AddEntry(vhCorrPtRef[0][0],reftitle+ "0-30%","p");
        leg->AddEntry(vhCorrPtRef[0][1],reftitle+ "30-100%","p");
    } else {
        leg->AddEntry(vhCorrPtRef[0][0],reftitle+ "0-10%","p");
        leg->AddEntry(vhCorrPtRef[0][1],reftitle+ "10-30%","p");
        leg->AddEntry(vhCorrPtRef[0][2],reftitle+ "30-50%","p");
        leg->AddEntry(vhCorrPtRef[0][3],reftitle+ "50-100%","p");
    }
   leg->Draw();
   
	drawText("CMS Simulation",0.64,0.89);
	drawText("Fake Rate",0.69,0.26);
   
   cEff->Print(outdir+"/"+tag+".gif");
   cEff->Print(outdir+"/"+tag+".pdf");

	TCanvas * cJet = new TCanvas("cJet","cJet",500,500);
	cJet->SetLogy();

	trkCorr->vhPtHat[1][icent]->Draw("E");
        
       for (Int_t c=0; c<numCentBinRef; ++c) {
	trkCorrRef->vhPtHat[1][c]->SetMarkerColor(kRed+c);
	trkCorrRef->vhPtHat[1][c]->SetMarkerStyle(kOpenCircle+c);
	trkCorrRef->vhPtHat[1][c]->Draw("same E");
        }

	TCanvas * cCent = new TCanvas("cCent","cCent",500,500);
   TH1D * hCent = (TH1D*)trkCorr->sample_[0]->Get("hCent");
   TH1D * hCentRef = (TH1D*)trkCorrRef->sample_[0]->Get("hCent");
	hCentRef->SetMarkerStyle(kOpenCircle);
	hCentRef->Scale(1./hCentRef->GetEntries());
	hCent->Scale(1./hCent->GetEntries());
	hCent->Draw("p");
	hCentRef->Draw("same p");

    if(SaveFile){
        TFile * outf = new TFile(Form("%s/%sTrkEffFake.root", outdir.Data(),tag.Data()), "CREATE");
        for (Int_t lv=0; lv<2; ++lv) {
        vhCorrPt[lv][icent]->Write();
            for (Int_t c=numCentBinRef-1; c>=0; --c) {
                vhCorrPtRef[lv][c]->Write();
            }
        }
        outf->Close();
    }
}
void PtSpectraCombination_StagedNormalization_EtaCM_M08_M13_NoOLDAlignmentRuns()
{
   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 = new TFile("CombineSpectra_minbias_EtaCM_M08_M13_NoOLDAlignmentRuns.root");
   TFile *f_FullTrack_12 = new TFile("CombineSpectra_FullTrackTrigger_Track12_EtaCM_M08_M13_NoOLDAlignmentRuns.root");
   TFile *f_FullTrack_20 = new TFile("CombineSpectra_FullTrackTrigger_Track20_EtaCM_M08_M13_NoOLDAlignmentRuns.root");
   TFile *f_FullTrack_30 = new TFile("CombineSpectra_FullTrackTrigger_Track30_EtaCM_M08_M13_NoOLDAlignmentRuns.root");
   TFile *f_out = new TFile("PtSpectraCombination_StagedNormalization_EtaCM_M08_M13_NoOLDAlignmentRuns_TrackTrigger.root","recreate");

   //Get spectra
   TH1D* hPartPt_minbias_corrected = (TH1D*)f_minbias->Get("hPartPt_minbias_trkCorr_trigCorr");
   TH1D* hPartPt_0_14_minbias_corrected = (TH1D*)f_minbias->Get("hPartPt_0_14_minbias_trkCorr_trigCorr");
   TH1D* hPartPt_14_22_FullTrack12_corrected = (TH1D*)f_FullTrack_12->Get("hPartPt_FullTrack12_14_22_trkCorr_trigCorr");
   TH1D* hPartPt_22_32_FullTrack20_corrected = (TH1D*)f_FullTrack_20->Get("hPartPt_FullTrack20_22_32_trkCorr_trigCorr");
   TH1D* hPartPt_32_X_FullTrack30_corrected = (TH1D*)f_FullTrack_30->Get("hPartPt_FullTrack30_SpectComb_trkCorr_trigCorr");

   hPartPt_0_14_minbias_corrected->SetBinContent(hPartPt_0_14_minbias_corrected->FindBin(103.24),0);//Remove muon event
   hPartPt_0_14_minbias_corrected->SetBinError(hPartPt_0_14_minbias_corrected->FindBin(103.24),0);//Remove muon event
   hPartPt_minbias_corrected->SetBinContent(hPartPt_minbias_corrected->FindBin(103.24),0);//Remove muon event
   hPartPt_minbias_corrected->SetBinError(hPartPt_minbias_corrected->FindBin(103.24),0);//Remove muon event

   //Get number of events
   TH1D* hNumEv_minbias = (TH1D*)f_minbias->Get("hNumEv_minbias_trigCorr");
   TH1D* hNumEv_0_14_minbias = (TH1D*)f_minbias->Get("hNumEv_0_14_minbias_trigCorr");
   TH1D* hNumEv_14_22_minbias = (TH1D*)f_minbias->Get("hNumEv_14_22_minbias_trigCorr");
   TH1D* hNumEv_14_22_FullTrack12 = (TH1D*)f_FullTrack_12->Get("hNumEv_FullTrack12_14_22_trigCorr");
   TH1D* hNumEv_22_32_FullTrack12 = (TH1D*)f_FullTrack_12->Get("hNumEv_FullTrack12_22_32_trigCorr");
   TH1D* hNumEv_22_32_FullTrack20 = (TH1D*)f_FullTrack_20->Get("hNumEv_FullTrack20_22_32_trigCorr");
   TH1D* hNumEv_32_X_FullTrack20 = (TH1D*)f_FullTrack_20->Get("hNumEv_FullTrack20_32_X_trigCorr");
   TH1D* hNumEv_32_X_FullTrack30 = (TH1D*)f_FullTrack_30->Get("hNumEv_FullTrack30_32_X_trigCorr");

   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;

   //Prepare the individual normalizations
   float norm_0_14_minbias = numev_minbias;
   float norm_14_22_FullTrack12 = numev_14_22_FullTrack12*numev_minbias/numev_14_22_minbias;
//   float norm_14_22_FullTrack12 = numev_14_22_FullTrack12*11165.040;
   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_M08_M13_NoOLDAlignmentRuns_c1.gif");
      c1->SaveAs("Figs/PtSpectraCombination_StagedNormalization_EtaCM_M08_M13_NoOLDAlignmentRuns_c1.eps");
      c1->SaveAs("Figs/PtSpectraCombination_StagedNormalization_EtaCM_M08_M13_NoOLDAlignmentRuns_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_M08_M13_NoOLDAlignmentRuns_c2.gif");
      c2->SaveAs("Figs/PtSpectraCombination_StagedNormalization_EtaCM_M08_M13_NoOLDAlignmentRuns_c2.eps");
      c2->SaveAs("Figs/PtSpectraCombination_StagedNormalization_EtaCM_M08_M13_NoOLDAlignmentRuns_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();

}
TH1D* getYield(TTree* nt, TTree* ntMC, TString triggerpass, TString triggername, TString prescale, TString variable, TString varname, TString varlatex, Int_t BIN_NUM, Double_t BIN_MIN, Double_t BIN_MAX, TString addcut="")
{
  TH1D* hDistrib = new TH1D(Form("h%s_Distrib_%s",triggername.Data(),varname.Data()),"",BIN_NUM,BIN_MIN,BIN_MAX);
  for(float ivar=0;ivar<BIN_NUM;ivar++)
  {
    TCanvas* c = new TCanvas(Form("c%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"",500,500);
    TH1D* h = new TH1D(Form("h%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),";D^{0} mass (GeV/c^{2});Candidates",60,1.7,2.0);
    TH1D* hMC = new TH1D(Form("hMC%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"",60,1.75,1.95);
    TH1D* hSW = new TH1D(Form("hSW%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"",60,1.75,1.95);
    Float_t varmin = BIN_MIN+ivar*((BIN_MAX-BIN_MIN)/BIN_NUM);
    Float_t varmax = BIN_MIN+(ivar+1)*((BIN_MAX-BIN_MIN)/BIN_NUM);
    nt->Project(Form("h%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),Form("Dmass%s",prescale.Data()),Form("%s%s&&(%s>%f&&%s<%f)%s",prefilter.Data(),addcut.Data(),variable.Data(),varmin,variable.Data(),varmax,triggerpass.Data()));
    ntMC->Project(Form("hMC%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"Dmass",Form("%s%s&&(%s>%f&&%s<%f)%s",prefilterMC.Data(),addcut.Data(),variable.Data(),varmin,variable.Data(),varmax,"&&1"));
    ntMC->Project(Form("hSW%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"Dmass",Form("%s%s&&(%s>%f&&%s<%f)%s",prefilterSW.Data(),addcut.Data(),variable.Data(),varmin,variable.Data(),varmax,"&&1"));
    h->SetMaximum(h->GetMaximum()*1.20);
    h->Draw();

    TF1* f = new TF1(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"[0]*([7]*([9]*Gaus(x,[1],[2]*(1+[11]))/(sqrt(2*3.14159)*[2]*(1+[11]))+(1-[9])*Gaus(x,[1],[10]*(1+[11]))/(sqrt(2*3.14159)*[10]*(1+[11])))+(1-[7])*Gaus(x,[1],[8]*(1+[11]))/(sqrt(2*3.14159)*[8]*(1+[11])))+[3]+[4]*x+[5]*x*x+[6]*x*x*x", 1.7, 2.0);
    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);
    f->FixParameter(11,0);
    h->GetEntries();

    hMC->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"q","",1.7,2.0);
    hMC->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"q","",1.7,2.0);
    f->ReleaseParameter(1);
    hMC->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"L q","",1.7,2.0);
    hMC->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"L q","",1.7,2.0);
    hMC->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"L m","",1.7,2.0);

    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);

    hSW->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"L q","",1.7,2.0);
    hSW->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"L q","",1.7,2.0);
    hSW->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"L q","",1.7,2.0);
    hSW->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"L m","",1.7,2.0);

    f->FixParameter(7,hMC->Integral(0,1000)/(hSW->Integral(0,1000)+hMC->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%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"q","",1.7,2.0);
    h->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"q","",1.7,2.0);
    f->ReleaseParameter(1);
    f->SetParLimits(1,1.86,1.87);
    f->ReleaseParameter(11);
    f->SetParLimits(11,-1.,1.);
    h->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"L q","",1.7,2.0);
    h->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"L q","",1.7,2.0);
    h->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"L q","",1.7,2.0);
    h->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"L m","",1.7,2.0);
    h->SetMarkerSize(0.8);
    h->SetMarkerStyle(20);

    TF1* background = new TF1(Form("background%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"[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(1.7,2.0);
    background->SetLineStyle(2);

    TF1* mass = new TF1(Form("fmass%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"[0]*([3]*([4]*Gaus(x,[1],[2]*(1+[6]))/(sqrt(2*3.14159)*[2]*(1+[6]))+(1-[4])*Gaus(x,[1],[5]*(1+[6]))/(sqrt(2*3.14159)*[5]*(1+[6]))))");
    mass->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(2),f->GetParameter(7),f->GetParameter(9),f->GetParameter(10),f->GetParameter(11));
    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%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"[0]*(1-[2])*Gaus(x,[1],[3]*(1+[4]))/(sqrt(2*3.14159)*[3]*(1+[4]))");
    massSwap->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(7),f->GetParameter(8),f->GetParameter(11));
    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(1.7,2.0);	
    mass->Draw("same");
    massSwap->SetRange(1.7,2.0);
    massSwap->Draw("same");
    f->Draw("same");

    Double_t yield = mass->Integral(1.7,2.0)/0.005;
    Double_t yieldErr = (mass->Integral(1.7,2.0)/0.005)*(mass->GetParError(0)/mass->GetParameter(0));
    std::cout<<"YIELD="<<yield<<std::endl;

    // Draw the legend:)   
    TLegend* leg = myLegend(0.20,0.60,0.53,0.94);
    leg->SetFillColor(0);
    leg->SetBorderSize(0);
    leg->AddEntry((TObject*)0,"CMS Preliminary","");
    if(isPbPb) leg->AddEntry((TObject*)0,"PbPb #sqrt{s_{NN}}= 5.02 TeV","");
    else leg->AddEntry((TObject*)0,"pp #sqrt{s_{NN}}= 5.02 TeV","");
    leg->AddEntry((TObject*)0,Form("%.1f<%s<%.1f",varmin,varlatex.Data(),varmax),"");
    leg->AddEntry(h,"Data","pl");
    leg->AddEntry(f,"Fit","l");
    leg->AddEntry(mass,"Signal","f");
    leg->AddEntry(massSwap,"K-#pi swapped","f");
    leg->AddEntry(background,"Combinatorial Background","l");
    leg->Draw();
    TLegend* leg2 = myLegend(0.45,0.80,0.90,0.94);
    leg2->SetFillColor(0);
    leg2->SetBorderSize(0);
    leg2->AddEntry(h,"D meson","");
    leg2->AddEntry(h,Form("M_{D}=%.2f #pm %.2f MeV/c^{2}",mass->GetParameter(1)*1000.,mass->GetParError(1)*1000.),"");
    leg2->AddEntry(h,Form("N_{D}=%.0f #pm %.0f", yield, yieldErr),"");
    leg2->Draw();

    hDistrib->SetBinContent(ivar+1,yield);
    hDistrib->SetBinError(ivar+1,yieldErr);

    if(isPbPb) c->SaveAs(Form("fitefficiencyPbPb/c%s_Fit_%s_%.0f.pdf",triggername.Data(),varname.Data(),ivar));
    else c->SaveAs(Form("fitefficiencyPP/c%s_Fit_%s_%.0f.pdf",triggername.Data(),varname.Data(),ivar));
  }
  TCanvas* cDistrib = new TCanvas(Form("c%s_Distrib_%s",triggername.Data(),varname.Data()),"",500,500);
  hDistrib->Draw();
  hDistrib->SetStats(0);
  if(isPbPb) cDistrib->SaveAs(Form("fitefficiencyPbPb/c%s_Distrib_%s.pdf",triggername.Data(),varname.Data()));
  else cDistrib->SaveAs(Form("fitefficiencyPP/data/pp/c%s_Distrib_%s.pdf",triggername.Data(),varname.Data()));

  return hDistrib;
}
Beispiel #8
0
void fitWe(const TString  outputDir="test",   // output directory
           const Double_t lumi=18.7,        // integrated luminosity (/fb)
	   const Int_t    Ecm=8,         // center-of-mass energy
	   const Int_t    doPU=1         // option for PU-reweighting
) {
  gBenchmark->Start("fitWe");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================   
  
  // MET histogram binning and range
  const Int_t    NBINS  = 50;
  const Double_t METMAX = 100;

  const Double_t PT_CUT  = 25;
  const Double_t ETA_CUT = 2.5;

  // file format for output plots
  const TString format("png"); 
    
  // file name with recoil correction
  TString recoilfname("../RecoilSyst/ZeeData/fits.root");
  
  // file name(s) with PU weights
  TString pufname("");
  if(doPU>0) {
    if(doPU==1) { pufname = "Utils/PileupReweighting.Summer11DYmm_To_Run2011A.root"; }
    else        { cout << "Invalid option for PU re-weighting! Aborting..." << endl; assert(0); }
  }
  
  //
  // input ntuple file names
  //
  enum { eData, eWenu, eEWK };  // data type enum
  vector<TString> fnamev;
  vector<Int_t>   typev;
  
  fnamev.push_back("../Selection/Wenu/ntuples/data_m23_select.root");   typev.push_back(eData);
  fnamev.push_back("../Selection/Wenu/ntuples/we_select.root");         typev.push_back(eWenu);
  fnamev.push_back("../Selection/Wenu/ntuples/ewk_select.root");        typev.push_back(eEWK);
  fnamev.push_back("../Selection/Wenu/ntuples/top_select.root");        typev.push_back(eEWK);


  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  
  
  // Create output directory
  gSystem->mkdir(outputDir,kTRUE);
  CPlot::sOutDir = outputDir;  
  
  // Get pile-up weights
  TFile *pufile    = 0;
  TH1D  *puWeights = 0;
  if(doPU>0) {
    pufile = new TFile(pufname);
    assert(pufile);
    puWeights = (TH1D*)pufile->Get("puWeights");
    assert(puWeights);
  }
  
  // Access recoil corrections
  //RecoilCorrector recoilCorr(recoilfname);
  
  //
  // Declare MET histograms
  //
  TH1D *hDataMet  = new TH1D("hDataMet", "",NBINS,0,METMAX); hDataMet->Sumw2();
  TH1D *hDataMetm = new TH1D("hDataMetm","",NBINS,0,METMAX); hDataMetm->Sumw2();  
  TH1D *hDataMetp = new TH1D("hDataMetp","",NBINS,0,METMAX); hDataMetp->Sumw2();
  TH1D *hWenuMet  = new TH1D("hWenuMet", "",NBINS,0,METMAX); hWenuMet->Sumw2();
  TH1D *hWenuMetp = new TH1D("hWenuMetp","",NBINS,0,METMAX); hWenuMetp->Sumw2();
  TH1D *hWenuMetm = new TH1D("hWenuMetm","",NBINS,0,METMAX); hWenuMetm->Sumw2();
  TH1D *hEWKMet   = new TH1D("hEWKMet",  "",NBINS,0,METMAX); hEWKMet->Sumw2();
  TH1D *hEWKMetp  = new TH1D("hEWKMetp", "",NBINS,0,METMAX); hEWKMetp->Sumw2();
  TH1D *hEWKMetm  = new TH1D("hEWKMetm", "",NBINS,0,METMAX); hEWKMetm->Sumw2();

  //
  // Declare variables to read in ntuple
  //
  UInt_t  runNum, lumiSec, evtNum;
  UInt_t  npv, npu;
  Float_t genWPt, genWPhi;
  Float_t scale1fb;
  Float_t met, metPhi, sumEt, mt, u1, u2;
  Int_t   q;
  LorentzVector *lep=0;
  LorentzVector *sc=0;
    
  TFile *infile=0;
  TTree *intree=0;

  //
  // Loop over files
  //
  for(UInt_t ifile=0; ifile<fnamev.size(); ifile++) {
    
    // Read input file and get the TTrees
    cout << "Processing " << fnamev[ifile] << "..." << endl;
    infile = new TFile(fnamev[ifile]);	  assert(infile);
    intree = (TTree*)infile->Get("Events"); assert(intree);

    intree->SetBranchAddress("runNum",   &runNum);    // event run number
    intree->SetBranchAddress("lumiSec",  &lumiSec);   // event lumi section
    intree->SetBranchAddress("evtNum",   &evtNum);    // event number
    intree->SetBranchAddress("npv",      &npv);       // number of primary vertices
    intree->SetBranchAddress("npu",      &npu);       // number of in-time PU events (MC)
    intree->SetBranchAddress("genVPt",   &genWPt);    // GEN W boson pT (signal MC)
    intree->SetBranchAddress("genVPhi",  &genWPhi);   // GEN W boson phi (signal MC)
    intree->SetBranchAddress("scale1fb", &scale1fb);  // event weight per 1/fb (MC)
    intree->SetBranchAddress("met",      &met);       // MET
    intree->SetBranchAddress("metPhi",   &metPhi);    // phi(MET)
    intree->SetBranchAddress("sumEt",    &sumEt);     // Sum ET
    intree->SetBranchAddress("mt",       &mt);        // transverse mass
    intree->SetBranchAddress("u1",       &u1);        // parallel component of recoil
    intree->SetBranchAddress("u2",       &u2);        // perpendicular component of recoil
    intree->SetBranchAddress("q",        &q);         // lepton charge
    intree->SetBranchAddress("lep",      &lep);       // lepton 4-vector
    intree->SetBranchAddress("sc",       &sc);        // electron Supercluster 4-vector
  
    //
    // loop over events
    //
    for(UInt_t ientry=0; ientry<intree->GetEntries(); ientry++) {
      intree->GetEntry(ientry);
      
      if(mt< 40)  continue;	// LUCA ADD
      TLorentzVector muPosP, muNegP, JpsiP;
      muPosP.SetPtEtaPhiM(lep->Pt(),lep->Eta(),lep->Phi(),lep->M()); // always use the muon
      muNegP.SetPtEtaPhiM(met,0,metPhi,0); // always use the neutrino
      JpsiP = muPosP + muNegP;
      
      // if(JpsiP.Pt() < 15 
      // || JpsiP.Pt() > 25 )  continue;	

      
      if(sc->Pt()        < PT_CUT)  continue;	
      if(fabs(sc->Eta()) > ETA_CUT) continue;
   
      if(typev[ifile]==eData) {
        hDataMet->Fill(met);
	if(q>0) { hDataMetp->Fill(met); } 
	else    { hDataMetm->Fill(met); }
      
      } else {
        Double_t weight = 1;
        weight *= scale1fb*lumi;
        if(puWeights)
	  weight *= puWeights->GetBinContent(npu+1);
	
	if(typev[ifile]==eWenu) {
          Double_t corrMet=met, corrMetPhi=metPhi;
        
	  // apply recoil corrections to W MC
	  //recoilCorr.Correct(corrMet,corrMetPhi,genWPt,genWPhi,lep->Pt(),lep->Phi());
	
          hWenuMet->Fill(corrMet,weight);
	  if(q>0) { hWenuMetp->Fill(corrMet,weight); } 
	  else    { hWenuMetm->Fill(corrMet,weight); }
        }
        if(typev[ifile]==eEWK) {
          hEWKMet->Fill(met,weight);
	  if(q>0) { hEWKMetp->Fill(met,weight); }
	  else    { hEWKMetm->Fill(met,weight); }
        }
      }
    }
  }  
  delete infile;
  infile=0, intree=0;   
  
  //
  // Declare fit parameters for signal and background yields
  // Note: W signal and EWK+top PDFs are constrained to the ratio described in MC
  //
  RooRealVar nSig("nSig","nSig",0.7*(hDataMet->Integral()),0,hDataMet->Integral());
  RooRealVar nQCD("nQCD","nQCD",0.3*(hDataMet->Integral()),0,hDataMet->Integral());
  RooRealVar cewk("cewk","cewk",0.1,0,5) ;
  cewk.setVal(hEWKMet->Integral()/hWenuMet->Integral());
  cewk.setConstant(kTRUE);
  RooFormulaVar nEWK("nEWK","nEWK","cewk*nSig",RooArgList(nSig,cewk));
  
  RooRealVar nSigp("nSigp","nSigp",0.7*(hDataMetp->Integral()),0,hDataMetp->Integral());
  RooRealVar nQCDp("nQCDp","nQCDp",0.3*(hDataMetp->Integral()),0,hDataMetp->Integral());
  RooRealVar cewkp("cewkp","cewkp",0.1,0,5) ;
  cewkp.setVal(hEWKMetp->Integral()/hWenuMetp->Integral());
  cewkp.setConstant(kTRUE);
  RooFormulaVar nEWKp("nEWKp","nEWKp","cewkp*nSigp",RooArgList(nSigp,cewkp));
  
  RooRealVar nSigm("nSigm","nSigm",0.7*(hDataMetm->Integral()),0,hDataMetm->Integral());
  RooRealVar nQCDm("nQCDm","nQCDm",0.3*(hDataMetm->Integral()),0,hDataMetm->Integral());
  RooRealVar cewkm("cewkm","cewkm",0.1,0,5) ;
  cewkm.setVal(hEWKMetm->Integral()/hWenuMetm->Integral());
  cewkm.setConstant(kTRUE);
  RooFormulaVar nEWKm("nEWKm","nEWKm","cewkm*nSigm",RooArgList(nSigm,cewkm));  
  
  //
  // Construct PDFs for fitting
  //
  RooRealVar pfmet("pfmet","pfmet",0,METMAX);
  pfmet.setBins(NBINS);
   
  // Signal PDFs
  RooDataHist wenuMet ("wenuMET", "wenuMET", RooArgSet(pfmet),hWenuMet);  RooHistPdf pdfWe ("we", "we", pfmet,wenuMet, 1);
  RooDataHist wenuMetp("wenuMETp","wenuMETp",RooArgSet(pfmet),hWenuMetp); RooHistPdf pdfWep("wep","wep",pfmet,wenuMetp,1);
  RooDataHist wenuMetm("wenuMETm","wenuMETm",RooArgSet(pfmet),hWenuMetm); RooHistPdf pdfWem("wem","wem",pfmet,wenuMetm,1); 
  
  // EWK+top PDFs
  RooDataHist ewkMet ("ewkMET", "ewkMET", RooArgSet(pfmet),hEWKMet);  RooHistPdf pdfEWK ("ewk", "ewk", pfmet,ewkMet, 1);
  RooDataHist ewkMetp("ewkMETp","ewkMETp",RooArgSet(pfmet),hEWKMetp); RooHistPdf pdfEWKp("ewkp","ewkp",pfmet,ewkMetp,1); 
  RooDataHist ewkMetm("ewkMETm","ewkMETm",RooArgSet(pfmet),hEWKMetm); RooHistPdf pdfEWKm("ewkm","ewkm",pfmet,ewkMetm,1); 
  
  // QCD Pdfs
  CPepeModel1 qcd("qcd",pfmet);
  CPepeModel1 qcdp("qcdp",pfmet);
  CPepeModel1 qcdm("qcdm",pfmet);
  
  // Signal + Background PDFs
  RooAddPdf pdfMet ("pdfMet", "pdfMet", RooArgList(pdfWe,pdfEWK,*(qcd.model)),   RooArgList(nSig,nEWK,nQCD));  
  RooAddPdf pdfMetp("pdfMetp","pdfMetp",RooArgList(pdfWep,pdfEWKp,*(qcdp.model)),RooArgList(nSigp,nEWKp,nQCDp));
  RooAddPdf pdfMetm("pdfMetm","pdfMetm",RooArgList(pdfWem,pdfEWKm,*(qcdm.model)),RooArgList(nSigm,nEWKm,nQCDm));
    
  //
  // Perform fits
  //
  RooDataHist dataMet("dataMet", "dataMet", RooArgSet(pfmet),hDataMet);
  RooFitResult *fitRes = pdfMet.fitTo(dataMet,Extended(),Minos(kTRUE),Save(kTRUE));
  
  RooDataHist dataMetp("dataMetp","dataMetp",RooArgSet(pfmet),hDataMetp);
  RooFitResult *fitResp = pdfMetp.fitTo(dataMetp,Extended(),Minos(kTRUE),Save(kTRUE));
  
  RooDataHist dataMetm("dataMetm","dataMetm",RooArgSet(pfmet),hDataMetm);
  RooFitResult *fitResm = pdfMetm.fitTo(dataMetm,Extended(),Minos(kTRUE),Save(kTRUE));
    
  //
  // Use histogram version of fitted PDFs to make ratio plots
  // (Will also use PDF histograms later for Chi^2 and KS tests)
  //
  TH1D *hPdfMet = (TH1D*)(pdfMet.createHistogram("hPdfMet", pfmet));
  hPdfMet->Scale((nSig.getVal()+nEWK.getVal()+nQCD.getVal())/hPdfMet->Integral());
  TH1D *hMetDiff = makeDiffHist(hDataMet,hPdfMet,"hMetDiff");
  hMetDiff->SetMarkerStyle(kFullCircle);
  hMetDiff->SetMarkerSize(0.9);
   
  TH1D *hPdfMetp = (TH1D*)(pdfMetp.createHistogram("hPdfMetp", pfmet));
  hPdfMetp->Scale((nSigp.getVal()+nEWKp.getVal()+nQCDp.getVal())/hPdfMetp->Integral());
  TH1D *hMetpDiff = makeDiffHist(hDataMetp,hPdfMetp,"hMetpDiff");
  hMetpDiff->SetMarkerStyle(kFullCircle);
  hMetpDiff->SetMarkerSize(0.9);
    
  TH1D *hPdfMetm = (TH1D*)(pdfMetm.createHistogram("hPdfMetm", pfmet));
  hPdfMetm->Scale((nSigm.getVal()+nEWKm.getVal()+nQCDm.getVal())/hPdfMetm->Integral());
  TH1D *hMetmDiff = makeDiffHist(hDataMetm,hPdfMetm,"hMetmDiff");
  hMetmDiff->SetMarkerStyle(kFullCircle); 
  hMetmDiff->SetMarkerSize(0.9);
   
  
  //--------------------------------------------------------------------------------------------------------------
  // Make plots 
  //==============================================================================================================  
  
  TCanvas *c = MakeCanvas("c","c",800,800);
  c->Divide(1,2,0,0);
  c->cd(1)->SetPad(0,0.3,1.0,1.0);
  c->cd(1)->SetTopMargin(0.1);
  c->cd(1)->SetBottomMargin(0.01);
  c->cd(1)->SetLeftMargin(0.18);  
  c->cd(1)->SetRightMargin(0.07);  
  c->cd(1)->SetTickx(1);
  c->cd(1)->SetTicky(1);  
  c->cd(2)->SetPad(0,0,1.0,0.3);
  c->cd(2)->SetTopMargin(0.05);
  c->cd(2)->SetBottomMargin(0.45);
  c->cd(2)->SetLeftMargin(0.18);
  c->cd(2)->SetRightMargin(0.07);
  c->cd(2)->SetTickx(1);
  c->cd(2)->SetTicky(1);
  gStyle->SetTitleOffset(1.400,"Y");
  
  char ylabel[100];  // string buffer for y-axis label
  
  // label for lumi
  char lumitext[100];
  if(lumi<0.1) sprintf(lumitext,"%.1f pb^{-1}  at  #sqrt{s} = %i TeV",lumi*1000.,Ecm);
  else         sprintf(lumitext,"%.2f fb^{-1}  at  #sqrt{s} = %i TeV",lumi,Ecm);
  
  // plot colors
  Int_t linecolorW   = kOrange-3;
  Int_t fillcolorW   = kOrange-2;
  Int_t linecolorEWK = kOrange+10;
  Int_t fillcolorEWK = kOrange+7;
  Int_t linecolorQCD = kViolet+2;
  Int_t fillcolorQCD = kViolet-5;
  Int_t ratioColor   = kGray+2;
  
  //
  // Dummy histograms for TLegend
  // (I can't figure out how to properly pass RooFit objects...)
  //
  TH1D *hDummyData = new TH1D("hDummyData","",0,0,10);
  hDummyData->SetMarkerStyle(kFullCircle);
  hDummyData->SetMarkerSize(0.9);
  
  TH1D *hDummyW = new TH1D("hDummyW","",0,0,10);
  hDummyW->SetLineColor(linecolorW);
  hDummyW->SetFillColor(fillcolorW);
  hDummyW->SetFillStyle(1001);
  
  TH1D *hDummyEWK = new TH1D("hDummyEWK","",0,0,10);
  hDummyEWK->SetLineColor(linecolorEWK);
  hDummyEWK->SetFillColor(fillcolorEWK);
  hDummyEWK->SetFillStyle(1001);
  
  TH1D *hDummyQCD = new TH1D("hDummyQCD","",0,0,10);
  hDummyQCD->SetLineColor(linecolorQCD);
  hDummyQCD->SetFillColor(fillcolorQCD);
  hDummyQCD->SetFillStyle(1001);
   
  //
  // W MET plot
  //
  RooPlot *weframe = pfmet.frame(Bins(NBINS));    
  dataMet.plotOn(weframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  pdfMet.plotOn(weframe,FillColor(fillcolorW),DrawOption("F"));
  pdfMet.plotOn(weframe,LineColor(linecolorW));
  pdfMet.plotOn(weframe,Components(RooArgSet(pdfEWK,*(qcd.model))),FillColor(fillcolorEWK),DrawOption("F"));
  pdfMet.plotOn(weframe,Components(RooArgSet(pdfEWK,*(qcd.model))),LineColor(linecolorEWK));
  pdfMet.plotOn(weframe,Components(RooArgSet(*(qcd.model))),FillColor(fillcolorQCD),DrawOption("F"));
  pdfMet.plotOn(weframe,Components(RooArgSet(*(qcd.model))),LineColor(linecolorQCD));
  pdfMet.plotOn(weframe,Components(RooArgSet(pdfWe)),LineColor(linecolorW),LineStyle(2));
  dataMet.plotOn(weframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));  
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMet->GetBinWidth(1));
  CPlot plotMet("fitmet",weframe,"","",ylabel);
  plotMet.SetLegend(0.68,0.57,0.93,0.77);
  plotMet.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotMet.GetLegend()->AddEntry(hDummyW,"W#rightarrowe#nu","F");
  plotMet.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotMet.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotMet.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotMet.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
  plotMet.SetYRange(0.1,1.1*(hDataMet->GetMaximum()));
//  plotMet.Draw(c,kFALSE,format,1);
  plotMet.Draw(c,kTRUE,format,1);

  CPlot plotMetDiff("fitmet","","#slash{E}_{T} [GeV]","#chi");
  plotMetDiff.AddHist1D(hMetDiff,"EX0",ratioColor);
  plotMetDiff.SetYRange(-8,8);
  plotMetDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotMetDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotMetDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotMetDiff.Draw(c,kTRUE,format,2);
  
  plotMet.SetName("fitmetlog");
  plotMet.SetLogy();
  plotMet.SetYRange(1e-3*(hDataMet->GetMaximum()),10*(hDataMet->GetMaximum()));
  plotMet.Draw(c,kTRUE,format,1);
    
  //
  // W+ MET plot
  //
  RooPlot *wepframe = pfmet.frame(Bins(NBINS));    
  dataMetp.plotOn(wepframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  pdfMetp.plotOn(wepframe,FillColor(fillcolorW),DrawOption("F"));
  pdfMetp.plotOn(wepframe,LineColor(linecolorW));
  pdfMetp.plotOn(wepframe,Components(RooArgSet(pdfEWKp,*(qcdp.model))),FillColor(fillcolorEWK),DrawOption("F"));
  pdfMetp.plotOn(wepframe,Components(RooArgSet(pdfEWKp,*(qcdp.model))),LineColor(linecolorEWK));
  pdfMetp.plotOn(wepframe,Components(RooArgSet(*(qcdp.model))),FillColor(fillcolorQCD),DrawOption("F"));
  pdfMetp.plotOn(wepframe,Components(RooArgSet(*(qcdp.model))),LineColor(linecolorQCD));
  pdfMetp.plotOn(wepframe,Components(RooArgSet(pdfWep)),LineColor(linecolorW),LineStyle(2));
  dataMetp.plotOn(wepframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));  
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMetp->GetBinWidth(1));
  CPlot plotMetp("fitmetp",wepframe,"","",ylabel);
  plotMetp.SetLegend(0.68,0.57,0.93,0.77);
  plotMetp.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotMetp.GetLegend()->AddEntry(hDummyW,"W^{+}#rightarrowe^{+}#nu","F");
  plotMetp.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotMetp.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotMetp.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotMetp.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
  plotMetp.SetYRange(0.1,1.1*(hDataMetp->GetMaximum()));
  plotMetp.Draw(c,kFALSE,format,1);

  CPlot plotMetpDiff("fitmetp","","#slash{E}_{T} [GeV]","#chi");
  plotMetpDiff.AddHist1D(hMetpDiff,"EX0",ratioColor);
  plotMetpDiff.SetYRange(-8,8);
  plotMetpDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotMetpDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotMetpDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotMetpDiff.Draw(c,kTRUE,format,2);
  
  plotMetp.SetName("fitmetplog");
  plotMetp.SetLogy();
  plotMetp.SetYRange(1e-3*(hDataMetp->GetMaximum()),10*(hDataMetp->GetMaximum()));
  plotMetp.Draw(c,kTRUE,format,1);
  
  //
  // W- MET plot
  //
  RooPlot *wemframe = pfmet.frame(Bins(NBINS)); 
  dataMetm.plotOn(wemframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  pdfMetm.plotOn(wemframe,FillColor(fillcolorW),DrawOption("F"));
  pdfMetm.plotOn(wemframe,LineColor(linecolorW));
  pdfMetm.plotOn(wemframe,Components(RooArgSet(pdfEWKm,*(qcdm.model))),FillColor(fillcolorEWK),DrawOption("F"));
  pdfMetm.plotOn(wemframe,Components(RooArgSet(pdfEWKm,*(qcdm.model))),LineColor(linecolorEWK));
  pdfMetm.plotOn(wemframe,Components(RooArgSet(*(qcdm.model))),FillColor(fillcolorQCD),DrawOption("F"));
  pdfMetm.plotOn(wemframe,Components(RooArgSet(*(qcdm.model))),LineColor(linecolorQCD));
  pdfMetm.plotOn(wemframe,Components(RooArgSet(pdfWem)),LineColor(linecolorW),LineStyle(2));
  dataMetm.plotOn(wemframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMetm->GetBinWidth(1));
  CPlot plotMetm("fitmetm",wemframe,"","",ylabel);
  plotMetm.SetLegend(0.68,0.57,0.93,0.77);
  plotMetm.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotMetm.GetLegend()->AddEntry(hDummyW,"W^{-}#rightarrowe^{-}#bar{#nu}","F");
  plotMetm.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotMetm.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotMetm.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotMetm.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
  plotMetm.SetYRange(0.1,1.1*(hDataMetm->GetMaximum()));
  plotMetm.Draw(c,kFALSE,format,1);

  CPlot plotMetmDiff("fitmetm","","#slash{E}_{T} [GeV]","#chi");
  plotMetmDiff.AddHist1D(hMetmDiff,"EX0",ratioColor);
  plotMetmDiff.SetYRange(-8,8);
  plotMetmDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotMetmDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotMetmDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotMetmDiff.Draw(c,kTRUE,format,2);
  
  plotMetm.SetName("fitmetmlog");
  plotMetm.SetLogy();
  plotMetm.SetYRange(1e-3*(hDataMetm->GetMaximum()),10*(hDataMetm->GetMaximum()));
  plotMetm.Draw(c,kTRUE,format,1);

    
  //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================
   
  cout << "*" << endl;
  cout << "* SUMMARY" << endl;
  cout << "*--------------------------------------------------" << endl;  
  
  //
  // Write fit results
  //
  ofstream txtfile;
  char txtfname[100];    
  
  ios_base::fmtflags flags;
  
  Double_t chi2prob, chi2ndf;
  Double_t ksprob, ksprobpe;
  
  chi2prob = hDataMet->Chi2Test(hPdfMet,"PUW");
  chi2ndf  = hDataMet->Chi2Test(hPdfMet,"CHI2/NDFUW");
  ksprob   = hDataMet->KolmogorovTest(hPdfMet);
  ksprobpe = hDataMet->KolmogorovTest(hPdfMet,"DX");
  sprintf(txtfname,"%s/fitresWe.txt",CPlot::sOutDir.Data());
  txtfile.open(txtfname);
  assert(txtfile.is_open());
  
  flags = txtfile.flags();
  txtfile << setprecision(10);
  txtfile << " *** Yields *** " << endl;
  txtfile << "Selected: " << hDataMet->Integral() << endl;
  txtfile << "  Signal: " << nSig.getVal() << " +/- " << nSig.getPropagatedError(*fitRes) << endl;
  txtfile << "     QCD: " << nQCD.getVal() << " +/- " << nQCD.getPropagatedError(*fitRes) << endl;
  txtfile << "   Other: " << nEWK.getVal() << " +/- " << nEWK.getPropagatedError(*fitRes) << endl;
  txtfile << endl; 
  txtfile.flags(flags);
  
  fitRes->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose);
  txtfile << endl;
  printCorrelations(txtfile, fitRes);
  txtfile << endl;
  printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe);
  txtfile.close();
  
  chi2prob = hDataMetp->Chi2Test(hPdfMetp,"PUW");
  chi2ndf  = hDataMetp->Chi2Test(hPdfMetp,"CHI2/NDFUW");
  ksprob   = hDataMetp->KolmogorovTest(hPdfMetp);
  ksprobpe = hDataMetp->KolmogorovTest(hPdfMetp,"DX");  
  sprintf(txtfname,"%s/fitresWep.txt",CPlot::sOutDir.Data());
  txtfile.open(txtfname);
  assert(txtfile.is_open());
  
  flags = txtfile.flags();
  txtfile << setprecision(10);
  txtfile << " *** Yields *** " << endl;
  txtfile << "Selected: " << hDataMetp->Integral() << endl;
  txtfile << "  Signal: " << nSigp.getVal() << " +/- " << nSigp.getPropagatedError(*fitResp) << endl;
  txtfile << "     QCD: " << nQCDp.getVal() << " +/- " << nQCDp.getPropagatedError(*fitResp) << endl;
  txtfile << "   Other: " << nEWKp.getVal() << " +/- " << nEWKp.getPropagatedError(*fitResp) << endl;
  txtfile << endl;  
  txtfile.flags(flags);
  
  fitResp->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose);
  txtfile << endl;
  printCorrelations(txtfile, fitResp);
  txtfile << endl;
  printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe);
  txtfile.close();

  chi2prob = hDataMetm->Chi2Test(hPdfMetm,"PUW");
  chi2ndf  = hDataMetm->Chi2Test(hPdfMetm,"CHI2/NDFUW");
  ksprob   = hDataMetm->KolmogorovTest(hPdfMetm);
  ksprobpe = hDataMetm->KolmogorovTest(hPdfMetm,"DX");  
  sprintf(txtfname,"%s/fitresWem.txt",CPlot::sOutDir.Data());
  txtfile.open(txtfname);
  assert(txtfile.is_open());
  
  flags = txtfile.flags();
  txtfile << setprecision(10);
  txtfile << " *** Yields *** " << endl;
  txtfile << "Selected: " << hDataMetm->Integral() << endl;
  txtfile << "  Signal: " << nSigm.getVal() << " +/- " << nSigm.getPropagatedError(*fitResm) << endl;
  txtfile << "     QCD: " << nQCDm.getVal() << " +/- " << nQCDm.getPropagatedError(*fitResm) << endl;
  txtfile << "   Other: " << nEWKm.getVal() << " +/- " << nEWKm.getPropagatedError(*fitResm) << endl;
  txtfile << endl;
  txtfile.flags(flags);
  
  fitResm->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose);
  txtfile << endl;
  printCorrelations(txtfile, fitResm);
  txtfile << endl;
  printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe);
  txtfile.close();

  makeHTML(outputDir);
  
  cout << endl;
  cout << "  <> Output saved in " << outputDir << "/" << endl;    
  cout << endl;     
  
  gBenchmark->Show("fitWe");
}
Beispiel #9
0
void doPlotsBtag(){
setTDRStyle();

//loop over variables
for(int i = 0; i<2; i++){
double MinX = MinXs[i];
double MaxX = MaxXs[i];
Variable = Variables[i];
TString Xtitle = XTitles[i];

//Data
TH1D* data = getSample("SingleMu", 1);

//MC
TH1D* tt = getSample("TTJet", lumi*225.2/6920475);

TH1D* wjets = getSample("W1Jet", lumi*37509/57708550);
TH1D* w1jets = getSample("W1Jet", lumi*5400.0/23140779);
TH1D* w2jets = getSample("W2Jets", lumi*1750.0/34041404);
TH1D* w3jets = getSample("W3Jets", lumi*519.0/15536443);
TH1D* w4jets = getSample("W4Jets", lumi*214.0/13370904);

TH1D* zjets = getSample("DY1JetsToLL", lumi*5745.25/30457954);
TH1D* z1jets = getSample("DY1JetsToLL", lumi*561.0/24042904);
TH1D* z2jets = getSample("DY2JetsToLL", lumi*181.0/21835749);
TH1D* z3jets = getSample("DY3JetsToLL", lumi*51.1/11010628);
TH1D* z4jets = getSample("DY4JetsToLL", lumi*23.04/6391785);

TH1D* qcd = getSample("QCD_Pt-15to20_MuEnrichedPt5",     lumi*34679.3/8500505);
TH1D* qcd1 = getSample("QCD_Pt-15to20_MuEnrichedPt5",   lumi*7.022e8 * 0.0039/1722678);
TH1D* qcd2 = getSample("QCD_Pt-20to30_MuEnrichedPt5",   lumi*2.87e8 * 0.0065/8486893);
TH1D* qcd3 = getSample("QCD_Pt-30to50_MuEnrichedPt5",   lumi*6.609e7 * 0.0122/8928999);
TH1D* qcd4 = getSample("QCD_Pt-50to80_MuEnrichedPt5",   lumi*8082000.0 * 0.0218/7256011);
TH1D* qcd5 = getSample("QCD_Pt-80to120_MuEnrichedPt5",  lumi*1024000.0 * 0.0395/9030624);
TH1D* qcd6 = getSample("QCD_Pt-120to170_MuEnrichedPt5", lumi*157800.0 * 0.0473/8500505);
TH1D* qcd7 = getSample("QCD_Pt-170to300_MuEnrichedPt5", lumi*34020.0 * 0.0676/7662483);
TH1D* qcd8 = getSample("QCD_Pt-300to470_MuEnrichedPt5", lumi*1757.0 * 0.0864/7797481);
TH1D* qcd9 = getSample("QCD_Pt-470to600_MuEnrichedPt5", lumi*115.2 * 0.1024/2995767);
TH1D* qcd10 = getSample("QCD_Pt-800to1000_MuEnrichedPt5",lumi*3.57 * 0.1033/4047142);
TH1D* qcd11 = getSample("QCD_Pt-1000_MuEnrichedPt5",     lumi*0.774 * 0.1097/3807263);

TH1D* top_t = getSample("T_t-channel", lumi*56.4/3757707);
TH1D* top_tw = getSample("T_tW-channel", lumi*11.1/497395);
TH1D* top_s = getSample("T_s-channel", lumi*3.79/249516);
TH1D* tbar_t = getSample("Tbar_t-channel", lumi*30.7/1934817);
TH1D* tbar_tw = getSample("Tbar_tW-channel", lumi*11.1/493239);
TH1D* tbar_s = getSample("Tbar_s-channel", lumi*1.76/139948);

THStack *hs = new THStack("hs","test");
  if(inclQ == true){
  hs->Add(qcd);
  }else{
  hs->Add(qcd1);
  hs->Add(qcd2);
  hs->Add(qcd3);
  hs->Add(qcd4);
  hs->Add(qcd5);
  hs->Add(qcd6);
  hs->Add(qcd7);
  hs->Add(qcd8);
  hs->Add(qcd9);
  hs->Add(qcd10);
  hs->Add(qcd11);
  }
  
  
  if(inclZ == true){
  hs->Add(zjets);
  }else{
  hs->Add(z1jets);
  hs->Add(z2jets);
  hs->Add(z3jets);
  hs->Add(z4jets);  
  }
  
  if(inclW == true){
  hs->Add(wjets);
  }else{
  hs->Add(w1jets);
  hs->Add(w2jets);
  hs->Add(w3jets);
  hs->Add(w4jets);  
  }
      
  hs->Add(top_t);
  hs->Add(top_tw);
  hs->Add(top_s);
  hs->Add(tbar_t);
  hs->Add(tbar_tw);
  hs->Add(tbar_s);
  
  hs->Add(tt);

  //draw histos to files
  TCanvas *c1 = new TCanvas("Plot","Plot",900, 600);
		
  hs->SetMaximum(data->GetBinContent(data->GetMaximumBin())*1.2);

  hs->Draw();
  data->Draw("E same");
  data->SetMarkerStyle(20);

//events:
cout << "ttbar: " << tt->Integral() << endl;
cout << "data: " << data->Integral() << endl;
  
  hs->GetXaxis()->SetLimits(MinX, MaxX);
  hs->GetXaxis()->SetTitle(Xtitle); hs->GetXaxis()->SetTitleSize(0.05);
  hs->GetYaxis()->SetTitle("Number of Events");hs->GetYaxis()->SetTitleSize(0.05);
  
  
  	TLegend *tleg2;
	tleg2 = new TLegend(0.7,0.7,0.8,0.9);
	tleg2->SetTextSize(0.04);
	tleg2->SetBorderSize(0);
	tleg2->SetFillColor(10);
	tleg2->AddEntry(data , "2012 data", "lpe");
	tleg2->AddEntry(tt , "t#bar{t}", "lf");
	tleg2->AddEntry(top_t, "single top", "lf");
	tleg2->AddEntry(wjets , "w+jets", "lf");
	tleg2->AddEntry(zjets , "z+jets", "lf");
	tleg2->AddEntry(qcd , "QCD", "lf");
	
	//tleg2->AddEntry(singtEff, "single-t"      , "l");
	//tleg2->AddEntry(singtwEff, "single-tW"      , "l");
 	tleg2->Draw("same");	
	
	TText* textPrelim = doPrelim(0.17,0.96);
	textPrelim->Draw();
	
  if(logPlot ==true){
  c1->SetLogy();
  }	
  
  TString plotName("plots/Control/Btags/");
  
  if(logPlot ==true){
    plotName += Variable+"Test_Log";
    plotName += ".pdf";
    
  }else{
    plotName += Variable;  
    plotName += ".pdf";
  }
 
 
  c1->SaveAs(plotName);
  delete c1;
  
  }
  	
}
Beispiel #10
0
void plotBalance(int cbin,
		 TString infname,
		 TString pythia,
		 TString mix,
		 bool drawXLabel,
		 bool drawLeg)
{

  bool showPbPb = 0;
  if(iPlot == 0 || iPlot == 3) showPbPb = 1;

  if(iPlot != 3) dijet = dijet&&deltaPhi;

  TCut centHF("");
  TCut centNtrk("");

  if(centMode == 0){
    cout<<"Obsolete centrality usage."<<endl;
    return;
    if(cbin==0) centHF = "bin>=20 && bin<26";
    if(cbin==1) centHF = "bin>=26 && bin<27";
    if(cbin==2) centHF = "bin>=27 && bin<28";
    if(cbin==3) centHF = "bin>=28 && bin<29";
    if(cbin==4) centHF = "bin>=29 && bin<31";
    if(cbin==5) centHF = "bin>=31";

    if(cbin==0) centNtrk = "ntrk >= 180";
    if(cbin==1) centNtrk = "150 <= ntrk && ntrk < 180";
    if(cbin==2) centNtrk = "110 <= ntrk && ntrk < 150";
    if(cbin==3) centNtrk = "90 <= ntrk && ntrk < 150";
    if(cbin==4) centNtrk = "60 <= ntrk && ntrk < 90";
    if(cbin==5) centNtrk = "ntrk < 60";
  }

  if(centMode == 1){
    centHF = hfPlusBins[cbin];
    centNtrk = centHF;
  }

  cout<<"plotting ntrk bin : "<<cbin<<endl;

  // open the data file

  if(iPlot > 100) entryMode = 1;

  string treeName = "ntdijet";
  string wName = "ntw";
  if(entryMode == 1){
    treeName = "ntjet";
    wName = "ntjetw";
  }

  if(entryMode == 2){
    treeName = "nttrk";
    wName = "nttrkw";
  }

  TFile *inf = new TFile(infname.Data());
  TTree *nt =(TTree*)inf->FindObjectAny(treeName.data());
  TTree *ntevt =(TTree*)inf->FindObjectAny("ntevt");
  if(entryMode < 1) nt->AddFriend(ntevt);

  // open the pythia (MC) file
  TFile *infReference = new TFile(pythia.Data());
  TTree *ntReference;
  TTree *ntevtReference;

  ntReference = (TTree*) infReference->FindObjectAny(treeName.data());
  ntevtReference = (TTree*) infReference->FindObjectAny("ntevt");
  if(entryMode < 1) ntReference->AddFriend(ntevtReference);
  
  // open the datamix file
  TFile *infMix = new TFile(mix.Data());
  TTree *ntMix =(TTree*)infMix->FindObjectAny(treeName.data());
  TTree *ntevtMix =(TTree*)infMix->FindObjectAny("ntevt");
  //  TFile *infW = new TFile("weights_hydjet.root");
  //  TTree *ntw =(TTree*)infW->FindObjectAny("ntw");

  TTree *ntw =(TTree*)infMix->FindObjectAny(wName.data());
  ntMix->AddFriend(ntw);
  if(entryMode < 1) ntMix->AddFriend(ntevtMix);

  int Nbin = 10;
  double max = 1.;
  double min = 0;

  if(iPlot == 1 || iPlot == 21 || iPlot == 22){
    Nbin = 20;
    max = 2;
    min = -2;
  };

  if(iPlot == 3){
    Nbin = 30;
    max = pi;
  };

  if(iPlot == 8){
    Nbin = 50;
    max = 25;
    min = -25;
  };

  if(iPlot == 9){
    Nbin = 50;
    max = 250;
  };

  if(iPlot == 11 || iPlot == 12){
    Nbin = 50;
    max = 25;
  };

  if(iPlot == 13 || iPlot == 14){
    Nbin = 75;
    max = 150;
  }

  if(iPlot == 101){
    Nbin = 20;
    max = 2;
    min = -2;
  }

  // projection histogram
  TH1D *h = new TH1D(Form("h",cbin),"",Nbin,min,max);
  TH1D *hReference = new TH1D(Form("hReference",cbin),"",Nbin,min,max);
  TH1D *hDataMix = new TH1D(Form("hDataMix",cbin),"",Nbin,min,max);

  TH1D *hB = new TH1D(Form("hB",cbin),"",Nbin,min,max);
  TH1D *hReferenceB = new TH1D(Form("hReferenceB",cbin),"",Nbin,min,max);
  TH1D *hDataMixB = new TH1D(Form("hDataMixB",cbin),"",Nbin,min,max);

  TH1D *hFull = new TH1D("hFull","",Nbin,min,max);
  TH1D *hReferenceFull = new TH1D("hReferenceFull","",Nbin,min,max);
  TH1D *hDataMixFull = new TH1D("hDataMixFull","",Nbin,min,max);

  TH1D* hNorm = new TH1D("hNorm","",1000,0,1000);
  TH1D* hNormReference = new TH1D("hNormReference","",1000,0,1000);
  TH1D* hNormDataMix = new TH1D("hNormDataMix","",1000,0,1000);

  hB->SetLineStyle(2);
  hReferenceB->SetLineStyle(2);
  hDataMixB->SetLineStyle(2);

  //  ntReference->SetAlias("pt1","et1");
  //  ntReference->SetAlias("pt2","et2");

  nt->SetAlias("pt1","jtpt1");
  nt->SetAlias("pt2","jtpt2");
  nt->SetAlias("eta1","jteta1");
  nt->SetAlias("eta2","jteta2");
  nt->SetAlias("phi1","jtphi1");
  nt->SetAlias("phi2","jtphi2");
  ntMix->SetAlias("pt1","jtpt1");
  ntMix->SetAlias("pt2","jtpt2");
  ntMix->SetAlias("eta1","jteta1");
  ntMix->SetAlias("eta2","jteta2");
  ntMix->SetAlias("phi1","jtphi1");
  ntMix->SetAlias("phi2","jtphi2");
  ntReference->SetAlias("pt1","jtpt1");
  ntReference->SetAlias("pt2","jtpt2");
  ntReference->SetAlias("eta1","jteta1");
  ntReference->SetAlias("eta2","jteta2");
  ntReference->SetAlias("phi1","jtphi1");
  ntReference->SetAlias("phi2","jtphi2");

  nt->SetAlias("cent","hfp");
  ntMix->SetAlias("cent","hfp");
  ntReference->SetAlias("cent","hfp");

  nt->SetAlias("dphi","acos(cos(phi1-phi2))");
  ntMix->SetAlias("dphi","acos(cos(phi1-phi2))");
  ntReference->SetAlias("dphi","acos(cos(phi1-phi2))");

  if(iPlot == 0){
    nt->SetAlias("var","pt2/pt1");
    ntReference->SetAlias("var","pt2/pt1");
    ntMix->SetAlias("var","pt2/pt1");
  }

  if(iPlot == 1){
    nt->SetAlias("var","(eta1+eta2)/2");
    ntReference->SetAlias("var","(eta1+eta2)/2");
    ntMix->SetAlias("var","(eta1+eta2)/2");
  }

  if(iPlot == 3){
    nt->SetAlias("var","acos(cos(phi1-phi2))");
    ntReference->SetAlias("var","acos(cos(phi1-phi2))");
    ntMix->SetAlias("var","acos(cos(phi1-phi2))");
  }

  if(iPlot == 8){
    nt->SetAlias("var","pu1-pu2");
    ntReference->SetAlias("var","pu1-pu2");
    ntMix->SetAlias("var","pu1-pu2");
  }

  if(iPlot == 11){
    nt->SetAlias("var","pu1");
    ntReference->SetAlias("var","pu1");
    ntMix->SetAlias("var","pu1");
  }

  if(iPlot == 12){
    nt->SetAlias("var","pu2");
    ntReference->SetAlias("var","pu2");
    ntMix->SetAlias("var","pu2");
  }

  if(iPlot == 13){
    nt->SetAlias("var","trkMax1");
    ntReference->SetAlias("var","trkMax1");
    ntMix->SetAlias("var","trkMax1");
  }

  if(iPlot == 14){
    nt->SetAlias("var","trkMax2");
    ntReference->SetAlias("var","trkMax2");
    ntMix->SetAlias("var","trkMax2");
  }

  if(iPlot == 9){
    nt->SetAlias("var","ntrk");
    ntReference->SetAlias("var","ntrk");
    ntMix->SetAlias("var","ntrk");
  }

  if(iPlot == 21){
    nt->SetAlias("var","eta1");
    ntReference->SetAlias("var","eta1");
    ntMix->SetAlias("var","eta1");
  }

  if(iPlot == 22){
    nt->SetAlias("var","eta2");
    ntReference->SetAlias("var","eta2");
    ntMix->SetAlias("var","eta2");
  }



  if(iPlot == 101){
    nt->SetAlias("var","eta");
    ntReference->SetAlias("var","eta");
    ntMix->SetAlias("var","eta");
  }

  if(iPlot == 51){
    nt->SetAlias("var","matchPt1/pt1");
    ntReference->SetAlias("var","matchPt1/pt1");
    ntMix->SetAlias("var","matchPt1/pt1");
  }

  if(iPlot == 52){
    nt->SetAlias("var","matchPt2/pt2");
    ntReference->SetAlias("var","matchPt2/pt2");
    ntMix->SetAlias("var","matchPt2/pt2");
  }


  nt->Draw("var>>hFull",dijet&&noise&&jetID&&centHF&&vtx); 
  nt->Draw("var>>hB",side&&noise&&jetID&&centHF&&vtx);
  nt->Draw("pt1>>hNorm",lead&&noise&&jetID&&centHF&&vtx);
   
  ntMix->Draw("var>>hDataMixFull",weight*(dijet&&jetID&&centHF&&vtx));
  ntMix->Draw("var>>hDataMixB",weight*(side&&jetID&&centHF&&vtx));
  ntMix->Draw("pt1>>hNormDataMix",weight*(lead&&jetID&&centHF&&vtx));
  
  ntReference->Draw("var>>hReferenceFull",dijet&&noise&&jetID&&centHF&&vtx);
  ntReference->Draw("var>>hReferenceB",side&&noise&&jetID&&centHF&&vtx);
  ntReference->Draw("pt1>>hNormReference",lead&&noise&&jetID&&centHF&&vtx);

  hDataMix->Add(hDataMixFull);
  h->Add(hFull);
  hReference->Add(hReferenceFull);

  if(subtract){
    hDataMix->Add(hDataMixB,-1);
    h->Add(hB,-1);
    hReference->Add(hReferenceB,-1);
  }

  hB->SetFillStyle(3005);
  hB->SetFillColor(15);

  // calculate the statistical error and normalize
  h->SetLineColor(dataColor);
  h->SetMarkerColor(dataColor);
  h->Sumw2();
  if(normLead){
    h->Scale(1./hNorm->Integral());
    hB->Scale(1./hNorm->Integral());
  }else{
    hB->Scale(1./h->Integral());
    h->Scale(1./h->Integral());
  }
  h->SetMarkerStyle(20);

  if(hReference->Integral() > 0){
    hReference->Scale(1./hNormReference->Integral());
  }

  hReference->SetLineColor(kBlue);
  hReference->SetFillColor(kAzure-8);
  hReference->SetFillStyle(3005);

  if(normLead){
    hDataMixB->Scale(1./hNormDataMix->Integral());
    hDataMix->Scale(1./hNormDataMix->Integral());
  }else{
    hDataMixB->Scale(1./hDataMix->Integral());
    hDataMix->Scale(1./hDataMix->Integral());
  }
  hDataMix->SetLineColor(mixColor);
  hDataMix->SetFillColor(mixColor);
  hDataMix->SetFillStyle(3004);
  
  hDataMix->SetMarkerSize(0);
  hDataMix->SetStats(0);

  hDataMix->GetXaxis()->SetLabelSize(22);
  hDataMix->GetXaxis()->SetLabelFont(43);
  hDataMix->GetXaxis()->SetTitleSize(28);
  hDataMix->GetXaxis()->SetTitleFont(43);
  hDataMix->GetXaxis()->SetTitleOffset(2.2);
  hDataMix->GetXaxis()->CenterTitle();
  
  
  hDataMix->GetYaxis()->SetLabelSize(22);
  hDataMix->GetYaxis()->SetLabelFont(43);
  hDataMix->GetYaxis()->SetTitleSize(28);
  hDataMix->GetYaxis()->SetTitleFont(43);
  hDataMix->GetYaxis()->SetTitleOffset(2.2);
  hDataMix->GetYaxis()->CenterTitle();
  
  if(drawXLabel) hDataMix->SetXTitle("A_{J} = (p_{T,1}-p_{T,2})/(p_{T,1}+p_{T,2})");  
  hDataMix->SetYTitle("Event Fraction");

  if(iPlot==1) hDataMix->SetXTitle("#eta_{dijet} = (#eta_{1}+#eta_{2})/2");
  if(iPlot==21) hDataMix->SetXTitle("#eta_{1}");
  if(iPlot==22) hDataMix->SetXTitle("#eta_{2}");

  if(iPlot==8) hDataMix->SetXTitle("p_{T,1}^{background}-p_{T,2}^{background}");
  if(iPlot==9) hDataMix->SetXTitle("N_{trk}^{offline}");

  if(iPlot==11) hDataMix->SetXTitle("p_{T,1}^{background}");
  if(iPlot==12) hDataMix->SetXTitle("p_{T,2}^{background}");

  if(iPlot==13) hDataMix->SetXTitle("p_{T} leading track in leading jet");
  if(iPlot==14) hDataMix->SetXTitle("p_{T} leading track in subleading jet");


  if(drawXLabel){
    if(iPlot==0) hDataMix->SetXTitle("p_{T,2}/p_{T,1}");
    if(iPlot==3) hDataMix->SetXTitle("#Delta #phi_{1,2}");
  }

  if(iPlot==0) hDataMix->SetMaximum(0.32);

  if(iPlot == 1 || iPlot==21 || iPlot==22){
    hDataMix->SetMaximum(0.3);
    hDataMix->SetMinimum(0);
  }


  if(iPlot==3){
    hDataMix->SetMaximum(2.52);
    hDataMix->SetMinimum(0.00004);
  }

  if(iPlot==8){
    hDataMix->SetMaximum(10);
    hDataMix->SetMinimum(0.00004);
  }

  if(iPlot==9){
    hDataMix->SetMaximum(0.15);
    hDataMix->SetMinimum(0.);
  }

  if(iPlot==11 || iPlot == 12){
    hDataMix->SetMaximum(10);
    hDataMix->SetMinimum(0.00004);
  }



  //hDataMix->GetXaxis()->SetNdivisions(905,true);
  hDataMix->GetYaxis()->SetNdivisions(505,true);

  hReference->SetMarkerColor(ppColor);
  hReference->SetLineColor(ppColor);
  hReference->SetMarkerStyle(25);

	hDataMix->Draw();//"hist");
	hDataMix->Draw("hist same");
	if(showPbPb) hReference->Draw("same");

	cout<<"PbPb ENTRIES : "<<endl;
	cout<<hReference->GetEntries()<<endl;

        cout<<"PbPb integral : "<<endl;
        cout<<hReference->Integral()<<endl;

	cout<<"pPb integral : "<<endl;
        cout<<h->Integral()<<endl;

	cout<<"Mix integral : "<<endl;
        cout<<hDataMix->Integral()<<endl;

	h->SetLineWidth(1);
	h->Draw("same");
	h->SetLineWidth(2);
	h->Draw("same");

	//	hDataMixB->Draw("same hist");
	//        hB->Draw("same hist");

	 cout<<" mean value of data "<<h->GetMean()<<endl;

  if(drawLeg){
    TLegend *t3=new TLegend(0.01,0.7,0.3,0.95);
    t3->AddEntry(h,"pPb #sqrt{s}=5.02 TeV","p");
    if(showPbPb) t3->AddEntry(hReference,"PbPb #sqrt{s}=2.76 TeV","p");
    t3->AddEntry(hDataMix,"PYTHIA+HIJING","lf");

    t3->SetFillColor(0);
    t3->SetBorderSize(0);
    t3->SetFillStyle(0);
    t3->SetTextFont(63);
    t3->SetTextSize(15);
    t3->Draw();
  }

}
void doControlPlotsMET(){
setTDRStyle();

//loop over variables
for(int i = 0; i<N; i++){
//double MinX = MinXs[i];
//double MaxX = MaxXs[i];
Variable = Variables[i];
TString Xtitle = XTitles[i];
int RebingFact = RebinFacts[i];

//Data
TH1D* data = getSample("DoubleMu", 1, Obj, Next, Variable, RebinFact, Systematic);

std::cout << data->Integral() << std::endl;

//MC
TH1D* tt = getSample("TTJet", 1, Obj, Next, Variable, RebinFact, Systematic);
TH1D* wjets = getSample("WJetsToLNu", 1, Obj, Next, Variable, RebinFact, Systematic);
TH1D* DY1 = getSample("DYJetsToLL_M-10To50", 1, Obj, Next, Variable, RebinFact, Systematic);
TH1D* DY2 = getSample("DYJetsToLL_M-50", 1, Obj, Next, Variable, RebinFact, Systematic);
TH1D* T_tW = getSample("T_tW-channel", 1, Obj, Next, Variable, RebinFact, Systematic);
TH1D* Tbar_tW = getSample("Tbar_tW-channel",1, Obj, Next, Variable, RebinFact, Systematic);

THStack *hs = new THStack("hs","test");

  hs->Add(wjets);
  hs->Add(DY1);
  hs->Add(DY2);
  hs->Add(T_tW); 
  hs->Add(Tbar_tW);
  hs->Add(tt); 
  
  //draw histos to files
  TCanvas *c1 = new TCanvas("Plot","Plot",900, 600);
		
  hs->SetMaximum(data->GetBinContent(data->GetMaximumBin())*1.3);

  hs->Draw();
  data->Draw("E same");
  data->SetMarkerStyle(20);
  
//  hs->GetXaxis()->SetLimits(MinX, MaxX);
  hs->GetXaxis()->SetTitle(Xtitle); hs->GetXaxis()->SetTitleSize(0.05);
  hs->GetYaxis()->SetTitle("Number of Events");hs->GetYaxis()->SetTitleSize(0.05);
   
   
  if(logPlot == true){
  c1->SetLogy();
  }	
  
  	TLegend *tleg2;
	tleg2 = new TLegend(0.6,0.7,0.8,0.9);
	tleg2->SetTextSize(0.04);
	tleg2->SetBorderSize(0);
	tleg2->SetFillColor(10);
	tleg2->AddEntry(data , "2012 data", "lpe");
	tleg2->AddEntry(tt , "t#bar{t}", "lf");
	tleg2->AddEntry(T_tW, "single-t", "lf");
	tleg2->AddEntry(Tbar_tW, "single-#bar{t}", "lf");	
	tleg2->AddEntry(DY1 , "DYJetsToLL-10To50", "lf");
	tleg2->AddEntry(DY2 , "DYJetsToLL-50", "lf");
	tleg2->AddEntry(wjets , "W+jets", "lf");
	
 	tleg2->Draw("same");	

  TString plotName("plots/Control/PassesCutsUpTo1Btag/MET/");
  
  if(logPlot == true){
    plotName += Variable+"Log.pdf";
//    plotName += Nbtags+".pdf";
    
  }else{
    plotName += Variable+".pdf";  
//    plotName += Nbtags+".pdf";
  }
 
  TText* textPrelim = doPrelim(0.16,0.96); 
  textPrelim->Draw();
  
  c1->SaveAs(plotName);
  delete c1;
  
  }
  	
}
void DoComparison(TString newFileName, TString oldFileName, vector<TString> newHistName, vector<TString> oldHistName)
{
  TFile newF(newFileName,"read");
  TDirectory *newDir = newF.GetDirectory("Merged");

  TFile old(oldFileName);

  TFile output("Comparison.root","update");

  assert(newHistName.size() == oldHistName.size());


  vector<TH1D*> newHists;
  vector<TH1D*> oldHists;
  
  for(UInt_t i = 0; i < newHistName.size(); i++) {
    TH1D *newH = (TH1D*)newDir->Get(newHistName[i]);
    if(!newH) {
      cout<<"Could not find "<<newHistName[i]<< " in "<<newDir->GetName()<<endl;
      return;
    }
    TH1D *oldH = (TH1D*)old.Get(oldHistName[i]);
    if(!oldH) {
      cout<<"Could not find "<<oldHistName[i]<< " in "<<old.GetName()<<endl;
      return;
    }
    
    newHists.push_back(newH);
    oldHists.push_back(oldH);
  }

  for(UInt_t i = 0; i < newHists.size(); i++) {

    // Make ratio
    TH1D *ratio = (TH1D*)newHists[i]->Clone();
    ratio->Divide(oldHists[i]);

    ratio->SetDirectory(0);
    TString newName = newHists[i]->GetName();
    newName += "Ratio";
    ratio->SetName(newName);
    ratio->SetTitle(newName);
    ratio->SetMarkerStyle(20);
    output.cd();
    ratio->Write(newName, TObject::kOverwrite);
    cout<<"Wrote "<<newName<<" to "<< output.GetName()<<endl;

    // Make difference
    TH1D *difference = (TH1D*)newHists[i]->Clone();
    difference->Add(oldHists[i],-1.);
    difference->SetDirectory(0);
    newName = newHists[i]->GetName();
    newName += "Difference";
    difference->SetName(newName);
    difference->SetTitle(newName);
    difference->SetMarkerStyle(20);
    output.cd();
    difference->Write(newName, TObject::kOverwrite);
    cout<<"Wrote "<<newName<<" to "<< output.GetName()<<endl;

    // Make side by side plot
    TString canName = "Canvas";
    canName += newHists[i]->GetName();
    canName += "Comparison";
    TCanvas *can = new TCanvas(canName, canName);
    newHists[i]->SetLineColor(kBlack);
    newHists[i]->SetMarkerStyle(20);
    newHists[i]->SetMarkerColor(kBlack);
    oldHists[i]->SetLineColor(kRed);
    oldHists[i]->SetMarkerStyle(20);
    oldHists[i]->SetMarkerColor(kRed);
    oldHists[i]->Draw();
    newHists[i]->Draw("same");
    can->Write(canName, TObject::kOverwrite);
    delete can; can = NULL;
  }

}
void Wpt_PASformat_withRatio(const TString  outputDir,   // output directory
           const TString  filetype,		// Select input root files for Nominal, Up, Down and Before Recoil Correction
           const Double_t lumi,        // integrated luminosity (/fb)
	   const Double_t nsigma=0     // vary MET corrections by n-sigmas (nsigma=0 means nominal correction)
)
{
  gBenchmark->Start("Wpt_PASformat_withRatio");

  //==================   
  // Settings 
  //==================   
  
  //const TString format("png"); 
  const TString format("pdf"); 
  //const TString format("root"); 

  // input ntuple file names
  TString fname = "MuonFitResultsModRayleighSimultNominal/RstMuon/SigYields_Nominal.root";
  if (filetype == "Electron")
    fname = "ElectronFitResultsModRayleighSimultNominal/RstElectron/SigYields_Nominal.root";

  TFile* infile = new TFile(fname);

  //-------------------------
  // Main analysis code 
  //=========================  
  
  // Create output directory
  gSystem->mkdir(outputDir,kTRUE);
  CPlot::sOutDir = outputDir;  
  cout << "check 1" << endl; 
  //
  // Declare MET histograms
  // 0 is for total

  TH1D *hdataWPpt;
  TH1D *hdataWMpt;
  TH1D *hSigWPpt;
  TH1D *hSigWMpt;
  TH1D *hQCDWPpt;
  TH1D *hQCDWMpt;
  TH1D *hDYToMuMuP;
  TH1D *hDYToMuMuM;
  TH1D *hWToTauNuP;
  TH1D *hWToTauNuM;
  TH1D *hTTJetsP;
  TH1D *hTTJetsM;
  TH1D *hDYToTauTauP;
  TH1D *hDYToTauTauM;

  // To get error from fit
  TH1D *hFitErrorP;
  TH1D *hFitErrorM;


  char histName[30],histName_org[30];

  cout << "check 2" << endl; 
  hdataWPpt    = (TH1D*)infile->Get("hdataWPpt")    -> Clone("hdataWPpt");
  cout << "check 3" << endl; 
  hdataWMpt    = (TH1D*)infile->Get("hdataWMpt")    -> Clone("hdataWMpt");
  hSigWPpt     = (TH1D*)infile->Get("hSigWPpt")     -> Clone("hSigWPpt");
  hSigWMpt     = (TH1D*)infile->Get("hSigWMpt")     -> Clone("hSigWMpt");
  hQCDWPpt     = (TH1D*)infile->Get("hQCDWPpt")     -> Clone("hQCDWPpt");
  hQCDWMpt     = (TH1D*)infile->Get("hQCDWMpt")     -> Clone("hQCDWMpt");
  hDYToMuMuP   = (TH1D*)infile->Get("hDYToMuMuP")   -> Clone("hDYToMuMuP");
  hDYToMuMuM   = (TH1D*)infile->Get("hDYToMuMuM")   -> Clone("hDYToMuMuM");
  hWToTauNuP   = (TH1D*)infile->Get("hWToTauNuP")   -> Clone("hWToTauNuP");
  hWToTauNuM   = (TH1D*)infile->Get("hWToTauNuM")   -> Clone("hWToTauNuM");
  hTTJetsP     = (TH1D*)infile->Get("hTTJetsP")     -> Clone("hTTJetsP");
  hTTJetsM     = (TH1D*)infile->Get("hTTJetsM")     -> Clone("hTTJetsM");
  hDYToTauTauP = (TH1D*)infile->Get("hDYToTauTauP") -> Clone("hDYToTauTauP");
  hDYToTauTauM = (TH1D*)infile->Get("hDYToTauTauM") -> Clone("hDYToTauTauM");

  //To get error from fit
  hFitErrorP      = (TH1D*)infile->Get("hWPptMCLog")   -> Clone("hFitErrorP");
  hFitErrorM      = (TH1D*)infile->Get("hWMptMCLog")   -> Clone("hFitErrorM");


  TCanvas *c;
  c = MakeCanvas("c","c",800,800);
  c->Divide(1,2,0,0);
  c->cd(1)->SetPad(0,0.3,1.0,1.0);
  c->cd(1)->SetTopMargin(0.1);
  //c->cd(1)->SetBottomMargin(0.01);
  c->cd(1)->SetBottomMargin(0.02);
  c->cd(1)->SetLeftMargin(0.15);
  c->cd(1)->SetRightMargin(0.07);
  c->cd(1)->SetTickx(1);
  c->cd(1)->SetTicky(1);
  c->cd(2)->SetPad(0,0,1.0,0.3);
  //c->cd(2)->SetTopMargin(0.05);
  c->cd(2)->SetTopMargin(0.07);
  c->cd(2)->SetBottomMargin(0.45);
  c->cd(2)->SetLeftMargin(0.15);
  c->cd(2)->SetRightMargin(0.07);
  c->cd(2)->SetTickx(1);
  c->cd(2)->SetTicky(1); 
  
//  c->SetPad(0,0,1.0,1.0);
//  c->SetTopMargin(0.1);
//  c->SetBottomMargin(0.15);
//  c->SetLeftMargin(0.15);  
//  c->SetRightMargin(0.07);  
//  c->SetTickx(1);
//  c->SetTicky(1);  
  gStyle->SetTitleOffset(1.400,"Y");
  TGaxis::SetMaxDigits(3);
  char ylabel[100];  // string buffer for y-axis label
  // label for lumi
  char lumitext[100];
  if(lumi<0.1) sprintf(lumitext,"%.1f pb^{-1} (8 TeV)",lumi*1000.);
  else         sprintf(lumitext,"%.2f fb^{-1}  at  #sqrt{s} = 8 TeV",lumi);
  char CMStext[100];
  sprintf(CMStext,"#font[61]{CMS}");
  char Preliminarytext[100];
  sprintf(Preliminarytext,"#font[52]{Preliminary}");
  char binlabel[50];
  
  // plot colors
  Int_t linecolorW   = kOrange-3;
  Int_t fillcolorW   = kOrange-2;
  Int_t linecolorEWK = kOrange+10;
  Int_t fillcolorEWK = kOrange+7;
  Int_t linecolorQCD = kViolet+2;
  Int_t fillcolorQCD = kViolet-5;

  //
  // Dummy histograms for TLegend
  // (I can't figure out how to properly pass RooFit objects...)
  //
  TH1D *hDummyData = new TH1D("hDummyData","",0,0,10);
  hDummyData->SetMarkerStyle(kFullCircle);
  hDummyData->SetMarkerSize(0.9);
  
  TH1D *hDummyW = new TH1D("hDummyW","",0,0,10);
  hDummyW->SetLineColor(linecolorW);
  hDummyW->SetFillColor(fillcolorW);
  hDummyW->SetFillStyle(1001);
  
  TH1D *hDummyEWK = new TH1D("hDummyEWK","",0,0,10);
  hDummyEWK->SetLineColor(linecolorEWK);
  hDummyEWK->SetFillColor(fillcolorEWK);
  hDummyEWK->SetFillStyle(1001);
  
  TH1D *hDummyQCD = new TH1D("hDummyQCD","",0,0,10);
  hDummyQCD->SetLineColor(linecolorQCD);
  hDummyQCD->SetFillColor(fillcolorQCD);
  hDummyQCD->SetFillStyle(1001);

// Wpt distribution=========================
  CPlot* plotWPptLog;
  CPlot* plotWPptDiffLog;
  CPlot* plotWMptLog;
  CPlot* plotWMptDiffLog;

//W plus pt distribution
  TH1D* hWptMC_p = (TH1D*)hDYToTauTauP->Clone("hWptMC_p");
  hWptMC_p->Add(hTTJetsP);
  hWptMC_p->Add(hWToTauNuP);
  hWptMC_p->Add(hDYToMuMuP);
  hWptMC_p->Add(hQCDWPpt);
  hWptMC_p->Add(hSigWPpt);
 
  TH1D* hWPptDiffLog;
  TH1D* hWMptDiffLog;

  //double WptBinsLog[14]={1,7.5,12.5,17.5,24,30,40,50,70,110,150,190,250,600};
  double WptBinsLog[14]={0.68,7.5,12.5,17.5,24,30,40,50,70,110,150,190,250,600};
  double x1,x2,x3,x4,x5,x6,x7,err;
  TH1D *hDYToTauTauLogP = new TH1D("hDYToTauTauLogP","",13,WptBinsLog);
  TH1D *hTTJetsLogP     = new TH1D("hTTJetsLogP","",13,WptBinsLog);
  TH1D *hWToTauNuLogP   = new TH1D("hWToTauNuLogP","",13,WptBinsLog);
  TH1D *hDYToMuMuLogP   = new TH1D("hDYToMuMuLogP","",13,WptBinsLog);
  TH1D *hQCDWptLogP     = new TH1D("hQCDWptLogP","",13,WptBinsLog);
  TH1D *hSigWptLogP     = new TH1D("hSigWptLogP","",13,WptBinsLog);
  TH1D *hdataWptLogP    = new TH1D("hdataWptLogP","",13,WptBinsLog);
  TAxis *xaxis = hSigWPpt->GetXaxis();
  for (int i=1; i<=hSigWPpt->GetNbinsX(); i++){
    x1=hDYToTauTauP->GetBinContent(i);
    x2=hTTJetsP->GetBinContent(i);
    x3=hWToTauNuP->GetBinContent(i);
    x4=hDYToMuMuP->GetBinContent(i);
    x5=hQCDWPpt->GetBinContent(i);
    x6=hSigWPpt->GetBinContent(i);
    x7=hdataWPpt->GetBinContent(i);
    err = hdataWPpt->GetBinError(i);
    hDYToTauTauLogP->Fill(xaxis->GetBinCenter(i),x1);
    hTTJetsLogP->Fill(xaxis->GetBinCenter(i),x2);
    hWToTauNuLogP->Fill(xaxis->GetBinCenter(i),x3);
    hDYToMuMuLogP->Fill(xaxis->GetBinCenter(i),x4);
    hQCDWptLogP->Fill(xaxis->GetBinCenter(i),x5);
    hSigWptLogP->Fill(xaxis->GetBinCenter(i),x6);
    hdataWptLogP->Fill(xaxis->GetBinCenter(i),x7);
    hdataWptLogP->SetBinError(i,err);
  }
  
  TH1D* hEwkWPptLog = (TH1D*)hDYToTauTauLogP->Clone("hEwkWPptLog");
  hEwkWPptLog->Add(hTTJetsLogP);
  hEwkWPptLog->Add(hWToTauNuLogP);
  hEwkWPptLog->Add(hDYToMuMuLogP);
  
  TString plotName = "FitWDistribution_MuonPLog";
  if (filetype == "Electron")
    plotName = "FitWDistribution_ElePLog";
  plotWPptLog=new CPlot(plotName,"","p_{T}^{W} [GeV]","Events");
  plotWPptLog->setOutDir(CPlot::sOutDir);
  plotWPptLog->AddHist1D(hdataWptLogP,"#font[42]{Data}","E");
  plotWPptLog->AddToStack(hEwkWPptLog,"#font[42]{EW+t#bar{t}}",fillcolorEWK,linecolorEWK);
  plotWPptLog->AddToStack(hQCDWptLogP,"#font[42]{QCD}",fillcolorQCD,linecolorQCD);
  if(filetype == "Muon")
    plotWPptLog->AddToStack(hSigWptLogP,"#font[42]{W^{+}#rightarrow #mu^{+}#nu}",fillcolorW,linecolorW);
  if(filetype == "Electron")
    plotWPptLog->AddToStack(hSigWptLogP,"#font[42]{W^{+}#rightarrow e^{+}#nu}",fillcolorW,linecolorW);
  plotWPptLog->SetLegend(0.67,0.70,.98,0.88);
  //plotWPptLog->SetYRange(0.25,1.4*(hWptMC_p->GetMaximum()));
  plotWPptLog->SetYRange(1,50*(hWptMC_p->GetMaximum()));
  plotWPptLog->SetLogx();
  plotWPptLog->SetLogy();
  plotWPptLog->AddTextBox(CMStext,0.14,0.90,0.24,0.97,0);
  plotWPptLog->AddTextBox(lumitext,0.65,0.90,0.95,0.97,0);
  plotWPptLog->Draw(c,kFALSE,format,1);
  gPad->RedrawAxis();

  // Pull distribution (Ratio)
  TH1D* hWPptMCLog = (TH1D*)hEwkWPptLog->Clone("hWPptMCLog");
  hWPptMCLog->Add(hQCDWptLogP);
  hWPptMCLog->Add(hSigWptLogP);

  //hWPptDiffLog = makeDiffHistWptLog(hdataWptLogP,hWPptMCLog,"hWPptDiffLog");
  hWPptDiffLog = makeDiffHistWptLog(hdataWptLogP,hWPptMCLog,hFitErrorP,"hWPptDiffLog"); // added histogram for fit error
  hWPptDiffLog->SetMarkerStyle(kFullCircle);
  hWPptDiffLog->SetMarkerSize(0.9);

  //plotWPptDiffLog=new CPlot(histName,"","p_{T}^{W} [GeV]","(data-mc)/#sigma_{data}");
  plotWPptDiffLog=new CPlot(histName,"","p_{T}^{W} [GeV]","(data-sum)/#sigma_{sum}");
  plotWPptDiffLog->setOutDir(CPlot::sOutDir);
  plotWPptDiffLog->AddHist1D(hWPptDiffLog,"",kAzure+1,1,1001);
  //plotWPptDiffLog->SetYRange(-0.15,0.15);
  plotWPptDiffLog->SetYRange(-1.3,1.3);
  plotWPptDiffLog->AddLine(0.68, 0,600, 0,kBlack,1);
  plotWPptDiffLog->SetLogx();
  plotWPptDiffLog->Draw(c,kFALSE,format,2);
  gPad->RedrawAxis();

  plotName = "Wpt_plots/FitWDistribution_MuonPLog_withRatio." + format;
  if (filetype == "Electron")
    plotName = "Wpt_plots/FitWDistribution_ElePLog_withRatio." + format;
  c->SaveAs(plotName);


//W minus pt distribution
  TH1D* hWptMC_m = (TH1D*)hDYToTauTauM->Clone("hWptMC_m");
  hWptMC_m->Add(hTTJetsM);
  hWptMC_m->Add(hWToTauNuM);
  hWptMC_m->Add(hDYToMuMuM);
  hWptMC_m->Add(hQCDWMpt);
  hWptMC_m->Add(hSigWMpt);
  
  TH1D *hDYToTauTauLogM = new TH1D("hDYToTauTauLogM","",13,WptBinsLog);
  TH1D *hTTJetsLogM = new TH1D("hTTJetsLogM","",13,WptBinsLog);
  TH1D *hWToTauNuLogM = new TH1D("hWToTauNuLogM","",13,WptBinsLog);
  TH1D *hDYToMuMuLogM = new TH1D("hDYToMuMuLogM","",13,WptBinsLog);
  TH1D *hQCDWptLogM = new TH1D("hQCDWptLogM","",13,WptBinsLog);
  TH1D *hSigWptLogM = new TH1D("hSigWptLogM","",13,WptBinsLog);
  TH1D *hdataWptLogM = new TH1D("hdataWptLogM","",13,WptBinsLog);
  for (int i=1; i<=hSigWMpt->GetNbinsX(); i++){
    x1=hDYToTauTauM->GetBinContent(i);
    x2=hTTJetsM->GetBinContent(i);
    x3=hWToTauNuM->GetBinContent(i);
    x4=hDYToMuMuM->GetBinContent(i);
    x5=hQCDWMpt->GetBinContent(i);
    x6=hSigWMpt->GetBinContent(i);
    x7=hdataWMpt->GetBinContent(i);
    err = hdataWMpt->GetBinError(i);
    hDYToTauTauLogM->Fill(xaxis->GetBinCenter(i),x1);
    hTTJetsLogM->Fill(xaxis->GetBinCenter(i),x2);
    hWToTauNuLogM->Fill(xaxis->GetBinCenter(i),x3);
    hDYToMuMuLogM->Fill(xaxis->GetBinCenter(i),x4);
    hQCDWptLogM->Fill(xaxis->GetBinCenter(i),x5);
    hSigWptLogM->Fill(xaxis->GetBinCenter(i),x6);
    hdataWptLogM->Fill(xaxis->GetBinCenter(i),x7);
    hdataWptLogM->SetBinError(i,err);
  }
  
  TH1D* hEwkWMptLog = (TH1D*)hDYToTauTauLogM->Clone("hEwkWMptLog");
  hEwkWMptLog->Add(hTTJetsLogM);
  hEwkWMptLog->Add(hWToTauNuLogM);
  hEwkWMptLog->Add(hDYToMuMuLogM);
  
  plotName = "FitWDistribution_MuonMLog";
  if (filetype == "Electron")
    plotName = "FitWDistribution_EleMLog";
  plotWMptLog=new CPlot(plotName,"","p_{T}^{W} [GeV]","Events");
  plotWMptLog->setOutDir(CPlot::sOutDir);
  plotWMptLog->AddHist1D(hdataWptLogM,"#font[42]{Data}","E");
  plotWMptLog->AddToStack(hEwkWMptLog,"#font[42]{EW+t#bar{t}}",fillcolorEWK,linecolorEWK);
  plotWMptLog->AddToStack(hQCDWptLogM,"#font[42]{QCD}",fillcolorQCD,linecolorQCD);
  if(filetype == "Muon")
    //plotWMptLog->AddToStack(hSigWptLogM,"#font[42]{W^{-}#rightarrow #mu^{-} #bar{#nu}}",fillcolorW,linecolorW);
    plotWMptLog->AddToStack(hSigWptLogM,"#font[42]{W^{#font[122]{-}}#rightarrow #mu^{#font[122]{-}} #bar{#nu}}",fillcolorW,linecolorW);
  if(filetype == "Electron")
    //plotWMptLog->AddToStack(hSigWptLogM,"#font[42]{W^{-}#rightarrow e^{-} #bar{#nu}}",fillcolorW,linecolorW);
    plotWMptLog->AddToStack(hSigWptLogM,"#font[42]{W^{#font[122]{-}}#rightarrow e^{#font[122]{-}} #bar{#nu}}",fillcolorW,linecolorW);
  //plotWMptLog->SetLegend(0.75,0.78,.98,0.88);
  plotWMptLog->SetLegend(0.67,0.70,.98,0.88);
  //plotWMptLog->SetYRange(0.25,1.4*(hWptMC_m->GetMaximum()));
  plotWMptLog->SetYRange(1,50*(hWptMC_m->GetMaximum()));
  plotWMptLog->SetLogx();
  plotWMptLog->SetLogy();
  plotWMptLog->AddTextBox(CMStext,0.14,0.90,0.24,0.97,0);
  plotWMptLog->AddTextBox(lumitext,0.65,0.90,0.95,0.97,0);
  plotWMptLog->Draw(c,kFALSE,format,1);
  gPad->RedrawAxis();
  
  // Pull distribution (Ratio)
  TH1D* hWMptMCLog = (TH1D*)hEwkWMptLog->Clone("hWMptMCLog");
  hWMptMCLog->Add(hQCDWptLogM);
  hWMptMCLog->Add(hSigWptLogM);

  //hWMptDiffLog = makeDiffHistWptLog(hdataWptLogM,hWMptMCLog,"hWMptDiffLog");
  hWMptDiffLog = makeDiffHistWptLog(hdataWptLogM,hWMptMCLog,hFitErrorM,"hWMptDiffLog"); // added histogram for fit error
  hWMptDiffLog->SetMarkerStyle(kFullCircle);
  hWMptDiffLog->SetMarkerSize(0.9);

  //plotWMptDiffLog=new CPlot(histName,"","p_{T}^{W} [GeV]","(data-mc)/#sigma_{data}");
  plotWMptDiffLog=new CPlot(histName,"","p_{T}^{W} [GeV]","(data-sum)/#sigma_{sum}");
  plotWMptDiffLog->setOutDir(CPlot::sOutDir);
  plotWMptDiffLog->AddHist1D(hWMptDiffLog,"",kAzure+1,1,1001);
  //plotWMptDiffLog->SetYRange(-0.15,0.15);
  plotWMptDiffLog->SetYRange(-1.3,1.3);
  plotWMptDiffLog->AddLine(0.68, 0,600, 0,kBlack,1);
  plotWMptDiffLog->SetLogx();
  plotWMptDiffLog->Draw(c,kFALSE,format,2);
  gPad->RedrawAxis();


  plotName = "Wpt_plots/FitWDistribution_MuonMLog_withRatio." + format;
  if (filetype == "Electron")
    plotName = "Wpt_plots/FitWDistribution_EleMLog_withRatio." + format;
  c->SaveAs(plotName);

  gBenchmark->Show("Wpt_PASformat_withRatio");
}
//_______________________________________________________________________
TH1D * GetPedestalHistoAndSystAndSubtractPed(Int_t binSystem, Int_t binAssoc,Int_t binMeson,TH1D *histo, TGraphAsymmErrors* gr,TGraphAsymmErrors *&grout, TString canvasname,TGraphAsymmErrors *&grbaseOut,TGraphAsymmErrors *&grv2Out){

  Double_t value = 0, pedestal=0;
  TGraphAsymmErrors *grBaseHelp,*grV2;
  grbaseOut=new TGraphAsymmErrors();
  grbaseOut->SetName(Form("grbaselineUncFull_%s_%s_%s",sets[binSystem].Data(),strmesonpt[binMeson].Data(),pthadron[binAssoc].Data()));

  Double_t xuncFull,errxuncFull;
  Double_t xuncv2,errxuncv2;
  Int_t bin,bingr;
  TString path = pedestalfilenames[binSystem][binAssoc];


  if(binSystem==0){//pp
    grV2=0x0;
    cout << "pp -->  Reading File from path: " << path << endl;
    
    TFile * file = TFile::Open(path.Data(),"READ");
    TCanvas* c=(TCanvas*)file->Get(canvasname.Data());
    TH1D* h = (TH1D*)c->GetListOfPrimitives()->FindObject("FinalTrendPedestal");
    grBaseHelp=(TGraphAsymmErrors*)c->GetListOfPrimitives()->FindObject("fBaselineVariationSystematicsPedestal");    

    if(isReflectedData){
      xuncFull=3.25;
      errxuncFull=0.075;
      xuncv2=-0.15; 
      errxuncv2=0.075;
    }
    else{
      xuncFull=4.83;
      errxuncFull=0.075;
      xuncv2=-1.7;
      errxuncv2=0.075;
    }

    bin=h->FindBin(mesonptcenter[binMeson]);
    bingr=GetBinGraph(mesonptcenter[binMeson],grBaseHelp);


    pedestal=h->GetBinContent(bin);
    Double_t x,y,erryl,erryh;
    Printf("histo: x=%f, graph: %f",h->GetBinCenter(bin),x);
    grBaseHelp->GetPoint(bingr,x,y);
    erryl=grBaseHelp->GetErrorYlow(bingr);
    erryh=grBaseHelp->GetErrorYhigh(bingr);
    
    grbaseOut->SetPoint(0,xuncFull,0);
    grbaseOut->SetPointError(0,errxuncFull,errxuncFull,erryl,erryh);
    if(grV2){
      grV2->GetPoint(bingr,x,y);
      erryl=grV2->GetErrorYlow(bingr);
      erryh=grV2->GetErrorYhigh(bingr);	
      grv2Out->SetPoint(0,xuncFull,0);
      grv2Out->SetPointError(0,errxuncFull,errxuncFull,erryl,erryh);
    }
  }

  cout<<"Baseline being subtracted for:"<<sets[binSystem].Data()<<strmesonpt[binMeson].Data()<<pthadron[binAssoc].Data()<<endl;
  
  grout=(TGraphAsymmErrors*)gr->Clone(Form("grSub_%s_%s_%s",sets[binSystem].Data(),strmesonpt[binMeson].Data(),pthadron[binAssoc].Data()));
  
  TString nameoutput = histo->GetName();
  nameoutput += "_subtr_";
  nameoutput += "pedestal";
  nameoutput += Form("_%s_%s_%s",sets[binSystem].Data(),strmesonpt[binMeson].Data(),pthadron[binAssoc].Data());
   
  TH1D * outputhisto = (TH1D*)histo->Clone(nameoutput.Data());
  outputhisto->Reset();
  outputhisto->SetStats(kFALSE);
    

  for(Int_t iBin = 1; iBin <= histo->GetNbinsX();iBin++){
        
        
    value = histo->GetBinContent(iBin);
    value -= pedestal;
      
    outputhisto->SetBinContent(iBin,value);
      
    outputhisto->SetBinError(iBin,histo->GetBinError(iBin));
    Double_t x,y,eyl,eyh;
    gr->GetPoint(iBin-1,x,y);
    eyl=gr->GetErrorYlow(iBin-1);
    eyh=gr->GetErrorYhigh(iBin-1);
    //cout<<x<<"  "<<y<<"  "<<eyl<<"  "<<eyh<<endl;
    grout->SetPoint(iBin-1,x,y-pedestal);

  }
  cout<<"sub -> "<<outputhisto->GetBinContent(5)<<endl;
  
  outputhisto->SetXTitle("#Delta#varphi (rad)");
  outputhisto->SetYTitle("#frac{1}{#it{N}_{D}} #frac{d#it{N}^{assoc}}{d#Delta#varphi} - baseline (rad^{-1})");
  outputhisto->GetYaxis()->CenterTitle();
  outputhisto->SetMarkerColor(kBlack);
  outputhisto->SetLineColor(kBlack);
  outputhisto->SetMarkerStyle(20);
  
  //  outputhisto->GetYaxis()->SetTitleOffset(1.5);
  //  outputhisto->GetYaxis()->SetTitleFont(42);
  //  outputhisto->GetXaxis()->SetTitleFont(42);
  //  outputhisto->GetYaxis()->SetTitleSize(25);
  //  outputhisto->GetXaxis()->SetTitleSize(25);
  //  outputhisto->GetYaxis()->SetLabelSize(0.04);
  //  outputhisto->GetXaxis()->SetLabelSize(0.04);

  cout<<"now return histogram"<<endl;

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

    TH1D *histo_obs_norm = (TH1D*)histo_obs->Clone();
    histo_obs_norm->Scale(1/histo_obs->Integral(xbinmin,xbinmax));

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

    TTree *t = (TTree*) fGlauber->Get("nt_p_Pb");
    Long_t Nevent;

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

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

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

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

    double hfbin[]= {0,1,2,3,4,6,8,10,13,16,20,25,30,40,55,70,90};
    int nhfbin = 16;
    rehisto_obs_norm = (TH1D*)histo_obs_norm->Rebin(nhfbin,"rehisto_obs_norm",hfbin);
    normalizeByBinWidth(rehisto_obs_norm);
    rehisto_exp_norm = (TH1D*)histo_exp_norm->Rebin(nhfbin,"rehisto_exp_norm",hfbin);
    normalizeByBinWidth(rehisto_exp_norm);
    TH1D* ratio = (TH1D*)rehisto_obs_norm->Clone("ratio");
    ratio->Divide(rehisto_exp_norm);
    ratio->SetMaximum(1.2);
    ratio->SetMinimum(0);
    ratio->GetXaxis()->SetTitle("HF #Sigma E_{T} |#eta|>4");
    ratio->GetYaxis()->SetTitle("ratio");

    TFile *fDSeff = TFile::Open("/afs/cern.ch/work/q/qixu/private/RpA/GlobalEvent/CentrDep/pPbHijing_EffCorr_forNBD.root");
    TFile *ftreff = TFile::Open("/afs/cern.ch/user/q/qixu/CMSSW_6_2_5/src/Centrality/Correction/pPbHist_Hijing_TrandEs.root");
    TH1D* hbef = (TH1D*)ftreff->Get("hHFEnergy4");
    TH1D* rehbef = (TH1D*)hbef->Rebin(nhfbin,"rehHFEnergy4",hfbin);
    TH1D* haft = (TH1D*)ftreff->Get("hHFEnergy4_tr");
    TH1D* rehaft = (TH1D*)haft->Rebin(nhfbin,"rehHFEnergy4_tr",hfbin);
    TGraphAsymmErrors *gtreff = new TGraphAsymmErrors();
    gtreff->BayesDivide(rehaft,rehbef);

    TGraphAsymmErrors *geff = (TGraphAsymmErrors*)fDSeff->Get("regEffHF4");
    for(int i=0; i<geff->GetN(); i++) {
        geff->SetPointEXlow(i,0);
        geff->SetPointEXhigh(i,0);
        gtreff->SetPointEXlow(i,0);
        gtreff->SetPointEXhigh(i,0);
    }

    ratio->SetTitle("");
    ratio->SetLineColor(1);
    ratio->SetMarkerStyle(24);
    ratio->SetMarkerColor(1);
    ratio->SetMarkerSize(1.5);
    ratio->Draw("P");

    geff->SetMarkerStyle(33);
    geff->SetMarkerColor(2);
    geff->SetMarkerSize(1.5);
    geff->Draw("Psame");

    gtreff->SetMarkerStyle(21);
    gtreff->SetMarkerColor(4);
    gtreff->SetMarkerSize(1.3);
    gtreff->Draw("Psame");

    TLegend *leg = new TLegend(0.60, 0.2, 0.78, 0.4);
    leg->SetFillColor(10);
    leg->SetFillStyle(0);
    leg->SetBorderSize(0.035);
    leg->SetTextFont(42);
    leg->SetTextSize(0.045);
    leg->AddEntry(ratio,"data/fit","p");
    leg->AddEntry(geff,"DS efficiency","p");
    leg->AddEntry(gtreff,"Event selection efficiency","p");
    leg->Draw("same");

    TLine *l = new TLine(0,1,90,1);
    l->SetLineStyle(2);
    l->Draw("same");
    c1->SaveAs(Form("%sratiovseff.png",dirname.Data()));

}
void distribution(const string folderNameWithRootFiles = "", const Int_t signalRegion0_controlRegion1 = 0, const Int_t mumu0_ee1 = 0, const Int_t data0_noData1 = 0, const string var = "met", const Int_t yAxisLog_flag = 0, const Int_t MCpoissonUncertainty_flag = 0, const Double_t xAxisMin = 0, const Double_t xAxisMax = -1, const Double_t yAxisMin = 0, const Double_t yAxisMax = -1, const Int_t binDensity_flag = 0, const Int_t MCnormalizedToData_flag = 0) {

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

  // mumu0_ee1 is for lepton flavour in CS (not used in SR)

  // data0_noData1 is to use or not a data file to compared with MC

  // yAxisLog_flag is to choose whether or not to use log scale in Y axis (default is 0, that is, normal scale)
  // xAxisMin and xAxisMax are the ranges for x Axis. Default values are used if xAxisMin > xAxisMax (otherwise user values are used)

  TH1::SetDefaultSumw2();            //all the following histograms will automatically call TH1::Sumw2() 

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

  string filenameExtension = ".root";
  // string fileDirectoryPath = "spring15_25ns_rootfiles/";
  string fileDirectoryPath = "/cmshome/ciprianim/CMSSW721/output/" + folderNameWithRootFiles + "/";

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

  if (mumu0_ee1 == 0) suffix = "_mumu";
  else if (mumu0_ee1 == 1) suffix = "_ee";
  else {
    cout << "Error: mumu0_ee1 must be 0 or 1. End of programme." << endl;
    exit(EXIT_FAILURE);
  }

  TH1D* hvar = NULL;   // to get histogram from file
  string hvarName;          // name of histogram to take from file
  string xAxisName;        // name of X axis when plotting distribution. It is a tex string (with ROOT standard), e.g. "#slash{E}_{T} [GeV]" for MET

  // ===== TO BE MODIFIED =====

  // hvarName = "HmetNoLepDistribution";
  // xAxisName = "#slash{E}_{T} [GeV]";

  setDistribution(signalRegion0_controlRegion1, mumu0_ee1, var, hvarName, xAxisName);
    
  // =====================

  vector<TH1D*> hMC;
  TH1D* hdata = NULL;

  vector<string> sampleName;
  vector<string> MC_TexLabel;
  if (data0_noData1 == 1) setSampleName(signalRegion0_controlRegion1, sampleName, MC_TexLabel, mumu0_ee1);
  else setSampleName2lepSkim(signalRegion0_controlRegion1, sampleName, MC_TexLabel, mumu0_ee1);

  string data_TexLabel = "data";

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

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

   string filenameBase;
   string canvasName;

   if (signalRegion0_controlRegion1 == 0) {

     filenameBase = "monojet_SR_spring15_25ns_";
     canvasName = var + "_monojetSR_";

   } else {

     canvasName = var + "_zjetsCS" + suffix;

     if (mumu0_ee1 == 0) filenameBase = "zmumujets_CS_spring15_25ns_";
     else if (mumu0_ee1 == 1) filenameBase = "zeejets_CS_spring15_25ns_";

   }
 

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

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

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

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

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

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

  } 

  // ==== FILE NAME WILL HAVE TO BE MODIFIED, NOW IT IS JUST A TEST =====

  string datafileName = fileDirectoryPath;

  if (data0_noData1 == 0) {

    if (signalRegion0_controlRegion1 == 0) {

      datafileName += "monojet_SR_spring15_25ns_DATA.root";

    } else {

      if (mumu0_ee1 == 0) datafileName += "zmumujets_CS_spring15_25ns_DATA.root";
      else if (mumu0_ee1 == 1) datafileName += "zeejets_CS_spring15_25ns_DATA.root";

    }

  }

  // ==== opening data file ======

  if (data0_noData1 == 0) {

    cout<<"fileName : "<<datafileName<<endl;

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

    hvar = (TH1D*)f->Get(hvarName.c_str());

    if (!hvar) {
      cout << "Error: histogram not found in file ' " << datafileName << "'. End of programme." << endl;
      exit(EXIT_FAILURE);
    }
    hdata = (TH1D*)hvar->Clone();

  }

  // ===============================

  THStack* hMCstack = new THStack("hMCstack","");
  Double_t stackNorm = 0.0;

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

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

      if (MCpoissonUncertainty_flag == 1) {

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

    }

    hMC[j]->SetFillColor(histColor[j]);
    stackNorm += hMC[j]->Integral();

  }

  // loop again on MC histograms to scale them and then fill the thstack

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

    if (data0_noData1 == 0 && MCnormalizedToData_flag != 0) {

      Double_t dataNorm = hdata->Integral();

      if (binDensity_flag != 0) hMC[j]->Scale(dataNorm/stackNorm,"width");
      else hMC[j]->Scale(dataNorm/stackNorm);

    } else if (binDensity_flag != 0) hMC[j]->Scale(1.0,"width");  // option width divides by bin width and manages the correct error setting

    hMCstack->Add(hMC[j]);

  }

  if (data0_noData1 == 0) {

    cout << "Events in data: " << hdata->Integral() << endl;
    cout << "Events in MC   : " << ((TH1D*) hMCstack->GetStack()->Last())->Integral() << endl;

  }
  
  if (data0_noData1 == 0 && binDensity_flag != 0) hdata->Scale(1.0,"width");
  //if (data0_noData1 == 0 && MCnormalizedToData_flag != 0)

  // now here we go with the canvas

  TH1D * ratioplot = NULL; // will use it for the ratio plots

  TPad *subpad_1 = NULL;  // will use it to access specific subpad in canvas
  TPad *subpad_2 = NULL; 

  TCanvas *c;
  if (data0_noData1 == 0) c = new TCanvas(canvasName.c_str(), (var + " distribution").c_str(), 700, 700);
  else c = new TCanvas(canvasName.c_str(), (var + " distribution").c_str());
  TLegend *leg = new TLegend(0.7,0.6,0.99,0.94);  

  // if there are data, split canvas to draw the dta/MC ratio plot

  if (data0_noData1 == 0) {

    subpad_1 = new TPad("pad_1","",0.0,0.28,1.0,1.0);
    if (yAxisLog_flag) subpad_1->SetLogy();
    //subpad_1->SetBottomMargin(0);
    subpad_2 = new TPad("pad_2","",0.0,0.0,1.0,0.32);
    subpad_2->SetGridy();
    //subpad_2->SetTopMargin(0);
    subpad_2->SetBottomMargin(0.3);
    subpad_1->Draw();
    subpad_2->Draw();

    subpad_1->cd();

  } else if (yAxisLog_flag) c->SetLogy();

  
  hMCstack->Draw("HIST");
  //if (yAxisMin > 0) hMCstack->SetMinimum(yAxisMin);

  if (yAxisMin < yAxisMax) {
    if (data0_noData1 == 0) subpad_1->Update();  // to be done after Draw() to access pad parameters such as default axis range
    else c->Update();  
    hMCstack->GetYaxis()->SetRangeUser(yAxisMin,yAxisMax);
  }

  // if (data0_noData1 == 0) {

  //   if (yAxisMin > 0) hMCstack->GetYaxis()->SetRangeUser(yAxisMin, subpad_1->GetY2());
  //   else hMCstack->GetYaxis()->SetRangeUser(yAxisMin, c->GetY2());

  // }

  //hMCstack->SetMaximum(4000.0);
  TH1D* stackCopy = (TH1D*)(((TH1D*)hMCstack->GetStack()->Last())->DrawCopy("E2 SAME"));
  stackCopy->SetFillColor(kBlack);
  stackCopy->SetFillStyle(3144);

  if (data0_noData1 == 1) {    //  when using data ( == 0) the x axis will not have labels (they will only be below in the ratio plot
    hMCstack->GetXaxis()->SetTitle(xAxisName.c_str());
    hMCstack->GetXaxis()->SetTitleSize(0.06);
    hMCstack->GetXaxis()->SetTitleOffset(0.6);
  }

  if (xAxisMin < xAxisMax) {
    if (data0_noData1 == 0) subpad_1->Update();  // to be done after Draw() to access pad parameters such as default axis range
    else c->Update();  
    hMCstack->GetXaxis()->SetRangeUser(xAxisMin,xAxisMax);
  }

  if (binDensity_flag == 0) hMCstack->GetYaxis()->SetTitle("events");
  else hMCstack->GetYaxis()->SetTitle("events / GeV");
  hMCstack->GetYaxis()->SetTitleSize(0.06);
  hMCstack->GetYaxis()->SetTitleOffset(0.8);
  hMCstack->GetYaxis()->CenterTitle();
  for (Int_t j = (nFiles-1); j >= 0; j--) {
    leg->AddEntry(hMC[j],Form("%s",MC_TexLabel[j].c_str()),"lf");
  }

  if (data0_noData1 == 0) {    
    hdata->SetMarkerStyle(8); // large dot
    hdata->Draw("EX0 SAME"); //X0 doesn't draw x error
    leg->AddEntry(hdata,Form("%s",data_TexLabel.c_str()),"p");
  }

  gStyle->SetStatStyle(0);
  leg->Draw(); 
  leg->SetMargin(0.3); 
  leg->SetBorderSize(0);

  if (data0_noData1 == 0) { // if using data, draw the ratio plot

    subpad_2->cd();
    ratioplot = new TH1D(*hdata);
    ratioplot->Divide(stackCopy);
    ratioplot->SetStats(0);
    ratioplot->SetTitle("");
    ratioplot->GetXaxis()->SetLabelSize(0.10);
    ratioplot->GetXaxis()->SetTitle(xAxisName.c_str());
    ratioplot->GetXaxis()->SetTitleSize(0.14);
    ratioplot->GetXaxis()->SetTitleOffset(0.8);
    ratioplot->GetYaxis()->SetLabelSize(0.10);
    ratioplot->GetYaxis()->SetTitle("data / MC");
    ratioplot->GetYaxis()->SetTitleSize(0.15);
    ratioplot->GetYaxis()->SetTitleOffset(0.3);
    ratioplot->GetYaxis()->CenterTitle();
    ratioplot->GetYaxis()->SetRangeUser(0.5,1.5);
    ratioplot->GetYaxis()->SetNdivisions(011);
    if (xAxisMin < xAxisMax) {
      //subpad_2->Update();  // to be done after Draw() to access pad parameters such as default axis range  
      ratioplot->GetXaxis()->SetRangeUser(xAxisMin,xAxisMax);
    }
    ratioplot->SetMarkerStyle(8);  //medium dot
    ratioplot->DrawCopy("E");  

  }

  c->SaveAs( (plotDirectoryPath + c->GetName() + plotFileExtension).c_str() );

}
Beispiel #17
0
void validation()
{
	msglvl[DBG] = SILENT;
	msglvl[INF] = VISUAL;
	msglvl[WRN] = VISUAL;
	msglvl[ERR] = VISUAL;
	msglvl[FAT] = VISUAL;

	TDirectory* oldDir = gDirectory; // remember old directory

	style();

	Int_t g4bin = (ng4bins/g4max+1); //==> g^4=1 ==> SSM !
	
	TString suffix = "";
	if(doTruth) suffix = "_truth";
	
	TString mctype  = (isMC11c) ? "mc11c" : "mc11a";
	
	// TString fBGname = "plots/ZP_2dtemplates_"+mctype+"_33st_overallEWkF_noInAmpSigEWkF_noHighMbins_wthOfficialZP_Xmass2000.root";
	// TString fBGname = "plots/ZP_2dtemplates_"+mctype+"_33st_noKKtmplates_overallEWkF_noInAmpSigEWkF_noTruth_wthOfficialZP_treeLevelMass_Xmass2000.root";
	// TString fBGname = "plots/ZP_2dtemplates_"+mctype+"_33st_noKKtmplates_overallEWkF_noInAmpSigEWkF_wthOfficialZP_treeLevelMass_Xmass2000.root";
	// TString fBGname = "plots/ZP_2dtemplates_mc11c_33st_noKKtmplates_overallEWkF_noInAmpSigEWkF_wthOfficialZP_fixedBWwidth_treeLevelMass_Xmass2000.root";
	// TString fBGname = "plots/ZP_2dtemplates_mc11c_33st_noKKtmplates_overallEWkF_noInAmpSigEWkF_noTruth_wthOfficialZP_treeLevelMass_Xmass2000.root";
	// TString fBGname = "plots/ZP_2dtemplates_"+mctype+"_33st_noKKtmplates_overallEWkF_noInAmpSigEWkF_noTruth_wthOfficialZP_treeLevelMass_Xmass2000.root";
	// TString fBGname = "plots/ZP_2dtemplates_"+mctype+"_33st_noKKtmplates_overallEWkF_noInAmpSigEWkF_noTruth_wthOfficialZP_fixedBWwidth_treeLevelMass_Xmass2000.root";

	TLegend* legR = new TLegend(0.15,0.75,0.35,0.85,NULL,"brNDC");
	legR->SetFillStyle(4000); //will be transparent
	legR->SetFillColor(0);
	legR->SetTextFont(42);
	TH1D* hDummy = new TH1D("","",1,0.,1.);
	hDummy->SetMarkerStyle(20);
	hDummy->SetMarkerSize(0.8);
	hDummy->SetMarkerColor(kBlack);
	if(!doResiduals) legR->AddEntry(hDummy,"#frac{template}{official}","lep");
	else             legR->AddEntry(hDummy,"#frac{template - official}{#sqrt{#delta^{2}template + #delta^{2}official}}","lep");
	
	TPaveText* ptxt = new TPaveText(0.145,0.35,0.245,0.55,"NDC");
	TText* txt;
	ptxt->SetTextSize(0.03);
	ptxt->SetBorderSize(0);
	ptxt->SetFillStyle(4000); //will be transparent
	ptxt->SetFillColor(0);
	ptxt->SetTextAlign(12);
	txt = ptxt->AddText("This range");
	txt = ptxt->AddText("is chopped");
	txt = ptxt->AddText("before the");
	txt = ptxt->AddText("template is");
	txt = ptxt->AddText("handed to");
	txt = ptxt->AddText("BAT (limit).");
	
	oldDir->cd();

	TString fBGname = "plots/validation/ZP_2dtemplates_mc11c_33st_noKKtmplates_wthOfficialZP_treeLevelMass_Xmass2000.root";
	TFile* fD = new TFile(fBGname,"READ");
	TH1D* hDY = NULL;
	if(doTruth) hDY = (TH1D*)fD->Get("hMass_DYmumu_truth")->Clone();
	else        hDY = (TH1D*)fD->Get("hMass_DYmumu")->Clone();
	hDY->SetLineColor(kMagenta-5);
	hDY->SetMarkerColor(kMagenta-5);

	oldDir->cd();

	TFile* fDYrozmin    = new TFile("plots/mass_plot_tables_3st.root","READ");
	TH1D* hDYrozmin = (TH1D*)fDYrozmin->Get("mass_log_dy")->Clone();
	hDYrozmin = (TH1D*)hGeV2TeV(hDYrozmin)->Clone();
	hDYrozmin = (TH1D*)hChopper(hDYrozmin,bins2chop)->Clone();
	oldDir->cd();
	TFile* f1dTemplates = new TFile("plots/ZpSignal_MM_MC11c_5points.root","READ");
	TObjArray* toarr1d = new TObjArray();
	toarr1d->Read("template");
	TMapTSP2TH1D h1dBrandeisTmpltMap;
	double Nflat = 399948;
	double sigmaflat = 4.3988E+07*nb2fb;
	double Lmcflat = Nflat/sigmaflat;
	double scale = luminosity/Lmcflat;
	TH1D* h1dTmp = NULL;
	h1dTmp = (TH1D*)((TObjArray*)toarr1d->At(0/*22*/))->Clone();
	h1dTmp->Scale(scale);
	h1dTmp = (TH1D*)hChopper(h1dTmp,bins2chop)->Clone();
	h1dTmp->Add(hDYrozmin);
	h1dBrandeisTmpltMap.insert( make_pair("1000",(TH1D*)resetErrors(h1dTmp)->Clone("1000")) );
	h1dTmp = NULL;
	h1dTmp = (TH1D*)((TObjArray*)toarr1d->At(1/*28*/))->Clone();
	h1dTmp->Scale(scale);
	h1dTmp = (TH1D*)hChopper(h1dTmp,bins2chop)->Clone();
	h1dTmp->Add(hDYrozmin);
	h1dBrandeisTmpltMap.insert( make_pair("1250",(TH1D*)resetErrors(h1dTmp)->Clone("1250")) );
	h1dTmp = NULL;
	h1dTmp = (TH1D*)((TObjArray*)toarr1d->At(2/*34*/))->Clone();
	h1dTmp->Scale(scale);
	h1dTmp = (TH1D*)hChopper(h1dTmp,bins2chop)->Clone();
	h1dTmp->Add(hDYrozmin);
	h1dBrandeisTmpltMap.insert( make_pair("1500",(TH1D*)resetErrors(h1dTmp)->Clone("1500")) );
	h1dTmp = NULL;
	h1dTmp = (TH1D*)((TObjArray*)toarr1d->At(3/*40*/))->Clone();
	h1dTmp->Scale(scale);
	h1dTmp = (TH1D*)hChopper(h1dTmp,bins2chop)->Clone();
	h1dTmp->Add(hDYrozmin);
	h1dBrandeisTmpltMap.insert( make_pair("1750",(TH1D*)resetErrors(h1dTmp)->Clone("1750")) );
	h1dTmp = NULL;
	h1dTmp = (TH1D*)((TObjArray*)toarr1d->At(4/*47*/))->Clone();
	h1dTmp->Scale(scale);
	h1dTmp = (TH1D*)hChopper(h1dTmp,bins2chop)->Clone();
	h1dTmp->Add(hDYrozmin);
	h1dBrandeisTmpltMap.insert( make_pair("2000",(TH1D*)resetErrors(h1dTmp)->Clone("2000")) );

	oldDir->cd();

	TMapTSP2TH1D h1Map;
	h1Map.insert( make_pair("1000o", (TH1D*)fD->Get("hMass_Zprime_SSM1000"+suffix)->Clone()) );
	h1Map.insert( make_pair("1000t", (TH1D*)fD->Get("hMass_Zprime_SSM1000_template"+suffix)->Clone()) );
	if(isMC11c)
	{
		h1Map.insert( make_pair("1250o", (TH1D*)fD->Get("hMass_Zprime_SSM1250"+suffix)->Clone()) );
		h1Map.insert( make_pair("1250t", (TH1D*)fD->Get("hMass_Zprime_SSM1250_template"+suffix)->Clone()) );
	}
	h1Map.insert( make_pair("1500o", (TH1D*)fD->Get("hMass_Zprime_SSM1500"+suffix)->Clone()) );
	h1Map.insert( make_pair("1500t", (TH1D*)fD->Get("hMass_Zprime_SSM1500_template"+suffix)->Clone()) );
	h1Map.insert( make_pair("1750o", (TH1D*)fD->Get("hMass_Zprime_SSM1750"+suffix)->Clone()) );
	h1Map.insert( make_pair("1750t", (TH1D*)fD->Get("hMass_Zprime_SSM1750_template"+suffix)->Clone()) );
	h1Map.insert( make_pair("2000o", (TH1D*)fD->Get("hMass_Zprime_SSM2000"+suffix)->Clone()) );
	h1Map.insert( make_pair("2000t", (TH1D*)fD->Get("hMass_Zprime_SSM2000_template"+suffix)->Clone()) );

	TMapTSP2TH1D h1rMap;
	h1rMap.insert( make_pair("1000", (TH1D*)fD->Get("hMass_Zprime_SSM1000"+suffix)->Clone()) );
	if(isMC11c) h1rMap.insert( make_pair("1250", (TH1D*)fD->Get("hMass_Zprime_SSM1250"+suffix)->Clone()) );
	h1rMap.insert( make_pair("1500", (TH1D*)fD->Get("hMass_Zprime_SSM1500"+suffix)->Clone()) );
	h1rMap.insert( make_pair("1750", (TH1D*)fD->Get("hMass_Zprime_SSM1750"+suffix)->Clone()) );
	h1rMap.insert( make_pair("2000", (TH1D*)fD->Get("hMass_Zprime_SSM2000"+suffix)->Clone()) );
	for(TMapTSP2TH1D::iterator it=h1rMap.begin() ; it!=h1rMap.end() ; ++it)
	{
		it->second->Reset();
		if(!doResiduals) it->second->Divide(h1Map[it->first+"o"],h1Map[it->first+"t"],1.,1.,"B");
		else             residuals(h1Map[it->first+"o"], h1Map[it->first+"t"], it->second);
		
		// for(Int_t i=0 ; i<=it->second->GetNbinsX()+1 ; i++) it->second->SetBinError(i,0);
		it->second->SetMarkerStyle(20);
		it->second->SetMarkerSize(0.5);
		it->second->GetXaxis()->SetLabelSize(0.073);
		it->second->GetYaxis()->SetLabelSize(0.073);
		it->second->GetXaxis()->SetTitleSize(0.073);
		it->second->GetYaxis()->SetTitleSize(0.073);
		it->second->SetTitleSize(0.075);
		it->second->GetYaxis()->SetTitleOffset(0.5);
		if(!doResiduals)
		{
			it->second->SetMinimum(0.2);
			it->second->SetMaximum(1.8);
		}
		else
		{
			it->second->SetMinimum(-5.);
			it->second->SetMaximum(+5.);
		}
		it->second->SetTitle("");
		if(!doResiduals) it->second->GetYaxis()->SetTitle("ratio");
		else             it->second->GetYaxis()->SetTitle("residuals");
	}

	TMapTSP2TGAE poissonGraphMap;
	TMapTSP2TLeg legMap;


	_INFO("");

	oldDir->cd();

	fD->cd();	
	TH1D* h1Template = (TH1D*)fD->Get("hMass_DYmumu"+suffix)->Clone();
	h1Template->Reset();
	TObjArray* toarr = new TObjArray();
	if(doTruth) toarr->Read("truth_template2d");
	else        toarr->Read("template2d");
	TH2D* h2SSM2000 = (TH2D*)((TObjArray*)toarr->At(0))->Clone("hMass"+suffix+"_Zprime_SSM2000_template2d");
	for(Int_t bin=1 ; bin<=h2SSM2000->GetNbinsX() ; bin++)
	{
		h1Template->SetBinContent(bin, h2SSM2000->GetBinContent(bin,g4bin));
		h1Template->SetBinError(bin, h2SSM2000->GetBinError(bin,g4bin));
	}
	h1Template->SetLineColor(kViolet);
	h1Template->SetLineWidth(1);
	h1Template->SetMarkerStyle(20);
	h1Template->SetMarkerSize(0.3);
	h1Template->SetMarkerColor(kViolet);
	// the functions
	h2Template = (TH2D*)h2SSM2000->Clone();
	vector<TF1*> vfunc;
	unsigned int nmllbins = h2Template->GetNbinsX();
	for(unsigned int mll=1 ; mll<=(nmllbins-bins2chop) ; mll++) // 1...(56-9 = 47)
	{
		TString mllname = (TString)_s(mll);
		TString mllval  = (TString)_s(h2Template->GetXaxis()->GetBinCenter(mll+bins2chop));
		
		TF1* f = new TF1("fNominal_mll"+mllname,fTH1toTF1,g4min,g4max,1);
		f->SetParameter(0,mll);
		f->SetParNames("mll");
		// f->SetLineColor(kBlue);
		// f->SetLineWidth(1);
		f->SetNpx(400);
		vfunc.push_back(f);
	}
	TGraph* graphDY = new TGraph();
	graphDY->SetMarkerStyle(25);
	graphDY->SetMarkerSize(0.6);
	graphDY->SetMarkerColor(kGreen+2);
	TGraph* graphSSM = new TGraph();
	graphSSM->SetMarkerStyle(24);
	graphSSM->SetMarkerSize(0.6);
	graphSSM->SetMarkerColor(kOrange+8);
	for(unsigned int i=0 ; i<vfunc.size() ; i++)
	{
		double DY = vfunc[i]->Eval(0.0);
		double SSM = vfunc[i]->Eval(1.0);
		graphDY->SetPoint(i,h2Template->GetXaxis()->GetBinCenter(bins2chop+i+1),DY);
		graphSSM->SetPoint(i,h2Template->GetXaxis()->GetBinCenter(bins2chop+i+1),SSM);
	}
	
	
	oldDir->cd();

	TObjArray* toarr1dTLV = new TObjArray();
	TMapTSP2TH1D h1dTlvTmpltMap;
	TFile* fT = NULL;
	TString fTname = "plots/validation/ZP_2dtemplates_mc11c_33st_noInterference_noKKtmplates_noOverallEWkF_wthOfficialZP_treeLevelMass_Xmass";
	
	fT = new TFile(fTname+"1000.root","READ");
	toarr1dTLV->Read("template");
	h1dTmp = (TH1D*)((TObjArray*)toarr1dTLV->At(0))->Clone();
	h1dTmp->Add(hDY);
	h1dTlvTmpltMap.insert( make_pair("1000",(TH1D*)resetErrors(h1dTmp)->Clone("1000")) );
	fT = new TFile(fTname+"1250.root","READ");
	toarr1dTLV->Read("template");
	h1dTmp = (TH1D*)((TObjArray*)toarr1dTLV->At(0))->Clone();
	h1dTmp->Add(hDY);
	h1dTlvTmpltMap.insert( make_pair("1250",(TH1D*)resetErrors(h1dTmp)->Clone("1250")) );
	fT = new TFile(fTname+"1500.root","READ");
	toarr1dTLV->Read("template");
	h1dTmp = (TH1D*)((TObjArray*)toarr1dTLV->At(0))->Clone();
	h1dTmp->Add(hDY);
	h1dTlvTmpltMap.insert( make_pair("1500",(TH1D*)resetErrors(h1dTmp)->Clone("1500")) );
	fT = new TFile(fTname+"1750.root","READ");
	toarr1dTLV->Read("template");
	h1dTmp = (TH1D*)((TObjArray*)toarr1dTLV->At(0))->Clone();
	h1dTmp->Add(hDY);
	h1dTlvTmpltMap.insert( make_pair("1750",(TH1D*)resetErrors(h1dTmp)->Clone("1750")) );
	fT = new TFile(fTname+"2000.root","READ");
	toarr1dTLV->Read("template");
	h1dTmp = (TH1D*)((TObjArray*)toarr1dTLV->At(0))->Clone();
	h1dTmp->Add(hDY);
	h1dTlvTmpltMap.insert( make_pair("2000",(TH1D*)resetErrors(h1dTmp)->Clone("2000")) );

	oldDir->cd();
	
	
	for(TMapTSP2TH1D::iterator it=h1Map.begin() ; it!=h1Map.end() ; ++it)
	{
		if(it->first.Contains("o"))
		{
			TString name = it->first;
			name.ReplaceAll("o","");
			it->second->SetFillColor(kAzure-9);
			if(doTruth) it->second->SetTitle("m_{Z'} = "+name+" GeV (truth)");
			else        it->second->SetTitle("m_{Z'} = "+name+" GeV");
		}
		if(it->first.Contains("t"))
		{
			//TGraphAsymmErrors* poisson(TH1D* h)
			it->second->SetLineColor(kBlue);
			it->second->SetMarkerStyle(20);
			it->second->SetMarkerSize(0.4);
			it->second->SetMarkerColor(kBlue);
			it->second->SetLineWidth(1);
			
			TString name = it->first;
			name.ReplaceAll("t","");
			poissonGraphMap.insert( make_pair(name, (TGraphAsymmErrors*)poisson(it->second)->Clone()) );
			poissonGraphMap[name]->SetMarkerStyle(20);
			poissonGraphMap[name]->SetMarkerSize(0.3);
			poissonGraphMap[name]->SetMarkerColor(kBlue);
			poissonGraphMap[name]->SetLineWidth(1);
			poissonGraphMap[name]->SetLineColor(kBlue);
		}
	}	

	Double_t yLine = (!doResiduals) ? 1. : 0.;

	TLine* line = new TLine(0.07,yLine,3.,yLine);	
	line->SetLineColor(kRed);
	line->SetLineWidth(2);
	
	TMapTSP2TCNV cnvMap;
	cnvMap.insert( make_pair("1000", new TCanvas("1000","1000",600,550)) );
	if(isMC11c) cnvMap.insert( make_pair("1250", new TCanvas("1250","1250",600,550)) );
	cnvMap.insert( make_pair("1500", new TCanvas("1500","1500",600,550)) );
	cnvMap.insert( make_pair("1750", new TCanvas("1750","1750",600,550)) );
	cnvMap.insert( make_pair("2000", new TCanvas("2000","2000",600,550)) );
	for(TMapTSP2TCNV::iterator it=cnvMap.begin() ; it!=cnvMap.end() ; ++it)
	{
		_INFO("starting "+(string)it->first);
		if(it->first=="2000") legMap.insert( make_pair(it->first, new TLegend(0.35,0.55,0.83,0.84,NULL,"brNDC")) );
		else                  legMap.insert( make_pair(it->first, new TLegend(0.35,0.60,0.83,0.84,NULL,"brNDC")) );
		legMap[it->first]->SetFillStyle(4000); //will be transparent
		legMap[it->first]->SetFillColor(0);
		legMap[it->first]->SetTextFont(42);
		legMap[it->first]->AddEntry(h1Map[it->first+"o"],"Official Z'_{SSM}","F");
		legMap[it->first]->AddEntry(hDY,"Official DY#mu#mu","lep");
		legMap[it->first]->AddEntry(h1Map[it->first+"t"],"ME^{2} method: Template w/o couplings scale","lep");
		if(it->first=="2000")
		{
			legMap[it->first]->AddEntry(h1Template,"ME^{2} method: Template histogram at  #it{g=1} (SSM)","lep");
			legMap[it->first]->AddEntry(graphSSM,  "ME^{2} method: Template function  at  #it{g=1} (SSM)","p");
			legMap[it->first]->AddEntry(graphDY,   "ME^{2} method: Template function  at  #it{g=0} (DY)","p");
		}
		if(!doTruth)
		{
			h1dTlvTmpltMap[it->first]->SetLineColor(kCyan+2);
			h1dTlvTmpltMap[it->first]->SetMarkerColor(kCyan+2);
			h1dTlvTmpltMap[it->first]->SetMarkerStyle(5);
			h1dTlvTmpltMap[it->first]->SetMarkerSize(0.5);
			legMap[it->first]->AddEntry(h1dTlvTmpltMap[it->first],"ME^{2} method: DY+Template (no interference)","p");
		
			h1dBrandeisTmpltMap[it->first]->SetLineColor(kRed);
			h1dBrandeisTmpltMap[it->first]->SetMarkerColor(kRed);
			h1dBrandeisTmpltMap[it->first]->SetMarkerStyle(27);
			h1dBrandeisTmpltMap[it->first]->SetMarkerSize(0.5);
			legMap[it->first]->AddEntry(h1dBrandeisTmpltMap[it->first],"Flat Z' method: DY+Template (no interference)","p");
		}

		it->second->Divide(1,2);
		TVirtualPad* ph = it->second->cd(1);
		TVirtualPad* pr = it->second->cd(2);	
		ph->SetPad(0.00, 0.35, 1.00, 1.00);
		pr->SetPad(0.00, 0.00, 1.00, 0.35);
		ph->SetBottomMargin(0.012);
		pr->SetBottomMargin(0.20);
		pr->SetTopMargin(0.012);
		
		ph->cd();
		ph->Draw();
		ph->SetTicks(1,1);
		ph->SetLogy();
		ph->SetLogx();
		// h1Map[it->first+"o"]->SetMaximum( h1Map[it->first+"t"]->GetMaximum()*1.5 );
		// h1Map[it->first+"o"]->Draw();
		TH1D* hTmpNoErr = (TH1D*)resetErrors(h1Map[it->first+"o"])->Clone();
		hTmpNoErr->SetMaximum( h1Map[it->first+"t"]->GetMaximum()*1.5 );
		hTmpNoErr->SetLineStyle(1);
		hTmpNoErr->SetLineColor(kBlack);
		hTmpNoErr->SetFillColor(kAzure-9);
		hTmpNoErr->Draw();
		TH1D* hTmpErr = (TH1D*)ShiftLog(h1Map[it->first+"o"],0.2)->Clone();
		hTmpErr->SetFillStyle(4000); //will be transparent
		hTmpErr->SetFillColor(0);
		hTmpErr->DrawCopy("epx0SAMES");
		hDY->Draw("SAMES");
		h1Map[it->first+"t"]->Draw("epSAMES");
		//poissonGraphMap[it->first]->Draw("pSAMES");
		if(it->first=="2000")
		{
			graphDY->Draw("SAMESp");
			graphSSM->Draw("SAMESp");
			h1Template->Draw("epSAMES");
		}
		_INFO("");
		h1dTlvTmpltMap[it->first]->Draw("SAMESp");
		h1dBrandeisTmpltMap[it->first]->Draw("SAMESp");
		
		TLine* chopline = new TLine(0.12805,getYmin(h1Map[it->first+"o"]),0.12805,7.e5);
		chopline->SetLineStyle(2);
		chopline->SetLineColor(kBlack);
		chopline->Draw("SAMES");
		ptxt->Draw("SAMES");
		
		legMap[it->first]->Draw("SAMES");
		ph->RedrawAxis();
		ph->Update();

		_INFO("");

		pr->cd();
		pr->Draw();
		pr->SetTicks(1,1);
		pr->SetGridy();
		pr->SetLogx();
		h1rMap[it->first]->Draw("ep");
		line->Draw("SAMES");
		h1rMap[it->first]->Draw("epSAMES");
		legR->Draw("SAMES");
		pr->RedrawAxis();
		pr->Update();

		unsigned int savestate = 1;
		if(it->first=="1000")      savestate = 0;
		else if(it->first=="2000") savestate = 2;
		else                       savestate = 1;
		TString testType = (doResiduals) ? "_residuals" : "_ratio";
		mutype   = (doTruth)     ? "_truth"     : "_recon";
		savemultipdf(it->second, "plots/validation/validation"+mutype+testType+"_"+mctype+"_all.pdf", savestate);
		saveas(it->second, "plots/validation/validation"+mutype+testType+"_"+mctype+"_"+it->first);
		
		TCanvas* c = new TCanvas(it->first,"",600,400);
		c->cd();
		c->Draw();
		c->SetTicks(1,1);
		c->SetLogy();
		c->SetLogx();
		hTmpNoErr->Draw();
		hTmpErr->DrawCopy("epx0SAMES");
		hDY->Draw("SAMES");
		h1Map[it->first+"t"]->Draw("epSAMES");
		//poissonGraphMap[it->first]->Draw("pSAMES");
		if(it->first=="2000")
		{
			graphDY->Draw("SAMESp");
			graphSSM->Draw("SAMESp");
			h1Template->Draw("epSAMES");
		}
		h1dTlvTmpltMap[it->first]->Draw("SAMESp");
		h1dBrandeisTmpltMap[it->first]->Draw("SAMESp");
		legMap[it->first]->Draw("SAMES");
		chopline->Draw("SAMES");
		ptxt->Draw("SAMES");
		c->RedrawAxis();
		c->Update();
		saveas(c,"plots/validation/validation_"+it->first+"_"+mutype+testType);
		
		_INFO("done "+(string)it->first);
	}
}
Beispiel #18
0
void Post_Exodus(char *filename)
{
    gStyle->SetOptStat(0);

    exodusfile=new TFile(filename,"READ");
    exodusfile->cd();

    TCanvas *c1 = new TCanvas("c1","Input Particles Spectrum");
    c1->SetLogy();

    TH1D *pi0pt=realpi0pt->Clone();
    TH1D *etapt=realetapt->Clone();
    TH1D *etaprimept=realetaprimept->Clone();
    TH1D *omegapt=realomegapt->Clone();

    pi0pt->SetMarkerStyle(20);
    pi0pt->SetMarkerColor(kBlack);

    etapt->SetMarkerStyle(21);
    etapt->SetMarkerColor(kRed);

    etaprimept->SetMarkerStyle(22);
    etaprimept->SetMarkerColor(kBlue);

    omegapt->SetMarkerStyle(23);
    omegapt->SetMarkerColor(kGreen);

    pi0pt->Rebin(10);
    etapt->Rebin(10);
    etaprimept->Rebin(10);
    omegapt->Rebin(10);

    etapt->Scale(0.1);
    etaprimept->Scale(0.01);
    omegapt->Scale(0.001);

    TAxis *yaxis=pi0pt->GetYaxis();
    yaxis->SetTitle("dN/dp_{T}dy");
    TAxis *xaxis=pi0pt->GetXaxis();
    xaxis->SetTitle("p_{T} [Gev/c]");

    pi0pt->Draw("e");
    etapt->Draw("esame");
    etaprimept->Draw("esame");
    omegapt->Draw("esame");

    TLatex *pi0=new TLatex(8,5000,"Min-Bias: #pi^{0},");
    pi0->SetTextColor(kBlack);

    TLatex *eta=new TLatex(16,5000,"#eta,");
    eta->SetTextColor(kRed);

    TLatex *etaprime=new TLatex(18,5000,"#eta^{'},");
    etaprime->SetTextColor(kBlue);

    TLatex *omega=new TLatex(20,5000,"#omega");
    omega->SetTextColor(kGreen);

    pi0->Draw();
    eta->Draw();
    etaprime->Draw();
    omega->Draw();

    TCanvas *c2 = new TCanvas("c2","eta to pi0 ratio");

    TH1D *etaratio = realetapt->Clone();

    etaratio->Rebin(10);
    etaratio->Divide(pi0pt);

    etaratio->SetMarkerStyle(21);
    etaratio->SetMarkerColor(kRed);

    TH1D *etaprimeratio = realetaprimept->Clone();

    etaprimeratio->SetMarkerStyle(22);
    etaprimeratio->SetMarkerColor(kBlue);

    etaprimeratio->Rebin(10);
    etaprimeratio->Divide(pi0pt);

    TH1D *omegaratio = realomegapt->Clone();
    omegaratio->SetMarkerStyle(23);
    omegaratio->SetMarkerColor(kGreen);

    omegaratio->Rebin(10);
    omegaratio->Divide(pi0pt);

    TAxis *yaxis=etaprimeratio->GetYaxis();
    yaxis->SetTitle("#eta(#eta^{'},#omega) / #pi^{0}");
    TAxis *xaxis=etaprimeratio->GetXaxis();
    xaxis->SetTitle("p_{T} [Gev/c]");

    TLegend *leg = new TLegend(0.5,0.2,0.6,0.4);

    char dummy[500];

    sprintf(dummy,"#eta/#pi^{0}");
    leg->AddEntry(etaratio,dummy,"p");

    sprintf(dummy,"#eta^{'}/#pi^{0}");
    leg->AddEntry(etaprimeratio,dummy,"p");

    sprintf(dummy,"#omega/#pi^{0}");
    leg->AddEntry(omegaratio,dummy,"p");

    etaprimeratio->SetTitle("#eta, #eta^{'}, #omega ratio to #pi^{0}");
    etaprimeratio->SetAxisRange(0.0,15.0);
    etaprimeratio->Draw("e");
    leg->Draw();
    omegaratio->Draw("esame");
    etaratio->Draw("esame");

    TCanvas *c3 = new TCanvas("c3","MC ratio break-down");
    c3->SetLogy();

    TH1D *allgamma = gammapt->Clone();

    allgamma->Rebin(10);
    pi0gamma->Rebin(10);
    etagamma->Rebin(10);
    etaprimegamma->Rebin(10);
    omegagamma->Rebin(10);

    TH1D *taggedgamma = pi0gamma->Clone();

    allgamma->Divide(pi0pt);
    pi0gamma->Divide(pi0pt);
    etagamma->Divide(pi0pt);
    etaprimegamma->Divide(pi0pt);
    omegagamma->Divide(pi0pt);

    allgamma->SetLineColor(kBlack);
    pi0gamma->SetLineColor(kRed);
    etagamma->SetLineColor(kBlue);
    etaprimegamma->SetLineColor(kGreen);
    omegagamma->SetLineColor(6);

    TAxis *yaxis=allgamma->GetYaxis();
    yaxis->SetTitle("#gamma / #pi^{0}");
    TAxis *xaxis=allgamma->GetXaxis();
    xaxis->SetTitle("p_{T} [Gev/c]");


    allgamma->Draw("e");
    pi0gamma->Draw("esame");
    etagamma->Draw("esame");
    etaprimegamma->Draw("esame");
    omegagamma->Draw("esame");

    TCanvas *c4 = new TCanvas("c4","Our Ratio");

    TH1D *allgamma2 = gammapt->Clone();

    allgamma2->Rebin(10);
    allgamma2->Divide(taggedgamma);

    for(int i = 1; i <= allgamma2->GetNbinsX(); i++)
        allgamma2->SetBinError(i,allgamma2->GetBinError(i)/sqrt(2));

    TAxis *yaxis=allgamma2->GetYaxis();
    yaxis->SetTitle("#gamma / #pi^{0}(#gamma)");
    TAxis *xaxis=allgamma2->GetXaxis();
    xaxis->SetTitle("p_{T} [Gev/c]");

    TLatex *ourratio=new TLatex(6.0, 1.125, "Min-Bias (N(#gamma_{1}^{hadron})/N(#gamma_{#pi^{0}}))_{MC}");

    allgamma2->SetTitle("#gamma_{1}^{hadron}/#gamma_{#pi^{0}} in full space");
    allgamma2->SetAxisRange(0.0,15.0);

    allgamma2->SetMarkerStyle(20);
    allgamma2->Draw();
    ourratio->Draw();
}
Beispiel #19
0
void draw_Src(TChain *tMc, TChain *tExpA, TChain *tExpB, const char *name, const char *fname, double kSP = 0.5, double kRndm = 0.0)
{
	char str[256];
	double rAB;
	long NA, NB;
	
	gStyle->SetOptStat("i");
	gStyle->SetOptFit(1);
//	gStyle->SetOptStat(0);
//	gStyle->SetOptFit(0);
	gStyle->SetTitleXSize(0.05);
	gStyle->SetTitleYSize(0.05);
	gStyle->SetLabelSize(0.05);
	gStyle->SetPadLeftMargin(0.15);
	gStyle->SetPadBottomMargin(0.15);
//	gStyle->SetLineWidth(4);
	
	sprintf(str, "Monte Carlo energy deposit in %s decay;E, MeV", name);
	TH1D *hMc = new TH1D("hMc", str, 70, 0, 7);
	sprintf(str, "Monte Carlo SiPM energy deposit in %s decay;E, MeV", name);
	TH1D *hMcSiPM = new TH1D("hMcSiPM", str, 35, 0, 7);
	sprintf(str, "Monte Carlo PMT energy deposit in %s decay;E, MeV", name);
	TH1D *hMcPMT = new TH1D("hMcPMT", str, 35, 0, 7);
	sprintf(str, "Monte Carlo energy deposit in %s decay with random %2.0f%%;E, MeV", name, kRndm*100);
	TH1D *hMcR = new TH1D("hMcR", str, 70, 0, 7);
	sprintf(str, "Monte Carlo number of hits from %s decay", name);
	TH1D *hMcHits = new TH1D("hMcHits", str, 20, 0, 20);
	TH2D *hXY = new TH2D("hXY", "XY distribution of gamma flash center;X, cm;Y, cm", 25, 0, 100, 25, 0, 100);
	sprintf(str, "DANSS energy deposit in %s decay;E, MeV", name);
	TH1D *hExpA = new TH1D("hExpA", str, 70, 0, 7);
	TH1D *hExpB = new TH1D("hExpB", str, 70, 0, 7);
	TH1D *hExpC = new TH1D("hExpC", str, 70, 0, 7);
	sprintf(str, "SiPM energy deposit in %s decay;E, MeV", name);
	TH1D *hExpSiPMA = new TH1D("hExpSiPMA", str, 70, 0, 7);
	TH1D *hExpSiPMB = new TH1D("hExpSiPMB", str, 70, 0, 7);
	TH1D *hExpSiPMC = new TH1D("hExpSiPMC", str, 70, 0, 7);
	sprintf(str, "PMT energy deposit in %s decay;E, MeV", name);
	TH1D *hExpPMTA = new TH1D("hExpPMTA", str, 70, 0, 7);
	TH1D *hExpPMTB = new TH1D("hExpPMTB", str, 70, 0, 7);
	TH1D *hExpPMTC = new TH1D("hExpPMTC", str, 70, 0, 7);
	sprintf(str, "Number of hits from %s decay", name);
	TH1D *hHitsA = new TH1D("hHitsA", str, 20, 0, 20);
	TH1D *hHitsB = new TH1D("hHitsB", str, 20, 0, 20);
	TH1D *hHitsC = new TH1D("hHitsC", str, 20, 0, 20);
	
	TH1D *hTmpA = new TH1D("hTmpA", "Normalization counts A", 100, 0, 1000);
	TH1D *hTmpB = new TH1D("hTmpB", "Normalization counts B", 100, 0, 1000);

	TCut cxyz("NeutronX[0] >= 0 && NeutronX[1] >= 0 && NeutronX[2] >= 0");
	TCut cz50("(NeutronX[2] - 49.5) * (NeutronX[2] - 49.5) < 100");
	TCut ccc("(NeutronX[0] - 48) * (NeutronX[0] - 48) + (NeutronX[1] - 48) * (NeutronX[1] - 48) + (NeutronX[2] - 49.5) * (NeutronX[2] - 49.5) < 400");
	TCut cVeto("VetoCleanHits < 2 && VetoCleanEnergy < 4");
	TCut cn("SiPmCleanHits > 5");
	
	sprintf(str, "%6.4f*SiPmCleanEnergy+%6.4f*PmtCleanEnergy", kSP, 1-kSP);
	tMc->Project("hMc", str, cxyz && ccc && cVeto && cn);
	tMc->Project("hMcSiPM", "SiPmCleanEnergy", cxyz && ccc && cVeto && cn);
	tMc->Project("hMcPMT", "PmtCleanEnergy", cxyz && ccc && cVeto && cn);
	sprintf(str, "MyRandom::GausAdd(%6.4f*SiPmCleanEnergy+%6.4f*PmtCleanEnergy, %6.4f)", kSP, 1-kSP, kRndm);
	tMc->Project("hMcR", str, cxyz && ccc && cVeto && cn);
	tMc->Project("hMcHits", "SiPmCleanHits", cxyz && ccc && cVeto);
	
	sprintf(str, "%6.4f*SiPmCleanEnergy+%6.4f*PmtCleanEnergy", kSP, 1-kSP);
	tExpA->Project("hXY", "NeutronX[1]+2:NeutronX[0]+2", cxyz && cz50 && cVeto && cn);
	tExpA->Project("hExpA", str, cxyz && ccc && cVeto && cn);
	tExpB->Project("hExpB", str, cxyz && ccc && cVeto && cn);
	tExpA->Project("hExpSiPMA", "SiPmCleanEnergy", cxyz && ccc && cVeto && cn);
	tExpB->Project("hExpSiPMB", "SiPmCleanEnergy", cxyz && ccc && cVeto && cn);
	tExpA->Project("hExpPMTA", "PmtCleanEnergy", cxyz && ccc && cVeto && cn);
	tExpB->Project("hExpPMTB", "PmtCleanEnergy", cxyz && ccc && cVeto && cn);
	tExpA->Project("hHitsA", "SiPmCleanHits", cxyz && ccc && cVeto);
	tExpB->Project("hHitsB", "SiPmCleanHits", cxyz && ccc && cVeto);
	NA = tExpA->Project("hTmpA", "SiPmCleanEnergy", "(SiPmCleanEnergy + PmtCleanEnergy) / 2 > 100");
	NB = tExpB->Project("hTmpB", "SiPmCleanEnergy", "(SiPmCleanEnergy + PmtCleanEnergy) / 2 > 100");
	
	rAB = 1.0 * NA / NB;
	printf("NA = %ld    NB = %ld    rAB = %f\n", NA, NB, rAB);
	
	hMc->Sumw2();
	hMcSiPM->Sumw2();
	hMcPMT->Sumw2();
	hMcR->Sumw2();
	hMcHits->Sumw2();
	hExpA->Sumw2();
	hExpB->Sumw2();
	hExpSiPMA->Sumw2();
	hExpSiPMB->Sumw2();
	hExpPMTA->Sumw2();
	hExpPMTB->Sumw2();
	hHitsA->Sumw2();
	hHitsB->Sumw2();
	
	hExpC->Add(hExpA, hExpB, 1.0, -rAB);
	hExpSiPMC->Add(hExpSiPMA, hExpSiPMB, 1.0, -rAB);
	hExpPMTC->Add(hExpPMTA, hExpPMTB, 1.0, -rAB);
	hHitsC->Add(hHitsA, hHitsB, 1.0, -rAB);
	hMcHits->Scale(hHitsC->Integral() / hMcHits->Integral());
	hMcR->Scale(hExpC->Integral() / hMcR->Integral());

	hMc->GetYaxis()->SetLabelSize(0.05);
	hMcSiPM->GetYaxis()->SetLabelSize(0.05);
	hMcPMT->GetYaxis()->SetLabelSize(0.05);
	hMcR->GetYaxis()->SetLabelSize(0.05);
	hMcR->SetLineColor(kRed);
	hMcHits->GetYaxis()->SetLabelSize(0.05);
	hMcHits->SetLineColor(kRed);
	hMcHits->SetMarkerColor(kRed);
	hMcHits->SetMarkerStyle(kFullCircle);
	hXY->GetXaxis()->SetLabelSize(0.045);
	hXY->GetYaxis()->SetLabelSize(0.045);
	hXY->GetZaxis()->SetLabelSize(0.045);
	hExpC->GetYaxis()->SetLabelSize(0.05);
	hExpC->SetLineWidth(2);
	hExpC->SetLineColor(kBlue);
	hExpSiPMC->GetYaxis()->SetLabelSize(0.05);
	hExpPMTC->GetYaxis()->SetLabelSize(0.05);
	hHitsC->GetYaxis()->SetLabelSize(0.05);
	hHitsC->SetLineColor(kBlue);
	hHitsC->SetMarkerColor(kBlue);
	hHitsC->SetMarkerStyle(kFullSquare);

	hMcHits->SetStats(0);
	hHitsC->SetStats(0);
	
	TLegend *lg = new TLegend(0.65, 0.8, 0.95, 0.93);
	lg->AddEntry(hMcHits, "Monte Carlo", "L");
	lg->AddEntry(hHitsC,  "DANSS", "LP");
	lg->SetTextSize(0.035);
	
	TCanvas *cMc = new TCanvas("cMc", "Monte Carlo", 1200, 800);
	cMc->Divide(2, 2);
	cMc->cd(1);
	hMc->Fit("gaus", "", "", 1.5, 3.5);
	cMc->cd(2);
	hMcSiPM->Fit("gaus", "", "", 1.5, 3.5);
	cMc->cd(3);
	hMcPMT->Fit("gaus", "", "", 1.5, 3.5);
	cMc->cd(4);
	hMcR->Fit("gaus", "", "", 1.5, 3.5);
	sprintf(str, "%s.pdf(", fname);
	cMc->SaveAs(str);
	
	TCanvas *cExp = new TCanvas("cExp", "Data", 1200, 800);
	cExp->Divide(2, 2);
	cExp->cd(1);
	hExpC->Fit("gaus", "", "", 1.5, 3.5);
	cExp->cd(2);
	hExpSiPMC->Fit("gaus", "", "", 1.5, 3.5);
	cExp->cd(3);
	hExpPMTC->Fit("gaus", "", "", 1.5, 3.5);
	cExp->cd(4);
	hXY->Draw("colz");
	sprintf(str, "%s.pdf", fname);
	cExp->SaveAs(str);

	TCanvas *cHits = new TCanvas("cHits", "Hits", 1200, 800);
	cHits->Divide(2, 1);
	cHits->cd(1);
	hHitsC->Draw();
	hMcHits->Draw("same,hist");
	lg->Draw();
	cHits->cd(2);
	hExpC->Draw();
	hMcR->Draw("same,hist");
	cHits->Update();
	sprintf(str, "%s.pdf)", fname);
	cHits->SaveAs(str);

	sprintf(str, "%s.root", fname);
	TFile *f = new TFile(str, "RECREATE");
	if (f->IsOpen()) {
		f->cd();
		hMc->Write();
		hMcSiPM->Write();
		hMcPMT->Write();
		hMcR->Write();
		hMcHits->Write();
		hXY->Write();
		hExpA->Write();
		hExpB->Write();
		hExpC->Write();
		hExpSiPMA->Write();
		hExpSiPMB->Write();
		hExpSiPMC->Write();
		hExpPMTA->Write();
		hExpPMTB->Write();
		hExpPMTC->Write();
		hHitsA->Write();
		hHitsB->Write();
		hHitsC->Write();
		f->Close();
	}
	
	TCanvas *cPRL = new TCanvas("PRL", "PRL", 800, 800);
	cPRL->SetLeftMargin(0.17);
	cPRL->SetRightMargin(0.03);
	cPRL->SetTopMargin(0.03);
	cPRL->SetBottomMargin(0.10);
	hExpC->SetLineColor(kBlack);
	hExpC->GetXaxis()->SetRange(0, 50);
	hExpC->SetTitle(";E, MeV;Events/100 keV");
	hExpC->SetStats(0);
	hExpC->GetYaxis()->SetTitleOffset(1.7);
	hExpC->Draw();
	hMcR->Draw("hits,same");
	lg->Draw();
	sprintf(str, "%s-prl.pdf", fname);
	cPRL->SaveAs(str);
}
Beispiel #20
0
void PlotTrkPt()
{
  gROOT->LoadMacro("$LOCAL/include/TUntilsOpHisto.h");
  gROOT->LoadMacro("$LOCAL/include/TUntilsAliFigs.h");
  gROOT->LoadMacro("$LOCAL/include/TUntilsPlotStd.h"); SetStyle();
//=============================================================================

  TFile *file = TFile::Open("data/AnalysisResults_vac_JetR05_skTR01.root", "READ");
  TH2D *hTrkPtEtaVac = (TH2D*)file->Get("hTrkPtEta"); hTrkPtEtaVac->SetName("hTrkPtEtaVac"); hTrkPtEtaVac->SetDirectory(0);
  file->Close();

  file = TFile::Open("data/AnalysisResults_med_JetR05_skTR01.root", "READ");
  TH2D *hTrkPtEtaMed = (TH2D*)file->Get("hTrkPtEta"); hTrkPtEtaMed->SetName("hTrkPtEtaMed"); hTrkPtEtaMed->SetDirectory(0);
  file->Close();
//=============================================================================

  TH1D *hTrkPtVac = hTrkPtEtaVac->ProjectionX("hTrkPtVac");
  TH1D *hTrkPtMed = hTrkPtEtaMed->ProjectionX("hTrkPtMed");

  hTrkPtVac->Rebin(10); hTrkPtVac->Scale(1./5.);
  hTrkPtMed->Rebin(10); hTrkPtMed->Scale(1./5.);
//=============================================================================

  TH1F    *hfm = 0;
  TCanvas *can = 0;
  TLegend *leg = 0;
  TLatex  *tex = 0;
  TLine  *line = 0;

  const Float_t dflx = 0., dfux = 300.;
  const Float_t dfly = 8e-13, dfuy = 8e2;

  const Float_t dlsx = 0.05, dlsy = 0.05;
  const Float_t dtsx = 0.06, dtsy = 0.06;
  const Float_t dtox = 1.10, dtoy = 1.00;

  const TString stnx = "#it{p}_{T} (GeV/#it{c})";
  const TString stny = "d#sigma/d#it{p}_{T} (mb/GeV/#it{c})";

  TH1D *hSE = new TH1D("hSE", "", 10., 0., 10.);
  hSE->SetLineWidth(2);
  hSE->SetLineColor(wcl[0]);
  hSE->SetMarkerStyle(wmk[0]);
  hSE->SetMarkerColor(wcl[0]);

  TH1D *hME = new TH1D("hME", "", 10., 0., 10.);
  hME->SetLineWidth(2);
  hME->SetLineColor(wcl[0]);
  hME->SetMarkerStyle(wmk[2]);
  hME->SetMarkerColor(wcl[0]);
//=============================================================================

  can = MakeCanvas("TrkPt"); can->SetGridx(); can->SetGridy(); can->SetLogy();
  hfm = can->DrawFrame(dflx, dfly, dfux, dfuy); SetupFrame(hfm, dlsx, dlsy, dtsx, dtsy, dtox, dtoy, stnx, stny);
  hfm->GetXaxis()->SetNdivisions(510);
  hfm->GetYaxis()->SetNdivisions(510);

  DrawHisto(hTrkPtVac, wcl[3], wmk[0], "SAME");
  DrawHisto(hTrkPtMed, wcl[1], wmk[0], "SAME");

  leg = new TLegend(0.62, 0.72, 0.98, 0.88); SetupLegend(leg);
  leg->AddEntry(hTrkPtVac, "Vacuum", "LP")->SetTextSizePixels(24);
  leg->AddEntry(hTrkPtMed, "Medium", "LP")->SetTextSizePixels(24);
  leg->Draw();

  tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSizePixels(24);
  tex->DrawLatex(0.16, 0.92, "PYTHIA+JEWEL, 2.76 TeV, |#eta|<2.6");
  CanvasEnd(can);
//=============================================================================

  const Double_t dBins[] = { 0., 5., 10., 20., 30., 50., 80., 120., 160., 200., 250., 300., 400., 500. };
  const Int_t nBins = sizeof(dBins) / sizeof(Double_t) - 1;

  TH1D *hTrkPtVacRB = hTrkPtVac->Rebin(nBins, "hTrkPtVacRB", dBins);
  TH1D *hTrkPtMedRB = hTrkPtMed->Rebin(nBins, "hTrkPtMedRB", dBins); hTrkPtMedRB->Divide(hTrkPtVacRB);

  can = MakeCanvas("TrkPtRAA"); can->SetGridx(); can->SetGridy();
  hfm = can->DrawFrame(dflx, 0., dfux, 2.); SetupFrame(hfm, dlsx, dlsy, dtsx, dtsy, dtox, dtoy, stnx, "#it{R}_{AA}");
  hfm->GetXaxis()->SetNdivisions(510);
  hfm->GetYaxis()->SetNdivisions(510);

  DrawHisto(hTrkPtMedRB, wcl[0], wmk[0], "SAME");

  tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSizePixels(24);
  tex->DrawLatex(0.16, 0.92, "PYTHIA+JEWEL, 2.76 TeV, |#eta|<2.6");
  CanvasEnd(can);
//=============================================================================

  return;
}
Beispiel #21
0
TF1* fit(Double_t ptmin, Double_t ptmax)
{
  TCanvas* c = new TCanvas(Form("c_%.0f_%.0f",ptmin,ptmax),"",600,600);
  TFile* infile = new TFile(Form("%s_%s_%.0f_%.0f.root",infname.Data(),collisionsystem.Data(),ptmin,ptmax));
  TH1D* h = (TH1D*)infile->Get("h");                    h->SetName(Form("h_%.0f_%.0f",ptmin,ptmax));
  TH1D* hMCSignal = (TH1D*)infile->Get("hMCSignal");    hMCSignal->SetName(Form("hMCSignal_%.0f_%.0f",ptmin,ptmax));
  TH1D* hMCSwapped = (TH1D*)infile->Get("hMCSwapped");  hMCSwapped->SetName(Form("hMCSwapped_%.0f_%.0f",ptmin,ptmax));
  TF1* f = new TF1(Form("f_%.0f_%.0f",ptmin,ptmax),"[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", 1.7, 2.0);

  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);
  h->GetEntries();
  
  hMCSignal->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"q","",minhisto,maxhisto);
  hMCSignal->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"q","",minhisto,maxhisto);
  f->ReleaseParameter(1);
  hMCSignal->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L q","",minhisto,maxhisto);
  hMCSignal->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L q","",minhisto,maxhisto);
  hMCSignal->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"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_%.0f_%.0f",ptmin,ptmax),"L q","",minhisto,maxhisto);
  hMCSwapped->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L q","",minhisto,maxhisto);
  hMCSwapped->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L q","",minhisto,maxhisto);
  hMCSwapped->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"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->SetLineColor(kRed);
  
  h->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"q","",minhisto,maxhisto);
  h->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"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_%.0f_%.0f",ptmin,ptmax),"L q","",minhisto,maxhisto);
  h->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L q","",minhisto,maxhisto);
  h->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L q","",minhisto,maxhisto);
  h->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L m","",minhisto,maxhisto);
  
  TF1* background = new TF1(Form("background_%.0f_%.0f",ptmin,ptmax),"[0]+[1]*x+[2]*x*x");
  background->SetParameter(0,f->GetParameter(3));
  background->SetParameter(1,f->GetParameter(4));
  background->SetParameter(2,f->GetParameter(5));
  background->SetLineColor(4);
  background->SetRange(minhisto,maxhisto);
  background->SetLineStyle(2);
  
  TF1* mass = new TF1(Form("fmass_%.0f_%.0f",ptmin,ptmax),"[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_%.0f_%.0f",ptmin,ptmax),"[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* texCms = new TLatex(0.18,0.93, "#scale[1.25]{CMS} Preliminary");
  texCms->SetNDC();
  texCms->SetTextAlign(12);
  texCms->SetTextSize(0.04);
  texCms->SetTextFont(42);
  texCms->Draw();

  TLatex* texCol = new TLatex(0.96,0.93, Form("%s #sqrt{s_{NN}} = 5.02 TeV",collisionsystem.Data()));
  texCol->SetNDC();
  texCol->SetTextAlign(32);
  texCol->SetTextSize(0.04);
  texCol->SetTextFont(42);
  texCol->Draw();

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

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

  TLatex* texYield = new TLatex(0.22,0.73,Form("N_{D} = %.0f #pm %.0f",yield,yieldErr));
  texYield->SetNDC();
  texYield->SetTextFont(42);
  texYield->SetTextSize(0.04);
  texYield->SetLineWidth(2);
  texYield->Draw();

  c->SaveAs(Form("plotFits/DMass_poly2_%s_%.0f_%.0f.pdf",collisionsystem.Data(),ptmin,ptmax));
  
  TCanvas* cPull = new TCanvas(Form("cPull_%.0f_%.0f",ptmin,ptmax),"",600,700);
  TH1D* hPull = (TH1D*)h->Clone("hPull");
  for(int i=0;i<h->GetNbinsX();i++)
    {
      Double_t nfit = f->Integral(h->GetBinLowEdge(i+1),h->GetBinLowEdge(i+1)+h->GetBinWidth(i+1))/h->GetBinWidth(i+1);
      hPull->SetBinContent(i+1,(h->GetBinContent(i+1)-nfit)/h->GetBinError(i+1));
      hPull->SetBinError(i+1,0);
    }
  hPull->SetMinimum(-4.);
  hPull->SetMaximum(4.);
  hPull->SetYTitle("Pull");
  hPull->GetXaxis()->SetTitleOffset(1.);
  hPull->GetYaxis()->SetTitleOffset(0.65);
  hPull->GetXaxis()->SetLabelOffset(0.007);
  hPull->GetYaxis()->SetLabelOffset(0.007);
  hPull->GetXaxis()->SetTitleSize(0.12);
  hPull->GetYaxis()->SetTitleSize(0.12);
  hPull->GetXaxis()->SetLabelSize(0.1);
  hPull->GetYaxis()->SetLabelSize(0.1);
  hPull->GetYaxis()->SetNdivisions(504);
  TLine* lPull = new TLine(1.7, 0, 2., 0);
  lPull->SetLineWidth(1);
  lPull->SetLineStyle(7);
  lPull->SetLineColor(1);
  TPad* pFit = new TPad("pFit","",0,0.3,1,1);
  pFit->SetBottomMargin(0);
  pFit->Draw();
  pFit->cd();
  h->Draw("e");
  background->Draw("same");
  mass->Draw("same");
  massSwap->Draw("same");
  f->Draw("same");
  leg->Draw("same");
  texCms->Draw();
  texCol->Draw();
  texPt->Draw();
  texY->Draw();
  texYield->Draw();
  cPull->cd();
  TPad* pPull = new TPad("pPull","",0,0,1,0.3);
  pPull->SetTopMargin(0);
  pPull->SetBottomMargin(0.3);
  pPull->Draw();
  pPull->cd();
  hPull->Draw("p");
  lPull->Draw();
  cPull->cd();
  cPull->SaveAs(Form("plotFits/DMass_poly2_%s_%.0f_%.0f_Pull.pdf",collisionsystem.Data(),ptmin,ptmax));

  return mass;
}
Beispiel #22
0
void plotcf(const char* sys="PP", const char* kT="kT1", const char* proj="Out", int mult=2, TString dir = "../train_results_central_dcaptdep", int period=11, int numofpsibins = 6) {

  int seppsi = 0; // indicates if draw in separate psi bins
  int psibins = 0; // indicates if one uses psi binning
  int fname = 1; // indicates if the file name is specified
  int plotinpsibins = 0;
  int rb = 1; // flag to rebinning

  if (mult<2)
    const char* centrality = "central";
  else
    const char* centrality = "semicentral";

  if (period == 11) {

    const int Nruns = 64;
    // const int Nruns = 66;

    int runs[Nruns] = {
      167915, 168115, 168460, 169035, 169238, 169859, 170228  , 167920 // , 168310
      , 168464, 169091, 169411, 169923, 170230, 167985, 168311, 169094, 169415, 170027, 170268, 167987, 168322, 168511, 169138, 169417, 170081, 170269, 167988, 168325, 168512, 169144, 169835, 170155, 170270, 168069,  168341, 168514, 169145, 169837, 170159, 170306// , 168076
      , 168342, 168777,  169148,      169838, 170163, 170308, 168105, 168361, 168826, 169156, 169846, 170193, 170309, 168107 // ,168362
      , 168988,       169160,      169855, 170203, 168108 , 168458,  168992,      169167, 169858, 170204
    };


    // const int Nruns = 62;
    // int runs[Nruns] = {
    //   167915, 168115, 168460, 169035, 169238, 169859, 170228  ,  // 167920 ,
    //   168310, 168464, 169091, 169411, 169923, 170230, 167985, 168311, 169094, 169415, 170027, 170268, 167987, 168322, 168511, 169138, 169417, 170081, 170269, 167988, 168325, 168512, 169144, 169835, 170155, 170270, 168069, // 168341,
    //   168514, 169145, 169837, 170159, 170306, 168076, 168342, 168777, // 169148,
    //   169838, 170163, 170308, 168105, 168361, 168826, 169156, 169846, 170193, 170309, 168107, 168362, // 168988,
    //   // 169160,
    //   169855, 170203, 168108 , 168458,  168992,
    //   169167, 169858, 170204
    // };

  }
  else if (period == 10) {
    const int Nruns = 89;
    int runs[Nruns] = {
      139510, 139507, 139505, 139503, 139465, 139438, 139437, 139360, 139329, 139328, 139314, 139310, 139309, 139173, 139107, 139105, 139038, 139037, 139036, 139029, 139028, 138872, 138871, 138870, 138837, 138732, 138730, 138666, 138662, 138653, 138652, 138638, 138624, 138621, 138583, 138582, 138579, 138578, 138534, 138469, 138442, 138439, 138438, 138396, 138364, 138275, 138225, 138201, 138197, 138192, 138190, 137848, 137844, 137752, 137751, 137724, 137722, 137718, 137704, 137693, 137692, 137691, 137686, 137685, 137639, 137638, 137608, 137595, 137549, 137544, 137541, 137539, 137443, 137441, 137440, 137439, 137434, 137432, 137431, 137430, 137366, 137243, 137236, 137235, 137232, 137231, 137230, 137162, 137161};
  }


  TFile* ifile_[Nruns+1];

  if (plotinpsibins) {
    for (int jf = 0 ; jf < Nruns; ++jf ) {
      ifile_[jf] = new TFile(Form("%s/%d.mergedbinsdir.root",dir.Data(),runs[jf]), "read");
    }
  }
  if (fname)
    ifile_[Nruns] = new TFile(Form("%s",dir.Data()), "read");
  else
    ifile_[Nruns] = new TFile(Form("%s/allrunsmergedbins.root",dir.Data()), "read");


  TH1D* numpp[13][3][Nruns+1];
  TH1D* denpp[13][3][Nruns+1];

  TH1D* numpapoutp[13][3];
  TH1D* numpapoutn[13][3];
  TH1D* numpaplongp[13][3];
  TH1D* numpaplongn[13][3];
  TH1D* numpapsidep[13][3];
  TH1D* numpapsiden[13][3];

  TH1D* denpapoutp[13][3];
  TH1D* denpapoutn[13][3];
  TH1D* denpaplongp[13][3];
  TH1D* denpaplongn[13][3];
  TH1D* denpapsidep[13][3];
  TH1D* denpapsiden[13][3];

  TH1D* numsum;
  TH1D* densum;

	TCanvas *myCan = new TCanvas("asd","asd");
	myCan->Draw();
	myCan->cd();

	TPad *myPad = new TPad("myPad", "The pad",0,0,1,1);
	myPadSetUp(myPad,0.15,0.04,0.04,0.15);
	myPad->Draw();
	myPad->cd();

  TGraph* grnument[13];
  TH2D* hnument = new TH2D("hipsiif","hipsiif",numofpsibins,-0.5,numofpsibins,Nruns,-0.5,Nruns);

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

  if (plotinpsibins) {

// _________________________________________________
// // Psi binning.....
// _________________________________________________

// each numerator and denominator from different run
    for (int iPsi = 0; iPsi < numofpsibins; ++iPsi) {

      grnument[iPsi] = new TGraph();

      for (int iif = 0; iif < Nruns; ++iif ) {


        // cout << Form("NumcqinvPPtpcM3Psi%d%s",iPsi,kT) << endl;
        // cout << Form("Numcqinv%stpcM%dPsi%d%s",sys,mult,iPsi,kT) << endl;
        // cout << "iPsi = " << iPsi << endl;
        // // cout << "ikT = " << ikT << endl;
        // cout << "iif = " << iif << endl << endl;

        bool exi = false;

        if (iPsi == 0) {

          if (strcmp(sys,"PAP") != 0) {


            if ( ifile_[iif]->GetListOfKeys()->Contains(Form("Numcqinv%stpcM%dPsi%d%s",sys,mult,iPsi,kT)) ) {
              exi = true;

              numsum = (TH1D*)ifile_[iif]->Get(Form("Numcqinv%stpcM%dPsi%d%s",sys,mult,iPsi,kT));
              densum = (TH1D*)ifile_[iif]->Get(Form("Dencqinv%stpcM%dPsi%d%s",sys,mult,iPsi,kT));

              grnument[iPsi]->SetPoint(grnument[iPsi]->GetN(), iif, numsum->GetEntries());
              hnument->SetBinContent(iPsi+1, iif, numsum->GetEntries());

              if (densum->GetEntries()==0) {
                cout << "iPsi = " << iPsi << endl;
                cout << "iif = " << iif << endl << endl;
              }
            }
          }
          else {
            exi = true;
            numsum = (TH1D*)ifile_[iif]->Get(Form("Num%sPckstarPAPtpcM%dPsi%d%s",proj,mult,iPsi,kT));
            densum = (TH1D*)ifile_[iif]->Get(Form("Den%sPckstarPAPtpcM%dPsi%d%s",proj,mult,iPsi,kT));
            numsumN = (TH1D*)ifile_[iif]->Get(Form("Num%sNckstarPAPtpcM%dPsi%d%s",proj,mult,iPsi,kT));
            densumN = (TH1D*)ifile_[iif]->Get(Form("Den%sNckstarPAPtpcM%dPsi%d%s",proj,mult,iPsi,kT));

            grnument[iPsi]->SetPoint(grnument[iPsi]->GetN(), iif, numsum->GetEntries());
            hnument->SetBinContent(iPsi+1, iif, numsum->GetEntries());

            // numsum->SetBit(TH1::kIsAverage);
            // densum->SetBit(TH1::kIsAverage);
            // numsumN->SetBit(TH1::kIsAverage);
            // densumN->SetBit(TH1::kIsAverage);

          }
          if (exi)
            if (!seppsi) {
              densum->Scale(numsum->GetEntries()/densum->GetEntries());
            }
          if (strcmp(sys,"PAP") == 0) {
            densumN->Scale(numsumN->GetEntries()/densumN->GetEntries());
          }
        }
        else {
          if (strcmp(sys,"PAP") != 0) {
            if ( ifile_[iif]->GetListOfKeys()->Contains(Form("Numcqinv%stpcM%dPsi%d%s",sys,mult,iPsi,kT)) ) {
              exi = true;
              numpp[iPsi][2][iif] = (TH1D*)ifile_[iif]->Get(Form("Numcqinv%stpcM%dPsi%d%s",sys,mult,iPsi,kT));
              denpp[iPsi][2][iif] = (TH1D*)ifile_[iif]->Get(Form("Dencqinv%stpcM%dPsi%d%s",sys,mult,iPsi,kT));

              grnument[iPsi]->SetPoint(grnument[iPsi]->GetN(), iif, numpp[iPsi][2][iif]->GetEntries());
              hnument->SetBinContent(iPsi+1, iif, numpp[iPsi][2][iif]->GetEntries());

              // cout << iPsi << endl;
              // cout << numpp[iPsi][2][iif]->GetEntries() << endl;
              // // cout << denpp[iPsi][2][iif]->GetEntries() << endl;
              // cout << endl;

              if (denpp[iPsi][2][iif]->GetEntries()==0) {
                cout << denpp[iPsi][2][iif]->GetEntries() << endl;
                cout << "iPsi = " << iPsi << endl;
                cout << "iif = " << iif << endl;
              }
            }
          }
          else {
            exi = true;
            numpp[iPsi][2][iif] = (TH1D*)ifile_[iif]->Get(Form("Num%sPckstarPAPtpcM%dPsi%d%s",proj,mult,iPsi,kT));
            denpp[iPsi][2][iif] = (TH1D*)ifile_[iif]->Get(Form("Den%sPckstarPAPtpcM%dPsi%d%s",proj,mult,iPsi,kT));
            numpp[iPsi][0][iif] = (TH1D*)ifile_[iif]->Get(Form("Num%sNckstarPAPtpcM%dPsi%d%s",proj,mult,iPsi,kT));
            denpp[iPsi][0][iif] = (TH1D*)ifile_[iif]->Get(Form("Den%sNckstarPAPtpcM%dPsi%d%s",proj,mult,iPsi,kT));
            // numpp[iPsi][2][iif]->SetBit(TH1::kIsAverage);
            // denpp[iPsi][2][iif]->SetBit(TH1::kIsAverage);
            // numpp[iPsi][0][iif]->SetBit(TH1::kIsAverage);
            // denpp[iPsi][0][iif]->SetBit(TH1::kIsAverage);
            grnument[iPsi]->SetPoint(grnument[iPsi]->GetN(), iif, numpp[iPsi][2][iif]->GetEntries());
            hnument->SetBinContent(iPsi+1, iif, numpp[iPsi][2][iif]->GetEntries());

          }

          if (exi) {
            numsum->Add(numpp[iPsi][2][iif]);
            if (!seppsi)
              denpp[iPsi][2][iif]->Scale(numpp[iPsi][2][iif]->GetEntries()/denpp[iPsi][2][iif]->GetEntries());
            densum->Add(denpp[iPsi][2][iif]);
            if (strcmp(sys,"PAP") == 0) {
              numsumN->Add(numpp[iPsi][0][iif]);
              denpp[iPsi][0][iif]->Scale(numpp[iPsi][0][iif]->GetEntries()/denpp[iPsi][0][iif]->GetEntries());
              densumN->Add(denpp[iPsi][0][iif]);
            }
          }

        }


        // int rb = 2;
        // if (exi) {
        //     cout << "exi" << endl;
        //     numsum->Rebin(rb);
        // }
        // densum->Rebin(rb);
        // numsum->Divide(densum);
        // numsum->SetMarkerColor(1+iPsi);
        // numsum->SetMarkerStyle(20);
        // numsum->SetMarkerSize(1.0);

        // if (iPsi == 0)
        //     numsum->Draw("p");
        // else
        // numsum->Draw("psame");

      }

      if (seppsi) {
        double norm = numsum->GetEntries()/densum->GetEntries();
        cout << iPsi << " " << norm << endl;
        TH1F *hnew = (TH1F*)densum->Clone("hnew");
        hnew->Scale(norm);

        numsum->SetMarkerColor(iPsi+1);
        numsum->SetMarkerStyle(20);
        numsum->SetMarkerSize(1.0);

        int rb = 1;

        numsum->Rebin(rb);
        // densum->Rebin(rb);
        // numsum->Divide(densum);

        hnew->Rebin(rb);
        numsum->Divide(hnew);
        if (iPsi == 0) {
          numsum->DrawCopy("p");
        }
        else {
          numsum->DrawCopy("psame");
        }

        // hnument[iPsi][iif]->Write();

      }
      // cout <<"write ipsi = " << iPsi << endl;
      // grnument[iPsi]->SetName(Form("gr%d",iPsi));
      // grnument[iPsi]->Write();
    }
    // hnument->Write();

    // numpp[6][2]->Draw("p");


    if (!seppsi) {


      if (strcmp(sys,"PAP")==0) {
        numsum->SetBit(TH1::kIsAverage);
        densum->SetBit(TH1::kIsAverage);
        numsumN->SetBit(TH1::kIsAverage);
        densumN->SetBit(TH1::kIsAverage);

        numsum->Add(numsumN);
        densum->Add(densumN);

        numsum->ResetBit(TH1::kIsAverage);
        densum->ResetBit(TH1::kIsAverage);
      }

      numsum->SetMarkerColor(kBlue);
      numsum->SetMarkerStyle(20);
      numsum->SetMarkerSize(1.0);

      int rb = 1;

      numsum->Rebin(rb);
      densum->Rebin(rb);
      numsum->Divide(densum);



      if (psibins)
        numsum->Draw("p");

      // densum->Draw("psame");
    }
  }

// _________________________________________________
// // bez Psi binningu.....
// _________________________________________________


  if (strcmp(sys,"PAP") != 0) {
    numpp[0][2][Nruns] = (TH1D*)ifile_[Nruns]->Get(Form("Numcqinv%stpcM%dPsi%d%s",sys,mult,numofpsibins,kT));
    denpp[0][2][Nruns] = (TH1D*)ifile_[Nruns]->Get(Form("Dencqinv%stpcM%dPsi%d%s",sys,mult,numofpsibins,kT));

    numpp[0][2][Nruns]->SetXTitle("#it{q}_{inv} (GeV/#it{c})");
    numpp[0][2][Nruns]->SetYTitle("C(#it{q}_{inv})");

    // numsum->SetXTitle("#it{q}_{inv} (GeV/#it{c})");
    // numsum->SetYTitle("C(#it{q}_{inv})");

  }
  else {
    numpp[0][2][Nruns] = (TH1D*)ifile_[Nruns]->Get(Form("Num%sPckstarPAPtpcM%dPsi%d%s",proj,mult,numofpsibins,kT));
    denpp[0][2][Nruns] = (TH1D*)ifile_[Nruns]->Get(Form("Den%sPckstarPAPtpcM%dPsi%d%s",proj,mult,numofpsibins,kT));

    numpp[0][0][Nruns] = (TH1D*)ifile_[Nruns]->Get(Form("Num%sNckstarPAPtpcM%dPsi%d%s",proj,mult,numofpsibins,kT));
    denpp[0][0][Nruns] = (TH1D*)ifile_[Nruns]->Get(Form("Den%sNckstarPAPtpcM%dPsi%d%s",proj,mult,numofpsibins,kT));

    numpp[0][2][Nruns]->SetBit(TH1::kIsAverage);
    denpp[0][2][Nruns]->SetBit(TH1::kIsAverage);

    numpp[0][0][Nruns]->SetBit(TH1::kIsAverage);
    denpp[0][0][Nruns]->SetBit(TH1::kIsAverage);

    numpp[0][2][Nruns]->Add(numpp[0][0][Nruns]);
    denpp[0][2][Nruns]->Add(denpp[0][0][Nruns]);

    numpp[0][2][Nruns]->ResetBit(TH1::kIsAverage);
    denpp[0][2][Nruns]->ResetBit(TH1::kIsAverage);

    numpp[0][2][Nruns]->SetXTitle("#it{k*} (GeV/#it{c})");
    numpp[0][2][Nruns]->SetYTitle("C(#it{k*})");

    // numsum->SetXTitle("#it{k*} (GeV/#it{c})");
    // numsum->SetYTitle("C(#it{k*})");

  }

  gStyle->SetOptStat(0);
  numpp[0][2][Nruns]->GetXaxis()->SetTitleSize(0.06);
  numpp[0][2][Nruns]->GetYaxis()->SetTitleSize(0.06);
  numpp[0][2][Nruns]->SetTitle("");

  numpp[0][2][Nruns]->Rebin(rb);
  denpp[0][2][Nruns]->Rebin(rb);

  numpp[0][2][Nruns]->SetMarkerColor(kRed);
  numpp[0][2][Nruns]->SetMarkerStyle(20);
  numpp[0][2][Nruns]->SetMarkerSize(1.0);

  // numsum->GetXaxis()->SetTitleSize(0.06);
  // numsum->GetYaxis()->SetTitleSize(0.06);
  // numsum->SetTitle("");

  // numsum->Rebin(rb);
  // densum->Rebin(rb);


  double norm = denpp[0][2][Nruns]->GetEntries()/numpp[0][2][Nruns]->GetEntries();
  //double norm = calculateNormalizationFactor(numpp[0][2][Nruns],denpp[0][2][Nruns],0.4,0.45 );
  //double norm = calculateNormalizationFactor(numpp[0][2][Nruns],denpp[0][2][Nruns],0.3,0.4 );

  numpp[0][2][Nruns]->Divide(denpp[0][2][Nruns]);
  numpp[0][2][Nruns]->Scale(norm);

  if (strcmp(sys,"PAP") == 0) {
    numpp[0][2][Nruns]->SetMaximum(1.5);
    numpp[0][2][Nruns]->SetMinimum(0.9);
    // numpp[0][2][Nruns]->GetXaxis()->SetRangeUser(0,0.46);
    // numpp[0][2][Nruns]->GetXaxis()->SetRangeUser(0,0.5);

    // numsum->GetXaxis()->SetRangeUser(0,0.6);

    // numsum->SetMaximum(1.058);
    // numsum->SetMinimum(0.912);
    // numsum->SetTitle("");
  }
  else {
    numpp[0][2][Nruns]->SetMaximum(1.5);
    numpp[0][2][Nruns]->SetMinimum(0.9);
    // numsum->SetMaximum(2.2);
    // numsum->SetMinimum(0.5);
    // numpp[0][2][Nruns]->GetXaxis()->SetRangeUser(0,0.26);
    numpp[0][2][Nruns]->GetXaxis()->SetRangeUser(0,0.5);
    // numsum->GetXaxis()->SetRangeUser(0,0.26);
    // numsum->GetXaxis()->SetRangeUser(0,0.3);
  }


// uncomment this to compare
  // if (!psibins)
  numpp[0][2][Nruns]->Draw("p");
  // else
  //   numpp[0][2][Nruns]->Draw("same");






  //numpp[0][2][Nruns]->Write();

  // if (strcmp(sys,"PAP") ==0 ) {
  //   numpp[0][0][Nruns]->Rebin(rb);
  //   denpp[0][0][Nruns]->Rebin(rb);

  //   numpp[0][0][Nruns]->SetMarkerColor(kBlack);
  //   numpp[0][0][Nruns]->SetMarkerStyle(20);
  //   numpp[0][0][Nruns]->SetMarkerSize(1.0);

  //   double norm = denpp[0][0][Nruns]->GetEntries()/numpp[0][0][Nruns]->GetEntries();
  //   numpp[0][0][Nruns]->Divide(denpp[0][0][Nruns]);
  //   numpp[0][0][Nruns]->Scale(norm);
  //   // numpp[0][0][Nruns]->Draw("same");

  //   numsumN->SetMarkerColor(kGreen+2);
  //   numsumN->SetMarkerStyle(20);
  //   numsumN->SetMarkerSize(1.0);

  //   numsumN->Rebin(rb);
  //   densumN->Rebin(rb);
  //   numsumN->Divide(densumN);

  //   // numsumN->Draw("same");
  // }


  // if (psibins) {
  //   TLegend *leg = new TLegend (0.5,0.2,0.7,0.3);
  //   leg->SetFillColor(kWhite);
  //   leg->SetBorderSize(0);
  //   leg->SetTextSize(0.07);
  //   leg->AddEntry(numsum,"w/ #Psi bins","p");
  //   leg->AddEntry(numpp[0][2][Nruns],"w/o EP cut","p");
  //   leg->Draw("same");
  // }


  // TString namef( dir(16,dir.Length()) );
  // cout << namef << endl;

  dir.ReplaceAll("/","_");
  dir.ReplaceAll("..","");
  dir.ReplaceAll(".root","");
  dir.ReplaceAll("_train_results_","");
  dir.ReplaceAll("_central_","");
  dir.ReplaceAll("_semicentral_","");
  dir.ReplaceAll("jun19_","");
  myCan->SaveAs(Form("figs/cf%s%s%s.png",sys,dir.Data(),kT));

  TFile* ofile = new TFile(Form("figs/cf%s%s%s.root",sys,dir.Data(),kT),"recreate");
  numpp[0][2][Nruns]->Write();

  //numsum->Write();


}
Beispiel #23
0
void compareTrig(){
  
  TFile *f1 = TFile::Open("hltmenu_1TeV_1.0e10_startup_run122314_PD_MinBias_ohlt_all_2009_12_3.root");
  TFile *f2 = TFile::Open("hltmenu_1TeV_1.0e10_startup_pythiaD6T_ohlt_30k_2009_12_3.root");

  TH2F *overlap_data = (TH2F *) f1->Get("overlap");
  TH2F *overlap_mc = (TH2F *) f2->Get("overlap");  
  TH2F *num_data = (TH2F *) f1->Get("trigCorrNum");
  TH2F *num_mc = (TH2F *) f2->Get("trigCorrNum");

  int nbin = num_data->GetNbinsY();
 
  for(int i=1 ; i <= nbin ;i++){ 
    string t = int2string(i);
    string name = "c"+t;
    TCanvas *c = new TCanvas(name.c_str(),"c",1);
    char *na = num_data->GetYaxis()->GetBinLabel(i);
    TH1D *x = overlap_data->ProjectionY("xh",i,i);
    TH1D *y = overlap_mc->ProjectionY("yh",i,i);

    //get denominators 
    double de_data = num_data->GetBinContent(i,i);
    double de_mc = num_mc->GetBinContent(i,i);

    if(debug) { 
      cout << na << endl;
      cout << "data= " << de_data << " mc= " << de_mc << endl;
    }
    //Set error from overlap plot
    for(int j=1; j <= nbin; j++){
      //get numerators
      double nu_data = num_data->GetBinContent(i,j);
      double nu_mc = num_mc->GetBinContent(i,j);

      double xerr = sigma(nu_data, de_data, 3);
      double yerr = sigma(nu_mc, de_mc, 3);
 
      if(debug){
        cout << "data= " << nu_data << " err= " << xerr << endl;
        cout << "mc= " << nu_mc << " err= " << yerr << endl;  
      }
      x->SetBinError(j,xerr);
      y->SetBinError(j,yerr);

    }

    //Set histograms 
    x->SetStats(0);
    x->Draw("P");
    y->Draw("PSame");
    x->SetMarkerStyle(20);
    y->SetMarkerStyle(22);
    x->SetMarkerSize(1.2);
    y->SetMarkerSize(1.2);
    x->SetMarkerColor(2);
    y->SetMarkerColor(4);
    x->SetLineColor(2);
    y->SetLineColor(4);
    x->GetXaxis()->LabelsOption("v");
    y->GetXaxis()->LabelsOption("v");

    c->SetBottomMargin(0.35);

  
    TLegend *l= new TLegend(0.6,0.91,1.0,1.0);
    l->SetHeader(na);
    l->AddEntry(x,"Data","pl");
    l->AddEntry(y,"MC","pl");
    l->SetFillColor(0);
    l->SetLineColor(0);
    l->Draw();

    x->Clear();
    y->Clear();
    
  }

}
Beispiel #24
0
void hPYphocalc(){
	gStyle->SetOptStat(kFALSE);
	const int maxNpart = 100;
	int sth=0, Gth=0;
        TFile *f = TFile::Open(outG);
        if(sth==0){TString dirname = "std";}
        else if(sth==1){TString dirname ="Gri055";}
        else {TString dirname ="Gri101";}
        TObjString* dataname = (TObjString*)f->Get(Form("dataname"));
        TObjString* histoname = (TObjString*)f->Get(Form("histoname"));
	TFile *fdata = TFile::Open(dataname->GetName());
                TString name;
        if(Gth==0)
                name = "G0";
        else if(Gth<nGlau)
                name = Form("Glau_%d",Gth);
        else
                name = Form("bin_%d",Gth-nGlau+1);
        TObjString* Glaubername = (TObjString*)f->Get(Form("%s/%s/Glaubername",dirname.Data(),name.Data()));
        TVectorD* k0 = (TVectorD*)f->Get(Form("%s/%s/k0",dirname.Data(),name.Data()));
        TVectorD* theta0 = (TVectorD*)f->Get(Form("%s/%s/theta0",dirname.Data(),name.Data()));
        TVectorD* xmin = (TVectorD*)f->Get(Form("%s/%s/xmin",dirname.Data(),name.Data()));
        TVectorD* xmax = (TVectorD*)f->Get(Form("%s/%s/xmax",dirname.Data(),name.Data()));
        TVectorD* thetabest = (TVectorD*)f->Get(Form("%s/%s/thetabest",dirname.Data(),name.Data()));
        TVectorD* kbest = (TVectorD*)f->Get(Form("%s/%s/kbest",dirname.Data(),name.Data()));
	TVectorD* kpoint = (TVectorD*)f->Get(Form("%s/%s/kpoint",dirname.Data(),name.Data()));
        TVectorD* NcollAver = (TVectorD*)f->Get(Form("%s/%s/NcollAver",dirname.Data(),name.Data()));
	TVectorD* centbin = (TVectorD*)f->Get(Form("%s/%s/centbin",dirname.Data(),name.Data()));

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

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

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

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

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

  TCanvas* c4 = new TCanvas("c4","",800,600);
  c4->Divide(2,2);
   
  TCanvas* c2 = new TCanvas("c2","",400,600);
  c2->Divide(1,2);

  TCanvas* c1 = new TCanvas();

  TCanvas* c15 = new TCanvas("c15","",1300,1000);
//  c15->Divide(3,5);
	c15->Divide(5,5);

  TFile* fPP = new TFile("bFeedDownPP.hist.root");
  TFile* fPPMB = new TFile("bFeedDownPPMB.hist.root");
  TFile* fPPMC = new TFile("bFeedDownPPMC.hist.root");
  TFile* fPPMBMC = new TFile("bFeedDownPPMBMC.hist.root");

  TH3D* hDataPP = (TH3D*)fPP->Get("hData");
  TH3D* hSidebandPP = (TH3D*)fPP->Get("hSideband");
  TH3D* hDataPPMB = (TH3D*)fPPMB->Get("hData");
  TH3D* hSidebandPPMB = (TH3D*)fPPMB->Get("hSideband");
  TH3D* hPtMD0DcaPP = (TH3D*)fPP->Get("hPtMD0Dca");
  TH3D* hPtMD0DcaPPMB = (TH3D*)fPPMB->Get("hPtMD0Dca");

  TH3D* hMCPSignalPP = (TH3D*)fPPMC->Get("hMCPSignal");
  TH3D* hMCNPSignalPP = (TH3D*)fPPMC->Get("hMCNPSignal");
  TH3D* hMCPSignalPPMB = (TH3D*)fPPMBMC->Get("hMCPSignal");
  TH3D* hMCNPSignalPPMB = (TH3D*)fPPMBMC->Get("hMCNPSignal");
  TH3D* hPtMD0DcaMCPSignalPP = (TH3D*)fPPMC->Get("hPtMD0DcaMCPSignal");
  TH3D* hPtMD0DcaMCPSwappedPP = (TH3D*)fPPMC->Get("hPtMD0DcaMCPSwapped");
  TH3D* hPtMD0DcaMCPSignalPPMB =(TH3D*)fPPMBMC->Get("hPtMD0DcaMCPSignal");
  TH3D* hPtMD0DcaMCPSwappedPPMB = (TH3D*)fPPMBMC->Get("hPtMD0DcaMCPSwapped");

  TH3D* hData = (TH3D*)hDataPP->Clone("hData");
  hData->Sumw2();
  hData->Add(hDataPPMB);

  TH3D* hSideband = (TH3D*)hSidebandPP->Clone("hSideband");
  hSideband->Sumw2();
  hSideband->Add(hSidebandPPMB);

  TH3D* hPtMD0Dca = (TH3D*)hPtMD0DcaPP->Clone("hPtMD0Dca");
  hPtMD0Dca->Sumw2();
  hPtMD0Dca->Add(hPtMD0DcaPPMB);

  TH3D* hMCPSignal = (TH3D*)hMCPSignalPP->Clone("hMCPSignal");
  hMCPSignal->Sumw2();
  hMCPSignal->Add(hMCPSignalPPMB);

  TH3D* hMCNPSignal = (TH3D*)hMCNPSignalPP->Clone("hMCNPSignal");
  hMCNPSignal->Sumw2();
  hMCNPSignal->Add(hMCNPSignalPPMB);

  TH3D* hPtMD0DcaMCPSignal = (TH3D*)hPtMD0DcaMCPSignalPP->Clone("hPtMD0DcaMCPSignal");
  hPtMD0DcaMCPSignal->Sumw2();
  hPtMD0DcaMCPSignal->Add(hPtMD0DcaMCPSignalPPMB);

  TH3D* hPtMD0DcaMCPSwapped =(TH3D*)hPtMD0DcaMCPSwappedPP->Clone("hPtMD0DcaMCPSwapped");
  hPtMD0DcaMCPSwapped->Sumw2();
  hPtMD0DcaMCPSwapped->Add(hPtMD0DcaMCPSwappedPPMB);

  TLatex* texCms = new TLatex(0.18,0.93, "#scale[1.25]{CMS} Preliminary");
  texCms->SetNDC();
  texCms->SetTextAlign(12);
  texCms->SetTextSize(0.06);
  texCms->SetTextFont(42);

  TLatex* texCol = new TLatex(0.96,0.93, "PP #sqrt{s_{NN}} = 5.02 TeV");
  texCol->SetNDC();
  texCol->SetTextAlign(32);
  texCol->SetTextSize(0.06);
  texCol->SetTextFont(42);

//  const int nPtBins = 14;
//  float ptBins[nPtBins+1] = {2.,3.,4.,5.,6.,8.,10.,12.5,15.0,20.,25.,30.,40.,60.,100};

  const int nPtBins = 9;
  float ptBins[nPtBins+1] = {2.,4.,6.,8.,10.,12.5,20.,40.,60.,100};


  float pts[nPtBins];
  float ptErrors[nPtBins];
  float promptFraction[nPtBins];
  float totalYield[nPtBins];
  float totalYieldInvMassFit[nPtBins];
  float totalYieldInvMassFitError[nPtBins];
  float bToDYield[nPtBins];
  float bToDYieldError[nPtBins];
  float bToDYieldErrorDataOnly[nPtBins];
  float promptDYield[nPtBins];
  float promptDYieldError[nPtBins];
  float promptDYieldErrorDataOnly[nPtBins];

  TH1D *D0DcaDataOut[nPtBins];
/*
  const int nBinY = 14;
  Float_t binsY[nBinY+1];
  float firstBinYWidth = 0.001;
  float binYWidthRatio = 1.27;
  binsY[0]=0;
  for(int i=1; i<=nBinY; i++)
    binsY[i] = binsY[i-1]+firstBinYWidth*pow(binYWidthRatio,i-1);
  cout<<"last y bin: "<<binsY[nBinY]<<endl;
*/
  const int nBinY = 20;
  Float_t binsY[nBinY+1] = {-0.0734,-0.0562,-0.0428,-0.0320,-0.0236,-0.0170,-0.0118,-0.0078,-0.0046,-0.002,0.0,0.002,0.0046,0.0078,0.0118,0.0170,0.0236,0.0320,0.0428,0.0562,0.0734};



  for(int i=1; i<=nPtBins; i++)
    {
      pts[i-1] = 0.5*(ptBins[i-1]+ptBins[i]);
      ptErrors[i-1] = 0.5*(ptBins[i]-ptBins[i-1]);
      float ptLow = ptBins[i-1];
      float ptHigh = ptBins[i];
      cout<<endl<<"======================================="<<endl;
      cout<<"pT range: "<<ptLow<<" "<<ptHigh<<endl;

      TLatex* texPtY = new TLatex(0.32,0.82,Form("%.1f < p_{T} < %.1f GeV/c      |y| < 1.0",ptLow,ptHigh));
      texPtY->SetNDC();
      texPtY->SetTextFont(42);
      texPtY->SetTextSize(0.06);
      texPtY->SetLineWidth(2);

      TLatex* texPt = new TLatex(0.18,0.82,Form("%.1f < p_{T} < %.1f GeV/c",ptLow,ptHigh));
      texPt->SetNDC();
      texPt->SetTextFont(42);
      texPt->SetTextSize(0.06);
      texPt->SetLineWidth(2);

      TLatex* texY = new TLatex(0.18,0.74,Form("|y| < 1.0"));
      texY->SetNDC();
      texY->SetTextFont(42);
      texY->SetTextSize(0.06);
      texY->SetLineWidth(2);

      c2->cd(1);

      hPtMD0Dca->GetZaxis()->SetRange(1,100);
      hPtMD0Dca->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);
      hPtMD0DcaMCPSignal->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);
      hPtMD0DcaMCPSwapped->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);
      TH1D* hMData = (TH1D*)hPtMD0Dca->Project3D("y")->Clone(Form("hM_%1.1f_%1.1f", ptLow, ptHigh));
      TH1D* hMMCSignal = (TH1D*)hPtMD0DcaMCPSignal->Project3D("y");
      TH1D* hMMCSwapped = (TH1D*)hPtMD0DcaMCPSwapped->Project3D("y");

      setColorTitleLabel(hMData);
      setColorTitleLabel(hMMCSignal);
      setColorTitleLabel(hMMCSwapped);

      TF1* fMass = fitMass(hMData, hMMCSignal, hMMCSwapped);

      texCms->Draw();
      texCol->Draw();
      texPt->Draw();
      texY->Draw();

      TF1* fSignalAndSwapped = new TF1("fSignalAndSwapped","[0]*([3]*([5]*Gaus(x,[1],[2]*(1+[7]))/(sqrt(2*3.1415927)*[2]*(1+[7]))+(1-[5])*Gaus(x,[1],[6]*(1+[7]))/(sqrt(2*3.1415927)*[6]*(1+[7])))+(1-[3])*Gaus(x,[1],[4]*(1+[7]))/(sqrt(2*3.1415927)*[4]*(1+[7])))", 1.7, 2.0);      
      fSignalAndSwapped->SetParameter(0,fMass->GetParameter(0));
      fSignalAndSwapped->SetParameter(1,fMass->GetParameter(1));
      fSignalAndSwapped->SetParameter(2,fMass->GetParameter(2));
      fSignalAndSwapped->SetParameter(3,fMass->GetParameter(7));
      fSignalAndSwapped->SetParameter(4,fMass->GetParameter(8));
      fSignalAndSwapped->SetParameter(5,fMass->GetParameter(9));
      fSignalAndSwapped->SetParameter(6,fMass->GetParameter(10));
      fSignalAndSwapped->SetParameter(7,fMass->GetParameter(11));
  
      TF1* background = new TF1("fBackground","[0]+[1]*x+[2]*x*x+[3]*x*x*x");
      background->SetParameter(0,fMass->GetParameter(3));
      background->SetParameter(1,fMass->GetParameter(4));
      background->SetParameter(2,fMass->GetParameter(5));
      background->SetParameter(3,fMass->GetParameter(6));

      cout<<"MC signal width: "<<fMass->GetParameter(2)<<"   "<<fMass->GetParameter(10)<<endl;
      cout<<"MC swapped width: "<<fMass->GetParameter(8)<<endl;

      float massD = 1.8649;
      float massSignal1 = massD-0.025;
      float massSignal2 = massD+0.025;
      float massSideBand1 = massD-0.1;
      float massSideBand2 = massD-0.075;
      float massSideBand3 = massD+0.075;
      float massSideBand4 = massD+0.1;

      float scaleSideBandBackground = background->Integral(massSignal1, massSignal2)/(background->Integral(massSideBand1, massSideBand2)+background->Integral(massSideBand3, massSideBand4));
      cout<<"scaleSideBandBackground: "<<scaleSideBandBackground<<endl;
      totalYieldInvMassFit[i-1] = fMass->GetParameter(0)*fMass->GetParameter(7)/hMData->GetBinWidth(1);
      totalYieldInvMassFitError[i-1] = fMass->GetParError(0)*fMass->GetParameter(7)/hMData->GetBinWidth(1);
      cout<<"totalYieldInvMassFit: "<<totalYieldInvMassFit[i-1]<<" +- "<<totalYieldInvMassFitError[i-1]<<endl;
      float scaleSideBandMethodSignal = fSignalAndSwapped->GetParameter(0)*fSignalAndSwapped->GetParameter(3) / (fSignalAndSwapped->Integral(massSignal1, massSignal2)-fSignalAndSwapped->Integral(massSideBand1, massSideBand2)-fSignalAndSwapped->Integral(massSideBand3, massSideBand4));
      cout<<"scaleSideBandMethodSignal: "<<scaleSideBandMethodSignal<<endl;

      TLatex* texScale = new TLatex(0.18,0.66,Form("side band bg scale: %1.3f", scaleSideBandBackground));
      texScale->SetNDC();
      texScale->SetTextFont(42);
      texScale->SetTextSize(0.06);
      texScale->SetLineWidth(2);
      texScale->Draw();

      TLine* lineSignal1 = new TLine(massSignal1, 0, massSignal1, hMData->GetMaximum()*0.5);
      TLine* lineSignal2 = new TLine(massSignal2, 0, massSignal2, hMData->GetMaximum()*0.5);
      TLine* lineSideBand1 = new TLine(massSideBand1, 0, massSideBand1, hMData->GetMaximum()*0.5);
      TLine* lineSideBand2 = new TLine(massSideBand2, 0, massSideBand2, hMData->GetMaximum()*0.5);
      TLine* lineSideBand3 = new TLine(massSideBand3, 0, massSideBand3, hMData->GetMaximum()*0.5);
      TLine* lineSideBand4 = new TLine(massSideBand4, 0, massSideBand4, hMData->GetMaximum()*0.5);
      lineSignal1->Draw();
      lineSignal2->Draw();
      lineSideBand1->Draw();
      lineSideBand2->Draw();
      lineSideBand3->Draw();
      lineSideBand4->Draw();

      c2->cd(2);
      gPad->SetLogy();

      hData->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);
      hSideband->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);
      hMCPSignal->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);
      hMCNPSignal->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);

      TH1D* hD0DcaData0 = (TH1D*)hData->Project3D("y")->Clone("hD0DcaData0");
      TH1D* hD0DcaSideband = (TH1D*)hSideband->Project3D("y")->Clone("hD0DcaSideband");
      TH1D* hD0DcaMCPSignal0 = (TH1D*)hMCPSignal->Project3D("y")->Clone("hD0DcaMCPSignal0");
      TH1D* hD0DcaMCNPSignal0 = (TH1D*)hMCNPSignal->Project3D("y")->Clone("hD0DcaMCNPSignal0");

      float integralRawYieldMCP = hD0DcaMCPSignal0->Integral();
      float integralRawYieldMCNP = hD0DcaMCNPSignal0->Integral();
      cout<<"integralRawYieldMCP: "<<integralRawYieldMCP<<endl;
      cout<<"integralRawYieldMCNP: "<<integralRawYieldMCNP<<endl;

      hD0DcaMCPSignal = hD0DcaMCPSignal0;
      hD0DcaMCNPSignal = hD0DcaMCNPSignal0;

      divideBinWidth(hD0DcaData0);
      divideBinWidth(hD0DcaSideband);
      setColorTitleLabel(hD0DcaData0, 1);
      hD0DcaData0->GetXaxis()->SetRangeUser(-0.07,0.07);
      hD0DcaData0->GetYaxis()->SetTitle("counts per cm");

      TH1D* hD0DcaSideband0 = (TH1D*)hD0DcaSideband->Clone("hD0DcaSideband0");
      hD0DcaSideband->Scale(scaleSideBandBackground);

      TH1D* hD0DcaDataSubSideBand = (TH1D*)hD0DcaData0->Clone("hD0DcaDataSubSideBand");
      hD0DcaDataSubSideBand->Add(hD0DcaSideband,-1);
      hD0DcaDataSubSideBand->Scale(scaleSideBandMethodSignal);

      hD0DcaData0->SetMarkerSize(0.6);
      hD0DcaData0->Draw();
      hD0DcaSideband->Draw("hsame");
      hD0DcaSideband0->SetLineStyle(2);
      hD0DcaSideband0->Draw("hsame");

      TLegend* leg1 = new TLegend(0.44,0.6,0.90,0.76,NULL,"brNDC");
      leg1->SetBorderSize(0);
      leg1->SetTextSize(0.06);
      leg1->SetTextFont(42);
      leg1->SetFillStyle(0);
      leg1->AddEntry(hD0DcaData0,"D^{0} candidate","pl");
      leg1->AddEntry(hD0DcaSideband,"side band","l");
      leg1->AddEntry(hD0DcaSideband0,"side band unscaled","l");
      leg1->Draw("same");

      texCms->Draw();
      texCol->Draw();
      texPtY->Draw();

      c2->SaveAs(Form("plots/PP_%.0f_%.0f_sideBand.pdf",ptLow,ptHigh));

      c2->cd(1);
      hMMCSignal->Draw();
      texCms->Draw();
      texCol->Draw();
      texPt->Draw();
      texY->Draw();

      c2->cd(2);
      gPad->SetLogy(0);
      hMMCSwapped->Draw();
      texCms->Draw();
      texCol->Draw();
      texPt->Draw();
      texY->Draw();

      c2->SaveAs(Form("plots/PP_%.0f_%.0f_McInvMassFit.pdf",ptLow,ptHigh));

      c15->cd(1);
      
      fitMass(hMData, hMMCSignal, hMMCSwapped);

      texPt->Draw();
      texY->Draw();

      TH1D* hD0DcaDataFit = new TH1D("hD0DcaDataFit", ";D^{0} DCA (cm);dN / d(D^{0} DCA) (cm^{-1})", nBinY, binsY);

      for(int j=1; j<=20; j++)
	{
	  c15->cd(j+1);
	  hPtMD0Dca->GetZaxis()->SetRange(j,j);
          float D0DcaLow = hPtMD0Dca->GetZaxis()->GetBinLowEdge(j);
	  float D0DcaHigh = hPtMD0Dca->GetZaxis()->GetBinUpEdge(j);
	  TH1D* hMData_D0Dca = (TH1D*)hPtMD0Dca->Project3D("y")->Clone(Form("hM_pt_%1.1f_%1.1f_D0Dca_%1.4f_%1.4f", ptLow, ptHigh, D0DcaLow, D0DcaHigh));
	  setColorTitleLabel(hMData_D0Dca);
	  fMass = fitMass(hMData_D0Dca, hMMCSignal, hMMCSwapped);

	  float yield = fMass->GetParameter(0)*fMass->GetParameter(7)/hMData_D0Dca->GetBinWidth(1);
	  float yieldError = fMass->GetParError(0)*fMass->GetParameter(7)/hMData_D0Dca->GetBinWidth(1);

	  hD0DcaDataFit->SetBinContent(j, yield);
	  hD0DcaDataFit->SetBinError(j, yieldError);

	  TLatex* texD0Dca = new TLatex(0.18,0.82,Form("D^{0} DCA: %1.4f - %1.4f",D0DcaLow,D0DcaHigh));
	  texD0Dca->SetNDC();
	  texD0Dca->SetTextFont(42);
	  texD0Dca->SetTextSize(0.06);
	  texD0Dca->SetLineWidth(2);
	  texD0Dca->Draw();

          TLatex* texYield = new TLatex(0.18,0.74,Form("D^{0} yield: %1.0f #pm %1.0f",yield,yieldError));
          texYield->SetNDC();
          texYield->SetTextFont(42);
          texYield->SetTextSize(0.06);
          texYield->SetLineWidth(2);
          texYield->Draw();
	}

      c15->SaveAs(Form("plots/PP_%.0f_%.0f_invMassFit.pdf",ptLow,ptHigh));

    if(pts[i-1]<=20)
    {     D0DcaDataOut[i-1]=(TH1D*)hD0DcaDataFit->Clone(Form("D0DcaDataOut_pt%i",i-1));}
    if(pts[i-1]>20)
    {      D0DcaDataOut[i-1]=(TH1D*)hD0DcaDataSubSideBand->Clone(Form("D0DcaDataOut_pt%i",i-1));
      mutiplyBinWidth(D0DcaDataOut[i-1]);
    }



      divideBinWidth(hD0DcaDataFit);

      c4->cd(1);
      gPad->SetLogy();
 
      normalize(hD0DcaMCPSignal);
      setColorTitleLabel(hD0DcaMCPSignal, 2);
      hD0DcaMCPSignal->GetXaxis()->SetRangeUser(-0.07,0.07);
   
      normalize(hD0DcaMCNPSignal);
      setColorTitleLabel(hD0DcaMCNPSignal, 4);
      hD0DcaMCNPSignal->GetXaxis()->SetRangeUser(-0.07,0.07);
      hD0DcaMCNPSignal->GetYaxis()->SetTitle("dN / d(D^{0} DCA) (cm^{-1})");
      hD0DcaMCNPSignal->GetXaxis()->SetTitle("D^{0} DCA (cm)");
      hD0DcaMCNPSignal->SetMaximum(hD0DcaMCPSignal->GetMaximum()*3.);

      hD0DcaMCNPSignal->Draw("");
      hD0DcaMCPSignal->Draw("same");

      TLegend* leg2 = new TLegend(0.54,0.72,0.90,0.88,NULL,"brNDC");
      leg2->SetBorderSize(0);
      leg2->SetTextSize(0.06);
      leg2->SetTextFont(42);
      leg2->SetFillStyle(0);
      leg2->AddEntry(hD0DcaMCPSignal,"MC Prompt D^{0}","pl");
      leg2->AddEntry(hD0DcaMCNPSignal,"MC Non-prompt D^{0}","pl");
      leg2->Draw("same");

      c4->cd(2);
      gPad->SetLogy();
      
      TH1D* hD0DcaData = hD0DcaDataFit;
      if(pts[i-1]>8) hD0DcaData = hD0DcaDataSubSideBand;

      setColorTitleLabel(hD0DcaData, 1);

      double integralTotalYield = hD0DcaData->Integral(1,hD0DcaData->GetXaxis()->GetNbins(),"width");
      cout<<"integralTotalYield: "<<integralTotalYield<<endl;

      TF1* fMix = new TF1("fMix",&funMix, -0.5, 0.5, 2);
      fMix->SetParameters(0.5*integralTotalYield,0.5*integralTotalYield);
      fMix->SetParLimits(0,0,2*integralTotalYield);
      fMix->SetParLimits(1,0,2*integralTotalYield);

      fMix->SetLineColor(2);
      fMix->SetFillColor(kRed-9);
      fMix->SetFillStyle(1001);
      
      float fitRangeL = -0.08;
      float fitRangeH = 0.08;
      
      hD0DcaData->GetXaxis()->SetRangeUser(-0.07,0.07);
      hD0DcaData->Draw();
      int fitStatus = 1;
      TFitResultPtr fitResult;
      double fitPrecision = 1.e-6;
      while(fitStatus)
	{
	  TFitter::SetPrecision(fitPrecision);
	  fMix->SetParameters(0.5*integralTotalYield,0.5*integralTotalYield);
	  fMix->SetParError(0,0.1*integralTotalYield);
	  fMix->SetParError(1,0.1*integralTotalYield);
	  fitResult = hD0DcaData->Fit("fMix","E SNQ0", "", fitRangeL, fitRangeH);
	  fitStatus = fitResult->Status();
	  cout<<"fit precision: "<<TFitter::GetPrecision()<<"   status: "<<fitStatus<<endl;
	  if(fitStatus)
	    fitPrecision *= 10;
	}
      cout<<"============== do main fit ============"<<endl;
      fMix->SetParameters(integralTotalYield,0.9);
      fMix->SetParError(0,0.1*integralTotalYield);
      fMix->SetParError(1,0.1);
      fMix->SetNpx(10000);
      fitResult = hD0DcaData->Fit("fMix","E S0", "", fitRangeL, fitRangeH);
      hD0DcaData->GetFunction("fMix")->Draw("flsame");
      fitStatus = fitResult->Status();
      cout<<"fit precision: "<<TFitter::GetPrecision()<<"   status: "<<fitStatus<<endl;

      TF1* fNP = new TF1("fNP",&funNonPrompt, 0., 0.5, 2);
      fNP->SetParameters(fMix->GetParameter(0),fMix->GetParameter(1));
      fNP->SetRange(fitRangeL,fitRangeH);
      fNP->SetLineColor(4);
      fNP->SetFillStyle(1001);
      fNP->SetFillColor(kBlue-9);
      fNP->SetNpx(10000);
      fNP->Draw("same");  
   
      hD0DcaData->Draw("same");

      promptDYield[i-1] = fMix->GetParameter(0);
      promptDYieldErrorDataOnly[i-1] = fMix->GetParError(0);
      bToDYield[i-1] = fMix->GetParameter(1);
      bToDYieldErrorDataOnly[i-1] = fMix->GetParError(1);
      totalYield[i-1] = promptDYield[i-1]+bToDYield[i-1];
      promptFraction[i-1] = promptDYield[i-1]/totalYield[i-1];

      cout<<"chi2 / NDF: "<<fitResult->Chi2()<<" / "<<fitResult->Ndf()<<endl;

      texCms->Draw();
      texCol->Draw();
      texPtY->Draw();

      TLatex* texPrompt = new TLatex(0.4,0.73,Form("Prompt D^{0} yield : %.0f #pm %.0f",fMix->GetParameter(0),fMix->GetParError(0)));
      texPrompt->SetNDC();
      texPrompt->SetTextFont(42);
      texPrompt->SetTextSize(0.06);
      texPrompt->SetLineWidth(2);
      texPrompt->Draw();
      
      TLatex* texNonPrompt = new TLatex(0.4,0.65,Form("B to D^{0} yield : %.0f #pm %.0f",fMix->GetParameter(1),fMix->GetParError(1)));
      texNonPrompt->SetNDC();
      texNonPrompt->SetTextFont(42);
      texNonPrompt->SetTextSize(0.06);
      texNonPrompt->SetLineWidth(2);
      texNonPrompt->Draw();

      TLegend* leg4 = new TLegend(0.56,0.38,0.90,0.62);
      leg4->SetBorderSize(0);
      leg4->SetTextSize(0.06);
      leg4->SetTextFont(42);
      leg4->SetFillStyle(0);
      leg4->AddEntry(hD0DcaData,"Data","pl");
      leg4->AddEntry(fMix,"Prompt D^{0}","f");
      leg4->AddEntry(fNP,"B to D^{0}","f");
      leg4->Draw("same");

      //smear MC smaple with the error, to simulate the MC statistic error effect.
      c4->cd(3);

      hD0DcaMCPSignal = (TH1D*)hD0DcaMCPSignal0->Clone("hMCPSignal");
      hD0DcaMCNPSignal = (TH1D*)hD0DcaMCNPSignal0->Clone("hMCNPSignal");
      
      TH1D* hNPYield = new TH1D("hNPYield", ";hNPYield", 100, 0., 1.1*(fMix->GetParameter(0)+fMix->GetParameter(1)));
      TH1D* hPYield = new TH1D("hPYield", ";hPYield", 100, 0., 1.1*(fMix->GetParameter(0)+fMix->GetParameter(1)));
      setColorTitleLabel(hNPYield, 1);
      setColorTitleLabel(hPYield, 1);

      int nSmear = 1000;

      for(int j=0; j<nSmear; j++)
	{
	  RandomSmear(hD0DcaMCPSignal0, hD0DcaMCPSignal);
	  RandomSmear(hD0DcaMCNPSignal0, hD0DcaMCNPSignal);
          fMix->SetParameters(0.5*integralTotalYield,0.5*integralTotalYield);
          fMix->SetParError(0,0.1*integralTotalYield);
          fMix->SetParError(1,0.1*integralTotalYield);

	  hD0DcaData->Fit("fMix","E QN0");
	  
          hPYield->Fill(fMix->GetParameter(0));
	  hNPYield->Fill(fMix->GetParameter(1));
	}
      
      hPYield->GetXaxis()->SetTitle("prompt D^{0} yield");
      hPYield->GetYaxis()->SetTitle("counts");
      hPYield->GetYaxis()->SetRangeUser(0.5, 1.4*hPYield->GetMaximum());
      hPYield->SetMarkerStyle(20);
      hPYield->SetStats(0);
      hPYield->Draw("e");
      hPYield->Fit("gaus");
      
      TLatex* texGaussMeanSigmaP = new TLatex(0.27,0.83,Form("#mu: %.0f              #sigma: %.0f",hPYield->GetFunction("gaus")->GetParameter(1),hPYield->GetFunction("gaus")->GetParameter(2)));
      texGaussMeanSigmaP->SetNDC();
      texGaussMeanSigmaP->SetTextFont(42);
      texGaussMeanSigmaP->SetTextSize(0.06);
      texGaussMeanSigmaP->SetLineWidth(2);
      texGaussMeanSigmaP->Draw();

      float promptYieldErrorMc = hPYield->GetFunction("gaus")->GetParameter(2);
      promptDYieldError[i-1] = sqrt(pow(promptDYieldErrorDataOnly[i-1],2)+pow(promptYieldErrorMc,2));

      c4->cd(4);

      hNPYield->GetXaxis()->SetTitle("B to D^{0} yield");
      hNPYield->GetYaxis()->SetTitle("counts");
      hNPYield->GetYaxis()->SetRangeUser(0.5, 1.4*hNPYield->GetMaximum());
      hNPYield->SetMarkerStyle(20);
      hNPYield->SetStats(0);
      hNPYield->Draw("e");
      hNPYield->Fit("gaus");

      TLatex* texGaussMeanSigmaNP = new TLatex(0.27,0.83,Form("#mu: %.0f              #sigma: %.0f",hNPYield->GetFunction("gaus")->GetParameter(1),hNPYield->GetFunction("gaus")->GetParameter(2)));
      texGaussMeanSigmaNP->SetNDC();
      texGaussMeanSigmaNP->SetTextFont(42);
      texGaussMeanSigmaNP->SetTextSize(0.06);
      texGaussMeanSigmaNP->SetLineWidth(2);
      texGaussMeanSigmaNP->Draw();

      float bToDYieldErrorMc = hNPYield->GetFunction("gaus")->GetParameter(2);
      bToDYieldError[i-1] = sqrt(pow(bToDYieldErrorDataOnly[i-1],2)+pow(bToDYieldErrorMc,2));

      cout<<"prompt D yield: "<<promptDYield[i-1]<<" +- "<<promptDYieldError[i-1]<<" (+- "<<promptDYieldErrorDataOnly[i-1]<<" +- "<<promptYieldErrorMc<<" )"<<endl;
      cout<<"B to D yield: "<<bToDYield[i-1]<<" +- "<<bToDYieldError[i-1]<<" (+- "<<bToDYieldErrorDataOnly[i-1]<<" +- "<<bToDYieldErrorMc<<" )"<<endl;
      cout<<"total yield: "<<totalYield[i-1]<<endl;
      cout<<"prompt fraction: "<<promptFraction[i-1]<<endl;

      float promptMCScale = promptDYield[i-1]/integralRawYieldMCP;
      float nonPromptMCScale = bToDYield[i-1]/integralRawYieldMCNP;

      cout<<"promptMCScale: "<<promptMCScale<<endl;
      cout<<"nonPromptMCScale: "<<nonPromptMCScale<<endl;

      //restore original unsmeared histograms before saving plots
      delete hD0DcaMCPSignal;
      delete hD0DcaMCNPSignal;
      hD0DcaMCPSignal = hD0DcaMCPSignal0;
      hD0DcaMCNPSignal = hD0DcaMCNPSignal0;
      hD0DcaData->Fit("fMix","E QN0");

      c4->SaveAs(Form("plots/PP_%.0f_%.0f_fit.pdf",ptLow,ptHigh));

      c1->cd();

      TH1D* hD0DcaDataOverFit = (TH1D*)hD0DcaData->Clone("hD0DcaDataOverFit");
      hD0DcaDataOverFit->Divide(fMix);
      hD0DcaDataOverFit->GetYaxis()->SetTitle("data / fit");
      hD0DcaDataOverFit->GetYaxis()->SetRangeUser(0,5);
      hD0DcaDataOverFit->GetXaxis()->SetRangeUser(-0.07,0.07);
      setColorTitleLabel(hD0DcaDataOverFit, 1);
      hD0DcaDataOverFit->Draw("e");
      
      TF1* fLine1 = new TF1("fLine1", "1", 0,1);
      fLine1->Draw("same");
      hD0DcaDataOverFit->Draw("esame");
      
      c1->SaveAs(Form("plots/dataOverFit_%.0f_%.0f_fit.pdf",ptLow,ptHigh));

      delete hD0DcaMCPSignal;
      delete hD0DcaMCNPSignal;

    }
  c1->cd();

  TH1D* hStupidJie = new TH1D("hStupidJie", "", 100, 0, 100);
  hStupidJie->GetYaxis()->SetRangeUser(0,1);
  hStupidJie->GetXaxis()->SetTitle("p_{T} (GeV/c)");
  hStupidJie->GetYaxis()->SetTitle("prompt fraction");
  hStupidJie->SetStats(0);
  hStupidJie->Draw();
  TGraph* grFraction = new TGraph(nPtBins, pts, promptFraction);
  grFraction->SetName("grPromptFraction");
  grFraction->SetMarkerStyle(20);
  grFraction->Draw("psame");

  c1->SaveAs("promptFraction.pdf");

  c1->SetLogy();

  TH1D* hBtoDRawYield = new TH1D("hBtoDRawYield", ";p_{T} (GeV/c);dN/dp_{T} ((GeV/c)^{-1})", nPtBins, ptBins);
  for(int i=1; i<=nPtBins; i++)
    {
      if(bToDYield[i-1] <= 0) continue;
      hBtoDRawYield->SetBinContent(i, bToDYield[i-1]);
      hBtoDRawYield->SetBinError(i, bToDYieldError[i-1]);
    }
  divideBinWidth(hBtoDRawYield);
  setColorTitleLabel(hBtoDRawYield, 1);
  c1->SetBottomMargin(0.14);
  hBtoDRawYield->Draw("p");
  c1->SaveAs("BtoD.pdf");

  TH1D* hPromptDRawYield = new TH1D("hPromptDRawYield", ";p_{T} (GeV/c);dN/dp_{T} ((GeV/c)^{-1})", nPtBins, ptBins);
  for(int i=1; i<=nPtBins; i++)
    {
      if(promptDYield[i-1] <= 0) continue;
      hPromptDRawYield->SetBinContent(i, promptDYield[i-1]);
      hPromptDRawYield->SetBinError(i, promptDYieldError[i-1]);
    }
  divideBinWidth(hPromptDRawYield);
  setColorTitleLabel(hPromptDRawYield, 1);
  c1->SetBottomMargin(0.14);
  hPromptDRawYield->Draw("p");
  c1->SaveAs("promptD.pdf");

  TH1D* hTotalDYieldInvMassFit = new TH1D("hTotalDYieldInvMassFit", ";p_{T} (GeV/c);dN/dp_{T} ((GeV/c)^{-1})", nPtBins, ptBins);
  for(int i=1; i<=nPtBins; i++)
    {
      if(totalYieldInvMassFit[i-1] <= 0) continue;
      hTotalDYieldInvMassFit->SetBinContent(i, totalYieldInvMassFit[i-1]);
      hTotalDYieldInvMassFit->SetBinError(i, totalYieldInvMassFitError[i-1]);
    }
  divideBinWidth(hTotalDYieldInvMassFit);
  setColorTitleLabel(hTotalDYieldInvMassFit, 1);
  hTotalDYieldInvMassFit->Draw("p");
  c1->SaveAs("totalDInvMassFit.pdf");

  TFile* fOut = new TFile("bFeedDownResult.root", "recreate");
  fOut->WriteTObject(grFraction);
  fOut->WriteTObject(hBtoDRawYield);
  fOut->WriteTObject(hPromptDRawYield);
  fOut->WriteTObject(hTotalDYieldInvMassFit);

  fOut->cd();
  for (int i = 0; i<nPtBins;i++){
    D0DcaDataOut[i]->Write();
  }

  fOut->Write();
  fOut->Close();

	cout<<"end of main"<<endl;
}
TF1* fit(TString variable, TString variableplot, TTree* nt, TTree* ntMC, Double_t ptmin, Double_t ptmax, int isMC)
{
  static int count=0;
  count++;

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

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

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

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

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

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

  TLatex* tex;

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

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

  h->GetFunction(Form("f%d",count))->Delete();
  TH1F* histo_copy_nofitfun = ( TH1F * ) h->Clone("histo_copy_nofitfun");
  histo_copy_nofitfun->Draw("esame");
//
  if(nBins==1) c->SaveAs(Form("DMass-inclusive%s_%d.pdf",collisionsystem.Data(),count));
  else c->SaveAs(Form("DMass%s_%d.pdf",collisionsystem.Data(),count));
  
  return mass;
}
Beispiel #27
0
//_________________________________________________________________________________________
Int_t checkPullTree(TString pathTree,  TString pathNameThetaMap, TString pathNameSigmaMap,
                    TString mapSuffix, const Int_t collType /*0: pp, 1: pPb, 2: PbPb*/, const Bool_t plotPull = kTRUE,
                    const Double_t downScaleFactor = 1,
                    TString pathNameSplinesFile = "", TString prSplinesName = "",
                    TString fileNameTree = "bhess_PIDetaTree.root", TString treeName = "fTree")
{
  const Bool_t isNonPP = collType != 0;
  const Double_t massProton = AliPID::ParticleMass(AliPID::kProton);
  
  Bool_t recalculateExpecteddEdx = pathNameSplinesFile != "";
  
  TFile* f = 0x0;
	
  f = TFile::Open(Form("%s/%s", pathTree.Data(), fileNameTree.Data()));
  if (!f)  {
    std::cout << "Failed to open tree file \"" << Form("%s/%s", pathTree.Data(), fileNameTree.Data()) << "\"!" << std::endl;
    return -1;
  }
      
  // Extract the data Tree
  TTree* tree = dynamic_cast<TTree*>(f->Get(treeName.Data()));
  if (!tree) {
    std::cout << "Failed to load data tree!" << std::endl;
    return -1;
  }
  
  // Extract the splines, if desired
  TSpline3* splPr = 0x0;
  if (recalculateExpecteddEdx) {
    std::cout << "Loading splines to recalculate expected dEdx!" << std::endl << std::endl;
    
    TFile* fSpl = TFile::Open(pathNameSplinesFile.Data());
    if (!fSpl) {
      std::cout << "Failed to open spline file \"" << pathNameSplinesFile.Data() << "\"!" << std::endl;
      return 0x0;
    }
    
    TObjArray* TPCPIDResponse = (TObjArray*)fSpl->Get("TPCPIDResponse");
    if (!TPCPIDResponse) {
      splPr = (TSpline3*)fSpl->Get(prSplinesName.Data());
      
      // If splines are in file directly, without TPCPIDResponse object, try to load them
      if (!splPr) {
        std::cout << "Failed to load object array from spline file \"" << pathNameSplinesFile.Data() << "\"!" << std::endl;
        return 0x0;
      }
    }
    else {
      splPr = (TSpline3*)TPCPIDResponse->FindObject(prSplinesName.Data());
      
      if (!splPr) {
        std::cout << "Failed to load splines from file \"" << pathNameSplinesFile.Data() << "\"!" << std::endl;
        return 0x0;
      }
    }
  }
  else
    std::cout << "Taking dEdxExpected from Tree..." << std::endl << std::endl;

  // Extract the correction maps
  TFile* fMap = TFile::Open(pathNameThetaMap.Data());
  if (!fMap)  {
    std::cout << "Failed to open thetaMap file \"" << pathNameThetaMap.Data() << "\"! Will not additionally correct data...." << std::endl;
  }

  TH2D* hMap = 0x0;
  
  if (fMap) {
    hMap = dynamic_cast<TH2D*>(fMap->Get(Form("hRefined%s", mapSuffix.Data())));
    if (!hMap) {
      std::cout << "Failed to load theta map!" << std::endl;
      return -1;
    }
  }

  TFile* fSigmaMap = TFile::Open(pathNameSigmaMap.Data());
  if (!fSigmaMap)  {
    std::cout << "Failed to open simgaMap file \"" << pathNameSigmaMap.Data() << "\"!" << std::endl;
    return -1;
  }

  TH2D* hThetaMapSigmaPar1 = dynamic_cast<TH2D*>(fSigmaMap->Get("hThetaMapSigmaPar1"));
  if (!hThetaMapSigmaPar1) {
    std::cout << "Failed to load sigma map for par 1!" << std::endl;
    return -1;
  }

  Double_t c0 = -1;
  TNamed* c0Info = dynamic_cast<TNamed*>(fSigmaMap->Get("c0"));
  if (!c0Info) {
    std::cout << "Failed to extract c0 from file with sigma map!" << std::endl;
    return -1;
  }

  TString c0String = c0Info->GetTitle();
  c0 = c0String.Atof();
  printf("Loaded parameter 0 for sigma: %f\n\n", c0);

  if (plotPull)
    std::cout << "Plotting pull..." << std::endl << std::endl;
  else
    std::cout << "Plotting delta'..." << std::endl << std::endl;

  Long64_t nTreeEntries = tree->GetEntriesFast();

  Double_t dEdx = 0.; // Measured dE/dx
  Double_t dEdxExpected = 0.; // Expected dE/dx according to parametrisation
  Double_t tanTheta = 0.; // Tangens of (local) theta at TPC inner wall
  Double_t pTPC = 0.; // Momentum at TPC inner wall
  UShort_t tpcSignalN = 0; // Number of clusters used for dEdx
  UChar_t  pidType = 0;
  Int_t    fMultiplicity = 0;
  //Double_t phiPrime = 0;

  // Only activate the branches of interest to save processing time
  tree->SetBranchStatus("*", 0); // Disable all branches
  tree->SetBranchStatus("pTPC", 1);
  tree->SetBranchStatus("dEdx", 1);
  tree->SetBranchStatus("dEdxExpected", 1);
  tree->SetBranchStatus("tanTheta", 1);
  tree->SetBranchStatus("tpcSignalN", 1);
  tree->SetBranchStatus("pidType", 1);
  //tree->SetBranchStatus("phiPrime", 1);
  if (isNonPP)
    tree->SetBranchStatus("fMultiplicity", 1);

  
  tree->SetBranchAddress("dEdx", &dEdx);
  tree->SetBranchAddress("dEdxExpected", &dEdxExpected);
  tree->SetBranchAddress("tanTheta", &tanTheta);
  tree->SetBranchAddress("tpcSignalN", &tpcSignalN);
  tree->SetBranchAddress("pTPC", &pTPC);
  tree->SetBranchAddress("pidType", &pidType);
  //tree->SetBranchAddress("phiPrime", &phiPrime);
  if (isNonPP)
    tree->SetBranchAddress("fMultiplicity", &fMultiplicity);

  
  // Output file
  TDatime daTime;
  TString savefileName = Form("%s%s_checkPullSigma_%04d_%02d_%02d__%02d_%02d.root", fileNameTree.ReplaceAll(".root", "").Data(),
                              recalculateExpecteddEdx ? "_recalcdEdx" : "",
                              daTime.GetYear(), daTime.GetMonth(), daTime.GetDay(), daTime.GetHour(), daTime.GetMinute());

  TFile* fSave = TFile::Open(Form("%s/%s", pathTree.Data(), savefileName.Data()), "recreate");
  if (!fSave) {
    std::cout << "Failed to open save file \"" << Form("%s/%s", pathTree.Data(), savefileName.Data()) << "\"!" << std::endl;
    return -1;
  }
  
  const Double_t pBoundLow = 0.1;
  const Double_t pBoundUp = 5;

  const Int_t nBins1 = TMath::Ceil(180 / downScaleFactor);
  const Int_t nBins2 = TMath::Ceil(100 / downScaleFactor);
  const Int_t nBins3 = TMath::Ceil(60 / downScaleFactor);
  
  const Int_t nPbinsForMap = nBins1 + nBins2 + nBins3;
  Double_t binsPforMap[nPbinsForMap + 1];
  
  Double_t binWidth1 = (1.0 - pBoundLow) / nBins1;
  Double_t binWidth2 = (2.0 - 1.0 ) / nBins2;
  Double_t binWidth3 = (pBoundUp - 2.0) / nBins3;
  
  for (Int_t i = 0; i < nBins1; i++)  {
    binsPforMap[i] = pBoundLow + i * binWidth1;
  }
  for (Int_t i = nBins1, j = 0; i < nBins1 + nBins2; i++, j++)  {
    binsPforMap[i] = 1.0 + j * binWidth2;
  }
  for (Int_t i = nBins1 + nBins2, j = 0; i < nBins1 + nBins2 + nBins3; i++, j++)  {
    binsPforMap[i] = 2.0 + j * binWidth3;
  }
  binsPforMap[nPbinsForMap] = pBoundUp;

  TH2D* hPull = new TH2D("hPull", "Pull vs. p_{TPC} integrated over tan(#Theta);p_{TPC} (GeV/c);Pull", nPbinsForMap, binsPforMap, 
                         plotPull ? 120 : 240, plotPull ? -6 : -0.6, plotPull ? 6 : 0.6);
  TH2D* hPullAdditionalCorr = (TH2D*)hPull->Clone("hPullAdditionalCorr");
  hPullAdditionalCorr->SetTitle("Pull vs. p_{TPC} integrated over tan(#Theta) with additional dEdx correction w.r.t. tan(#Theta)");
  /*
  const Int_t nThetaHistos = 3;
  TH2D* hPullTheta[nThetaHistos];
  TH2D* hPullAdditionalCorrTheta[nThetaHistos];
  Double_t tThetaLow[nThetaHistos] = { 0.0, 0.4, 0.9 };
  Double_t tThetaHigh[nThetaHistos] = { 0.1, 0.5, 1.0 };
  */
  const Int_t nThetaHistos = 10;
  TH2D* hPullTheta[nThetaHistos];
  TH2D* hPullAdditionalCorrTheta[nThetaHistos];
  Double_t tThetaLow[nThetaHistos] = { 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9 };
  Double_t tThetaHigh[nThetaHistos] = { 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0 };
  

  for (Int_t i = 0; i < nThetaHistos; i++)    {
    hPullTheta[i] = new TH2D(Form("hPullTheta_%d", i),
                             Form("Pull vs. p_{TPC} for %.2f <= |tan(#Theta)| < %.2f;p_{TPC} (GeV/c);Pull", tThetaLow[i], tThetaHigh[i]),
                             nPbinsForMap, binsPforMap, plotPull ? 120 : 240, plotPull ? -6 : -0.6, plotPull ? 6 : 0.6);

    hPullAdditionalCorrTheta[i] =
      new TH2D(Form("hPullAdditionalCorrTheta_%d", i),
               Form("Pull vs. p_{TPC} for %.2f <= |tan(#Theta)| < %.2f with additional dEdx correction w.r.t. tan(#Theta);p_{TPC} (GeV/c);Pull",
                    tThetaLow[i], tThetaHigh[i]),
               nPbinsForMap, binsPforMap, plotPull ? 120 : 240, plotPull ? -6 : -0.6, plotPull ? 6 : 0.6);
  }

  
  
  
  
  
  TF1 corrFuncMult("corrFuncMult", "[0] + [1]*TMath::Max([4], TMath::Min(x, [3])) + [2] * TMath::Power(TMath::Max([4], TMath::Min(x, [3])), 2)",
                   0., 0.2);
  TF1 corrFuncMultTanTheta("corrFuncMultTanTheta", "[0] * (x -[2]) + [1] * (x * x - [2] * [2])", -1.5, 1.5);
  TF1 corrFuncSigmaMult("corrFuncSigmaMul", "TMath::Max(0, [0] + [1]*TMath::Min(x, [3]) + [2] * TMath::Power(TMath::Min(x, [3]), 2))", 0., 0.2);
  
  
  // LHC13b.pass2
  if (isNonPP)
    printf("Using corr Parameters for 13b.pass2\n!");
  
  corrFuncMult.SetParameter(0, -5.906e-06);
  corrFuncMult.SetParameter(1, -5.064e-04);
  corrFuncMult.SetParameter(2, -3.521e-02);
  corrFuncMult.SetParameter(3,  2.469e-02);
  corrFuncMult.SetParameter(4, 0);
  
  corrFuncMultTanTheta.SetParameter(0, -5.32e-06);
  corrFuncMultTanTheta.SetParameter(1,  1.177e-05);
  corrFuncMultTanTheta.SetParameter(2, -0.5);
  
  corrFuncSigmaMult.SetParameter(0, 0.);
  corrFuncSigmaMult.SetParameter(1, 0.);
  corrFuncSigmaMult.SetParameter(2, 0.);
  corrFuncSigmaMult.SetParameter(3, 0.);
  
  
  /* OK, but PID task was not very satisfying
  corrFuncMult.SetParameter(0, -6.27187e-06);
  corrFuncMult.SetParameter(1, -4.60649e-04);
  corrFuncMult.SetParameter(2, -4.26450e-02);
  corrFuncMult.SetParameter(3, 2.40590e-02);
  corrFuncMult.SetParameter(4, 0);
  
  corrFuncMultTanTheta.SetParameter(0, -5.338e-06);
  corrFuncMultTanTheta.SetParameter(1,  1.220e-05);
  corrFuncMultTanTheta.SetParameter(2, -0.5);
  
  corrFuncSigmaMult.SetParameter(0, 7.89237e-05);
  corrFuncSigmaMult.SetParameter(1, -1.30662e-02);
  corrFuncSigmaMult.SetParameter(2, 8.91548e-01);
  corrFuncSigmaMult.SetParameter(3, 1.47931e-02);
  */
  
  
  /*
  // LHC11a10a
  if (isNonPP)
    printf("Using corr Parameters for 11a10a\n!");
  
  corrFuncMult.SetParameter(0, 6.90133e-06);
  corrFuncMult.SetParameter(1, -1.22123e-03);
  corrFuncMult.SetParameter(2, 1.80220e-02);
  corrFuncMult.SetParameter(3, 0.1);
  corrFuncMult.SetParameter(4, 6.45306e-03);
  
  corrFuncMultTanTheta.SetParameter(0, -2.85505e-07);
  corrFuncMultTanTheta.SetParameter(1, -1.31911e-06);
  corrFuncMultTanTheta.SetParameter(2, -0.5);
  
  corrFuncSigmaMult.SetParameter(0, -4.29665e-05);
  corrFuncSigmaMult.SetParameter(1, 1.37023e-02);
  corrFuncSigmaMult.SetParameter(2, -6.36337e-01);
  corrFuncSigmaMult.SetParameter(3, 1.13479e-02);
  */
  
  /* OLD without saturation and large error for negative slopes
  corrFuncSigmaMult.SetParameter(0, -4.79684e-05);
  corrFuncSigmaMult.SetParameter(1, 1.49938e-02);
  corrFuncSigmaMult.SetParameter(2, -7.15269e-01);
  corrFuncSigmaMult.SetParameter(3, 1.06855e-02);
  */
  
  /* OLD very good try, but with fewer pBins for the fitting
  corrFuncMult.SetParameter(0, 6.88365e-06);
  corrFuncMult.SetParameter(1, -1.22324e-03);
  corrFuncMult.SetParameter(2, 1.81625e-02);
  corrFuncMult.SetParameter(3, 0.1);
  corrFuncMult.SetParameter(4, 6.36890e-03);
  
  corrFuncMultTanTheta.SetParameter(0, -2.85505e-07);
  corrFuncMultTanTheta.SetParameter(1, -1.31911e-06);
  corrFuncMultTanTheta.SetParameter(2, -0.5);
  
  corrFuncSigmaMult.SetParameter(0, -4.28401e-05);
  corrFuncSigmaMult.SetParameter(1, 1.24812e-02);
  corrFuncSigmaMult.SetParameter(2, -5.28531e-01);
  corrFuncSigmaMult.SetParameter(3, 1.25147e-02);
  */
  /*OLD good try
  corrFuncMult.SetParameter(0, 7.50321e-06);
  corrFuncMult.SetParameter(1, -1.25250e-03);
  corrFuncMult.SetParameter(2, 1.85437e-02);
  corrFuncMult.SetParameter(3, 0.1);
  corrFuncMult.SetParameter(4, 6.21192e-03);
  
  corrFuncMultTanTheta.SetParameter(0, -1.43112e-07);
  corrFuncMultTanTheta.SetParameter(1, -1.53e-06);
  corrFuncMultTanTheta.SetParameter(2, 0.3);
  
  corrFuncSigmaMult.SetParameter(0, -2.54019e-05);
  corrFuncSigmaMult.SetParameter(1, 8.68883e-03);
  corrFuncSigmaMult.SetParameter(2, -3.36176e-01);
  corrFuncSigmaMult.SetParameter(3, 1.29230e-02);
  */
  
  /*
  // LHC10h.pass2
  if (isNonPP)
    printf("Using corr Parameters for 10h.pass2\n!");
  
  corrFuncMult.SetParameter(0, 3.21636e-07);
  corrFuncMult.SetParameter(1, -6.65876e-04);
  corrFuncMult.SetParameter(2, 1.28786e-03);
  corrFuncMult.SetParameter(3, 1.47677e-02);
  corrFuncMult.SetParameter(4, 0.);
  
  corrFuncMultTanTheta.SetParameter(0, 7.23591e-08);
  corrFuncMultTanTheta.SetParameter(1, 2.7469e-06);
  corrFuncMultTanTheta.SetParameter(2, -0.5);
  
  corrFuncSigmaMult.SetParameter(0, -1.22590e-05);
  corrFuncSigmaMult.SetParameter(1, 6.88888e-03);
  corrFuncSigmaMult.SetParameter(2, -3.20788e-01);
  corrFuncSigmaMult.SetParameter(3, 1.07345e-02);
  */
  
  /*OLD bad try
  corrFuncMult.SetParameter(0, 2.71514e-07);
  corrFuncMult.SetParameter(1, -6.92031e-04);
  corrFuncMult.SetParameter(2, 3.56042e-03);
  corrFuncMult.SetParameter(3, 1.47497e-02);
  corrFuncMult.SetParameter(4, 0.);
  
  corrFuncMultTanTheta.SetParameter(0, 8.53204e-08);
  corrFuncMultTanTheta.SetParameter(1, 2.85591e-06);
  corrFuncMultTanTheta.SetParameter(2, -0.5);
  
  corrFuncSigmaMult.SetParameter(0, -6.82477e-06);
  corrFuncSigmaMult.SetParameter(1, 4.97051e-03);
  corrFuncSigmaMult.SetParameter(2, -1.64954e-01);
  corrFuncSigmaMult.SetParameter(3, 9.21061e-03);
  */
  

  //TODO NOW
  TF1* fShapeSmallP = new TF1("fShapeSmallP", "pol5", -0.4, 0.4);
  fShapeSmallP->SetParameters(1.01712, -0.0202725, -0.260692, 0.261623, 0.671854, -1.14014);
    
  for (Long64_t i = 0; i < nTreeEntries; i++) {
    tree->GetEntry(i);

    if (dEdx <= 0 || dEdxExpected <= 0 || tpcSignalN <= 10)
      continue;
    /*
    Double_t pT = pTPC*TMath::Sin(-TMath::ATan(tanTheta)+TMath::Pi()/2.0);
    if ((phiPrime > 0.072/pT+TMath::Pi()/18.0-0.035 && phiPrime < 0.07/pT/pT+0.1/pT+TMath::Pi()/18.0+0.035)) 
      continue;
    */
      
    if (pidType != kMCid) {
      if (pidType == kTPCid && pTPC > 0.6)
        continue;
      if (pidType == kTPCandTOFid && (pTPC < 0.6 || pTPC > 2.0))
        continue;
      if ((collType == 2) && pidType == kTPCandTOFid && pTPC > 1.0)
        continue;// Only V0's in case of PbPb above 1.0 GeV/c
      if (pidType == kV0idPlusTOFrejected) //TODO NOW NEW
        continue;
    }
    
    if (recalculateExpecteddEdx) {
      dEdxExpected = 50. * splPr->Eval(pTPC / massProton); //WARNING: What, if MIP is different from 50.? Seems not to be used (tested for pp, MC_pp, PbPb and MC_PbPb), but can in principle happen
    }
      
    //TODO NOW
    /*
    if (TMath::Abs(tanTheta) <= 0.4) {
      Double_t p0 = fShapeSmallP->Eval(tanTheta) - 1.0; // Strength of the correction
      Double_t p1 = -9.0; // How fast the correction is turned off
      Double_t p2 = -0.209; // Turn off correction around 0.2 GeV/c
      Double_t p3 = 1.0; // Delta' for large p should be 1

      Double_t corrFactor = TMath::Erf((pTPC + p2) * p1) * p0 + p3 + p0; // Add p0 to have 1 for p3 = 1 and large pTPC
      dEdxExpected *= corrFactor;
    }*/
    
     /*TODO old unsuccessful try 
    Double_t thetaGlobalTPC = -TMath::ATan(tanTheta) + TMath::Pi() / 2.;
    Double_t pTtpc = pTPC * TMath::Sin(thetaGlobalTPC);
    Double_t pTtpcInv = (pTtpc > 0) ? 1. / pTtpc : 0;
    Double_t p0 = 1.0;
    Double_t p1 = 1./ 0.5;//TODO 2.0;
    Double_t p2 = -0.2;//TODO 0.1
    Double_t pTcorrFactor = p0 + (pTtpcInv > p1) * p2 * (pTtpcInv - p1);
    
    dEdxExpected *= pTcorrFactor;
    */
    
      
    // From the momentum (via dEdxExpected) and the tanTheta of the track, the expected dEdx can be calculated (correctedDeDxExpected).
    // If the splines are correct, this should give in average the same value as dEdx. 
    // Now valid: Maps created from corrected data with splines adopted to corrected data, so lookup should be for dEdxExpected=dEdxSplines (no further
    // eta correction) or the corrected dEdx from the track (which should ideally be = dEdxSplines)
    
    // Tested with corrected data for LHC10d.pass2: using dEdx for the lookup (which is the corrected value and should ideally be = dEdxSplines):
    // Results almost the same. Maybe slightly better for dEdxExpected.
    
    // No longer valid: Note that the maps take always the uncorrected dEdx w.r.t.
    // tanTheta, so that correctedDeDxExpected is needed here normally. However, the information for the correction will be lost at some point.
    // Therefore, dEdxExpected can be used instead and should provide a good approximation.
    Double_t c1FromSigmaMap = hThetaMapSigmaPar1->GetBinContent(getBinX(hThetaMapSigmaPar1, tanTheta), getBinY(hThetaMapSigmaPar1, 1./dEdxExpected));
    
    Double_t expectedSigma = dEdxExpected * TMath::Sqrt( c0 * c0 + (c1FromSigmaMap * c1FromSigmaMap) / tpcSignalN);
    Double_t pull = (dEdx - dEdxExpected) / (plotPull ? expectedSigma: dEdxExpected);

    // Fill pull histo
    hPull->Fill(pTPC, pull);

    Double_t tanThetaAbs = TMath::Abs(tanTheta);
    
    for (Int_t j = 0; j < nThetaHistos; j++)    {
      if (tanThetaAbs  >= tThetaLow[j] && tanThetaAbs < tThetaHigh[j])  {
        hPullTheta[j]->Fill(pTPC, pull);
      }
    }

    if (!hMap)
      continue;

    Double_t correctionFactor = 1.;
    
    if (isNonPP) {
      // 1. Correct eta dependence
      correctionFactor = hMap->GetBinContent(getBinX(hMap, tanTheta), getBinY(hMap, 1./dEdxExpected));
      
      // 2. Correct for multiplicity dependence:
      Double_t multCorrectionFactor = 1.;
      
      if (fMultiplicity > 0) {
        Double_t relSlope = corrFuncMult.Eval(1. / (dEdxExpected * correctionFactor));
        relSlope += corrFuncMultTanTheta.Eval(tanTheta);

        multCorrectionFactor = 1. + relSlope * fMultiplicity;
      }

      c1FromSigmaMap = hThetaMapSigmaPar1->GetBinContent(getBinX(hThetaMapSigmaPar1, tanTheta), getBinY(hThetaMapSigmaPar1, 1./dEdxExpected));
      
      // Multiplicity dependence of sigma depends on the real dEdx at zero multiplicity, i.e. the eta (only) corrected dEdxExpected value has to be used
      // since all maps etc. have been created for ~zero multiplicity
      Double_t relSigmaSlope = corrFuncSigmaMult.Eval(1. / (dEdxExpected * correctionFactor));
      Double_t multSigmaCorrectionFactor = 1. + relSigmaSlope * fMultiplicity;
      
      dEdxExpected *= correctionFactor * multCorrectionFactor; 
      
      expectedSigma = dEdxExpected * TMath::Sqrt( c0 * c0 + (c1FromSigmaMap * c1FromSigmaMap) / tpcSignalN);
      expectedSigma *= multSigmaCorrectionFactor;
      
      pull = (dEdx - dEdxExpected) / (plotPull ? expectedSigma: dEdxExpected);
    }
    else {
      correctionFactor = hMap->GetBinContent(getBinX(hMap, tanTheta), getBinY(hMap, 1./dEdxExpected));
      
      c1FromSigmaMap = hThetaMapSigmaPar1->GetBinContent(getBinX(hThetaMapSigmaPar1, tanTheta), getBinY(hThetaMapSigmaPar1, 1./dEdxExpected));
   
      dEdxExpected *= correctionFactor; // If data is not corrected, but the sigma map is for corrected data, re-do analysis with corrected dEdx
      
      expectedSigma = dEdxExpected * TMath::Sqrt( c0 * c0 + (c1FromSigmaMap * c1FromSigmaMap) / tpcSignalN);
      pull = (dEdx - dEdxExpected) / (plotPull ? expectedSigma: dEdxExpected);
    }

    pull = (dEdx - dEdxExpected) / (plotPull ? expectedSigma: dEdxExpected);

    hPullAdditionalCorr->Fill(pTPC, pull);

    for (Int_t j = 0; j < nThetaHistos; j++)    {
      if (tanThetaAbs  >= tThetaLow[j] && tanThetaAbs < tThetaHigh[j])  {
        hPullAdditionalCorrTheta[j]->Fill(pTPC, pull);
      }
    }
  }
/*
  // Mean, Sigma, chi^2/NDF of pull of different theta bins and all in one plot
  TCanvas* canvPullMean = new TCanvas("canvPullMean", "canvPullMean", 100,10,1380,800);
  canvPullMean->SetLogx(kTRUE);
  canvPullMean->SetGridx(kTRUE);
  canvPullMean->SetGridy(kTRUE);
  TCanvas* canvPullSigma = new TCanvas("canvPullSigma", "canvPullSigma", 100,10,1380,800);
  canvPullSigma->SetLogx(kTRUE);
  canvPullSigma->SetGridx(kTRUE);
  canvPullSigma->SetGridy(kTRUE);
  TCanvas* canvPullChi2 = new TCanvas("canvPullChi2", "canvPullChi2", 100,10,1380,800);
  canvPullChi2->SetLogx(kTRUE);
  canvPullChi2->SetGridx(kTRUE);
  canvPullChi2->SetGridy(kTRUE);
  

  TCanvas* canvPull[nThetaHistos + 1];
  for (Int_t i = 0, j = nThetaHistos; i < nThetaHistos + 1; i++, j--)  {
    canvPull[i] = new TCanvas(Form("canvPull_%d", i), "canvPull", 100,10,1380,800);
    canvPull[i]->cd();
    canvPull[i]->SetLogx(kTRUE);
    canvPull[i]->SetLogz(kTRUE);
    canvPull[i]->SetGrid(kTRUE, kTRUE);

    TH2D* hTemp = 0x0;
    TString thetaString = "";
    if (i == nThetaHistos)  {
      hTemp = hPull;
      thetaString = "tan(#Theta) integrated";
    }
    else {
      hTemp = hPullTheta[i];
      thetaString = Form("%.2f #leq |tan(#Theta)| < %.2f", tThetaLow[i], tThetaHigh[i]);
    }
    
    normaliseHisto(hTemp);
    hTemp->FitSlicesY();
    hTemp->GetYaxis()->SetNdivisions(12);
    hTemp->GetXaxis()->SetMoreLogLabels(kTRUE);
    TH1D* hTempMean = (TH1D*)gDirectory->Get(Form("%s_1", hTemp->GetName()));
    hTempMean->SetTitle(Form("mean(pull), %s", thetaString.Data()));
    hTempMean->GetXaxis()->SetMoreLogLabels(kTRUE);
    hTempMean->SetLineWidth(2);
    hTempMean->SetMarkerStyle(20);
    TH1D* hTempSigma = (TH1D*)gDirectory->Get(Form("%s_2", hTemp->GetName()));
    hTempSigma->SetTitle(Form("#sigma(pull), %s", thetaString.Data()));
    hTempSigma->GetXaxis()->SetMoreLogLabels(kTRUE);
    hTempSigma->SetLineColor(kMagenta);
    hTempSigma->SetMarkerStyle(20);
    hTempSigma->SetMarkerColor(kMagenta);
    hTempSigma->SetLineWidth(2);
    TH1D* hTempChi2 = (TH1D*)gDirectory->Get(Form("%s_chi2", hTemp->GetName()));
    hTempChi2->SetTitle(Form("#chi^{2} / NDF (pull), %s", thetaString.Data()));
    hTempChi2->GetXaxis()->SetMoreLogLabels(kTRUE);
    hTempChi2->SetLineColor(kMagenta + 2);
    hTempChi2->SetMarkerStyle(20);
    hTempChi2->SetMarkerColor(kMagenta + 2);
    hTempChi2->SetLineWidth(2);

    hTemp->DrawCopy("colz");
    hTempMean->DrawCopy("same");
    hTempSigma->DrawCopy("same");
    hTempChi2->Scale(-1./10.);
    hTempChi2->DrawCopy("same");
    hTempChi2->Scale(-10.);

    canvPullMean->cd();
    hTempMean->SetLineColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
    hTempMean->SetMarkerColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
    hTempMean->DrawCopy((i == 0 ? "" : "same"));

    canvPullSigma->cd();
    hTempSigma->SetLineColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
    hTempSigma->SetMarkerColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
    hTempSigma->DrawCopy((i == 0 ? "" : "same"));

    canvPullChi2->cd();
    hTempChi2->SetLineColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
    hTempChi2->SetMarkerColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
    hTempChi2->DrawCopy((i == 0 ? "" : "same"));
  }

  canvPullMean->BuildLegend();
  canvPullSigma->BuildLegend();
  canvPullChi2->BuildLegend();
*/
  // Histograms with additional correction
  TCanvas* canvPullMeanCorr = 0x0;
  TCanvas* canvPullSigmaCorr = 0x0;
  TCanvas* canvPullChi2Corr = 0x0;
  TCanvas* canvPullCorr[nThetaHistos + 1];
  for (Int_t i = 0; i < nThetaHistos + 1; i++) 
    canvPullCorr[i] = 0x0;
  
  if (hMap) {
    // Mean, Sigma, chi^2/NDF of pull of different theta bins and all in one plot
    canvPullMeanCorr = new TCanvas("canvPullMeanCorr", "canvPullMeanCorr", 100,10,1380,800);
    canvPullMeanCorr->SetLogx(kTRUE);
    canvPullMeanCorr->SetGridx(kTRUE);
    canvPullMeanCorr->SetGridy(kTRUE);
    canvPullSigmaCorr = new TCanvas("canvPullSigmaCorr", "canvPullSigmaCorr", 100,10,1380,800);
    canvPullSigmaCorr->SetLogx(kTRUE);
    canvPullSigmaCorr->SetGridx(kTRUE);
    canvPullSigmaCorr->SetGridy(kTRUE);
    canvPullChi2Corr = new TCanvas("canvPullChi2Corr", "canvPullChi2Corr", 100,10,1380,800);
    canvPullChi2Corr->SetLogx(kTRUE);
    canvPullChi2Corr->SetGridx(kTRUE);
    canvPullChi2Corr->SetGridy(kTRUE);
    
    for (Int_t i = 0, j = nThetaHistos; i < nThetaHistos + 1; i++, j--)  {
      canvPullCorr[i] = new TCanvas(Form("canvPullCorr_%d", i), "canvPullCorr", 100,10,1380,800);
      canvPullCorr[i]->cd();
      canvPullCorr[i]->SetLogx(kTRUE);
      canvPullCorr[i]->SetLogz(kTRUE);
      canvPullCorr[i]->SetGrid(kTRUE, kTRUE);

      TH2D* hTemp = 0x0;
      TString thetaString = "";
      
      if (i == nThetaHistos)  {
        hTemp = hPullAdditionalCorr;
        thetaString = "tan(#Theta) integrated";
      }
      else    {
        hTemp = hPullAdditionalCorrTheta[i];
        thetaString = Form("%.2f #leq |tan(#Theta)| < %.2f", tThetaLow[i], tThetaHigh[i]);
      }

      normaliseHisto(hTemp);
      hTemp->FitSlicesY();
      hTemp->GetYaxis()->SetNdivisions(12);
      hTemp->GetXaxis()->SetMoreLogLabels(kTRUE);
      TH1D* hTempMean = (TH1D*)gDirectory->Get(Form("%s_1", hTemp->GetName()));
      hTempMean->SetTitle(Form("mean(pull), %s", thetaString.Data()));
      hTempMean->GetXaxis()->SetMoreLogLabels(kTRUE);
      hTempMean->SetLineWidth(2);
      hTempMean->SetMarkerStyle(20);
      TH1D* hTempSigma = (TH1D*)gDirectory->Get(Form("%s_2", hTemp->GetName()));
      hTempSigma->SetTitle(Form("#sigma(pull), %s", thetaString.Data()));
      hTempSigma->GetXaxis()->SetMoreLogLabels(kTRUE);
      hTempSigma->SetLineColor(kMagenta);
      hTempSigma->SetMarkerStyle(20);
      hTempSigma->SetMarkerColor(kMagenta);
      hTempSigma->SetLineWidth(2);
      TH1D* hTempChi2 = (TH1D*)gDirectory->Get(Form("%s_chi2", hTemp->GetName()));
      hTempChi2->SetTitle(Form("#chi^{2} / NDF (pull), %s", thetaString.Data()));
      hTempChi2->GetXaxis()->SetMoreLogLabels(kTRUE);
      hTempChi2->SetLineColor(kMagenta + 2);
      hTempChi2->SetMarkerStyle(20);
      hTempChi2->SetMarkerColor(kMagenta + 2);
      hTempChi2->SetLineWidth(2);

      hTemp->DrawCopy("colz");
      hTempMean->DrawCopy("same");
      hTempSigma->DrawCopy("same");
      hTempChi2->Scale(-1./10.);
      hTempChi2->DrawCopy("same");
      hTempChi2->Scale(-10.);
  
      canvPullMeanCorr->cd();
      hTempMean->SetLineColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
      hTempMean->SetMarkerColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
      hTempMean->DrawCopy((i == 0 ? "" : "same"));
      
      canvPullSigmaCorr->cd();
      hTempSigma->SetLineColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
      hTempSigma->SetMarkerColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
      hTempSigma->DrawCopy((i == 0 ? "" : "same"));
      
      canvPullChi2Corr->cd();
      hTempChi2->SetLineColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
      hTempChi2->SetMarkerColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
      hTempChi2->DrawCopy((i == 0 ? "" : "same"));
    }
    
    canvPullMeanCorr->BuildLegend();
    canvPullSigmaCorr->BuildLegend();
    canvPullChi2Corr->BuildLegend();
  }
  
  
  
  
  
  fSave->cd();
  /*canvPullMean->Write();
  canvPullSigma->Write();
  canvPullChi2->Write();
  
  for (Int_t  i = 0; i < nThetaHistos + 1; i++) {
    canvPull[i]->Write();
  }*/
  
  canvPullMeanCorr->Write();
  canvPullSigmaCorr->Write();
  canvPullChi2Corr->Write();
  
  for (Int_t  i = 0; i < nThetaHistos + 1; i++) {
    canvPullCorr[i]->Write();
  }

  TNamed* info = new TNamed(Form("Theta map: %s\n\nSigma map: %s\n\nSplines file: %s\n\nSplines name: %s", pathNameThetaMap.Data(), 
                                 pathNameSigmaMap.Data(), pathNameSplinesFile.Data(), prSplinesName.Data()),
                            "info");
  info->Write();
  fSave->Close();
  
  return 0;
}
void plotDeltaPhi(int cbin,
		  TString infname,
		  TString pythia,
		  TString mix,
		  bool useWeight,
		  bool drawXLabel,
		  bool drawLeg,
		  bool balance)
{

  TString cut="et1>120 && et2>50";
  TString cutpp="et1>120 && et2>50";
  TString cstring = "";
  if(cbin==0) {
    cstring = "0-10%";
    cut+=" && bin>=0 && bin<4";
    if (balance==true)  cut+=" && ((et1-et2)/(et1+et2) < 0.3)";
    else cut+=" && ((et1-et2)/(et1+et2) > 0.3)";

  } else if (cbin==1) {
    cstring = "10-30%";
    cut+=" && bin>=4 && bin<12";
    if (balance==true)  cut+=" && ((et1-et2)/(et1+et2) < 0.3)";
    else cut+=" && ((et1-et2)/(et1+et2) > 0.3)";

  } else {
    cstring = "30-100%";
    cut+=" && bin>=12 && bin<40";
    if (balance==true)  cut+=" && ((et1-et2)/(et1+et2) < 0.3)";
    else cut+=" && ((et1-et2)/(et1+et2) > 0.3)";
  }

  // open the data file
  TFile *inf = new TFile(infname.Data());
  TTree *nt =(TTree*)inf->FindObjectAny("nt");

  // open the pythia (MC) file
  TFile *infPythia = new TFile(pythia.Data());
  TTree *ntPythia = (TTree*) infPythia->FindObjectAny("nt");

  // open the datamix file
  TFile *infMix = new TFile(mix.Data());
  TTree *ntMix =(TTree*)infMix->FindObjectAny("nt");

  // projection histogram
  TH1D *h = new TH1D("h","",20,-3.14159,3.14159);
  TH1D *hPythia = new TH1D("hPythia","",20,-3.14159,3.14159);
  TH1D *hDataMix = new TH1D("hDataMix","",20,-3.14159,3.14159);
  
  nt->Draw("phi1>>h",Form("(%s)",cut.Data())); 
   
  if (useWeight) {
    // use the weight value caluculated by Matt's analysis macro
    ntPythia->Draw("phi1>>hPythia",Form("(%s)",cutpp.Data())); 
    ntMix->Draw("phi1>>hDataMix",Form("(%s)*weight",cut.Data())); 
  } else {
    // ignore centrality reweighting
     ntPythia->Draw("phi1>>hPythia",Form("(%s)",cutpp.Data()));
     ntMix->Draw("phi1>>hDataMix",Form("(%s)",cut.Data()));  
  }
  
  // calculate the statistical error and normalize
  h->Sumw2();
  h->Scale(1./h->GetEntries());
  h->SetMarkerStyle(20);

  hPythia->Scale(1./hPythia->Integral(0,20));
  hPythia->SetLineColor(kBlue);
  hPythia->SetFillColor(kAzure-8);
  hPythia->SetFillStyle(3005);
   
  hPythia->SetStats(0);
  hPythia->Draw("hist");

  if(drawXLabel) hPythia->SetXTitle("Leading jet #phi");

  hPythia->GetXaxis()->SetLabelSize(20);
  hPythia->GetXaxis()->SetLabelFont(43);
  hPythia->GetXaxis()->SetTitleSize(22);
  hPythia->GetXaxis()->SetTitleFont(43);
  hPythia->GetXaxis()->SetTitleOffset(1.5);
  hPythia->GetXaxis()->CenterTitle();

  //hPythia->GetXaxis()->SetNdivisions(905,true);

  hPythia->SetYTitle("Event Fraction");

  hPythia->GetYaxis()->SetLabelSize(20);
  hPythia->GetYaxis()->SetLabelFont(43);
  hPythia->GetYaxis()->SetTitleSize(20);
  hPythia->GetYaxis()->SetTitleFont(43);
  hPythia->GetYaxis()->SetTitleOffset(2.5);
  hPythia->GetYaxis()->CenterTitle();

  hPythia->SetAxisRange(1.001E-3,5.9,"Y");
  hDataMix->SetAxisRange(1.001E-3,5.9,"Y");
  h->SetAxisRange(1.001E-3,1.9,"Y");

  h->Draw("same");

  hDataMix->Scale(1./hDataMix->Integral(0,20));
  hDataMix->SetLineColor(kRed);
  hDataMix->SetFillColor(kRed-9);
  hDataMix->SetFillStyle(3004);
  hDataMix->Draw("same");

  if(drawLeg){
    TLegend *t3=new TLegend(0.05,0.69,0.59,0.85);
    t3->AddEntry(h,"Pb+Pb  #sqrt{s}_{_{NN}}=2.76 TeV","pl");
    t3->AddEntry(hPythia,"PYTHIA","lf");
    t3->AddEntry(hDataMix,"embedded PYTHIA","lf");
    t3->SetFillColor(0);
    t3->SetBorderSize(0);
    t3->SetFillStyle(0);
    t3->SetTextFont(63);
    t3->SetTextSize(15);
    t3->Draw();
  }

}
Beispiel #29
0
//void testFit(int count=3,Double_t ptmin=30.,Double_t ptmax=40,TString sample="PbPb")
void compareUpgrade(int option=2)
{

  int count; Double_t ptmin; Double_t ptmax; TString sample;
  int nmin,nmax,mymaxhisto;
  
  if (option==1)
  {count=3; ptmin=30.; ptmax=40; sample="PbPb"; mymaxhisto=2000;  };
  if (option==2)
  {count=1; ptmin=2.; ptmax=3; sample="PbPbMB"; mymaxhisto=600000;};


  TCanvas* c= new TCanvas(Form("c%d",count),"",600,600);
  TFile *file=new TFile(Form("FitsFiles/Fits_%s_%d.root",sample.Data(), count));
  TH1D* h = (TH1D*)file->Get(Form("h-%d",count));
  TH1D* hMCSignal = (TH1D*)file->Get(Form("hMCSignal-%d",count));
  TH1D* hMCSwapped = (TH1D*)file->Get(Form("hMCSwapped-%d",count));
    
  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);

  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);
  

  /*
  TCanvas*mycanvas=new TCanvas("mycanvas","mycanvas",1000,500);
  mycanvas->Divide(2,1);
  mycanvas->cd(1);
  hMCSignal->Draw();
  mycanvas->cd(2);
  hMCSwapped->Draw();
  mycanvas->SaveAs("mycanvas.pdf");
*/
  
  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);
  
  std::cout<<"parameter 10="<<f->GetParameter(10)<<std::endl;

  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 yieldtotal = f->Integral(minhisto,maxhisto)/binwidthmass;
  Double_t yieldErr = mass->Integral(minhisto,maxhisto)/binwidthmass*mass->GetParError(0)/mass->GetParameter(0);
  
  std::cout<<"yield signal="<<yield<<std::endl;
  std::cout<<"total counts="<<yieldtotal<<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} Performance");
  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");

 TH1D* hTest = new TH1D("hTest","",nbinsmasshisto,minhisto,maxhisto);

 for (int m=0;m<yieldtotal;m++){
 double r = f->GetRandom();
 hTest->Fill(r);
 
 }

 TF1* ffaketotal=(TF1*)f->Clone("ffake");
 TF1* ffakemass=(TF1*)mass->Clone("ffakemass");
 TF1* ffakebackground=(TF1*)background->Clone("ffakebackground");
 TF1* ffakemassSwap=(TF1*)massSwap->Clone("ffakemassSwap");
 
 Double_t yieldtotal_original = ffaketotal->Integral(minhisto,maxhisto)/binwidthmass;
 Double_t yieldmass_original = ffakemass->Integral(minhisto,maxhisto)/binwidthmass;
 Double_t yieldbackground_original = ffakebackground->Integral(minhisto,maxhisto)/binwidthmass;
 Double_t yieldswapped_original = ffakemassSwap->Integral(minhisto,maxhisto)/binwidthmass;

 TH1D* hTestFake = new TH1D("hTestFake","",nbinsmasshisto,minhisto,maxhisto);
  ffakemass->SetParameter(2,ffaketotal->GetParameter(2)*0.8);
  ffakemass->SetParameter(10,ffaketotal->GetParameter(10)*0.8);
 
Double_t yieldmass_modified= ffakemass->Integral(minhisto,maxhisto)/binwidthmass;

cout<<"mass original="<<yieldmass_original<<endl;
cout<<"mass modified="<<yieldmass_modified<<endl;

 for (int m=0;m<yieldmass_original*scalefactor;m++){
   double r = ffakemass->GetRandom();
   hTestFake->Fill(r);
 }

  for (int m=0;m<(int)(yieldbackground_original*scalefactor*bkgreduction);m++){
   double r = ffakebackground->GetRandom();
   hTestFake->Fill(r);
 }
 
 for (int m=0;m<(int)(yieldswapped_original*scalefactor*bkgreduction);m++){
   double r = ffakemassSwap->GetRandom();
   hTestFake->Fill(r);
 }

 TCanvas*c2=new TCanvas("c2","c2",500,500);
 c2->cd();
 hTest->SetMaximum(2000);
  hTest->SetXTitle("m_{#piK} (GeV/c^{2})");
  hTest->SetYTitle("Entries / (5 MeV/c^{2})");
  hTest->GetXaxis()->CenterTitle();
  hTest->GetYaxis()->CenterTitle();
  hTest->SetAxisRange(0,hTest->GetMaximum()*1.*1.2,"Y");
  hTest->GetXaxis()->SetTitleOffset(1.3);
  hTest->GetYaxis()->SetTitleOffset(1.8);
  hTest->GetXaxis()->SetLabelOffset(0.007);
  hTest->GetYaxis()->SetLabelOffset(0.007);
  hTest->GetXaxis()->SetTitleSize(0.045);
  hTest->GetYaxis()->SetTitleSize(0.045);
  hTest->GetXaxis()->SetTitleFont(42);
  hTest->GetYaxis()->SetTitleFont(42);
  hTest->GetXaxis()->SetLabelFont(42);
  hTest->GetYaxis()->SetLabelFont(42);
  hTest->GetXaxis()->SetLabelSize(0.04);
  hTest->GetYaxis()->SetLabelSize(0.04);
  hTest->SetMarkerSize(0.8);
  hTest->SetMarkerStyle(20);
  hTest->SetStats(0);
  hTest->Draw("e");

 hTest->SetLineColor(1);
 hTest->SetMarkerColor(1);
  hTestFake->SetLineColor(2);
 hTestFake->SetMarkerColor(2);

 
 hTest->Draw("ep");
 hTestFake->Draw("epsame");

  TLegend* myleg = new TLegend(0.2177419,0.6292373,0.6633065,0.7266949,NULL,"brNDC");
  myleg->SetBorderSize(0);
  myleg->SetTextSize(0.04);
  myleg->SetTextFont(42);
  myleg->SetFillStyle(0);
  myleg->AddEntry(hTest,"Current CMS, |y|<1, L_{int}=0.5/nb","pl");
  myleg->AddEntry(hTestFake,"Upgraded CMS, |y|<2, L_{int}=1.5/nb","l");
  myleg->Draw("same");

  TLatex* mytex;

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

  mychannel = new TLatex(0.22,0.765,"D^{0} #rightarrow K#pi");
  mychannel->SetNDC();
  mychannel->SetTextFont(42);
  mychannel->SetTextSize(0.055);
  mychannel->SetLineWidth(2);
  mychannel->Draw();

  TLatex myTl;
  myTl.SetNDC();
  myTl.SetTextAlign(12);
  myTl.SetTextSize(0.04);
  myTl.SetTextFont(42);
  myTl.DrawLatex(0.2,0.90, "#scale[1.25]{CMS} Performance");
  myTl.DrawLatex(0.63,0.90, Form("%s #sqrt{s_{NN}} = 5.02 TeV",collisionsystem.Data()));
  
  
  TFile*foutput=new TFile(Form("foutput_%s.root",sample.Data()),"recreate");
  foutput->cd();
  hTest->SetName("hTest");
  hTestFake->SetName("hTestFake");
  hTest->SetMaximum(mymaxhisto);
  hTest->Write();
  hTestFake->SetMaximum(mymaxhisto);
  hTestFake->Write();
  hMCSignal->Write();
  hMCSwapped->Write();
  c2->SaveAs(Form("PlotsUpgrade/canvasPerformance%s.pdf",sample.Data()));
  c2->SaveAs(Form("PlotsUpgrade/canvasPerformance%s.png",sample.Data()));

 
}
Beispiel #30
0
void PlotJetRAA()
{
  gROOT->LoadMacro("$LOCAL/include/TUntilsOpHisto.h");
  gROOT->LoadMacro("$LOCAL/include/TUntilsAliFigs.h");
  gROOT->LoadMacro("$LOCAL/include/TUntilsPlotStd.h"); SetStyle();
//=============================================================================

  TFile *file = TFile::Open("data/incl/AnalysisOutputs_jet_py8_JetR05_SjeR01.root", "READ");
  TH1D *h5py8 = (TH1D*)file->Get("hJet"); h5py8->SetName("h5py8"); h5py8->SetDirectory(0);
  file->Close();

  file = TFile::Open("data/incl/AnalysisOutputs_jet_py6_JetR05_SjeR01.root", "READ");
  TH1D *h5py6 = (TH1D*)file->Get("hJet"); h5py6->SetName("h5py6"); h5py6->SetDirectory(0);
  file->Close();

  file = TFile::Open("data/incl/AnalysisOutputs_jet_qpy_JetR05_SjeR01.root", "READ");
  TH1D *h5qpy = (TH1D*)file->Get("hJet"); h5qpy->SetName("h5qpy"); h5qpy->SetDirectory(0);
  file->Close();

  file = TFile::Open("data/incl/AnalysisOutputs_jet_vac_JetR05_SjeR01.root", "READ");
  TH1D *h5vac = (TH1D*)file->Get("hJet"); h5vac->SetName("h5vac"); h5vac->SetDirectory(0);
  file->Close();

  file = TFile::Open("data/incl/AnalysisOutputs_jet_med_JetR05_SjeR01.root", "READ");
  TH1D *h5med = (TH1D*)file->Get("hJet"); h5med->SetName("h5med"); h5med->SetDirectory(0);
  file->Close();


  file = TFile::Open("data/incl/AnalysisOutputs_jet_py8_JetR04_SjeR01.root", "READ");
  TH1D *h4py8 = (TH1D*)file->Get("hJet"); h4py8->SetName("h4py8"); h4py8->SetDirectory(0);
  file->Close();

  file = TFile::Open("data/incl/AnalysisOutputs_jet_py6_JetR04_SjeR01.root", "READ");
  TH1D *h4py6 = (TH1D*)file->Get("hJet"); h4py6->SetName("h4py6"); h4py6->SetDirectory(0);
  file->Close();

  file = TFile::Open("data/incl/AnalysisOutputs_jet_qpy_JetR04_SjeR01.root", "READ");
  TH1D *h4qpy = (TH1D*)file->Get("hJet"); h4qpy->SetName("h4qpy"); h4qpy->SetDirectory(0);
  file->Close();

  file = TFile::Open("data/incl/AnalysisOutputs_jet_vac_JetR04_SjeR01.root", "READ");
  TH1D *h4vac = (TH1D*)file->Get("hJet"); h4vac->SetName("h4vac"); h4vac->SetDirectory(0);
  file->Close();

  file = TFile::Open("data/incl/AnalysisOutputs_jet_med_JetR04_SjeR01.root", "READ");
  TH1D *h4med = (TH1D*)file->Get("hJet"); h4med->SetName("h4med"); h4med->SetDirectory(0);
  file->Close();
//=============================================================================

  TH1F    *hfm = 0;
  TCanvas *can = 0;
  TLegend *leg = 0;
  TLatex  *tex = 0;
  TLine  *line = 0;

  const Float_t dflx = -40., dfux = 200.;
  const Float_t dfly = 8e-10, dfuy = 8e3;

  const Float_t dlsx = 0.05, dlsy = 0.05;
  const Float_t dtsx = 0.06, dtsy = 0.06;
  const Float_t dtox = 1.10, dtoy = 1.00;

  const TString stnx = "#it{p}_{T,jet}^{ch} (GeV/#it{c})";
  const TString stny = "d#sigma/d#it{p}_{T} (mb/GetV/#it{c})";

  TH1D *hSE = new TH1D("hSE", "", 10., 0., 10.);
  hSE->SetLineWidth(2);
  hSE->SetLineColor(wcl[0]);
  hSE->SetMarkerStyle(wmk[0]);
  hSE->SetMarkerColor(wcl[0]);

  TH1D *hME = new TH1D("hME", "", 10., 0., 10.);
  hME->SetLineWidth(2);
  hME->SetLineColor(wcl[0]);
  hME->SetMarkerStyle(wmk[2]);
  hME->SetMarkerColor(wcl[0]);
//=============================================================================

  can = MakeCanvas("Jet5"); can->SetGridx(); can->SetGridy(); can->SetLogy();
  hfm = can->DrawFrame(0., 8e-13, 500., 8e3); SetupFrame(hfm, dlsx, dlsy, dtsx, dtsy, dtox, dtoy,
                                                        "#it{p}_{T,jet} (GeV/#it{c})",
                                                        "d#sigma/d#it{p}_{T} (mb/GeV/#it{c})");
  hfm->GetXaxis()->SetNdivisions(510);
  hfm->GetYaxis()->SetNdivisions(510);

  DrawHisto(h5py8, wcl[3], wmk[0], "SAME");
  DrawHisto(h5qpy, wcl[1], wmk[0], "SAME");
  DrawHisto(h5med, wcl[5], wmk[0], "SAME");

  leg = new TLegend(0.62, 0.64, 0.98, 0.88); SetupLegend(leg);
  leg->AddEntry(h5py8, "PYTHIA 8", "LP")->SetTextSizePixels(24);
  leg->AddEntry(h5qpy, "Q-PYTHIA", "LP")->SetTextSizePixels(24);
  leg->AddEntry(h5med, "JEWEL+PYTHIA", "LP")->SetTextSizePixels(24);
  leg->Draw();

  tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSizePixels(24);
  tex->DrawLatex(0.16, 0.92, "2.76 TeV, jet anti-#it{k}_{T}, #it{R}=0.5, |#eta_{jet}|<1");
  CanvasEnd(can);
//=============================================================================

  can = MakeCanvas("Jet4"); can->SetGridx(); can->SetGridy(); can->SetLogy();
  hfm = can->DrawFrame(0., 8e-13, 500., 8e3); SetupFrame(hfm, dlsx, dlsy, dtsx, dtsy, dtox, dtoy,
                                                        "#it{p}_{T,jet} (GeV/#it{c})",
                                                        "d#sigma/d#it{p}_{T} (mb/GeV/#it{c})");
  hfm->GetXaxis()->SetNdivisions(510);
  hfm->GetYaxis()->SetNdivisions(510);

  DrawHisto(h4py8, wcl[3], wmk[0], "SAME");
  DrawHisto(h4qpy, wcl[1], wmk[0], "SAME");
  DrawHisto(h4med, wcl[5], wmk[0], "SAME");

  leg = new TLegend(0.62, 0.64, 0.98, 0.88); SetupLegend(leg);
  leg->AddEntry(h4py8, "PYTHIA 8", "LP")->SetTextSizePixels(24);
  leg->AddEntry(h4qpy, "Q-PYTHIA", "LP")->SetTextSizePixels(24);
  leg->AddEntry(h4med, "JEWEL+PYTHIA", "LP")->SetTextSizePixels(24);
  leg->Draw();

  tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSizePixels(24);
  tex->DrawLatex(0.16, 0.92, "2.76 TeV, jet anti-#it{k}_{T}, #it{R}=0.4, |#eta_{jet}|<1");
  CanvasEnd(can);
//=============================================================================

  const Double_t dBin[] = { 0., 10., 20., 30., 40., 50., 60., 80., 100., 120., 150., 200., 250., 300., 350., 400., 500. };
  const Int_t nBin = sizeof(dBin) / sizeof(Double_t) -1;

  TH1D *h5py8rb = h5py8->Rebin(nBin, "h5py8rb", dBin); TH1D *h4py8rb = h4py8->Rebin(nBin, "h4py8rb", dBin);
  TH1D *h5py6rb = h5py6->Rebin(nBin, "h5py6rb", dBin); TH1D *h4py6rb = h4py6->Rebin(nBin, "h4py6rb", dBin);
  TH1D *h5qpyrb = h5qpy->Rebin(nBin, "h5qpyrb", dBin); TH1D *h4qpyrb = h4qpy->Rebin(nBin, "h4qpyrb", dBin);
  TH1D *h5vacrb = h5vac->Rebin(nBin, "h5vacrb", dBin); TH1D *h4vacrb = h4vac->Rebin(nBin, "h4vacrb", dBin);
  TH1D *h5medrb = h5med->Rebin(nBin, "h5medrb", dBin); TH1D *h4medrb = h4med->Rebin(nBin, "h4medrb", dBin);
//=============================================================================

  TH1D *hRpy8 = (TH1D*)h4py8rb->Clone("hRpy8"); hRpy8->Divide(h5py8rb);
  TH1D *hRqpy = (TH1D*)h4qpyrb->Clone("hRqpy"); hRqpy->Divide(h5qpyrb);
  TH1D *hRmed = (TH1D*)h4medrb->Clone("hRmed"); hRmed->Divide(h5medrb);
//=============================================================================

  can = MakeCanvas("JetR"); can->SetGridx(); can->SetGridy();
  hfm = can->DrawFrame(0., 0.4, 500., 1.5); SetupFrame(hfm, dlsx, dlsy, dtsx, dtsy, dtox, dtoy,
                                                      "#it{p}_{T,jet} (GeV/#it{c})",
                                                      "Ratio: #it{R}=0.4 / #it{R}=0.5");
  hfm->GetXaxis()->SetNdivisions(510);
  hfm->GetYaxis()->SetNdivisions(510);

  DrawHisto(hRpy8, wcl[3], wmk[0], "SAME");
  DrawHisto(hRqpy, wcl[1], wmk[0], "SAME");
  DrawHisto(hRmed, wcl[5], wmk[0], "SAME");

  leg = new TLegend(0.62, 0.64, 0.98, 0.88); SetupLegend(leg);
  leg->AddEntry(hRpy8, "PYTHIA 8", "LP")->SetTextSizePixels(24);
  leg->AddEntry(hRqpy, "Q-PYTHIA", "LP")->SetTextSizePixels(24);
  leg->AddEntry(hRmed, "JEWEL+PYTHIA", "LP")->SetTextSizePixels(24);
  leg->Draw();

  tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSizePixels(24);
  tex->DrawLatex(0.16, 0.92, "2.76 TeV, Jets anti-#it{k}_{T}, |#eta_{jet}|<1");
  CanvasEnd(can);
//=============================================================================

  TH1D *h5qpyRAA = (TH1D*)h5qpyrb->Clone("h5qpyRAA"); h5qpyRAA->Divide(h5py6rb);
  TH1D *h5medRAA = (TH1D*)h5medrb->Clone("h5medRAA"); h5medRAA->Divide(h5vacrb);

  TH1D *h4qpyRAA = (TH1D*)h4qpyrb->Clone("h4qpyRAA"); h4qpyRAA->Divide(h4py6rb);
  TH1D *h4medRAA = (TH1D*)h4medrb->Clone("h4medRAA"); h4medRAA->Divide(h4vacrb);

  can = MakeCanvas("JetRAA"); can->SetGridx(); can->SetGridy();
  hfm = can->DrawFrame(0., 0., 500., 1.2); SetupFrame(hfm, dlsx, dlsy, dtsx, dtsy, dtox, dtoy,
                                                        "#it{p}_{T,jet} (GeV/#it{c})",
                                                        "#it{R}_{AA}");
  hfm->GetXaxis()->SetNdivisions(510);
  hfm->GetYaxis()->SetNdivisions(510);

  DrawHisto(h5qpyRAA, wcl[1], wmk[0], "SAME");
  DrawHisto(h5medRAA, wcl[5], wmk[0], "SAME");

  DrawHisto(h4qpyRAA, wcl[1], wmk[2], "SAME");
  DrawHisto(h4medRAA, wcl[5], wmk[2], "SAME");

  leg = new TLegend(0.48, 0.56, 0.98, 0.88); SetupLegend(leg);
  leg->AddEntry(h5qpyRAA, "#it{R}=0.5, Q-PYTHIA", "LP")->SetTextSizePixels(24);
  leg->AddEntry(h4qpyRAA, "#it{R}=0.4, Q-PYTHIA", "LP")->SetTextSizePixels(24);
  leg->AddEntry(h5medRAA, "#it{R}=0.5, JEWEL+PYTHIA", "LP")->SetTextSizePixels(24);
  leg->AddEntry(h4medRAA, "#it{R}=0.4, JEWEL+PYTHIA", "LP")->SetTextSizePixels(24);
  leg->Draw();

  tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSizePixels(24);
  tex->DrawLatex(0.16, 0.92, "2.76 TeV, Jet anti-#it{k}_{T}, |#eta_{jet}|<1");
  CanvasEnd(can);
//=============================================================================

  return;
}