Example #1
0
void offline(const char* FileName="test")
{
    TH1F::SetDefaultSumw2();
    // Set Style parameters for this macro
    gStyle->SetOptTitle(1); // Show Title (off by default for cleanliness)
    gErrorIgnoreLevel = kError; // Set Verbosity Level (kPrint shows all)

    // Set Output options
    Int_t number;
    Bool_t fPaintAll = checkPaintAllTrigs();
    checkBatchMode();
    Bool_t makePDF = checkMakePDF();
    Bool_t makeROOT= checkMakeRoot();

    // Open ROOT File
    char name[1000];
    sprintf(name,"/Users/zach/Research/rootFiles/run12NPEhPhi/%s.root",FileName);
    TFile *f = new TFile(name,"READ");
    if (f->IsOpen()==kFALSE)
    {   std::cout << "!!! File Not Found !!!" << std::endl;
        exit(1);
    }
    // f->ls(); // - DEBUG by printing all objects in ROOT file

    char fname[100];
    TFile* file;
    if(makeROOT) {
        sprintf(fname,"/Users/zach/Research/rootFiles/run12NPEhPhi/%s_processed.root",FileName);
        file = new TFile(fname,"RECREATE");
        if (file->IsOpen()==kFALSE)
        {
            std::cout << "!!! Outfile Not Opened !!!" << std::endl;
            makeROOT = kFALSE;
        }
    }

    const Int_t numPtBins = anaConst::nPtBins;
    Float_t lowpt[numPtBins],highpt[numPtBins];
    for(Int_t c=0; c< numPtBins; c++) {
        lowpt[c] = anaConst::lpt[c];
        highpt[c] = anaConst::hpt[c];
    }
    Float_t hptCut=anaConst::hptCut;
    const Int_t numTrigs = 4;
    Double_t epsilon[numPtBins] = {0.593164, 0.626663, 0.655916, 0.674654, 0.685596, 0.700600, 0.716682, 0.724638, 0.713977, 0.730550, 0.735204, 0.744336, 0.761323, 0.758423};
    Float_t hptMax=25; // Set max above range to allow overflow
    Float_t lowPhi=anaConst::lowPhi, highPhi=anaConst::highPhi;
    Double_t pu[2][numPtBins][numTrigs]; // To store fit parameters for later use
    Double_t hhNorm, HHScale, hadPur;

    TH1D * LSIM[numPtBins][numTrigs];
    TH1D * USIM[numPtBins][numTrigs];
    TH1D * USIMNP[numPtBins][numTrigs];
    TH1D * LSIMNP[numPtBins][numTrigs];
    TH1D * INCLNP[numPtBins][numTrigs];
    TH1D * INCL[numPtBins][numTrigs];
    TH1D * LSIM2[numPtBins][numTrigs];
    TH1D * USIM2[numPtBins][numTrigs];
    TH1D * INCL2[numPtBins][numTrigs];
    TH1D * LSMM[numPtBins][numTrigs];
    TH1D * USMM[numPtBins][numTrigs];
    TH1D * HHDP[numPtBins][numTrigs];
    TH1D * NSPI[numPtBins][numTrigs];
    TH2F * MON[numTrigs];
    TH1F * AVGTRKS[numTrigs];
    TH2F * MON2[numTrigs];
    TH1F * AVGTRKS2[numTrigs];
    TH2F* mh2PhiQPt[numTrigs];
    TH2F* mh2nSigmaEPt[numTrigs];
    TH2F* mh2nSigmaEPt_eID[numTrigs];
    TH3F* mh3DelPhiIncl[numTrigs];
    TH3F* mh3DelPhiPhotLS[numTrigs];
    TH3F* mh3DelPhiPhotUS[numTrigs];
    TH3F* mh3DelPhiPhotUSNP[numTrigs];
    TH3F* mh3DelPhiPhotLSNP[numTrigs];
    TH3F* mh3DelPhiInclNP[numTrigs];
    TH3F* mh3DelPhiInclWt[numTrigs];
    TH3F* mh3DelPhiPhotLSWt[numTrigs];
    TH3F* mh3DelPhiPhotUSWt[numTrigs];
    TH2F* mh2InvMassPtLS[numTrigs];
    TH2F* mh2InvMassPtUS[numTrigs];
    TH2F* mh2PtEZdcx[numTrigs];
    TH2F* mh2PtEZdcxUS[numTrigs];
    TH2F* mh2PtEZdcxLS[numTrigs];
    TH2F* mh2PtEZdcxHad[numTrigs];
    TH3F* mh3nTracksZdcx[numTrigs];
    TH3F* mh3nTracksZdcxUS[numTrigs];
    TH3F* mh3nTracksZdcxLS[numTrigs];
    TH3F* mh3nTracksZdcxHad[numTrigs];
    TH3F* mh3MixedDelPhi;
    TH3F* mh3MixedDelEta;
    TH3F* mh3MixedEtaPhi;
    TH3F* mh3DelPhiHadHad[numTrigs];
    TH2F* mh2nSigmaPion[numTrigs];
    TH1F* mh1PtHadTracks[numTrigs];
    TH1F* mh1PtETracks[numTrigs];
    TH1D* projHPhi[numPtBins][numTrigs];
    TH1D* projnSigmaE[numPtBins][numTrigs];
    TH1D* projnSigmaE_eID[numPtBins][numTrigs];
    TH1D* projDelPhiIncl[numPtBins][numTrigs];
    TH1D* projDelPhiPhotLS[numPtBins][numTrigs];
    TH1D* projDelPhiPhotUS[numPtBins][numTrigs];
    TH1D* projDelPhiPhotUSNP[numPtBins][numTrigs];
    TH1D* projDelPhiPhotLSNP[numPtBins][numTrigs];
    TH1D* projDelPhiInclNP[numPtBins][numTrigs];
    TH1D* projDelPhiInclWt[numPtBins][numTrigs];
    TH1D* projDelPhiPhotLSWt[numPtBins][numTrigs];
    TH1D* projDelPhiPhotUSWt[numPtBins][numTrigs];
    TH1D* projDelPhiHadHad[numPtBins][numTrigs];
    TH1D* projInvMassLS[numPtBins][numTrigs];
    TH1D* projInvMassUS[numPtBins][numTrigs];
    TH1D* projnSigmaPion[numPtBins][numTrigs];
    TH1D* projEMixedEtaPhi;
    TH1D* projPMixedEtaPhi;
    TH2D* proj2DMixedEtaPhi;
    TH2D* proj2DMixedEvent[numPtBins];
    TH1D* projMixedDelPhi[numPtBins];
    TH1D* projMixedDelEta[numPtBins];
    TH2F* histoNorms;
    TH1D* projZDCxHad[numPtBins][numTrigs];
    TH1D* projZDCxTrig[numPtBins][numTrigs];
    TH1D* projZDCxHadUS[numPtBins][numTrigs];
    TH1D* projZDCxTrigUS[numPtBins][numTrigs];
    TH1D* projZDCxHadLS[numPtBins][numTrigs];
    TH1D* projZDCxTrigLS[numPtBins][numTrigs];
    TH1D* projZDCxHadHad[numPtBins][numTrigs];
    TH1D* projZDCxTrigHad[numPtBins][numTrigs];
    TProfile2D* profileZDCx[numTrigs];
    TCanvas * c[numTrigs];
    TCanvas * c2[numTrigs];
    TCanvas * IN[numTrigs];
    TCanvas * IN2[numTrigs];
    TCanvas * pile[numTrigs];
    TCanvas * pileHad[numTrigs];
    TCanvas * result[numTrigs];
    TCanvas * result2[numTrigs];
    TCanvas * inMass[numTrigs];
    TCanvas * USComp[numTrigs];
    TCanvas * LSComp[numTrigs];
    TCanvas * InclComp[numTrigs];
    TCanvas * cHH[numTrigs];
    TCanvas * nSigPi[numTrigs];
    TCanvas * allDist[numTrigs];
    TCanvas * mixedC;
    TCanvas * mixedCbinEta;
    TCanvas * mixedCbinPhi;
    TCanvas * mixedCbin;
    TCanvas * singlePlot;

    TPaveText* lbl[numPtBins];
    TPaveText* stat[numPtBins];
    char textLabel[100];
    singlePlot =  new TCanvas("singlePlot","Single Plot",150,0,1150,1000);

    // Trigger Independent Hists
    mixedC     = new TCanvas("mixedC","Mixed Events",150,0,1150,1000);
    mixedCbinEta = new TCanvas("mixedCbinEta","Mixed Events Eta",150,0,1150,1000);
    mixedCbinPhi = new TCanvas("mixedCbinPhi","Mixed Events Phi",150,0,1150,1000);
    mixedCbin = new TCanvas("mixedCbin","Mixed Events 2D",150,0,1150,1000);

    mixedC       -> Divide(2,2);
    mixedCbinEta -> Divide(4,3);
    mixedCbinPhi -> Divide(4,3);

    mh3MixedDelPhi = (TH3F*)f->Get("mh3MixedDelPhi");
    mh3MixedDelEta = (TH3F*)f->Get("mh3MixedDelEta");
    mh3MixedEtaPhi = (TH3F*)f->Get("mh3MixedEtaPhi");

    ///////////////////////////
    projPMixedEtaPhi  = mh3MixedEtaPhi -> ProjectionX("projPMixedEtaPhi");
    projEMixedEtaPhi  = mh3MixedEtaPhi -> ProjectionY("projEMixedEtaPhi");
    proj2DMixedEtaPhi = (TH2D*)mh3MixedEtaPhi -> Project3D("yx");
    Int_t RB2 = 2;
    projEMixedEtaPhi->Rebin(RB2);
    projPMixedEtaPhi->Rebin(RB2);

    mixedC->cd(1);
    mh3MixedEtaPhi->GetXaxis()->SetTitle("#Delta#phi");
    mh3MixedEtaPhi->GetXaxis()->SetRangeUser(lowPhi,highPhi);
    mh3MixedEtaPhi->GetYaxis()->SetTitle("#Delta#eta");
    mh3MixedEtaPhi->GetYaxis()->SetRangeUser(-1.5,1.5);
    mh3MixedEtaPhi->GetZaxis()->SetTitle("P_{t,e}");
    mh3MixedEtaPhi->Draw();
    mixedC->cd(2);
    projPMixedEtaPhi->GetXaxis()->SetRangeUser(lowPhi,highPhi);
    projPMixedEtaPhi->GetXaxis()->SetTitle("#Delta#phi");
    projPMixedEtaPhi->GetYaxis()->SetRangeUser(0,20000);
    projPMixedEtaPhi->SetTitle("Mixed Event #Delta#phi");
    projPMixedEtaPhi->Draw();
    mixedC->cd(3);
    projEMixedEtaPhi->GetXaxis()->SetRangeUser(-2.5,2.5);
    projEMixedEtaPhi->GetXaxis()->SetTitle("#Delta#eta");
    projEMixedEtaPhi->SetTitle("Mixed Event #Delta#eta");
    projEMixedEtaPhi->Draw();
    mixedC->cd(4);
    mixedC->SetLogz(1);
    proj2DMixedEtaPhi->GetXaxis()->SetTitle("#Delta#phi");
    proj2DMixedEtaPhi->GetXaxis()->SetRangeUser(lowPhi,highPhi);
    proj2DMixedEtaPhi->GetYaxis()->SetTitle("#Delta#eta");
    proj2DMixedEtaPhi->GetYaxis()->SetRangeUser(-1.5,1.5);
    proj2DMixedEtaPhi->Draw("colz");

    TH3F* temp3D[numPtBins];
    // PtBins for Mixed Event
    for(Int_t ptbin = 0; ptbin < numPtBins; ptbin++) {

        // Init necessary plotting tools
        lbl[ptbin] = new TPaveText(.2,.8,.5,.85,Form("NB NDC%i",ptbin));
        sprintf(textLabel,"%.1f < P_{T,e} < %.1f",lowpt[ptbin],highpt[ptbin]);
        lbl[ptbin]->AddText(textLabel);
        lbl[ptbin]->SetFillColor(kWhite);

        projMixedDelPhi[ptbin] = mh3MixedEtaPhi->ProjectionX(Form("projMixedDelPhi_%i",ptbin),0,-1,mh3MixedEtaPhi->GetZaxis()->FindBin(lowpt[ptbin]),mh3MixedEtaPhi->GetZaxis()->FindBin(highpt[ptbin])-1);
        projMixedDelEta[ptbin] = mh3MixedEtaPhi->ProjectionY(Form("projMixedDelEta_%i",ptbin),0,-1,mh3MixedEtaPhi->GetZaxis()->FindBin(lowpt[ptbin]),mh3MixedEtaPhi->GetZaxis()->FindBin(highpt[ptbin])-1);

        mixedCbinEta->cd(ptbin+1);
        projMixedDelEta[ptbin]->GetXaxis()->SetRangeUser(-2.5,2.5);
        projMixedDelEta[ptbin]->GetXaxis()->SetTitle("#Delta#eta");
        projMixedDelEta[ptbin]->Draw();

        mixedCbinPhi->cd(ptbin+1);
        projMixedDelPhi[ptbin]->GetXaxis()->SetRangeUser(lowPhi-.5,highPhi+.5);
        // projMixedDelPhi[ptbin]->GetYaxis()->SetRangeUser(0,2000);
        projMixedDelPhi[ptbin]->GetXaxis()->SetTitle("#Delta#phi");
        projMixedDelPhi[ptbin]->Draw();

        /*   temp3D[ptbin] = (TH3F*)mh3MixedEtaPhi->Clone(); // make a clone to set axis range on for 3D to 2D projection
        temp3D[ptbin]->GetZaxis()->SetRangeUser(lowpt[ptbin],highpt[ptbin]); // project3d only projects active range
        proj2DMixedEvent[ptbin] = (TH2D*)temp3D[ptbin] -> Project3D("yx");
        proj2DMixedEvent[ptbin]->SetName(Form("proj2DMixedEvent_%i",ptbin));

        mixedCbin->cd(ptbin+1);
        proj2DMixedEvent[ptbin]->GetXaxis()->SetTitle("#Delta#phi");
        proj2DMixedEvent[ptbin]->GetXaxis()->SetRangeUser(lowPhi,highPhi);
        proj2DMixedEvent[ptbin]->GetYaxis()->SetTitle("#Delta#eta");
        proj2DMixedEvent[ptbin]->GetYaxis()->SetRangeUser(-1.5,1.5);
        proj2DMixedEvent[ptbin]->Draw("colz");*/

    }

    /// TRIGGER LOOP
    histoNorms = new TH2F("histoNorms","",4,0,12,20,0,20); // Fill normalization in a single histogram for accessing later

    for(Int_t trig = 0; trig < numTrigs; trig++) {

        if(!fPaintAll && (trig == 1 || trig == 3)) continue;
        // Create and Segment Canvas
        c[trig]        = new TCanvas(Form("c%i",trig),"Photonic Hists",150,0,1150,1000);
        IN[trig]       = new TCanvas(Form("IN%i",trig),"Inclusive Hists",150,0,1150,1000);
        pile[trig]     = new TCanvas(Form("pile%i",trig),"Pileup Monitor",150,0,1150,1000);
        pileHad[trig]  = new TCanvas(Form("pileHad%i",trig),"Pileup Monitor",150,0,1150,1000);
        //  pileTrig[trig] = new TCanvas(Form("pileTrig%i",trig),"Pileup Monitor",150,0,1150,1000);
        inMass[trig]   = new TCanvas(Form("inMass%i",trig),"Invariant Mass",150,0,1150,1000);
        result[trig]   = new TCanvas(Form("result%i",trig),"Inclusive - Photonic",150,0,1150,1000);
        USComp[trig]   = new TCanvas(Form("USComp%i",trig),"Unlike Sign Distributions",150,0,1150,1000);
        LSComp[trig]   = new TCanvas(Form("LSComp%i",trig),"Like Sign Distributions",150,0,1150,1000);
        InclComp[trig] = new TCanvas(Form("InclComp%i",trig),"Inclusive Distributions",150,0,1150,1000);
        cHH[trig]      = new TCanvas(Form("cHH%i",trig),"Hadron-Hadron Distributions",150,0,1150,1000);
        nSigPi[trig]   = new TCanvas(Form("nSigPi_%i",trig),"n#sigma#pi QA",150,0,1150,1000);
        allDist[trig]  = new TCanvas(Form("allDist_%i",trig),"Distribution Comparison",150,0,1150,1000);
        c[trig]        -> Divide(4,3);
        inMass[trig]   -> Divide(4,3);
        IN[trig]       -> Divide(4,3);
        pile[trig]     -> Divide(4,3);
        result[trig]   -> Divide(4,3);
        USComp[trig]   -> Divide(4,3);
        LSComp[trig]   -> Divide(4,3);
        InclComp[trig] -> Divide(4,3);
        cHH[trig]      -> Divide(4,3);
        nSigPi[trig]   -> Divide(4,3);
        allDist[trig]  -> Divide(4,3);

        // Make Projections (first get 2d/3d hists, then project)
        mh2PhiQPt[trig]         = (TH2F*)f->Get(Form("mh2PhiQPt_%i",trig));
        mh2nSigmaEPt[trig]      = (TH2F*)f->Get(Form("mh2nSigmaEPt_%i",trig));
        mh2nSigmaEPt_eID[trig]  = (TH2F*)f->Get(Form("mh2nSigmaEPt_eID_%i",trig));
        mh3DelPhiIncl[trig]     = (TH3F*)f->Get(Form("mh3DelPhiIncl_%i",trig));
        mh3DelPhiPhotLS[trig]   = (TH3F*)f->Get(Form("mh3DelPhiPhotLS_%i",trig));
        mh3DelPhiPhotUS[trig]   = (TH3F*)f->Get(Form("mh3DelPhiPhotUS_%i",trig));
        mh3DelPhiPhotUSNP[trig] = (TH3F*)f->Get(Form("mh3DelPhiPhotUSNP_%i",trig));
        mh3DelPhiPhotLSNP[trig] = (TH3F*)f->Get(Form("mh3DelPhiPhotLSNP_%i",trig));
        mh3DelPhiInclNP[trig]   = (TH3F*)f->Get(Form("mh3DelPhiPhotInclNP_%i",trig));
        mh3DelPhiInclWt[trig]   = (TH3F*)f->Get(Form("mh3DelPhiInclWt_%i",trig));
        mh3DelPhiPhotLSWt[trig] = (TH3F*)f->Get(Form("mh3DelPhiPhotLSWt_%i",trig));
        mh3DelPhiPhotUSWt[trig] = (TH3F*)f->Get(Form("mh3DelPhiPhotUSWt_%i",trig));
        mh2InvMassPtLS[trig]    = (TH2F*)f->Get(Form("mh2InvMassPtLS_%i",trig));
        mh2InvMassPtUS[trig]    = (TH2F*)f->Get(Form("mh2InvMassPtUS_%i",trig));
        mh3DelPhiHadHad[trig]   = (TH3F*)f->Get(Form("mh3DelPhiHadHad_%i",trig));
        mh1PtHadTracks[trig]    = (TH1F*)f->Get(Form("mh1PtHadTracks_%i",trig));
        mh1PtETracks[trig]      = (TH1F*)f->Get(Form("mh1PtETracks_%i",trig));
        mh2nSigmaPion[trig]     = (TH2F*)f->Get(Form("mh2nSigmaPionPt_%i",trig));

        for(Int_t ptbin=0; ptbin<numPtBins; ptbin++)
        {
            // - Make projections into electron ptbins
            projHPhi[ptbin][trig] = mh2PhiQPt[trig]->ProjectionX(Form("projHPhi_%i_%i",ptbin,trig),mh2PhiQPt[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh2PhiQPt[trig]->GetYaxis()->FindBin(highpt[ptbin])-1);

            projnSigmaE[ptbin][trig] = mh2nSigmaEPt[trig]->ProjectionX(Form("projnSigmaE_%i_%i",ptbin,trig),mh2nSigmaEPt[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh2nSigmaEPt[trig]->GetYaxis()->FindBin(highpt[ptbin])-1);

            projnSigmaE_eID[ptbin][trig] = mh2nSigmaEPt_eID[trig]->ProjectionX(Form("projnSigmaE_eID_%i_%i",ptbin,trig),mh2nSigmaEPt_eID[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh2nSigmaEPt_eID[trig]->GetYaxis()->FindBin(highpt[ptbin])-1);

            projDelPhiIncl[ptbin][trig] = mh3DelPhiIncl[trig]->ProjectionX(Form("projDelPhiIncl_%i_%i",ptbin,trig),mh3DelPhiIncl[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiIncl[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiIncl[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiIncl[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiPhotUS[ptbin][trig] = mh3DelPhiPhotUS[trig]->ProjectionX(Form("projDelPhiPhotUS_%i_%i",ptbin,trig),mh3DelPhiPhotUS[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiPhotUS[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiPhotUS[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiPhotUSNP[ptbin][trig] = mh3DelPhiPhotUSNP[trig]->ProjectionX(Form("projDelPhiPhotUSNP_%i_%i",ptbin,trig),mh3DelPhiPhotUSNP[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiPhotUSNP[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiPhotUSNP[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiPhotLS[ptbin][trig] = mh3DelPhiPhotLS[trig]->ProjectionX(Form("projDelPhiPhotLS_%i_%i",ptbin,trig),mh3DelPhiPhotLS[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiPhotLS[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiPhotLS[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiPhotLSNP[ptbin][trig] = mh3DelPhiPhotLSNP[trig]->ProjectionX(Form("projDelPhiPhotLSNP_%i_%i",ptbin,trig),mh3DelPhiPhotLSNP[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiPhotLSNP[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiPhotLSNP[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiInclNP[ptbin][trig] = mh3DelPhiInclNP[trig]->ProjectionX(Form("projDelPhiInclNP_%i_%i",ptbin,trig),mh3DelPhiInclNP[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiInclNP[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiPhotLS[ptbin][trig] = mh3DelPhiPhotLS[trig]->ProjectionX(Form("projDelPhiPhotLS_%i_%i",ptbin,trig),mh3DelPhiPhotLS[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiPhotLS[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiPhotLS[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiPhotLS[ptbin][trig] = mh3DelPhiPhotLS[trig]->ProjectionX(Form("projDelPhiPhotLS_%i_%i",ptbin,trig),mh3DelPhiPhotLS[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiPhotLS[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiPhotLS[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiInclWt[ptbin][trig] = mh3DelPhiInclWt[trig]->ProjectionX(Form("projDelPhiInclWt_%i_%i",ptbin,trig),mh3DelPhiInclWt[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiInclWt[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiInclWt[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiPhotUSWt[ptbin][trig] = mh3DelPhiPhotUSWt[trig]->ProjectionX(Form("projDelPhiPhotUSWt_%i_%i",ptbin,trig),mh3DelPhiPhotUSWt[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiPhotUSWt[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiPhotUSWt[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiPhotLSWt[ptbin][trig] = mh3DelPhiPhotLSWt[trig]->ProjectionX(Form("projDelPhiPhotLSWt_%i_%i",ptbin,trig),mh3DelPhiPhotLSWt[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiPhotLSWt[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiPhotLSWt[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projInvMassUS[ptbin][trig] = mh2InvMassPtUS[trig]->ProjectionX(Form("projInvMassUS_%i_%i",ptbin,trig),mh2InvMassPtUS[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh2InvMassPtUS[trig]->GetYaxis()->FindBin(highpt[ptbin])-1);

            projInvMassLS[ptbin][trig] = mh2InvMassPtLS[trig]->ProjectionX(Form("projInvMassLS_%i_%i",ptbin,trig),mh2InvMassPtLS[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh2InvMassPtLS[trig]->GetYaxis()->FindBin(highpt[ptbin])-1);

            projDelPhiHadHad[ptbin][trig] = mh3DelPhiHadHad[trig]->ProjectionX(Form("projDelPhiHadHad_%i_%i",ptbin,trig),mh3DelPhiHadHad[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiHadHad[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiHadHad[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projnSigmaPion[ptbin][trig] = mh2nSigmaPion[trig]->ProjectionX(Form("projnSigmaPion_%i_%i",ptbin,trig),mh2nSigmaPion[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh2nSigmaPion[trig]->GetYaxis()->FindBin(highpt[ptbin])-1);
        }

        for(Int_t ptbin = 0; ptbin < numPtBins; ptbin++) {

            // Init necessary plotting tools
            lbl[ptbin] = new TPaveText(.15,.15,.35,.23,Form("NB NDC%i",ptbin));
            sprintf(textLabel,"%.1f < P_{T,e} < %.1f",lowpt[ptbin],highpt[ptbin]);
            lbl[ptbin]->AddText(textLabel);
            lbl[ptbin]->SetFillColor(kWhite);

            // Calculate electron purity from pol3 fit of xiaozhi data
            Float_t ptAv = (lowpt[ptbin]+highpt[ptbin])/2.;
            Float_t p[3] = {0.9743, 0.02128, -0.00438};
            Float_t purity = p[0] + (p[1]*ptAv)+(p[2]*ptAv*ptAv);
            hadPur = 1-purity;

            // Calculate PHe Reconstruction Eff from Xiaozhi embedding (fit)
            Float_t par[5] = {.26214, 4.75137, .526075, .0276979, .00054599};
            Float_t x = ptAv;
            Float_t eps = par[0]*TMath::Log(par[1]*x - par[2]*x*x + par[3]*x*x*x - par[4]*x*x*x*x);
            epsilon[ptbin] = eps;

            // Make stats label with purity and effeciency
            char statLabel[100];
            stat[ptbin] = new TPaveText(.4,.3,.85,.35,Form("NB NDC%i",ptbin));
            sprintf(statLabel,"Eff: %.2f; ePure:%.2f",epsilon[ptbin],purity);
            stat[ptbin]->InsertText(statLabel);
            stat[ptbin]->SetFillColor(kWhite);

            // Calculate Normalization for NPE delPhi
            Int_t inclNorm = mh1PtETracks[trig]->Integral(mh1PtETracks[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh1PtETracks[trig]->GetXaxis()->FindBin(highpt[ptbin])-1);
            Int_t LSNorm   = projInvMassLS[ptbin][trig]->Integral();
            Int_t USNorm   = projInvMassUS[ptbin][trig]->Integral();
            hhNorm   = mh1PtHadTracks[trig]->Integral(mh1PtHadTracks[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh1PtHadTracks[trig]->GetXaxis()->FindBin(highpt[ptbin])-1);
            HHScale = (Float_t)inclNorm/(Float_t)hhNorm; // so the purity comparison is 1:1
            Float_t Norm = (Float_t)inclNorm - (1/epsilon[ptbin] - 1.)*(Float_t)USNorm + (1/epsilon[ptbin])*(Float_t)LSNorm - HHScale*hadPur*hhNorm; // Use the number of "signal" counts
            histoNorms->SetBinContent(histoNorms->GetBin(trig+1,ptbin+1), Norm); // Find the bin and fill with the Normalization
            //cout << trig << "; " << ptbin << ": " << Norm << endl;

            Int_t counter = numPtBins*trig+ptbin;
            // DEBUG cout << counter << endl;
            c[trig]->cd(ptbin+1);
            // Assign to a single, simpler name for manip
            LSIM[ptbin][trig]  = projDelPhiPhotLS[ptbin][trig];
            USIM[ptbin][trig]  = projDelPhiPhotUS[ptbin][trig];
            USIMNP[ptbin][trig]= projDelPhiPhotUSNP[ptbin][trig];
            LSIMNP[ptbin][trig]= projDelPhiPhotLSNP[ptbin][trig];
            INCLNP[ptbin][trig]= projDelPhiInclNP[ptbin][trig];
            INCL[ptbin][trig]  = projDelPhiIncl[ptbin][trig];
            INCL2[ptbin][trig] = projDelPhiInclWt[ptbin][trig];
            LSIM2[ptbin][trig] = projDelPhiPhotLSWt[ptbin][trig];
            USIM2[ptbin][trig] = projDelPhiPhotUSWt[ptbin][trig];
            LSMM[ptbin][trig]  = projInvMassLS[ptbin][trig];
            USMM[ptbin][trig]  = projInvMassUS[ptbin][trig];
            HHDP[ptbin][trig]  = projDelPhiHadHad[ptbin][trig];
            NSPI[ptbin][trig]  = projnSigmaPion[ptbin][trig];
            // Rebin all as necessary
            Int_t RB = 1;
            LSIM[ptbin][trig]  -> Rebin(RB);
            USIM[ptbin][trig]  -> Rebin(RB);
            USIMNP[ptbin][trig]-> Rebin(RB);
            LSIMNP[ptbin][trig]-> Rebin(RB);
            INCLNP[ptbin][trig]-> Rebin(RB);
            INCL[ptbin][trig]  -> Rebin(RB);
            INCL2[ptbin][trig] -> Rebin(RB);
            LSIM2[ptbin][trig] -> Rebin(RB);
            USIM2[ptbin][trig] -> Rebin(RB);
            HHDP[ptbin][trig]  -> Rebin(RB);
            NSPI[ptbin][trig]  -> Rebin(10);

            // Actually manipulate histos and plot (photnic del Phi)

            USIMNP[ptbin][trig]->SetLineColor(kRed);
            USIMNP[ptbin][trig]->SetLineWidth(1);
            USIMNP[ptbin][trig]->GetXaxis()->SetTitle("#Delta#phi_{eh}");
            USIMNP[ptbin][trig]->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            if(ptbin == 0)
                USIMNP[ptbin][trig]->SetTitle("Photonic Electron Reconstruction (No Partner Track)");
            else if (ptbin == 1 && trig !=3)
                USIMNP[ptbin][trig]->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                USIMNP[ptbin][trig]->SetTitle("MB");
            else
                USIMNP[ptbin][trig]->SetTitle("");
            USIMNP[ptbin][trig]->Draw("");

            LSIMNP[ptbin][trig]->SetLineColor(kBlack);
            LSIMNP[ptbin][trig]->SetLineWidth(1);
            LSIMNP[ptbin][trig]->Draw(" same");
            lbl[ptbin]->Draw("same");

            // Subtraction of (USNP-LS)
            TH1F *SUB = (TH1F*)USIMNP[ptbin][trig]->Clone(); //
            SUB->SetName("Subtraction");      // Create SUB as a clone of USIMNP
            SUB->Add(LSIMNP[ptbin][trig],-1);
            SUB->SetLineColor(kBlue);
            SUB->SetLineWidth(1);
            SUB->SetFillStyle(3001);
            SUB->SetFillColor(kBlue);
            SUB->Draw("same");
            lbl[ptbin]->Draw("same");
            TLegend* leg = new TLegend(0.2,0.73,0.55,0.85);
            leg->AddEntry(USIMNP[ptbin][trig],"Unlike Sign","lpe");
            leg->AddEntry(LSIM[ptbin][trig],"Like Sign", "lpe");
            leg->AddEntry(SUB,"Unlike - Like", "lpe");
            leg->Draw();

            // Plot different US (w/wo partner)
            USComp[trig]->cd(ptbin+1);
            TH1F *USwP = (TH1F*)USIM[ptbin][trig]->Clone();
            USwP->SetLineColor(kRed); //with partner tracks
            USwP->GetXaxis()->SetTitle("#Delta#phi_{eh}");
            USwP->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            if(ptbin == 0)
                USwP->SetTitle("Photonic Unlike Sign Distributions");
            else if (ptbin == 1 && trig !=3)
                USwP->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                USwP->SetTitle("MB");
            else
                USwP->SetTitle("");
            USwP->Draw("");
            TH1F *USnP = (TH1F*)USIMNP[ptbin][trig]->Clone();
            USnP->SetLineColor(kBlack);
            USnP->Draw("same");
            lbl[ptbin]->Draw("same");
            TLegend* legUS = new TLegend(0.35,0.8,0.77,0.87);
            legUS->AddEntry(USwP,"With Partner Track","lpe");
            legUS->AddEntry(USnP,"Partner Track Removed", "lpe");
            legUS->Draw();

            // Plot different LS (w/wo partner)
            LSComp[trig]->cd(ptbin+1);
            TH1F *LSwP = (TH1F*)LSIM[ptbin][trig]->Clone();
            LSwP->SetLineColor(kRed); //with partner tracks
            LSwP->GetXaxis()->SetTitle("#Delta#phi_{eh}");
            LSwP->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            if(ptbin == 0)
                LSwP->SetTitle("Photonic Like Sign Distributions");
            else if (ptbin == 1 && trig !=3)
                LSwP->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                LSwP->SetTitle("MB");
            else
                LSwP->SetTitle("");
            LSwP->Draw("");
            TH1F *LSnP = (TH1F*)LSIMNP[ptbin][trig]->Clone();
            LSnP->SetLineColor(kBlack);
            LSnP->Draw("same");
            lbl[ptbin]->Draw("same");
            TLegend* legLS = new TLegend(0.35,0.8,0.77,0.87);
            legLS->AddEntry(LSwP,"With Partner Track","lpe");
            legLS->AddEntry(LSnP,"Partner Track Removed", "lpe");
            legLS->Draw();

            // Plot different Incl (w/wo partner)
            InclComp[trig]->cd(ptbin+1);
            TH1F *InclwP = (TH1F*)INCL[ptbin][trig]->Clone();
            InclwP->SetLineColor(kRed); //with partner tracks
            InclwP->GetXaxis()->SetTitle("#Delta#phi_{eh}");
            InclwP->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            if(ptbin == 0)
                InclwP->SetTitle("Inclusive Distributions");
            else if (ptbin == 1 && trig !=3)
                InclwP->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                InclwP->SetTitle("MB");
            else
                InclwP->SetTitle("");
            InclwP->Draw("");
            TH1F *InclnP = (TH1F*)INCLNP[ptbin][trig]->Clone();
            InclnP->SetLineColor(kBlack);
            InclnP->Draw("same");
            lbl[ptbin]->Draw("same");
            TLegend* legIncl = new TLegend(0.35,0.8,0.77,0.87);
            legIncl->AddEntry(InclwP,"Inclusive","lpe");
            legIncl->AddEntry(InclnP,"Semi-Inclusive", "lpe");
            legIncl->Draw();

            // Actually manipulate histos and plot (photonic InvMass)
            inMass[trig]->cd(ptbin+1);
            USMM[ptbin][trig]->SetLineColor(kRed);
            USMM[ptbin][trig]->SetLineWidth(1);
            USMM[ptbin][trig]->GetXaxis()->SetTitle("InvMass (GeV/c^{2})");
            USMM[ptbin][trig]->GetXaxis()->SetRangeUser(0,0.4);
            if(ptbin == 0)
                USMM[ptbin][trig]->SetTitle("Photonic Electron Reconstruction");
            else if (ptbin == 1 && trig !=3)
                USMM[ptbin][trig]->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                USMM[ptbin][trig]->SetTitle("MB");
            else
                USMM[ptbin][trig]->SetTitle("");
            USMM[ptbin][trig]->Draw("");

            LSMM[ptbin][trig]->SetLineColor(kBlack);
            LSMM[ptbin][trig]->SetLineWidth(1);
            LSMM[ptbin][trig]->Draw("same");
            lbl[ptbin]->Draw("same");

            // Subtraction of (US-LS)
            TH1F *SUB4 = (TH1F*)USMM[ptbin][trig]->Clone(); //
            SUB4->SetName("Subtraction");      // Create SUB as a clone of USIM
            SUB4->Add(LSMM[ptbin][trig],-1);
            SUB4->SetLineColor(kBlue);
            SUB4->SetLineWidth(1);
            SUB4->SetFillStyle(3001);
            SUB4->SetFillColor(kBlue);
            SUB4->Draw("same");
            TLegend* leg2 = new TLegend(0.45,0.6,0.85,0.75);
            leg2->AddEntry(USMM[ptbin][trig],"Unlike Sign","lpe");
            leg2->AddEntry(LSMM[ptbin][trig],"Like Sign", "lpe");
            leg2->AddEntry(SUB4,"Unlike - Like", "lpe");
            leg2->Draw();

            // Handle Inclusive Hists
            IN[trig]->cd(ptbin+1);
            INCL[ptbin][trig]->SetLineColor(kBlue);
            INCL[ptbin][trig]->SetLineWidth(1);
            INCL[ptbin][trig]->GetXaxis()->SetTitle("#Delta#phi_{eh}");
            INCL[ptbin][trig]->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            if(ptbin == 0)
                INCL[ptbin][trig]->SetTitle("Inclusive Electrons");
            else if (ptbin == 1 && trig !=3)
                INCL[ptbin][trig]->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                INCL[ptbin][trig]->SetTitle("MB");
            else
                INCL[ptbin][trig]->SetTitle("");
            INCL[ptbin][trig]->Draw("");
            lbl[ptbin]->Draw("same");

            IN[trig]->Update();

            // Plot Had-Had correlations
            cHH[trig]->cd(ptbin+1);
            HHDP[ptbin][trig]->SetLineColor(kGreen+3);
            HHDP[ptbin][trig]->SetLineWidth(1);
            HHDP[ptbin][trig]->GetXaxis()->SetTitle("#Delta#phi_{eh}");
            HHDP[ptbin][trig]->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            if(ptbin == 0)
                HHDP[ptbin][trig]->SetTitle("Hadron-Hadron Correlations");
            else if (ptbin == 1 && trig !=3)
                HHDP[ptbin][trig]->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                HHDP[ptbin][trig]->SetTitle("MB");
            else
                HHDP[ptbin][trig]->SetTitle("");
            HHDP[ptbin][trig]->Draw("");
            lbl[ptbin]->Draw("same");


            // Subtraction of Inclusive - (1/e - 1)US + (1/e)LS - (1-purity)HadHad
            result[trig]->cd(ptbin+1);
            TH1F *INCDP = (TH1F*)INCLNP[ptbin][trig]->Clone();
            TH1F *ULDP  = (TH1F*)USIMNP[ptbin][trig]->Clone();
            TH1F *LSDP  = (TH1F*)LSIMNP[ptbin][trig]->Clone();
            TH1F *HADDP = (TH1F*)HHDP[ptbin][trig]->Clone();
            INCDP->SetName(Form("scaleNPEhDelPhi_%i_%i",trig,ptbin));
            ULDP->Scale(1./epsilon[ptbin] - 1.); // Scale each distribution by associated factors
            LSDP->Scale(1./epsilon[ptbin]);
            HADDP->Scale(HHScale*hadPur);
            INCDP->Add(ULDP,-1);
            INCDP->Add(LSDP,1);
            INCDP->Add(HADDP,-1);
            TH1F *unscaleINCDP = (TH1F*)INCDP->Clone();   //
            unscaleINCDP->SetName(Form("NPEhDelPhi_%i_%i",trig,ptbin)); // Make a clone before normalization, to pass to fit program
            INCDP->Scale(1./((Double_t)Norm));//*INCDP->GetBinWidth(1)));
            INCDP->SetLineColor(kBlack);
            INCDP->SetLineWidth(1);
            INCDP->SetFillStyle(3001);
            INCDP->SetFillColor(kYellow);
            INCDP->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            INCDP->GetXaxis()->SetTitle("#Delta#phi_{eh}");
            INCDP->GetYaxis()->SetTitle("1/N_{NPE} #upoint dN/d(#Delta)#phi");
            INCDP->GetYaxis()->SetTitleOffset(1.55);
            if(ptbin == 0)
                INCDP->SetTitle("#Delta#phi Non-Photonic Electrons and Hadrons");
            else if (ptbin == 1 && trig !=3)
                INCDP->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                INCDP->SetTitle("MB");
            else
                INCDP->SetTitle("");
            INCDP->Draw("");
            lbl[ptbin]->Draw("same");

            // Setup unscaled for fractionFit (don't normalize here!)
            unscaleINCDP->SetLineColor(kBlack);
            unscaleINCDP->SetLineWidth(1);
            unscaleINCDP->SetFillStyle(3001);
            unscaleINCDP->SetFillColor(kYellow);
            unscaleINCDP->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            unscaleINCDP->GetXaxis()->SetTitle("#Delta#phi_{eh}");
            unscaleINCDP->GetYaxis()->SetTitle("1/N_{NPE} #upoint dN/d(#Delta)#phi");
            unscaleINCDP->GetYaxis()->SetTitleOffset(1.55);
            if(ptbin == 0)
                unscaleINCDP->SetTitle("#Delta#phi Non-Photonic Electrons and Hadrons");
            else if (ptbin == 1 && trig !=3)
                unscaleINCDP->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                unscaleINCDP->SetTitle("MB");
            else
                unscaleINCDP->SetTitle("");

            // nSigmaPion QA
            nSigPi[trig]->cd(ptbin+1);
            NSPI[ptbin][trig]->SetLineColor(kGreen+3);
            NSPI[ptbin][trig]->SetLineWidth(1);
            NSPI[ptbin][trig]->GetXaxis()->SetTitle("n#sigma_{#pi}");
            NSPI[ptbin][trig]->GetXaxis()->SetRangeUser(-2.,2.);
            if(ptbin == 0)
                NSPI[ptbin][trig]->SetTitle("n Sigma Pion (n#sigma_{#pi})");
            else if (ptbin == 1 && trig !=3)
                NSPI[ptbin][trig]->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                NSPI[ptbin][trig]->SetTitle("MB");
            else
                NSPI[ptbin][trig]->SetTitle("");
            NSPI[ptbin][trig]->Draw("");
            lbl[ptbin]->Draw("same");

            // All Distributions
            allDist[trig]->cd(ptbin+1);
            TH1F *INCLUSIVE = (TH1F*)INCLNP[ptbin][trig]->Clone();
            TH1F *UNLIKE  = (TH1F*)USIMNP[ptbin][trig]->Clone();
            TH1F *LIKE  = (TH1F*)LSIMNP[ptbin][trig]->Clone();
            TH1F *HADRON = (TH1F*)HHDP[ptbin][trig]->Clone();
            TH1F *USmLS  = (TH1F*)USIMNP[ptbin][trig]->Clone();
            USmLS->Add(LIKE,-1);
            USmLS->Scale(1./(USNorm-LSNorm));
            INCLUSIVE->Scale(1./inclNorm);
            UNLIKE->Scale(1./USNorm);
            LIKE->Scale(1./LSNorm);
            HADRON->Scale(1./hhNorm);
            INCLUSIVE->SetLineColor(7);
            LIKE->SetLineColor(kBlue);
            INCLUSIVE->GetYaxis()->SetRangeUser(0.01,2);
            gPad->SetLogy(1);
            INCLUSIVE->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            INCLUSIVE->SetMarkerStyle(20);
            UNLIKE->SetMarkerStyle(21);
            LIKE->SetMarkerStyle(22);
            HADRON->SetMarkerStyle(23);
            USmLS->SetMarkerStyle(34);
            INCLUSIVE->SetMarkerColor(7);
            INCLUSIVE->SetMarkerSize(0.3);
            UNLIKE->SetMarkerSize(0.3);
            LIKE->SetMarkerSize(0.3);
            HADRON->SetMarkerSize(0.3);
            USmLS->SetMarkerSize(0.3);
            INCLUSIVE->SetMarkerColor(7);
            UNLIKE->SetMarkerColor(kRed);
            LIKE->SetMarkerColor(kBlue);
            HADRON->SetMarkerColor(kGreen+3);
            INCLUSIVE->Draw("");
            UNLIKE->Draw("same");
            LIKE->Draw("same");
            HADRON->Draw("same");
            USmLS->Draw("same");
            INCDP->Draw("same");
            lbl[ptbin]->Draw("same");
            stat[ptbin]->Draw("same");
            TLegend* legAll = new TLegend(0.45,0.11,0.85,0.3);
            legAll->AddEntry(INCLUSIVE,"Inclusive","lpe");
            legAll->AddEntry(UNLIKE,"Unlike Sign","lpe");
            legAll->AddEntry(LIKE,"Like Sign", "lpe");
            legAll->AddEntry(HADRON,"Hadron-Hadron", "lpe");
            legAll->AddEntry(USmLS,"Unlike-Like","lpe");
            legAll->AddEntry(INCDP,"NPE-h","lpe");
            legAll->Draw("same");

        }

        // Pileup Calculation (using just the hPtCut in the anaConst.h)
        /* mh3nTracksZdcx[trig]    = (TH3F*)f->Get(Form("mh3nTracksZdcx_%i_%i",trig,0));   // originally filled for various hpT cuts, use 0 which starts at hpt > 0.3
        mh3nTracksZdcxUS[trig]  = (TH3F*)f->Get(Form("mh3nTracksZdcxUS_%i_%i",trig,0)); // These histos are (epT,hpT,ZDCx), get nHadrons vs ZDCx
        mh3nTracksZdcxLS[trig]  = (TH3F*)f->Get(Form("mh3nTracksZdcxLS_%i_%i",trig,0));
        mh3nTracksZdcxHad[trig] = (TH3F*)f->Get(Form("mh3nTracksZdcxHad_%i_%i",trig,0));
        mh3nTracksZdcx[trig]->Sumw2(); mh3nTracksZdcxUS[trig]->Sumw2(); mh3nTracksZdcxLS[trig]->Sumw2();  mh3nTracksZdcxHad[trig]->Sumw2();

        mh2PtEZdcx[trig]       = (TH2F*)f->Get(Form("mh2PtEZdcx_%i",trig));            // Filled (epT,ZDCx). Get nTrigs vs ZDCx
        mh2PtEZdcxUS[trig]     = (TH2F*)f->Get(Form("mh2PtEZdcxUS_%i",trig));
        mh2PtEZdcxLS[trig]     = (TH2F*)f->Get(Form("mh2PtEZdcxLS_%i",trig));
        mh2PtEZdcxHad[trig]     = (TH2F*)f->Get(Form("mh2PtEZdcxHad_%i",trig));
        mh2PtEZdcx[trig]->Sumw2(); mh2PtEZdcxUS[trig]->Sumw2(); mh2PtEZdcxLS[trig]->Sumw2(); mh2PtEZdcxHad[trig]->Sumw2();

        for(Int_t ptbin=0; ptbin<numPtBins; ptbin++)// cut in to trigger pt slices
          {
        projZDCxHad[ptbin][trig] = mh3nTracksZdcx[trig]->ProjectionZ(Form("projZDCxHad_%i_%i",ptbin,trig),mh3nTracksZdcx[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh3nTracksZdcx[trig]->GetXaxis()->FindBin(highpt[ptbin])-1,mh3nTracksZdcx[trig]->GetYaxis()->FindBin(hptCut),mh3nTracksZdcx[trig]->GetYaxis()->FindBin(hptMax));
        projZDCxHadUS[ptbin][trig] = mh3nTracksZdcxUS[trig]->ProjectionZ(Form("projZDCxHadUS_%i_%i",ptbin,trig),mh3nTracksZdcxUS[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh3nTracksZdcxUS[trig]->GetXaxis()->FindBin(highpt[ptbin])-1,mh3nTracksZdcxUS[trig]->GetYaxis()->FindBin(hptCut),mh3nTracksZdcxUS[trig]->GetYaxis()->FindBin(hptMax));
        projZDCxHadLS[ptbin][trig] = mh3nTracksZdcxLS[trig]->ProjectionZ(Form("projZDCxHadLS_%i_%i",ptbin,trig),mh3nTracksZdcxLS[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh3nTracksZdcxLS[trig]->GetXaxis()->FindBin(highpt[ptbin])-1,mh3nTracksZdcxLS[trig]->GetYaxis()->FindBin(hptCut),mh3nTracksZdcxLS[trig]->GetYaxis()->FindBin(hptMax));
        projZDCxHadHad[ptbin][trig] = mh3nTracksZdcxHad[trig]->ProjectionZ(Form("projZDCxHadHad_%i_%i",ptbin,trig),mh3nTracksZdcxHad[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh3nTracksZdcxHad[trig]->GetXaxis()->FindBin(highpt[ptbin])-1,mh3nTracksZdcxHad[trig]->GetYaxis()->FindBin(hptCut),mh3nTracksZdcxHad[trig]->GetYaxis()->FindBin(hptMax));

        projZDCxTrig[ptbin][trig] = mh2PtEZdcx[trig]->ProjectionY(Form("projZDCxTrig_%i_%i",ptbin,trig),mh2PtEZdcx[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh2PtEZdcx[trig]->GetXaxis()->FindBin(highpt[ptbin])-1);
        projZDCxTrigUS[ptbin][trig] = mh2PtEZdcxUS[trig]->ProjectionY(Form("projZDCxTrigUS_%i_%i",ptbin,trig),mh2PtEZdcxUS[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh2PtEZdcxUS[trig]->GetXaxis()->FindBin(highpt[ptbin])-1);
        projZDCxTrigLS[ptbin][trig] = mh2PtEZdcxLS[trig]->ProjectionY(Form("projZDCxTrigLS_%i_%i",ptbin,trig),mh2PtEZdcxLS[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh2PtEZdcxLS[trig]->GetXaxis()->FindBin(highpt[ptbin])-1);
        projZDCxTrigHad[ptbin][trig] = mh2PtEZdcxHad[trig]->ProjectionY(Form("projZDCxTrigHad_%i_%i",ptbin,trig),mh2PtEZdcxHad[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh2PtEZdcxHad[trig]->GetXaxis()->FindBin(highpt[ptbin])-1);

        // Get Total number of hadrons in pileup (first scale each distribution by efficiency, just like data)
        projZDCxHadUS[ptbin][trig] -> Scale(1./epsilon[ptbin] - 1.);
        projZDCxHadLS[ptbin][trig] -> Scale(1./epsilon[ptbin]);
        projZDCxHadHad[ptbin][trig]-> Scale(HHScale*hadPur);
        projZDCxHad[ptbin][trig] -> Add(projZDCxHadUS[ptbin][trig], -1.);
        projZDCxHad[ptbin][trig] -> Add(projZDCxHadLS[ptbin][trig], 1.);
        projZDCxHad[ptbin][trig] -> Add(projZDCxHadHad[ptbin][trig], -1.);

        // Get Total number of trigs in pileup (first scale each distribution by efficiency, just like data)
        projZDCxTrigUS[ptbin][trig] -> Scale(1./epsilon[ptbin] - 1.);
        projZDCxTrigLS[ptbin][trig] -> Scale(1./epsilon[ptbin]);
        projZDCxTrigHad[ptbin][trig]-> Scale(HHScale*hadPur);
        projZDCxTrig[ptbin][trig] -> Add(projZDCxTrigUS[ptbin][trig], -1.);
        projZDCxTrig[ptbin][trig] -> Add(projZDCxTrigLS[ptbin][trig], 1.);
        projZDCxTrig[ptbin][trig] -> Add(projZDCxTrigHad[ptbin][trig], -1.);

        // Actually do the division of total hadrons/total trigs
        projZDCxHad[ptbin][trig]->Divide(projZDCxTrig[ptbin][trig]);

        // plot projections
        pile[trig]->cd(ptbin+1);
        projZDCxHad[ptbin][trig]->SetLineColor(kBlack);
        projZDCxHad[ptbin][trig]->GetXaxis()->SetTitle("ZDCx");
        projZDCxHad[ptbin][trig]->GetYaxis()->SetTitle("<nHadrons>/<nTracks>");
        projZDCxHad[ptbin][trig]->GetYaxis()->SetRangeUser(0,20);
        //
        gStyle->SetOptFit(1111);
        projZDCxHad[ptbin][trig]->Fit("pol1");
        projZDCxHad[ptbin][trig]->GetFunction("pol1")->SetLineColor(kRed);
        TPaveStats *st = ((TPaveStats*)(projZDCxHad[ptbin][trig]->GetListOfFunctions()->FindObject("stats")));
        if (st) {
          st->SetTextColor(projZDCxHad[ptbin][trig]->GetFunction("pol1")->GetLineColor());
          st->SetX1NDC(0.64); st->SetX2NDC(0.99);
          st->SetY1NDC(0.4); st->SetY2NDC(0.6);
        }
        pile[trig]->Modified();pile[trig]->Update();
        projZDCxHad[ptbin][trig]->Draw("");

        // Get Fit information and store to use in corrections
        TF1 *fitResult = projZDCxHad[ptbin][trig]->GetFunction("pol1");
        pu[0][ptbin][trig] = fitResult->GetParameter(0);
        pu[1][ptbin][trig] = fitResult->GetParameter(1);
           	cout << trig << " " << ptbin << ": " << pu[0][ptbin][trig] << " " << pu[1][ptbin][trig] << endl;
        }*/
    }

    // Draw on "SinglePlot" canvas for saving single plots from grid
    TPad* pNew = (TPad*)result[2]->GetPad(4)->Clone();
    singlePlot->cd();
    pNew->ResizePad();
    pNew->Draw();

    // Make PDF with output canvases
    if(makePDF)
    {
        //Set front page
        TCanvas* fp = new TCanvas("fp","Front Page",100,0,1000,900);
        fp->cd();
        TBox *bLabel = new TBox(0.01, 0.88, 0.99, 0.99);
        bLabel->SetFillColor(38);
        bLabel->Draw();
        TLatex tl;
        tl.SetNDC();
        tl.SetTextColor(kWhite);
        tl.SetTextSize(0.033);
        char tlName[100];
        char tlName2[100];

        TString titlename = FileName;
        int found = titlename.Last('/');
        if(found >= 0) {
            titlename.Replace(0, found+1, "");
        }
        sprintf(tlName, "RUN 12 pp 200 GeV NPE-h    #Delta#phi Analysis");
        tl.SetTextSize(0.05);
        tl.SetTextColor(kWhite);
        tl.DrawLatex(0.05, 0.92,tlName);

        TBox *bFoot = new TBox(0.01, 0.01, 0.99, 0.12);
        bFoot->SetFillColor(38);
        bFoot->Draw();
        tl.SetTextColor(kWhite);
        tl.SetTextSize(0.05);
        tl.DrawLatex(0.05, 0.05, (new TDatime())->AsString());
        tl.SetTextColor(kBlack);
        tl.SetTextSize(0.03);
        tl.DrawLatex(0.1, 0.14, titlename);
        sprintf(tlName,"eID: -1 < n  #sigma_{e TPC} < 3;  #left|gDCA #right| < 1 cm; 0.3 < p/E < 1.5;");
        tl.DrawLatex(0.1, 0.8,tlName);
        sprintf(tlName,"       nHitsFit > 20; nHits   #frac{dE}{dx} > 15; nHitFit/Max > 0.52;    #left|#eta#right| < 0.7;");
        tl.DrawLatex(0.1, 0.75,tlName);
        sprintf(tlName,"       n #phi > 1; n #eta > 1;  #left|dZ#right| < 3 cm;  #left|d#phi#right| < 0.015;");
        tl.DrawLatex(0.1, 0.7,tlName);
        sprintf(tlName,"hID: p_{T} > 0.5;  #left|#eta#right| < 1; nHitsFit > 15; nHits   #frac{dE}{dx} > 10; DCA < 1 cm;");
        tl.DrawLatex(0.1, 0.6,tlName);
        sprintf(tlName,"Event:  #left|V_{z}#right| < 35 cm;");
        tl.DrawLatex(0.1, 0.5,tlName);
        sprintf(tlName,"Triggers:  BHT0; BHT2;");
        tl.DrawLatex(0.1, 0.4,tlName);


        // Place canvases in order
        TCanvas* temp = new TCanvas();
        sprintf(name, "%s.pdf[", FileName);
        temp->Print(name);
        sprintf(name, "%s.pdf", FileName);
        temp = fp; // print front page
        temp->Print(name);
        temp = mixedC;
        temp->Print(name);
        temp = mixedCbinEta;
        temp->Print(name);
        temp = mixedCbinPhi;
        temp->Print(name);
        temp = mixedCbin;
        temp->Print(name);
        for(Int_t ii=0; ii<numTrigs; ii++)
        {
            if(!fPaintAll && (ii==1 || ii==3))
                continue;
            temp = IN[ii];
            temp->Print(name);
            temp = c[ii];
            temp->Print(name);
            temp = cHH[ii];
            temp->Print(name);
            temp = result[ii];
            temp->Print(name);
            temp = pile[ii];
            temp->Print(name);
            /*temp = inMass[ii];
            temp->Print(name);
            temp = USComp[ii];
            temp->Print(name);
            temp = LSComp[ii];
            temp->Print(name);
            temp = InclComp[ii];
            temp->Print(name);*/
            temp = nSigPi[ii];
            temp->Print(name);
            temp = allDist[ii];
            temp->Print(name);

        }
        sprintf(name, "%s.pdf]", FileName);
        temp->Print(name);
    }

    if(makeROOT)
    {
        file->Write();
        file->Close();
    }
}
Example #2
0
void AllInOne_combineLepton(const std::string& dataset,int btag=0, double timesX=1, bool useNewShape=false){

  std::string useNewShapeText = (useNewShape) ? "_newshape" : "";

  char wsFileName[700];
  sprintf(wsFileName,"datacards/400/hzz2l2q_ee%db.input.root",btag);
  //sprintf(wsFileName,"PROVA/datacards_%s%s/hzz2l2q_ee%db.input.root",dataset.c_str(), useNewShapeText.c_str(),btag);

  gSystem->Load("libRooFit");
  gSystem->Load("libFFTW");

  string histoName[3];
  histoName[0]="mZZ_kinfit_hiMass_0btag";
  histoName[1]="mZZ_kinfit_hiMass_1btag";
  histoName[2]="mZZ_kinfit_hiMass_2btag";
  string btagName[3]={"0b","1b","2b"};

  double LumiScale=0.;
  if( dataset=="Run2011A_FULL" ) LumiScale = 2100.;
  else if( dataset=="LP11" ) LumiScale = 1600.;
  else {
    std::cout << "Unknown dataset '" << dataset << "'. Exiting." << std::endl;
  }

  RooDataSet *data_bkg;  
  RooDataSet *data_temp;
  TFile *file;

  string cutString[3];
  cutString[0]="nBTags==0 && (mZjj>75 && mZjj<105) && mZZ>183";
  cutString[1]="nBTags==1 && (mZjj>75 && mZjj<105) && mZZ>183";
  cutString[2]="nBTags==2 && (mZjj>75 && mZjj<105) && mZZ>183";

  int binWidth=20;
  int highBin=750;
  int lowBin=150;

//double muonEff[3]={.576,.548,.489};

//double expSig[3];
//expSig[0]=5.65*LumiScale ;
//expSig[1]=4.89*LumiScale ;
//expSig[2]=2.37*LumiScale ;

  char alphaFileName[200];
  sprintf( alphaFileName, "alphaFile_%s_%dbtag_ALL.root", dataset.c_str(), btag);
  TFile* alphaFile = TFile::Open(alphaFileName);
  TTree* treeSidebandsDATA_alphaCorr = (TTree*)alphaFile->Get("sidebandsDATA_alpha");
  TH1D* h1_mZZ_sidebands_alpha = new TH1D("mZZ_sidebands_alpha", "", 65, 150., 800.);
  char sidebandsCut_alpha[500];
  sprintf(sidebandsCut_alpha, "eventWeight_alpha*(isSidebands && nBTags==%d)", btag);
  treeSidebandsDATA_alphaCorr->Project("mZZ_sidebands_alpha", "mZZ", sidebandsCut_alpha);
  float expBkg = h1_mZZ_sidebands_alpha->Integral();
  std::cout <<  "++++ expBkg: " << expBkg << std::endl;



  stringstream convert;

  // --------------------- measurable (ZZ invariant mass) ----------------
  string temp;
  temp="m_{ZZ}";
  RooRealVar mZZ("mZZ",temp.c_str(),lowBin,highBin);
  RooRealVar nBTags("nBTags","nBTags",-1.,3.);
  RooRealVar leptType("leptType","leptType",0,1);
  RooRealVar mZjj("mZjj","mZjj",0,200.);

  // ----------------- get parameters from data cards! -----------------
  
  TFile *wsFile = new TFile(wsFileName);
  RooWorkspace *ws = (RooWorkspace*) wsFile->Get("w");

  // ==================== defining bkg PDF ==========================
  // ------------------------ fermi ------------------------------
  RooRealVar cutOff("cutOff","position of fermi",ws->var("cutOff_BKG")->getVal());
  cutOff.setConstant(kTRUE);
  RooRealVar beta("beta","width of fermi",ws->var("beta_BKG")->getVal());
  beta.setConstant(kTRUE);
	     		       
  RooFermi fermi("fermi","fermi function",mZZ,cutOff,beta);
  // -------------------- double gauss ---------------------------
  temp="CMS_hzz2l2q_bkg"+btagName[btag]+"p1";
  RooRealVar m("m","m",ws->var(temp.c_str())->getVal());
  m.setConstant(kTRUE);
  temp="CMS_hzz2l2q_bkg"+btagName[btag]+"p2";
  RooRealVar wdth("wdth","wdth",ws->var(temp.c_str())->getVal());
  wdth.setConstant(kTRUE);
  temp="CMS_hzz2l2q_bkg"+btagName[btag]+"p3";
  RooRealVar n("n","n",ws->var(temp.c_str())->getVal());
  n.setConstant(kTRUE);
  temp="CMS_hzz2l2q_bkg"+btagName[btag]+"p4";
  RooRealVar alpha("alpha","alpha",ws->var(temp.c_str())->getVal());
  alpha.setConstant(kTRUE);
  temp="CMS_hzz2l2q_bkg"+btagName[btag]+"p5";
  RooRealVar theta("theta","theta",ws->var(temp.c_str())->getVal());
  theta.setConstant(kTRUE);

  RooCB CB("CB","Crystal ball",mZZ,m,wdth,alpha,n,theta);
  
  RooProdPdf background("background","background",RooArgSet(fermi,CB));


  // ------------------ get data --------------------------
  // for reading sideband extrapolated data...
  std::string fileName = "HZZlljjRM_DATA_" + dataset + "_optLD_looseBTags_v2_ALL.root";
  file = new TFile(fileName.c_str());
  //file = new TFile("../HZZlljjRM_DATA_Run2011A_FULL_optLD_looseBTags_v2_ALL.root");
  TTree* t=(TTree*)file->Get("tree_passedEvents");
  data_bkg=new RooDataSet("data_bkg","data_bkg",t,
			  RooArgSet(mZZ,leptType,nBTags,mZjj),
			  cutString[btag].c_str());

  // --------- draw MC data -------------------
  RooPlot *plot_MCbkg = mZZ.frame(lowBin,highBin,(int)(highBin-lowBin)/binWidth);

  //-----------------------------------------------------------------------
  TCanvas *c2 = new TCanvas("c2","c2",600,600);

  TPaveText* cmslabel = new TPaveText( 0.145, 0.953, 0.6, 0.975, "brNDC" );
  cmslabel->SetFillColor(kWhite);
  cmslabel->SetTextSize(0.038);
  cmslabel->SetTextAlign(11);
  cmslabel->SetTextFont(62);
  cmslabel->SetBorderSize(0);
  char lumilabel[500];
  sprintf( lumilabel, "CMS Preliminary 2011, %.1f fb^{-1}", LumiScale/1000.);
  cmslabel->AddText(lumilabel);

  TPaveText* label_sqrt = new TPaveText(0.7,0.953,0.96,0.975, "brNDC");
  label_sqrt->SetFillColor(kWhite);
  label_sqrt->SetTextSize(0.038);
  label_sqrt->SetTextFont(42);
  label_sqrt->SetTextAlign(31); // align right
  label_sqrt->SetBorderSize(0);
  label_sqrt->AddText("#sqrt{s} = 7 TeV");
  //-----------------------------------------------------------------------

  background.plotOn(plot_MCbkg,Normalization(expBkg));
  data_bkg->plotOn(plot_MCbkg,Binning((int)(highBin-lowBin)/binWidth));
  // -------------------- get histograms -----------------
  
  TFile *ZjetsFile = new TFile("HZZlljjRM_DYJetsToLL_TuneZ2_M-50_7TeV-madgraph-tauola_Summer11-PU_S4_START42_V11-v1_optLD_looseBTags_v2_ALL.root");
  TFile *TTFile = new TFile("HZZlljjRM_TT_TW_TuneZ2_7TeV-powheg-tauola_Summer11-PU_S4_START42_V11-v1_optLD_looseBTags_v2_ALL.root");
  TFile *VVFile = new TFile("HZZlljjRM_VV_TuneZ2_7TeV-pythia6-tauola_Summer11-PU_S4_START42_V11-v1_optLD_looseBTags_v2_ALL.root");
  TFile *H400File = new TFile("HZZlljjRM_GluGluToHToZZTo2L2Q_M-400_7TeV-powheg-pythia6_Summer11-PU_S4_START42_V11-v1_optLD_looseBTags_v2_ALL.root");

  TH1F *hZjets =(TH1F*)ZjetsFile->Get(histoName[btag].c_str());
  hZjets->SetName("hZjets");
  hZjets->Scale(LumiScale);
  hZjets->Rebin(binWidth);
  hZjets->SetFillColor(30);

  TH1F *hTT =(TH1F*)TTFile->Get(histoName[btag].c_str());
  hTT->SetName("hTT");
  convert << binWidth;
  temp=";m_{ZZ} [GeV]; Events / "+convert.str()+" GeV";
  hTT->SetTitle(temp.c_str());
  hTT->Scale(LumiScale);
  hTT->Rebin(binWidth);
  hTT->SetFillColor(39);
  gStyle->SetOptStat(0);

  //if(btag==0)
  //  hTT->GetYaxis()->SetRangeUser(0.0001,245);
  //if(btag==1)
  //  hTT->GetYaxis()->SetRangeUser(0.0001,245);
  //if(btag==2)
  //  hTT->GetYaxis()->SetRangeUser(0.0001,25);

  //hTT->Draw();


  TH1F *hVV =(TH1F*)VVFile->Get(histoName[btag].c_str());
  hVV->SetName("hVV");
  hVV->Scale(LumiScale);
  hVV->Rebin(binWidth);
  hVV->SetFillColor(38);

  TH1F* hH400 = (TH1F*)H400File->Get(histoName[btag].c_str());
  hH400->SetName("hH400");
  hH400->Scale(LumiScale*timesX);
  cout << "SIGNAL NORMALIZATION: " << hH400->Integral() << endl;
  hH400->Rebin(binWidth);
  hH400->SetFillColor(kYellow);//kRed+3);

  temp = ";m_{ZZ} [GeV];Events / "+convert.str()+" GeV";
  THStack *hBkg = new THStack("hBkg",temp.c_str());
  convert.str("");

  hBkg->Add(hVV);
  hBkg->Add(hTT);
  hBkg->Add(hZjets);
  hBkg->Add(hH400);

  float xMin = 150.;
  float xMax = 750.;
  float yMin = 0.;
  float yMax = 1.3*hBkg->GetMaximum();

  char yAxisName[500];
  sprintf( yAxisName, "Events / %.0f GeV", hVV->GetXaxis()->GetBinWidth(1) );
  //std::string yAxisName = "Events / "+convert.str()+" GeV";
  convert.str("");

//char xAxisName[400];
//sprintf( xAxisName, "m_{%s%sjj} [GeV]", leptType_forLegend.c_str(), leptType_forLegend.c_str() );

  TH2D* h2_axes = new TH2D("axes", "", 10, xMin, xMax, 10, yMin, yMax);
  h2_axes->SetXTitle("m_{lljj} [GeV]");
  h2_axes->SetYTitle(yAxisName);
  h2_axes->Draw();

  hBkg->Draw("SAMEHIST");
  plot_MCbkg->Draw("SAME");
  cmslabel->Draw();
  label_sqrt->Draw();
  // ---------------legend ---------------------------

  TLegend *leg = new TLegend(.4,.5,.8,.9);
  leg->SetTextSize(0.036);
  leg->SetFillColor(0);
  leg->SetBorderSize(0);
  convert.str("");
  convert << LumiScale/1000;
  temp="CMS Preliminary #sqrt{s}=7 TeV "+convert.str()+" fb^{-1}";
  //leg->SetHeader(temp.c_str());
  leg->AddEntry("background_Norm[mZZ]","Sideband Extrapolated Fit","l");
  //leg->AddEntry("model_Norm[mZZ]","Background+10#timesSignal","l");

  if(btag==0)
    temp="0 b-tag 2l2q data";
  if(btag==1)
    temp="1 b-tag 2l2q data";
  if(btag==2)
    temp="2 b-tag 2l2q data";

  leg->AddEntry("h_data_bkg",temp.c_str(),"p");
  leg->AddEntry("hZjets","Z + Jets","f");
  leg->AddEntry("hTT","tt/tW","f");
  leg->AddEntry("hVV","ZZ/WZ/WW","f");
  convert.str("");
  convert << timesX;
  temp="400 GeV SM Higgs#times"+convert.str();
  leg->AddEntry("hH400",temp.c_str(),"f");
  leg->Draw();

  string saveFileName="AllInOne_"+dataset + "_"+btagName[btag]+"tag_ll_LIMIT" + useNewShapeText + ".eps";

  c2->SaveAs(saveFileName.c_str()); 

}
Example #3
0
int binfit_function_dy_y_squarecuts() {
  gROOT->Reset();

  float scaledps,scaledpsy,scalesps,scalenlo,siggg,siggu,sigug;
  float datamass[81]={0};
  int dpsmass[81]={0};
  int spsmass[81]={0};
  float nlomass[81]={0.0};
  int nloggmass[81]={0};
  int nlogumass[81]={0};
  int nlougmass[81]={0};
  float rapmax = 1.9;
  float ptmin  = 8.0;
  //  float datapt[60],datady[20],datay[20];
  TChain data("PATEventTree");
  TChain dps("PATEventTree");
  TChain sps("PATEventTree");
  TChain nlogg("PATEventTree");
  TChain nlogu("PATEventTree");
  TChain nloug("PATEventTree");

  data.Add("Selected_events_newAcc.root");
//  dps.Add("Modified_Input_To_Fit_2012DPS_TMTight_3MuL3Match.root");
  dps.Add("Modified_Input_To_Fit_2012DPS_PUold_TMTight_3MuL3MatchPv.root");
  //dps.Add("Modified_Input_To_Fit_2012DPS_GENTupleOnly_TMTight_MuL3Match.root");
  sps.Add("Modified_Input_To_Fit_2012SPSLOpy8_TMTight_3MuL3Match.root");
  //nlogg.Add("Modified_Input_To_Fit_2012SPSNLOpy8_gg_TMTight_3MuL3Match.root");
  nlogg.Add("Modified_Input_To_Fit_2012SPSNLO_gg_TMTight_MuL3Match_PU_OffsetBS.root");
  //float massbins[]={6.2,7,8,10,13,17,23,30,42,80};
  //float ptbins[]={0,7,12,16,20,25,80};
  //float dybins[]={0,0.2,0.4,0.6,0.9,1.3,1.8,2.4,4.5};
  ////float ybins[]={-2.2,-1.8,-1.6,-1.4,-1.2,-1.0,-0.8,-0.6,-0.4,-0.2,0,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.2};
  //float ybins[]={0,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.2};
  //int nmbins = 9; 
  //int nptbins = 6;
  //int ndybins = 8;
  //int nybins = 10;
  float massbins[]={0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80};
  float ptbins[]={0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80};
  float dybins[]={0,.3,.6,.9,1.2,1.5,1.8,2.1,2.4,2.7,3.0,3.3,3.6};
  //float dybins[]={0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.1,2.2,2.3,2.4,2.5,2.6,2.7,2.8,2.9,3.0,3.1,3.2,3.3,3.4,3.5,3.6};
  float ybins[]={0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.1,2.2};
    int nmbins = 40;
    int nptbins = 40;
    int ndybins =12;
    //int ndybins = 36;
    int nybins = 22;
  //int nybins = 20;
    int mbinerr = -99;
    int ptbinerr = -99;
    int dybinerr = -99;
    int ybinerr = -99;
  TH1F *mass_data = new TH1F("mass_data","mass_data",nmbins,massbins); 
  TH1F *mass_dps = new TH1F("mass_dps","mass_dps",nmbins,massbins); 
  TH1F *mass_sps = new TH1F("mass_sps","mass_sps",nmbins,massbins); 
  TH1F *mass_nlogg = new TH1F("mass_nlogg","mass_nlogg",nmbins,massbins); 
  TH1F *mass_nlogu = new TH1F("mass_nlogu","mass_nlogu",nmbins,massbins); 
  TH1F *mass_nloug = new TH1F("mass_nloug","mass_nloug",nmbins,massbins); 
  TH1F *mass_nlo = new TH1F("mass_nlo","mass_nlo",nmbins,massbins); 
  TH1F *pt_data = new TH1F("pt_data","pt_data",nptbins,ptbins); 
  TH1F *pt_dps = new TH1F("pt_dps","pt_dps",nptbins,ptbins); 
  TH1F *pt_sps = new TH1F("pt_sps","pt_sps",nptbins,ptbins); 
  TH1F *pt_nlogg = new TH1F("pt_nlogg","pt_nlogg",nptbins,ptbins); 
  TH1F *pt_nlogu = new TH1F("pt_nlogu","pt_nlogu",nptbins,ptbins); 
  TH1F *pt_nloug = new TH1F("pt_nloug","pt_nloug",nptbins,ptbins); 
  TH1F *pt_nlo = new TH1F("pt_nlo","pt_nlo",nptbins,ptbins); 
  TH1F *dy_data = new TH1F("dy_data","dy_data",ndybins,dybins); 
  TH1F *dy_dps = new TH1F("dy_dps","dy_dps",ndybins,dybins); 
  TH1F *dy_sps = new TH1F("dy_sps","dy_sps",ndybins,dybins); 
  TH1F *dy_nlogg = new TH1F("dy_nlogg","dy_nlogg",ndybins,dybins); 
  TH1F *dy_nlogu = new TH1F("dy_nlogu","dy_nlogu",ndybins,dybins); 
  TH1F *dy_nloug = new TH1F("dy_nloug","dy_nloug",ndybins,dybins); 
  TH1F *dy_nlo = new TH1F("dy_nlo","dy_nlo",ndybins,dybins); 
  TH1F *y_data = new TH1F("y_data","y_data",nybins,ybins); 
  TH1F *y_dps = new TH1F("y_dps","y_dps",nybins,ybins); 
  TH1F *y_sps = new TH1F("y_sps","y_sps",nybins,ybins); 
  TH1F *y_nlogg = new TH1F("y_nlogg","y_nlogg",nybins,ybins); 
  TH1F *y_nlogu = new TH1F("y_nlogu","y_nlogu",nybins,ybins); 
  TH1F *y_nloug = new TH1F("y_nloug","y_nloug",nybins,ybins); 
  TH1F *y_nlo = new TH1F("y_nlo","y_nlo",nybins,ybins); 
  data.Draw("FourMu_Mass >> mass_data",Form("FourMu_pT<80&&abs(FourMu_Rapidity)<1.8&&FourMu_Mass<60&&Sum$(Psi_pT>%.1f&&abs(Psi_y)<=%.1f)==2",ptmin,rapmax),"goff");
    mass_dps->SetEntries(109951.);
//    mass_dps->SetEntries(127.);
    dps.Draw("FourMu_Mass >> mass_dps",Form("FourMu_Mass>=0&&FourMu_Mass<=60&&FourMu_VtxProb>=0.1&&Sum$(abs(Psi_y)<=%.1f&&Psi_pT>%.1f)==2&&Sum$(abs(Mu_Eta)<=1.2&&Mu_pT>3.5||abs(Mu_Eta)>1.2&&abs(Mu_Eta)<1.6&&(Mu_pT>-3.75*abs(Mu_Eta)+8)||abs(Mu_Eta)>=1.6&&abs(Mu_Eta)<=2.0&&Mu_pT>2.0)==4",rapmax,ptmin),"goff");
    sps.Draw("FourMu_Mass >> mass_sps",Form("FourMu_Mass>=0&&FourMu_Mass<=60&&FourMu_VtxProb>=0.1&&Sum$(abs(Psi_y)<=%.1f&&Psi_pT>%.1f)==2&&Sum$(abs(Mu_Eta)<=1.2&&Mu_pT>3.5||abs(Mu_Eta)>1.2&&abs(Mu_Eta)<1.6&&(Mu_pT>-3.75*abs(Mu_Eta)+8)||abs(Mu_Eta)>=1.6&&abs(Mu_Eta)<=2.0&&Mu_pT>2.0)==4",rapmax,ptmin),"goff");
nlogg.Draw("FourMu_Mass >> mass_nlogg",Form("FourMu_Mass>=0&&FourMu_Mass<=60&&FourMu_VtxProb>=0.1&&Sum$(abs(Psi_y)<=%.1f&&Psi_pT>%.1f)==2&&Sum$(abs(Mu_Eta)<=1.2&&Mu_pT>3.5||abs(Mu_Eta)>1.2&&abs(Mu_Eta)<1.6&&(Mu_pT>-3.75*abs(Mu_Eta)+8)||abs(Mu_Eta)>=1.6&&abs(Mu_Eta)<=2.0&&Mu_pT>2.0)==4",rapmax,ptmin),"goff");
nlogu.Draw("FourMu_Mass >> mass_nlogu",Form("FourMu_Mass>=0&&FourMu_Mass<=60&&FourMu_VtxProb>=0.1&&Sum$(abs(Psi_y)<=%.1f&&Psi_pT>%.1f)==2&&Sum$(abs(Mu_Eta)<=1.2&&Mu_pT>3.5||abs(Mu_Eta)>1.2&&abs(Mu_Eta)<1.6&&(Mu_pT>-3.75*abs(Mu_Eta)+8)||abs(Mu_Eta)>=1.6&&abs(Mu_Eta)<=2.0&&Mu_pT>2.0)==4",rapmax,ptmin),"goff");
nloug.Draw("FourMu_Mass >> mass_nloug",Form("FourMu_Mass>=0&&FourMu_Mass<=60&&FourMu_VtxProb>=0.1&&Sum$(abs(Psi_y)<=%.1f&&Psi_pT>%.1f)==2&&Sum$(abs(Mu_Eta)<=1.2&&Mu_pT>3.5||abs(Mu_Eta)>1.2&&abs(Mu_Eta)<1.6&&(Mu_pT>-3.75*abs(Mu_Eta)+8)||abs(Mu_Eta)>=1.6&&abs(Mu_Eta)<=2.0&&Mu_pT>2.0)==4",rapmax,ptmin),"goff");

  datamass[0]=mass_data->Integral();
  std::cout<<datamass[0]<<std::endl;
//dps MC reco integral
  dpsmass[2]=127.;
//data reshuffle integral
  dpsmass[1]=109951./7.14777;
  dpsmass[0]=mass_dps->Integral();
  spsmass[0]=mass_sps->Integral();
  nloggmass[0]=mass_nlogg->Integral();
  nlogumass[0]=mass_nlogu->Integral();
  nlougmass[0]=mass_nlogg->Integral();
  //siggg=2.01;siggu=0.45;sigug=0.13;
  siggg=1.0;siggu=0.0;sigug=0.0;
  nlomass[0]=siggg*nloggmass[0] + siggu*nlogumass[0] + sigug*nlougmass[0]; 

  scaledps = datamass[0]/ (float) dpsmass[0];
  scaledps1 = datamass[0]/ (float) dpsmass[1];
  scaledps2 = datamass[0]/ (float) dpsmass[1];
  scalesps= datamass[0]/ (float) spsmass[0];
  scalenlo= datamass[0]/ (float) nloggmass[0];
  float Chi2=0;
  float minchi2norm=99999999.9;
  float minchi2=9999999.9;
  float mina, minb, minc, minan, minbn, mincn;
    TH1F *DpsBestdy = new TH1F("DpsBestdy","DpsBestdy",ndybins,dybins);
    TH1F *DpsBesty = new TH1F("DpsBesty","DpsBesty",nybins,ybins);

  //   Chi2 = Chi2 + pow((datamass[1] - (0.00*scaledps*dpsmass[1] + 0.0*scalesps*spsmass[1] + 0.0*scalenlo*nlomass[1])),2)/sqrt(datamass[1]);
  //  std::cout<<"Scale: " <<datamass[0]<<" " << dpsmass[0]<<" "<<scaledps<<" "<<scalesps<<" "<<scalenlo<<" "<<std::endl;
  for(float a=0.0; a<0.5; a=a+0.01){
    for(float b=0.0; b<0.009; b=b+0.01){
      for(float c=0.5; c<1; c=c+0.01){
        data.Draw("FourMu_Mass >> mass_data",Form("FourMu_pT<80&&abs(FourMu_Rapidity)<1.8&&FourMu_Mass<60&&Sum$(Psi_pT>%.1f&&abs(Psi_y)<=%.1f)==2",ptmin,rapmax),"goff");
            dps.Draw("FourMu_Mass >> mass_dps",Form("FourMu_Mass>=0&&FourMu_Mass<=60&&FourMu_VtxProb>=0.1&&Sum$(abs(Psi_y)<=%.1f&&Psi_pT>%.1f)==2&&Sum$(abs(Mu_Eta)<=1.2&&Mu_pT>3.5||abs(Mu_Eta)>1.2&&abs(Mu_Eta)<1.6&&(Mu_pT>-3.75*abs(Mu_Eta)+8)||abs(Mu_Eta)>=1.6&&abs(Mu_Eta)<=2.0&&Mu_pT>2.0)==4",rapmax,ptmin),"goff");
            sps.Draw("FourMu_Mass >> mass_sps",Form("FourMu_Mass>=0&&FourMu_Mass<=60&&FourMu_VtxProb>=0.1&&Sum$(abs(Psi_y)<=%.1f&&Psi_pT>%.1f)==2&&Sum$(abs(Mu_Eta)<=1.2&&Mu_pT>3.5||abs(Mu_Eta)>1.2&&abs(Mu_Eta)<1.6&&(Mu_pT>-3.75*abs(Mu_Eta)+8)||abs(Mu_Eta)>=1.6&&abs(Mu_Eta)<=2.0&&Mu_pT>2.0)==4",rapmax,ptmin),"goff");
        nlogg.Draw("FourMu_Mass >> mass_nlogg",Form("FourMu_Mass>=0&&FourMu_Mass<=60&&FourMu_VtxProb>=0.1&&Sum$(abs(Psi_y)<=%.1f&&Psi_pT>%.1f)==2&&Sum$(abs(Mu_Eta)<=1.2&&Mu_pT>3.5||abs(Mu_Eta)>1.2&&abs(Mu_Eta)<1.6&&(Mu_pT>-3.75*abs(Mu_Eta)+8)||abs(Mu_Eta)>=1.6&&abs(Mu_Eta)<=2.0&&Mu_pT>2.0)==4",rapmax,ptmin),"goff");
        data.Draw("FourMu_pT >> pt_data",Form("FourMu_pT<80&&abs(FourMu_Rapidity)<1.8&&FourMu_Mass<60&&Sum$(Psi_pT>%.1f&&abs(Psi_y)<=%.1f)==2",ptmin,rapmax),"goff");
                dps.Draw("FourMu_pT >> pt_dps",Form("FourMu_Mass>=0&&FourMu_Mass<=60&&FourMu_VtxProb>=0.1&&Sum$(abs(Psi_y)<=%.1f&&Psi_pT>%.1f)==2&&Sum$(abs(Mu_Eta)<=1.2&&Mu_pT>3.5||abs(Mu_Eta)>1.2&&abs(Mu_Eta)<1.6&&(Mu_pT>-3.75*abs(Mu_Eta)+8)||abs(Mu_Eta)>=1.6&&abs(Mu_Eta)<=2.0&&Mu_pT>2.0)==4",rapmax,ptmin),"goff");
                sps.Draw("FourMu_pT >> pt_sps",Form("FourMu_Mass>=0&&FourMu_Mass<=60&&FourMu_VtxProb>=0.1&&Sum$(abs(Psi_y)<=%.1f&&Psi_pT>%.1f)==2&&Sum$(abs(Mu_Eta)<=1.2&&Mu_pT>3.5||abs(Mu_Eta)>1.2&&abs(Mu_Eta)<1.6&&(Mu_pT>-3.75*abs(Mu_Eta)+8)||abs(Mu_Eta)>=1.6&&abs(Mu_Eta)<=2.0&&Mu_pT>2.0)==4",rapmax,ptmin),"goff");
            nlogg.Draw("FourMu_pT >> pt_nlogg",Form("FourMu_Mass>=0&&FourMu_Mass<=60&&FourMu_VtxProb>=0.1&&Sum$(abs(Psi_y)<=%.1f&&Psi_pT>%.1f)==2&&Sum$(abs(Mu_Eta)<=1.2&&Mu_pT>3.5||abs(Mu_Eta)>1.2&&abs(Mu_Eta)<1.6&&(Mu_pT>-3.75*abs(Mu_Eta)+8)||abs(Mu_Eta)>=1.6&&abs(Mu_Eta)<=2.0&&Mu_pT>2.0)==4",rapmax,ptmin),"goff");
        data.Draw("Psi1To2_dY >> dy_data",Form("FourMu_pT<80&&abs(FourMu_Rapidity)<1.8&&FourMu_Mass<60&&Sum$(Psi_pT>%.1f&&abs(Psi_y)<=%.1f)==2",ptmin,rapmax),"goff");
              dps.Draw("Psi1To2_dY ",Form("FourMu_Mass>=0&&FourMu_Mass<=60&&FourMu_VtxProb>=0.1&&Sum$(abs(Psi_y)<=%.1f&&Psi_pT>%.1f)==2&&Sum$(abs(Mu_Eta)<=1.2&&Mu_pT>3.5||abs(Mu_Eta)>1.2&&abs(Mu_Eta)<1.6&&(Mu_pT>-3.75*abs(Mu_Eta)+8)||abs(Mu_Eta)>=1.6&&abs(Mu_Eta)<=2.0&&Mu_pT>2.0)==4",rapmax,ptmin),"goff");
              sps.Draw("Psi1To2_dY >> dy_sps",Form("FourMu_Mass>=0&&FourMu_Mass<=60&&FourMu_VtxProb>=0.1&&Sum$(abs(Psi_y)<=%.1f&&Psi_pT>%.1f)==2&&Sum$(abs(Mu_Eta)<=1.2&&Mu_pT>3.5||abs(Mu_Eta)>1.2&&abs(Mu_Eta)<1.6&&(Mu_pT>-3.75*abs(Mu_Eta)+8)||abs(Mu_Eta)>=1.6&&abs(Mu_Eta)<=2.0&&Mu_pT>2.0)==4",rapmax,ptmin),"goff");
          nlogg.Draw("Psi1To2_dY >> dy_nlogg",Form("FourMu_Mass>=0&&FourMu_Mass<=60&&FourMu_VtxProb>=0.1&&Sum$(abs(Psi_y)<=%.1f&&Psi_pT>%.1f)==2&&Sum$(abs(Mu_Eta)<=1.2&&Mu_pT>3.5||abs(Mu_Eta)>1.2&&abs(Mu_Eta)<1.6&&(Mu_pT>-3.75*abs(Mu_Eta)+8)||abs(Mu_Eta)>=1.6&&abs(Mu_Eta)<=2.0&&Mu_pT>2.0)==4",rapmax,ptmin),"goff");
        data.Draw("abs(FourMu_Rapidity)>> y_data",Form("FourMu_pT<80&&abs(FourMu_Rapidity)<1.8&&FourMu_Mass<60&&Sum$(Psi_pT>%.1f&&abs(Psi_y)<=%.1f)==2",ptmin,rapmax),"goff");
       dps.Draw("abs(FourMu_Rapidity)",Form("FourMu_Mass>=0&&FourMu_Mass<=60&&FourMu_VtxProb>=0.1&&Sum$(abs(Psi_y)<=%.1f&&Psi_pT>%.1f)==2&&Sum$(abs(Mu_Eta)<=1.2&&Mu_pT>3.5||abs(Mu_Eta)>1.2&&abs(Mu_Eta)<1.6&&(Mu_pT>-3.75*abs(Mu_Eta)+8)||abs(Mu_Eta)>=1.6&&abs(Mu_Eta)<=2.0&&Mu_pT>2.0)==4",rapmax,ptmin),"goff");
      sps.Draw("abs(FourMu_Rapidity) >> y_sps",Form("FourMu_Mass>=0&&FourMu_Mass<=60&&FourMu_VtxProb>=0.1&&Sum$(abs(Psi_y)<=%.1f&&Psi_pT>%.1f)==2&&Sum$(abs(Mu_Eta)<=1.2&&Mu_pT>3.5||abs(Mu_Eta)>1.2&&abs(Mu_Eta)<1.6&&(Mu_pT>-3.75*abs(Mu_Eta)+8)||abs(Mu_Eta)>=1.6&&abs(Mu_Eta)<=2.0&&Mu_pT>2.0)==4",rapmax,ptmin),"goff");
  nlogg.Draw("abs(FourMu_Rapidity) >> y_nlogg",Form("FourMu_Mass>=0&&FourMu_Mass<=60&&FourMu_VtxProb>=0.1&&Sum$(abs(Psi_y)<=%.1f&&Psi_pT>%.1f)==2&&Sum$(abs(Mu_Eta)<=1.2&&Mu_pT>3.5||abs(Mu_Eta)>1.2&&abs(Mu_Eta)<1.6&&(Mu_pT>-3.75*abs(Mu_Eta)+8)||abs(Mu_Eta)>=1.6&&abs(Mu_Eta)<=2.0&&Mu_pT>2.0)==4",rapmax,ptmin),"goff");
        for(int mbin=1; mbin<=nmbins; ++mbin){
          if (mass_data->GetBinContent(mbin) == 0){
            //mbinerr = 1.;
            continue;
          }
          else{mbinerr = sqrt(abs(mass_data->GetBinContent(mbin)));}
   //       Chi2=Chi2 + pow((mass_data->GetBinContent(mbin) - (a*scaledps*mass_dps->GetBinContent(mbin) + b*scalesps*mass_sps->GetBinContent(mbin) + c*scalenlo*mass_nlogg->GetBinContent(mbin))),2)/mbinerr;
//          Chi2=Chi2 + pow((mass_data->GetBinContent(mbin) - (a*scaledps*mass_dps->GetBinContent(mbin) + b*scalesps*mass_sps->GetBinContent(mbin) + c*scalenlo*mass_nlogg->GetBinContent(mbin)))/sqrt(abs(mass_data->GetBinContent(mbin))),2);
          //           std::cout<<Chi2<<std::endl;
        }
        for(int ptbin=1; ptbin<=nptbins; ++ptbin){
          if (pt_data->GetBinContent(ptbin) == 0){
            ptbinerr = 1.;
          }
          else{ptbinerr = sqrt(abs(pt_data->GetBinContent(ptbin)));}
          Chi2=Chi2 + pow((pt_data->GetBinContent(ptbin) - (a*scaledps*pt_dps->GetBinContent(ptbin) + b*scalesps*pt_sps->GetBinContent(ptbin) + c*scalenlo*pt_nlogg->GetBinContent(ptbin)))/ptbinerr,2);
            //         std::cout<<pt_data->GetBinContent(ptbin)<<std::endl;
        }
        for(int dybin=1; dybin<=ndybins; ++dybin){
          if (dy_data->GetBinContent(dybin) == 0){
            dybinerr = 1.;
          }
          else{dybinerr = sqrt(abs(dy_data->GetBinContent(dybin)));}
          float avgval = (dpsget(dybins[dybin])+dpsget(dybins[dybin-1]))/2.;
          dy_dps->SetBinContent(dybin,avgval);
          if(avgval>=0){
          DpsBestdy->SetBinContent(dybin,avgval);
          }
          Chi2=Chi2 + pow((dy_data->GetBinContent(dybin) - (a*scaledps1*dy_dps->GetBinContent(dybin) + b*scalesps*dy_sps->GetBinContent(dybin) + c*scalenlo*dy_nlogg->GetBinContent(dybin)))/dybinerr,2);
          //           std::cout<<Chi2<<std::endl;
        }
        for(int ybin=1; ybin<=nybins; ++ybin){
          if (y_data->GetBinContent(ybin) == 0){
            ybinerr = 1.;
          }
          else{ybinerr = sqrt(abs(y_data->GetBinContent(ybin)));}
          float avgval = (dpsgety(ybins[ybin])+dpsgety(ybins[ybin-1]))/2.;
          y_dps->SetBinContent(ybin,avgval);
          if(avgval>=0){
          DpsBesty->SetBinContent(ybin,avgval);
          }
          Chi2=Chi2 + pow((y_data->GetBinContent(ybin) - (a*scaledps2*y_dps->GetBinContent(ybin) + b*scalesps*y_sps->GetBinContent(ybin) + c*scalenlo*y_nlogg->GetBinContent(ybin)))/ybinerr,2);
          //           std::cout<<Chi2<<std::endl;
        }
//                std::cout<<"a, b, c: "<<a<<" "<<b<<" "<<c<<" Chi2: "<<Chi2<<std::endl;
        if (Chi2<=minchi2norm){
          if ( abs(1. - abs(a+b+c))<0.001){
            minchi2norm=Chi2; minan = a; minbn = b; mincn = c;
            std::cout<<a<<" "<<b<<" "<<c<<" "<<Chi2<<std::endl;
          }
        }
        if (Chi2<=minchi2){
          minchi2=Chi2; mina = a; minb = b; minc = c;
        }
        //        std::cout<<a<<" "<<b<<" "<<c<<" "<<Chi2<<std::endl;
        Chi2=0;
        }
      }
    }
    std::cout<<"Min Chi2: "<<minchi2<<" dps, sps, nlo: "<<mina<<" "<<minb<<" "<<minc<<std::endl;
    std::cout<<"Min normed Chi2: "<<minchi2norm<<" dps, sps, nlo: "<<minan<<" "<<minbn<<" "<<mincn<<std::endl;
    TCanvas* disp = new TCanvas("disp","disp",900,900);
    disp->Divide(2,2);
    TH1F *MassSum = new TH1F("MassSum","MassSum",nmbins,massbins);
    TH1F *MassBest = new TH1F("MassBest","MassBest",nmbins,massbins);
    TH1F *DpsBestM = new TH1F("DpsBestM","DpsBestM",nmbins,massbins);
    TH1F *SpsBestM = new TH1F("SpsBestM","SpsBestM",nmbins,massbins);
    TH1F *NloBestM = new TH1F("NloBestM","NloBestM",nmbins,massbins);
    TH1F *pTBest = new TH1F("pTBest","pTBest",nptbins,ptbins);
    TH1F *pTSum = new TH1F("pTSum","pTSum",nptbins,ptbins);
    TH1F *DpsBestpt = new TH1F("DpsBestpt","DpsBestpt",nptbins,ptbins);
    TH1F *SpsBestpt = new TH1F("SpsBestpt","SpsBestpt",nptbins,ptbins);
    TH1F *NloBestpt = new TH1F("NloBestpt","NloBestpt",nptbins,ptbins);
    TH1F *dyBest = new TH1F("dyBest","dyBest",ndybins,dybins);
    TH1F *dySum = new TH1F("dySum","dySum",ndybins,dybins);
    TH1F *SpsBestdy = new TH1F("SpsBestdy","SpsBestdy",ndybins,dybins);
    TH1F *NloBestdy = new TH1F("NloBestdy","NloBestdy",ndybins,dybins);
    TH1F *yBest = new TH1F("yBest","yBest",nybins,ybins);
    TH1F *ySum = new TH1F("ySum","ySum",nybins,ybins);
    TH1F *SpsBesty = new TH1F("SpsBesty","SpsBesty",nybins,ybins);
    TH1F *NloBesty = new TH1F("NloBesty","NloBesty",nybins,ybins);
    MassBest->SetMinimum(0);pTBest->SetMinimum(0);dyBest->SetMinimum(0);yBest->SetMinimum(0);
    dps.Draw("FourMu_Mass>>DpsBestM",Form("(FourMu_Mass>=0&&FourMu_Mass<=60&&FourMu_VtxProb>=0.1&&Sum$(abs(Psi_y)<=%.1f&&Psi_pT>%.1f)==2&&Sum$(abs(Mu_Eta)<=1.2&&Mu_pT>3.5||abs(Mu_Eta)>1.2&&abs(Mu_Eta)<1.6&&(Mu_pT>-3.75*abs(Mu_Eta)+8)||abs(Mu_Eta)>=1.6&&abs(Mu_Eta)<=2.0&&Mu_pT>2.0)==4)",rapmax,ptmin),"goff");
    sps.Draw("FourMu_Mass>>SpsBestM",Form("(FourMu_Mass>=0&&FourMu_Mass<=60&&FourMu_VtxProb>=0.1&&Sum$(abs(Psi_y)<=%.1f&&Psi_pT>%.1f)==2&&Sum$(abs(Mu_Eta)<=1.2&&Mu_pT>3.5||abs(Mu_Eta)>1.2&&abs(Mu_Eta)<1.6&&(Mu_pT>-3.75*abs(Mu_Eta)+8)||abs(Mu_Eta)>=1.6&&abs(Mu_Eta)<=2.0&&Mu_pT>2.0)==4)",rapmax,ptmin),"goff");
  nlogg.Draw("FourMu_Mass>>NloBestM",Form("(FourMu_Mass>=0&&FourMu_Mass<=60&&FourMu_VtxProb>=0.1&&Sum$(abs(Psi_y)<=%.1f&&Psi_pT>%.1f)==2&&Sum$(abs(Mu_Eta)<=1.2&&Mu_pT>3.5||abs(Mu_Eta)>1.2&&abs(Mu_Eta)<1.6&&(Mu_pT>-3.75*abs(Mu_Eta)+8)||abs(Mu_Eta)>=1.6&&abs(Mu_Eta)<=2.0&&Mu_pT>2.0)==4)",rapmax,ptmin),"goff");
     dps.Draw("FourMu_pT>>DpsBestpt",Form("(FourMu_Mass>=0&&FourMu_Mass<=60&&FourMu_VtxProb>=0.1&&Sum$(abs(Psi_y)<=%.1f&&Psi_pT>%.1f)==2&&Sum$(abs(Mu_Eta)<=1.2&&Mu_pT>3.5||abs(Mu_Eta)>1.2&&abs(Mu_Eta)<1.6&&(Mu_pT>-3.75*abs(Mu_Eta)+8)||abs(Mu_Eta)>=1.6&&abs(Mu_Eta)<=2.0&&Mu_pT>2.0)==4)",rapmax,ptmin),"goff");
     sps.Draw("FourMu_pT>>SpsBestpt",Form("(FourMu_Mass>=0&&FourMu_Mass<=60&&FourMu_VtxProb>=0.1&&Sum$(abs(Psi_y)<=%.1f&&Psi_pT>%.1f)==2&&Sum$(abs(Mu_Eta)<=1.2&&Mu_pT>3.5||abs(Mu_Eta)>1.2&&abs(Mu_Eta)<1.6&&(Mu_pT>-3.75*abs(Mu_Eta)+8)||abs(Mu_Eta)>=1.6&&abs(Mu_Eta)<=2.0&&Mu_pT>2.0)==4)",rapmax,ptmin),"goff");
   nlogg.Draw("FourMu_pT>>NloBestpt",Form("(FourMu_Mass>=0&&FourMu_Mass<=60&&FourMu_VtxProb>=0.1&&Sum$(abs(Psi_y)<=%.1f&&Psi_pT>%.1f)==2&&Sum$(abs(Mu_Eta)<=1.2&&Mu_pT>3.5||abs(Mu_Eta)>1.2&&abs(Mu_Eta)<1.6&&(Mu_pT>-3.75*abs(Mu_Eta)+8)||abs(Mu_Eta)>=1.6&&abs(Mu_Eta)<=2.0&&Mu_pT>2.0)==4)",rapmax,ptmin),"goff");
//    dps.Draw("Psi1To2_dY>>DpsBestdy",Form("(FourMu_Mass>=0&&FourMu_Mass<=60&&FourMu_VtxProb>=0.1&&Sum$(abs(Psi_y)<=%.1f&&Psi_pT>%.1f)==2&&Sum$(abs(Mu_Eta)<=1.2&&Mu_pT>3.5||abs(Mu_Eta)>1.2&&abs(Mu_Eta)<1.6&&(Mu_pT>-3.75*abs(Mu_Eta)+8)||abs(Mu_Eta)>=1.6&&abs(Mu_Eta)<=2.0&&Mu_pT>2.0)==4)",rapmax,ptmin),"goff");
    sps.Draw("Psi1To2_dY>>SpsBestdy",Form("(FourMu_Mass>=0&&FourMu_Mass<=60&&FourMu_VtxProb>=0.1&&Sum$(abs(Psi_y)<=%.1f&&Psi_pT>%.1f)==2&&Sum$(abs(Mu_Eta)<=1.2&&Mu_pT>3.5||abs(Mu_Eta)>1.2&&abs(Mu_Eta)<1.6&&(Mu_pT>-3.75*abs(Mu_Eta)+8)||abs(Mu_Eta)>=1.6&&abs(Mu_Eta)<=2.0&&Mu_pT>2.0)==4)",rapmax,ptmin),"goff");
  nlogg.Draw("Psi1To2_dY>>NloBestdy",Form("(FourMu_Mass>=0&&FourMu_Mass<=60&&FourMu_VtxProb>=0.1&&Sum$(abs(Psi_y)<=%.1f&&Psi_pT>%.1f)==2&&Sum$(abs(Mu_Eta)<=1.2&&Mu_pT>3.5||abs(Mu_Eta)>1.2&&abs(Mu_Eta)<1.6&&(Mu_pT>-3.75*abs(Mu_Eta)+8)||abs(Mu_Eta)>=1.6&&abs(Mu_Eta)<=2.0&&Mu_pT>2.0)==4)",rapmax,ptmin),"goff");
//    dps.Draw("abs(FourMu_Rapidity)>>DpsBesty",Form("(FourMu_Mass>=0&&FourMu_Mass<=60&&FourMu_VtxProb>=0.1&&Sum$(abs(Psi_y)<=%.1f&&Psi_pT>%.1f)==2&&Sum$(abs(Mu_Eta)<=1.2&&Mu_pT>3.5||abs(Mu_Eta)>1.2&&abs(Mu_Eta)<1.6&&(Mu_pT>-3.75*abs(Mu_Eta)+8)||abs(Mu_Eta)>=1.6&&abs(Mu_Eta)<=2.0&&Mu_pT>2.0)==4)",rapmax,ptmin),"goff");
    sps.Draw("abs(FourMu_Rapidity)>>SpsBesty",Form("(FourMu_Mass>=0&&FourMu_Mass<=60&&FourMu_VtxProb>=0.1&&Sum$(abs(Psi_y)<=%.1f&&Psi_pT>%.1f)==2&&Sum$(abs(Mu_Eta)<=1.2&&Mu_pT>3.5||abs(Mu_Eta)>1.2&&abs(Mu_Eta)<1.6&&(Mu_pT>-3.75*abs(Mu_Eta)+8)||abs(Mu_Eta)>=1.6&&abs(Mu_Eta)<=2.0&&Mu_pT>2.0)==4)",rapmax,ptmin),"goff");
  nlogg.Draw("abs(FourMu_Rapidity)>>NloBesty",Form("(FourMu_Mass>=0&&FourMu_Mass<=60&&FourMu_VtxProb>=0.1&&Sum$(abs(Psi_y)<=%.1f&&Psi_pT>%.1f)==2&&Sum$(abs(Mu_Eta)<=1.2&&Mu_pT>3.5||abs(Mu_Eta)>1.2&&abs(Mu_Eta)<1.6&&(Mu_pT>-3.75*abs(Mu_Eta)+8)||abs(Mu_Eta)>=1.6&&abs(Mu_Eta)<=2.0&&Mu_pT>2.0)==4)",rapmax,ptmin),"goff");
    //MassSum->Add(DpsBest,(float) mina);
    //MassSum->Add(SpsBest,minb);
    //MassSum->Add(NloBest,minc);
    MassBest->SetMinimum(0);
    disp->cd(1);
    DpsBestM->SetLineColor(kRed);
    SpsBestM->SetLineColor(kBlue);
    NloBestM->SetLineColor(kGreen);
    DpsBestM->Scale(minan*scaledps);
    SpsBestM->Scale(minbn*scalesps);
    NloBestM->Scale(mincn*scalenlo);
    MassSum->Add(DpsBestM);
    MassSum->Add(SpsBestM);
    MassSum->Add(NloBestM);
    data.Draw("FourMu_Mass >> MassBest",Form("FourMu_pT<80&&abs(FourMu_Rapidity)<1.8&&FourMu_Mass<60&&Sum$(Psi_pT>%.1f&&abs(Psi_y)<=%.1f)==2",ptmin,rapmax),"e");
    MassSum->Draw("same");
    DpsBestM->Draw("same");
    SpsBestM->Draw("same");
    NloBestM->Draw("same");
    disp->cd(2);
    DpsBestpt->SetLineColor(kRed);
    SpsBestpt->SetLineColor(kBlue);
    NloBestpt->SetLineColor(kGreen);
    DpsBestpt->Scale(minan*scaledps);
    SpsBestpt->Scale(minbn*scalesps);
    NloBestpt->Scale(mincn*scalenlo);
    pTSum->Add(DpsBestpt);
    pTSum->Add(SpsBestpt);
    pTSum->Add(NloBestpt);
    data.Draw("FourMu_pT >> pTBest",Form("FourMu_pT<80&&abs(FourMu_Rapidity)<1.8&&FourMu_Mass<60&&Sum$(Psi_pT>%.1f&&abs(Psi_y)<=%.1f)==2",ptmin,rapmax),"e");
    pTSum->Draw("same");
    DpsBestpt->Draw("same");
    SpsBestpt->Draw("same");
    NloBestpt->Draw("same");
    disp->cd(3);
    DpsBestdy->SetLineColor(kRed);
    SpsBestdy->SetLineColor(kBlue);
    NloBestdy->SetLineColor(kGreen);
    DpsBestdy->Scale(minan*scaledps1);
    SpsBestdy->Scale(minbn*scalesps);
    NloBestdy->Scale(mincn*scalenlo);
    dySum->Add(DpsBestdy);
    dySum->Add(SpsBestdy);
    dySum->Add(NloBestdy);
    data.Draw("Psi1To2_dY >> dyBest",Form("FourMu_pT<80&&abs(FourMu_Rapidity)<1.8&&FourMu_Mass<60&&Sum$(Psi_pT>%0.1f&&abs(Psi_y)<=%0.1f)==2",ptmin,rapmax),"e");
    dySum->Draw("same");
    DpsBestdy->Draw("same");
    SpsBestdy->Draw("same");
    NloBestdy->Draw("same");
    disp->cd(4);
    DpsBesty->SetLineColor(kRed);
    SpsBesty->SetLineColor(kBlue);
    NloBesty->SetLineColor(kGreen);
    DpsBesty->Scale(minan*scaledps2);
    SpsBesty->Scale(minbn*scalesps);
    NloBesty->Scale(mincn*scalenlo);
    ySum->Add(DpsBesty);
    ySum->Add(SpsBesty);
    ySum->Add(NloBesty);
    data.Draw("abs(FourMu_Rapidity)>> yBest",Form("FourMu_pT<80&&abs(FourMu_Rapidity)<1.8&&FourMu_Mass<60&&Sum$(Psi_pT>%0.1f&&abs(Psi_y)<=%.1f)==2",ptmin,rapmax),"e");
    ySum->Draw("same");
    DpsBesty->Draw("same");
    SpsBesty->Draw("same");
    NloBesty->Draw("same");
  }
Example #4
0
void ROCoverlays() {
  TFile *SoftLepton = TFile::Open("FullVariables/histos/AllHistograms.root"); 
  TFile *NoSLInfo = TFile::Open("../../NewVariables/DUSG/LDefault2/histos/AllHistograms.root");

  // loop over pT ranges
  for (Int_t i=7; i<8; i++){
    // Discriminators with SL information
    TH1F *SLC = (TH1F*)SoftLepton->Get(Form("histBDTG_C_Pt%i",i));
    TH1F *SLL = (TH1F*)SoftLepton->Get(Form("histBDTG_light_Pt%i",i));
    
    // Discriminators without SL information
    TH1F *DefC = (TH1F*)NoSLInfo->Get(Form("histBDTG_C_Pt%i",i));
    TH1F *DefL = (TH1F*)NoSLInfo->Get(Form("histBDTG_light_Pt%i",i));
    
    //ROC CvDUSG
    TGraph *SLCvL = (TGraph*)SoftLepton->Get(Form("ROC_C_light_%i",i));
    TGraph *noSLCvL = (TGraph*)NoSLInfo->Get(Form("ROC_C_light_%i",i));
  
    // Normalize Discriminators
    SLC->Scale(1./SLC->Integral());
    SLL->Scale(1./SLL->Integral());
    DefC->Scale(1./DefC->Integral());
    DefL->Scale(1./DefL->Integral());
    
    //Set colors
    noSLCvL->SetLineColor(kBlack);
    SLCvL->SetLineColor(kRed);

    noSLCvL->SetLineWidth(2); 
    SLCvL->SetLineWidth(2);     
    DefC->SetLineWidth(2);
    DefL->SetLineWidth(2);
    SLL->SetLineWidth(2); 
    SLC->SetLineWidth(2);
    
    TCanvas *cv = 0;
    TLegend *l = 0;
    TLatex *tex = 0;

    // Default Discriminators
    DefC->SetLineColor(kBlack);
    DefL->SetLineColor(kRed)

    cv = new TCanvas("cv","cv",800,800);
    cv->SetGridx();
    cv->SetGridy();
    DefL->SetTitle("No Soft Lepton Information");
    DefL->GetYaxis()->SetRangeUser(0,0.03);
    DefL->GetYaxis()->SetTitleOffset(1.6);
    DefL->GetYaxis()->SetTitle("Normalized Events");  
    DefL->GetXaxis()->SetTitle("BDT Output");
    DefL->Draw();
    DefC->Draw("same");
    gStyle->SetOptStat(0);

    l = new TLegend(0.55,0.8,0.90,0.9);
    l->SetBorderSize(0);
    l->SetFillStyle(0);
    l->AddEntry(DefC,"C Discriminator","l");
    l->AddEntry(DefL,"DUSG Discriminator","l");
    l->Draw();
    cv->Update();
    cv->SaveAs(Form("Default_Discriminators_%i.png",i));
    DefL->SetLineColor(kBlack);   

    // Soft Lepton Discriminators
    SLC->SetLineColor(kBlack);
    SLL->SetLineColor(kRed);

    cv = new TCanvas("cv","Reco",800,800);
    cv->SetGridx();
    cv->SetGridy();
    SLC->SetLineColor(kBlack);
    SLL->SetTitle("Soft Lepton Information");
    SLL->GetYaxis()->SetRangeUser(0,0.03);
    SLL->GetYaxis()->SetTitleOffset(1.6);
    SLL->GetYaxis()->SetTitle("Normalized Events");
    SLL->GetXaxis()->SetTitle("BDT Output");
    SLL->Draw();
    SLC->Draw("same");
    gStyle->SetOptStat(0);

    l = new TLegend(0.55,0.8,0.90,0.9);
    l->SetBorderSize(0);
    l->SetFillStyle(0);
    l->AddEntry(SLC,"C Discriminator","l");
    l->AddEntry(SLL,"DUSG Discriminator","l");
    l->Draw();
    cv->Update();
    cv->SaveAs(Form("SL_Discriminators_%i.png",i));
    SLC->SetLineColor(kBlue);


    // C Discriminators
    cv = new TCanvas("cv","C",800,800);
    cv->SetGridx();
    cv->SetGridy();
    SLC->Draw();
    SLC->SetTitle("Charm Discriminators");
    SLC->GetYaxis()->SetRangeUser(0,0.03);
    SLC->GetYaxis()->SetTitleOffset(1.6);
    SLC->GetYaxis()->SetTitle("Normalized Events");
    SLC->GetXaxis()->SetTitle("BDT Output");
    DefC->Draw("same");
    gStyle->SetOptStat(0);

    l = new TLegend(0.55,0.75,0.90,0.9);
    l->SetBorderSize(0);
    l->SetFillStyle(0);
    l->AddEntry(DefC,"No Soft Lepton Info","l");
    l->AddEntry(SLC,"With Soft Lepton Info","l");
    l->Draw();
    cv->Update();
    cv->SaveAs(Form("C_Discriminators_%i.png",i));
    
    // B Discriminators
    cv = new TCanvas("cv","B",800,800);
    cv->SetGridx();
    cv->SetGridy();
    SLL->SetTitle("DUSG  Discriminators");
    SLL->GetYaxis()->SetRangeUser(0,0.03);
    SLL->GetYaxis()->SetTitleOffset(1.6);
    SLL->GetYaxis()->SetTitle("Normalized Events");
    SLL->GetXaxis()->SetTitle("BDT Output");
    SLL->Draw();
    DefL->Draw("same");
    gStyle->SetOptStat(0);

    l = new TLegend(0.55,0.75,0.90,0.9);
    l->SetBorderSize(0);
    l->SetFillStyle(0);
    l->AddEntry(DefL,"No Soft Lepton Info","l");
    l->AddEntry(SLL,"With Soft Lepton Info","l");
    l->Draw();
    cv->Update();
    cv->SaveAs(Form("L_Discriminators_%i.png",i));
    
    // CvDUSG
    cv = new TCanvas("cv","",800,800);
    cv->SetLogy();
    cv->SetGrid(1,1);
    noSLCvL->SetTitle("CvDUSG, Inclusive");
    noSLCvL->Draw();
    SLCvL->Draw("same");
    
    l = new TLegend(0.55,0.2,0.9,0.35);
    l->SetBorderSize(0);
    l->SetFillStyle(0);
    l->AddEntry(SLCvL,"SL Variables","l");
    l->AddEntry(noSLCvL,"No SL Variables","l");
    l->Draw();
    cv->SaveAs(Form("CvDUSG_SL_%i.png",i));

  }
}
Example #5
0
int compare(){
	
    gROOT->SetStyle("Plain");

    // For the canvas:
    gStyle->SetCanvasColor(0);

    // For the Pad:
    gStyle->SetPadColor(0);
    gStyle->SetPadTickX(1);
    gStyle->SetPadTickY(1);
    gStyle->SetPadBorderSize(2);

    // For the frame:
    gStyle->SetFrameBorderMode(0);


    // For the statistics box:
    gStyle->SetOptStat(0);

    // Margins:
    gStyle->SetPadBottomMargin(0.25);
    gStyle->SetPadTopMargin(0.15);
    gStyle->SetPadLeftMargin(0.15);
    gStyle->SetPadRightMargin(0.1);

    // For the Global title:
    gStyle->SetOptTitle(0);
    gStyle->SetTitleColor(1);
    gStyle->SetTitleFillColor(10);
    gStyle->SetTitleTextColor(1);
    gStyle->SetTitleFont(42);
    gStyle->SetTitleFontSize(0.05);
    gStyle->SetTitleBorderSize(0);

    // For the axis
    gStyle->SetNdivisions(510, "X");
    gStyle->SetNdivisions(510, "Y");
    gStyle->SetTickLength(0.03);

    // For the axis titles:
    gStyle->SetTitleOffset(1.4, "X");
    gStyle->SetTitleOffset(1.2, "Y");
    gStyle->SetTitleOffset(0.5, "Z");
    gStyle->SetTitleSize(0.061, "XYZ");
    gStyle->SetTitleFont(42, "XYZ");

    // For the axis labels:
    gStyle->SetLabelSize(0.04, "XYZ");
    gStyle->SetLabelOffset(0.01, "XYZ");
    gStyle->SetLabelFont(42, "XYZ");

    // For the legend
    gStyle->SetLegendBorderSize(0);

    gROOT->ForceStyle();

    ////////////////////////////////////////

	TFile *f1 = new TFile("output_GetPrediction/prediction_histos_MyTest_data_METsoftSmeared_noAngSmear_N20_CR_v3.root", "READ", "", 0);
    TFile *f2 = new TFile("output_GetPrediction/bkg.root", "READ", "", 0);
	selection = (TH1F*) f1->FindObjectAny("VBF_MET_presel_4JV_dPhiSide_selection");
	prediction = (TH1F*) f1->FindObjectAny("VBF_MET_presel_4JV_dPhiSide_prediction_px");
	background2 = (TH1F*) f2->FindObjectAny("met_check_inVR_rebin");
	TH1F* background = new TH1F(*prediction);
	background->Reset();
	for (int i = 1; i <= background->GetXaxis()->GetNbins(); ++i) {
		float x = background->GetXaxis()->GetBinCenter(i);
		int j = background2->GetXaxis()->FindBin(x);
		float value = background2->GetBinContent(j);
		float error = background2->GetBinError(j);
		background->SetBinContent(i,value);
		background->SetBinError(i,error);
	}
	
	//double MinX = selection->GetXaxis()->GetBinLowEdge(1);
    //double MaxX = selection->GetXaxis()->GetBinUpEdge(selection->GetXaxis()->GetNbins());
	double MinX = 150;
    double MaxX = 500;
    double BinWidth = selection->GetXaxis()->GetBinWidth(selection->GetXaxis()->GetNbins());
    double MaxY = prediction->GetBinContent(prediction->GetMaximumBin());
    double MaxYsel = selection->GetBinContent(selection->GetMaximumBin());
    if (MaxY < MaxYsel) MaxY = MaxYsel;
    double YRangeMax = 2.*pow(10., int(log10(MaxY))+2);
    double MinY = prediction->GetBinContent(prediction->GetMinimumBin());
    double MinYsel = selection->GetBinContent(selection->GetMinimumBin());
    if (MinY > MinYsel) MinY = MinYsel;
    if (MinY < 0.001) MinY = 0.001;
    double YRangeMin = 0.5*pow(10., int(log10(MinY))-2);
    TString titlePrediction;
    TString titleSelection;
    TString titleBackground;
    TString RatioTitle;
    TString LumiTitle;
    TString Title;
    TString xTitle;
    TString yTitle;

	LumiTitle = "ATLAS internal, L = 36.1 fb^{  -1}, #sqrt{s} = 13 TeV";

    Title = "3 jets, 1.8<#Delta#phi(jj)<2.7, MET>150 GeV, M(jj)>0.6 TeV, p_{T}^{3rd}<50 GeV";
    xTitle = "#slash{E}_{T} (GeV)";
    yTitle = "Events";

    titlePrediction = "Data-driven Pred.";
    titleSelection = "Data";
    titleBackground = "non-QCD background";

    RatioTitle = "(Pred-Data)/Data";

    static Int_t c_LightBrown = TColor::GetColor( "#D9D9CC" );
    static Int_t c_LightGray  = TColor::GetColor( "#DDDDDD" );

    selection->SetAxisRange(MinX, MaxX, "X");
    selection->GetYaxis()->SetRangeUser(YRangeMin, YRangeMax);
    selection->SetMarkerStyle(20);
    selection->SetMarkerSize(0.9);
    selection->SetMarkerColor(kBlack);
    selection->SetXTitle(xTitle);
    selection->SetYTitle(yTitle);

    prediction->SetAxisRange(MinX, MaxX, "X");
    prediction->GetYaxis()->SetRangeUser(YRangeMin, YRangeMax);
    prediction->SetFillColor(c_LightGray);
    prediction->SetTitle("");
    prediction->SetXTitle(xTitle);
    prediction->SetYTitle(yTitle);

    background->SetAxisRange(MinX, MaxX, "X");
    background->GetYaxis()->SetRangeUser(YRangeMin, YRangeMax);
    background->SetTitle("");
    background->SetLineColor(kRed);
    background->SetLineWidth(2);
    background->SetXTitle(xTitle);
    background->SetYTitle(yTitle);

    TCanvas *c = new TCanvas("ca", "Comparison and ratio of two histos", 700, 700);

    TPad *pad1 = new TPad("pad1a", "pad1a", 0, 0.35, 1, 1);
    pad1->SetLogy();
    pad1->SetBottomMargin(0);
    pad1->Draw();
    pad1->cd();

    prediction->DrawCopy("hist");
    selection->Draw("same");
    prediction->SetFillColor(kAzure-3);
    prediction->SetFillStyle(3354);
    prediction->DrawCopy("e2same");
    background->Scale(36.1/32.6);
    background->Draw("same");

    prediction->SetFillStyle(1001);
    //prediction->SetFillColor(c_LightBrown);
    prediction->SetFillColor(c_LightGray);

    //TLegend* leg1 = new TLegend(0.48, 0.63, 0.95, 0.83);
    TLegend* leg1 = new TLegend(0.44, 0.63, 0.91, 0.83);
    leg1->SetFillStyle(0);
    leg1->SetLineStyle(1);
    leg1->SetTextFont(42);
    //leg1->SetTextSize(0.04);
    leg1->SetTextSize(0.045);
    leg1->AddEntry(prediction, titlePrediction, "lf");
    leg1->AddEntry(selection, titleSelection, "lep");
    leg1->AddEntry(background, titleBackground, "l");
    leg1->Draw("same");

    TPaveText* pt = new TPaveText(0.11, 0.98, 0.95, 0.86, "NDC");
    pt->SetBorderSize(0);
    pt->SetFillStyle(0);
    pt->SetTextAlign(12);
    pt->SetTextSize(0.045);
    pt->AddText(Title);
    pt->AddText(LumiTitle);
    pt->Draw();

    c->cd();
    TPad *pad2 = new TPad("pad2a", "pad2a", 0, 0, 1, 0.35);
    pad2->SetTopMargin(0);
    pad2->Draw();
    pad2->cd();
    TH1F* r = new TH1F(*prediction);
    r->SetTitle("");
    r->SetLabelSize(0.08, "XYZ");
    r->SetLabelOffset(0.01, "XYZ");
    // r->SetTitleSize(0.09, "XYZ");
    r->SetTitleSize(0.125, "XYZ");
    r->SetTitleOffset(0.95, "X");
    r->SetTitleOffset(0.53, "Y");
    // r->SetTitleOffset(0.65, "Y");
    r->SetTickLength(0.05);
    r->SetYTitle(RatioTitle);
    r->SetStats(0);
    r->SetMarkerStyle(20);
    r->SetMarkerSize(0.9);
    r->SetMarkerColor(kBlack);
    r->Reset();
    r->Add(prediction, 1);
    r->Add(background, 1);
    r->Add(selection, -1);
    r->Divide(selection);
    r->SetMaximum(2.2);
    r->SetMinimum(-2.2);
    r->Draw("ep");
    TLine l;
    l.DrawLine(MinX, 0., MaxX+BinWidth, 0.);
    c->cd();
    
    c->SaveAs("compare.pdf");
	
	return 0;
}
Example #6
0
File: pythia8.C Project: Y--/root
void pythia8(Int_t nev  = 100, Int_t ndeb = 1)
{
   const char *p8dataenv = gSystem->Getenv("PYTHIA8DATA");
   if (!p8dataenv) {
      const char *p8env = gSystem->Getenv("PYTHIA8");
      if (!p8env) {
         Error("pythia8.C",
               "Environment variable PYTHIA8 must contain path to pythia directory!");
         return;
      }
      TString p8d = p8env;
      p8d += "/xmldoc";
      gSystem->Setenv("PYTHIA8DATA", p8d);
   }

   const char* path = gSystem->ExpandPathName("$PYTHIA8DATA");
   if (gSystem->AccessPathName(path)) {
         Error("pythia8.C",
               "Environment variable PYTHIA8DATA must contain path to $PYTHIA8/xmldoc directory !");
      return;
   }

// Load libraries
#ifndef G__WIN32 // Pythia8 is a static library on Windows
   if (gSystem->Getenv("PYTHIA8")) {
      gSystem->Load("$PYTHIA8/lib/libpythia8");
   } else {
      gSystem->Load("libpythia8");
   }
#endif
   gSystem->Load("libEG");
   gSystem->Load("libEGPythia8");
// Histograms
   TH1F* etaH = new TH1F("etaH", "Pseudorapidity", 120, -12., 12.);
   TH1F* ptH  = new TH1F("ptH",  "pt",              50,   0., 10.);


// Array of particles
   TClonesArray* particles = new TClonesArray("TParticle", 1000);
// Create pythia8 object
   TPythia8* pythia8 = new TPythia8();

// Configure
   pythia8->ReadString("HardQCD:all = on");


// Initialize

   pythia8->Initialize(2212 /* p */, 2212 /* p */, 14000. /* TeV */);

// Event loop
   for (Int_t iev = 0; iev < nev; iev++) {
      pythia8->GenerateEvent();
      if (iev < ndeb) pythia8->EventListing();
      pythia8->ImportParticles(particles,"All");
      Int_t np = particles->GetEntriesFast();
// Particle loop
      for (Int_t ip = 0; ip < np; ip++) {
         TParticle* part = (TParticle*) particles->At(ip);
         Int_t ist = part->GetStatusCode();
         // Positive codes are final particles.
         if (ist <= 0) continue;
         Int_t pdg = part->GetPdgCode();
         Float_t charge = TDatabasePDG::Instance()->GetParticle(pdg)->Charge();
         if (charge == 0.) continue;
         Float_t eta = part->Eta();
         Float_t pt  = part->Pt();

         etaH->Fill(eta);
         if (pt > 0.) ptH->Fill(pt, 1./(2. * pt));
      }
   }

   pythia8->PrintStatistics();

   TCanvas* c1 = new TCanvas("c1","Pythia8 test example",800,800);
   c1->Divide(1, 2);
   c1->cd(1);
   etaH->Scale(5./Float_t(nev));
   etaH->Draw();
   etaH->SetXTitle("#eta");
   etaH->SetYTitle("dN/d#eta");

   c1->cd(2);
   gPad->SetLogy();
   ptH->Scale(5./Float_t(nev));
   ptH->Draw();
   ptH->SetXTitle("p_{t} [GeV/c]");
   ptH->SetYTitle("dN/dp_{t}^{2} [GeV/c]^{-2}");
 }
int main(int argc, char * argv[]) {

  // first argument - config file 
  // second argument - filelist

  using namespace std;

  // **** configuration
  Config cfg(argv[1]);

  const bool isData = cfg.get<bool>("IsData");
  const bool applyLeptonSF = cfg.get<bool>("ApplyLeptonSF");

  const bool applyGoodRunSelection = cfg.get<bool>("ApplyGoodRunSelection");

  // pile up reweighting
  const bool applyPUreweighting_vertices = cfg.get<bool>("ApplyPUreweighting_vertices");
  const bool applyPUreweighting_official = cfg.get<bool>("ApplyPUreweighting_official");


  // kinematic cuts on muons
  const float ptMuonLowCut   = cfg.get<float>("ptMuonLowCut");
  const float ptMuonHighCut  = cfg.get<float>("ptMuonHighCut");
  const float etaMuonHighCut = cfg.get<float>("etaMuonHighCut");
  const float etaMuonLowCut = cfg.get<float>("etaMuonLowCut");
  const float dxyMuonCut     = cfg.get<float>("dxyMuonCut");
  const float dzMuonCut      = cfg.get<float>("dzMuonCut");
  const float isoMuonCut     = cfg.get<float>("isoMuonCut");
  const bool  applyTauTauSelection = cfg.get<bool>("ApplyTauTauSelection");
  const bool  selectZToTauTauMuMu = cfg.get<bool>("SelectZToTauTauMuMu");

  // topological cuts
  const float dRleptonsCut   = cfg.get<float>("dRleptonsCut");
  const float DRTrigMatch    = cfg.get<float>("DRTrigMatch"); 
  const bool oppositeSign    = cfg.get<bool>("OppositeSign");


  // vertex cuts
  const float ndofVertexCut  = cfg.get<float>("NdofVertexCut");   
  const float zVertexCut     = cfg.get<float>("ZVertexCut");
  const float dVertexCut     = cfg.get<float>("DVertexCut");

  // jet related cuts
  const float jetEtaCut      = cfg.get<float>("JetEtaCut");
  const float jetEtaTrkCut   = cfg.get<float>("JetEtaTrkCut");
  const float jetPtHighCut   = cfg.get<float>("JetPtHighCut");
  const float jetPtLowCut    = cfg.get<float>("JetPtLowCut");
  const float dRJetLeptonCut = cfg.get<float>("dRJetLeptonCut");

  // Run range
  const unsigned int RunRangeMin = cfg.get<unsigned int>("RunRangeMin");
  const unsigned int RunRangeMax = cfg.get<unsigned int>("RunRangeMax");

  const string dataBaseDir = cfg.get<string>("DataBaseDir");
  // vertex distributions filenames and histname
  const string vertDataFileName = cfg.get<string>("VertexDataFileName");
  const string vertMcFileName   = cfg.get<string>("VertexMcFileName");
  const string vertHistName     = cfg.get<string>("VertexHistName");

  const string jsonFile = cfg.get<string>("jsonFile");
  string cmsswBase = (getenv ("CMSSW_BASE"));
  string fullPathToJsonFile = cmsswBase + "/src/DesyTauAnalyses/NTupleMaker/test/json/" + jsonFile;

  // Run-lumi selector
  std::vector<Period> periods;  
  if (isData) { // read the good runs 
	  std::fstream inputFileStream(fullPathToJsonFile.c_str(), std::ios::in);
  	  if (inputFileStream.fail() ) {
            std::cout << "Error: cannot find json file " << fullPathToJsonFile << std::endl;
            std::cout << "please check" << std::endl;
            std::cout << "quitting program" << std::endl;
	    exit(-1);
	  }
  
          for(std::string s; std::getline(inputFileStream, s); ) {
           periods.push_back(Period());
           std::stringstream ss(s);
           ss >> periods.back();
          }
  }

  // **** end of configuration
/*
  // Run-lumi selector
  std::vector<Period> periods;
    
  std::fstream inputFileStream("temp", std::ios::in);
  for(std::string s; std::getline(inputFileStream, s); )
    {
      periods.push_back(Period());
      std::stringstream ss(s);
      ss >> periods.back();
    }
*/
  char ff[100];

  sprintf(ff,"%s/%s",argv[3],argv[2]);
  // file name and tree name
  std::string rootFileName(argv[2]);
  std::ifstream fileList(ff);
  std::ifstream fileList0(ff);
  std::string ntupleName("makeroottree/AC1B");
  
  TString era=argv[3];
  TString TStrName(rootFileName);
  std::cout <<TStrName <<std::endl;  

  TFile * file = new TFile(era+"/"+TStrName+TString(".root"),"update");
  file->cd("");

  TH1D * inputEventsH = new TH1D("inputEventsH","",1,-0.5,0.5);
  TH1D * histWeightsH = new TH1D("histWeightsH","",1,-0.5,0.5);


  TH1D * metAll  = new TH1D("metAll","",400,0,4000);

  TH1D * hDiJetmet = new TH1D("hDiJetmet","",400,0,4000);
  TH1D * hDiJetmass = new TH1D("hDiJetmass","",400,0,4000);
  TH1D * hDiJet1mass = new TH1D("hDiJet1mass","",400,0,4000);
  TH1D * hDiJet2mass = new TH1D("hDiJet2mass","",400,0,4000);
  TH1D * hHT_ = new TH1D("hHT_","",400,0,4000);
  TH1D * PUweightsOfficialH = new TH1D("PUweightsOfficialH","PU weights w/ official reweighting",1000, 0, -1);

 // PILE UP REWEIGHTING - OPTIONS

  if (applyPUreweighting_vertices and applyPUreweighting_official) 
	{std::cout<<"ERROR: Choose only ONE PU reweighting method (vertices or official, not both!) " <<std::endl; exit(-1);}

  // reweighting with vertices

  // reading vertex weights
  TFile * fileDataNVert = new TFile(TString(cmsswBase)+"/src/"+dataBaseDir+"/"+vertDataFileName);
  TFile * fileMcNVert   = new TFile(TString(cmsswBase)+"/src/"+dataBaseDir+"/"+vertMcFileName);

  TH1F * vertexDataH = (TH1F*)fileDataNVert->Get(TString(vertHistName));
  TH1F * vertexMcH   = (TH1F*)fileMcNVert->Get(TString(vertHistName));

  float normVertexData = vertexDataH->GetSumOfWeights();
  float normVertexMc   = vertexMcH->GetSumOfWeights();

  vertexDataH->Scale(1/normVertexData);
  vertexMcH->Scale(1/normVertexMc);


 // reweighting official recipe 
  	// initialize pile up object
  PileUp * PUofficial = new PileUp();
  

  
  if (applyPUreweighting_official) {
    TFile * filePUdistribution_data = new TFile(TString(cmsswBase)+"/src/DesyTauAnalyses/NTupleMaker/data/PileUpDistrib/Data_Pileup_2015D_Nov17.root","read"); 
    TFile * filePUdistribution_MC = new TFile (TString(cmsswBase)+"/src/DesyTauAnalyses/NTupleMaker/data/PileUpDistrib/MC_Spring15_PU25_Startup.root", "read"); 
    TH1D * PU_data = (TH1D *)filePUdistribution_data->Get("pileup");
    TH1D * PU_mc = (TH1D *)filePUdistribution_MC->Get("pileup");
    PUofficial->set_h_data(PU_data); 
    PUofficial->set_h_MC(PU_mc);
  }

  

  int nFiles = 0;
  int nEvents = 0;
  int selEventsAllMuons = 0;
  int selEventsIdMuons = 0;
  int selEventsIsoMuons = 0;



  int nTotalFiles = 0;
  std::string dummy;
  // count number of files --->
  while (fileList0 >> dummy) nTotalFiles++;

  unsigned int RunMin = 9999999;
  unsigned int RunMax = 0;

  std::vector<unsigned int> allRuns; allRuns.clear();
 vector <unsigned int> run_;
 vector <unsigned int> lumi_;
 vector <unsigned int> event_;
 run_.clear();
 lumi_.clear();
 event_.clear();
 

    std::vector<Event> EventList;
    std::string line;
    std::ifstream EventsFile;
    TString file_events=argv[4]; //eventlist_csc2015.txt
    //EventsFile.open("MET_filters/eventlist_"+file_events+".txt");
    EventsFile.open(era+"/"+file_events+".txt");
    //cout<<"  limits  int -> "<<std::numeric_limits<int>::max()<<"  long int -> "<<std::numeric_limits<long int>::max()<<"  unsigned int -> "<<std::numeric_limits<unsigned int>::max()<<endl;
    cout<<" The file that will be used will be "<<era<<"/"<<file_events<<".txt"<<endl;


    while (getline(EventsFile, line))
    {
        std::vector<std::string> columns = split(line,':');
        run_.push_back(std::stoi(columns[0]));
        lumi_.push_back(std::stoi(columns[1]));
        event_.push_back(std::stoul(columns[2]));
   	/*   Event events_;

        events_.name     = "Test";
        events_.run     = std::stoi(columns[0]);
        events_.lumi   = std::stoi(columns[1]);
        events_.eventrn = std::stof(columns[2]);

        EventList.push_back(events_);
  */
      	}

  cout<<" In total there are "<<run_.size()<< " entries for "<<file_events<<" filter "<<endl;
    EventsFile.close();

//    for (unsigned int sz=0;sz<run_.size();sz++)
//	    cout<<" run "<<run_[sz]<<"  "<<lumi_[sz]<<"  "<<event_[sz]<<endl;
    /*
         for (const Event & m: EventList) 
	{
	if (m.run == 20286)
	cout<<"  "<<m.name<<"  "<<m.run<<"  "<<m.lumi<<"  "<<m.eventrn<<endl;
	}
*/

  //----Attention----//
  //if(XSec!=1) nTotalFiles=20;
  //nTotalFiles=5;
  //
  //
 

  std::string initNtupleName("initroottree/AC1B");

  for (int iF=0; iF<nTotalFiles; ++iF) {

    std::string filen;
    fileList >> filen;

    std::cout << "file " << iF+1 << " out of " << nTotalFiles << " filename : " << filen << std::endl;
    TFile * file_ = TFile::Open(TString(filen));
    
    TH1D * histoInputEvents = NULL;
    histoInputEvents = (TH1D*)file_->Get("makeroottree/nEvents");
    if (histoInputEvents==NULL) continue;
    int NE = int(histoInputEvents->GetEntries());
    for (int iE=0;iE<NE;++iE)
      inputEventsH->Fill(0.);
    std::cout << "      number of input events         = " << NE << std::endl;

    TTree * _inittree = NULL;
    _inittree = (TTree*)file_->Get(TString(initNtupleName));
    if (_inittree==NULL) continue;
    Float_t genweight;
    if (!isData)
      _inittree->SetBranchAddress("genweight",&genweight);
    Long64_t numberOfEntriesInitTree = _inittree->GetEntries();
    std::cout << "      number of entries in Init Tree = " << numberOfEntriesInitTree << std::endl;
    for (Long64_t iEntry=0; iEntry<numberOfEntriesInitTree; iEntry++) {
      _inittree->GetEntry(iEntry);
      if (isData)
	histWeightsH->Fill(0.,1.);
      else
	histWeightsH->Fill(0.,genweight);
    }

    TTree * _tree = NULL;
    _tree = (TTree*)file_->Get(TString(ntupleName));
    if (_tree==NULL) continue;
    Long64_t numberOfEntries = _tree->GetEntries();
    std::cout << "      number of entries in Tree      = " << numberOfEntries << std::endl;
    AC1B analysisTree(_tree);


    // EVENT LOOP //
    
    
    std::cout << "      number of entries in Tree = " << numberOfEntries << std::endl;
    
    for (Long64_t iEntry=0; iEntry<numberOfEntries; iEntry++) { 
    
      analysisTree.GetEntry(iEntry);
      nEvents++;
      
      if (nEvents%10000==0) 
	cout << "      processed " << nEvents << " events" << endl; 

      float weight = 1;



      //------------------------------------------------
      // vertex cuts
      
      if (fabs(analysisTree.primvertex_z)>zVertexCut) continue;
      if (analysisTree.primvertex_ndof<ndofVertexCut) continue;
      float dVertex = (analysisTree.primvertex_x*analysisTree.primvertex_x+
		       analysisTree.primvertex_y*analysisTree.primvertex_y);
      if (dVertex>dVertexCut) continue;

      if (!isData) 
	weight *=analysisTree.genweight;

      histWeightsH->Fill(float(0),weight);


      //cout<< " We have zero counts ? "<<analysisTree.primvertex_count<<endl;

      if (!isData) {
	if (applyPUreweighting_vertices) {
	  int binNvert = vertexDataH->FindBin(analysisTree.primvertex_count);
	  float_t dataNvert = vertexDataH->GetBinContent(binNvert);
	  float_t mcNvert = vertexMcH->GetBinContent(binNvert);
	  if (mcNvert < 1e-10){mcNvert=1e-10;}
	  float_t vertWeight = dataNvert/mcNvert;
	  weight *= vertWeight;
	  //	  cout << "NVert = " << analysisTree.primvertex_count << "   weight = " << vertWeight << endl;
	}

        if (applyPUreweighting_official) {

	double Ninteractions = analysisTree.numtruepileupinteractions;
	double PUweight = PUofficial->get_PUweight(Ninteractions);
	weight *= PUweight;
	PUweightsOfficialH->Fill(PUweight);

        }
      }
      if (isData){
	
	
	bool lumi = false;
	int n=analysisTree.event_run;
	int lum = analysisTree.event_luminosityblock;
	int nr = analysisTree.event_nr;

	std::string num = std::to_string(n);
	std::string lnum = std::to_string(lum);
	for(const auto& a : periods)
	  {
	    
	    if ( num.c_str() ==  a.name ) {
	      //std::cout<< " Eureka "<<num<<"  "<<a.name<<" ";
	      //     std::cout <<"min "<< last->lower << "- max last " << last->bigger << std::endl;
	      
	      for(auto b = a.ranges.begin(); b != std::prev(a.ranges.end()); ++b) {
		
		//	cout<<b->lower<<"  "<<b->bigger<<endl;
		if (lum  >= b->lower && lum <= b->bigger ) lumi = true;
	      }
	      auto last = std::prev(a.ranges.end());
	      //    std::cout <<"min "<< last->lower << "- max last " << last->bigger << std::endl;
	      if (  (lum >=last->lower && lum <= last->bigger )) lumi=true;
	      
	      
	    }
	    
	  }
    
	//if (lumi ) cout<<"  =============  Found good run"<<"  "<<n<<"  "<<lum<<endl;
	//std::remove("myinputfile");
	if (!lumi) continue;
        bool runbool=false;
	bool lumibool=false;
	bool eventbool=false;
	runbool= std::find(run_.begin(), run_.end(), n) != run_.end();
	lumibool= std::find(lumi_.begin(), lumi_.end(), lum) != lumi_.end();
	eventbool= std::find(event_.begin(), event_.end(), nr) != event_.end();

       if (runbool && lumibool && eventbool) continue;
//	cout<<"=========================================== >>>>>>>>>>>> "<<n<<"  "<<lum<<"  "<<nr<<endl;
/*	//cout<<" Will cross-check against the list now "<<endl;
        for (const Event & m: EventList) 
	{
	if (m.run == n && m.lumi==lnum && m.eventrn == nr)
	cout<<"=========================================== >>>>>>>>>>>>  "<<m.name<<"  "<<m.run<<"  "<<m.lumi<<"  "<<m.eventrn<<endl;
	}
*/
	}


      float metall = sqrt(analysisTree.pfmet_ex*analysisTree.pfmet_ex+analysisTree.pfmet_ey*analysisTree.pfmet_ey);
                
             metAll->Fill(metall,weight);

      if (analysisTree.event_run<RunMin)
	RunMin = analysisTree.event_run;
      
      if (analysisTree.event_run>RunMax)
	RunMax = analysisTree.event_run;
      
      //std::cout << " Run : " << analysisTree.event_run << std::endl;
      
      bool isNewRun = true;
      if (allRuns.size()>0) {
	for (unsigned int iR=0; iR<allRuns.size(); ++iR) {
	  if (analysisTree.event_run==allRuns.at(iR)) {
	    isNewRun = false;
	    break;
	  }
	}
      }
	
      if (isNewRun) 
	allRuns.push_back(analysisTree.event_run);
      

	// selecting good jets --->
	if (analysisTree.pfjet_count>1) { 
			
	  for (unsigned int jet=0; jet<2; ++jet) {
	  float energy = analysisTree.pfjet_e[jet];
	  float absJetEta = fabs(analysisTree.pfjet_eta[jet]);
	  float chf = analysisTree.pfjet_chargedhadronicenergy[jet]/energy;
	  float nhf = analysisTree.pfjet_neutralhadronicenergy[jet]/energy;
	  float phf = analysisTree.pfjet_neutralemenergy[jet]/energy;
	  float elf = analysisTree.pfjet_chargedemenergy[jet]/energy;
	  float chm = analysisTree.pfjet_chargedmulti[jet];
	  float npr = analysisTree.pfjet_chargedmulti[jet] + analysisTree.pfjet_neutralmulti[jet];
	  bool isPFJetId = (npr>1 && phf<0.99 && nhf<0.99) && (absJetEta>2.4 || (elf<0.99 && chf>0 && chm>0));
	  if (!isPFJetId) continue;

	  if ( analysisTree.pfjet_pt[0] > 200. && analysisTree.pfjet_pt[1] > 200.) 
	  { 
          float metSel = sqrt(analysisTree.pfmet_ex*analysisTree.pfmet_ex+analysisTree.pfmet_ey*analysisTree.pfmet_ey);
	  hDiJetmet->Fill(metSel, weight);
	  
	  TLorentzVector jmass1; jmass1.SetPxPyPzE(analysisTree.pfjet_px[0],
					analysisTree.pfjet_py[0],
					analysisTree.pfjet_pz[0],
					analysisTree.pfjet_e[0]);

	  TLorentzVector jmass2; jmass2.SetPxPyPzE(analysisTree.pfjet_px[1],
					analysisTree.pfjet_py[1],
					analysisTree.pfjet_pz[1],
					analysisTree.pfjet_e[1]);

	  TLorentzVector dijet = jmass1 + jmass2;
	  hDiJetmass->Fill(dijet.M(),weight);
	  hDiJet1mass->Fill(jmass1.M(),weight);
	  hDiJet2mass->Fill(jmass2.M(),weight);

	  }
         }
	 }	 
     // HT variables
	float HT_=0;
	for (unsigned int jet=0; jet<analysisTree.pfjet_count; ++jet) {
	  float absJetEta = fabs(analysisTree.pfjet_eta[jet]);
	  if (absJetEta>jetEtaCut) continue;
          
	  

	  float energy = analysisTree.pfjet_e[jet];
	  float chf = analysisTree.pfjet_chargedhadronicenergy[jet]/energy;
	  float nhf = analysisTree.pfjet_neutralhadronicenergy[jet]/energy;
	  float phf = analysisTree.pfjet_neutralemenergy[jet]/energy;
	  float elf = analysisTree.pfjet_chargedemenergy[jet]/energy;
	  float chm = analysisTree.pfjet_chargedmulti[jet];
	  float npr = analysisTree.pfjet_chargedmulti[jet] + analysisTree.pfjet_neutralmulti[jet];
	  bool isPFJetId = (npr>1 && phf<0.99 && nhf<0.99) && (absJetEta>2.4 || (elf<0.99 && chf>0 && chm>0));
	  if (!isPFJetId) continue;
	  
	  HT_=HT_+analysisTree.pfjet_pt[jet];

	  }	  
        
	  hHT_->Fill(HT_,weight);



      
    } // end of file processing (loop over events in one file)
    nFiles++;
    delete _tree;
    file_->Close();
    delete file_;
  }
  std::cout << std::endl;
  int allEvents = int(inputEventsH->GetEntries());
  std::cout << "Total number of input events                     = " << allEvents << std::endl;
  std::cout << "Total number of events in Tree                   = " << nEvents << std::endl;
  std::cout << "Total number of selected events (iso muon pairs) = " << selEventsIsoMuons << std::endl;
  std::cout << std::endl;
  std::cout << "RunMin = " << RunMin << std::endl;
  std::cout << "RunMax = " << RunMax << std::endl;

  //cout << "weight used:" << weight << std::endl;

  // using object as comp
  std::sort (allRuns.begin(), allRuns.end(), myobject);
  std::cout << "Runs : ";
  for (unsigned int iR=0; iR<allRuns.size(); ++iR)
    std::cout << " " << allRuns.at(iR);
  std::cout << std::endl;
  
  file->Write();
  file->Close();
  delete file;
  
  }
//*********************************************************************************
// Start of main function 
// parameters: 
//  * filename         - name of the tree-input file
//  * optionCollSystem - selection of collision system should be either "pp" or 
//		                   "PbPb"
//  * optionTest       - test option will allow not to analyse the full data sample
//                       at first but just 100 events
//  * startCentrality  - gives the starting point of your centrality bin
//  * endCentrality 	  - gives the end point of your centrality bin
//*********************************************************************************
void AnalyseTreeForRAAStudents(TString filename = "MasterClassesTree_LHC10h_Run139036.root", TString optionCollSystem = "PbPb", TString optionTest= "kFALSE", Int_t startCentrality = 0., Int_t endCentrality = 100.){


  //Reset ROOT and connect tree file
  gROOT->Reset();
  StyleSettings();		
  
  gStyle->SetOptStat(1);

	
  cout << "Analysing file " <<  filename.Data() << endl;
  cout << "Collision system chosen: " << optionCollSystem.Data() << endl;
  if (optionCollSystem.CompareTo("PbPb")==0){
    cout << "Centrality chosen between: " << startCentrality << " - " << endCentrality << endl;
  }
  
  TString alice_portal = gSystem->Getenv("ALICE_PORTAL");
  if (alice_portal.IsNull()) {
     printf("ALICE_PORTAL not defined. Exiting.");
     exit(1);
  }
  if (gSystem->AccessPathName(filename)) {
  // Download file from the portal
     TString sfile = Form("%s/eve_files/data/%s", alice_portal.Data(), filename.Data());
     if (!TFile::Cp(sfile,filename, kFALSE)) {
        printf("File %s not available on the ALICE portal", filename.Data());
        exit(1);
     }   
  }
  //*********************************************************************************
  //Attaching the file
  //*********************************************************************************
  TFile *f = new TFile(filename.Data());
   
  //*********************************************************************************
  //Declaration of leaves types for track tree 
  //*********************************************************************************
  Float_t         trackCentrality;  // variable for the centrality in the track tree
  Double_t        trackPt;	    // variable for the transverse momentum of the track

  //*********************************************************************************
  //Declaration of leaves types for event tree
  //*********************************************************************************
  Float_t         eventCentrality;  // variable for the centrality in the event tree
  Int_t           eventMult;	    // variable for the multiplicity in the event
	
  //*********************************************************************************
  // Definition of input trees 
  //*********************************************************************************
  TTree *Track = (TTree*)gDirectory->Get("Track");  // stores track properties
  TTree *Event = (TTree*)gDirectory->Get("Event");  // stores event properties
	
	
  // Set branch addresses for track tree 
  Track->SetBranchAddress("centrality",&trackCentrality);
  Track->SetBranchAddress("trackpt",&trackPt);
  // Set branch addresses for event tree
  Event->SetBranchAddress("nTPCAccepted",&eventMult);
  Event->SetBranchAddress("centrality",&eventCentrality);

  //*********************************************************************************
  // maximum number of files for testing 
  //*********************************************************************************
  ULong64_t nEntriesTest = 1000;
		
  //*********************************************************************************
  // Getting the number of entries in the track tree
  //*********************************************************************************
  ULong64_t nEntriesTrack = Track->GetEntries();
  cout << "You have " << nEntriesTrack << " for the track tree" << endl;
  if (optionTest.CompareTo("kTRUE") == 0){
    cout << "You will at maximum analyse "<< nEntriesTest <<" tracks in the tree for testing "  << endl;
    if (nEntriesTrack > nEntriesTest){
      nEntriesTrack = nEntriesTest;
    }
  }

  //*********************************************************************************
  // Getting the number of entries in the event tree 
  //*********************************************************************************
  ULong64_t nEntriesEvent = Event->GetEntries();
  cout << "You have " << nEntriesEvent << " for the event tree" << endl;
  if (optionTest.CompareTo("kTRUE") == 0){
    cout << "You will at maximum analyse "<< nEntriesTest <<" events in the tree for testing "  << endl;
    if (nEntriesEvent > nEntriesTest){
      nEntriesEvent = nEntriesTest;
    }
  }
  
  //*********************************************************************************
  // Definition of bins in transverse momentum pt, due to steply falling spectrum 
  // and not enough statistics at high pt 
  //*********************************************************************************
  Int_t fNBinsPt = 54; 								 
  Double_t fBinsPt[55] = {0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45,
			  0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95,
			  1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9,
			  2, 2.2, 2.4, 2.6, 2.8, 3, 3.2, 3.4, 3.6, 3.8,
			  4, 4.5, 5, 5.5, 6, 6.5, 7, 8, 9, 10, 
			  11, 12, 13, 14, 15};
								 
								 
								 
  //*********************************************************************************
  // Defintion of histograms:
  // * to be filled with trackpt and number of charged tracks in the TPC (TH1*)
  // * correlation between centrality an nTracks TPC (TH2F)							 
  //*********************************************************************************	
								 
  TH1D* htrackPt = new TH1D("htrackPt","track pt",fNBinsPt,fBinsPt);
  TH1F *hNTPC = new TH1F("hNTPC","Number of TPC tracks ",200,0,2000);
  TH2F *hNTPCvsCent = new TH2F("hNTPCvsCent","Number of TPC tracks ",200,0,2000, 100, 0, 100);
	
  //*********************************************************************************
  // Definition of correction histogram in order to normalise for the binwidth in
  // Pt
  //*********************************************************************************
  TH1D* fDeltaPt = new TH1D("deltaPt","",fNBinsPt,fBinsPt);
  for(Int_t iPt=1;iPt<fNBinsPt+1;iPt++){
    fDeltaPt->SetBinContent(iPt,fBinsPt[iPt]-fBinsPt[iPt-1]);
    fDeltaPt->SetBinError(iPt,0);
  }
	
  //*********************************************************************************
  // * Reading the entries form the event tree (extract nTracksTPC) and filling 
  //   it in the multiplicity histograms (hNTPC,hNTPCvsCent)
  // * Distinction between PbPb and pp as for PbPb you need to fill them with 
  //   restriction in centrality
  // * nEntriesPerCent will give you the normalization value for the different 
  //	  centralities
  //*********************************************************************************

  ULong_t nEntriesPerCent= 0;
  ULong64_t nbytes2 = 0;
  for (ULong_t i=0; i<nEntriesEvent;i++) {
    nbytes2 += Event->GetEvent(i);
    if (eventCentrality > startCentrality && eventCentrality < endCentrality){
      hNTPC->Fill(eventMult);
      hNTPCvsCent->Fill(eventMult,eventCentrality);
      nEntriesPerCent++;
    }
    // give an output for every 10Mio events processed to see that is working 
    if ( i%10000000 == 0 ) {
      cout << i/10000000 << " * 10^7 events have been processed" << endl;
    }
  }

	
  //*********************************************************************************
  // * Reading the entries form the track tree (extract pt values) and filling it 
  //   in the pt-histogram
  // * Distinction between PbPb and pp as for PbPb you need to fill them with 
  //   restriction in centrality
  //*********************************************************************************
  ULong64_t nbytes = 0;
  cout << nEntriesTrack/100000000 << " * 10^8 tracks have to be processed" << endl;
  for (ULong_t i=0; i<nEntriesTrack;i++) {
    nbytes += Track->GetEvent(i);
    /// To do: here you need to add something

		
		
		
		
		
		
		
		
		
		
  }

	
  //*********************************************************************************
  //	Definition of canvas
  //*********************************************************************************
  TCanvas *c1 = new TCanvas("c1","Pt");
  TCanvas *c2 = new TCanvas("c2","nTracksTPC");
  TCanvas *c3 = new TCanvas("c3","nTracksTPCvsCent");
  //*********************************************************************************
  // * Axis labeling for multiplicity histogram and plotting it to an eps file with
  //   the name dependent on the collision system and centrality
  //*********************************************************************************
  hNTPC->Sumw2();
  hNTPC->GetYaxis()->SetTitleOffset(1.3);
  hNTPC->Scale(1./nEntriesPerCent);
  hNTPC->SetXTitle("number TPC tracks");
  hNTPC->SetYTitle("Counts/N_{evt}");	
  c2->cd();
  c2->SetLogy(1);
  HistoSetMarkerAndColor( hNTPC, 20, 1., kBlue, kBlue );
  hNTPC->Draw("e1,p");
  c2->SaveAs(Form("nTracksTPC_%i-%i.eps",startCentrality,endCentrality));	
  
  
  hNTPCvsCent->SetXTitle("number TPC tracks");
  hNTPCvsCent->SetYTitle("Centrality");
  hNTPCvsCent->GetYaxis()->SetTitleOffset(1.3);
  c3->cd(); 
  c3->SetLogy(0);
  c3->SetLogz(1);
  c3->SetRightMargin(0.1);
  hNTPCvsCent->Draw("colz");
  c3->SaveAs(Form("nTracksTPCvsCent_%i-%i.eps",startCentrality,endCentrality));	

	
	
  //*********************************************************************************
  // * Normalisation of the pt-histogram to the number of entries in this 
  //   centrality bin and to the bin with in pt by deviding through the created 
  //   histogram for deltaPt (fDeltaPt)
  // * Labeling of the histograms and plotting it to an eps file with the name
  //   dependent on the collision system and the centralities
  //*********************************************************************************
  cout << "Entries total: " << nEntriesEvent << "\t Entries per Centrality: "  << nEntriesPerCent << endl;
  
  /// To do:The following commands need to be uncommented and you need to add the plotting of the 
  ///        pt-histogram, don't forget to label your axis.
  
  //htrackPt->Sumw2();
  //htrackPt->Divide(fDeltaPt);
  //htrackPt->Scale(1./nEntriesPerCent);
  //htrackPt->GetYaxis()->SetTitleOffset(1.3);
  
	
	
	
	
	
	
	
	
	
   
	
  //*********************************************************************************
  // Saving the histograms to a root-file for further processing for the RAA 
  // * the option "UPDATE" in the end will allow to save different centrality classes
  //   in one file as it just creates the file vom scratch if it is non existent
  //   and just overwrites the histograms which are written if it exists
  //*********************************************************************************
	
  TFile* fileOutput = new TFile("RAABaseOutput.root","UPDATE");
  hNTPC->Write(Form("nTracksTPC_%s_%i-%i",optionCollSystem.Data(),startCentrality,endCentrality),TObject::kOverwrite);
  /// To do: uncomment this as soon as you are ready 
  // 		htrackPt->Write(Form("trackPt_%s_%i-%i",optionCollSystem.Data(),startCentrality,endCentrality),TObject::kOverwrite);
  fileOutput->Write();
  fileOutput->Close();

	
	
}
Example #9
0
//------------------------------------------------------------------------------
// DrawHistogram
//------------------------------------------------------------------------------
void DrawHistogram(TString  hname,
		   TString  xtitle,
		   Int_t    ngroup       = -1,
		   Int_t    precision    = 1,
		   TString  units        = "NULL",
		   Double_t xmin         = -999,
		   Double_t xmax         =  999,
		   Bool_t   moveOverflow = true)
{
  //TCanvas* canvas = new TCanvas(hname, hname, 550, 720);
  TCanvas* canvas = new TCanvas(hname, hname, 800, 800);

  TPad* pad1 = new TPad("pad1", "pad1", 0, 0.3, 1, 1.0);
  TPad* pad2 = new TPad("pad2", "pad2", 0, 0.0, 1, 0.3); 

  pad1->SetTopMargin   (0.08);
  pad1->SetBottomMargin(0.02);
  pad1->Draw();
      
  pad2->SetTopMargin   (0.08);
  pad2->SetBottomMargin(0.35);
  pad2->Draw();


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

  pad1->SetLogy(_setLogy);

  THStack* hstack = new THStack(hname, hname);

  TH1F* hist[nProcesses];

  //Save histograms to root file
  TFile* outfile;
  //TString fname = Form("files/%s_%djet.root", hname.Data(),_njet);
  TString fname = "files/0jet_"+hname+".root";
  if(_njet==1) fname = "files/1jet_"+hname+".root";
  outfile = new TFile(fname, "create");
  
  TH1F* data;
  TH1F* top;
  TH1F* tW;
  TH1F* WW;
  TH1F* WZ;
  TH1F* ZZ;
  TH1F* Wg;
  TH1F* WgSMu;
  TH1F* WgSEl;
  TH1F* Wjets;
  TH1F* Zjets;
  TH1F* DYtau;
  TH1F* Zgamma;
  TH1F* ggH;



  
  for (UInt_t ip=0; ip<nProcesses; ip++) {

    hist[ip] = (TH1F*)input[ip]->Get(hname);
    hist[ip]->SetName(hname + process[ip]);
    hist[ip]->SetTitle("");

    if(ip == iData)   data   = (TH1F*)hist[iData]->Clone("Data");     //data   -> Sumw2();
    if(ip == itt)     top    = (TH1F*)hist[itt]->Clone("top");        //top    -> Sumw2();
    if(ip == itW)     tW     = (TH1F*)hist[itW]->Clone("tW");         //tW     -> Sumw2();
    if(ip == iWW)     WW     = (TH1F*)hist[iWW]->Clone("WW");         //WW     -> Sumw2();
    if(ip == iWZ)     WZ     = (TH1F*)hist[iWZ]->Clone("WZ");   //VV     -> Sumw2();
    if(ip == iZZ)     ZZ     = (TH1F*)hist[iZZ]->Clone("ZZ");         //ZZ     -> Sumw2();
    if(ip == iWg)     Wg     = (TH1F*)hist[iWg]->Clone("Wg");         //Wg     -> Sumw2();
    if(ip == iWgSMu){
      WgSMu  = (TH1F*)hist[iWgSMu]->Clone("WgSMu");         //WgSMu     -> Sumw2();
      hist[iWgSMu]->Scale(1.5);
    }
    if(ip == iWgSEl){
      WgSEl  = (TH1F*)hist[iWgSEl]->Clone("WgSEl");         //WgSel     -> Sumw2();
      hist[iWgSEl]->Scale(1.5);         //WgSel     -> Sumw2();
    }
    if(ip == iWj)     Wjets  = (TH1F*)hist[iWj]->Clone("W+jets");     //Wjets  -> Sumw2();
    if(ip == iDY)     Zjets  = (TH1F*)hist[iDY]->Clone("Z+jets");     //Zjets  -> Sumw2();
    if(ip == iDYtau)  DYtau  = (TH1F*)hist[iDYtau]->Clone("DYtau");   //DYtau  -> Sumw2();
    if(ip == iZgamma) Zgamma = (TH1F*)hist[iZgamma]->Clone("Zgamma"); //Zgamma -> Sumw2();
    if(ip == iH125)   ggH    = (TH1F*)hist[iH125]->Clone("ggH");      //ggH    -> Sumw2();
    
    if (moveOverflow) MoveOverflowBins  (hist[ip], xmin, xmax);
    else              ZeroOutOfRangeBins(hist[ip], xmin, xmax);

    if (ngroup > 0) hist[ip]->Rebin(ngroup);

    if (ip == iWg) {
      //hist[ip]->Scale(0.01);
    }
    
    if (ip == iData) {
      hist[ip]->SetMarkerStyle(kFullCircle);
    }
    else {
      hist[ip]->SetFillColor(color[ip]);
      hist[ip]->SetFillStyle(1001);
      hist[ip]->SetLineColor(color[ip]);

      if (_dataDriven && ip == itt)    hist[ip]->Scale(ttScale[_njet]);
      if (_dataDriven && ip == itW)    hist[ip]->Scale(tWScale[_njet]);
      if (_dataDriven && ip == iWW)    hist[ip]->Scale(WWScale[_njet]);
      if (_dataDriven && ip == iDY)    hist[ip]->Scale(ZjScale[_njet]);
      if (_dataDriven && ip == iDYtau) hist[ip]->Scale(ZjScale[_njet]);

      if( ip != iZZ ) hstack->Add(hist[ip]);//TODO something wrong with ZZ
      
    }
  }

  if (_dataDriven)
  {
    top->Scale(ttScale[_njet]);
    tW->Scale(tWScale[_njet]);
    WW->Scale(WWScale[_njet]);
    Zjets->Scale(ZjScale[_njet]);
    DYtau->Scale(ZjScale[_njet]);
  }
  
  top  ->Add(tW);
  //VV   ->Add(ZZ);
  //VV   ->Add(Wg);  
  //Zjets->Add(DYtau);
  //Zjets->Add(Zgamma);

  data  -> Write();
  top   -> Write();
  WW    -> Write();
  //VV    -> Write();
  //Wjets -> Write();
  //Zjets -> Write();
  ggH   -> Write();
  
  outfile->Close();


  // All MC
  //----------------------------------------------------------------------------
  TH1F* allmc = (TH1F*)hist[iData]->Clone("allmc");

  allmc->SetFillColor  (kGray+2);
  allmc->SetFillStyle  (   3345);
  allmc->SetLineColor  (kGray+2);
  allmc->SetMarkerColor(kGray+2);
  allmc->SetMarkerSize (      0);

  for (UInt_t ibin=1; ibin<=allmc->GetNbinsX(); ibin++) {

    Double_t binValue = 0;
    Double_t binError = 0;

    for (UInt_t ip=0; ip<nProcesses; ip++) {

      if (ip == iData) continue;
      if (ip == iZZ) continue;

      Double_t binContent = hist[ip]->GetBinContent(ibin);
      
      binValue += binContent;
      binError += (hist[ip]->GetBinError(ibin) * hist[ip]->GetBinError(ibin));

      //We need to calculate systematic uncertainty for ggH case
//      if (_dataDriven)
//	binError += (systError[ip]*binContent * systError[ip]*binContent);
    }
    
    binError = sqrt(binError);

    allmc->SetBinContent(ibin, binValue);
    allmc->SetBinError  (ibin, binError);
  }


  // Axis labels
  //------------------------------------------------------------------
  TAxis* xaxis = hist[iData]->GetXaxis();
  TAxis* yaxis = hist[iData]->GetYaxis();

  TString ytitle = Form("entries / %s.%df", "%", precision);

  xaxis->SetTitle(xtitle);
  yaxis->SetTitle(Form(ytitle.Data(), hist[iData]->GetBinWidth(0)));
  yaxis->SetTitleOffset(1.6);

  if (!units.Contains("NULL")) {
    
    xaxis->SetTitle(Form("%s [%s]", xaxis->GetTitle(), units.Data()));
    yaxis->SetTitle(Form("%s %s",   yaxis->GetTitle(), units.Data()));
  }


  // Draw
  //--------------------------------------------------------------------
  xaxis->SetRangeUser(xmin, xmax);

  hist[iData]->Draw("ep");
  hstack     ->Draw("hist,same");
  allmc      ->Draw("e2,same");
  hist[iData]->Draw("ep,same");

  // Adjust scale
  //----------------------------------------------------------------------------
  Float_t theMax   = GetMaximumIncludingErrors(hist[iData], xmin, xmax);
  Float_t theMaxMC = GetMaximumIncludingErrors(allmc,       xmin, xmax);

  if (theMaxMC > theMax) theMax = theMaxMC;

  if (pad1->GetLogy()) {

    theMax = TMath::Power(10, TMath::Log10(theMax) + 2.7);

    hist[iData]->SetMinimum(0.05);
  }
  else theMax *= 1.55;

  hist[iData]->SetMaximum(theMax);


  // Legend
  //----------------------------------------------------------------------
  Double_t x0      = 0.720; 
  Double_t y0      = 0.834; 
  Double_t yoffset = 0.048;
  Double_t delta   = yoffset + 0.001;
  Double_t ndelta  = 0;

  Double_t YieldTop   = Yield(hist[itt]) + Yield(hist[itW]);
  Double_t YieldWZ    = Yield(hist[iWZ]);
  Double_t YieldVV    = Yield(hist[iWZ]) + Yield(hist[iZZ]) + Yield(hist[iWg]);
  //Double_t YieldZJets = Yield(hist[iDY]) + Yield(hist[iDYtau]);
  Double_t YieldZJets = Yield(hist[iDY]) + Yield(hist[iDYtau]) + Yield(hist[iZgamma]);

  DrawLegend(x0 - 0.49, y0 - ndelta, hist[iData],  Form(" data (%.0f)", Yield(hist[iData])), "lp", 0.03, 0.2, yoffset); ndelta += delta;
  //DrawLegend(x0 - 0.23, y0 - ndelta, hist[itt],    Form(" tt (%.0f)",  Yield(hist[itt])),   "f",  0.03, 0.2, yoffset); ndelta += delta;
  //DrawLegend(x0 - 0.23, y0 - ndelta, hist[itW],    Form(" tW (%.0f)",  Yield(hist[itW])),   "f",  0.03, 0.2, yoffset); ndelta += delta;
  //DrawLegend(x0 - 0.49, y0 - ndelta, allmc,        Form(" all (%.0f)",  Yield(allmc)),       "f",  0.03, 0.2, yoffset); ndelta += delta;
  DrawLegend(x0 - 0.49, y0 - ndelta, hist[iWW],    Form(" WW (%.0f)",   Yield(hist[iWW])),   "f",  0.03, 0.2, yoffset); ndelta += delta;
  DrawLegend(x0 - 0.49, y0 - ndelta, hist[iWZ],    Form(" WZ (%.0f)",   Yield(hist[iWZ])),  "f",  0.03, 0.2, yoffset); ndelta += delta;
  DrawLegend(x0 - 0.49, y0 - ndelta, hist[iWg],    Form(" Wg (%.0f)",    Yield(hist[iWg])),   "f",  0.03, 0.2, yoffset); ndelta += delta;
  DrawLegend(x0 - 0.49, y0 - ndelta, hist[iWgSMu], Form(" Wg*Mu (%.0f)",    Yield(hist[iWgSMu])),   "f",  0.03, 0.2, yoffset); ndelta += delta;
  DrawLegend(x0 - 0.49, y0 - ndelta, hist[iWgSEl], Form(" Wg*El (%.0f)",    Yield(hist[iWgSEl])),   "f",  0.03, 0.2, yoffset); ndelta += delta;
  DrawLegend(x0 - 0.49, y0 - ndelta, hist[iWj],    Form(" W+jets (%.0f)",Yield(hist[iWj])),   "f",  0.03, 0.2, yoffset); ndelta += delta;
  DrawLegend(x0 - 0.49, y0 - ndelta, hist[iZZ],    Form(" ZZ (%.0f)",    Yield(hist[iZZ])),   "f",  0.03, 0.2, yoffset); ndelta += delta;


  ndelta = 0;
  DrawLegend(x0 - 0.23, y0 - ndelta, hist[iDY],    Form(" DY (%.0f)",    Yield(hist[iDY])),   "f",  0.03, 0.2, yoffset); ndelta += delta;
  DrawLegend(x0 - 0.23, y0 - ndelta, hist[iDYtau], Form(" DYtau (%.0f)", Yield(hist[iDYtau])),"f",  0.03, 0.2, yoffset); ndelta += delta;
  DrawLegend(x0 - 0.23, y0 - ndelta, hist[iZgamma],Form(" Zg (%.0f)",   Yield(hist[iZgamma])),"f",  0.03, 0.2, yoffset); ndelta += delta;
  //DrawLegend(x0 - 0.23, y0 - ndelta, hist[iDY],   Form(" Z+jets (%.0f)", YieldZJets),         "f",  0.03, 0.2, yoffset); ndelta += delta;
  //DrawLegend(x0 - 0.23, y0 - ndelta, hist[iH125], Form(" Higgs (%.0f)",  Yield(hist[iH125])), "f",  0.03, 0.2, yoffset); ndelta += delta;
  DrawLegend(x0 - 0.23, y0 - ndelta, hist[iH125],  Form(" ggH (%.0f)",  Yield(hist[iH125])), "f",  0.03, 0.2, yoffset); ndelta += delta;
  DrawLegend(x0 - 0.23, y0 - ndelta, hist[itt],  Form(" tt (%.0f)",  Yield(hist[itt])), "f",  0.03, 0.2, yoffset); ndelta += delta;
  DrawLegend(x0 - 0.23, y0 - ndelta, hist[itW],  Form(" tW (%.0f)",  Yield(hist[itW])), "f",  0.03, 0.2, yoffset); ndelta += delta;


  // Additional titles
  //----------------------------------------------------------------------------
  //TString channelLabel = "ee/#mu#mu/e#mu/#mue";
  TString channelLabel = "";

  //if (_channel == "EE")   channelLabel = "ee";
  //if (_channel == "MuMu") channelLabel = "#mu#mu";
  //if (_channel == "EMu")  channelLabel = "e#mu";
  //if (_channel == "MuE")  channelLabel = "#mue";
  //if (_channel == "SF")   channelLabel = "ee/#mu#mu";
  //if (_channel == "OF")   channelLabel = "e#mu/#mue";

  channelLabel += Form(" %d", _njet);

  if (_njet == 0) channelLabel += "-jets";
  if (_njet == 1) channelLabel += "-jet";
  if (_njet >= 2) channelLabel += "-jets";

  double nBin;
  double binWidth;
  nBin = allmc->GetSize();
  nBin -=2;
  binWidth = allmc->GetBinWidth(2);

  int Z1bin=70/binWidth;
  int Z2bin=110/binWidth;

  cout<<"number of bin: "<<nBin<<endl;
  cout<<"Z bin1: "<<Z1bin<<" Z bin2: "<<Z2bin<<endl;
  double nMcZ, nDataZ;
  nMcZ   = allmc->Integral(Z1bin,Z2bin);
  nDataZ = hist[iData]->Integral(Z1bin,Z2bin);
  double effiCorr;
  effiCorr=nDataZ/nMcZ;
  cout<<"efficiency correction factor: "<<effiCorr<<endl;
  double nMcGstar, nDataGstar, nMcGamma;
  nMcGstar   = hist[iWgSMu]->Integral(1,2);
  nMcGamma   = hist[iWg]->Integral(1,2);
  //nMcGstar   = allmc->Integral(1,2);
  nMcGstar *= effiCorr;
  nMcGamma *= effiCorr;
  nDataGstar = hist[iData]->Integral(1,2);
  double Kfactor;
  double KfactorErr;
  nDataGstar -= nMcGamma;
  Kfactor = nDataGstar/nMcGstar;
  KfactorErr =Kfactor* TMath::Sqrt(nDataGstar/nDataGstar/nDataGstar + nMcGstar/nMcGstar/nMcGstar);
  KfactorErr += 0.1;
  cout<<"Kfactor: "<<Kfactor<<"+"<<KfactorErr<<endl;

  //DrawTLatex(0.185, 0.975, 0.05, 13, channelLabel.Data(),"");
  DrawTLatex(0.940, 0.983, 0.05, 33, Form("L = %.1f fb^{-1}", _luminosity/1e3),"");
  DrawTLatex(0.45, 0.48, 0.04, 13, Form("K factor (Data/Wg*) = %.2f #pm %.2f", Kfactor, KfactorErr ),"");
  DrawTLatex(0.45, 0.43, 0.04, 13, Form("0< InvM(#mu^{+}#mu^{-}) <4 GeV"),"");

  //----------------------------------------------------------------------------
  // pad2
  //----------------------------------------------------------------------------
  pad2->cd();
    
  TH1F* ratio       = (TH1F*)hist[iData]->Clone("ratio");
  TH1F* uncertainty = (TH1F*)allmc->Clone("uncertainty");
    
  for (UInt_t ibin=1; ibin<=ratio->GetNbinsX(); ibin++) {

    Double_t mcValue = allmc->GetBinContent(ibin);
    Double_t mcError = allmc->GetBinError  (ibin);
    
    Double_t dtValue = ratio->GetBinContent(ibin);
    Double_t dtError = ratio->GetBinError  (ibin);

    Double_t ratioValue       = (mcValue > 0) ? dtValue/mcValue : 0.0;
    Double_t ratioError       = (mcValue > 0) ? dtError/mcValue : 0.0;
    Double_t uncertaintyError = (mcValue > 0) ? mcError/mcValue : 0.0;

    ratio->SetBinContent(ibin, ratioValue);
    ratio->SetBinError  (ibin, ratioError);

    uncertainty->SetBinContent(ibin, 1.0);
    uncertainty->SetBinError  (ibin, uncertaintyError);
  }


  TAxis* uaxis = (TAxis*)uncertainty->GetXaxis();
    
  uaxis->SetRangeUser(xmin, xmax);
    
    
  uncertainty->Draw("e2");
  ratio      ->Draw("ep,same");

  uncertainty->GetYaxis()->SetRangeUser(0, 2.5);


  // Save
  //----------------------------------------------------------------------
  pad2->cd(); SetAxis(uncertainty, hist[iData]->GetXaxis()->GetTitle(), "data / prediction", 0.10, 0.8);
  pad1->cd(); SetAxis(hist[iData], "", hist[iData]->GetYaxis()->GetTitle(),                  0.05, 1.6);

  canvas->cd();

  TString suffixLogy = (_setLogy) ? "_Log" : "_Lin";

  canvas->SaveAs(Form("%s/%s%s.%s",
		      _output.Data(),
		      hname.Data(),
		      suffixLogy.Data(),
		      _format.Data()));
}
Example #10
0
int ntuAnalyzer(std::string fileName)
{
  setGlobalStyle();
  
  //###############################
  //## run274200 ##
  unsigned int HT250Calo  = 9; //index of DST_HT250_CaloScouting_v   old:1 ref:9
  float HT250Calo_rate = 1928;

  unsigned int HT410PF = 7; //index of DST_HT410_PFScouting_v   old:3 ref:7
  float HT410PF_rate = 294;

  unsigned int MJJ200Calo = 12; //index of DST_DiCaloWideJetMass200_CaloScouting_v
  
  unsigned int HTT200 = 0; //index if L1_HTT200
  unsigned int HTT240 = 1; //index if L1_HTT240
  unsigned int HTT270 = 2; //index if L1_HTT270
  unsigned int HTT280 = 3; //index if L1_HTT280
  unsigned int DoubleJetC100 = 7; //index if L1_DoubleJetC100
  unsigned int DoubleJetC112 = 8; //index if L1_DoubleJetC112
  unsigned int DoubleIsoTau28er = 11; //index if L1_DoubleJetC112

  float instLumi = 0.4; //E34
  float targetLumi = 1; //E34
  float lumiScaleFactor = targetLumi/instLumi;

  float PDRate = 59300; //unprescaled rate of HLTPhysics accordingly to: https://cmswbm2.web.cern.ch/cmswbm2/cmsdb/servlet/DatasetSummary?RUN=274200 and prescale of 9000
  

  unsigned int L1scenario = HTT240;
  //###############################

  TChain* tt = new TChain("MyAnalysis/HLTree");
  tt->Add(fileName.c_str());

  //set branches
  TBranch* b_lumi;
  
  TBranch* b_caloMjj;
  TBranch* b_PFMjj;

  TBranch* b_hltAccept;
  TBranch* b_l1Accept;
  TBranch* b_l1Names;

  TBranch* b_caloJet1Pt;
  TBranch* b_caloJet2Pt;
  TBranch* b_caloJet1Eta;
  TBranch* b_caloJet2Eta;
  TBranch* b_caloDeltaEta;

  TBranch* b_PFJet1Pt;
  TBranch* b_PFJet2Pt;
  TBranch* b_PFJet1Eta;
  TBranch* b_PFJet2Eta;
  TBranch* b_PFDeltaEta;

  int lumi = 0;
  float caloMjj = 0;
  float PFMjj = 0;

  float caloJet1Pt_ = 0;
  float caloJet2Pt_ = 0;
  float caloJet1Eta_ = -999;
  float caloJet2Eta_ = -999;
  float caloDeltaEta_ = -999;

  float PFJet1Pt_ = 0;
  float PFJet2Pt_ = 0;
  float PFJet1Eta_ = -999;
  float PFJet2Eta_ = -999;
  float PFDeltaEta_ = -999;

  
  std::vector<int>* hltAccept = 0;
  std::vector<int>* l1Accept = 0;
  std::vector<string>* l1Names = 0;

  tt->SetBranchAddress("lumi", &lumi, &b_lumi);

  tt->SetBranchAddress("caloMjj", &caloMjj, &b_caloMjj);
  tt->SetBranchAddress("PFMjj", &PFMjj, &b_PFMjj);

  tt->SetBranchAddress("caloJet1Pt", &caloJet1Pt_, &b_caloJet1Pt);
  tt->SetBranchAddress("caloJet2Pt", &caloJet2Pt_, &b_caloJet2Pt);
  tt->SetBranchAddress("caloJet1Eta", &caloJet1Eta_, &b_caloJet1Eta);
  tt->SetBranchAddress("caloJet2Eta", &caloJet2Eta_, &b_caloJet2Eta);
  tt->SetBranchAddress("caloDeltaEta", &caloDeltaEta_, &b_caloDeltaEta);

  tt->SetBranchAddress("PFJet1Pt", &PFJet1Pt_, &b_PFJet1Pt);
  tt->SetBranchAddress("PFJet2Pt", &PFJet2Pt_, &b_PFJet2Pt);
  tt->SetBranchAddress("PFJet1Eta", &PFJet1Eta_, &b_PFJet1Eta);
  tt->SetBranchAddress("PFJet2Eta", &PFJet2Eta_, &b_PFJet2Eta);
  tt->SetBranchAddress("PFDeltaEta", &PFDeltaEta_, &b_PFDeltaEta);

  tt->SetBranchAddress("hltAccept", &hltAccept, &b_hltAccept);
  tt->SetBranchAddress("l1Accept", &l1Accept, &b_l1Accept);
  tt->SetBranchAddress("l1Names", &l1Names, &b_l1Names);

  int nentries = tt->GetEntries();
  std::cout << "Number of entries: " << nentries << std::endl;

  //book graphs and plots
  float min = 0.;
  float max = 1000.;
  int nBins = 20;

  TF1* f1 = new TF1("f1","[0]*TMath::Erf((x-[1])/[2])-[0]*TMath::Erf((-x-[1])/[2])",min,max);
  f1->SetParameters(0.5,350,40);  
  f1->FixParameter(0,0.5);
  f1->SetLineWidth(2.);
  f1->SetLineColor(kRed);

  TF1* f2 = (TF1*)f1->Clone("f2");
  f2->SetParameters(0.5,150,10);
  f2->SetLineColor(kBlack);

  TH1F* caloMjjSpectrum = new TH1F("caloMjjSpectrum","caloMjjSpectrum",nBins,min,max);
  TH1F* PFMjjSpectrum = new TH1F("PFMjjSpectrum","PFMjjSpectrum",nBins,min,max);
  
  TEfficiency* mjj450_eff = new TEfficiency("mjj450_eff","mjj450_eff",nBins,min,max);
  mjj450_eff->SetMarkerColor(kRed);
  mjj450_eff->SetLineColor(kRed);
  mjj450_eff->SetLineWidth(2);
  mjj450_eff->SetTitle("turnOn;Mjj [GeV]");
  TEfficiency* mjj200_eff = new TEfficiency("mjj200_eff","mjj200_eff",nBins,min,max);
  mjj200_eff->SetLineWidth(2);
  mjj200_eff->SetTitle("turnOn;Mjj [GeV]");
  TEfficiency* pf410_eff = new TEfficiency("pf410_eff","pf410_eff",nBins,min,max);
  pf410_eff->SetMarkerColor(kOrange+1);
  pf410_eff->SetLineColor(kOrange+1);
  TEfficiency* calo250_eff = new TEfficiency("calo250_eff","calo250_eff",nBins,min,max);
  calo250_eff->SetMarkerColor(kBlue);
  calo250_eff->SetLineColor(kBlue);
  TEfficiency* HTT240_eff = new TEfficiency("HTT240_eff","HTT240_eff",nBins,min,max);
  HTT240_eff->SetMarkerColor(kGreen+2);
  HTT240_eff->SetLineColor(kGreen+2);

  TH1F* l1 = new TH1F("l1","l1",14,0.,14.);
  TH1F* l2 = new TH1F("l2","l2",14,0.,14.);
  
  //loop
  for (Long64_t jentry=0; jentry<nentries;++jentry)
    {
      tt->GetEntry(jentry);

      //remove low rate lumis.
      //see: https://cmswbm2.web.cern.ch/cmswbm2/cmsdb/servlet/ChartHLTTriggerRates?RUNID=274200&PATHID=2043408&LSLENGTH=23.31040958&TRIGGER_PATH=DST_HT250_CaloScouting_v2
      //if(lumi > 539 && lumi < 553) continue;

      //l1 and hlt rates
      for(unsigned int ii=0; ii<l1Names->size(); ++ii)
	if (l1Accept->at(ii)==1)
	  l1->Fill(ii);
      
      
      //analysis cuts needed to compare to the analysis
      //calo analysis
      if (caloJet1Pt_ > 60. &&
	  caloJet2Pt_ > 30. &&
	  fabs(caloJet1Eta_) < 2.5 &&
	  fabs(caloJet2Eta_) < 2.5 &&
	  caloDeltaEta_ < 1.3)
	{
	  caloMjjSpectrum->Fill(caloMjj);
	  mjj200_eff->Fill((caloMjj>200 && l1Accept->at(L1scenario)==1) || hltAccept->at(HT250Calo)==1, caloMjj);
	  calo250_eff->Fill((hltAccept->at(HT250Calo)==1 && l1Accept->at(L1scenario)==1), caloMjj);

	  //references
	  HTT240_eff->Fill(l1Accept->at(HTT240)==1, caloMjj);
	  //l1 and hlt rates
	  for(unsigned int ii=0; ii<l1Names->size(); ++ii)
	    if (l1Accept->at(ii)==1)
	      l2->Fill(ii);
	}

      //PF analysis
      if (PFJet1Pt_ > 60. &&
	  PFJet2Pt_ > 30. &&
	  fabs(PFJet1Eta_) < 2.5 &&
	  fabs(PFJet2Eta_) < 2.5 &&
	  PFDeltaEta_ < 1.3)
	{
	  PFMjjSpectrum->Fill(PFMjj);
	  mjj450_eff->Fill((caloMjj>450 && l1Accept->at(L1scenario)==1) || hltAccept->at(HT410PF)==1, PFMjj);
	  pf410_eff->Fill((hltAccept->at(HT410PF)==1 && l1Accept->at(L1scenario)==1), PFMjj);
	}
    }

  mjj450_eff->Fit(f1,"r");
  mjj200_eff->Fit(f2,"r");


  caloMjjSpectrum->Scale(1./caloMjjSpectrum->GetBinContent(caloMjjSpectrum->GetMaximumBin()));
  PFMjjSpectrum->Scale(1./PFMjjSpectrum->GetBinContent(PFMjjSpectrum->GetMaximumBin()));

			      
  
  TLegend* leg0 = new TLegend(0.62, 0.78, 0.83, 0.89);
  leg0->AddEntry(mjj200_eff,"MJJ200Calo || HT250Calo","L");
  leg0->AddEntry(calo250_eff,"HT250_Calo","P");
  leg0->AddEntry(HTT240_eff,"HTT240","P");

  TLegend* leg1 = new TLegend(0.62, 0.78, 0.83, 0.89);
  leg1->AddEntry(mjj450_eff,"MJJ450PF || HT410PF","L");
  leg1->AddEntry(pf410_eff,"HT410_PF","P");

  TCanvas* c1 = new TCanvas();
  mjj200_eff->Draw();
  calo250_eff->Draw("sames");
  HTT240_eff->Draw("sames");
  caloMjjSpectrum->Draw("L,sames");
  leg0->Draw("sames");

  TCanvas* c2 = new TCanvas();
  mjj450_eff->Draw();
  pf410_eff->Draw("sames");
  PFMjjSpectrum->Draw("L,sames");
  leg1->Draw("sames");

  TCanvas* c3 = new TCanvas();
  //l1->Scale(PDRate/nentries);

  for(unsigned int ii=0; ii<l1Names->size(); ++ii)
    l1->GetXaxis()->SetBinLabel(ii+1,l1Names->at(ii).c_str());
  //l1->GetYaxis()->SetTitle("L1 Rate @4E33 [Hz]");
  l1->SetMaximum(l1->GetMaximum()+200);
  l2->SetLineColor(kRed);
  
  l1->Draw();
  l2->Draw("same");
  c3->Update();

  // TGaxis *l1axis = new TGaxis(gPad->GetUxmax(),gPad->GetUymin(),gPad->GetUxmax(), gPad->GetUymax(),
  // 			      l1->GetMinimum()*lumiScaleFactor,
  // 			      l1->GetMaximum()*lumiScaleFactor,510,"+L");

  // c2->SetTicky(0);
  // l1axis->SetLineColor(kRed);
  // l1axis->SetLabelColor(kRed);
  // l1axis->SetTextColor(kRed);
  // l1axis->SetTitleOffset(1.3);
  // l1axis->SetLabelSize(0.03);
  // l1axis->SetTitle("L1 Rate @1E34 [Hz]");
  // l1axis->Draw();
  
  
  //return 0;

  //##############################################
  //##############################################

  //book graphs and plots
  TGraphErrors* totRateVsCut = new TGraphErrors();
  totRateVsCut->SetMinimum(0);
  TGraphErrors* pureRateVsCut450 = new TGraphErrors();
  TGraphErrors* pureRateVsCut280 = new TGraphErrors();

  //loops
  int bin = 0;
  for (int cut = 350; cut < 500; cut=cut+10)
    {
      int mjjPassed = 0;
      int HT250Calo_Passed = 0;
      int excl410_passed = 0;
      int excl250_passed = 0;
      for (Long64_t jentry=0; jentry<nentries;++jentry) 
	{
	  tt->GetEntry(jentry);

	  if (hltAccept->at(HT250Calo) == 1)
	    ++HT250Calo_Passed;

	  //if (caloMjj > cut && !hltAccept->at(HT410PF))
	  if (caloMjj > cut && l1Accept->at(L1scenario) == 1 && hltAccept->at(HT410PF)==0)
	    ++excl410_passed;
	  if (caloMjj > cut && l1Accept->at(L1scenario)==1 && hltAccept->at(HT250Calo)==0)
	    ++excl250_passed;
	  if (caloMjj > cut && l1Accept->at(L1scenario)==1)
	    ++mjjPassed;

	  // if (hltAccept->at(HT250Calo) == 0 && mjj > cut)
	  //   std::cout << "ref trigger doesn't completely cover cut at " << cut << std::endl;
	}
      // float mjjTotalRate = (float)mjjPassed/(float)HT250Calo_Passed*HT250Calo_rate;
      // float mjjPureRate = (float)exclPassed/(float)HT250Calo_Passed*HT250Calo_rate;

      float sigmaMjjPassed = sqrt((float)mjjPassed);
      float sigmaNentries = sqrt((float)nentries);
      float sigmaExcl410_passed = sqrt((float)excl410_passed);
      float sigmaExcl250_passed = sqrt((float)excl250_passed);

      float mjjTotalRate = (float)mjjPassed/(float)nentries*PDRate;
      float mjjTotalRateE = PDRate*sqrt(pow((sigmaMjjPassed/nentries),2)+pow((sigmaNentries*mjjPassed/nentries/nentries),2));

      float mjj450_PureRate = (float)excl410_passed/(float)nentries*PDRate;
      float mjj450_PureRateE = PDRate*sqrt(pow((sigmaExcl410_passed/nentries),2)+pow((sigmaNentries*excl410_passed/nentries/nentries),2));
      
      float mjj280_PureRate = (float)excl250_passed/(float)nentries*PDRate;
      float mjj280_PureRateE = PDRate*sqrt(pow((sigmaExcl250_passed/nentries),2)+pow((sigmaNentries*excl250_passed/nentries/nentries),2));

      totRateVsCut->SetPoint(bin,cut,mjjTotalRate);
      totRateVsCut->SetPointError(bin,0.,mjjTotalRateE);

      pureRateVsCut450->SetPoint(bin,cut,mjj450_PureRate);
      pureRateVsCut450->SetPointError(bin,0.,mjj450_PureRateE);

      pureRateVsCut280->SetPoint(bin,cut,mjj280_PureRate);
      pureRateVsCut280->SetPointError(bin,0.,mjj280_PureRateE);

      ++bin;
    }

  //plotting and styling
  TLegend* leg = new TLegend(0.62, 0.78, 0.83, 0.89);
  leg->AddEntry(totRateVsCut,"total rate","P");
  leg->AddEntry(pureRateVsCut450,"pure rate wrt HT410PF","P");
  leg->AddEntry(pureRateVsCut280,"pure rate wrt HT250Calo","P");

  totRateVsCut->SetTitle("Rate Ref");

  totRateVsCut->GetXaxis()->SetTitle("Mjj cut threshold [GeV]");
  totRateVsCut->GetYaxis()->SetTitle("Rate @4E33 [Hz]");
  pureRateVsCut450->SetMarkerColor(kRed);
  pureRateVsCut450->SetLineColor(kRed);
  pureRateVsCut280->SetMarkerColor(kOrange+1);
  pureRateVsCut280->SetLineColor(kOrange+1);

  TCanvas* c4 = new TCanvas();
  c4->cd();
  totRateVsCut->Draw("AP");
  pureRateVsCut450->Draw("P,sames");
  pureRateVsCut280->Draw("P,sames");
  leg->Draw("sames");
  c4->Update();

  TGaxis *axis = new TGaxis(gPad->GetUxmax(),gPad->GetUymin(),gPad->GetUxmax(), gPad->GetUymax(),
    			    (totRateVsCut->GetYaxis()->GetBinLowEdge(1))*lumiScaleFactor,
			    (totRateVsCut->GetYaxis()->GetBinLowEdge(totRateVsCut->GetYaxis()->GetNbins())+totRateVsCut->GetYaxis()->GetBinWidth(1))*lumiScaleFactor,510,"+L");

  c4->SetTicky(0);
  axis->SetLineColor(kRed);
  axis->SetLabelColor(kRed);
  axis->SetTextColor(kRed);
  axis->SetTitleOffset(1.3);
  axis->SetLabelSize(0.03);
  axis->SetTitle("Rate @1E34 [Hz]");
  axis->Draw();


  return 0;
}
void plotVariable(string variable = "Elec_Fbrem",
		  const TString& category = "TauNoGammas",
		  const TString& xAxisTitle = "Fbrem",
		  const TString& yAxisTitle = "a.u.",
		  float xMin = -0.2, 
		  float xMax = 1,
		  int nBins = 100, 
		  int numPVMin = 0, 
		  int numPVMax = 50,
		  float PtMin = 10, 
		  float PtMax = 60,
		  const TString& Region = "Endcap"
		   )
{
   string discriminator = "";
//   string discriminator = "-AntiEMed";

  float AbsEtaMin = 0; 
  float AbsEtaMax = 3.0;
  if(Region == "Barrel"){
    AbsEtaMin = 0; 
    AbsEtaMax = 1.479;
  }
  if(Region == "Endcap"){
    AbsEtaMin = 1.479; 
    AbsEtaMax = 3.0;
  }
  TCanvas *c1 = new TCanvas("c1","",5,30,650,600);
  c1->SetGrid(0,0);
  c1->SetFillStyle(4000);
  c1->SetFillColor(10);
  c1->SetTicky();
  c1->SetObjectStat(0);

  gStyle->SetOptStat(0);
  gStyle->SetTitleFillColor(0);
  gStyle->SetCanvasBorderMode(0);
  gStyle->SetCanvasColor(0);
  gStyle->SetPadBorderMode(0);
  gStyle->SetPadColor(0);
  gStyle->SetTitleFillColor(0);
  gStyle->SetTitleBorderSize(0);
  gStyle->SetTitleH(0.07);
  gStyle->SetTitleFontSize(0.1);
  gStyle->SetTitleStyle(0);
  gStyle->SetTitleOffset(1.3,"y");

  TLegend* leg = new TLegend(0.6,0.75,0.8,0.88,NULL,"brNDC");
  leg->SetFillStyle(0);
  leg->SetBorderSize(0);
  leg->SetFillColor(10);
  leg->SetTextSize(0.03);
  //leg->SetHeader("#splitline{CMS Preliminary}{ #sqrt{s}=7 TeV}");

//   std::string inputFileName = "/data_CMS/cms/ivo/AntiEMVA/Trees/AntiEMVA_Fall11DYJetsToLL-iter4.root";
//   std::string inputFileName = "/data_CMS/cms/ivo/AntiEMVA/Trees/Trees_ForV4/AntiEMVA_AntiEMVATrees-DYJetsToLL-madgraph-PUS6.root";
  std::string inputFileName = "/data_CMS/cms/ivo/AntiEMVA/Trees/Trees_ForV4/AntiEMVA_V4.root";
  TFile* inputFile = new TFile (inputFileName.data(),"READ");
  if(inputFile->IsZombie()){
    cout << "No such file!" << endl;
    return;
  }
  TTree* inputTree = (TTree*)inputFile->Get("AntiEMVAAnalyzer2/tree");
//   TTree* inputTree = (TTree*)inputFile->Get("AntiEMVAAnalyzer/tree");
  std::vector<TH1*> histograms;

  std::vector<std::string> matchings ; 
  matchings.push_back("GenHadMatch");
  matchings.push_back("GenEleMatch");

  for ( std::vector<std::string>::const_iterator matching = matchings.begin();
	matching  != matchings.end(); ++matching ) {


    TCut PUSelection(Form("NumPV>%i && NumPV<%i",numPVMin,numPVMax));
    TCut ElecPtSelection (Form("Elec_Pt>%0f && Elec_Pt<%0f",PtMin,PtMax));
    TCut TauPtSelection (Form("Tau_Pt>%0f && Tau_Pt<%0f",PtMin,PtMax));
    TCut ElecAbsEtaSelection (Form("Elec_AbsEta>%0f && Elec_AbsEta<%0f",AbsEtaMin,AbsEtaMax));
    TCut TauAbsEtaSelection = "";
    if(Region == "Barrel"){
      TauAbsEtaSelection = "Tau_Eta>-1.479 && Tau_Eta<1.479";
    }
    if(Region == "Endcap"){
      TauAbsEtaSelection = "(Tau_Eta>1.479 && Tau_Eta<3.0) || (Tau_Eta>-3.0 && Tau_Eta<-1.479)";
    }
    //   TCut TauAbsEtaSelection (Form("Tau_AbsEta>%0f && Tau_AbsEta<%0f",AbsEtaMin,AbsEtaMax));
    TCut ElecMatchSelection (Form("Elec_%s == 1",matching->data()));
    //   TCut ElecMatchSelection (Form("Elec_PFTauMatch && Elec_%s",matching->data()));
    TCut TauMatchSelection (Form("Tau_%s",matching->data()));
    TCut CategorySelection = "";
    if(discriminator == ""){
      if (category == "NoEleMatch") CategorySelection = "Tau_GsfEleMatch<0.5"; 
      if (category == "woG") CategorySelection = "Tau_NumGammaCands<0.5"; 
      if (category == "wGwoGSF") CategorySelection = "Tau_NumGammaCands>0.5 && Tau_HasGsf<0.5";
      if (category == "wGwGSFwoPFMVA")CategorySelection = "Tau_NumGammaCands>0.5 && Tau_HasGsf>0.5 && Elec_PFMvaOutput<-0.1";
      if (category == "wGwGSFwPFMVA")CategorySelection = "Tau_NumGammaCands>0.5 && Tau_HasGsf>0.5 && Elec_PFMvaOutput>-0.1";
    }

    if(discriminator == "-AntiEMed"){
      if (category == "NoEleMatch") CategorySelection = "Tau_GsfEleMatch<0.5"; 
      if (category == "woG") CategorySelection = "Tau_NumGammaCands<0.5"; 
      if (category == "wGwoGSF") CategorySelection = "Tau_NumGammaCands>0.5 && (Tau_HasGsf<0.5 || (Tau_HasGsf>0.5 && Elec_PFMvaOutput>-0.1))";
      if (category == "wGwGSFwoPFMVA")CategorySelection = "Tau_NumGammaCands>0.5 && Tau_HasGsf>0.5 && Elec_PFMvaOutput<-0.1";
    }

  TCut ElecSelection = CategorySelection && PUSelection && ElecPtSelection && ElecAbsEtaSelection && ElecMatchSelection ;
  TCut TauSelection = CategorySelection && PUSelection && TauPtSelection && TauAbsEtaSelection && TauMatchSelection ;
  TCut Selection;
  if (variable.find("Elec")!=std::string::npos)Selection = ElecSelection;
  if (variable.find("Tau")!=std::string::npos)Selection = TauSelection;
  

  TH1F* hVariable   = new TH1F( "hVariable" ,"" , nBins ,xMin, xMax);
  hVariable->SetXTitle(Form("%s",variable.data()));

  if (matching->find("EleMatch")!=std::string::npos){
//     hVariable->SetFillColor(kRed);
//     hVariable->SetFillStyle(3345);
    hVariable->SetLineColor(kRed);
    hVariable->SetLineWidth(2);
  }
  if (matching->find("HadMatch")!=std::string::npos){
//     hVariable->SetFillColor(kBlue);
//     hVariable->SetFillStyle(3354);
    hVariable->SetLineColor(kBlue);
    hVariable->SetLineWidth(2);
  }  
  inputTree->Draw(Form("%s>>hVariable",variable.data()));

  cout<<"Variable plotted : "<<variable<<endl;
  cout<<"Matching applied : "<<matching->data()<<endl;
  cout<<"  Total number of Candidates : "<<hVariable->GetEntries()<<endl;
  inputTree->Draw(Form("%s>>hVariable",variable.data()),Selection);
  cout<<"  Number of Cantidates after selection: "<<hVariable->GetEntries()<<endl;
  hVariable->Scale(1./hVariable->Integral());
  leg->AddEntry(hVariable,Form("%s",matching->data()));

  histograms.push_back(hVariable);
  c1->Clear();
  }
//   double yMin = +1.e+6;
//   double yMax = -1.e+6;
  TH1* refHistogram = histograms.front();
  refHistogram->SetStats(false);
  refHistogram->SetTitle("");
//   refHistogram->SetMinimum(yMin);
//   refHistogram->SetMaximum(yMax);


  if (xAxisTitle == "HoHplusE" ) {
    refHistogram->SetMaximum(1.0);
    refHistogram->SetMinimum(0.01);
    c1->SetLogy();
  }

  if(xAxisTitle == "E_{#gamma}/(P_{in}-P_{out})" ){
    refHistogram->SetMaximum(0.03);
    refHistogram->SetMinimum(0.0);
  }

  if(xAxisTitle == "HadrMva(#tau)" ){
    refHistogram->SetMaximum(0.25);
    refHistogram->SetMinimum(0.0);
  }

  TAxis* xAxis = refHistogram->GetXaxis();
  xAxis->SetTitle(xAxisTitle.Data());
  xAxis->SetTitleOffset(1.15);
  //if(variable.find("AbsEta")!=std::string::npos)xAxis->SetLimits(AbsEtaMin, AbsEtaMax);
  TAxis* yAxis = refHistogram->GetYaxis();
  yAxis->SetTitle(yAxisTitle.Data());
  yAxis->SetTitleOffset(1.30);

  int numHistograms = histograms.size();
  float YMax = 0;
  for ( int iHistogram = 0; iHistogram < numHistograms; ++iHistogram ) {
    TH1* histogram = histograms[iHistogram];
    if(histogram->GetMaximum()>YMax) YMax = histogram->GetMaximum();
  }
  for ( int iHistogram = 0; iHistogram < numHistograms; ++iHistogram ) {
    TH1* histogram = histograms[iHistogram];
    yAxis->SetRangeUser(0.,YMax+0.10*YMax);
    std::string drawOption = "hist";
    if ( iHistogram > 0 ) drawOption.append("same");
    histogram->Draw(drawOption.data());
    leg->Draw();

  }//loop matchings
  string outputName = Form("plots/plotVariablesAntiEMVA/%s/plotVariablesAntiEMVA_v4_%s_%s_%s",category.Data(),category.Data(),variable.data(),Region.Data());
  c1->Print(std::string(outputName).append(".png").data());
  c1->Print(std::string(outputName).append(".pdf").data());

}
Example #12
0
void test_msv(std::string var="m_sv",int nbins=25, double xmin=0, double xmax=250,std::string xtitle="m_sv", std::string ytitle="Events")
{
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");
  TH1::SetDefaultSumw2(1);

  std::string dir = "/afs/cern.ch/work/a/arapyan/public/svfitsamples/";
  double sigscale = 10;
  double sigscale1 = 10; 
  std::stringstream scale; scale << sigscale;
  std::stringstream scale1; scale1 << sigscale1;

  //Cut definitions
  double luminosity = 3000;
  std::stringstream lumi; lumi << luminosity;
  std::string objcut = "(ptTau1>30 && ptTau2>30 && abs(etaTau1) <4.0 && abs(etaTau1)<4.0 )";
  //std::string jetcut = objcut+"*(ptJet1>30 && ptJet2>30 && abs(etaJet1) <4.7 && abs(etaJet2) <4.7 )";
  std::string mthcut = objcut+"*( ( (tauCat1==3 && tauCat2==2) || (tauCat2==3 && tauCat1==2) ) )";

  //signal region
  //std::string vbfcut = ththcut+"*eventWeight*(eventType==0)*"+lumi.str();
  //std::string zttcut = ththcut+"*eventWeight*(eventType==1)*"+lumi.str();
  //std::string ttbarcut = ththcut+"*eventWeight*(eventType==3)*"+lumi.str();
  //std::string ewkcut = ththcut+"*eventWeight*(eventType==2)*"+lumi.str();
  //std::string othercut = ththcut+"*eventWeight*(eventType==4 || eventType==2)*"+lumi.str();
  
  //--------------------------------------------------------------------------
  
  //Get the trees
  TTree *tree = load(dir+"hh.root"); 
  TTree *tree2 = load(dir+"Bjj-vbf.root"); 
  TTree *tree3 = load(dir+"vbf_bgd.root"); 

  //-------------------------------------------------------------------------
  
  //Get histograms
  TCanvas *canv0 = MakeCanvas("canv", "histograms", 600, 600);
  canv0->cd();
  std::string vardraw;
  TH1F *vbf = new TH1F("VBFH","",nbins,xmin,xmax);
  vardraw = var+">>"+"VBFH";
  tree->Draw(vardraw.c_str(),mthcut.c_str());
  InitSignal(vbf);
  vbf->SetLineColor(kBlack);
  //TH1F *ttbar = new TH1F("TTbar","",nbins,xmin,xmax);
  //vardraw = var+">>"+"TTbar";
  //tree->Draw(vardraw.c_str(),ttbarcut.c_str());
  //InitHist(ttbar, xtitle.c_str(), ytitle.c_str(), TColor::GetColor(155,152,204), 1001);
  TH1F *ztt = new TH1F("Ztt","",nbins,xmin,xmax);
  vardraw = var+">>"+"Ztt";
  tree2->Draw(vardraw.c_str(),mthcut.c_str());
  InitHist(ztt, xtitle.c_str(), ytitle.c_str(), TColor::GetColor(248,206,104), 1001);
  //TH1F *ewk = new TH1F("Ewk","",nbins,xmin,xmax);
  //vardraw = var+">>"+"Ewk";
  //tree->Draw(vardraw.c_str(),ewkcut.c_str());
  //InitHist(ewk, xtitle.c_str(), ytitle.c_str(),  TColor::GetColor(222,90,106), 1001);
  TH1F *other = new TH1F("Other","",nbins,xmin,xmax);
  vardraw = var+">>"+"Other";
  tree3->Draw(vardraw.c_str(),mthcut.c_str());
  InitHist(other, xtitle.c_str(), ytitle.c_str(),  TColor::GetColor(222,90,106), 1001);
  
  delete canv0;

  //----------------------------------------------------------------------------
  //Print out the yields
  /*  Double_t error=0.0;
  ofstream outfile;
  outfile.open("yields_test.txt");
  outfile << "Yields for the signal region." << std::endl;
  outfile << "VBF   "  << vbf->IntegralAndError(0,vbf->GetNbinsX(),error) << "+/-" << error << endl;
  outfile << "TTbar   "  << ttbar->IntegralAndError(0,ttbar->GetNbinsX(),error) << "+/-" << error << endl;
  outfile << "Ztt    "  << ztt->IntegralAndError(0,ztt->GetNbinsX(),error) << "+/-" << error << endl;
  //outfile << "ewk    "  << ewk->IntegralAndError(0,ewk->GetNbinsX(),error) << "+/-" << error << endl;
  outfile << "other   "  << other->IntegralAndError(0,other->GetNbinsX(),error) << "+/-" << error << endl;
  outfile << "S/sqrt(B)    "  << vbf->Integral()/(other->Integral()+ztt->Integral()+ttbar->Integral()) << endl;
  //--------------------------------------------------------------------------
  //continue outputing
  //outfile << "Ewk total    "  << ewk->IntegralAndError(0,ewk->GetNbinsX(),error) << "+/-" << error << endl;
  outfile << endl << endl << endl;
  outfile << "In the signal region (100,150GeV)  " <<endl;
  outfile << "VBF   "  << vbf->IntegralAndError(5,11,error) << "+/-" << error << endl;
  outfile << "TTbar    "  << ttbar->IntegralAndError(5,11,error) << "+/-" << error << endl;
  outfile << "Ztt    "  << ztt->IntegralAndError(5,11,error) << "+/-" << error << endl;
  //outfile << "ewk    "  << ewk->IntegralAndError(5,11,error) << "+/-" << error << endl;
  outfile << "other    "  << other->IntegralAndError(5,11,error) << "+/-" << error << endl;
  outfile.close();*/
  //-----------------------------------------------------------------------
  //Draw the histograms
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);
  canv->cd();
  //ewk->Add(other); ttbar->Add(ewk); 
  //ztt->Add(ttbar); vbf->Add(ztt);
  other->Add(ztt);
  //Error band stat
  TH1F* errorBand = (TH1F*)vbf ->Clone("errorBand");
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(13);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  //  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
  //     if(errorBand->GetBinContent(idx)>0){
  //       std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
  //       break;
  //     }
  //}
  Float_t n=other->GetEntries();
  other->Scale(1.0/n);
  n=vbf->GetEntries();
  vbf->Scale(1.0/n);
  //for (Int_t i=1; i<nbins+1; i++) {
  //cout << "i: " << i << " " <<  other->GetBinCenter(i) << " " << other->Integral(0,i) << " " << other->Integral(i,nbins+1) << endl;
  //}
  cout << " other " << other->Integral(10,15) << endl;
  cout << " htt " << vbf->Integral(10,15) << endl;
  //n=ztt->GetEntries();
  //ztt->Scale(1.0/n);
  other->SetMaximum(1.2*std::max(maximum(vbf, 0), maximum(other, 0)));
  //blind(vbf,75,150);
  //ttbar->Draw("histsame");
  //ewk->Draw("histsame");
  other->Draw("hist");
  //ztt->Draw("histsame");
  vbf->Draw("histsame");
  //errorBand->Draw("e2same");
  canv->RedrawAxis();
  //---------------------------------------------------------------------------
  //Adding a legend
  TLegend* leg = new TLegend(0.53, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(vbf , "HH"             , "F");
  //leg->AddEntry(ztt  , "bjj-vbf"  , "F" );
  //leg->AddEntry(ttbar, "t#bar{t}"              , "F" );
  //leg->AddEntry(ewk  , "Electroweak"           , "F" );
  leg->AddEntry(other, "Other"                 , "F" );
  //leg->AddEntry(errorBand,"bkg. uncertainty","F");
  leg->Draw();
  //---------------------------------------------------------------------------

  //CMS preliminary 
  const char* dataset = "CMS Preliminary, H#rightarrow#tau#tau, 3.0 ab^{-1} at 14 TeV";
  const char* category = "";
  CMSPrelim(dataset, "#mu#tau_{h}", 0.17, 0.835);
  //CMSPrelim(dataset, "", 0.16, 0.835);
  TPaveText* chan     = new TPaveText(0.52, 0.35, 0.91, 0.55, "tlbrNDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText(category);
  chan->Draw();
  //-------------------------------------------------------------------------
  //Save histograms
  canv->Print((var+"_test.png").c_str());

}
Example #13
0
void draw_prefit_Sample(std::string inputF, std::string channel, int MaxY, std::string xTitle, std::string nameHisto) {

    //    gStyle->SetOptStat(0);


    SetStyle();
    //    InitSubPad
    TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);
    float SIGNAL_SCALE = 10;
    bool scaled = true;
    bool log = false;

    TFile* input = new TFile(inputF.c_str());
    //cout<<"1";

    const char* dataset;


    //    std::string channel = "muTau_btag/";
    //    std::string channel = "eleTau_inclusive/";
    THStack hs("hs", "");
    TH1F* data = (TH1F*) input->Get((channel + "data_obs").c_str());
    TH1F* zero = (TH1F*) data->Clone("zero");


    TH1F* QCD = (TH1F*) input->Get((channel + "QCD").c_str());
    InitHist(QCD, "", "", TColor::GetColor(250, 202, 255), 1001);
    hs.Add(QCD);



    TH1F* W = (TH1F*) input->Get((channel + "W").c_str());
    InitHist(W, "", "", 46, 1001);

    TH1F* ZJ = (TH1F*) input->Get((channel + "ZJ").c_str());
//    InitHist(ZJ, "", "", TColor::GetColor(100, 182, 232), 1001);
    W->Add(ZJ);

    TH1F* ZL = (TH1F*) input->Get((channel + "ZL").c_str());
//    InitHist(ZL, "", "", TColor::GetColor(100, 182, 232), 1001);
    W->Add(ZL);


    TH1F* VV = (TH1F*) input->Get((channel + "VV").c_str());
//    InitHist(VV, "", "", TColor::GetColor(100, 182, 232), 1001);
    W->Add(VV);

    hs.Add(W);
    ////    TH1F* ZLL = (TH1F*) input->Get((channel +"ZLL");
    //    InitHist(ttbar, "", "", TColor::GetColor(155, 152, 204), 1001);

    TH1F* TT = (TH1F*) input->Get((channel + "TT").c_str());
    InitHist(TT, "", "", 9, 1001);
    hs.Add(TT);

    TH1F* ZTT = (TH1F*) input->Get((channel + "ZTT").c_str());
    InitHist(ZTT, "", "", TColor::GetColor(248, 206, 104), 1001);

    TH1F* ZTTLow = (TH1F*) input->Get((channel + "ZTT_lowMass").c_str());
    InitHist(ZTTLow, "", "", TColor::GetColor(248, 206, 104), 1001);

    ZTT->Add(ZTTLow);

    hs.Add(ZTT);
    

    InitData(data);

    TH1F* signal = (TH1F*) input->Get((channel + "bba150").c_str());
    signal->Scale(10);
    InitSignal(signal);
    //    signal->SetFillColor(kGreen);
    //    signal->SetLineColor(kGreen);
    hs.Add(signal);


    canv->cd();

    //    const char * MMM = xTitle.c_str();
    //    hs.GetXaxis()->SetLabelSize(9);
    zero->Scale(0);
    zero->GetXaxis()->SetRangeUser(0,60);
    zero->GetXaxis()->SetTitle(xTitle.c_str());
    zero->SetMaximum(MaxY);
    zero->Draw();

    hs.Draw("hsame");
    data->SetBinContent(1,0);
    data->SetBinContent(2,0);
    data->SetBinContent(3,0);
    data->SetBinContent(4,0);
    data->SetBinContent(5,0);
    data->SetBinContent(6,0);
    data->SetBinContent(7,0);
    data->SetBinContent(8,0);
    data->SetBinContent(9,0);
    data->SetBinContent(10,0);
    data->SetBinContent(11,0);
    data->SetBinContent(12,0);
    data->SetBinContent(13,0);
    data->Draw("PEsame");


    const char* dataset;
    dataset = "CMS Preliminary,  bba1#rightarrow#tau#tau, 19.7 fb^{-1} at 8 TeV";
    CMSPrelim(dataset, "", 0.17, 0.835);



    TLegend* leg = new TLegend(0.62, 0.58, 0.92, 0.89);
    SetLegendStyle(leg);
    leg->AddEntry(signal, TString::Format("a1(50 GeV)#rightarrow#tau#tau [XS= 10 bp]", SIGNAL_SCALE), "L");



    leg->AddEntry(data, "observed", "LP");
    leg->AddEntry(ZTT, "Z#rightarrow#tau#tau", "F");
    leg->AddEntry(TT, "t#bar{t}", "F");
    leg->AddEntry(W, "electroweak", "F");
    leg->AddEntry(QCD, "QCD", "F");
    leg->Draw();

//    canv->Print(TString::Format( (nameHisto+".pdf").c_str()));
//    canv->Print(TString::Format( (nameHisto+".root").c_str()));
    canv->Print(TString::Format( (nameHisto+"_Low_.pdf").c_str()));
    canv->Print(TString::Format( (nameHisto+"_Low_.root").c_str()));
}
Example #14
0
void fitM3()
{

	// LOAD HISTOGRAMS FROM FILES
	/////////////////////////////////
	TH1F *hTTjets;
	TH1F *hWjets;
	TH1F *hM3;
	TH1F *hZjets;
	TH1F *hQCD;
	TH1F *hST_s;
	TH1F *hST_t;
	TH1F *hST_tW;

	// histograms from nonimal sample
	///////////
	
	TFile *infile0 = TFile::Open("nominal_IPsig3_Iso95/TopAnalysis_TTJets-madgraph_Fall08_all_all.root");
	//TFile *infile0 = TFile::Open("nominal_IPsig3_Iso95/TopAnalysis_TauolaTTbar.root");
	hTTjets = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");
	
	TFile *infile1 = TFile::Open("nominal_IPsig3_Iso95/TopAnalysis_WJets_madgraph_Fall08_all.root");
	hWjets = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");
	
	TFile *infile1Fast = TFile::Open("nominal_IPsig3_Iso95_Fast/TopAnalysis_Wjets_madgraph_Winter09_v2_all.root");
	hWjetsFast = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileZ = TFile::Open("nominal_IPsig3_Iso95/TopAnalysis_ZJets_madgraph_Fall08_all.root");
	hZjets = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");
	TFile *infileZFast = TFile::Open("nominal_IPsig3_Iso95_Fast/TopAnalysis_Zjets_madgraph_Winter09_v2_all.root");
	hZjetsFast = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileST_s = TFile::Open("nominal_IPsig3_Iso95/TopAnalysis_ST_s.root");
	hST_s = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileST_t = TFile::Open("nominal_IPsig3_Iso95/TopAnalysis_ST_t.root");
	hST_t = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileST_tW = TFile::Open("nominal_IPsig3_Iso95/TopAnalysis_ST_tW.root");
	hST_tW = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileQCD = TFile::Open("nominal_IPsig3_Iso95/TopAnalysis_InclusiveMuPt15_Summer08_all.root");
	hQCD = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	// histograms from systematic samples
	//////////
	TFile *infile0S = TFile::Open("nominal_JESUp/TopAnalysis_TTJets-madgraph_Fall08_all_all.root");
	hTTjetsS = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");
		
	TFile *infile1S = TFile::Open("nominal_JESUp/TopAnalysis_WJets_madgraph_Fall08_all.root");// from FullSim
	hWjetsS = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	//TFile *infile1SF = TFile::Open("nominal_JESUp_Fast/TopAnalysis_WJets_madgraph_Fall08_all.root");// from FastSim
	//TFile *infile1SF = TFile::Open("nominal_IPsig3_Iso95_Fast/TopAnalysis_Wjets_ScaleUp_madgraph_Winter09_all.root");
	TFile *infile1SF = TFile::Open("nominal_IPsig3_Iso95_Fast/TopAnalysis_WJets_Threshold20GeV_madgraph_Winter09_all.root");
	hWjetsSFast = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileZS = TFile::Open("nominal_JESUp/TopAnalysis_ZJets_madgraph_Fall08_all.root");// from FullSim
	hZjetsS = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileZSF = TFile::Open("nominal_JESUp_Fast/TopAnalysis_ZJets_madgraph_Fall08_all.root");// from FullSim
	hZjetsSFast = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileST_sS = TFile::Open("nominal_JESUp/TopAnalysis_ST_s.root");
	hST_sS = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileST_tS = TFile::Open("nominal_JESUp/TopAnalysis_ST_t.root");
	hST_tS = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileST_tWS = TFile::Open("nominal_JESUp/TopAnalysis_ST_tW.root");
	hST_tWS = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileQCDS = TFile::Open("nominal_JESUp/TopAnalysis_InclusiveMuPt15_Summer08_all.root");//
	hQCDS = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");
	
	//TFile *infileQCD_CS = TFile::Open("nominal_antiMuon/TopAnalysis_InclusiveMuPt15_Summer08_all.root");
	//hQCD_CS = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	// write templates to file
	//TFile *outfile = TFile::Open("templates.root","RECREATE");
	//hTTjets->Write("ttbar");
	//hWjets->Write("Wjets");
	//outfile->Close();

	// Add over/underflow bins if requested
	bool UseOverflow = true;
	bool UseUnderflow = true;
	
	if (UseOverflow) {
		int maxbin=hTTjets->GetNbinsX();
	
		hTTjets->SetBinContent(maxbin,    hTTjets->GetBinContent(maxbin+1)+hTTjets->GetBinContent(maxbin) );
		hWjets->SetBinContent(maxbin,     hWjets->GetBinContent(maxbin+1)+hWjets->GetBinContent(maxbin) );
		hWjetsFast->SetBinContent(maxbin, hWjetsFast->GetBinContent(maxbin+1)+hWjetsFast->GetBinContent(maxbin) );
		hZjets->SetBinContent(maxbin,     hZjets->GetBinContent(maxbin+1)+hZjets->GetBinContent(maxbin) );
		hZjetsFast->SetBinContent(maxbin, hZjetsFast->GetBinContent(maxbin+1)+hZjetsFast->GetBinContent(maxbin) );
		hQCD->SetBinContent(maxbin,       hQCD->GetBinContent(maxbin+1)+hQCD->GetBinContent(maxbin) );
		//hQCD_CS->SetBinContent(maxbin, hQCD_CS->GetBinContent(maxbin+1)+hQCD_CS->GetBinContent(maxbin) );
		hST_s->SetBinContent(maxbin,      hST_s->GetBinContent(maxbin+1)+hST_s->GetBinContent(maxbin) );
		hST_t->SetBinContent(maxbin,      hST_t->GetBinContent(maxbin+1)+hST_t->GetBinContent(maxbin) );
		hST_tW->SetBinContent(maxbin,     hST_tW->GetBinContent(maxbin+1)+hST_tW->GetBinContent(maxbin) );
	}
	//underflow bin
	if (UseUnderflow) {
		int maxbin=1;
		hTTjets->SetBinContent(maxbin,    hTTjets->GetBinContent(maxbin-1)+hTTjets->GetBinContent(maxbin) );
		hWjets->SetBinContent(maxbin,     hWjets->GetBinContent(maxbin-1)+hWjets->GetBinContent(maxbin) );
		hWjetsFast->SetBinContent(maxbin, hWjetsFast->GetBinContent(maxbin-1)+hWjetsFast->GetBinContent(maxbin) );
		hZjets->SetBinContent(maxbin,     hZjets->GetBinContent(maxbin-1)+hZjets->GetBinContent(maxbin) );
		hZjetsFast->SetBinContent(maxbin, hZjetsFast->GetBinContent(maxbin-1)+hZjetsFast->GetBinContent(maxbin) );
		hQCD->SetBinContent(maxbin,       hQCD->GetBinContent(maxbin-1)+hQCD->GetBinContent(maxbin) );
		//hQCD_CS->SetBinContent(maxbin, hQCD_CS->GetBinContent(maxbin-1)+hQCD_CS->GetBinContent(maxbin) );
		hST_s->SetBinContent(maxbin,      hST_s->GetBinContent(maxbin-1)+hST_s->GetBinContent(maxbin) );
		hST_t->SetBinContent(maxbin,      hST_t->GetBinContent(maxbin-1)+hST_t->GetBinContent(maxbin) );
		hST_tW->SetBinContent(maxbin,     hST_tW->GetBinContent(maxbin-1)+hST_tW->GetBinContent(maxbin) );
	}
	//syst.
	if (UseOverflow) {
		int maxbin=hTTjetsS->GetNbinsX();
		hTTjetsS->SetBinContent(maxbin,    hTTjetsS->GetBinContent(maxbin+1)+hTTjetsS->GetBinContent(maxbin) );
		hWjetsS->SetBinContent(maxbin,     hWjetsS->GetBinContent(maxbin+1)+hWjetsS->GetBinContent(maxbin) );
		hWjetsSFast->SetBinContent(maxbin, hWjetsSFast->GetBinContent(maxbin+1)+hWjetsSFast->GetBinContent(maxbin) );
		hZjetsS->SetBinContent(maxbin,     hZjetsS->GetBinContent(maxbin+1)+hZjetsS->GetBinContent(maxbin) );
		hZjetsSFast->SetBinContent(maxbin, hZjetsSFast->GetBinContent(maxbin+1)+hZjetsSFast->GetBinContent(maxbin) );
		hQCDS->SetBinContent(maxbin,       hQCDS->GetBinContent(maxbin+1)+hQCDS->GetBinContent(maxbin) );
		hST_sS->SetBinContent(maxbin,      hST_sS->GetBinContent(maxbin+1)+hST_sS->GetBinContent(maxbin) );
		hST_tS->SetBinContent(maxbin,      hST_tS->GetBinContent(maxbin+1)+hST_tS->GetBinContent(maxbin) );
		hST_tWS->SetBinContent(maxbin,     hST_tWS->GetBinContent(maxbin+1)+hST_tWS->GetBinContent(maxbin) );
	}
	if (UseUnderflow) {
		//underflow bin
		int maxbin=1;
		hTTjetsS->SetBinContent(maxbin,    hTTjetsS->GetBinContent(maxbin-1)+hTTjetsS->GetBinContent(maxbin) );
		hWjetsS->SetBinContent(maxbin,     hWjetsS->GetBinContent(maxbin-1)+hWjetsS->GetBinContent(maxbin) );
		hWjetsSFast->SetBinContent(maxbin, hWjetsSFast->GetBinContent(maxbin-1)+hWjetsSFast->GetBinContent(maxbin) );
		hZjetsS->SetBinContent(maxbin,     hZjetsS->GetBinContent(maxbin-1)+hZjetsS->GetBinContent(maxbin) );
		hZjetsSFast->SetBinContent(maxbin,     hZjetsSFast->GetBinContent(maxbin-1)+hZjetsSFast->GetBinContent(maxbin) );
		hQCDS->SetBinContent(maxbin,       hQCDS->GetBinContent(maxbin-1)+hQCDS->GetBinContent(maxbin) );
		hST_sS->SetBinContent(maxbin,      hST_sS->GetBinContent(maxbin-1)+hST_sS->GetBinContent(maxbin) );
		hST_tS->SetBinContent(maxbin,      hST_tS->GetBinContent(maxbin-1)+hST_tS->GetBinContent(maxbin) );
		hST_tWS->SetBinContent(maxbin,     hST_tWS->GetBinContent(maxbin-1)+hST_tWS->GetBinContent(maxbin) );
	}
	
	// scale histograms to 20/pb

	hTTjets->Scale(0.0081); // madgraph
	//hTTjets->Scale(0.0777);//Tauola
	hWjets->Scale(0.0883);
	//hWjetsFast->Scale(0.0091); //fastsim
	hWjetsFast->Scale(hWjets->Integral() / hWjetsFast->Integral()); // scale to FullSim
		
	hZjets->Scale(0.0731);
	hZjetsFast->Scale(hZjets->Integral()/hZjetsFast->Integral()); //scale to FullSim
	hQCD->Scale(0.4003);
	hQCD_WFast = (TH1F*) hWjetsFast->Clone("hQCD_WFast"); //take shape from Wjets
	hQCD_WFast->Scale(hQCD->Integral()/hQCD_WFast->Integral()); //scale to FullSim
	hST_t->Scale(0.003);
	hST_s->Scale(0.0027);
	hST_tW->Scale(0.0034);

	hTTjetsS->Scale(0.0081); // 
	//hTTjetsS->Scale(0.0008); // for fastsim
	hWjetsS->Scale(0.0883);
	//hWjetsS->Scale(0.0091);// from fastsim
	//hWjetsSFast->Scale(hWjetsS->Integral() / hWjetsSFast->Integral()); // scale to FullSim
	//hWjetsSFast->Scale(0.6642); // scaleUP
	//hWjetsSFast->Scale(0.8041); // scaleDown
	//hWjetsSFast->Scale(0.0605); // threshold 5gev
	hWjetsSFast->Scale(0.042); // threshold 20gev
	
	hZjetsS->Scale(0.0731);
	//hZjetsS->Scale(0.0085);// from fastsim
	hZjetsSFast->Scale(hZjetsS->Integral() / hZjetsSFast->Integral()); // scale to FullSim
	hQCDS->Scale(0.4003);
	//hQCDS_WFast = (TH1F*) hWjetsS->Clone("hQCDS_WFast");
	//hQCDS_WFast->Scale(hQCDS->Integral()/hQCDS_WFast->Integral());
	hST_tS->Scale(0.003);
	hST_sS->Scale(0.0027);
	hST_tWS->Scale(0.0034);
	
	cout << " N expected ttbar+jets events = " << hTTjets->Integral() << endl;
	cout << " N expected W+jets     events = " << hWjets->Integral()  << endl;
	cout << " N expected Z+jets     events = " << hZjets->Integral()  << endl;
	cout << " N expected ST s       events = " << hST_s->Integral()  << endl;
	cout << " N expected ST t       events = " << hST_t->Integral()  << endl;
	cout << " N expected ST tW      events = " << hST_tW->Integral()  << endl;
	cout << " N expected qcd        events = " << hQCD->Integral()  << endl;

	cout << endl;
	cout << " N expected W+jets fast = " << hWjetsFast->Integral() << endl;
	cout << " N expected z+jets fast = " << hZjetsFast->Integral() << endl;
	cout << " N expected qcd Wfast = " << hQCD_WFast->Integral() << endl;

	cout << "\n systematics: " << endl;
	cout << " N expected W+jets fast = " << hWjetsSFast->Integral() << endl;
	cout << " N expected z+jets fast = " << hZjetsS->Integral() << endl;
	cout << " N expected qcd Wfast = " << hQCDS->Integral() << endl;

	// add all three single top samples

	// for systematics
	//hST_t->Scale(2.);
	
	hST_t->Add(hST_s);
	hST_t->Add(hST_tW);
	cout << " number of ST = " << hST_t->Integral() << endl;
	// syst. uncertainty in single top
	//double tmpST = 0.6* hST_t->Integral();
	//hST_t->Scale(0.6);
	//cout << tmpST << endl;
	cout << " New number of ST = " << hST_t->Integral() << endl;
	
	hST_tS->Add(hST_sS);
	hST_tS->Add(hST_tWS);

	// dump scaled histograms in root file
	//TFile *output = TFile::Open("fitM3.root","RECREATE");
	//hTTjets->SetName("ttbar");hTTjets->Write();
	//hWjetsFast->SetName("WjetsFast");hWjetsFast->Write();
	//hST_t->SetName("ST");hST_t->Write();
	//output->Close();
	
		
	hM3 = (TH1F*) hTTjets->Clone("hM3");
	hM3->Add(hWjets);
	hM3->Add(hZjets);
	hM3->Add(hQCD);
	hM3->Add(hST_t);
	
	int Nbins = hM3->GetNbinsX();
	
	// --- Observable ---
        
	RooRealVar mass("mass","M3'(#chi^{2})",100,500,"GeV/c^{2}") ; 
	RooRealVar Ntt("Ntt","number of t#bar{t} events", hTTjets->Integral(), -100 , 1000);
    RooRealVar NW("NW","number of W+jets events", hWjetsFast->Integral(), -500 , 1000);
	RooRealVar NST("NST","number of single top events", hST_t->Integral(), -500,100);
	RooRealVar NZjets("NZjets","number of Z+jets events", hZjetsS->Integral(), -500,500);
	RooRealVar Nqcd("Nqcd","number of QCD events", hQCD_WFast->Integral(), -500,100);
	//RooRealVar Nbkg("Nbkg","number of bkg events", hWjetsFast->Integral()+hST_t->Integral()+hZjetsFast->Integral()+hQCD_WFast->Integral(), -500 , 1000);
	//RooRealVar Nbkg("Nbkg","number of W+jets events", hWjets->Integral(), -500 , 1000); // 2 templates

	RooRealVar Nbkg("Nbkg","number of bkg events", hWjetsFast->Integral()+hZjets->Integral()+hQCD_WFast->Integral(), -500 , 1000);
	//RooRealVar Nbkg("Nbkg","number of bkg events", hWjetsFast->Integral(), -500 , 1000);
	
	// for systematics
	//RooRealVar Nbkg("Nbkg","number of bkg events", hWjetsSFast->Integral()+hZjetsS->Integral()+hQCDS->Integral(), -500 , 1000);
	//RooRealVar Nbkg("Nbkg","number of bkg events", hWjetsSFast->Integral(), -500 , 1000);
	
	mass.setBins(Nbins);

	// RooFit datasets
	RooDataHist hdata_ttbar("hdata_ttbar","ttbar", mass, hTTjets);       
	//RooDataHist hdata_wjets("hdata_wjets","wjets", mass, hWjets);
	RooDataHist hdata_wjetsFast("hdata_wjetsFast","wjets_Fast", mass, hWjetsFast);
	RooDataHist hdata_ST("hdata_ST","ST", mass, hST_t);
	RooDataHist hdata_zjets("hdata_zjets","zjets", mass, hZjets);
	//RooDataHist hdata_qcd("hdata_qcd","qcd", mass, hQCD);
	RooDataHist hdata_zjetsFast("hdata_zjetsFast","zjets_Fast", mass, hZjetsFast);
	RooDataHist hdata_qcdWFast("hdata_qcdWFast","qcd WFast", mass, hQCD_WFast);
	
	RooHistPdf hpdf_ttbar("hpdf_ttbar","signal pdf", mass, hdata_ttbar, 0 );
	//RooHistPdf hpdf_wjets("hpdf_wjets","W+jets pdf", mass, hdata_wjets, 0 );
	RooHistPdf hpdf_wjetsFast("hpdf_wjetsFast","W+jets pdf", mass, hdata_wjetsFast, 0 );
	RooHistPdf hpdf_ST("hpdf_ST","ST pdf", mass, hdata_ST, 0 );
	//RooHistPdf hpdf_zjets("hpdf_zjets","Z+jets pdf", mass, hdata_zjets, 0 );
	//RooHistPdf hpdf_qcd("hpdf_qcd","qcd pdf", mass, hdata_qcd, 0 );
	RooHistPdf hpdf_zjetsFast("hpdf_zjetsFast","Z+jets pdf", mass, hdata_zjetsFast, 0 );
	RooHistPdf hpdf_qcdWFast("hpdf_qcdWFast","qcd WFast pdf", mass, hdata_qcdWFast, 0 );
	
	// for systematics
	RooDataHist hdata_ttbarS("hdata_ttbarS","ttbar", mass, hTTjetsS);       
	RooDataHist hdata_wjetsS("hdata_wjetsS","wjets", mass, hWjetsSFast);
	RooDataHist hdata_STS("hdata_STS","ST", mass, hST_tS);
	RooDataHist hdata_zjetsS("hdata_zjetsS","zjets", mass, hZjetsSFast);
	RooDataHist hdata_qcdS("hdata_qcdS","qcd", mass, hQCDS);
	//RooDataHist hdata_qcdSWFast("hdata_qcdSWFast","qcd WFast", mass, hQCDS_WFast);
		
	RooHistPdf hpdf_ttbarS("hpdf_ttbarS","signal pdf", mass, hdata_ttbarS, 0 );
	RooHistPdf hpdf_wjetsS("hpdf_wjetsS","W+jets pdf", mass, hdata_wjetsS, 0 );
	RooHistPdf hpdf_STS("hpdf_STS","ST pdf", mass, hdata_STS, 0 );
	RooHistPdf hpdf_zjetsS("hpdf_zjetsS","Z+jets pdf", mass, hdata_zjetsS, 0 );
	RooHistPdf hpdf_qcdS("hpdf_qcdS","qcd pdf", mass, hdata_qcdS, 0 );
	//RooHistPdf hpdf_qcdSWFast("hpdf_qcdSWFast","qcd WFast pdf", mass, hdata_qcdSWFast, 0 );

	//RooAddPdf hpdf_bkg("hpdf_bkg","bkg", RooArgList(hpdf_wjetsFast,hpdf_ST,hpdf_qcdWFast),
	//				   RooArgList(NW,NST,Nqcd) );
					   
	//RooAddPdf hpdf_bkg("hpdf_bkg","bkg", RooArgList(hpdf_wjetsFast,hpdf_ST,hpdf_zjetsFast,hpdf_qcdWFast),
					   //RooAddPdf hpdf_bkg("hpdf_bkg","bkg", RooArgList(hpdf_wjetsS,hpdf_STS,hpdf_zjetsS,hpdf_qcdSWFast),
					   //RooArgList(NW,NST,NZjets,Nqcd) );
// only two pdfs: ttbar + Wjets
//RooHistPdf hpdf_bkg = hpdf_wjetsFast;
	
	//RooAddPdf model_M3("modelM3","all", RooArgList(hpdf_ttbar,hpdf_wjetsFast,hpdf_ST,hpdf_zjetsFast,hpdf_qcdWFast),
	//			   RooArgList(Ntt,Nbkg,NST,NZjets,Nqcd));
	// for systematics
	RooAddPdf model_M3("modelM3","all", RooArgList(hpdf_ttbar,hpdf_wjetsFast,hpdf_ST),//RooArgList(hpdf_ttbar,hpdf_wjetsS,hpdf_ST),
					   RooArgList(Ntt,Nbkg,NST) );
	
	//RooAddPdf model_M3("modelM3","all",RooArgList(hpdf_ttbar,hpdf_bkg),
	//		   RooArgList(Ntt,Nbkg) );
	//RooArgList(Ntt,Nbkg,NST,Nqcd) );
	
	RooAddPdf model_histpdf("model", "TTjets+Wjets", RooArgList(hpdf_ttbar,hpdf_wjetsFast,hpdf_ST),
							RooArgList(Ntt, Nbkg, NST) ) ;

	// Construct another Gaussian constraint p.d.f on parameter f at n with resolution of sqrt(n)
	RooGaussian STgaussConstraint("STgaussConstraint","STgaussConstraint",NST,RooConst(hST_t->Integral()),RooConst(sqrt(hST_t->Integral() + (0.3*hST_t->Integral())*(0.3*hST_t->Integral()))) );
	//RooGaussian fconstext2("fconstext2","fconstext2",NZjets,RooConst(hZjets->Integral()),RooConst(sqrt(hZjets->Integral())) );
	
	// --- Generate a toyMC sample 
	//RooMCStudy *mcstudyM3 = new RooMCStudy(model_M3, mass, Binned(kTRUE),Silence(),Extended(),
	//								   FitOptions(Save(kTRUE),Minos(kTRUE),Extended(), ExternalConstraints(fconstext)) );

	// generate PEs
	int Nsamples = 1000;
	// PEs for ttbar
/*
	RooExtendPdf ext_hpdf_ttbar("ext_hpdf_ttbar","ext_hpdf_ttbar",hpdf_ttbar,Ntt);
	RooExtendPdf ext_hpdf_wjets("ext_hpdf_wjets","ext_hpdf_wjets",hpdf_wjetsFast,NW);
	RooExtendPdf ext_hpdf_zjets("ext_hpdf_zjets","ext_hpdf_zjets",hpdf_zjetsFast,NZjets);
	RooExtendPdf ext_hpdf_qcd("ext_hpdf_qcd","ext_hpdf_qcd",hpdf_qcdWFast,Nqcd);
	RooExtendPdf ext_hpdf_ST("ext_hpdf_ST","ext_hpdf_ST",hpdf_ST,NST);
	
	RooMCStudy *mc_ttbar = new RooMCStudy(ext_hpdf_ttbar,mass,Binned(kTRUE),Silence(kTRUE));
	mc_ttbar->generate(Nsamples,0,kFALSE,"data/toymc_ttbar_%04d.dat");
	RooMCStudy *mc_wjets = new RooMCStudy(ext_hpdf_wjets,mass,Binned(kTRUE),Silence(kTRUE));
	mc_wjets->generate(Nsamples,0,kFALSE,"data/toymc_wjets_%04d.dat");
	RooMCStudy *mc_zjets = new RooMCStudy(ext_hpdf_zjets,mass,Binned(kTRUE),Silence(kTRUE));
	mc_zjets->generate(Nsamples,0,kFALSE,"data/toymc_zjets_%04d.dat");
	RooMCStudy *mc_qcd = new RooMCStudy(ext_hpdf_qcd,mass,Binned(kTRUE),Silence(kTRUE));
	mc_qcd->generate(Nsamples,0,kFALSE,"data/toymc_qcd_%04d.dat");
	RooMCStudy *mc_ST = new RooMCStudy(ext_hpdf_ST,mass,Binned(kTRUE),Silence(kTRUE),FitOptions(ExternalConstraints(STgaussConstraint)));
	mc_ST->generate(Nsamples,0,kFALSE,"data/toymc_ST_%04d.dat");

	return;
*/	
	RooMCStudy *mcstudy = new RooMCStudy(model_M3, mass, FitModel(model_histpdf),Binned(kTRUE),Silence(kTRUE), Extended() , 
										 //FitOptions(Save(kTRUE),Minos(kTRUE),Extended()) );
										 FitOptions(Save(kTRUE),Minos(kTRUE),Extended(),ExternalConstraints(STgaussConstraint)));//RooArgList(fconstext,fconstext2)) )); //gaussian constraint
	
		
	//mcstudyM3->generate(Nsamples,0,kFALSE,"toymc.dat");
	//mcstudyM3->generateAndFit(Nsamples,0,kFALSE,"toymc.dat");
	
	//TList dataList;
	//for (int isample=0; isample<Nsamples; ++isample) dataList.Add( mcstudyM3->genData(isample));

	
	// Fit
	mcstudy->generateAndFit(Nsamples,0,kTRUE);
	//mcstudy->fit(Nsamples, "data/toymc_%04d.dat");

		
	gDirectory->Add(mcstudy) ;	
	// E x p l o r e   r e s u l t s   o f   s t u d y 
	// ------------------------------------------------

	// Make plots of the distributions of mean, the error on mean and the pull of mean
	RooPlot* frame1 = mcstudy->plotParam(Ntt,Bins(40));
	RooPlot* frame2 = mcstudy->plotError(Ntt,Bins(40)) ;
	RooPlot* frame3 = mcstudy->plotPull(Ntt,Bins(40),FitGauss(kTRUE)) ;
	RooPlot* frame1w = mcstudy->plotParam(Nbkg,Bins(40)) ;
	RooPlot* frame2w = mcstudy->plotError(Nbkg,Bins(40)) ;
	RooPlot* frame3w = mcstudy->plotPull(Nbkg,Bins(40),FitGauss(kTRUE)) ;
	RooPlot* frame1st = mcstudy->plotParam(NST,Bins(40)) ;
	RooPlot* frame2st = mcstudy->plotError(NST,Bins(40)) ;
	//RooPlot* frame3st = mcstudy->plotPull(NST,Bins(40),FitGauss(kTRUE)) ;
	
	// Plot distribution of minimized likelihood
	RooPlot* frame4 = mcstudy->plotNLL(Bins(40)) ;

	// Make some histograms from the parameter dataset
	TH1* hh_cor_ttbar_w = mcstudy->fitParDataSet().createHistogram("hh",Ntt,YVar(Nbkg)) ;

	// Access some of the saved fit results from individual toys
	//TH2* corrHist000 = mcstudy->fitResult(0)->correlationHist("c000") ;
	//TH2* corrHist127 = mcstudy->fitResult(127)->correlationHist("c127") ;
	//TH2* corrHist953 = mcstudy->fitResult(953)->correlationHist("c953") ;

	
	// Draw all plots on a canvas
	gStyle->SetPalette(1) ;
	gStyle->SetOptStat(0) ;

	TCanvas* cv = new TCanvas("cv","cv",600,600) ;
	hM3->SetFillColor(kRed);
	hWjets->SetFillColor(kGreen);
	hM3->Draw();
	hWjets->Draw("same");
	gPad->RedrawAxis();
	
	TCanvas* cva = new TCanvas("cva","cva",1800,600) ;
	cva->Divide(3);
	cva->cd(1) ;
	RooPlot *initialframe = mass.frame();
	//initial->SetMaximum(10);
	hpdf_ttbar.plotOn(initialframe,LineColor(kRed));
	hpdf_wjetsFast.plotOn(initialframe,LineColor(kGreen));
	hpdf_ST.plotOn(initialframe,LineColor(kYellow));
	initialframe->Draw();
	//initialframe->SetTitle();
	cva->cd(2);
	//retrieve data for only one PE
	
	int Npe = 10;
	RooPlot *genframe = mass.frame(Nbins);
	RooDataSet *gendata = mcstudy->genData(Npe);
	cout << " N events = " << gendata->numEntries() << endl;
	gendata->plotOn(genframe);
	//mcstudy->fitResult(Npe)->plotOn(genframe, model_histpdf);
	genframe->Draw();
	cva->cd(3);
	RooPlot *genframe2 = mass.frame(Nbins);
	mcstudy->fitResult(Npe)->Print("v");
	gendata->plotOn(genframe2);
	RooArgList arglist = mcstudy->fitResult(Npe)->floatParsFinal();

	
	//cout << "name of argument:" << arglist[2].GetName() << endl;
	//cout << "name of argument:" << arglist[1].GetName() << endl;
	//cout << "name of argument:" << arglist[0].GetName() << endl;
	
	RooAddPdf model_histpdf_fitted("modelfitted", "TTjets+Wjets", RooArgList(hpdf_ttbar,hpdf_wjetsFast,hpdf_ST),
							   RooArgList(arglist[2],arglist[1],arglist[0]) ) ;
	
	model_histpdf_fitted.plotOn(genframe2,LineColor(kRed));
	model_histpdf_fitted.plotOn(genframe2,Components(hpdf_wjetsFast),LineColor(kGreen));
	model_histpdf_fitted.plotOn(genframe2,Components(hpdf_ST),LineColor(kYellow));
	genframe2->Draw();

	TCanvas* cvb = new TCanvas("cvb","cvb",1800,600) ;
	cvb->Divide(3);
	cvb->cd(1) ; frame1->Draw();
	cvb->cd(2) ; frame2->Draw();
	cvb->cd(3) ; frame3->Draw();
	TCanvas* cvbb = new TCanvas("cvbb","cvbb",1800,600) ;
	cvbb->Divide(3);
	cvbb->cd(1) ; frame1w->Draw();
	cvbb->cd(2) ; frame2w->Draw();
	cvbb->cd(3) ; frame3w->Draw();

	TCanvas* cvbbb = new TCanvas("cvbbb","cvbbb",1200,600) ;
	cvbbb->Divide(2);
	cvbbb->cd(1) ; frame1st->Draw();
	cvbbb->cd(2) ; frame2st->Draw();
	//cvbbb->cd(3) ; frame3st->Draw();
	
	TCanvas* cvbc = new TCanvas("cvbc","cvbc",600,600) ;
	TH2 *h2 = Ntt.createHistogram("Nttbar vs NWjets",Nbkg);
	mcstudy->fitParDataSet().fillHistogram(h2,RooArgList(Ntt,Nbkg));
	h2->Draw("box");

	
	TCanvas* cvc = new TCanvas("cvc","cvc",600,600) ;	
	// Plot distribution of minimized likelihood
	RooPlot* frame4 = mcstudy->plotNLL(Bins(40)) ;
	frame4->Draw();

	//return;//debuging

	
	TCanvas* cvd = new TCanvas("cvd","cvd",600,600) ;
	TCanvas* cve = new TCanvas("cve","cve",1200,600) ;
	TCanvas* cvf = new TCanvas("cvf","cvf",600,600) ;

	TH1F *hNgen = new TH1F("hNgen","Number of observed events",30,350,650);
	hNgen->SetXTitle("Number of observed events");

	TH1F *hNttresults = new TH1F("hNttresults","number of ttbar events",50,20,600);
	TH1F *hNWresults = new TH1F("hNWresults","number of W events",50,-150,400);
	TH1F *hNSTresults = new TH1F("hNSTresults","number of ttbar events",50,5,25);
									 
	bool gotone = false;
	int Nfailed = 0;
	for ( int i=0; i< Nsamples; i++)
	{
		
		RooFitResult *r = mcstudy->fitResult(i);
		RooArgList list = r->floatParsFinal();
		RooRealVar *rrv_nt = (RooRealVar*)list.at(2);
		double nt = rrv_nt->getVal();
		//double nte= rrv_nt->getError();
		RooRealVar *rrv_nw = (RooRealVar*)list.at(1);
		double nw = rrv_nw->getVal();
		//double nwe= rrv_nw->getError();
		RooRealVar *rrv_nst = (RooRealVar*)list.at(0);
		double nst = rrv_nst->getVal();

				
		hNttresults->Fill(nt);
		hNWresults->Fill(nw);
		hNSTresults->Fill(nst);
		
		
		RooDataSet *adata = mcstudy->genData(i);
		hNgen->Fill(adata->numEntries());
		
		if ( r->numInvalidNLL() > 0 ) Nfailed++;
		
		
		/*
		if ( false ) {
			cout << " sample # " << i << endl;
			gotone = true;
			r->Print("v");
			cout << " invalidNLL = "<< r->numInvalidNLL() << endl;
			cout << " N events = " << adata->numEntries() << endl;

			
			RooAddPdf amodel("amodel", "TTjets+Wjets", RooArgList(hpdf_ttbar,hpdf_wjets,hpdf_ST),
							 RooArgList(list[2],list[1],list[0])) ;
			RooPlot *d2 = new RooPlot(Ntt,NW,0,500,-200,200);
			r->plotOn(d2,Ntt,NW,"ME12ABHV");
			cvd->cd();
			d2->Draw();
			
			RooNLLVar nll("nll","nll", amodel, *adata, Extended() );//, Extended(), PrintEvalErrors(-1) );
			RooMinuit myminuit(nll)
			myminuit.migrad();
			myminuit.hesse();
			myminuit.minos();
			//myminuit.Save()->Print("v");

			cve->Divide(2);
			RooPlot *nllframett = Ntt.frame(Bins(50),Range(100,600));//,Range(10,2000));
			nll.plotOn(nllframett);//,ShiftToZero());
						
			RooProfileLL pll_ntt("pll_ntt","pll_ntt",nll,Ntt);
			pll_ntt.plotOn(nllframett,LineColor(kRed));

			RooPlot *nllframeW = NW.frame(Bins(50),Range(0,250));//,Range(10,2000));
			nll.plotOn(nllframeW);//,ShiftToZero());
						
			RooProfileLL pll_nW("pll_nW","pll_nW",nll,NW);
			pll_nW.plotOn(nllframeW,LineColor(kRed));

			cve->cd(1);
			nllframett->SetMaximum(2);
			nllframett->Draw();
			cve->cd(2);
			nllframeW->SetMaximum(2);
			nllframeW->Draw();
			
		}
		*/
	}

	TCanvas *tmpcv = new TCanvas("tmpcv","tmpcv",700,700);
	cout << "\n ==================================" << endl;
	cout << "gaussian fit of Nttbar fitted values: " << endl;
	//hNttresults->Print("all");
	hNttresults->Fit("gaus");

	cout << "\n ==================================" << endl;
	cout << "gaussian fit of NW fitted values: " << endl;
	//hNWresults->Print("all");
	hNWresults->Fit("gaus");

	cout << "\n ==================================" << endl;
	cout << "gaussian fit of NST fitted values: " << endl;
	//hNSTresults->Print("all");
	hNSTresults->Fit("gaus");

	
	cout << "N failed fits = " << Nfailed << endl;
	
	cvf->cd();
	hNgen->Draw();
	
	// Make RooMCStudy object available on command line after
	// macro finishes
	//gDirectory->Add(mcstudy) ;
}
Example #15
0
//================================================
void DeltaZVsPos(const Int_t save = 0)
{
  THnSparseF *hn = (THnSparseF*)f->Get(Form("mhTrkDzDy_%s",trigName[kTrigType]));
  TList *list = new TList;

  // dz vs BL
  TH2F *hTrkDzVsBL = (TH2F*)hn->Projection(1,3);
  c = draw2D(hTrkDzVsBL,Form("%s: #Deltaz of matched track-hit pairs",trigName[kTrigType]));
  if(save) 
    {
      c->SaveAs(Form("~/Work/STAR/analysis/Plots/%s/ana_Match/%sDeltaZ_vs_BL_%s.pdf",run_type,run_cfg_name.Data(),trigName[kTrigType]));
      c->SaveAs(Form("~/Work/STAR/analysis/Plots/%s/ana_Match/%sDeltaZ_vs_BL_%s.png",run_type,run_cfg_name.Data(),trigName[kTrigType]));
    }

  list->Clear();
  TString legName[30];
  TH1F *hTrkDzInBL[30];
  Int_t counter = 0;
  for(Int_t i=0; i<30; i++)
    {
      hTrkDzInBL[i] = (TH1F*)hTrkDzVsBL->ProjectionY(Form("hDeltaZ_BL%d",i+1),i+1,i+1);
      if(hTrkDzInBL[i]->GetEntries()>0)
	{
	  legName[counter] = Form("Module %d",i+1);
	  hTrkDzInBL[i]->SetLineColor(color[counter]);
	  list->Add(hTrkDzInBL[i]);
	  counter ++;
	}
    }
  c = drawHistos(list,"TrkDzInBL",Form("%s: #Deltaz of matched track-hit pairs in backleg;#Deltaz (cm)",trigName[kTrigType]),kTRUE,-100,100,kTRUE,0,1.2*hTrkDzInBL[1]->GetMaximum(),kFALSE,kTRUE,legName,kTRUE,"",0.15,0.25,0.2,0.88,kFALSE,0.04,0.04,kFALSE,1,kTRUE,kFALSE);
  TLine *line = GetLine(0,0,0,1.1*hTrkDzInBL[1]->GetMaximum(),1);
  line->Draw();
  if(save) 
    {
      c->SaveAs(Form("~/Work/STAR/analysis/Plots/%s/ana_Match/%sDeltaZ_in_BL_%s.pdf",run_type,run_cfg_name.Data(),trigName[kTrigType]));
      c->SaveAs(Form("~/Work/STAR/analysis/Plots/%s/ana_Match/%sDeltaZ_in_BL_%s.png",run_type,run_cfg_name.Data(),trigName[kTrigType]));
    }

  // dz vs Mod
  TH2F *hTrkDzVsMod = (TH2F*)hn->Projection(1,4);
  c = draw2D(hTrkDzVsMod,Form("%s: #Deltaz of matched track-hit pairs",trigName[kTrigType]));
  if(save) 
    {
      c->SaveAs(Form("~/Work/STAR/analysis/Plots/%s/ana_Match/%sDeltaZ_vs_Mod_%s.pdf",run_type,run_cfg_name.Data(),trigName[kTrigType]));
      c->SaveAs(Form("~/Work/STAR/analysis/Plots/%s/ana_Match/%sDeltaZ_vs_Mod_%s.png",run_type,run_cfg_name.Data(),trigName[kTrigType]));
    }

  TH1F *hMthMod = (TH1F*)hTrkDzVsMod->ProjectionX("hMthMod");
  hMthMod->Sumw2();
  hMthMod->Scale(1./hMthMod->Integral());
  TH2F *hMtdHitMap = (TH2F*)f->Get(Form("mhMtdHitMap_%s",trigName[kTrigType]));
  TH1F *htmp = (TH1F*)hMtdHitMap->ProjectionY("hHitMod_finebin");
  htmp->Rebin(12);
  TH1F *hMtdHitMod = new TH1F(Form("hMtdHitMod_%s",trigName[kTrigType]),"# of MTD hits per module;module",5,1,6);
  for(int i=0; i<hMtdHitMod->GetNbinsX(); i++)
    {
      hMtdHitMod->SetBinContent(i+1,htmp->GetBinContent(i+1));
      hMtdHitMod->SetBinError(i+1,htmp->GetBinError(i+1));
    }
  hMtdHitMod->Scale(1./hMtdHitMod->Integral());
  list->Clear();
  list->Add(hMthMod);
  list->Add(hMtdHitMod);
  TString legName3[2] = {"Matched good hits","All good hits"};
  c = drawHistos(list,"MtdHitMod",Form("%s: MTD hits per module;module;probability",trigName[kTrigType]),kFALSE,0,5,kTRUE,0,0.5,kFALSE,kTRUE,legName3,kTRUE,"",0.15,0.25,0.6,0.88,kTRUE);
  if(save) 
    {
      c->SaveAs(Form("~/Work/STAR/analysis/Plots/%s/ana_Match/%sCompMtdHitMod_%s.pdf",run_type,run_cfg_name.Data(),trigName[kTrigType]));
      c->SaveAs(Form("~/Work/STAR/analysis/Plots/%s/ana_Match/%sCompMtdHitMod_%s.png",run_type,run_cfg_name.Data(),trigName[kTrigType]));
    }

  list->Clear();
  TString legName2[5];
  TH1F *hTrkDzInMod[5];
  for(Int_t i=0; i<5; i++)
    {
      hTrkDzInMod[i] = (TH1F*)hTrkDzVsMod->ProjectionY(Form("hDeltaZ_Mod%d",i+1),i+1,i+1);
      legName2[i] = Form("Module %d",i+1);
      list->Add(hTrkDzInMod[i]);
    }
  c = drawHistos(list,"TrkDzInMod",Form("%s: #Deltaz of matched track-hit pairs in module;#Deltaz (cm)",trigName[kTrigType]),kTRUE,-100,100,kTRUE,0,1.2*hTrkDzInMod[3]->GetMaximum(),kFALSE,kTRUE,legName2,kTRUE,"",0.15,0.25,0.6,0.88,kTRUE);
  TLine *line = GetLine(0,0,0,hTrkDzInMod[3]->GetMaximum()*1.05,1);
  line->Draw();
  if(save) 
    {
      c->SaveAs(Form("~/Work/STAR/analysis/Plots/%s/ana_Match/%sDeltaZ_in_Mod_%s.pdf",run_type,run_cfg_name.Data(),trigName[kTrigType]));
      c->SaveAs(Form("~/Work/STAR/analysis/Plots/%s/ana_Match/%sDeltaZ_in_Mod_%s.png",run_type,run_cfg_name.Data(),trigName[kTrigType]));
    }
}
Example #16
0
void comparisonJetMCData(string plot,int rebin){
  string tmp;

  string dir="/gpfs/cms/data/2011/Observables/Approval/";
	
  if (isAngularAnalysis){
    mcfile=dir+"MC_zjets"+version;
    back_w=dir+"MC_wjets"+version;
    back_ttbar=dir+"MC_ttbar"+version;
    WW=dir+"MC_diW"+version;
    ZZ=dir+"MC_siZ"+version;
    WZ=dir+"MC_diWZ"+version;
    datafile=dir+"DATA"+version;
    mcfiletau=dir+"MC_zjetstau"+version;
  }
  // List of files

  TFile *dataf = TFile::Open(datafile.c_str()); //data file
  TFile *mcf = TFile::Open(mcfile.c_str()); //MC file
  TFile *mcftau = TFile::Open(mcfiletau.c_str()); //MC file
  TFile *ttbarf = TFile::Open(back_ttbar.c_str()); //MC background file
  TFile *wf = TFile::Open(back_w.c_str());


  TFile *qcd23emf = TFile::Open(qcd23em.c_str());
  TFile *qcd38emf = TFile::Open(qcd38em.c_str());
  TFile *qcd817emf = TFile::Open(qcd817em.c_str());

  TFile *qcd23bcf = TFile::Open(qcd23bc.c_str());
  TFile *qcd38bcf = TFile::Open(qcd38bc.c_str());
  TFile *qcd817bcf = TFile::Open(qcd817bc.c_str());

  TFile *WZf = TFile::Open(WZ.c_str());
  TFile *ZZf = TFile::Open(ZZ.c_str());
  TFile *WWf = TFile::Open(WW.c_str());


  // Canvas
  if (CanvPlot) delete CanvPlot;
  CanvPlot = new TCanvas("CanvPlot","CanvPlot",0,0,800,600);

  // Getting, defining ...
  dataf->cd("validationJEC");
  if (isMu && isAngularAnalysis) dataf->cd("validationJECmu");
	
  TObject * obj;
  gDirectory->GetObject(plot.c_str(),obj);

  TH1 *data;
  TH2F *data2; 
  TH1D *data3; 

  THStack *hs = new THStack("hs","Total MC");


  int flag=-1;
  if ((data = dynamic_cast<TH1F *>(obj)) ){
    flag=1;
    gROOT->Reset();
    gROOT->ForceStyle();
    gStyle->SetPadRightMargin(0.03);
    gPad->SetLogy(1);
    gPad->Modified();
    gPad->Update();
  }
  if ((data2 = dynamic_cast<TH2F *>(obj)) ){
    flag=2;
    gStyle->SetPalette(1);
    gStyle->SetPadRightMargin(0.15);
    gPad->Modified();
  }



  //===================
  // Dirty jobs :)
  if (flag==1){
    CanvPlot->cd();
    TPad *pad1 = new TPad("pad1","pad1",0.01,0.33,0.99,0.99);
    pad1->Draw();
    pad1->cd();
    pad1->SetTopMargin(0.1);
    pad1->SetBottomMargin(0.01);
    pad1->SetRightMargin(0.1);
    pad1->SetFillStyle(0);
    pad1->SetLogy(1);
    TString str=data->GetTitle();
    if (str.Contains("jet") && !str.Contains("zMass") && !str.Contains("Num") && !str.Contains("Eta") && !str.Contains("Phi") && !str.Contains("eld") && !str.Contains("meanPtZVsNjet")) {
      if (!isAngularAnalysis) rebin=1;
    }

    //======================
    // DATA
    Double_t dataint = data->Integral();
    data->SetLineColor(kBlack);
    data->Rebin(rebin);
    if(str.Contains("nJetVtx")) data->GetXaxis()->SetRangeUser(0,10);	
    if(str.Contains("zMass")) data->GetXaxis()->SetRangeUser(70,110);	
    data->SetMinimum(1.);
    data->Sumw2();

    //Canvas style copied from plotsHistsRatio.C
    data->SetLabelSize(0.0);
    data->GetXaxis()->SetTitleSize(0.00);
    data->GetYaxis()->SetLabelSize(0.07);
    data->GetYaxis()->SetTitleSize(0.08);
    data->GetYaxis()->SetTitleOffset(0.76);
    data->SetTitle("");
    gStyle->SetOptStat(0);

    data->GetYaxis()->SetLabelSize(0.06);
    data->GetYaxis()->SetTitleSize(0.06);
    data->GetYaxis()->SetTitleOffset(0.8);

    data->Draw("E1");


    TLegend* legend = new TLegend(0.725,0.27,0.85,0.72);
    legend->SetFillColor(0);
    legend->SetFillStyle(0);
    legend->SetBorderSize(0);
    legend->SetTextSize(0.060);
    legend->AddEntry(data,"data","p");

    // hack to calculate some yields in restricted regions...
    int num1=0, num2=0, num3=0, num4=0, num5=0;
    if(str.Contains("invMass") && !str.Contains("PF")){
      for(int j=1;j<=data->GetNbinsX();j++){
	num1 += data->GetBinContent(j); 		//conto quante Z ci sono tra 60 e 120 GeV
	if(j>10&&j<=50) num2 += data->GetBinContent(j); // ... tra 70 e 110
	if(j>15&&j<=45) num3 += data->GetBinContent(j); // ... tra 75 e 105
      }
      cout << "\n";
      cout << data->GetNbinsX() <<" Number of bins of the invmass histo\n";
      printf("Number of Z in 60-120 %i --- 70-110 %i --- 75-105 %i \n",num1,num2,num3);
      cout << "\n";
    }
    if(str.Contains("zYieldVsjets") && !str.Contains("Vtx")){
      for(int j=1;j<=data->GetNbinsX();j++){
	num1 += data->GetBinContent(j); 		//conto quante Z
	if(j>1) num2 += data->GetBinContent(j); // ... +1,2,3,4... jets
	if(j>2) num3 += data->GetBinContent(j); // ... +2,3,4... jets
	if(j>3) num4 += data->GetBinContent(j); // ..    if(str=="jet_pT"){
	if(j>4) num5 += data->GetBinContent(j); // ... +4... jets
      }
      cout << "\n";
      cout << data->GetNbinsX() <<" Number of bins of the zYieldVsjets histo\n";
      printf("Number of Z+n jet %i --- >1 %i --- >2 %i --- >3 %i --- >4 %i \n",num1,num2,num3,num4,num5);
      cout << "\n";
    }    

    //======================
    // Z + jets signal
    mcf->cd("validationJEC");
    if (isMu) mcf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      mcf->cd("validationJEC/");
      if (isMu) mcf->cd("validationJECmu/");
    }

    TH1F* mc;
    gDirectory->GetObject(plot.c_str(),mc);
    TH1F * hsum;
    if(mc){
      hsum =  (TH1F*) mc->Clone();
      hsum->SetTitle("hsum");
      hsum->SetName("hsum");
      hsum->Reset();

      Double_t mcint = mc->Integral();
      mc->SetFillColor(kRed);
      mc->Sumw2();
      if(lumiweights==0) mc->Scale(dataint/mcint);
		
      // Blocco da propagare negli altri MC
      if(zNumEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) mc->Scale( dataLumi2011pix / (zNumEvents / zjetsXsect));
	    else mc->Scale( dataLumi2011 / (zNumEvents / zjetsXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) mc->Scale( dataLumi2011Apix / (zNumEvents / zjetsXsect));
	      else mc->Scale( dataLumi2011A / (zNumEvents / zjetsXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) mc->Scale( dataLumi2011Bpix / (zNumEvents / zjetsXsect));
	      else mc->Scale( dataLumi2011B / (zNumEvents / zjetsXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) mc->Scale(zjetsScale);
      }

      // fin qui
      if(lumiweights==1) mc->Scale(1./zwemean);  // perche' i Weights non fanno 1...
      mc->Rebin(rebin);
      if(lumiweights==0) mc->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(mc);
      legend->AddEntry(mc,"Z+jets","f");
    }

    //======================
    // ttbar
    ttbarf->cd("validationJEC");
    if (isMu) ttbarf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      ttbarf->cd("validationJEC/");
      if (isMu) ttbarf->cd("validationJECmu/");
    }

    TH1F* ttbar;
    gDirectory->GetObject(plot.c_str(),ttbar);
	
    if(ttbar){
      ttbar->SetFillColor(kBlue);
      ttbar->Sumw2();

      if(ttNumEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) ttbar->Scale( dataLumi2011pix / (ttNumEvents / ttbarXsect));
	    else ttbar->Scale( dataLumi2011 / (ttNumEvents / ttbarXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) ttbar->Scale( dataLumi2011Apix / (ttNumEvents / ttbarXsect));
	      else ttbar->Scale( dataLumi2011A / (ttNumEvents / ttbarXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) ttbar->Scale( dataLumi2011Bpix / (ttNumEvents / ttbarXsect));
	      else ttbar->Scale( dataLumi2011B / (ttNumEvents / ttbarXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) ttbar->Scale(ttwemean);
      }
      // fin qui
		
      if(lumiweights==1) ttbar->Scale(1./ttwemean);  // perche' i Weights non fanno 1...
      ttbar->Rebin(rebin);
      if(lumiweights==0) ttbar->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(ttbar);
      if(lumiweights==1)legend->AddEntry(ttbar,"ttbar","f");

      //////////
      //Storing the bckgrounds!
      //////////
      cout<<str<<endl;
      if (isAngularAnalysis){
      if(str=="jet_pT") evaluateAndFillBackgrounds(ttbar,"jet_pT");
      if(str=="jet_pT2") evaluateAndFillBackgrounds(ttbar,"jet_pT2");
      if(str=="jet_pT3") evaluateAndFillBackgrounds(ttbar,"jet_pT3");
      if(str=="jet_pT4") evaluateAndFillBackgrounds(ttbar,"jet_pT4");
      if(str=="Jet_multi") evaluateAndFillBackgrounds(ttbar,"jet_Multiplicity");
      if(str=="jet_eta") evaluateAndFillBackgrounds(ttbar,"jet_eta");
      if(str=="jet_eta2") evaluateAndFillBackgrounds(ttbar,"jet_eta2");
      if(str=="jet_eta3") evaluateAndFillBackgrounds(ttbar,"jet_eta3");
      if(str=="jet_eta4") evaluateAndFillBackgrounds(ttbar,"jet_eta4");
      if(str=="HT") evaluateAndFillBackgrounds(ttbar,"HT");
      if(str=="HT_1j") evaluateAndFillBackgrounds(ttbar,"HT1");
      if(str=="HT_2j") evaluateAndFillBackgrounds(ttbar,"HT2");
      if(str=="HT_3j") evaluateAndFillBackgrounds(ttbar,"HT3");
      if(str=="HT_4j") evaluateAndFillBackgrounds(ttbar,"HT4");
      if(str=="Phi_star") evaluateAndFillBackgrounds(ttbar,"PhiStar");
      }
    }

    //======================
    // w+jets
    wf->cd("validationJEC");
    if (isMu) wf->cd("validationJECmu/");
    if (isAngularAnalysis) {
      wf->cd("validationJEC/");
      if (isMu) wf->cd("validationJECmu/");      
    }

    TH1F* w;
    gDirectory->GetObject(plot.c_str(),w);
    if(w){

      w->SetFillColor(kViolet+2);
      w->Sumw2();

      if(wNumEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) w->Scale( dataLumi2011pix / (wNumEvents / wjetsXsect));
	    else w->Scale( dataLumi2011 / (wNumEvents / wjetsXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) w->Scale( dataLumi2011Apix / (wNumEvents / wjetsXsect));
	      else w->Scale( dataLumi2011A / (wNumEvents / wjetsXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) w->Scale( dataLumi2011Bpix / (wNumEvents / wjetsXsect));
	      else w->Scale( dataLumi2011B / (wNumEvents / wjetsXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) w->Scale(wwemean);
      }
      // fin qui
		
      if(lumiweights==1) w->Scale(1./wwemean);  // perche' i Weights non fanno 1...
      w->Rebin(rebin);
      if(lumiweights==0) w->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(w);
      if(lumiweights==1)legend->AddEntry(w,"W+jets","f");
    }

    //======================
    // wz+jets
    WZf->cd("validationJEC");
    if (isMu) WZf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      WZf->cd("validationJEC/");
      if (isMu) WZf->cd("validationJECmu/");
    }

    TH1F* wz;
    gDirectory->GetObject(plot.c_str(),wz);
    if(wz){
      wz->SetFillColor(kYellow+2);
      wz->Sumw2();

      if(wzEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) wz->Scale( dataLumi2011pix / (wzEvents / WZXsect));
	    else wz->Scale( dataLumi2011 / (wzEvents / WZXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) wz->Scale( dataLumi2011Apix / (wzEvents / WZXsect));
	      else wz->Scale( dataLumi2011A / (wzEvents / WZXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) wz->Scale( dataLumi2011Bpix / (wzEvents / WZXsect));
	      else wz->Scale( dataLumi2011B / (wzEvents / WZXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) wz->Scale(wzjetsScale);
      }
      // fin qui
		
      if(lumiweights==1) wz->Scale(1./wzwemean);  // perche' i Weights non fanno 1...
      wz->Rebin(rebin);
      if(lumiweights==0) wz->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(wz);
      legend->AddEntry(wz,"WZ+jets","f");


      //////////
      //Storing the bckgrounds!
      //////////
     if (isAngularAnalysis){
      if(str=="jet_pT") evaluateAndFillBackgrounds(wz,"jet_pT");
      if(str=="jet_pT2") evaluateAndFillBackgrounds(wz,"jet_pT2");
      if(str=="jet_pT3") evaluateAndFillBackgrounds(wz,"jet_pT3");
      if(str=="jet_pT4") evaluateAndFillBackgrounds(wz,"jet_pT4");
      if(str=="jet_eta") evaluateAndFillBackgrounds(wz,"jet_eta");
      if(str=="jet_eta2") evaluateAndFillBackgrounds(wz,"jet_eta2");
      if(str=="jet_eta3") evaluateAndFillBackgrounds(wz,"jet_eta3");
      if(str=="jet_eta4") evaluateAndFillBackgrounds(wz,"jet_eta4");
      if(str=="Jet_multi") evaluateAndFillBackgrounds(wz,"jet_Multiplicity");
      if(str=="HT") evaluateAndFillBackgrounds(wz,"HT");
      if(str=="HT_1j") evaluateAndFillBackgrounds(wz,"HT1");
      if(str=="HT_2j") evaluateAndFillBackgrounds(wz,"HT2");
      if(str=="HT_3j") evaluateAndFillBackgrounds(wz,"HT3");
      if(str=="HT_4j") evaluateAndFillBackgrounds(wz,"HT4");
      if(str=="Phi_star") evaluateAndFillBackgrounds(wz,"PhiStar");
     }
    }
    
		
    //======================
    // zz+jets
    ZZf->cd("validationJEC");
    if (isMu) ZZf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      ZZf->cd("validationJEC/");
      if (isMu) ZZf->cd("validationJECmu/");
    }

    TH1F* zz;
    gDirectory->GetObject(plot.c_str(),zz);
    if(zz){
      zz->SetFillColor(kOrange+2);
      zz->Sumw2();

      if(zzEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) zz->Scale( dataLumi2011pix / (zzEvents / ZZXsect));
	    else zz->Scale( dataLumi2011 / (zzEvents / ZZXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) zz->Scale( dataLumi2011Apix / (zzEvents / ZZXsect));
	      else zz->Scale( dataLumi2011A / (zzEvents / ZZXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) zz->Scale( dataLumi2011Bpix / (zzEvents / ZZXsect));
	      else zz->Scale( dataLumi2011B / (zzEvents / ZZXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) zz->Scale(zzjetsScale);
      }
      // fin qui
		
      if(lumiweights==1) zz->Scale(1./zzwemean);  // perche' i Weights non fanno 1...
      zz->Rebin(rebin);
      if(lumiweights==0) zz->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(zz);
      legend->AddEntry(zz,"ZZ+jets","f");

      //////////
      //Storing the bckgrounds!
      //////////
     if (isAngularAnalysis){
      if(str=="jet_pT") evaluateAndFillBackgrounds(zz,"jet_pT");
      if(str=="jet_pT2") evaluateAndFillBackgrounds(zz,"jet_pT2");
      if(str=="jet_pT3") evaluateAndFillBackgrounds(zz,"jet_pT3");
      if(str=="jet_pT4") evaluateAndFillBackgrounds(zz,"jet_pT4");
      if(str=="jet_eta") evaluateAndFillBackgrounds(zz,"jet_eta");
      if(str=="jet_eta2") evaluateAndFillBackgrounds(zz,"jet_eta2");
      if(str=="jet_eta3") evaluateAndFillBackgrounds(zz,"jet_eta3");
      if(str=="jet_eta4") evaluateAndFillBackgrounds(zz,"jet_eta4");
      if(str=="Jet_multi") evaluateAndFillBackgrounds(zz,"jet_Multiplicity");
      if(str=="HT") evaluateAndFillBackgrounds(zz,"HT");
      if(str=="HT_1j") evaluateAndFillBackgrounds(zz,"HT1");
      if(str=="HT_2j") evaluateAndFillBackgrounds(zz,"HT2");
      if(str=="HT_3j") evaluateAndFillBackgrounds(zz,"HT3");
      if(str=="HT_4j") evaluateAndFillBackgrounds(zz,"HT4");
      if(str=="Phi_star") evaluateAndFillBackgrounds(zz,"PhiStar");
     }  
    }
    
    //======================
    // ww+jets
    WWf->cd("validationJEC");
    if (isMu) WWf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      WWf->cd("validationJEC/");
      if (isMu) WWf->cd("validationJECmu/");
    }

    TH1F* ww;
    gDirectory->GetObject(plot.c_str(),ww);
    if(ww){
      ww->SetFillColor(kBlack);
      ww->Sumw2();

      if(wwEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) ww->Scale( dataLumi2011pix / (wwEvents / WWXsect));
	    else ww->Scale( dataLumi2011 / (wwEvents / WWXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) ww->Scale( dataLumi2011Apix / (wwEvents / WWXsect));
	      else ww->Scale( dataLumi2011A / (wwEvents / WWXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) ww->Scale( dataLumi2011Bpix / (wwEvents / WWXsect));
	      else ww->Scale( dataLumi2011B / (wwEvents / WWXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) ww->Scale(wwjetsScale);
      }
      // fin qui
		
      if(lumiweights==1) ww->Scale(1./wwwemean);  // perche' i Weights non fanno 1...
      ww->Rebin(rebin);
      if(lumiweights==0) ww->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(ww);
      legend->AddEntry(ww,"WW+jets","f");

      //////////
      //Storing the bckgrounds!
      //////////
     if (isAngularAnalysis){
      if(str=="jet_pT") evaluateAndFillBackgrounds(ww,"jet_pT");
      if(str=="jet_pT2") evaluateAndFillBackgrounds(ww,"jet_pT2");
      if(str=="jet_pT3") evaluateAndFillBackgrounds(ww,"jet_pT3");
      if(str=="jet_pT4") evaluateAndFillBackgrounds(ww,"jet_pT4");
      if(str=="jet_eta") evaluateAndFillBackgrounds(ww,"jet_eta");
      if(str=="jet_eta2") evaluateAndFillBackgrounds(ww,"jet_eta2");
      if(str=="jet_eta3") evaluateAndFillBackgrounds(ww,"jet_eta3");
      if(str=="jet_eta4") evaluateAndFillBackgrounds(ww,"jet_eta4");
      if(str=="Jet_multi") evaluateAndFillBackgrounds(ww,"jet_Multiplicity");
      if(str=="HT") evaluateAndFillBackgrounds(ww,"HT");
      if(str=="HT_1j") evaluateAndFillBackgrounds(ww,"HT1");
      if(str=="HT_2j") evaluateAndFillBackgrounds(ww,"HT2");
      if(str=="HT_3j") evaluateAndFillBackgrounds(ww,"HT3");
      if(str=="HT_4j") evaluateAndFillBackgrounds(ww,"HT4");
      if(str=="Phi_star") evaluateAndFillBackgrounds(ww,"PhiStar");
     }
    }

    /// Tau 

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

    mcftau->cd("validationJEC");
    if (isMu) mcftau->cd("validationJECmu/");

    if (isAngularAnalysis) {
      mcftau->cd("validationJEC/");
      if (isMu) mcftau->cd("validationJECmu/");
    }

    TH1F* tau;
    gDirectory->GetObject(plot.c_str(),tau);
    if(tau){
      tau->SetFillColor(kGreen);
      tau->Sumw2();

      if(zNumEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) tau->Scale( dataLumi2011pix / (zNumEvents / zjetsXsect));
	    else tau->Scale( dataLumi2011 / (zNumEvents / zjetsXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) tau->Scale( dataLumi2011Apix / (zNumEvents / zjetsXsect));
	      else tau->Scale( dataLumi2011A / (zNumEvents / zjetsXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) tau->Scale( dataLumi2011Bpix / (zNumEvents / zjetsXsect));
	      else tau->Scale( dataLumi2011B / (zNumEvents / zjetsXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) tau->Scale(zjetsScale);
      }
      // fin qui
		
      if(lumiweights==1) tau->Scale(1./zwemean);  // perche' i Weights non fanno 1...
      tau->Rebin(rebin);
      if(lumiweights==0) tau->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      tau->Scale(1./1000.); //aaaaaaa
      hsum->Add(tau);
      legend->AddEntry(tau,"#tau#tau+jets","f");

      //////////
      //Storing the bckgrounds!
      //////////
     if (isAngularAnalysis){
      if(str=="jet_pT") evaluateAndFillBackgrounds(tau,"jet_pT");
      if(str=="jet_pT2") evaluateAndFillBackgrounds(tau,"jet_pT2");
      if(str=="jet_pT3") evaluateAndFillBackgrounds(tau,"jet_pT3");
      if(str=="jet_pT4") evaluateAndFillBackgrounds(tau,"jet_pT4");
      if(str=="jet_eta") evaluateAndFillBackgrounds(tau,"jet_eta");
      if(str=="jet_eta2") evaluateAndFillBackgrounds(tau,"jet_eta2");
      if(str=="jet_eta3") evaluateAndFillBackgrounds(tau,"jet_eta3");
      if(str=="jet_eta4") evaluateAndFillBackgrounds(tau,"jet_eta4");
      if(str=="Jet_multi") evaluateAndFillBackgrounds(tau,"jet_Multiplicity");
      if(str=="HT") evaluateAndFillBackgrounds(tau,"HT");
      if(str=="HT_1j") evaluateAndFillBackgrounds(tau,"HT1");
      if(str=="HT_2j") evaluateAndFillBackgrounds(tau,"HT2");
      if(str=="HT_3j") evaluateAndFillBackgrounds(tau,"HT3");
      if(str=="HT_4j") evaluateAndFillBackgrounds(tau,"HT4");
      if(str=="Phi_star") evaluateAndFillBackgrounds(tau,"PhiStar");
     }
    }


    /////////
    // Print the bkg contributions
    ////////

    for(int j=0;j<bckg_leadingJetPt.size();j++){      
      cout<<bckg_leadingJetPt[j]<<endl;
    }	

    //======================
    // QCD EM enriched
    qcd23emf->cd("validationJEC");
    TH1F* qcd23emp;
    gDirectory->GetObject(plot.c_str(),qcd23emp);

    if(qcd23emp){
      TH1D * qcdTotEM =  (TH1D*) qcd23emp->Clone(); 
      qcdTotEM->SetTitle("qcd em");
      qcdTotEM->SetName("qcd em");
      qcdTotEM->Reset();
      qcdTotEM->Rebin(rebin);

      qcd38emf->cd("validationJEC");
      TH1F* qcd38emp;
      gDirectory->GetObject(plot.c_str(),qcd38emp);


      qcd817emf->cd("validationJEC");
      TH1F* qcd817emp;
      gDirectory->GetObject(plot.c_str(),qcd817emp);

      qcd23emp->Rebin(rebin);
      qcd23emp->Sumw2();
      qcd23emp->Scale(qcd23emScale); 
      qcd38emp->Rebin(rebin);
      qcd38emp->Sumw2();
      qcd38emp->Scale(qcd38emScale); 
      qcd817emp->Rebin(rebin);
      qcd817emp->Sumw2();
      qcd817emp->Scale(qcd817emScale); 

      qcdTotEM->SetFillColor(kOrange+1);
      qcdTotEM->Add(qcd23emp);
      qcdTotEM->Add(qcd38emp);
      qcdTotEM->Add(qcd817emp);

      hsum->Add(qcdTotEM);

      //if(lumiweights==1)legend->AddEntry(qcdTotEM,"QCD em","f");
    }

    //======================
    // QCD bc
    qcd23bcf->cd("validationJEC");
    TH1F* qcd23bcp;
    TH1D * qcdTotBC;
    bool  qcdbcempty=true;
    gDirectory->GetObject(plot.c_str(),qcd23bcp);

    if(qcd23bcp){
      qcdTotBC =  (TH1D*) qcd23bcp->Clone(); 
      qcdTotBC->SetTitle("qcd bc");
      qcdTotBC->SetName("qcd bc");
      qcdTotBC->Reset();
      qcdTotBC->Rebin(rebin);

      qcd38bcf->cd("validationJEC");
      TH1F* qcd38bcp;
      gDirectory->GetObject(plot.c_str(),qcd38bcp);

      qcd817bcf->cd("validationJEC");
      TH1F* qcd817bcp;
      gDirectory->GetObject(plot.c_str(),qcd817bcp);

      qcd23bcp->Rebin(rebin);
      qcd23bcp->Sumw2();
      qcd23bcp->Scale(qcd23bcScale); 
      qcd38bcp->Rebin(rebin);
      qcd38bcp->Sumw2();
      qcd38bcp->Scale(qcd38bcScale); 
      qcd817bcp->Rebin(rebin);
      qcd817bcp->Sumw2();
      qcd817bcp->Scale(qcd817bcScale); 

      qcdTotBC->SetFillColor(kGreen+2);
      qcdTotBC->Add(qcd23bcp);
      qcdTotBC->Add(qcd38bcp);
      qcdTotBC->Add(qcd817bcp);

      hsum->Add(qcdTotBC);
      if (qcdTotBC->GetEntries()>0) qcdbcempty=false; 

      //if(lumiweights==1)legend->AddEntry(qcdTotBC,"QCD bc","f");
    }

    //======================
    // Add here other backgrounds


    //======================
    // Stacked Histogram
    //if(qcd23em) 	hs->Add(qcdTotEM);
    if(!qcdbcempty) 	hs->Add(qcdTotBC);
    if(w)  	        hs->Add(w);
    if (ww)         hs->Add(ww);
    if(tau)		hs->Add(tau); //Z+Jets
    if (zz)         hs->Add(zz);
    if (wz)         hs->Add(wz);
    if (ttbar)	hs->Add(ttbar);
    if(mc)		hs->Add(mc); //Z+Jets

    // per avere le statistiche
    if(lumiweights==1) hsum->Draw("HISTO SAME");


    //======================
    // Setting the stats
    //pad1->Update(); // altrimenti non becchi la stat
    
    //TPaveStats *r2;
    //if(lumiweights==0) r2 = (TPaveStats*)mc->FindObject("stats");
    //if(lumiweights==1) r2 = (TPaveStats*)hsum->FindObject("stats");
    //r2->SetY1NDC(0.875);     //Uncomment if you wonna add your statistics in the top right corner
    //r2->SetY2NDC(0.75); 
    //r2->SetTextColor(kRed);
		
    if(lumiweights==1) hs->Draw("HISTO SAME");
    gPad->RedrawAxis();
    data->Draw("E1 SAME");
    //r2->Draw(); //here to reactivate the stats
    legend->Draw();
    TLegend* lumi = new TLegend(0.45,0.3,0.75,0.2);
    lumi->SetFillColor(0);
    lumi->SetFillStyle(0);
    lumi->SetBorderSize(0);
    //lumi->AddEntry((TObject*)0,"#int L dt =4.9 1/fb","");
    lumi->Draw();
    string channel;
    if (isMu) channel="Z#rightarrow#mu#mu";
    if (!isMu) channel="Z#rightarrow ee";
    TLatex *latexLabel=CMSPrel(4.890,channel,0.55,0.85); // make fancy label
    latexLabel->Draw("same");

    CanvPlot->Update();

	


    //===============//
    // RATIO DATA MC //
    //===============//
    CanvPlot->cd();
    TPad *pad2 = new TPad("pad2","pad2",0.01,0.01,0.99,0.32);
    pad2->Draw();
    pad2->cd();
    pad2->SetTopMargin(0.01);
    pad2->SetBottomMargin(0.3);
    pad2->SetRightMargin(0.1);
    pad2->SetFillStyle(0);

    TH1D * ratio =  (TH1D*) data->Clone();
    ratio->SetTitle("");
    ratio->SetName("ratio");
    ratio->Reset();

    ratio->Sumw2();
    //data->Sumw2();
    hsum->Sumw2(); // FIXME controlla che sia corretto questo... 
    ratio->SetMarkerSize(.5);
    ratio->SetLineColor(kBlack);
    ratio->SetMarkerColor(kBlack);
    //gStyle->SetOptStat("m");
    TH1F* sumMC;

    hs->Draw("nostack"); 
 
   sumMC=(TH1F*) hs->GetHistogram();
    cout<<sumMC->GetEntries()<<endl;
    ratio->Divide(data,hsum,1.,1.);
    ratio->GetYaxis()->SetRangeUser(0.5,1.5);
    ratio->SetMarkerSize(0.8);
    //pad2->SetTopMargin(1);

   //Canvas style copied from plotsHistsRatio.C
    ratio->GetYaxis()->SetNdivisions(5);
    ratio->GetXaxis()->SetTitleSize(0.14);
    ratio->GetXaxis()->SetLabelSize(0.14);
    ratio->GetYaxis()->SetLabelSize(0.11);
    ratio->GetYaxis()->SetTitleSize(0.11);
    ratio->GetYaxis()->SetTitleOffset(0.43);
    ratio->GetYaxis()->SetTitle("ratio data/MC");   

    ratio->Draw("E1");
		
    TLine *OLine = new TLine(ratio->GetXaxis()->GetXmin(),1.,ratio->GetXaxis()->GetXmax(),1.);
    OLine->SetLineColor(kBlack);
    OLine->SetLineStyle(2);
    OLine->Draw();
 
    TLegend* label = new TLegend(0.60,0.9,0.50,0.95);
    label->SetFillColor(0);
    label->SetFillStyle(0);
    label->SetBorderSize(0);
    //horrible mess
    double binContent = 0;
    double binSum = 0;
    double weightSum = 0;
    double binError = 1;
    double totalbins = ratio->GetSize() -2;
    for(unsigned int bin=1;bin<=totalbins;bin++){
      binContent = ratio->GetBinContent(bin);
      binError = ratio->GetBinError(bin);
      if(binError!=0){
	binSum += binContent/binError;
	weightSum += 1./binError;
      }
    }
    double ymean = binSum / weightSum;
    //double ymean = ratio->GetMean(2);
    stringstream sYmean;
    sYmean << ymean;
    string labeltext=sYmean.str()+" mean Y";
    //label->AddEntry((TObject*)0,labeltext.c_str(),""); // mean on Y
    //label->Draw();
		
    //TPaveStats *r3 = (TPaveStats*)ratio->FindObject("stats");
    //r3->SetX1NDC(0.01);
    //r3->SetX2NDC(0.10); 
    //r3->SetY1NDC(0.20);
    //r3->SetY2NDC(0.50); 
    //gStyle->SetOptStat("mr");
    //r3->SetTextColor(kWhite);
    //r3->SetLineColor(kWhite);
    //r3->Draw();
    CanvPlot->Update();

    tmp=plotpath+plot+".png";
    CanvPlot->Print(tmp.c_str());

  }
  else if (flag==2){
    //CanvPlot.Divide(2,1);
    //CanvPlot.cd(1);

    // data
    dataf->cd("validationJEC");
    if (isMu && isAngularAnalysis) dataf->cd("validationJECmu");

    gDirectory->GetObject(plot.c_str(),data2);
    data2->Draw("COLZ");

    gPad->Update(); // altrimenti non becchi la stat
    TPaveStats *r1 = (TPaveStats*)data2->FindObject("stats");
    //r1->SetX1NDC(0.70); Uncomment if you wonna draw your stat in the top right corner
    //r1->SetX2NDC(0.85); 
    //r1->Draw();
    CanvPlot->Update();

    tmp=plotpath+plot+"data.png";
    CanvPlot->Print(tmp.c_str());


    //CanvPlot.cd(2);
    // montecarlo
    mcf->cd("validationJEC");
    if (isMu) mcf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      mcf->cd("validationJEC/");
      if (isMu) mcf->cd("validationJECmu/");
    }

    gDirectory->GetObject(plot.c_str(),data2);

    data2->SetMinimum(1);
    data2->Draw("COLZ");

    gPad->Update(); // altrimenti non becchi la stat
    //TPaveStats *r2 = (TPaveStats*)data2->FindObject("stats");
    //r2->SetX1NDC(0.70);
    //r2->SetX2NDC(0.85); 
    //r2->Draw();
    CanvPlot->Update();

    tmp=plotpath+plot+"mc.png";
    CanvPlot->Print(tmp.c_str());
  }
  //	else { cout << "You're getting an exception! Most likely there's no histogram here... \n"; }

  delete data;
  delete data2;
  delete hs;
  //delete CanvPlot;

  dataf->Close();
  mcf->Close();
  ttbarf->Close();
  wf->Close();
  qcd23emf->Close();
  qcd38emf->Close();
  qcd817emf->Close();
  qcd23bcf->Close();
  qcd38bcf->Close();
  qcd817bcf->Close();
  WZf->Close();
  ZZf->Close();
  
  if (isAngularAnalysis){
    if (bckg_leadingJetPt.size()>0 && bckg_2leadingJetPt.size()>0 && bckg_3leadingJetPt.size()>0 && bckg_4leadingJetPt.size()>0  && bckg_JetMultiplicity.size()>0 && bckg_HT.size()>0 && bckg_leadingJetEta.size()>0 && bckg_PhiStar.size()>0 && cold){
      fzj->cd();
      treeBKG_->Fill();
      treeBKG_->Write();
      TH1F *leadhisto=new TH1F("leadhisto","leading jet background contribution",bckg_leadingJetPt.size(),0,bckg_leadingJetPt.size());
      TH1F *leadhisto2=new TH1F("leadhisto2","subleading jet background contribution",bckg_leadingJetPt.size(),0,bckg_leadingJetPt.size());
      TH1F *leadhisto3=new TH1F("leadhisto3","subsubleading jet background contribution",bckg_leadingJetPt.size(),0,bckg_leadingJetPt.size());
      TH1F *leadhisto4=new TH1F("leadhisto4","subsubsubleading jet background contribution",bckg_leadingJetPt.size(),0,bckg_leadingJetPt.size());
      TH1F *multiphisto=new TH1F("multiphisto","jet multiplicity background contribution",bckg_JetMultiplicity.size(),0,bckg_JetMultiplicity.size());

      TH1F *HT=new TH1F("HT","HT background contribution",bckg_HT.size(),0,bckg_HT.size());
      TH1F *HT1=new TH1F("HT1","HT background contribution when >= 1 jet",bckg_HT1.size(),0,bckg_HT1.size());
      TH1F *HT2=new TH1F("HT2","HT background contribution when >= 2 jets",bckg_HT2.size(),0,bckg_HT2.size());
      TH1F *HT3=new TH1F("HT3","HT background contribution when >= 3 jets",bckg_HT3.size(),0,bckg_HT3.size());
      TH1F *HT4=new TH1F("HT4","HT background contribution when >= 4 jets",bckg_HT4.size(),0,bckg_HT4.size());

      TH1F *leadhistoeta=new TH1F("leadhistoeta","leading jet background contribution",bckg_leadingJetEta.size(),0,bckg_leadingJetEta.size());
      TH1F *leadhistoeta2=new TH1F("leadhistoeta2","subleading jet background contribution",bckg_leadingJetEta.size(),0,bckg_leadingJetEta.size());
      TH1F *leadhistoeta3=new TH1F("leadhistoeta3","subsubleading jet background contribution",bckg_leadingJetEta.size(),0,bckg_leadingJetEta.size());
      TH1F *leadhistoeta4=new TH1F("leadhistoeta4","subsubsubleading jet background contribution",bckg_leadingJetEta.size(),0,bckg_leadingJetEta.size());

      TH1F *PhiStar=new TH1F("PhiStar","PhiStar background contribution",bckg_PhiStar.size(),0,bckg_PhiStar.size());

      for (int i=0; i< bckg_leadingJetPt.size(); i++){
	leadhisto->Fill(i,bckg_leadingJetPt[i]);
	leadhisto2->Fill(i,bckg_2leadingJetPt[i]);
	leadhisto3->Fill(i,bckg_3leadingJetPt[i]);
	leadhisto4->Fill(i,bckg_4leadingJetPt[i]);
      }
      leadhisto->Write();
      leadhisto2->Write();
      leadhisto3->Write();
      leadhisto4->Write();

      for (int i=0; i< bckg_leadingJetEta.size(); i++){
	leadhistoeta->Fill(i,bckg_leadingJetEta[i]);
	leadhistoeta2->Fill(i,bckg_2leadingJetEta[i]);
	leadhistoeta3->Fill(i,bckg_3leadingJetEta[i]);
	leadhistoeta4->Fill(i,bckg_4leadingJetEta[i]);
      }
      leadhistoeta->Write();
      leadhistoeta2->Write();
      leadhistoeta3->Write();
      leadhistoeta4->Write();
      //fzj->Close();

      for (int i=0; i< bckg_JetMultiplicity.size(); i++){
	multiphisto->Fill(i,bckg_JetMultiplicity[i]);
      }
      multiphisto->Write();
      
      ///////////////

      for (int i=0; i< bckg_HT.size(); i++){
	HT->Fill(i,bckg_HT[i]);
      }
      HT->Write();
      
      for (int i=0; i< bckg_HT1.size(); i++){
	HT1->Fill(i,bckg_HT1[i]);
      }
      HT1->Write();
      
      for (int i=0; i< bckg_HT2.size(); i++){
	HT2->Fill(i,bckg_HT2[i]);
      }
      HT2->Write();
      
      for (int i=0; i< bckg_HT3.size(); i++){
	HT3->Fill(i,bckg_HT3[i]);
      }
      HT3->Write();
      
      for (int i=0; i< bckg_HT4.size(); i++){
	HT4->Fill(i,bckg_HT4[i]);
      }
      HT4->Write();

      //Phi star
      for (int i=0; i< bckg_PhiStar.size(); i++){
	PhiStar->Fill(i,bckg_PhiStar[i]);
      }
      PhiStar->Write();

    cold=false;
    }
  }
  return;
}
Example #17
0
void makehisto(TString varname, TString process, TString ofile, TString file, TString dir, TString syst)
{
	TFile *fo = new TFile("histos/input/"+ofile+"__"+syst+".root","RECREATE");
	TFile *f = new TFile("trees_8TeV/"+dir+"/"+file+".root");

	TTree *tree = (TTree*)f->Get("trees/Events");

	cout << "Filling histogram " << varname << "__" << process << "__" << syst << " with " << file << endl;

	fo->cd();

	Float_t lumi = 19739;

	// weights
	Float_t weight = 1.0;
	Float_t pu_weight = 1.0;
	Float_t btag_weight = 1.0;
	Float_t muonID_weight = 1.0;
	Float_t muonIso_weight = 1.0;
	Float_t muonTrigger_weight = 1.0;
	tree->SetBranchAddress("pu_weight", &pu_weight);
	tree->SetBranchAddress("b_weight_nominal", &btag_weight);
	tree->SetBranchAddress("muon_IDWeight", &muonID_weight);
	tree->SetBranchAddress("muon_IsoWeight", &muonIso_weight);
	tree->SetBranchAddress("muon_TriggerWeight", &muonTrigger_weight);
	// cut variables
	Float_t muonIso = 0;
	Float_t jetrms = 0;
	Float_t mtw = 0;
	tree->SetBranchAddress("mu_iso", &muonIso);
	tree->SetBranchAddress("rms_lj", &jetrms);
	tree->SetBranchAddress("mt_mu", &mtw);
	//
	Int_t wjets_class = -1;
	tree->SetBranchAddress("wjets_classification", &wjets_class);

	Float_t var = 0;
	tree->SetBranchAddress(varname, &var);
	
	TH1::SetDefaultSumw2(true);
	TH1I *hcount = (TH1I*)f->Get("trees/count_hist");
	Int_t count = hcount->GetBinContent(1); 
	cout << count << endl;

	//cout << "sample size: " << count << endl;
	Float_t xsec = get_xsec(file);
	cout << "xsec: " << xsec << endl;
	
	TH1F *histo = new TH1F(varname+"__"+process+"__"+syst,varname+"__"+process+"__"+syst,bin_y,list_y);
	histo->Sumw2();
	
	Long_t nentries = tree->GetEntries();
	for(Long_t i = 0; i < nentries; i++) {
		tree->GetEntry(i);

		// wjets
		if(process == "wjets_light") {
			if(wjets_class == 0 || wjets_class == 1) continue;
		} else if (process == "wjets_heavy") {
			if(wjets_class != 0 && wjets_class != 1) continue;
		}
		
		if(jetrms >= 0.025) continue;
		if(mtw <= 50) continue;
		if(process == "qcd") {
			if (muonIso < 0.3 || muonIso > 0.5) continue;
		}
		
		if(process != "DATA"  && process != "qcd") {
			weight = pu_weight*btag_weight*muonID_weight*muonIso_weight*muonTrigger_weight;
			weight *= lumi;
			weight *= xsec;
			weight /= (Float_t)count;
		}
		
		histo->Fill(var,weight);
	}
	if(process == "qcd") histo->Scale(xsec);


	cout << "integral: " << histo->Integral() << endl;
	// write histos
	histo->Write();
	fo->Close();
}
Example #18
0
void RAA_dataDrivenUnfoldingErrorCheck_new(int radius = 3, bool isATLASCut = true)
{

  TStopwatch timer; 
  timer.Start();
  
  TH1::SetDefaultSumw2();
  TH2::SetDefaultSumw2();
  
  bool printDebug = true;
  bool dofakeremove = false;
  bool do10GeVBins = true;

  char * scale = (char*)"NeqScale";
  // 944Scale
  // NeqScale
  // NeqScalePerCent
  
  int unfoldingCut = 20;
  char * outLocation = (char*) "July20/";
  if(isATLASCut) outLocation = (char*)"July20/ATLASCut/";
  
  // get the data and mc histograms from the output of the read macro. 
  
  TDatime date;//this is just here to get them to run optimized. 

  // Pawan's files:
  //TFile * fPbPb_in = TFile::Open(Form("Pawan_TTree_PbPb_Data_MC_subid0_spectra_JetID_CutA_finebins_%s_R0p%d.root", etaWidth, radius));
  //TFile * fPbPb_in = TFile::Open(Form("Pawan_TTree_PbPb_Data_MC_subid0_spectra_JetID_CutA_muMaxOverSumcandMaxLT0p975_finebins_%s_R0p%d.root", etaWidth, radius));
  //TFile * fPbPb_in = TFile::Open(Form("Pawan_TTree_PbPb_Data_MC_subid0_spectra_JetID_CutA_trkMaxOverpfptGT0p02_finebins_%s_R0p%d.root", etaWidth, radius));
  //TFile * fPbPb_in = TFile::Open(Form("Pawan_TTree_PbPb_Data_noPrescl_MC_subid0_spectra_JetID_CutA_finebins_%s_R0p%d.root", etaWidth, radius));
  //TFile * fPbPb_in = TFile::Open(Form("Pawan_TTree_PbPb_Data_noPrescl_MC_subid0_spectra_JetID_CutA_7GeVTrackCut_finebinscut_%s_R0p%d.root", etaWidth, radius));
  // get the files to perform MC closure from the fixed ntuples
  TFile * fPbPb_in, *fMinBias, *fPbPb_MC_in, * fTrig;
  
  if(isATLASCut) fPbPb_in    = new TFile(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/Jun29/PbPb_Data_histograms_FromForest_trkMax7OrNeMax8GeVCut_akPu%d_20_eta_20.root",radius),"r");
  if(!isATLASCut) fPbPb_in    = new TFile(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/Jun29/PbPb_Data_histograms_FromForest_akPu%d_20_eta_20.root",radius),"r");
  if(isATLASCut) fMinBias    = TFile::Open(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/Jun29/PbPb_MB_Data_histograms_FromForest_trkMax7OrNeMax8GeVCut_fix_pt15GeVCut_akPu%d_20_eta_20.root",radius));
  if(!isATLASCut) fMinBias    = TFile::Open(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/Jun29/PbPb_MB_Data_histograms_FromForest_fix_pt15GeVCut_akPu%d_20_eta_20.root",radius));
  //TFile * fPbPb_MC_in = TFile::Open(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/Jun29/PbPb_MC_histograms_FromForest_pthat50andabove_akPu%d_20_eta_20.root",radius));
  if(isATLASCut) fPbPb_MC_in = new TFile(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/Jun29/PbPb_MC_histograms_FromForest_trkMax7OrNeMax8GeVCut_akPu%d_20_eta_20.root",radius),"r");
  if(!isATLASCut) fPbPb_MC_in = new TFile(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/Jun29/PbPb_MC_histograms_FromForest_akPu%d_20_eta_20.root",radius),"r");
  TFile * fPP_in      = new TFile(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/Jun29/pp_Data_histograms_FromForest_ak%d_20_eta_20.root",radius),"r");
  TFile * fPP_MC_in   = new TFile(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/Jun29/pp_MC_histograms_FromForest_ak%d_20_eta_20.root",radius),"r");
  if(isATLASCut) fTrig       = new TFile(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/Jun29/PbPb_Data_nofkSub_trkMax7OrNeMax8GeVCut_new_MC_turnonCurves_R%d_20_eta_20_20150715.root",radius),"r");
  if(!isATLASCut) fTrig       = new TFile(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/Jun29/PbPb_Data_nofkSub_new_MC_turnonCurves_R%d_20_eta_20_20150715.root",radius),"r");
  TFile * fTrig_pp = new TFile(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/Jun29/pp_MC_turnonCurves_R%d_20_eta_20_20150702.root", radius),"r");
  // TFile * fPPMCTrig = new TFile(Form("PP_Data_MC_turnonCurves_R%d_20_eta_20_20150618.root",radius),"r");

  TH1F * hMC_turnon[nbins_cent+1], * hData_turnon[nbins_cent+1];
  cout<<"after input file declaration"<<endl;
  
  
  // histogram declarations with the following initial appendage: d - Data, m - MC, u- Unfolded
  // for the MC closure test, ive kept separate 

  TH1F *dPbPb_TrgComb[nbins_cent+1], *dPbPb_TrgCombInput[nbins_cent+1], *dPbPb_Comb[nbins_cent+1], *dPbPb_Trg80[nbins_cent+1], *dPbPb_Trg65[nbins_cent+1], *dPbPb_Trg55[nbins_cent+1], *dPbPb_1[nbins_cent+1], *dPbPb_2[nbins_cent+1], *dPbPb_3[nbins_cent+1], *dPbPb_80[nbins_cent+1], *dPbPb_65[nbins_cent+1], *dPbPb_55[nbins_cent+1];
  
  TH1F *mPbPb_GenInput[nbins_cent+1], *mPbPb_RecoInput[nbins_cent+1];
  TH1F *mPbPb_Gen[nbins_cent+1], *mPbPb_Reco[nbins_cent+1];
  TH2F *mPbPb_Matrix[nbins_cent+1], * mPbPb_MatrixInput[nbins_cent+1], *mPbPb_Response[nbins_cent+1], *mPbPb_ResponseNorm[nbins_cent+1];
  TH1F *mPbPb_mcclosure_data[nbins_cent+1];
  TH2F *mPbPb_mcclosure_Matrix[nbins_cent+1],*mPbPb_mcclosure_Response[nbins_cent+1], *mPbPb_mcclosure_ResponseNorm[nbins_cent+1];
  TH1F *mPbPb_mcclosure_gen[nbins_cent+1];
  const int Iterations = 20; //for unfolding systematics. 
  const int BayesIter = 4;
  TH1F *uPbPb_Bayes[nbins_cent+1], *uPbPb_BinByBin[nbins_cent+1], *uPbPb_SVD[nbins_cent+1]; 
  TH1F *uPbPb_BayesianIter[nbins_cent+1][Iterations];
  TH1F *dPbPb_MinBias[nbins_cent];
  TH1F *hMinBias[nbins_cent];
  
  TH1F *dPP_1, *dPP_2, *dPP_3, *dPP_Comb, * dPP_CombInput;
  TH1F *mPP_Gen, *mPP_Reco, *mPP_GenInput, *mPP_RecoInput;
  TH2F *mPP_Matrix, *mPP_MatrixInput, *mPP_Response,*mPP_ResponseNorm;
  TH1F *mPP_mcclosure_data;
  TH2F *mPP_mcclosure_Matrix, *mPP_mcclosure_Response,*mPP_mcclosure_ResponseNorm;
  TH1F *mPP_mcclosure_Gen;
  TH1F *uPP_Bayes, *uPP_BinByBin, *uPP_SVD;
  TH1F *uPP_BayesianIter[Iterations];

  TH1F * hData_FaketoSub_fullbin[nbins_cent+1];
  
  // would be better to read in the histograms and rebin them. come to think of it, it would be better to have them already rebinned (and properly scaled - to the level of differential cross section in what ever barns (inverse micro barns) but keep it consistent) from the read macro. 

  if(radius == 2) unfoldingCut = unfoldingCut_R2;
  if(radius == 3) unfoldingCut = unfoldingCut_R3;
  if(radius == 4) unfoldingCut = unfoldingCut_R4;
  
  // TH1F * htest = new TH1F("htest","",nbins, ptbins_long);
  // Int_t unfoldingCutBin = htest->FindBin(unfoldingCut);
  
  //Float_t cutarray[6]={50,50,40,35,35,35};
  float cutarray[nbins_cent] = {0.0,0.0,0.0,0.0,0.0,0.0};
  
  if(radius == 2){
    cutarray[0] = 50;
    cutarray[1] = 40;
    cutarray[2] = 40;
    cutarray[3] = 40;
    cutarray[4] = 30;
    cutarray[5] = 30;
  }
  if(radius == 3){
    cutarray[0] = 55;
    cutarray[1] = 50;
    cutarray[2] = 50;
    cutarray[3] = 40;
    cutarray[4] = 35;
    cutarray[5] = 40;
  }
    
  if(radius == 4){
    cutarray[0] = 70;
    cutarray[1] = 60;
    cutarray[2] = 60;
    cutarray[3] = 45;
    cutarray[4] = 40;
    cutarray[5] = 30;
  }
    
  TH1F * hDataBeforeSub[nbins_cent], * hDataAfterSub[nbins_cent];
  
  // get PbPb data
  for(int i = 0;i<nbins_cent;++i){
    if(printDebug) cout<<"cent_"<<i<<endl;

    hData_turnon[i] = (TH1F*)fTrig->Get(Form("hHist_Data_Turnon_cent%d",i));
    
    hData_turnon[i] = (TH1F*)hData_turnon[i]->Rebin(nbins_short, Form("hData_turnon_cent%d",i), boundaries_short);
    //hData_turnon[i] = (TH1F*)hData_turnon[i]->Rebin(10);

    divideBinWidth(hData_turnon[i]);

     //  hMinBias[i]     = (TH1F*)fMinBias->Get(Form("hpbpb_noTrg_R%d_%s_cent%d",radius,etaWidth,i)); //MinBias Histo
    hMinBias[i]     = (TH1F*)fMinBias->Get(Form("hpbpb_HLTMBwoLJSbJ_R%d_%s_cent%d",radius,etaWidth,i)); //MinBias Histo
    hMinBias[i]->Print("base");

    dPbPb_TrgComb[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_HLTComb_%s_R%d_%s_cent%d",scale, radius,etaWidth,i));
    //dPbPb_TrgComb[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_HLT80_R%d_%s_cent%d",radius,etaWidth,i));
    //dPbPb_TrgComb[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_HLT65_R%d_%s_cent%d",radius,etaWidth,i));
    //dPbPb_TrgComb[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_HLT55_R%d_%s_cent%d",radius,etaWidth,i));
    // dPbPb_TrgComb[i]->Scale(1./(1+0.898+0.494)/1e16);
    // //dPbPb_TrgComb[i]->Scale(4*145.156*1e6);
    dPbPb_TrgComb[i]->Print("base");

    hDataBeforeSub[i] = (TH1F*)dPbPb_TrgComb[i]->Clone(Form("hData_Before_Sub_cent%d",i));
    
    //dPbPb_TrgComb[i] = (TH1F*)fPbPb_DataCorr_in->Get(Form("Data_TrigEffCorrected_FakeSub_cent%d",i));
    //dPbPb_TrgComb[i]->Print("base");
    
    // dPbPb_JEC_TrgComb[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_JEC_HLTComb_R%d_%s_cent%d",radius,etaWidth,i));
    // // //dPbPb_TrgComb[i]->Scale(4*145.156*1e6);
    // dPbPb_JEC_TrgComb[i]->Print("base");
    // dPbPb_Smear_TrgComb[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_Smear_HLTComb_R%d_%s_cent%d",radius,etaWidth,i));
    // // //dPbPb_TrgComb[i]->Scale(4*145.156*1e6);
    // dPbPb_Smear_TrgComb[i]->Print("base");
    // dPbPb_Trg80[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_HLT80_R%d_%s_cent%d",radius,etaWidth,i));
    // //dPbPb_Trg80[i]->Scale(4*145.156*1e6);
    // dPbPb_Trg80[i]->Print("base");
    // dPbPb_Trg65[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_HLT65_R%d_%s_cent%d",radius,etaWidth,i));
    // //dPbPb_Trg65[i]->Scale(4*145.156*1e6);
    // dPbPb_Trg65[i]->Print("base");
    // dPbPb_Trg55[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_HLT55_R%d_%s_cent%d",radius,etaWidth,i));
    // //dPbPb_Trg55[i]->Scale(4*145.156*1e6);
    // dPbPb_Trg55[i]->Print("base");

    // if(dotrigcor){
      
    //   doTrigCorr(dPbPb_TrgComb[i], hData_turnon[i]);
    //   doTrigCorr(dPbPb_JEC_TrgComb[i], hData_turnon[i]);
    //   doTrigCorr(dPbPb_Smear_TrgComb[i], hData_turnon[i]);

    // }
    
    //Lets do the subtraction here _Sevil 

      // Float_t bincon=cutarray[i]; 
      // Int_t bincut= hMinBias[i]->FindBin(bincon); 
      
      // for(int k = bincut;k<=hMinBias[i]->GetNbinsX();k++) { 
      // 	hMinBias[i]->SetBinContent(k,0); 
      // 	hMinBias[i]->SetBinError(k,0);
      // } 

      // for(int k = 1;k<=15;k++) { 
      // 	hMinBias[i]->SetBinContent(k,0); 
      // 	hMinBias[i]->SetBinError(k,0);
      // }
      
      Float_t   bin_no = dPbPb_TrgComb[i]->FindBin(15);
      Float_t bin_end=dPbPb_TrgComb[i]->FindBin(25);
      
      Float_t   bin_nomb = hMinBias[i]->FindBin(15);
      Float_t bin_endmb=hMinBias[i]->FindBin(25);
      
      float scalerangeweight=dPbPb_TrgComb[i]->Integral(bin_no,bin_end)/hMinBias[i]->Integral(bin_nomb,bin_endmb);

      // for(int j = 0; j<hMinBias[i]->GetNbinsX(); ++j)
      // 	hMinBias[i]->SetBinError(j+1, (Float_t)hMinBias[i]->GetBinError(j+1)/scalerangeweight);
      
      hMinBias[i]->Scale(scalerangeweight);
      if(dofakeremove) dPbPb_TrgComb[i]->Add(hMinBias[i], -1);

      hDataAfterSub[i] = (TH1F*)dPbPb_TrgComb[i]->Clone(Form("hData_After_Sub_cent%d",i));
      
      // dPbPb_JEC_TrgComb[i]->Add(hMinBias[i], -1);
      // dPbPb_Smear_TrgComb[i]->Add(hMinBias[i], -1);

      // for(int j = 1; j<dPbPb_TrgComb[i]->GetNbinsX(); ++j){

      // 	if(dPbPb_TrgComb[i]->GetBinContent(j) <= 0 ||dPbPb_JEC_TrgComb[i]->GetBinContent(j) <= 0||dPbPb_Smear_TrgComb[i]->GetBinContent(j) <= 0){
      // 	  dPbPb_TrgComb[i]->SetBinContent(j, 0);
      // 	  dPbPb_JEC_TrgComb[i]->SetBinContent(j, 0);
      // 	  dPbPb_Smear_TrgComb[i]->SetBinContent(j, 0);
      // 	  dPbPb_TrgComb[i]->SetBinError(j, 0);
      // 	  dPbPb_JEC_TrgComb[i]->SetBinError(j, 0);
      // 	  dPbPb_Smear_TrgComb[i]->SetBinError(j, 0);
      // 	}
      // }
      
    

    // // lets truncate the histograms here:
    // cout<<" going to truncate Data histogram here cent "<<i<<endl;
    // dPbPb_TrgCombInput[i]->Print("base");

    // dPbPb_TrgComb[i] = new TH1F(Form("PbPb_data_minbiasSub_cent%d",i),"",365, 30, 395);
    // Truncate1D(dPbPb_TrgCombInput[i], dPbPb_TrgComb[i]);    
    
    // // dPbPb_TrgComb[i] = (TH1F*)Truncate1D(dPbPb_TrgComb[i], 340, unfoldingCutBin, 395);
    // // dPbPb_TrgComb[i]->Print("base");
    
    //dPbPb_TrgComb[i] = (TH1F*)dPbPb_TrgComb[i]->Rebin(nbins, Form("PbPb_data_minbiasSub_cent%d",i), ptbins_long);
    dPbPb_TrgComb[i] = (TH1F*)dPbPb_TrgComb[i]->Rebin(10);
    dPbPb_TrgComb[i]->SetName(Form("PbPb_data_minbiasSub_cent%d",i));
    divideBinWidth(dPbPb_TrgComb[i]);
    
    hMinBias[i] = (TH1F*)hMinBias[i]->Rebin(10);
    hDataAfterSub[i] = (TH1F*)hDataAfterSub[i]->Rebin(10);
    hDataBeforeSub[i] = (TH1F*)hDataBeforeSub[i]->Rebin(10);

    divideBinWidth(hMinBias[i]);
    divideBinWidth(hDataAfterSub[i]);
    divideBinWidth(hDataBeforeSub[i]);
    
    dPbPb_TrgComb[i]->Scale(1./(166 * 1e9));
    
    // dPbPb_TrgComb[i]->Print("base");
    
  }

  if(printDebug)cout<<"loaded the data histograms PbPb"<<endl;
  // get PbPb MC
  for(int i = 0;i<nbins_cent;i++){
    
    // mPbPb_GenInput[i] = (TH1F*)fPbPb_MC_in->Get(Form("hpbpb_anaBin_JetComb_gen_R%d_%s_cent%d",radius,etaWidth,i));
    // mPbPb_GenInput[i]->Print("base");
    // mPbPb_RecoInput[i] = (TH1F*)fPbPb_MC_in->Get(Form("hpbpb_anaBin_JetComb_reco_R%d_%s_cent%d",radius,etaWidth,i));
    // mPbPb_RecoInput[i]->Print("base");
    // mPbPb_MatrixInput[i] = (TH2F*)fPbPb_MC_in->Get(Form("hpbpb_anaBin_matrix_HLT_R%d_%s_cent%d",radius,etaWidth,i));
    // mPbPb_MatrixInput[i]->Print("base");

    mPbPb_Gen[i] = (TH1F*)fPbPb_MC_in->Get(Form("hpbpb_JetComb_gen_R%d_%s_cent%d",radius,etaWidth,i));
    //mPbPb_Gen[i]->Rebin(nbins, Form("mPbPb_Gen_cent%d",i), ptbins_long);
    mPbPb_Gen[i]->Rebin(10);
    divideBinWidth(mPbPb_Gen[i]);
    mPbPb_Gen[i]->Print("base");
    mPbPb_Reco[i] = (TH1F*)fPbPb_MC_in->Get(Form("hpbpb_JetComb_reco_R%d_%s_cent%d",radius,etaWidth,i));
    //mPbPb_Reco[i]->Rebin(nbins, Form("mPbPb_Reco_cent%d",i), ptbins_long);
    mPbPb_Reco[i]->Rebin(10);
    divideBinWidth(mPbPb_Reco[i]);
    mPbPb_Reco[i]->Print("base");
    mPbPb_Matrix[i] = (TH2F*)fPbPb_MC_in->Get(Form("hpbpb_matrix_HLT_R%d_%s_cent%d",radius,etaWidth,i));
    //mPbPb_Matrix[i] = (TH2F*)fPbPb_MC_in->Get(Form("hpbpb_anaBin_matrix_HLT_R%d_%s_cent%d",radius,etaWidth,i));
    mPbPb_Matrix[i]->Rebin2D(10, 10);
    mPbPb_Matrix[i]->Print("base");
    
    // if(etaWidth == "10_eta_10"){
    //   if(i == 0 && radius==2) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 1 && radius==2) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 2 && radius==2) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 3 && radius==2) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 4 && radius==2) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 5 && radius==2) unfoldingCutBin = htest->FindBin(30);

    //   if(i == 0 && radius==3) unfoldingCutBin = htest->FindBin(40);
    //   if(i == 1 && radius==3) unfoldingCutBin = htest->FindBin(40);
    //   if(i == 2 && radius==3) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 3 && radius==3) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 4 && radius==3) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 5 && radius==3) unfoldingCutBin = htest->FindBin(30);

    //   if(i == 0 && radius==4) unfoldingCutBin = htest->FindBin(50);
    //   if(i == 1 && radius==4) unfoldingCutBin = htest->FindBin(50);
    //   if(i == 2 && radius==4) unfoldingCutBin = htest->FindBin(40);
    //   if(i == 3 && radius==4) unfoldingCutBin = htest->FindBin(40);
    //   if(i == 4 && radius==4) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 5 && radius==4) unfoldingCutBin = htest->FindBin(30);
    // }

    // if(etaWidth == "10_eta_18"){
    //   if(i == 0 && radius==2) unfoldingCutBin = htest->FindBin(50);
    //   if(i == 1 && radius==2) unfoldingCutBin = htest->FindBin(50);
    //   if(i == 2 && radius==2) unfoldingCutBin = htest->FindBin(40);
    //   if(i == 3 && radius==2) unfoldingCutBin = htest->FindBin(40);
    //   if(i == 4 && radius==2) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 5 && radius==2) unfoldingCutBin = htest->FindBin(30);

    //   if(i == 0 && radius==3) unfoldingCutBin = htest->FindBin(60);
    //   if(i == 1 && radius==3) unfoldingCutBin = htest->FindBin(50);
    //   if(i == 2 && radius==3) unfoldingCutBin = htest->FindBin(40);
    //   if(i == 3 && radius==3) unfoldingCutBin = htest->FindBin(40);
    //   if(i == 4 && radius==3) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 5 && radius==3) unfoldingCutBin = htest->FindBin(30);

    //   if(i == 0 && radius==4) unfoldingCutBin = htest->FindBin(70);
    //   if(i == 1 && radius==4) unfoldingCutBin = htest->FindBin(60);
    //   if(i == 2 && radius==4) unfoldingCutBin = htest->FindBin(50);
    //   if(i == 3 && radius==4) unfoldingCutBin = htest->FindBin(50);
    //   if(i == 4 && radius==4) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 5 && radius==4) unfoldingCutBin = htest->FindBin(30);
    // }

    // if(etaWidth == "20_eta_20"){
    //   if(i == 0 && radius==2) unfoldingCutBin = htest->FindBin(70);
    //   if(i == 1 && radius==2) unfoldingCutBin = htest->FindBin(60);
    //   if(i == 2 && radius==2) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 3 && radius==2) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 4 && radius==2) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 5 && radius==2) unfoldingCutBin = htest->FindBin(30);

    //   if(i == 0 && radius==3) unfoldingCutBin = htest->FindBin(70);
    //   if(i == 1 && radius==3) unfoldingCutBin = htest->FindBin(60);
    //   if(i == 2 && radius==3) unfoldingCutBin = htest->FindBin(50);
    //   if(i == 3 && radius==3) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 4 && radius==3) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 5 && radius==3) unfoldingCutBin = htest->FindBin(30);

    //   if(i == 0 && radius==4) unfoldingCutBin = htest->FindBin(80);
    //   if(i == 1 && radius==4) unfoldingCutBin = htest->FindBin(60);
    //   if(i == 2 && radius==4) unfoldingCutBin = htest->FindBin(50);
    //   if(i == 3 && radius==4) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 4 && radius==4) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 5 && radius==4) unfoldingCutBin = htest->FindBin(30);
    // }

    int bincut = mPbPb_Gen[i]->FindBin(50);
    for(int k = 1;k<=bincut;k++){

    //   mPbPb_Gen[i]->SetBinContent(k,0);
    //   mPbPb_Reco[i]->SetBinContent(k,0);
    //   mPbPb_Gen[i]->SetBinError(k,0);
    //   mPbPb_Reco[i]->SetBinError(k,0);
    //   // set bin content matrix l,k works 
      for(int l = 1;l<=mPbPb_Gen[i]->GetNbinsX();l++){
	mPbPb_Matrix[i]->SetBinContent(l,k,0);
	mPbPb_Matrix[i]->SetBinError(l,k,0);
      }
      
    }

    SetUnfoldBins1D(dPbPb_TrgComb[i], 50, 350);
    
    // cout<<"going to truncate the MC histograms here."<<endl;
    
    // // mPbPb_Reco[i]->Print("base");
    // // mPbPb_Reco[i] = (TH1F*)Truncate1D_anaBin(mPbPb_Reco[i], nbins, ptbins_long);
    // // mPbPb_Reco[i]->Print("base");

    // mPbPb_GenInput[i]->Print("base");
    // mPbPb_Gen[i] = new TH1F(Form("mPbPb_Gen_spectra_cent%d",i),"",nbins, ptbins_long);
    // Truncate1D(mPbPb_GenInput[i], mPbPb_Gen[i]);
    // mPbPb_Gen[i]->Print("base");
    
    // mPbPb_RecoInput[i]->Print("base");
    // mPbPb_Reco[i] = new TH1F(Form("mPbPb_REco_spectra_cent%d",i),"",nbins, ptbins_long);
    // Truncate1D(mPbPb_RecoInput[i], mPbPb_Reco[i]);
    // mPbPb_Reco[i]->Print("base");
    
    // mPbPb_MatrixInput[i]->Print("base");
    // mPbPb_Matrix[i] = new TH2F(Form("mPbPb_Response_Matrix_cent%d",i),"",nbins_truncated, ptbins_long_truncated, nbins_truncated, ptbins_long_truncated);
    // Truncate2D(mPbPb_MatrixInput[i], mPbPb_Matrix[i]);
    // mPbPb_Matrix[i]->Print("base");
 
  }
  
  if(printDebug) cout<<"loaded the data and mc PbPb histograms from the files"<<endl;

  // get PP data
  if(printDebug) cout<<"Getting PP data and MC"<<endl;

  //fPP_in->ls();

  // dPP_1 = (TH1F*)fPP_in->Get(Form("hpp_HLT80_R%d_%s",radius,etaWidth)); 
  // dPP_1->Print("base");
  // dPP_2 = (TH1F*)fPP_in->Get(Form("hpp_HLT60_R%d_%s",radius,etaWidth));
  // dPP_2->Print("base");
  // dPP_3 = (TH1F*)fPP_in->Get(Form("hpp_HLT40_R%d_%s",radius,etaWidth));
  // dPP_3->Print("base");
  dPP_Comb = (TH1F*)fPP_in->Get(Form("hpp_HLTComb_R%d_%s",radius,etaWidth));
  //dPP_Comb = (TH1F*)dPP_1->Clone(Form("hpp_TrgComb_R%d_n20_eta_p20",radius,etaWidth));   
  //dPP_CombInput->Print("base");
  dPP_Comb->Scale(1./(5.3 * 1e9));
  
  // dPP_Comb = new TH1F("PP_MeasuredSpectra","",365, 30, 395);
  // Truncate1D(dPP_CombInput, dPP_Comb);

  //dPP_Comb = (TH1F*)dPP_Comb->Rebin(nbins, "PP_MeasuredSpectra", ptbins_long);
  dPP_Comb = (TH1F*)dPP_Comb->Rebin(10);
  dPP_Comb->SetName("PP_MeasuredSpectra");
  divideBinWidth(dPP_Comb);
  dPP_Comb->Print("base");
  
  // get PP MC
  // mPP_GenInput = (TH1F*)fPP_MC_in->Get(Form("hpp_anaBin_JetComb_gen_R%d_%s",radius,etaWidth));
  // mPP_GenInput->Print("base");
  // mPP_Gen = new TH1F("mPP_Gen_spectra","",nbins, ptbins_long);
  // Truncate1D(mPP_GenInput, mPP_Gen);
  // mPP_Gen->Print("base");
  
  // mPP_RecoInput = (TH1F*)fPP_MC_in->Get(Form("hpp_anaBin_JetComb_reco_R%d_%s",radius,etaWidth));
  // mPP_RecoInput->Print("base");
  // mPP_Reco = new TH1F("mPP_Reco_spectra","",nbins, ptbins_long);
  // Truncate1D(mPP_RecoInput, mPP_Reco);
  // mPP_Reco->Print("base");
  
  // mPP_MatrixInput = (TH2F*)fPP_MC_in->Get(Form("hpp_anaBin_matrix_HLT_R%d_%s",radius,etaWidth));
  // mPP_MatrixInput->Print("base");
  // mPP_Matrix = new TH2F("mPP_response_Matrix","",nbins_truncated, ptbins_long_truncated, nbins_truncated, ptbins_long_truncated);
  // Truncate2D(mPP_MatrixInput, mPP_Matrix);
  // mPP_Matrix->Print("base");

  // get PP MC
  // change from fPP_MC_in to fPP_in to run finebinscut
  //mPP_Gen = (TH1F*)fPP_MC_in->Get(Form("hpp_anaBin_JetComb_gen_R%d_20_eta_20",radius));
  mPP_Gen = (TH1F*)fPP_MC_in->Get(Form("hpp_JetComb_gen_R%d_20_eta_20",radius));
  //mPP_Gen->Rebin(nbins, "mPP_Gen", ptbins_long);
  mPP_Gen->Rebin(10);
  divideBinWidth(mPP_Gen);
  mPP_Gen->Print("base");

  //mPP_Reco = (TH1F*)fPP_MC_in->Get(Form("hpp_anaBin_JetComb_reco_R%d_20_eta_20",radius));
  mPP_Reco = (TH1F*)fPP_MC_in->Get(Form("hpp_JetComb_reco_R%d_20_eta_20",radius));
  //mPP_Gen->Rebin(nbins, "mPP_Gen", ptbins_long);
  mPP_Reco->Rebin(10);
  divideBinWidth(mPP_Reco);
  mPP_Reco->Print("base");

  //mPP_Matrix = (TH2F*)fPP_MC_in->Get(Form("hpp_anaBin_matrix_HLT_R%d_20_eta_20",radius));
  mPP_Matrix = (TH2F*)fPP_MC_in->Get(Form("hpp_matrix_HLT_R%d_20_eta_20",radius));
  mPP_Matrix->Rebin2D(10, 10);
  mPP_Matrix->Print("base");

  if(printDebug) cout<<"Filling the PbPb response Matrix"<<endl;

  // response matrix and unfolding for PbPb 
  // going to try it the way kurt has its. 

  for(int i = 0;i<nbins_cent;i++){
    if(printDebug) cout<<"centrality bin iteration = "<<i<<endl;
    TF1 *f = new TF1("f","[0]*pow(x+[2],[1])");
    f->SetParameters(1e10,-8.8,40);
    // TH1F *hGenSpectraCorr = (TH1F*)mPbPb_Matrix[i]->ProjectionX()->Clone(Form("hGenSpectraCorr_cent%d",i));
    // hGenSpectraCorr->Fit("f"," ");
    // hGenSpectraCorr->Fit("f","","");
    // hGenSpectraCorr->Fit("f","LL");
    // TH1F *fHist = functionHist(f,hGenSpectraCorr,Form("fHist_cent%d",i));// function that you get from the fitting 
    // hGenSpectraCorr->Divide(fHist);
    for (int y=1;y<=mPbPb_Matrix[i]->GetNbinsY();y++) {
      double sum=0;
      for (int x=1;x<=mPbPb_Matrix[i]->GetNbinsX();x++) {
	if (mPbPb_Matrix[i]->GetBinContent(x,y)<=1*mPbPb_Matrix[i]->GetBinError(x,y)) {
	  //in the above line mine had 0*getbinerror while Kurt's had 1*. 
	  mPbPb_Matrix[i]->SetBinContent(x,y,0);
	  mPbPb_Matrix[i]->SetBinError(x,y,0);
	}
	sum+=mPbPb_Matrix[i]->GetBinContent(x,y);
      }
      
      for (int x=1;x<=mPbPb_Matrix[i]->GetNbinsX();x++) {	   
	double ratio = 1;
	// if (hGenSpectraCorr->GetBinContent(x)!=0) ratio = 1e5/hGenSpectraCorr->GetBinContent(x);
	mPbPb_Matrix[i]->SetBinContent(x,y,mPbPb_Matrix[i]->GetBinContent(x,y)*ratio);
	mPbPb_Matrix[i]->SetBinError(x,y,mPbPb_Matrix[i]->GetBinError(x,y)*ratio);
      }
    }
    //mPbPb_Matrix[i]->Smooth(0);
    // Ok major differences here between my code and Kurt in b-jet Tools under Unfold - lines 469 and above.  
    
    mPbPb_Response[i] = (TH2F*)mPbPb_Matrix[i]->Clone(Form("mPbPb_Response_cent%d",i));
    TH1F *hProj = (TH1F*)mPbPb_Response[i]->ProjectionY()->Clone(Form("hProj_cent%d",i));

    for (int y=1;y<=mPbPb_Response[i]->GetNbinsY();y++) {
      double sum=0;
      for (int x=1;x<=mPbPb_Response[i]->GetNbinsX();x++) {
	if (mPbPb_Response[i]->GetBinContent(x,y)<=1*mPbPb_Response[i]->GetBinError(x,y)) {
	  // in the above if loop, kurt has 1*error and my old had 0*error
	  mPbPb_Response[i]->SetBinContent(x,y,0);
	  mPbPb_Response[i]->SetBinError(x,y,0);
	}
	sum+=mPbPb_Response[i]->GetBinContent(x,y);
      }
      
      for (int x=1;x<=mPbPb_Response[i]->GetNbinsX();x++) {  	
	if (sum==0) continue;
	double ratio = 1;
	//if(dPbPb_TrgComb[i]->GetBinContent(y)==0) ratio = 1e-100/sum;
	// else ratio = dPbPb_TrgComb[i]->GetBinContent(y)/sum
	ratio = 1./sum;
	if (hProj->GetBinContent(y)==0) ratio = 1e-100/sum;
	else ratio = hProj->GetBinContent(y)/sum;
	mPbPb_Response[i]->SetBinContent(x,y,mPbPb_Response[i]->GetBinContent(x,y)*ratio);
	mPbPb_Response[i]->SetBinError(x,y,mPbPb_Response[i]->GetBinError(x,y)*ratio);
      }
    }
    
    mPbPb_ResponseNorm[i] = (TH2F*)mPbPb_Matrix[i]->Clone(Form("mPbPb_ResponseNorm_cent%d",i));
    for (int x=1;x<=mPbPb_ResponseNorm[i]->GetNbinsX();x++) {
      double sum=0;
      for (int y=1;y<=mPbPb_ResponseNorm[i]->GetNbinsY();y++) {
	if (mPbPb_ResponseNorm[i]->GetBinContent(x,y)<=1*mPbPb_ResponseNorm[i]->GetBinError(x,y)) {
	  mPbPb_ResponseNorm[i]->SetBinContent(x,y,0);
	  mPbPb_ResponseNorm[i]->SetBinError(x,y,0);
	}
	sum+=mPbPb_ResponseNorm[i]->GetBinContent(x,y);
      }
      
      for (int y=1;y<=mPbPb_ResponseNorm[i]->GetNbinsY();y++) {  	
	if (sum==0) continue;
	double ratio = 1./sum;
	mPbPb_ResponseNorm[i]->SetBinContent(x,y,mPbPb_ResponseNorm[i]->GetBinContent(x,y)*ratio);
	mPbPb_ResponseNorm[i]->SetBinError(x,y,mPbPb_ResponseNorm[i]->GetBinError(x,y)*ratio);
      }
      
    }
    
    
  }

  
  if(printDebug) cout<<"Filling PP response Matrix"<<endl;

  // response matrix for pp.  
  // Kurt doesnt have this whole hGenSpectraCorr thing in his macro. need to check why the difference exists between out codes
  
  TF1 *fpp = new TF1("fpp","[0]*pow(x+[2],[1])");
  fpp->SetParameters(1e10,-8.8,40);
  // if(printDebug) cout<<"before getting the gen spectra corr matrix"<<endl;
  // TH1F *hGenSpectraCorrPP = (TH1F*)mPP_Matrix->ProjectionX()->Clone("hGenSpectraCorrPP");
  // if(printDebug) cout<<"after gettign the gen spectra corr matrix"<<endl;
  // hGenSpectraCorrPP->Fit("f"," ");
  // hGenSpectraCorrPP->Fit("f","","");
  // hGenSpectraCorrPP->Fit("f","LL");
  // TH1F *fHistPP = functionHist(fpp,hGenSpectraCorrPP,"fHistPP");// that the function that you get from the fitting 
  // hGenSpectraCorrPP->Divide(fHistPP);
  
  for (int y=1;y<=mPP_Matrix->GetNbinsY();y++) {
    double sum=0;
    for (int x=1;x<=mPP_Matrix->GetNbinsX();x++) {
      if (mPP_Matrix->GetBinContent(x,y)<=1*mPP_Matrix->GetBinError(x,y)) {
	mPP_Matrix->SetBinContent(x,y,0);
	mPP_Matrix->SetBinError(x,y,0);
      }
      sum+=mPP_Matrix->GetBinContent(x,y);
    }
    
    for (int x=1;x<=mPP_Matrix->GetNbinsX();x++) {	   
      double ratio = 1;
      // if (hGenSpectraCorrPP->GetBinContent(x)!=0) ratio = 1e5/hGenSpectraCorrPP->GetBinContent(x);
      mPP_Matrix->SetBinContent(x,y,mPP_Matrix->GetBinContent(x,y)*ratio);
      mPP_Matrix->SetBinError(x,y,mPP_Matrix->GetBinError(x,y)*ratio);
    }
  }
  // mPbPb_Matrix[i]->Smooth(0);
  
  // Ok major differences here between my code and Kurt in b-jet Tools under Unfold - lines 469 and above.  

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

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

  // for(int i = 0;i<nbins_cent;++i){
  //   dPbPb_TrgComb[i] = (TH1F*)dPbPb_TrgComb[i]->Rebin(nbins,Form("PbPb_measured_spectra_combined_cent%d",i),ptbins_long);
  //   divideBinWidth(dPbPb_TrgComb[i]);
  // }

  // dPP_Comb = (TH1F*)dPP_Comb->Rebin(nbins,"pp_measured_spectra_combined",ptbins_long);
  // divideBinWidth(dPP_Comb);
  // dPP_Comb->Scale(1./ dPP_Comb->GetBinContent(nbins));
  
  // Now that we have all the response matrix for the 6 centralities in PbPb and one pp spectra lets start doing the steps:
  // we have 39 pt bins, so we need 1000 gaussian functions for each pt bin.
  
  Int_t unfoldingTrials = 1000;
  Double_t meanMeasPbPb[nbins][nbins_cent], sigmaMeasPbPb[nbins][nbins_cent];
  Double_t meanMeasPP[nbins], sigmaMeasPP[nbins];
  Double_t meanUnfoldPbPb[nbins][nbins_cent][unfoldingTrials], sigmaUnfoldPbPb[nbins][nbins_cent][unfoldingTrials];
  Double_t meanUnfoldPP[nbins][unfoldingTrials], sigmaUnfoldPP[nbins][unfoldingTrials]; 
  
  TRandom3 *random = new TRandom3(0);

  TH1F * hPbPb_beforeUnfold_Gaussian_pt150[nbins_cent];
  TH1F * hPP_beforeUnfold_Gaussian_pt150; 
  hPP_beforeUnfold_Gaussian_pt150 = new TH1F("hPP_beforeUnfold_Gaussian_pt150","",1000, 0.1 * dPP_Comb->GetBinContent(dPP_Comb->FindBin(150)) , 1.9 * dPP_Comb->GetBinContent(dPP_Comb->FindBin(150)));
  
  for(int i = 0; i<nbins_cent; ++i)
    hPbPb_beforeUnfold_Gaussian_pt150[i] = new TH1F(Form("hPbPb_beforeUnfold_Gaussian_pt150_cent%d",i),"Before Unfolding pt bin at 150 value spectra",1000, 0.1 * dPbPb_TrgComb[i]->GetBinContent(dPbPb_TrgComb[i]->FindBin(150)), 1.9 * dPbPb_TrgComb[i]->GetBinContent(dPbPb_TrgComb[i]->FindBin(150)));
  

  for(int u = 0;u<unfoldingTrials;++u){
    cout<<"unfolding trial no = "<<u+1<<endl;
  
    for(int j = 0;j<nbins;++j){
      for(int i = 0;i<nbins_cent;++i){
      
	meanMeasPbPb[j][i] = dPbPb_TrgComb[i]->GetBinContent(j+1);
	sigmaMeasPbPb[j][i] = dPbPb_TrgComb[i]->GetBinError(j+1);

      }// centrality loop

      meanMeasPP[j] = dPP_Comb->GetBinContent(j+1);
      sigmaMeasPP[j] = dPP_Comb->GetBinError(j+1);
      
    }// nbins loop

    // now proceed to unfolding for each trial.

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

      TH1F * hPreUnfoldingSpectra = new TH1F("hPreUnfoldingSpectra","",nbins,0, 1000);
      TH1F * hAfterUnfoldingSpectra;

      for(int j = 0;j<nbins;++j){
	
	hPreUnfoldingSpectra->SetBinContent(j+1, random->Gaus(meanMeasPbPb[j][i], sigmaMeasPbPb[j][i]));
	hPreUnfoldingSpectra->SetBinError(j+1, sigmaMeasPbPb[j][i]/sqrt(unfoldingTrials));
	if(j+1 == dPbPb_TrgComb[i]->FindBin(150)) hPbPb_beforeUnfold_Gaussian_pt150[i]->Fill(random->Gaus(meanMeasPbPb[j][i], sigmaMeasPbPb[j][i]));
	
      }// nbins loop

      TH1F* hMCGen          = (TH1F*)mPbPb_Response[i]->ProjectionX();
      removeZero(hMCGen);
      bayesianUnfold myUnfoldingMulti(mPbPb_Matrix[i], hMCGen, 0);
      myUnfoldingMulti.unfold(hPreUnfoldingSpectra, BayesIter);

      hAfterUnfoldingSpectra = (TH1F*) myUnfoldingMulti.hPrior->Clone("hAfterUnfoldingSpectra");

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

	meanUnfoldPbPb[j][i][u] = hAfterUnfoldingSpectra->GetBinContent(j+1);
	sigmaUnfoldPbPb[j][i][u] = hAfterUnfoldingSpectra->GetBinError(j+1);

      }// nbins loop
      
      delete hPreUnfoldingSpectra;
      delete hAfterUnfoldingSpectra;
      delete hMCGen; 
      
    }// centrality loop

    cout<<"pp "<<endl;

    // now do it for the pp:
    TH1F * hPreUnfoldingSpectraPP = new TH1F("hPreUnfoldingSpectraPP","",nbins,0, 1000);
    TH1F * hAfterUnfoldingSpectraPP;
    
    for(int j = 0;j<nbins;++j){
	
      hPreUnfoldingSpectraPP->SetBinContent(j+1, random->Gaus(meanMeasPP[j], sigmaMeasPP[j]));
      hPreUnfoldingSpectraPP->SetBinError(j+1, sigmaMeasPP[j]/sqrt(unfoldingTrials));
      if(j+1 == dPP_Comb->FindBin(150)) hPP_beforeUnfold_Gaussian_pt150->Fill(random->Gaus(meanMeasPP[j], sigmaMeasPP[j]));
      
    }// nbins loop
    TH1F* hMCGenPP          = (TH1F*)mPP_Response->ProjectionX();
    removeZero(hMCGenPP);
    bayesianUnfold myUnfoldingMultiPP(mPP_Matrix, hMCGenPP, 0);
    myUnfoldingMultiPP.unfold(hPreUnfoldingSpectraPP, BayesIter);

    hAfterUnfoldingSpectraPP = (TH1F*) myUnfoldingMultiPP.hPrior->Clone("hAfterUnfoldingSpectraPP");

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

      meanUnfoldPP[j][u] = hAfterUnfoldingSpectraPP->GetBinContent(j+1);
      sigmaUnfoldPP[j][u] = hAfterUnfoldingSpectraPP->GetBinError(j+1);

    }// nbins loop

    delete hPreUnfoldingSpectraPP;
    delete hAfterUnfoldingSpectraPP;
    delete hMCGenPP; 
    
  }// unfolding trials loop


  // Now that we have all the necesary values we need, lets proceed to fill a histogram with the mean values for each ptbin and get the corrected values.
  TH1F * hAfterUnfoldingptBinDistribution[nbins];
  TH1F * hCorrUnfoldingPbPb[nbins_cent];

  // we need to store one gaussian histogram in the root file which we can plot 
  TH1F * hPbPb_Gaussian_pt150[nbins_cent];
  TH1F * hPP_Gaussian_pt150;


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

    hCorrUnfoldingPbPb[i] = new TH1F(Form("PbPb_BayesianUnfolded_cent%d",i),"Spectra after correction", nbins,0, 1000);
    hPbPb_Gaussian_pt150[i] = new TH1F(Form("PbPb_Gaussian_pt150_cent%d",i),"gaussian distribution of values at pt bin at 150",1000, 0.1 * dPbPb_TrgComb[i]->GetBinContent(dPbPb_TrgComb[i]->FindBin(150)), 1.9 * dPbPb_TrgComb[i]->GetBinContent(dPbPb_TrgComb[i]->FindBin(150)));

    for(int j = 0;j<nbins;++j){
      
      hAfterUnfoldingptBinDistribution[j] = new TH1F(Form("hAfterUnfoldingptBinDistribution_ptBin%d",j),"",100,	0, 1);
      for(int u = 0;u<unfoldingTrials;++u){

	hAfterUnfoldingptBinDistribution[j]->Fill(meanUnfoldPbPb[j][i][u]);
	if(j+1 == dPbPb_TrgComb[i]->FindBin(150)) hPbPb_Gaussian_pt150[i]->Fill(meanUnfoldPbPb[j][i][u]);

      }// unfolding trials loop

      hCorrUnfoldingPbPb[i]->SetBinContent(j+1, hAfterUnfoldingptBinDistribution[j]->GetMean());
      hCorrUnfoldingPbPb[i]->SetBinError(j+1, hAfterUnfoldingptBinDistribution[j]->GetRMS());

      delete hAfterUnfoldingptBinDistribution[j];
      
    }// nbins loop

  }// centrality loop

  // similar for the pp:
  TH1F * hAfterUnfoldingptBinDistributionPP[nbins];
  TH1F * hCorrUnfoldingPP;
  
  hCorrUnfoldingPP = new TH1F("PP_BayesianUnfolded","Spectra after unfolding error correction",nbins,0, 1000);
  hPP_Gaussian_pt150 = new TH1F("PP_Gaussian_pt100","gaussian distribution of values at pt bin at 150",1000, 0.1 * dPP_Comb->GetBinContent(dPP_Comb->FindBin(150)) , 1.9 * dPP_Comb->GetBinContent(dPP_Comb->FindBin(150)));
  
  for(int j = 0;j<nbins;++j){
    
    hAfterUnfoldingptBinDistributionPP[j] = new TH1F(Form("hAfterUnfoldingptBinDistributionPP_ptBin%d",j),"",100, 0, 1);
    for(int u = 0;u<unfoldingTrials;++u){
      
      hAfterUnfoldingptBinDistributionPP[j]->Fill(meanUnfoldPP[j][u]);
      if(j+1 == dPP_Comb->FindBin(150)) hPP_Gaussian_pt150->Fill(meanUnfoldPP[j][u]);
      
    }// unfolding trials loop
    
    hCorrUnfoldingPP->SetBinContent(j+1, hAfterUnfoldingptBinDistributionPP[j]->GetMean());
    hCorrUnfoldingPP->SetBinError(j+1, hAfterUnfoldingptBinDistributionPP[j]->GetRMS());
    
    delete hAfterUnfoldingptBinDistributionPP[j];
    
  }// nbins loop
    
  TFile f(Form("July20/HiForest_%disATLASCut_%ddo10GeVBins_data_driven_correction_ak%d.root" , isATLASCut, do10GeVBins, radius),"RECREATE");
  f.cd();

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

    //hCorrUnfoldingPbPb[i] = (TH1F*)hCorrUnfoldingPbPb[i]->Rebin(nbins_coarse, Form("PbPb_BayesianUnfolded_cent%d",i), ptbins_long_coarse);
    //divideBinWidth(hCorrUnfoldingPbPb[i]);
    //dPbPb_TrgComb[i] = (TH1F*)dPbPb_TrgComb[i]->Rebin(nbins_coarse, Form("PbPb_measured_cent%d",i), ptbins_long_coarse);
    //divideBinWidth(dPbPb_TrgComb[i]);

    hMinBias[i]->Write();
    hDataBeforeSub[i]->Write();
    hDataAfterSub[i]->Write();
    
    hCorrUnfoldingPbPb[i]->Scale(166 * 1e9);
    hCorrUnfoldingPbPb[i]->Write();
    hCorrUnfoldingPbPb[i]->Print("base");

    dPbPb_TrgComb[i]->Scale(166 * 1e9);
    dPbPb_TrgComb[i]->SetName(Form("PbPb_data_minbiasSub_cent%d",i));
    //dPbPb_TrgComb[i]->Scale(145.156 * 1e9);
    dPbPb_TrgComb[i]->Write();
    dPbPb_TrgComb[i]->Print("base");

    hPbPb_beforeUnfold_Gaussian_pt150[i]->Write();
    hPbPb_beforeUnfold_Gaussian_pt150[i]->Print("base");
    
    hPbPb_Gaussian_pt150[i]->Write();
    hPbPb_Gaussian_pt150[i]->Print("base");

    mPbPb_Matrix[i]->Write();
    
  }

  //hCorrUnfoldingPP = (TH1F*)hCorrUnfoldingPP->Rebin(nbins_coarse, "PP_BayesianUnfolded", ptbins_long_coarse);
  //divideBinWidth(hCorrUnfoldingPP);
  //dPP_Comb = (TH1F*)dPP_Comb->Rebin(nbins_coarse, "PP_measured", ptbins_long_coarse);  
  //divideBinWidth(dPP_Comb);
  
  hCorrUnfoldingPP->Scale(5.3 * 1e9);
  hCorrUnfoldingPP->Write();
  hCorrUnfoldingPP->Print("base");

  dPP_Comb->Scale(5.3 * 1e9);
  dPP_Comb->Write();
  dPP_Comb->Print("base");

  hPP_beforeUnfold_Gaussian_pt150->Write();
  hPP_beforeUnfold_Gaussian_pt150->Print("base");
  
  hPP_Gaussian_pt150->Write();
  hPP_Gaussian_pt150->Print("base");
  mPP_Matrix->Write();

  f.Write();
  f.Close();

  // make the data driven Error correction histograms and plots here:
  
  TH1F * hError_Meas[nbins_cent+1], * hError_Fixed[nbins_cent+1];
  for(int i = 0; i<nbins_cent+1; ++i){
    cout<<"centrality "<<i<<endl;
    if(i < nbins_cent){
      hError_Meas[i]  = new TH1F(Form("hError_Meas_cent%d",i),"",nbins, 0, 1000);
      hError_Fixed[i] = new TH1F(Form("hError_Fixed_cent%d",i),"",nbins, 0, 1000);
    }
    if(i == nbins_cent){
      hError_Meas[i]  = new TH1F(Form("hError_PP_Meas_cent%d",i),"",nbins, 0, 1000);
      hError_Fixed[i] = new TH1F(Form("hError_PP_Fixed_cent%d",i),"",nbins, 0, 1000);
    }

    for(int j = 1; j<=nbins; ++j){
      //cout<<"ptbins "<<j<<endl;
      if(i < nbins_cent){
	if(dPbPb_TrgComb[i]->GetBinContent(j)!=0) hError_Meas[i]->SetBinContent(j, (float)dPbPb_TrgComb[i]->GetBinError(j)/dPbPb_TrgComb[i]->GetBinContent(j));
        //hError_Meas[i]->SetBinContent(j, (float)dPbPb_TrgComb[i]->GetBinError(j));
	if(hCorrUnfoldingPbPb[i]->GetBinContent(j)!=0)hError_Fixed[i]->SetBinContent(j, (float)hCorrUnfoldingPbPb[i]->GetBinError(j)/hCorrUnfoldingPbPb[i]->GetBinContent(j));
	cout<<j<<" "<<hError_Fixed[i]->GetBinContent(j)<<endl;
	//hError_Fixed[i]->SetBinContent(j, (float)hCorrUnfoldingPbPb[i]->GetBinError(j));
      }
      if(i == nbins_cent){
	hError_Meas[i]->SetBinContent(j, (float)dPP_Comb->GetBinError(j)/dPP_Comb->GetBinContent(j));
	//hError_Meas[i]->SetBinContent(j, (float)dPP_Comb->GetBinError(j));
	hError_Fixed[i]->SetBinContent(j, (float)hCorrUnfoldingPP->GetBinError(j)/hCorrUnfoldingPP->GetBinContent(j));
	//hError_Fixed[i]->SetBinContent(j, (float)hCorrUnfoldingPP->GetBinError(j));
      }
    }
    
    hError_Meas[i]->SetAxisRange(50, 299, "X");
    //hError_Meas[i]->Print("base");
    //hError_Fixed[i]->Print("base");
    //hError_Meas[i]->SetAxisRange(1e-12, 1, "Y");
  }
  //cout<<" passed the loop"<<endl;

  TCanvas * cSpectra = new TCanvas("cSpectra","",1200,1000);
  makeMultiPanelCanvas(cSpectra,3,2,0.0,0.0,0.2,0.15,0.07);  
  for(int i = 0; i<nbins_cent; ++i){
    //cout<<i<<endl;
    cSpectra->cd(nbins_cent-i);
    cSpectra->cd(nbins_cent-i)->SetLogy();
    dPbPb_TrgComb[i]->SetMarkerStyle(24);
    dPbPb_TrgComb[i]->SetMarkerColor(kBlack);
    makeHistTitle(dPbPb_TrgComb[i]," ","jet pT","dN/dpT");
    dPbPb_TrgComb[i]->SetAxisRange(50, 299, "X");
    dPbPb_TrgComb[i]->Draw("p");

    hCorrUnfoldingPbPb[i]->SetMarkerStyle(33);
    hCorrUnfoldingPbPb[i]->SetMarkerColor(kRed);
    hCorrUnfoldingPbPb[i]->Draw("psame");

  }
  TLegend * Spec = myLegend(0.55,0.55,0.75,0.75);
  cSpectra->cd(1);
  putCMSPrel();
  Spec->AddEntry(dPbPb_TrgComb[0],"Measured","pl");
  Spec->AddEntry(hCorrUnfoldingPbPb[0],"Data Driven Correction","pl");
  Spec->SetTextSize(0.04);
  Spec->Draw();
  
  cSpectra->SaveAs(Form("%sUnfoldingSpectra_fromDataDrivenMacro_PbPb_%s_R%d_%d_hiForest_%dGeVCut.pdf",outLocation,etaWidth,radius,date.GetDate(),unfoldingCut),"RECREATE");

  
  TCanvas * cErrorFix = new TCanvas("cErrorFix","",1200,1000);
  makeMultiPanelCanvas(cErrorFix,3,2,0.0,0.0,0.2,0.15,0.07);  
  for(int i = 0; i<nbins_cent; ++i){
    //cout<<i<<endl;
    cErrorFix->cd(nbins_cent-i);
    cErrorFix->cd(nbins_cent-i)->SetLogy();
    makeHistTitle(hError_Meas[i]," ","jet pT","Error/Content");
    hError_Meas[i]->SetMarkerStyle(24);
    hError_Meas[i]->SetMarkerColor(kBlack);
    hError_Meas[i]->Draw("p");

    hError_Fixed[i]->SetMarkerStyle(33);
    hError_Fixed[i]->SetMarkerColor(kRed);
    hError_Fixed[i]->Draw("psame");

  }
  TLegend * err = myLegend(0.55,0.55,0.75,0.75);
  cErrorFix->cd(1);
  putCMSPrel();
  err->AddEntry(hError_Meas[0],"Measured","pl");
  err->AddEntry(hError_Fixed[0],"Data Driven Correction","pl");
  err->SetTextSize(0.04);
  err->Draw();
  
  cErrorFix->SaveAs(Form("%sUnfoldingErrorFix_fromDataDrivenMacro_PbPb_%s_R%d_%d_hiForest_%dGeVCut.pdf",outLocation,etaWidth,radius,date.GetDate(),unfoldingCut),"RECREATE");

  TCanvas * cErrorFixPP = new TCanvas("cErrorFixPP","",800,600);
  cErrorFixPP->SetLogy();
  hError_Meas[nbins_cent]->SetMarkerStyle(24);
  hError_Meas[nbins_cent]->SetMarkerColor(kBlack);
  hError_Meas[nbins_cent]->Draw("p");
  
  hError_Fixed[nbins_cent]->SetMarkerStyle(33);
  hError_Fixed[nbins_cent]->SetMarkerColor(kRed);
  hError_Fixed[nbins_cent]->Draw("psame");
  TLegend * errPP = myLegend(0.55,0.55,0.75,0.75);
  putCMSPrel();
  errPP->AddEntry(hError_Meas[nbins_cent],"Measured","pl");
  errPP->AddEntry(hError_Fixed[nbins_cent],"Data Driven Correction","pl");
  errPP->SetTextSize(0.04);
  errPP->Draw();
  
  cErrorFixPP->SaveAs(Form("%sUnfoldingErrorFix_fromDataDrivenMacro_PP_%s_R%d_%d_hiForest_%dGeVCut.pdf",outLocation,etaWidth,radius,date.GetDate(),unfoldingCut),"RECREATE");
  
  timer.Stop();
  if(printDebug) cout<<"CPU time (mins) = "<<(Float_t)timer.CpuTime()/60<<endl;
  if(printDebug) cout<<"Real tile (mins) = "<<(Float_t)timer.RealTime()/60<<endl;


}
Example #19
0
void plot_ljpsi(const char* fdata, const char* fmc) {
   TFile *tfd = TFile::Open(fdata);
   TFile *tfm = TFile::Open(fmc);

   TCanvas *c1 = new TCanvas();
   c1->cd();
   TPad *p1 = new TPad("p1","",0,0,1,0.33);
   p1->SetBottomMargin(2.*gStyle->GetPadBottomMargin());
   p1->SetTopMargin(0);
   p1->SetFrameBorderMode(0);
   p1->SetBorderMode(0);
   p1->SetBorderSize(0);
   p1->SetGridy();
   if (datamc) p1->Draw();
   TPad *p2 = new TPad("p2","",0,0.33,1,1);
   // p2->SetTopMargin(gStyle->GetPadTopMargin()/(1.-0.2));
   p2->SetBottomMargin(0);
   p2->SetFrameBorderMode(0);
   p2->SetBorderMode(0);
   p2->SetBorderSize(0);
   // p2->SetLogy();
   if (datamc) p2->Draw();
   p1->cd();
   if (!datamc) c1->cd();

   TF1 *dg = new TF1("f1","[0]*([1]*TMath::Gaus(x,[2],[3])+(1-[1])*TMath::Gaus(x,[4],[3]*[5]))",-0.2,0.04);
   dg->SetParLimits(0,0,1e15);
   dg->SetParLimits(1,0.5,1);
   dg->SetParLimits(2,-0.05,0.05);
   dg->SetParLimits(3,0,0.1);
   dg->SetParLimits(4,-0.05,0.05);
   dg->SetParLimits(5,0,100);
   dg->SetParameters(1000,0.8,1e-3,0.03,1e-4,2.);

   TIter next(tfd->GetListOfKeys()); TObject *obj;
   while ((obj = next())) {
      obj = ((TKey*) obj)->ReadObj();
      if (TString(obj->ClassName()) == "TH1F") {
         TH1F *hdata = (TH1F*) tfd->Get(obj->GetName());
         TH1F *hmc = (TH1F*) tfm->Get(obj->GetName());
         // hdata->Rebin(6);
         // hmc->Rebin(6);

         if (!integrate) {
            double int_data = hdata->Integral(hdata->FindBin(-0.015), hdata->FindBin(0.015));
            double int_mc = hmc->Integral(hmc->FindBin(-0.015), hmc->FindBin(0.015));
            hmc->Scale(int_data/int_mc);
         } else {
            double int_mc_all = hmc->Integral(0, hmc->GetNbinsX()+1);
            double int_data_all = hdata->Integral(0, hdata->GetNbinsX()+1);
            hmc->Scale(1./int_mc_all);
            hdata->Scale(1./int_data_all);
            double int_data = hdata->Integral(0, hdata->FindBin(0.));
            double int_mc = hmc->Integral(0, hmc->FindBin(0.));
            hdata->Scale(int_mc/int_data); 
            integrateHist(hdata);
            integrateHist(hmc);
         }
         hdata->GetXaxis()->SetTitle("#font[12]{l}_{J/#psi} [mm]");
         hdata->GetYaxis()->SetTitle("Entries");
         if (integrate) hdata->GetYaxis()->SetTitle("c.d.f.");

         // read the bin from the name
         TString thname(hdata->GetName());
         bool isfwd = (thname.Index("fwd") != kNPOS);
         int pos1 = thname.Index("pt")+2;
         int pos2 = thname.Index("-")-pos1;
         TString tsubstr(thname(pos1,pos2));
         float ptmin = atof(tsubstr.Data());
         pos1 = thname.Index("-")+1;
         pos2 = thname.Length();
         tsubstr = TString(thname(pos1,pos2));
         float ptmax = atof(tsubstr.Data());

         if (datamc) p2->cd();
         hdata->Draw();
         hmc->SetLineColor(kRed);
         hmc->SetMarkerColor(kRed);
         hmc->Draw("same");
         gPad->Update();

         // display the position of the ctau cut
         double a=1,b=1;
         if (!isfwd){a=ctaucut_a_mid_pp; b=ctaucut_b_mid_pp;} 
         else {a=ctaucut_a_fwd_pp; b=ctaucut_b_fwd_pp;}
         double cutmin = a + b / ptmin;
         double cutmax = a + b / ptmax;
         double xmin, xmax, ymin, ymax;
         TBox *tb = new TBox(cutmin,gPad->GetUymin(),cutmax,gPad->GetUymax());
         tb->SetFillColor(kBlack);
         tb->SetFillStyle(3003);
         tb->Draw();

         if (integrate) {
            TLine *tl = new TLine(hdata->GetXaxis()->GetXmin(),0.9,hdata->GetXaxis()->GetXmax(),0.9);
            tl->SetLineStyle(3);
            tl->SetLineColor(kBlack);
            tl->SetLineWidth(5);
            tl->Draw();
         }

         if (datamc) {
            p1->cd();
            TH1F *hratio = (TH1F*) hdata->Clone("hratio");
            hratio->Divide(hmc);
            hratio->GetYaxis()->SetTitle("data/MC");
            hratio->GetYaxis()->SetRangeUser(0.5,1.5);
            hratio->GetXaxis()->SetLabelSize(2.*hratio->GetXaxis()->GetLabelSize());
            hratio->GetXaxis()->SetTitleSize(2.*hratio->GetXaxis()->GetTitleSize());
            hratio->GetYaxis()->SetLabelSize(2.*hratio->GetYaxis()->GetLabelSize());
            hratio->GetYaxis()->SetTitleSize(2.*hratio->GetYaxis()->GetTitleSize());
            hratio->Draw();

            p2->cd();
         }

         // dg->SetParameters(1000,0.8,1e-3,0.03,1e-4,2.);
         // dg->SetParameter(0,int_data);
         // dg->SetParLimits(0,0,int_data*100.);
         // hdata->Fit(dg, "LERQ");
         // double sigma_data = dg->GetParameter(3);
         // double dsigma_data = dg->GetParError(3);
         // dg->SetRange(-5.*sigma_data,1.5*sigma_data);
         // hdata->Fit(dg, "LERQ");
         // sigma_data = dg->GetParameter(3);
         // dsigma_data = dg->GetParError(3);
         // dg->SetRange(-5.*sigma_data,1.5*sigma_data);
         // hdata->Fit(dg, "LERQ");
         // sigma_data = dg->GetParameter(3);
         // dsigma_data = dg->GetParError(3);
         // hmc->Fit(dg, "LERQ");
         // double sigma_mc = dg->GetParameter(3);
         // double dsigma_mc = dg->GetParError(3);

         double lx1=0.61, lx2=0.9, ly1=0.6, ly2=0.88;
         if (integrate) {ly1-=0.4; ly2-=0.4;}
         TLegend *tleg = new TLegend(lx1,ly1,lx2,ly2);
         tleg->SetBorderSize(0);
         TString header("#splitline{");
         header += isfwd ? "1.6<|y|<2.4" : "|y|<1.6";
         header += Form("}{%.1f<pt<%.1f GeV/c}",ptmin,ptmax);
         tleg->SetHeader(header);
         // tleg->AddEntry(hdata,Form("pp data (#sigma = %.3f +/- %.3f)",sigma_data,dsigma_data),"lp");
         // tleg->AddEntry(hmc,Form("pp prompt J/#psi mc (#sigma = %.3f +/- %.3f)",sigma_mc,dsigma_mc),"lp");
         tleg->AddEntry(hdata,"data","lp");
         tleg->AddEntry(hmc,"prompt J/#psi mc","lp");
         tleg->Draw();
         c1->SaveAs(Form("%s.pdf",hdata->GetName()));
         c1->SaveAs(Form("%s.png",hdata->GetName()));
      }
   }
}
void AnalyseGammaCorrelation(TString nameFileData = "GammaConvCorr_Data.root", TString cutSelection = "001023", TString suffix ="eps",TString optData = "Data", TString optEnergy = "7TeV", TString optMCGenerator = ""){
		
	gROOT->Reset();
	gROOT->SetStyle("Plain");
 
	TString collisionSystem;
	if(optEnergy.CompareTo("7TeV") == 0){
			collisionSystem = 			"pp @  #sqrt{#it{s}} = 7 TeV";          
	} else if( optEnergy.CompareTo("2.76TeV") == 0) {
		collisionSystem = 			"pp @ #sqrt{#it{s}} = 2.76 TeV";
	} else if( optEnergy.CompareTo("900GeV") == 0) {
			collisionSystem = 			"pp @ #sqrt{#it{s}} = 0.9 TeV";
	} else if( optEnergy.CompareTo("HI") == 0) {
			collisionSystem =			"PbPb @ #sqrt{#it{s}_{_{NN}}} = 2.76 TeV";
	} else {
			cout << "No correct collision system specification, has been given" << endl;
			return;         
	}

	TString textGenerator;
	if(optMCGenerator.CompareTo("") ==0){
		textGenerator = "";
	} else {
		textGenerator = optMCGenerator;
	}
	TString outputDirectory;
	TString outputDirectory1;
	TString outputDirectory2;
	outputDirectory1 =	 Form("%s",cutSelection.Data());
	outputDirectory2 =	 Form("%s/%s/",cutSelection.Data(),suffix.Data());
	outputDirectory =	 	Form("%s/%s/GammaCorrelation",cutSelection.Data(),suffix.Data());
	gSystem->Exec("mkdir "+outputDirectory1);
	gSystem->Exec("mkdir "+outputDirectory2);
	gSystem->Exec("mkdir "+outputDirectory);
     
	StyleSettingsThesis();
//  	SetPlotStyle();
	SetPlotStyleNConts(99);
	
	//How big should the right margin in 2D plots be? 
	Float_t 	rightMargin = 			0.01;
	Float_t 	leftMargin = 			0.15;
	Float_t 	rightMargin2 = 		0.12;
	Float_t 	leftMargin2 = 			0.12;
	Float_t 	bottomMargin = 		0.07;
	Float_t 	topMargin = 		0.01;
	// Array defintion for printing Logo in right upper corner
	Float_t 	floatLocationRightUp[4]= {0.8,0.605,0.15, 0.02};
	Float_t 	floatLocationRightUpR[4]= {0.8,0.45,0.15, 0.02};
	Float_t 	floatLocationRightUp2[4]= {0.8,0.76,0.15, 0.02};
	Float_t 	floatLocationRightDown[4]=	{0.7,0.23,0.15, 0.02};
	Float_t 	floatLocationRightUp2D[4]=	{0.68,0.775,0.11, 0.02};
	Float_t 	floatLocationRightUp2DXY[4]=	{0.69,0.85,0.115, 0.025};
	Float_t 	floatLocationRightUp2DZR[4]=	{0.69,0.23,0.115, 0.025};
	// Array defintion for printing Logo in left upper corner
	Float_t 	floatLocationLeftUp[4]=		{0.18,0.76, 0.15, 0.02};
	// Array defintion for printing text in right upper corner
	Float_t 	floatLocationRightUpText[4]=	{0.16,0.92,0.15, 0.04};
	Float_t 	floatLocationRightUpText2[4]=	{0.7,0.8,0.15, 0.04};
	
	TFile* fileGammaCorr = new TFile(nameFileData.Data());
	TDirectory*  directoryGammaCorr = 		(TDirectory*)fileGammaCorr->Get(Form("CorrGamma_%s",  cutSelection.Data())); 	
	
	TH1F*	histoAssociatedGamma = 	(TH1F*)directoryGammaCorr->Get("ESD_AssociatedGamma");
	Float_t numberOfTriggerGammas = histoAssociatedGamma->Integral();
	cout << "number of trigger photons: \t " << numberOfTriggerGammas << endl;
	histoAssociatedGamma->Scale(1/numberOfTriggerGammas);
	PlotStandard1D( histoAssociatedGamma, Form("%s/%s_NumberAssociatedGamma.%s",outputDirectory.Data(),optData.Data(),suffix.Data()), "", "number associated #gamma", "N_{#gamma, assoc}/N_{#gamma, trig}", kTRUE, 0, 20, kFALSE, 1.5,1e-7, kTRUE, 0, 1, floatLocationRightUp2DXY);
// 	delete histoAssociatedGamma;
	
	TH1F*	histoAssociatedCh =  (TH1F*)directoryGammaCorr->Get("ESD_AssociatedCh");
	histoAssociatedCh->Scale(1/numberOfTriggerGammas);
	PlotStandard1D( histoAssociatedCh, Form("%s/%s_NumberAssociatedCharged.%s",outputDirectory.Data(),optData.Data(),suffix.Data()), "", "number associated h^{+/-}", "N_{#gamma, ch}/N_{#gamma, trig}", kTRUE, 0, 200, kFALSE, 1.5,1e-9, kTRUE, 0, 1, floatLocationRightUp2DXY);
// 	delete histoAssociatedCh;

	TH2F*	histoCorrGamma_Phi_Pt = (TH2F*)directoryGammaCorr->Get("ESD_CorrGamma_Phi_Pt");
	histoCorrGamma_Phi_Pt->Scale(1./numberOfTriggerGammas);
 	ConvGammaRebinWithBinCorrection2D(histoCorrGamma_Phi_Pt, 1, 1, 3);
	PlotStandard2D( histoCorrGamma_Phi_Pt , Form("%s/%s_GammaCorr_Phi_Pt.%s",outputDirectory.Data(),optData.Data(),suffix.Data()), "", "#phi (rad)", "p_{t} (GeV/c)", "#frac{dN_{#gamma,trig}}{N_{#gamma, trig} d#phi dp_{t}}",  kTRUE, -TMath::Pi(), TMath::Pi(),kTRUE, 0.1, 50., kTRUE,  9e-6, histoCorrGamma_Phi_Pt->GetMaximum(), 0,1, 1, floatLocationRightUp2DXY,1000,880,rightMargin2, leftMargin2,bottomMargin,topMargin, "Perf","COLZ");
	delete histoCorrGamma_Phi_Pt;

	TH2F*	histoCorrGamma_Eta_Pt = (TH2F*)directoryGammaCorr->Get("ESD_CorrGamma_Eta_Pt");
	histoCorrGamma_Eta_Pt->Scale(1./numberOfTriggerGammas);
 	ConvGammaRebinWithBinCorrection2D(histoCorrGamma_Eta_Pt, 1, 1, 3);
	PlotStandard2D( histoCorrGamma_Eta_Pt , Form("%s/%s_GammaCorr_Eta_Pt.%s",outputDirectory.Data(),optData.Data(),suffix.Data()), "", "#eta", "p_{t} (GeV/c)", "#frac{dN_{#gamma,trig}}{N_{#gamma, trig} d#phi dp_{t}}", kTRUE, -0.9, 0.9,kTRUE, 0.1, 50., kTRUE,  9e-6, histoCorrGamma_Eta_Pt->GetMaximum(), 0,1, 1, floatLocationRightUp2DXY,1000,880,rightMargin2, leftMargin2,bottomMargin,topMargin, "Perf","COLZ");
	delete histoCorrGamma_Eta_Pt;

	
	TH2F*	histoCorrGamma_Phi_Eta = (TH2F*)directoryGammaCorr->Get("ESD_CorrGamma_Phi_Eta");
	histoCorrGamma_Phi_Eta->Scale(1./numberOfTriggerGammas);
	ConvGammaRebinWithBinCorrection2D(histoCorrGamma_Phi_Eta, 4, 4, 3);
	PlotStandard2D( histoCorrGamma_Phi_Eta , Form("%s/%s_GammaCorr_PhiCh_EtaCh.%s",outputDirectory.Data(),optData.Data(),suffix.Data()), "", "#phi (rad)", "#eta", "#frac{dN_{#gamma,trig}}{N_{#gamma, trig} d#eta d#phi}",  kTRUE, -TMath::Pi(), TMath::Pi(),kTRUE, -0.9, 0.9, kTRUE,  9e-2, histoCorrGamma_Phi_Eta->GetMaximum(), 0, 0, 1, floatLocationRightUp2DXY,1000,880,rightMargin, leftMargin,bottomMargin,topMargin, "Perf","SURF7");
	delete histoCorrGamma_Phi_Eta;
	
 	TH2F*	histoCorrGamma_dPhiCh_dEtaCh = (TH2F*)directoryGammaCorr->Get("ESD_CorrGamma_dPhiCh_dEtaCh");
	histoCorrGamma_dPhiCh_dEtaCh->Scale(1./numberOfTriggerGammas);
	ConvGammaRebinWithBinCorrection2D(histoCorrGamma_dPhiCh_dEtaCh, 4, 3, 3);
	PlotStandard2D( histoCorrGamma_dPhiCh_dEtaCh , Form("%s/%s_GammaCorr_dPhiCh_dEtaCh.%s",outputDirectory.Data(),optData.Data(),suffix.Data()), "", "#Delta#phi (rad)", "#Delta#eta", "#frac{dN_{ch,ass}}{N_{#gamma, trig} d#Delta#eta d#Delta#phi}", kFALSE, 0., 15., kTRUE, -1., 1.,kTRUE,  6.e-2, histoCorrGamma_dPhiCh_dEtaCh->GetMaximum(), 0, 0, 1, floatLocationRightUp2DXY,1000,880,rightMargin, leftMargin,bottomMargin,topMargin, "Perf","SURF7");
	delete histoCorrGamma_dPhiCh_dEtaCh;
	
 	TH2F*	histoCorrGamma_dPhiCh_dEtaCh_PtA1GeV_PtT2GeV = (TH2F*)directoryGammaCorr->Get("ESD_CorrGamma_dPhiCh_dEtaCh_PtA1GeV_PtT2GeV");
	histoCorrGamma_dPhiCh_dEtaCh_PtA1GeV_PtT2GeV->Scale(1./numberOfTriggerGammas);
	ConvGammaRebinWithBinCorrection2D(histoCorrGamma_dPhiCh_dEtaCh_PtA1GeV_PtT2GeV, 4, 3, 3);
	PlotStandard2D( histoCorrGamma_dPhiCh_dEtaCh_PtA1GeV_PtT2GeV , Form("%s/%s_GammaCorr_dPhiCh_dEtaCh_PtA1GeV_PtT2GeV.%s",outputDirectory.Data(),optData.Data(),suffix.Data()), "p_{t}^{A} > 1 GeV/c, p_{t}^{T} > 2 GeV/c", "#Delta#phi (rad)", "#Delta#eta","#frac{dN_{ch,ass}}{N_{#gamma, trig} d#Delta#eta d#Delta#phi}", kFALSE, 0., 15., kTRUE, -1., 1.,kTRUE,  1.e-3, histoCorrGamma_dPhiCh_dEtaCh_PtA1GeV_PtT2GeV->GetMaximum(), 0,0,  1, floatLocationRightUp2DXY,1000,880,rightMargin, leftMargin,bottomMargin,topMargin, "Perf","SURF7","p_{t}^{A} > 1 GeV/c, p_{t}^{T} > 2 GeV/c");
	delete histoCorrGamma_dPhiCh_dEtaCh_PtA1GeV_PtT2GeV;
	
	TH2F*	histoCorrGamma_dPhiCh_dEtaCh_PtA1GeV_PtT5GeV = (TH2F*)directoryGammaCorr->Get("ESD_CorrGamma_dPhiCh_dEtaCh_PtA1GeV_PtT5GeV");
	histoCorrGamma_dPhiCh_dEtaCh_PtA1GeV_PtT5GeV->Scale(1./numberOfTriggerGammas);
	ConvGammaRebinWithBinCorrection2D(histoCorrGamma_dPhiCh_dEtaCh_PtA1GeV_PtT5GeV, 4, 3, 3);
	PlotStandard2D( histoCorrGamma_dPhiCh_dEtaCh_PtA1GeV_PtT5GeV , Form("%s/%s_GammaCorr_dPhiCh_dEtaCh_PtA1GeV_PtT5GeV.%s",outputDirectory.Data(),optData.Data(),suffix.Data()), "p_{t}^{A} > 1 GeV/c, p_{t}^{T} > 5 GeV/c", "#Delta#phi (rad)", "#Delta#eta", "#frac{dN_{ch,ass}}{N_{#gamma, trig} d#Delta#eta d#Delta#phi}", kFALSE, 0., 15., kTRUE, -1., 1.,kTRUE,  1.e-5, histoCorrGamma_dPhiCh_dEtaCh_PtA1GeV_PtT5GeV->GetMaximum(), 0, 0, 1, floatLocationRightUp2DXY,1000,880,rightMargin, leftMargin,bottomMargin,topMargin, "Perf","SURF7","p_{t}^{A} > 1 GeV/c, p_{t}^{T} > 5 GeV/c");
	delete histoCorrGamma_dPhiCh_dEtaCh_PtA1GeV_PtT5GeV;
	
	TH2F*	histoCorrGamma_dPhiGa_dEtaGa =(TH2F*)directoryGammaCorr->Get("ESD_CorrGamma_dPhiGa_dEtaGa");
	histoCorrGamma_dPhiGa_dEtaGa->Scale(1./numberOfTriggerGammas);
	ConvGammaRebinWithBinCorrection2D(histoCorrGamma_dPhiGa_dEtaGa, 4, 3, 3);
	PlotStandard2D( histoCorrGamma_dPhiGa_dEtaGa , Form("%s/%s_GammaCorr_dPhiGa_dEtaGa.%s",outputDirectory.Data(),optData.Data(),suffix.Data()), "", "#Delta#phi (rad)", "#Delta#eta", "#frac{dN_{#gamma,ass}}{N_{#gamma, trig} d#Delta#eta d#Delta#phi}", kFALSE, 0., 15., kTRUE, -1., 1.,kTRUE,  2.e-3, histoCorrGamma_dPhiGa_dEtaGa->GetMaximum(), 0,0,  1, floatLocationRightUp2DXY,1000,880,rightMargin, leftMargin,bottomMargin,topMargin, "Perf","SURF7");
	delete histoCorrGamma_dPhiGa_dEtaGa;
	
// 	TH2F*	histoCorrGamma_IsoCh_PtTrig = (TH2F*)directoryGammaCorr->Get("ESD_CorrGamma_IsoCh_PtTrig");
// 	TH2F*	histoCorrGamma_IsoGa_PtTrig = (TH2F*)directoryGammaCorr->Get("ESD_CorrGamma_IsoGa_PtTrig");
 	TH2F*	histoCorrGamma_IsoMin_Pt = (TH2F*)directoryGammaCorr->Get("ESD_CorrGamma_IsoMin_Pt");
	histoCorrGamma_IsoMin_Pt->Scale(1./numberOfTriggerGammas);
	ConvGammaRebinWithBinCorrection2D(histoCorrGamma_IsoMin_Pt, 1, 1, 3);
 	PlotStandard2D( histoCorrGamma_IsoMin_Pt , Form("%s/%s_GammaCorr_IsoMin_PtTrig.%s",outputDirectory.Data(),optData.Data(),suffix.Data()), "", "R_{min}", "p_{t}^{T} (GeV/c)", "#frac{dN_{#gamma,trig}}{N_{#gamma, trig} dR dp_{t}}", kFALSE, 0., 15., kFALSE, -1., 1.,kTRUE,  2.e-5, histoCorrGamma_IsoMin_Pt->GetMaximum(), 0,0,  1, floatLocationRightUp2DXY,1000,880,rightMargin2, leftMargin2,bottomMargin,topMargin, "Perf","Colz");

	TH3F*	histoCorrGamma_dPhiCh_PtAssoc_PtTrig = (TH3F*)directoryGammaCorr->Get("ESD_CorrGamma_dPhiCh_PtAssoc_PtTrig");
	TH2D* histo2DGamma_dPhi_PtTrig = (TH2D*)histoCorrGamma_dPhiCh_PtAssoc_PtTrig->Project3D("zx_CorrGammaPhiA");
	histoCorrGamma_dPhiCh_PtAssoc_PtTrig->GetYaxis()->SetRange(histoCorrGamma_dPhiCh_PtAssoc_PtTrig->GetYaxis()->FindBin(1.),histoCorrGamma_dPhiCh_PtAssoc_PtTrig->GetYaxis()->FindBin(50.));
	TH2D* histo2DGamma_dPhi_PtTrig_minPtAss05 = (TH2D*)histoCorrGamma_dPhiCh_PtAssoc_PtTrig->Project3D("zx_CorrGammaPhiB");
	histoCorrGamma_dPhiCh_PtAssoc_PtTrig->GetYaxis()->SetRange(histoCorrGamma_dPhiCh_PtAssoc_PtTrig->GetYaxis()->FindBin(2.),histoCorrGamma_dPhiCh_PtAssoc_PtTrig->GetYaxis()->FindBin(50.));
	TH2D* histo2DGamma_dPhi_PtTrig_minPtAss1 = (TH2D*)histoCorrGamma_dPhiCh_PtAssoc_PtTrig->Project3D("zx_CorrGammaPhiC");
 	delete histoCorrGamma_dPhiCh_PtAssoc_PtTrig;
	
	TH3F*	histoCorrGamma_dEtaCh_PtAssoc_PtTrig = (TH3F*)directoryGammaCorr->Get("ESD_CorrGamma_dEtaCh_PtAssoc_PtTrig");
	TH2D* histo2DGamma_dEta_PtTrig = (TH2D*)histoCorrGamma_dEtaCh_PtAssoc_PtTrig->Project3D("zx_CorrGammaEtaA");
	histoCorrGamma_dEtaCh_PtAssoc_PtTrig->GetYaxis()->SetRange(histoCorrGamma_dEtaCh_PtAssoc_PtTrig->GetYaxis()->FindBin(1.),histoCorrGamma_dEtaCh_PtAssoc_PtTrig->GetYaxis()->FindBin(50.));
	TH2D* histo2DGamma_dEta_PtTrig_minPtAss05 = (TH2D*)histoCorrGamma_dEtaCh_PtAssoc_PtTrig->Project3D("zx_CorrGammaEtaB");
	histoCorrGamma_dEtaCh_PtAssoc_PtTrig->GetYaxis()->SetRange(histoCorrGamma_dEtaCh_PtAssoc_PtTrig->GetYaxis()->FindBin(2.),histoCorrGamma_dEtaCh_PtAssoc_PtTrig->GetYaxis()->FindBin(50.));
	TH2D* histo2DGamma_dEta_PtTrig_minPtAss1 = (TH2D*)histoCorrGamma_dEtaCh_PtAssoc_PtTrig->Project3D("zx_CorrGammaEtaC");
 	delete histoCorrGamma_dEtaCh_PtAssoc_PtTrig;

	TH3F*	histoCorrGamma_dPhiGa_PtAssoc_PtTrig = (TH3F*)directoryGammaCorr->Get("ESD_CorrGamma_dPhiGa_PtAssoc_PtTrig");
	TH2D* histo2DGamma_dPhiGa_PtTrig = (TH2D*)histoCorrGamma_dPhiGa_PtAssoc_PtTrig->Project3D("zx_CorrGammaPhiGaA");
	histoCorrGamma_dPhiGa_PtAssoc_PtTrig->GetYaxis()->SetRange(histoCorrGamma_dPhiGa_PtAssoc_PtTrig->GetYaxis()->FindBin(1.),histoCorrGamma_dPhiGa_PtAssoc_PtTrig->GetYaxis()->FindBin(50.));
	TH2D* histo2DGamma_dPhiGa_PtTrig_minPtAss05 = (TH2D*)histoCorrGamma_dPhiGa_PtAssoc_PtTrig->Project3D("zx_CorrGammaPhiGaB");
	histoCorrGamma_dPhiGa_PtAssoc_PtTrig->GetYaxis()->SetRange(histoCorrGamma_dPhiGa_PtAssoc_PtTrig->GetYaxis()->FindBin(2.),histoCorrGamma_dPhiGa_PtAssoc_PtTrig->GetYaxis()->FindBin(50.));
	TH2D* histo2DGamma_dPhiGa_PtTrig_minPtAss1 = (TH2D*)histoCorrGamma_dPhiGa_PtAssoc_PtTrig->Project3D("zx_CorrGammaPhiGaC");
 	delete histoCorrGamma_dPhiGa_PtAssoc_PtTrig;

	TH3F*	histoCorrGamma_dEtaGa_PtAssoc_PtTrig = (TH3F*)directoryGammaCorr->Get("ESD_CorrGamma_dEtaGa_PtAssoc_PtTrig");
	TH2D* histo2DGamma_dEtaGa_PtTrig = (TH2D*)histoCorrGamma_dEtaGa_PtAssoc_PtTrig->Project3D("zx_CorrGammaEtaGaA");
	histoCorrGamma_dEtaGa_PtAssoc_PtTrig->GetYaxis()->SetRange(histoCorrGamma_dEtaGa_PtAssoc_PtTrig->GetYaxis()->FindBin(1.),histoCorrGamma_dEtaGa_PtAssoc_PtTrig->GetYaxis()->FindBin(50.));
	TH2D* histo2DGamma_dEtaGa_PtTrig_minPtAss05 = (TH2D*)histoCorrGamma_dEtaGa_PtAssoc_PtTrig->Project3D("zx_CorrGammaEtaGaB");
	histoCorrGamma_dEtaGa_PtAssoc_PtTrig->GetYaxis()->SetRange(histoCorrGamma_dEtaGa_PtAssoc_PtTrig->GetYaxis()->FindBin(2.),histoCorrGamma_dEtaGa_PtAssoc_PtTrig->GetYaxis()->FindBin(50.));
	TH2D* histo2DGamma_dEtaGa_PtTrig_minPtAss1 = (TH2D*)histoCorrGamma_dEtaGa_PtAssoc_PtTrig->Project3D("zx_CorrGammaEtaGaC");
 	delete histoCorrGamma_dEtaGa_PtAssoc_PtTrig;

	TH3F*	histoCorrGammaIso_dPhiCh_PtAssoc_PtTrig = (TH3F*)directoryGammaCorr->Get("ESD_CorrGammaIso_dPhiCh_PtAssoc_PtTrig");
	TH2D* histo2DGammaIso_dPhi_PtTrig = (TH2D*)histoCorrGammaIso_dPhiCh_PtAssoc_PtTrig->Project3D("zx_GammaCorrIsoPhiA");
	histoCorrGammaIso_dPhiCh_PtAssoc_PtTrig->GetYaxis()->SetRange(histoCorrGammaIso_dPhiCh_PtAssoc_PtTrig->GetYaxis()->FindBin(1.),histoCorrGammaIso_dPhiCh_PtAssoc_PtTrig->GetYaxis()->FindBin(50.));
	TH2D* histo2DGammaIso_dPhi_PtTrig_minPtAss05 = (TH2D*)histoCorrGammaIso_dPhiCh_PtAssoc_PtTrig->Project3D("zx_GammaCorrIsoPhiB");
	histoCorrGammaIso_dPhiCh_PtAssoc_PtTrig->GetYaxis()->SetRange(histoCorrGammaIso_dPhiCh_PtAssoc_PtTrig->GetYaxis()->FindBin(2.),histoCorrGammaIso_dPhiCh_PtAssoc_PtTrig->GetYaxis()->FindBin(50.));
	TH2D* histo2DGammaIso_dPhi_PtTrig_minPtAss1 = (TH2D*)histoCorrGammaIso_dPhiCh_PtAssoc_PtTrig->Project3D("zx_GammaCorrIsoPhiC");
 	delete histoCorrGammaIso_dPhiCh_PtAssoc_PtTrig;


	TH3F*	histoCorrGammaIso_dEtaCh_PtAssoc_PtTrig = (TH3F*)directoryGammaCorr->Get("ESD_CorrGammaIso_dEtaCh_PtAssoc_PtTrig");
	TH2D* histo2DGammaIso_dEta_PtTrig = (TH2D*)histoCorrGammaIso_dEtaCh_PtAssoc_PtTrig->Project3D("zx_GammaCorrIsoEtaA");
	histoCorrGammaIso_dEtaCh_PtAssoc_PtTrig->GetYaxis()->SetRange(histoCorrGammaIso_dEtaCh_PtAssoc_PtTrig->GetYaxis()->FindBin(1.),histoCorrGammaIso_dEtaCh_PtAssoc_PtTrig->GetYaxis()->FindBin(50.));
	TH2D* histo2DGammaIso_dEta_PtTrig_minPtAss05 = (TH2D*)histoCorrGammaIso_dEtaCh_PtAssoc_PtTrig->Project3D("zx_GammaCorrIsoEtaB");
	histoCorrGammaIso_dEtaCh_PtAssoc_PtTrig->GetYaxis()->SetRange(histoCorrGammaIso_dEtaCh_PtAssoc_PtTrig->GetYaxis()->FindBin(2.),histoCorrGammaIso_dEtaCh_PtAssoc_PtTrig->GetYaxis()->FindBin(50.));
	TH2D* histo2DGammaIso_dEta_PtTrig_minPtAss1 = (TH2D*)histoCorrGammaIso_dEtaCh_PtAssoc_PtTrig->Project3D("zx_GammaCorrIsoEtaC");
 	delete histoCorrGammaIso_dEtaCh_PtAssoc_PtTrig;
	
	
	TString fileNameOutput = "CorrelationOutputNew1stStep.root";
	TFile* fileCorrWrite = new TFile(fileNameOutput.Data(),"UPDATE");
	fileCorrWrite->mkdir(Form("CorrGamma_%s",  cutSelection.Data()));
	fileCorrWrite->cd(Form("CorrGamma_%s",  cutSelection.Data()));
	
	histoCorrGamma_IsoMin_Pt->Write(Form("ESD_%s_CorrGamma_IsoMin_Pt",optData.Data()),TObject::kWriteDelete);		
	
	histoAssociatedGamma->Write(Form("ESD_%s_AssociatedGamma",optData.Data()),TObject::kWriteDelete);		
	histoAssociatedCh->Write(Form("ESD_%s_AssociatedCh",optData.Data()),TObject::kWriteDelete);		
	
	histo2DGamma_dEta_PtTrig->Write(Form("ESD_%s_CorrGamma_dEtaCh_PtTrig",optData.Data()),TObject::kWriteDelete);
	histo2DGamma_dEta_PtTrig_minPtAss05->Write(Form("ESD_%s_CorrGamma_dEtaCh_PtTrig_minPtAssA",optData.Data()),TObject::kWriteDelete);
	histo2DGamma_dEta_PtTrig_minPtAss1->Write(Form("ESD_%s_CorrGamma_dEtaCh_PtTrig_minPtAssB",optData.Data()),TObject::kWriteDelete);
	histo2DGammaIso_dEta_PtTrig->Write(Form("ESD_%s_CorrGammaIso_dEtaCh_PtTrig",optData.Data()),TObject::kWriteDelete);
	histo2DGammaIso_dEta_PtTrig_minPtAss05->Write(Form("ESD_%s_CorrGammaIso_dEtaCh_PtTrig_minPtAssA",optData.Data()),TObject::kWriteDelete);
	histo2DGammaIso_dEta_PtTrig_minPtAss1->Write(Form("ESD_%s_CorrGammaIso_dEtaCh_PtTrig_minPtAssB",optData.Data()),TObject::kWriteDelete);
	histo2DGamma_dEtaGa_PtTrig->Write(Form("ESD_%s_CorrGamma_dEtaGa_PtTrig",optData.Data()),TObject::kWriteDelete);
	histo2DGamma_dEtaGa_PtTrig_minPtAss05->Write(Form("ESD_%s_CorrGamma_dEtaGa_PtTrig_minPtAssA",optData.Data()),TObject::kWriteDelete);
	histo2DGamma_dEtaGa_PtTrig_minPtAss1->Write(Form("ESD_%s_CorrGamma_dEtaGa_PtTrig_minPtAssB",optData.Data()),TObject::kWriteDelete);
	
	histo2DGamma_dPhi_PtTrig->Write(Form("ESD_%s_CorrGamma_dPhiCh_PtTrig",optData.Data()),TObject::kWriteDelete);
	histo2DGamma_dPhi_PtTrig_minPtAss05->Write(Form("ESD_%s_CorrGamma_dPhiCh_PtTrig_minPtAssA",optData.Data()),TObject::kWriteDelete);
	histo2DGamma_dPhi_PtTrig_minPtAss1->Write(Form("ESD_%s_CorrGamma_dPhiCh_PtTrig_minPtAssB",optData.Data()),TObject::kWriteDelete);
	histo2DGammaIso_dPhi_PtTrig->Write(Form("ESD_%s_CorrGammaIso_dPhiCh_PtTrig",optData.Data()),TObject::kWriteDelete);
	histo2DGammaIso_dPhi_PtTrig_minPtAss05->Write(Form("ESD_%s_CorrGammaIso_dPhiCh_PtTrig_minPtAssA",optData.Data()),TObject::kWriteDelete);
	histo2DGammaIso_dPhi_PtTrig_minPtAss1->Write(Form("ESD_%s_CorrGammaIso_dPhiCh_PtTrig_minPtAssB",optData.Data()),TObject::kWriteDelete);
	histo2DGamma_dPhiGa_PtTrig->Write(Form("ESD_%s_CorrGamma_dPhiGa_PtTrig",optData.Data()),TObject::kWriteDelete);
	histo2DGamma_dPhiGa_PtTrig_minPtAss05->Write(Form("ESD_%s_CorrGamma_dPhiGa_PtTrig_minPtAssA",optData.Data()),TObject::kWriteDelete);
	histo2DGamma_dPhiGa_PtTrig_minPtAss1->Write(Form("ESD_%s_CorrGamma_dPhiGa_PtTrig_minPtAssB",optData.Data()),TObject::kWriteDelete);
	
	fileCorrWrite->Write();

	if (optData.CompareTo("MCRec")== 0){
		optData = "MCTrue" ;
		TH2F*	histoCorrTrueGamma_Phi_Eta = (TH2F*)directoryGammaCorr->Get("ESD_CorrTrueGamma_Phi_Eta");
		histoCorrTrueGamma_Phi_Eta->Scale(1./numberOfTriggerGammas);
		ConvGammaRebinWithBinCorrection2D(histoCorrTrueGamma_Phi_Eta, 4, 4, 3);
		PlotStandard2D( histoCorrTrueGamma_Phi_Eta , Form("%s/%s_GammaCorr_PhiCh_EtaCh.%s",outputDirectory.Data(),optData.Data(),suffix.Data()), "", "#phi (rad)", "#eta", "#frac{dN_{#gamma,trig}}{N_{#gamma, trig} d#eta d#phi}",  kTRUE, -TMath::Pi(), TMath::Pi(),kTRUE, -0.9, 0.9, kTRUE,  9e-2, histoCorrTrueGamma_Phi_Eta->GetMaximum(), 0, 0, 1, floatLocationRightUp2DXY,1000,880,rightMargin, leftMargin,bottomMargin,topMargin, "Perf","SURF7");
		delete histoCorrTrueGamma_Phi_Eta;
		
		TH2F*	histoCorrTrueGamma_dPhiCh_dEtaCh = (TH2F*)directoryGammaCorr->Get("ESD_CorrTrueGamma_dPhiCh_dEtaCh");
		histoCorrTrueGamma_dPhiCh_dEtaCh->Scale(1./numberOfTriggerGammas);
		ConvGammaRebinWithBinCorrection2D(histoCorrTrueGamma_dPhiCh_dEtaCh, 4, 3, 3);
		PlotStandard2D( histoCorrTrueGamma_dPhiCh_dEtaCh , Form("%s/%s_GammaCorr_dPhiCh_dEtaCh.%s",outputDirectory.Data(),optData.Data(),suffix.Data()), "", "#Delta#phi (rad)", "#Delta#eta", "#frac{dN_{ch,ass}}{N_{#gamma, trig} d#Delta#eta d#Delta#phi}", kFALSE, 0., 15., kTRUE, -1., 1.,kTRUE,  6.e-2, histoCorrTrueGamma_dPhiCh_dEtaCh->GetMaximum(), 0, 0, 1, floatLocationRightUp2DXY,1000,880,rightMargin, leftMargin,bottomMargin,topMargin, "Perf","SURF7");
		delete histoCorrTrueGamma_dPhiCh_dEtaCh;
		
		TH2F*	histoCorrTrueGamma_dPhiCh_dEtaCh_PtA1GeV_PtT2GeV = (TH2F*)directoryGammaCorr->Get("ESD_CorrTrueGamma_dPhiCh_dEtaCh_PtA1GeV_PtT2GeV");
		histoCorrTrueGamma_dPhiCh_dEtaCh_PtA1GeV_PtT2GeV->Scale(1./numberOfTriggerGammas);
		ConvGammaRebinWithBinCorrection2D(histoCorrTrueGamma_dPhiCh_dEtaCh_PtA1GeV_PtT2GeV, 4, 3, 3);
		PlotStandard2D( histoCorrTrueGamma_dPhiCh_dEtaCh_PtA1GeV_PtT2GeV , Form("%s/%s_GammaCorr_dPhiCh_dEtaCh_PtA1GeV_PtT2GeV.%s",outputDirectory.Data(),optData.Data(),suffix.Data()), "p_{t}^{A} > 1 GeV/c, p_{t}^{T} > 2 GeV/c", "#Delta#phi (rad)", "#Delta#eta","#frac{dN_{ch,ass}}{N_{#gamma, trig} d#Delta#eta d#Delta#phi}", kFALSE, 0., 15., kTRUE, -1., 1.,kTRUE,  1.e-3, histoCorrTrueGamma_dPhiCh_dEtaCh_PtA1GeV_PtT2GeV->GetMaximum(), 0,0,  1, floatLocationRightUp2DXY,1000,880,rightMargin, leftMargin,bottomMargin,topMargin, "Perf","SURF7","p_{t}^{A} > 1 GeV/c, p_{t}^{T} > 2 GeV/c");
		delete histoCorrTrueGamma_dPhiCh_dEtaCh_PtA1GeV_PtT2GeV;
		
		TH2F*	histoCorrTrueGamma_dPhiCh_dEtaCh_PtA1GeV_PtT5GeV = (TH2F*)directoryGammaCorr->Get("ESD_CorrTrueGamma_dPhiCh_dEtaCh_PtA1GeV_PtT5GeV");
		histoCorrTrueGamma_dPhiCh_dEtaCh_PtA1GeV_PtT5GeV->Scale(1./numberOfTriggerGammas);
		ConvGammaRebinWithBinCorrection2D(histoCorrTrueGamma_dPhiCh_dEtaCh_PtA1GeV_PtT5GeV, 4, 3, 3);
		PlotStandard2D( histoCorrTrueGamma_dPhiCh_dEtaCh_PtA1GeV_PtT5GeV , Form("%s/%s_GammaCorr_dPhiCh_dEtaCh_PtA1GeV_PtT5GeV.%s",outputDirectory.Data(),optData.Data(),suffix.Data()), "p_{t}^{A} > 1 GeV/c, p_{t}^{T} > 5 GeV/c", "#Delta#phi (rad)", "#Delta#eta", "#frac{dN_{ch,ass}}{N_{#gamma, trig} d#Delta#eta d#Delta#phi}", kFALSE, 0., 15., kTRUE, -1., 1.,kTRUE,  1.e-5, histoCorrTrueGamma_dPhiCh_dEtaCh_PtA1GeV_PtT5GeV->GetMaximum(), 0, 0, 1, floatLocationRightUp2DXY,1000,880,rightMargin, leftMargin,bottomMargin,topMargin, "Perf","SURF7","p_{t}^{A} > 1 GeV/c, p_{t}^{T} > 5 GeV/c");
		delete histoCorrTrueGamma_dPhiCh_dEtaCh_PtA1GeV_PtT5GeV;
		
		TH2F*	histoCorrTrueGamma_dPhiGa_dEtaGa =(TH2F*)directoryGammaCorr->Get("ESD_CorrTrueGamma_dPhiGa_dEtaGa");
		histoCorrTrueGamma_dPhiGa_dEtaGa->Scale(1./numberOfTriggerGammas);
		ConvGammaRebinWithBinCorrection2D(histoCorrTrueGamma_dPhiGa_dEtaGa, 4, 3, 3);
		PlotStandard2D( histoCorrTrueGamma_dPhiGa_dEtaGa , Form("%s/%s_GammaCorr_dPhiGa_dEtaGa.%s",outputDirectory.Data(),optData.Data(),suffix.Data()), "", "#Delta#phi (rad)", "#Delta#eta", "#frac{dN_{#gamma,ass}}{N_{#gamma, trig} d#Delta#eta d#Delta#phi}", kFALSE, 0., 15., kTRUE, -1., 1.,kTRUE,  2.e-3, histoCorrTrueGamma_dPhiGa_dEtaGa->GetMaximum(), 0,0,  1, floatLocationRightUp2DXY,1000,880,rightMargin, leftMargin,bottomMargin,topMargin, "Perf","SURF7");
		delete histoCorrTrueGamma_dPhiGa_dEtaGa;
		
		TH2F*	histoCorrTrueGamma_IsoMin_Pt = (TH2F*)directoryGammaCorr->Get("ESD_CorrTrueGamma_IsoMin_Pt");
		histoCorrTrueGamma_IsoMin_Pt->Scale(1./numberOfTriggerGammas);
		ConvGammaRebinWithBinCorrection2D(histoCorrTrueGamma_IsoMin_Pt, 1, 1, 3);
		PlotStandard2D( histoCorrTrueGamma_IsoMin_Pt , Form("%s/%s_GammaCorr_IsoMin_PtTrig.%s",outputDirectory.Data(),optData.Data(),suffix.Data()), "", "R_{min}", "p_{t}^{T} (GeV/c)", "#frac{dN_{#gamma,trig}}{N_{#gamma, trig} dR dp_{t}}", kFALSE, 0., 15., kFALSE, -1., 1.,kTRUE,  2.e-5, histoCorrTrueGamma_IsoMin_Pt->GetMaximum(), 0,0,  1, floatLocationRightUp2DXY,1000,880,rightMargin2, leftMargin2,bottomMargin,topMargin, "Perf","Colz");

		TH3F*	histoCorrTrueGamma_dPhiCh_PtAssoc_PtTrig = (TH3F*)directoryGammaCorr->Get("ESD_CorrTrueGamma_dPhiCh_PtAssoc_PtTrig");
		TH2D* histo2DTrueGamma_dPhi_PtTrig = (TH2D*)histoCorrTrueGamma_dPhiCh_PtAssoc_PtTrig->Project3D("zx_CorrTrueGammaPhiA");
		histoCorrTrueGamma_dPhiCh_PtAssoc_PtTrig->GetYaxis()->SetRange(histoCorrTrueGamma_dPhiCh_PtAssoc_PtTrig->GetYaxis()->FindBin(1.),histoCorrTrueGamma_dPhiCh_PtAssoc_PtTrig->GetYaxis()->FindBin(50.));
		TH2D* histo2DTrueGamma_dPhi_PtTrig_minPtAss05 = (TH2D*)histoCorrTrueGamma_dPhiCh_PtAssoc_PtTrig->Project3D("zx_CorrTrueGammaPhiB");
		histoCorrTrueGamma_dPhiCh_PtAssoc_PtTrig->GetYaxis()->SetRange(histoCorrTrueGamma_dPhiCh_PtAssoc_PtTrig->GetYaxis()->FindBin(2.),histoCorrTrueGamma_dPhiCh_PtAssoc_PtTrig->GetYaxis()->FindBin(50.));
		TH2D* histo2DTrueGamma_dPhi_PtTrig_minPtAss1 = (TH2D*)histoCorrTrueGamma_dPhiCh_PtAssoc_PtTrig->Project3D("zx_CorrTrueGammaPhiC");
		delete histoCorrTrueGamma_dPhiCh_PtAssoc_PtTrig;
		
		TH3F*	histoCorrTrueGamma_dEtaCh_PtAssoc_PtTrig = (TH3F*)directoryGammaCorr->Get("ESD_CorrTrueGamma_dEtaCh_PtAssoc_PtTrig");
		TH2D* histo2DTrueGamma_dEta_PtTrig = (TH2D*)histoCorrTrueGamma_dEtaCh_PtAssoc_PtTrig->Project3D("zx_CorrTrueGammaEtaA");
		histoCorrTrueGamma_dEtaCh_PtAssoc_PtTrig->GetYaxis()->SetRange(histoCorrTrueGamma_dEtaCh_PtAssoc_PtTrig->GetYaxis()->FindBin(1.),histoCorrTrueGamma_dEtaCh_PtAssoc_PtTrig->GetYaxis()->FindBin(50.));
		TH2D* histo2DTrueGamma_dEta_PtTrig_minPtAss05 = (TH2D*)histoCorrTrueGamma_dEtaCh_PtAssoc_PtTrig->Project3D("zx_CorrTrueGammaEtaB");
		histoCorrTrueGamma_dEtaCh_PtAssoc_PtTrig->GetYaxis()->SetRange(histoCorrTrueGamma_dEtaCh_PtAssoc_PtTrig->GetYaxis()->FindBin(2.),histoCorrTrueGamma_dEtaCh_PtAssoc_PtTrig->GetYaxis()->FindBin(50.));
		TH2D* histo2DTrueGamma_dEta_PtTrig_minPtAss1 = (TH2D*)histoCorrTrueGamma_dEtaCh_PtAssoc_PtTrig->Project3D("zx_CorrTrueGammaEtaC");
		delete histoCorrTrueGamma_dEtaCh_PtAssoc_PtTrig;

		TH3F*	histoCorrTrueGamma_dPhiGa_PtAssoc_PtTrig = (TH3F*)directoryGammaCorr->Get("ESD_CorrTrueGamma_dPhiGa_PtAssoc_PtTrig");
		TH2D* histo2DTrueGamma_dPhiGa_PtTrig = (TH2D*)histoCorrTrueGamma_dPhiGa_PtAssoc_PtTrig->Project3D("zx_CorrTrueGammaPhiGaA");
		histoCorrTrueGamma_dPhiGa_PtAssoc_PtTrig->GetYaxis()->SetRange(histoCorrTrueGamma_dPhiGa_PtAssoc_PtTrig->GetYaxis()->FindBin(1.),histoCorrTrueGamma_dPhiGa_PtAssoc_PtTrig->GetYaxis()->FindBin(50.));
		TH2D* histo2DTrueGamma_dPhiGa_PtTrig_minPtAss05 = (TH2D*)histoCorrTrueGamma_dPhiGa_PtAssoc_PtTrig->Project3D("zx_CorrTrueGammaPhiGaB");
		histoCorrTrueGamma_dPhiGa_PtAssoc_PtTrig->GetYaxis()->SetRange(histoCorrTrueGamma_dPhiGa_PtAssoc_PtTrig->GetYaxis()->FindBin(2.),histoCorrTrueGamma_dPhiGa_PtAssoc_PtTrig->GetYaxis()->FindBin(50.));
		TH2D* histo2DTrueGamma_dPhiGa_PtTrig_minPtAss1 = (TH2D*)histoCorrTrueGamma_dPhiGa_PtAssoc_PtTrig->Project3D("zx_CorrTrueGammaPhiGaC");
		delete histoCorrTrueGamma_dPhiGa_PtAssoc_PtTrig;

		TH3F*	histoCorrTrueGamma_dEtaGa_PtAssoc_PtTrig = (TH3F*)directoryGammaCorr->Get("ESD_CorrTrueGamma_dEtaGa_PtAssoc_PtTrig");
		TH2D* histo2DTrueGamma_dEtaGa_PtTrig = (TH2D*)histoCorrTrueGamma_dEtaGa_PtAssoc_PtTrig->Project3D("zx_CorrTrueGammaEtaGaA");
		histoCorrTrueGamma_dEtaGa_PtAssoc_PtTrig->GetYaxis()->SetRange(histoCorrTrueGamma_dEtaGa_PtAssoc_PtTrig->GetYaxis()->FindBin(1.),histoCorrTrueGamma_dEtaGa_PtAssoc_PtTrig->GetYaxis()->FindBin(50.));
		TH2D* histo2DTrueGamma_dEtaGa_PtTrig_minPtAss05 = (TH2D*)histoCorrTrueGamma_dEtaGa_PtAssoc_PtTrig->Project3D("zx_CorrTrueGammaEtaGaB");
		histoCorrTrueGamma_dEtaGa_PtAssoc_PtTrig->GetYaxis()->SetRange(histoCorrTrueGamma_dEtaGa_PtAssoc_PtTrig->GetYaxis()->FindBin(2.),histoCorrTrueGamma_dEtaGa_PtAssoc_PtTrig->GetYaxis()->FindBin(50.));
		TH2D* histo2DTrueGamma_dEtaGa_PtTrig_minPtAss1 = (TH2D*)histoCorrTrueGamma_dEtaGa_PtAssoc_PtTrig->Project3D("zx_CorrTrueGammaEtaGaC");
		delete histoCorrTrueGamma_dEtaGa_PtAssoc_PtTrig;

		TH3F*	histoCorrTrueGammaIso_dPhiCh_PtAssoc_PtTrig = (TH3F*)directoryGammaCorr->Get("ESD_CorrTrueGammaIso_dPhiCh_PtAssoc_PtTrig");
		TH2D* histo2DTrueGammaIso_dPhi_PtTrig = (TH2D*)histoCorrTrueGammaIso_dPhiCh_PtAssoc_PtTrig->Project3D("zx_TrueGammaCorrIsoPhiA");
		histoCorrTrueGammaIso_dPhiCh_PtAssoc_PtTrig->GetYaxis()->SetRange(histoCorrTrueGammaIso_dPhiCh_PtAssoc_PtTrig->GetYaxis()->FindBin(1.),histoCorrTrueGammaIso_dPhiCh_PtAssoc_PtTrig->GetYaxis()->FindBin(50.));
		TH2D* histo2DTrueGammaIso_dPhi_PtTrig_minPtAss05 = (TH2D*)histoCorrTrueGammaIso_dPhiCh_PtAssoc_PtTrig->Project3D("zx_TrueGammaCorrIsoPhiB");
		histoCorrTrueGammaIso_dPhiCh_PtAssoc_PtTrig->GetYaxis()->SetRange(histoCorrTrueGammaIso_dPhiCh_PtAssoc_PtTrig->GetYaxis()->FindBin(2.),histoCorrTrueGammaIso_dPhiCh_PtAssoc_PtTrig->GetYaxis()->FindBin(50.));
		TH2D* histo2DTrueGammaIso_dPhi_PtTrig_minPtAss1 = (TH2D*)histoCorrTrueGammaIso_dPhiCh_PtAssoc_PtTrig->Project3D("zx_TrueGammaCorrIsoPhiC");
		delete histoCorrTrueGammaIso_dPhiCh_PtAssoc_PtTrig;


		TH3F*	histoCorrTrueGammaIso_dEtaCh_PtAssoc_PtTrig = (TH3F*)directoryGammaCorr->Get("ESD_CorrTrueGammaIso_dEtaCh_PtAssoc_PtTrig");
		TH2D* histo2DTrueGammaIso_dEta_PtTrig = (TH2D*)histoCorrTrueGammaIso_dEtaCh_PtAssoc_PtTrig->Project3D("zx_TrueGammaCorrIsoEtaA");
		histoCorrTrueGammaIso_dEtaCh_PtAssoc_PtTrig->GetYaxis()->SetRange(histoCorrTrueGammaIso_dEtaCh_PtAssoc_PtTrig->GetYaxis()->FindBin(1.),histoCorrTrueGammaIso_dEtaCh_PtAssoc_PtTrig->GetYaxis()->FindBin(50.));
		TH2D* histo2DTrueGammaIso_dEta_PtTrig_minPtAss05 = (TH2D*)histoCorrTrueGammaIso_dEtaCh_PtAssoc_PtTrig->Project3D("zx_TrueGammaCorrIsoEtaB");
		histoCorrTrueGammaIso_dEtaCh_PtAssoc_PtTrig->GetYaxis()->SetRange(histoCorrTrueGammaIso_dEtaCh_PtAssoc_PtTrig->GetYaxis()->FindBin(2.),histoCorrTrueGammaIso_dEtaCh_PtAssoc_PtTrig->GetYaxis()->FindBin(50.));
		TH2D* histo2DTrueGammaIso_dEta_PtTrig_minPtAss1 = (TH2D*)histoCorrTrueGammaIso_dEtaCh_PtAssoc_PtTrig->Project3D("zx_TrueGammaCorrIsoEtaC");
		delete histoCorrTrueGammaIso_dEtaCh_PtAssoc_PtTrig;
		
		fileCorrWrite->cd(Form("CorrGamma_%s",  cutSelection.Data()));
		
		histoCorrTrueGamma_IsoMin_Pt->Write(Form("ESD_%s_CorrGamma_IsoMin_Pt",optData.Data()),TObject::kWriteDelete);		
		
		histo2DTrueGamma_dEta_PtTrig->Write(Form("ESD_%s_CorrGamma_dEtaCh_PtTrig",optData.Data()),TObject::kWriteDelete);
		histo2DTrueGamma_dEta_PtTrig_minPtAss05->Write(Form("ESD_%s_CorrGamma_dEtaCh_PtTrig_minPtAssA",optData.Data()),TObject::kWriteDelete);
		histo2DTrueGamma_dEta_PtTrig_minPtAss1->Write(Form("ESD_%s_CorrGamma_dEtaCh_PtTrig_minPtAssB",optData.Data()),TObject::kWriteDelete);
		histo2DTrueGammaIso_dEta_PtTrig->Write(Form("ESD_%s_CorrGammaIso_dEtaCh_PtTrig",optData.Data()),TObject::kWriteDelete);
		histo2DTrueGammaIso_dEta_PtTrig_minPtAss05->Write(Form("ESD_%s_CorrGammaIso_dEtaCh_PtTrig_minPtAssA",optData.Data()),TObject::kWriteDelete);
		histo2DTrueGammaIso_dEta_PtTrig_minPtAss1->Write(Form("ESD_%s_CorrGammaIso_dEtaCh_PtTrig_minPtAssB",optData.Data()),TObject::kWriteDelete);
		histo2DTrueGamma_dEtaGa_PtTrig->Write(Form("ESD_%s_CorrGamma_dEtaGa_PtTrig",optData.Data()),TObject::kWriteDelete);
		histo2DTrueGamma_dEtaGa_PtTrig_minPtAss05->Write(Form("ESD_%s_CorrGamma_dEtaGa_PtTrig_minPtAssA",optData.Data()),TObject::kWriteDelete);
		histo2DTrueGamma_dEtaGa_PtTrig_minPtAss1->Write(Form("ESD_%s_CorrGamma_dEtaGa_PtTrig_minPtAssB",optData.Data()),TObject::kWriteDelete);
		
		histo2DTrueGamma_dPhi_PtTrig->Write(Form("ESD_%s_CorrGamma_dPhiCh_PtTrig",optData.Data()),TObject::kWriteDelete);
		histo2DTrueGamma_dPhi_PtTrig_minPtAss05->Write(Form("ESD_%s_CorrGamma_dPhiCh_PtTrig_minPtAssA",optData.Data()),TObject::kWriteDelete);
		histo2DTrueGamma_dPhi_PtTrig_minPtAss1->Write(Form("ESD_%s_CorrGamma_dPhiCh_PtTrig_minPtAssB",optData.Data()),TObject::kWriteDelete);
		histo2DTrueGammaIso_dPhi_PtTrig->Write(Form("ESD_%s_CorrGammaIso_dPhiCh_PtTrig",optData.Data()),TObject::kWriteDelete);
		histo2DTrueGammaIso_dPhi_PtTrig_minPtAss05->Write(Form("ESD_%s_CorrGammaIso_dPhiCh_PtTrig_minPtAssA",optData.Data()),TObject::kWriteDelete);
		histo2DTrueGammaIso_dPhi_PtTrig_minPtAss1->Write(Form("ESD_%s_CorrGammaIso_dPhiCh_PtTrig_minPtAssB",optData.Data()),TObject::kWriteDelete);
		histo2DTrueGamma_dPhiGa_PtTrig->Write(Form("ESD_%s_CorrGamma_dPhiGa_PtTrig",optData.Data()),TObject::kWriteDelete);
		histo2DTrueGamma_dPhiGa_PtTrig_minPtAss05->Write(Form("ESD_%s_CorrGamma_dPhiGa_PtTrig_minPtAssA",optData.Data()),TObject::kWriteDelete);
		histo2DTrueGamma_dPhiGa_PtTrig_minPtAss1->Write(Form("ESD_%s_CorrGamma_dPhiGa_PtTrig_minPtAssB",optData.Data()),TObject::kWriteDelete);
		
		fileCorrWrite->Write();
		fileCorrWrite->Close();

	}
	
}
Example #21
0
void 
HBB_LEP_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., const char* inputfile="root/$HISTFILE", const char* directory="bb_$CATEGORY")
{
  // define common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  // determine category tag
  const char* category_extra = "";
  if(std::string(directory) == std::string("bb_had0"  )){ category_extra = "all-had_{0}";  }
  if(std::string(directory) == std::string("bb_had1"  )){ category_extra = "all-had_{1}";  }
  if(std::string(directory) == std::string("bb_had2"  )){ category_extra = "all-had_{2}";  }
  if(std::string(directory) == std::string("bb_had3"  )){ category_extra = "all-had_{3}";  }
  if(std::string(directory) == std::string("bb_had4"  )){ category_extra = "all-had_{4}";  }
  if(std::string(directory) == std::string("bb_had5"  )){ category_extra = "all-had_{5}";  }
  if(std::string(directory) == std::string("bb_lep"   )){ category_extra = "semi-lep";  }

  const char* dataset;
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "Preliminary, #sqrt{s} = 7 TeV, L = 4.8 fb^{-1}";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "Preliminary, #sqrt{s} = 8 TeV, L = 19.4 fb^{-1}";}
  
  TFile* input = new TFile(inputfile);
  TH1F* bkgBBB  = refill((TH1F*)input->Get(TString::Format("%s/bkgBBB"   , directory)), "bkgBBB"); InitHist(bkgBBB, "", "", kMagenta-10, 1001);;
#ifdef MSSM
  float bbHScale = 1.; // scenario for MSSM, mhmax, mA=160, tanb=20, A+H for the time being
  if(std::string(inputfile).find("7TeV")!=std::string::npos){ bbHScale = (23314.3*0.879 + 21999.3*0.877)/1000.; }
  if(std::string(inputfile).find("8TeV")!=std::string::npos){ bbHScale = (31087.9*0.879 + 29317.8*0.877)/1000.; }
 //  float bbHScale = 1.; // scenario for MSSM, mhmax, mA=160, tanb=10, A+H for the time being
//   if(std::string(inputfile).find("7TeV")!=std::string::npos){ bbHScale = (6211.6*0.89 + 5145.0*0.85)/1000.; }
//   if(std::string(inputfile).find("8TeV")!=std::string::npos){ bbHScale = (8282.7*0.89 + 6867.8*0.85)/1000.; }
  TH1F* bbH  = refill((TH1F*)input->Get(TString::Format("%s/bbH160"  , directory)), "bbH"  ); InitSignal(bbH); bbH->Scale(bbHScale);
#endif
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
  InitHist(data, "#bf{m_{b#bar{b}} [GeV]}", "#bf{dN/dm_{b#bar{b}} [1/GeV]}"); InitData(data);

  TH1F* ref=(TH1F*)bkgBBB->Clone("ref");

  double unscaled[7];
  unscaled[0] = bkgBBB ->Integral();
#ifdef MSSM
  unscaled[1] = bbH ->Integral();
  unscaled[2] = 0;
#endif

  if(scaled){
    rescale(bkgBBB,   1);
#ifdef MSSM 
    rescale(bbH,   2);
#endif
  }

  TH1F* scales[7];
  scales[0] = new TH1F("scales-bkgBBB", "", 3, 0, 3);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (bkgBBB  ->Integral()/unscaled[0]-1.) : 0.);
#ifdef MSSM
  scales[1] = new TH1F("scales-bbH"  , "", 3, 0, 3);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? (bbH  ->Integral()/unscaled[1]-1.) : 0.);
  scales[2] = new TH1F("scales-NONE" , "", 3, 0, 3);
  scales[2]->SetBinContent(3, 0.);
#endif

  if(!log){
#ifdef MSSM
    bbH  ->Add(bkgBBB);
#endif
  }

  /*
    mass plot before and after fit
  */
  TCanvas* canv = MakeCanvas("canv", "histograms", 600, 600);
  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(0, data->FindBin(350)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(1000)); };
#endif

  data->SetNdivisions(505);
  data->SetMinimum(min);
  data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(bkgBBB, log)));
  data->Draw("e");

  TH1F* errorBand = (TH1F*)bkgBBB ->Clone();
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(1);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);

  if(log){
    bkgBBB  ->Draw("histsame");
    $DRAW_ERROR
#ifndef DROP_SIGNAL
    bbH     ->Draw("histsame");
#endif
  }
  else{  
#ifndef DROP_SIGNAL
    bbH     ->Draw("histsame");
#endif  
    bkgBBB  ->Draw("histsame");
    $DRAW_ERROR
  }
  data->Draw("esame");
  canv->RedrawAxis();

  //CMSPrelim(dataset, "b#bar{b}", 0.17, 0.835);
  CMSPrelim(dataset, "", 0.17, 0.835);  
  TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "NDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText("b#bar{b}");
  chan->Draw();

  TPaveText* cat      = new TPaveText(0.20, 0.68+0.061, 0.32, 0.68+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();
 
#ifdef MSSM
  TPaveText* massA      = new TPaveText(0.75, 0.48+0.061, 0.85, 0.48+0.161, "NDC");
  massA->SetBorderSize(   0 );
  massA->SetFillStyle(    0 );
  massA->SetTextAlign(   12 );
  massA->SetTextSize ( 0.03 );
  massA->SetTextColor(    1 );
  massA->SetTextFont (   62 );
  massA->AddText("m_{A}=160GeV");
  massA->Draw();

  TPaveText* tanb      = new TPaveText(0.75, 0.44+0.061, 0.85, 0.44+0.161, "NDC");
  tanb->SetBorderSize(   0 );
  tanb->SetFillStyle(    0 );
  tanb->SetTextAlign(   12 );
  tanb->SetTextSize ( 0.03 );
  tanb->SetTextColor(    1 );
  tanb->SetTextFont (   62 );
  tanb->AddText("tan#beta=20");
  tanb->Draw();

  TPaveText* scen      = new TPaveText(0.75, 0.40+0.061, 0.85, 0.40+0.161, "NDC");
  scen->SetBorderSize(   0 );
  scen->SetFillStyle(    0 );
  scen->SetTextAlign(   12 );
  scen->SetTextSize ( 0.03 );
  scen->SetTextColor(    1 );
  scen->SetTextFont (   62 );
  scen->AddText("mhmax");
  scen->Draw();
#endif


#ifdef MSSM  
  TLegend* leg = new TLegend(0.55, 0.65, 0.94, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(bbH  , "#phi#rightarrowb#bar{b}" , "L" );
#endif
  leg->AddEntry(data,   "observed"                       , "LP");
  leg->AddEntry(bkgBBB, "bkgBBB"                      , "F" );
  $ERROR_LEGEND
  leg->Draw();

//#ifdef MSSM
//  TPaveText* mssm  = new TPaveText(0.69, 0.85, 0.90, 0.90, "NDC");
//  mssm->SetBorderSize(   0 );
//  mssm->SetFillStyle(    0 );
//  mssm->SetTextAlign(   12 );
//  mssm->SetTextSize ( 0.03 );
//  mssm->SetTextColor(    1 );
//  mssm->SetTextFont (   62 );
//  mssm->AddText("(m_{A}=250, tan#beta=5)");
//  mssm->Draw();
//#else
//  TPaveText* mssm  = new TPaveText(0.83, 0.85, 0.95, 0.90, "NDC");
//  mssm->SetBorderSize(   0 );
//  mssm->SetFillStyle(    0 );
//  mssm->SetTextAlign(   12 );
//  mssm->SetTextSize ( 0.03 );
//  mssm->SetTextColor(    1 );
//  mssm->SetTextFont (   62 );
//  mssm->AddText("m_{H}=125");
//  mssm->Draw();
//#endif

  /*
    Ratio Data over MC
  */
  TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
  canv0->SetGridx();
  canv0->SetGridy();
  canv0->cd();

  TH1F* zero = (TH1F*)ref ->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)data->Clone("rat"); 
  rat1->Divide(bkgBBB);
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
    zero->SetBinContent(ibin+1, 0.);
  }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+1.5);
  rat1->SetMinimum(-1.5);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
  rat1->GetXaxis()->SetTitle("#bf{m_{b#bar{b}} [GeV]}");
  rat1->Draw();
  zero->SetLineColor(kBlack);
  zero->Draw("same");
  canv0->RedrawAxis();

  /*
    Ratio After fit over Prefit
  */
  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  TH1F* rat2 = (TH1F*) bkgBBB->Clone("rat2");
  rat2->Divide(ref);
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    if(rat2->GetBinContent(ibin+1)>0){
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
    }
  }
  rat2->SetLineColor(kRed+ 3);
  rat2->SetFillColor(kRed-10);
  rat2->SetMaximum(+0.3);
  rat2->SetMinimum(-0.3);
  rat2->GetYaxis()->SetTitle("#bf{Fit/Prefit-1}");
  rat2->GetYaxis()->CenterTitle();
  rat2->GetXaxis()->SetTitle("#bf{m_{b#bar{b}} [GeV]}");
  rat2->GetXaxis()->SetRange(0, 28);
  rat2->Draw();
  zero->SetLineColor(kBlack);
  zero->Draw("same");
  canv1->RedrawAxis();

  /*
    Relative shift per sample
  */
  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
  canv2->SetGridx();
  canv2->SetGridy();
  canv2->cd();

  InitHist  (scales[0], "", "", kMagenta-10, 1001);
  scales[0]->Draw();
  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{bkgBBB}");
#ifdef MSSM
  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{bbH}"  );
  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{NONE}" );
#endif
  scales[0]->SetMaximum(+1.0);
  scales[0]->SetMinimum(-1.0);
  scales[0]->GetYaxis()->CenterTitle();
  scales[0]->GetYaxis()->SetTitle("#bf{Fit/Prefit-1}");
  zero->Draw("same");
  canv2->RedrawAxis();

  /*
    prepare output
  */
  bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.png"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.pdf"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.eps"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  TFile* output = new TFile(TString::Format("%s_%sscaled_%s_%s.root", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""), "update");
  output->cd();
  data ->Write("data_obs");
  bkgBBB  ->Write("bkgBBB"  );
#ifdef MSSM
  bbH  ->Write("bbH"     );
#endif
  if(errorBand){
    errorBand->Write("errorBand");
  }
  output->Close();
}
Example #22
0
void DrawVariable(TString DIR,TString VAR,float LUMI,bool LOG,int REBIN,float XMIN,float XMAX,TString XTITLE,bool isINT,int XNDIV,bool PRINT)
{
  gROOT->ForceStyle();
  const int N = 14;

  TString SAMPLE[N] = {
    "JetHT",
    "TT_TuneCUETP8M1_13TeV-powheg-pythia8",
    "WJetsToQQ_HT180_13TeV-madgraphMLM-pythia8",
    "DYJetsToQQ_HT180_13TeV-madgraphMLM-pythia8",
    "ST_t-channel_top_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1",
    "ST_t-channel_antitop_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1",
    "ST_tW_top_5f_inclusiveDecays_13TeV-powheg-pythia8_TuneCUETP8M1",
    "ST_tW_antitop_5f_inclusiveDecays_13TeV-powheg-pythia8_TuneCUETP8M1",
    "QCD_HT300to500_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT500to700_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT700to1000_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT1000to1500_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT1500to2000_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT2000toInf_TuneCUETP8M1_13TeV-madgraphMLM-pythia8"
  };
  float XSEC[N] = {1.0,0.5*832,3539,1460.,136.02,80.95,35.6,35.6,3.67e+5,2.94e+4,6.524e+03,1.064e+03,121.5,2.542e+01};

  TFile *inf[N];
  TH1F  *h[N];

  TCanvas *can = new TCanvas("DataVsMC_"+DIR+"_"+VAR,"DataVsMC_"+DIR+"_"+VAR,900,600);
  can->SetRightMargin(0.15);

  for(int i=0;i<N;i++) {
    inf[i] = TFile::Open("Histo_"+SAMPLE[i]+".root");
    h[i] = (TH1F*)inf[i]->Get(DIR+"/hWt_"+VAR);
    if (!h[i]) {
      cout<<"Histogram "<<"hWt_"+VAR<<" does not exist !!!"<<endl;
      break;
    } 
    h[i]->SetDirectory(0);
    h[i]->Sumw2();
    h[i]->Rebin(REBIN);
    h[i]->SetLineWidth(1);
    h[i]->SetLineColor(kBlack);
    if (i>0) {
      float norm = ((TH1F*)inf[i]->Get("eventCounter/GenEventWeight"))->GetSumOfWeights();   
      //cout<<SAMPLE[i]<<" "<<norm<<endl;
      h[i]->Scale(LUMI*XSEC[i]/norm);
    }
    inf[i]->Close();
  }

  TH1F *hQCD = (TH1F*)h[8]->Clone("hQCD");
  for(int i=9;i<N;i++) {
    hQCD->Add(h[i]);
  }
 
  TH1F *hST = (TH1F*)h[4]->Clone("hST");
  hST->Add(h[5]);
  hST->Add(h[6]);
  hST->Add(h[7]);
  h[0]->SetLineWidth(2);//data
  hQCD->SetFillColor(kBlue-10);//QCD
  h[1]->SetFillColor(kOrange);//ttbar
  h[2]->SetFillColor(kGreen-10);//WJets
  h[3]->SetFillColor(kGreen-8);//ZJets
  hST->SetFillColor(kOrange-1);//ST

  float kfactor = 1.0;
  if (hQCD->Integral() > 0) { 
    kfactor = (h[0]->Integral()-h[1]->Integral()-h[2]->Integral()-h[3]->Integral()-hST->Integral())/hQCD->Integral();
  }  
  hQCD->Scale(kfactor);

  TH1F *hBkg = (TH1F*)hQCD->Clone("hBkg");
  hBkg->Add(h[1]);
  hBkg->Add(h[2]);
  hBkg->Add(h[3]);
  hBkg->Add(h[4]);
  hBkg->Add(hST);
  //hBkg->SetFillColor(kGray);

  cout<<"======== "<<VAR<<"====================="<<endl;
  cout<<"Data events:  "<<h[0]->Integral()<<endl;
  cout<<"QCD events:   "<<hQCD->Integral()<<endl;
  cout<<"WJets events: "<<h[2]->Integral()<<endl;
  cout<<"ZJets events: "<<h[3]->Integral()<<endl;
  cout<<"ST events:    "<<hST->Integral()<<endl;
  cout<<"TTbar events: "<<h[1]->Integral()<<endl;
  cout<<"kfactor:      "<<kfactor<<endl;

  THStack *hs = new THStack("hs","hs");
  if (LOG) {   
    hs->Add(h[2]);
    hs->Add(h[3]);
    hs->Add(hST); 
    hs->Add(hQCD);
    hs->Add(h[1]);
  }
  else {
    hs->Add(h[3]);
    hs->Add(hST);
    hs->Add(h[2]);
    hs->Add(hQCD);
    hs->Add(h[1]);
  }
  TH1F *hRatio = (TH1F*)h[0]->Clone("Ratio");
  hRatio->SetLineWidth(2);
  hRatio->Divide(hBkg);

  TLegend *leg = new TLegend(0.86,0.7,0.99,0.9);
  leg->SetFillColor(0);
  leg->SetTextFont(42);
  leg->SetTextSize(0.03);
  leg->AddEntry(hQCD,"QCD","F");
  leg->AddEntry(h[1],"TTbar","F"); 
  leg->AddEntry(hST,"ST","F"); 
  leg->AddEntry(h[2],"WJets","F");
  leg->AddEntry(h[3],"ZJets","F"); 
  
  can->SetBottomMargin(0.25);
  TH1F *hAux = (TH1F*)h[0]->Clone("aux");
  hAux->Reset();
  hAux->GetXaxis()->SetNdivisions(XNDIV);
  if (isINT) {
    hAux->GetXaxis()->CenterLabels();
  } 
  hAux->GetYaxis()->SetRangeUser(0.5,1.1*TMath::Max(hBkg->GetBinContent(hBkg->GetMaximumBin()),h[0]->GetBinContent(h[0]->GetMaximumBin())));  
  if (LOG) {
    gPad->SetLogy(); 
    hAux->GetYaxis()->SetRangeUser(0.5,2*TMath::Max(hBkg->GetBinContent(hBkg->GetMaximumBin()),h[0]->GetBinContent(h[0]->GetMaximumBin())));
  }
  hAux->GetXaxis()->SetRangeUser(XMIN,XMAX);
  hAux->GetYaxis()->SetTitle(TString::Format("Number of events / %1.2f fb^{-1}",LUMI/1000));
  hAux->GetXaxis()->SetTitle("");
  hAux->GetXaxis()->SetLabelSize(0.0);
  hAux->Draw();
  hs->Draw("hist same");
  //hBkg->Draw("sames hist"); 
  h[0]->Draw("sames E");
  
  leg->Draw();
  gPad->RedrawAxis();

  TPad *pad = new TPad("pad","pad",0.,0.,1.,1.);
  pad->SetTopMargin(0.77);
  pad->SetRightMargin(0.15);
  pad->SetFillColor(0);
  pad->SetFillStyle(0);
  pad->Draw();
  pad->cd(0);
  pad->SetGridy();
  hRatio->GetXaxis()->SetTitleOffset(0.95);
  hRatio->GetYaxis()->SetTitleOffset(1.5);
  hRatio->GetYaxis()->SetTickLength(0.06);
  hRatio->GetYaxis()->SetTitleSize(0.03);
  hRatio->GetYaxis()->SetLabelSize(0.03);
  hRatio->GetYaxis()->SetTitle("Data/MC");
  hRatio->GetXaxis()->SetTitle(XTITLE);
  hRatio->GetXaxis()->SetRangeUser(XMIN,XMAX);
  hRatio->GetYaxis()->SetRangeUser(0.5,1.5);
  hRatio->GetYaxis()->SetNdivisions(505);
  hRatio->GetXaxis()->SetNdivisions(XNDIV);
  if (isINT) {
    hRatio->GetXaxis()->CenterLabels();
  }
  hRatio->Draw();
  if (PRINT) {
    can->Print("plots/"+TString(can->GetName())+".pdf"); 
    can->Print("plots/"+TString(can->GetName())+".png");
  }
}
void DrawFits(TemplateFIT * FIT,FileSaver finalHistos,FileSaver Plots){

	std::string pathdata  = (FIT->GetName() + "/Fit Results/Data");
	std::string pathtemplP= (FIT->GetName() + "/Fit Results/ScaledTemplatesP");
	std::string pathtemplD= (FIT->GetName() + "/Fit Results/ScaledTemplatesD");	
	std::string pathtemplHe=(FIT->GetName() + "/Fit Results/ScaledTemplatesHe");	

	std::string pathfit   = (FIT->GetName() + "/Fit Results/FractionFits");
	std::string pathtrans = (FIT->GetName() + "/Fit Results/TrasnferFunctions");
	std::string pathres   = (FIT->GetName() + "/Fit Results/");
	
	TFile * infile = finalHistos.GetFile();	


	for(int i=1; i<FIT->GetBinning().size();i++){
		
		std::string pathbinP    = pathtemplP + "/Bin"+to_string(i);
		std::string pathbinD    = pathtemplD + "/Bin"+to_string(i);
		std::string pathbinHe   = pathtemplHe+ "/Bin"+to_string(i);
		std::string pathbindata = pathdata   + "/Bin"+to_string(i);
		std::string pathbinfit  = pathfit    + "/Bin"+to_string(i);

		std::vector<TH1F*> TemplatesP=GetListOfTemplates(infile, pathbinP);
		std::vector<TH1F*> TemplatesD=GetListOfTemplates(infile, pathbinD);		
		std::vector<TH1F*> TemplatesHe=GetListOfTemplates(infile, pathbinHe);		
		std::vector<TH1F*> Datas     =GetListOfTemplates(infile, pathbindata);
		std::vector<TH1F*> Fits      =GetListOfTemplates(infile, pathbinfit);
		std::vector<TH1F*> Transfer  =GetListOfTemplates(infile, pathtrans);

		cout<<pathbinHe<<" "<<TemplatesHe.size()<<" "<<TemplatesHe[0]<<endl;
	

		TCanvas * c1 = new TCanvas("Modified Templates");
		c1->SetCanvasSize(2000,1500);

		for(int j=TemplatesP.size()-1;j>=0;j--){
			if(j==0) PlotDistribution(gPad, TemplatesP[j],"Reconstructed Mass [GeV/c^2]","Counts",1,"same",1,TemplatesP[j]->GetBinContent(TemplatesP[j]->GetMaximumBin())*1.13,10);
			else     PlotDistribution(gPad, TemplatesP[j],"Reconstructed Mass [GeV/c^2]","Counts",colorbase + j,"same",1,TemplatesP[j]->GetBinContent(TemplatesP[j]->GetMaximumBin())*1.13,7,"",false,false,true);		
		}
	
		Plots.Add(c1);
		Plots.writeObjsInFolder((FIT->GetName()+"/Fits/Bin"+to_string(i)).c_str());	


		TCanvas * c2 = new TCanvas("Modified T. Fits");
                c2->SetCanvasSize(2000,1500);

		PlotDistribution(gPad, TemplatesP[0], "Reconstructed Mass [GeV/c^2]","Counts",2,"same",1,Datas[0]->GetBinContent(Datas[0]->GetMaximumBin())*1.13,10,"Original Protons MC Template");
		PlotDistribution(gPad, TemplatesD[0], "Reconstructed Mass [GeV/c^2]","Counts",4,"same",1,1e5,10,"Original Deuterons MC Template");
		PlotDistribution(gPad, TemplatesHe[0],"Reconstructed Mass [GeV/c^2]","Counts",3,"same",1,1e5,10,"Original He Fragm. MC Template");

		for(int j=TemplatesP.size()-1;j>=1;j--){
                        PlotDistribution(gPad, TemplatesP[j],"Reconstructed Mass [GeV/c^2]","Counts",2,"same",1,1e5,1,"",false,false,true);
			PlotDistribution(gPad, TemplatesD[j],"Reconstructed Mass [GeV/c^2]","Counts",4,"same",1,1e5,1,"",false,false,true);
                	//PlotDistribution(gPad, TemplatesHe[j],"Reconstructed Mass [GeV/c^2]","Counts",3,"same",1,1e5,1,"",false,false,true);
		}
		PlotDistribution(gPad, Datas[0],"Reconstructed Mass [GeV/c^2]","Counts",1,"ePsame",1,1e5,3,"ISS data",false,true);
	


		Plots.Add(c2);
                Plots.writeObjsInFolder((FIT->GetName()+"/Fits/Bin"+to_string(i)).c_str());
		
		
		TCanvas * c3 = new TCanvas("Template Fits");
                c3->SetCanvasSize(2000,1500);

		PlotDistribution(gPad, TemplatesP[0] ,"Reconstructed Mass [GeV/c^2]","Counts",2,"same",1,Datas[0]->GetBinContent(Datas[0]->GetMaximumBin())*1.13,2,"Original Protons MC Template");
		PlotDistribution(gPad, TemplatesD[0] ,"Reconstructed Mass [GeV/c^2]","Counts",4,"same",1,1e5,2,"Original Deuterons MC Template");
		PlotDistribution(gPad, TemplatesHe[0],"Reconstructed Mass [GeV/c^2]","Counts",3,"same",1,1e5,2,"Original He Fragm. MC Template");
		PlotDistribution(gPad, TemplatesP[1] ,"Reconstructed Mass [GeV/c^2]","Counts",2,"same",1,Datas[0]->GetBinContent(Datas[0]->GetMaximumBin())*1.13,10,"Best #chi^{2} Protons MC Template");
		PlotDistribution(gPad, TemplatesD[1] ,"Reconstructed Mass [GeV/c^2]","Counts",4,"same",1,1e5,10,"Best #chi^{2} Deuterons MC Template");
		PlotDistribution(gPad, TemplatesHe[1],"Reconstructed Mass [GeV/c^2]","Counts",3,"same",1,1e5,10,"Best #chi^{2} he Fragm. MC Template");
		

		PlotDistribution(gPad, Datas[0],"Reconstructed Mass [GeV/c^2]","Counts",1,"ePsame",1,1e5,3,"ISS data",false,true);
		if(Fits.size()>0) PlotDistribution(gPad, Fits[0],"Reconstructed Mass [gev/c^2]","counts",6,"same",1,1e5,4,"Fraction Fit");
	

		Plots.Add(c3);
                Plots.writeObjsInFolder((FIT->GetName()+"/Fits/Bin"+to_string(i)).c_str());

		TCanvas * c5 = new TCanvas("Transfer Functions");
                c5->SetCanvasSize(2000,1500);

		for(int j=0;j<Transfer.size();j++){
			Transfer[j]->Smooth(3);
			PlotDistribution(gPad, Transfer[j],"Reconstructed Mass [GeV/c^2]","Prim. / (Prim. + Sec.)",j,"hist,same",0,1,7,("Bin. "+to_string(j)).c_str(),false,false);
		}

		Plots.Add(c5);
                Plots.writeObjsInFolder((FIT->GetName()+"/Fits").c_str());

	

		TCanvas * c4 = new TCanvas("ChiSquare");
                c4->SetCanvasSize(2000,1500);
		gPad->SetLogz();	
		TH2F * Chi = (TH2F*) infile->Get((FIT->GetName()+"/Fit Results/Spreads/ChiSquare/ChiSquare Bin "+to_string(i)).c_str());
                Chi->GetZaxis()->SetRangeUser(0.2,100);
                PlotTH2F(gPad, Chi, "Additive #sigma","Mean shift", "colz");	


		Plots.Add(c4);
                Plots.writeObjsInFolder((FIT->GetName()+"/Fits/Bin"+to_string(i)).c_str());

		TCanvas * c6 = new TCanvas("OverCutoff Events");
                c6->SetCanvasSize(2000,1500);
			
		TH1F * OverCutoffP = (TH1F *) TemplatesP[1]->Clone();
		OverCutoffP->Multiply(Transfer[i]);
		TH1F * OverCutoffD = (TH1F *) TemplatesD[1]->Clone();
		OverCutoffD->Multiply(Transfer[i]);
		TH1F * NoCutoffP = (TH1F *) TemplatesP[1]->Clone();

		NoCutoffP->Scale(
			OverCutoffP->GetBinContent(OverCutoffP->GetMaximumBin())/
			NoCutoffP->GetBinContent(NoCutoffP->GetMaximumBin()) );

		PlotDistribution(gPad, NoCutoffP,"Reconstructed Mass [GeV/c^2]","Primary Counts",2,"same",1,Datas[1]->GetBinContent(Datas[1]->GetMaximumBin())*1.13,3,"Best #chi^{2} Protons MC Template");
		PlotDistribution(gPad, OverCutoffP,"Reconstructed Mass [GeV/c^2]","Counts",2,"same",1,Datas[0]->GetBinContent(Datas[0]->GetMaximumBin())*1.13,10,"Best #chi^{2} Protons MC (Cutoff filtered)");
		PlotDistribution(gPad, OverCutoffD,"Reconstructed Mass [GeV/c^2]","Counts",4,"same",1,Datas[0]->GetBinContent(Datas[0]->GetMaximumBin())*1.13,10,"Best #chi^{2} Deutons MC (Cutoff filtered)");
		PlotDistribution(gPad, Datas[1],"Reconstructed Mass [GeV/c^2]","Primary Counts",1,"ePsame",1,Datas[1]->GetBinContent(Datas[1]->GetMaximumBin())*1.13,3,"ISS data",false,true);
	

		Plots.Add(c6);
                Plots.writeObjsInFolder((FIT->GetName()+"/Fits/Bin"+to_string(i)).c_str());


	

	}

	return;

}
void 
HTT_TT_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., string inputfile="root/$HISTFILE", const char* directory="tauTau_$CATEGORY")
{
  // defining the common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  // determine category tag
  const char* category_extra = "";
  if(std::string(directory) == std::string("tauTau_1jet"      )){ category_extra = "1 jet";             }
  if(std::string(directory) == std::string("tauTau_vbf"       )){ category_extra = "2 jet (VBF)";       }
  if(std::string(directory) == std::string("tauTau_nobtag"    )){ category_extra = "No B-Tag";          }
  if(std::string(directory) == std::string("tauTau_btag"      )){ category_extra = "B-Tag";             }

  const char* dataset;
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "CMS Preliminary,  H#rightarrow#tau#tau,  4.9 fb^{-1} at 7 TeV";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS Preliminary,  H#rightarrow#tau#tau,  19.8 fb^{-1} at 8 TeV";}
#ifdef MSSM
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS Preliminary, #sqrt{s} = 8 TeV, L = 19.8 fb^{-1}, H #rightarrow #tau #tau";}
#endif

  // open example histogram file
  TFile* input = new TFile(inputfile.c_str());
#ifdef MSSM
  TFile* input2 = new TFile((inputfile+"_$MA_$TANB").c_str());
#endif
  TH1F* Fakes  = refill((TH1F*)input->Get(TString::Format("%s/QCD"   , directory)), "QCD"); InitHist(Fakes, "", "", kMagenta-10, 1001);
  TH1F* EWK1   = refill((TH1F*)input->Get(TString::Format("%s/W"     , directory)), "W"  ); InitHist(EWK1 , "", "", kRed    + 2, 1001);
  TH1F* EWK2   = refill((TH1F*)input->Get(TString::Format("%s/ZJ"    , directory)), "ZJ" ); InitHist(EWK2 , "", "", kRed    + 2, 1001);
//TH1F* EWK3   = refill((TH1F*)input->Get(TString::Format("%s/ZL"    , directory)), "ZL" ); InitHist(EWK3 , "", "", kRed    + 2, 1001);
  TH1F* EWK    = refill((TH1F*)input->Get(TString::Format("%s/VV"    , directory)), "VV" ); InitHist(EWK  , "", "", kRed    + 2, 1001);
  TH1F* ttbar  = refill((TH1F*)input->Get(TString::Format("%s/TT"    , directory)), "TT" ); InitHist(ttbar, "", "", kBlue   - 8, 1001);
  TH1F* Ztt    = refill((TH1F*)input->Get(TString::Format("%s/ZTT"   , directory)), "ZTT"); InitHist(Ztt  , "", "", kOrange - 4, 1001);
#ifdef MSSM
  // float ggHScale = 1., bbHScale = 1.;
//   ggHScale = ($MSSM_SIGNAL_ggH_xseff_A + $MSSM_SIGNAL_ggH_xseff_hH);
//   bbHScale = ($MSSM_SIGNAL_bbH_xseff_A + $MSSM_SIGNAL_bbH_xseff_hH);
  TH1F* ggH    = refill((TH1F*)input2->Get(TString::Format("%s/ggH$MA", directory)), "ggH"); InitSignal(ggH); ggH->Scale($TANB); //ggH ->Scale(ggHScale);
  TH1F* bbH    = refill((TH1F*)input2->Get(TString::Format("%s/bbH$MA", directory)), "bbH"); InitSignal(bbH); bbH->Scale($TANB); //bbH ->Scale(bbHScale);
#else
  TH1F* ggH    = refill((TH1F*)input->Get(TString::Format("%s/ggH125", directory)), "ggH"); InitSignal(ggH); ggH ->Scale(SIGNAL_SCALE);
  TH1F* qqH    = refill((TH1F*)input->Get(TString::Format("%s/qqH125", directory)), "qqH"); InitSignal(qqH); qqH ->Scale(SIGNAL_SCALE);
  TH1F* VH     = refill((TH1F*)input->Get(TString::Format("%s/VH125" , directory)), "VH" ); InitSignal(VH ); VH  ->Scale(SIGNAL_SCALE);
#endif
#ifdef ASIMOV
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs_asimov", directory)), "data", true);
#else
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
#endif
  InitHist(data, "#bf{m_{#tau#tau} [GeV]}", "#bf{dN/dm_{#tau#tau} [1/GeV]}"); InitData(data);

  TH1F* ref=(TH1F*)Fakes->Clone("ref");
  ref->Add(EWK1 );
  ref->Add(EWK2 );
//ref->Add(EWK3 );
  ref->Add(ttbar);
  ref->Add(Ztt  );

  double unscaled[7];
  unscaled[0] = Fakes->Integral();
  unscaled[1] = EWK  ->Integral();
  unscaled[1]+= EWK1 ->Integral();
  unscaled[1]+= EWK2 ->Integral();
//unscaled[1]+= EWK3 ->Integral();
  unscaled[2] = ttbar->Integral();
  unscaled[3] = Ztt  ->Integral();
#ifdef MSSM
  unscaled[4] = ggH  ->Integral();
  unscaled[5] = bbH  ->Integral();
  unscaled[6] = 0;
#else
  unscaled[4] = ggH  ->Integral();
  unscaled[5] = qqH  ->Integral();
  unscaled[6] = VH   ->Integral();
#endif

  if(scaled){
    rescale(Fakes, 7); 
    rescale(EWK1 , 3); 
    rescale(EWK2 , 4); 
  //rescale(EWK3 , 5);
    rescale(EWK  , 6); 
    rescale(ttbar, 2); 
    rescale(Ztt  , 1);
#ifdef MSSM
    rescale(ggH  , 8); 
    rescale(bbH  , 9);  
#else
    rescale(ggH  , 8); 
    rescale(qqH  , 9);  
    rescale(VH   ,10);  
#endif
  }

  TH1F* scales[7];
  scales[0] = new TH1F("scales-Fakes", "", 7, 0, 7);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (Fakes->Integral()/unscaled[0]-1.) : 0.);
  scales[1] = new TH1F("scales-EWK"  , "", 7, 0, 7);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? ((EWK  ->Integral()
					       +EWK1 ->Integral()
					       +EWK2 ->Integral()
					      //+EWK3 ->Integral()
						)/unscaled[1]-1.) : 0.);
  scales[2] = new TH1F("scales-ttbar", "", 7, 0, 7);
  scales[2]->SetBinContent(3, unscaled[2]>0 ? (ttbar->Integral()/unscaled[2]-1.) : 0.);
  scales[3] = new TH1F("scales-Ztt"  , "", 7, 0, 7);
  scales[3]->SetBinContent(4, unscaled[3]>0 ? (Ztt  ->Integral()/unscaled[3]-1.) : 0.);
#ifdef MSSM
  scales[4] = new TH1F("scales-ggH"  , "", 7, 0, 7);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggH  ->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-bbH"  , "", 7, 0, 7);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (bbH  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-NONE" , "", 7, 0, 7);
  scales[6]->SetBinContent(7, 0.);
#else
  scales[4] = new TH1F("scales-ggH"  , "", 7, 0, 7);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggH  ->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-qqH"  , "", 7, 0, 7);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (qqH  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-VH"   , "", 7, 0, 7);
  scales[6]->SetBinContent(7, unscaled[6]>0 ? (VH   ->Integral()/unscaled[6]-1.) : 0.);
#endif

  EWK1 ->Add(Fakes);
  EWK2 ->Add(EWK1 );
//EWK3 ->Add(EWK2 );
//EWK  ->Add(EWK3 );
  EWK  ->Add(EWK2 );
  ttbar->Add(EWK  );
  Ztt  ->Add(ttbar);
  if(log){
#ifdef MSSM
    ggH  ->Add(bbH);
#else
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
  }
  else{
#ifdef MSSM    
    bbH  ->Add(Ztt);
    ggH  ->Add(bbH);
#else
    VH   ->Add(Ztt);
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
  }

  /*
    Mass plot before and after fit
  */
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);

  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(0, data->FindBin(500)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(1000)); };
#else
  data->GetXaxis()->SetRange(0, data->FindBin(350));
#endif
  data->SetNdivisions(505);
  data->SetMinimum(min);
  data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Ztt, log)));
  data->Draw("e");

  TH1F* errorBand = (TH1F*)Ztt ->Clone();
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(1);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
    if(errorBand->GetBinContent(idx)>0){
      std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
      break;
    }
  }
  if(log){
    Ztt  ->Draw("histsame");
    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    Fakes->Draw("histsame");
    $DRAW_ERROR
    ggH  ->Draw("histsame");
  }
  else{
    ggH  ->Draw("histsame");
    Ztt  ->Draw("histsame");
    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    Fakes->Draw("histsame");
    $DRAW_ERROR
  }
  data->Draw("esame");
  canv->RedrawAxis();

  //CMSPrelim(dataset, "#tau_{h}#tau_{h}", 0.17, 0.835);
  CMSPrelim(dataset, "", 0.18, 0.835);  
  TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "NDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText("#tau_{h}#tau_{h}");
  chan->Draw();

  TPaveText* cat      = new TPaveText(0.20, 0.68+0.061, 0.32, 0.68+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();

#ifdef MSSM
  TPaveText* massA      = new TPaveText(0.75, 0.48+0.061, 0.85, 0.48+0.161, "NDC");
  massA->SetBorderSize(   0 );
  massA->SetFillStyle(    0 );
  massA->SetTextAlign(   12 );
  massA->SetTextSize ( 0.03 );
  massA->SetTextColor(    1 );
  massA->SetTextFont (   62 );
  massA->AddText("m_{A}=$MA GeV");
  massA->Draw();

  TPaveText* tanb      = new TPaveText(0.75, 0.44+0.061, 0.85, 0.44+0.161, "NDC");
  tanb->SetBorderSize(   0 );
  tanb->SetFillStyle(    0 );
  tanb->SetTextAlign(   12 );
  tanb->SetTextSize ( 0.03 );
  tanb->SetTextColor(    1 );
  tanb->SetTextFont (   62 );
  tanb->AddText("tan#beta=$TANB");
  tanb->Draw();

  TPaveText* scen      = new TPaveText(0.75, 0.40+0.061, 0.85, 0.40+0.161, "NDC");
  scen->SetBorderSize(   0 );
  scen->SetFillStyle(    0 );
  scen->SetTextAlign(   12 );
  scen->SetTextSize ( 0.03 );
  scen->SetTextColor(    1 );
  scen->SetTextFont (   62 );
  scen->AddText("m^{h}_{max}");
  scen->Draw();
#endif
  
#ifdef MSSM
  TLegend* leg = new TLegend(0.45, 0.65, 0.95, 0.88);
  SetLegendStyle(leg);
  leg->AddEntry(ggH  , "#phi#rightarrow#tau#tau" , "L" );
#else
  TLegend* leg = new TLegend(0.50, 0.65, 0.95, 0.88);
  SetLegendStyle(leg);
  if(SIGNAL_SCALE!=1){
    leg->AddEntry(ggH  , TString::Format("%.0f#timesH(125 GeV)#rightarrow#tau#tau", SIGNAL_SCALE) , "L" );
  }
  else{
    leg->AddEntry(ggH  , "H(125 GeV)#rightarrow#tau#tau" , "L" );
  }
#endif
#ifdef ASIMOV
  leg->AddEntry(data , "sum(bkg) + SM125 GeV signal"    , "LP");
#else
  leg->AddEntry(data , "observed"                       , "LP");
#endif
  leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
  leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
  leg->AddEntry(EWK  , "electroweak"                    , "F" );
  leg->AddEntry(Fakes, "QCD"                            , "F" );
  $ERROR_LEGEND
  leg->Draw();

//#ifdef MSSM
//  TPaveText* mssm  = new TPaveText(0.69, 0.85, 0.90, 0.90, "NDC");
//  mssm->SetBorderSize(   0 );
//  mssm->SetFillStyle(    0 );
//  mssm->SetTextAlign(   12 );
//  mssm->SetTextSize ( 0.03 );
//  mssm->SetTextColor(    1 );
//  mssm->SetTextFont (   62 );
//  mssm->AddText("(m_{A}=120, tan#beta=10)");
//  mssm->Draw();
//#else
//  TPaveText* mssm  = new TPaveText(0.83, 0.85, 0.95, 0.90, "NDC");
//  mssm->SetBorderSize(   0 );
//  mssm->SetFillStyle(    0 );
//  mssm->SetTextAlign(   12 );
//  mssm->SetTextSize ( 0.03 );
//  mssm->SetTextColor(    1 );
//  mssm->SetTextFont (   62 );
//  mssm->AddText("m_{H}=125");
//  mssm->Draw();
//#endif

  /*
    Ratio Data over MC
  */
  TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
  canv0->SetGridx();
  canv0->SetGridy();
  canv0->cd();

  TH1F* zero = (TH1F*)ref->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)data->Clone("rat"); 
  rat1->Divide(Ztt);
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
    zero->SetBinContent(ibin+1, 0.);
  }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+0.5);
  rat1->SetMinimum(-0.5);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
  rat1->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  rat1->Draw();
  zero->SetLineColor(kBlack);
  zero->Draw("same");
  canv0->RedrawAxis();

  /*
    Ratio After fit over Prefit
  */
  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  TH1F* rat2 = (TH1F*) Ztt->Clone("rat2");
  rat2->Divide(ref);
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    if(rat2->GetBinContent(ibin+1)>0){
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
    }
  }
  rat2->SetLineColor(kRed+ 3);
  rat2->SetFillColor(kRed-10);
  rat2->SetMaximum(+0.3);
  rat2->SetMinimum(-0.3);
  rat2->GetYaxis()->SetTitle("#bf{Fit/Prefit-1}");
  rat2->GetYaxis()->CenterTitle();
  rat2->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  rat2->Draw();
  zero->SetLineColor(kBlack);
  zero->Draw("same");
  canv1->RedrawAxis();

  /*
    Relative shift per sample
  */
  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
  canv2->SetGridx();
  canv2->SetGridy();
  canv2->cd();

  InitHist  (scales[0], "", "", kMagenta-10, 1001);
  InitHist  (scales[1], "", "", kRed    + 2, 1001);
  InitHist  (scales[2], "", "", kBlue   - 8, 1001);
  InitHist  (scales[3], "", "", kOrange - 4, 1001);
  InitSignal(scales[4]);
  InitSignal(scales[5]);
  InitSignal(scales[6]);

  scales[0]->Draw();
  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{Fakes}");
  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{EWK}"  );
  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{ttbar}");
  scales[0]->GetXaxis()->SetBinLabel(4, "#bf{Ztt}"  );
#ifdef MSSM
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{bbH}"  );
  scales[0]->GetXaxis()->SetBinLabel(7, "NONE"      );
#else
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{qqH}"  );
  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{VH}"   );
#endif
  scales[0]->SetMaximum(+1.0);
  scales[0]->SetMinimum(-1.0);
  scales[0]->GetYaxis()->CenterTitle();
  scales[0]->GetYaxis()->SetTitle("#bf{Fit/Prefit-1}");
  scales[1]->Draw("same");
  scales[2]->Draw("same");
  scales[3]->Draw("same");
  scales[4]->Draw("same");
  scales[5]->Draw("same");
  scales[6]->Draw("same");
  zero->Draw("same");
  canv2->RedrawAxis();

  /*
    prepare output
  */
  bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv ->Print(TString::Format("%s_%sfit_%s_%s.png"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv ->Print(TString::Format("%s_%sfit_%s_%s.pdf"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv ->Print(TString::Format("%s_%sfit_%s_%s.eps"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  if(!log || FULLPLOTS)
  {
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }
  if((!log && scaled) || FULLPLOTS)
  {
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }

  TFile* output = new TFile(TString::Format("%s_%sfit_%s_%s.root", directory, scaled ? "pre" : "post", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"), "update");
  output->cd(); 
  data ->Write("data_obs");
  Fakes->Write("Fakes"   );
  EWK  ->Write("EWK"     );
  ttbar->Write("ttbar"   );
  Ztt  ->Write("Ztt"     );
#ifdef MSSM
  ggH  ->Write("ggH"     );
  bbH  ->Write("bbH"     );
#else
  ggH  ->Write("ggH"     );
  qqH  ->Write("qqH"     );
  VH   ->Write("VH"      );
#endif
  output->Close();
}
Example #25
0
void BINcomb(){

  TFile *fqcd = new TFile("QCD.root");
  TFile *fsig = new TFile("SIG.root");
  TFile *fttb = new TFile("TTB.root");

  double xcqcd = 25.42*1000; 
  double xcttb = 831.76*1000; 
  double xcsig = 0.0624391*1000;
  
  double lumi = 5.0 ; 
  

  double nt_qcd = xcqcd*lumi; 
  double nt_sig = xcsig*lumi; 
  double nt_ttb = xcttb*lumi; 

  fqcd->cd();
  demo->cd();
  double scf_qcd = nt_qcd/(1.0*Ev0->GetEntries()); 

  TH1F *ak8ptq = ak8pt->Clone();
  TH1F *t31q = ak8t31->Clone();
  TH1F *ak8_phosubfq = ak8_phosubFrac->Clone();  
  TH1F *pm0q = ak8_prunnedM0->Clone(); 
  TH1F *pm1q = ak8_prunnedM1->Clone(); 
  TH1F *pm2q = ak8_prunnedM2->Clone(); 
  TH1F *pm3q = ak8_prunnedM3->Clone(); 
  TH1F *pm4q = ak8_prunnedM4->Clone(); 
  TH1F *pm5q = ak8_prunnedM5->Clone(); 
  TH1F *njt3q = NJT3->Clone();
  TH1F *njl3q = NJL3->Clone();
  TH1F *njt4q = NJT4->Clone();
  TH1F *njl4q = NJL4->Clone();
  TH1F *htaq = HTa->Clone();
  TH1F *ht3q = HT3->Clone();
  TH1F *ht4q = HT4->Clone();
  TH1F *ht4l1q = HT4L1->Clone();
  TH1F *ht4l2q = HT4L2->Clone();
  TH1F *ht4t1q = HT4T1->Clone();
  TH1F *ht4t2q = HT4T2->Clone();
  TH1F *ht3l1q = HT3L1->Clone();
  TH1F *ht3l2q = HT3L2->Clone();
  TH1F *ht3t1q = HT3T1->Clone();
  TH1F *ht3t2q = HT3T2->Clone();
  
  TH1F *Thotmassq = T2jet_4evmasspruned->Clone();
  TH1F *Lhotmassq = L3jet_4evmasspruned->Clone();
 

  fttb->cd();
  demo->cd();
  double scf_ttb = nt_ttb/(1.0*Ev0->GetEntries()); 



  TH1F *Thotmasst = T2jet_4evmasspruned->Clone();
  TH1F *Lhotmasst = L3jet_4evmasspruned->Clone();
 
 
  TH1F *ak8ptt = ak8pt->Clone();
  TH1F *t31t = ak8t31->Clone();
  TH1F *ak8_phosubft = ak8_phosubFrac->Clone();  
  TH1F *pm0t = ak8_prunnedM0->Clone(); 
  TH1F *pm1t = ak8_prunnedM1->Clone(); 
  TH1F *pm2t = ak8_prunnedM2->Clone(); 
  TH1F *pm3t = ak8_prunnedM3->Clone(); 
  TH1F *pm4t = ak8_prunnedM4->Clone(); 
  TH1F *pm5t = ak8_prunnedM5->Clone(); 
  TH1F *njt3t = NJT3->Clone();
  TH1F *njl3t = NJL3->Clone();
  TH1F *njt4t = NJT4->Clone();
  TH1F *njl4t = NJL4->Clone();
  TH1F *htat = HTa->Clone();
  TH1F *ht3t = HT3->Clone();
  TH1F *ht4t = HT4->Clone();
  TH1F *ht4l1t = HT4L1->Clone();
  TH1F *ht4l2t = HT4L2->Clone();
  TH1F *ht4t1t = HT4T1->Clone();
  TH1F *ht4t2t = HT4T2->Clone();
  TH1F *ht3l1t = HT3L1->Clone();
  TH1F *ht3l2t = HT3L2->Clone();
  TH1F *ht3t1t = HT3T1->Clone();
  TH1F *ht3t2t = HT3T2->Clone();


  fsig->cd();
  demo->cd();
  double scf_sig = nt_sig/(1.0*Ev0->GetEntries()); 

  TH1F *Thotmasss = T2jet_4evmasspruned->Clone();
  TH1F *Lhotmasss = L3jet_4evmasspruned->Clone();
 

  TH1F *ak8pts = ak8pt->Clone();
  TH1F *t31s = ak8t31->Clone();
  TH1F *ak8_phosubfs = ak8_phosubFrac->Clone();  
  TH1F *pm0s = ak8_prunnedM0->Clone(); 
  TH1F *pm1s = ak8_prunnedM1->Clone(); 
  TH1F *pm2s = ak8_prunnedM2->Clone(); 
  TH1F *pm3s = ak8_prunnedM3->Clone(); 
  TH1F *pm4s = ak8_prunnedM4->Clone(); 
  TH1F *pm5s = ak8_prunnedM5->Clone(); 
  TH1F *njt3s = NJT3->Clone();
  TH1F *njl3s = NJL3->Clone();
  TH1F *njt4s = NJT4->Clone();
  TH1F *njl4s = NJL4->Clone();
  TH1F *htas = HTa->Clone();
  TH1F *ht3s = HT3->Clone();
  TH1F *ht4s = HT4->Clone();
  TH1F *ht4l1s = HT4L1->Clone();
  TH1F *ht4l2s = HT4L2->Clone();
  TH1F *ht4t1s = HT4T1->Clone();
  TH1F *ht4t2s = HT4T2->Clone();
  TH1F *ht3l1s = HT3L1->Clone();
  TH1F *ht3l2s = HT3L2->Clone();
  TH1F *ht3t1s = HT3T1->Clone();
  TH1F *ht3t2s = HT3T2->Clone();


  //Scaling all the historgrams: 
  ak8pts->Scale(scf_sig);
  t31s->Scale(scf_sig);
  ak8_phosubfs->Scale(scf_sig);
  pm0s->Scale(scf_sig);
  pm1s->Scale(scf_sig);
  pm2s->Scale(scf_sig);
  pm3s->Scale(scf_sig);
  pm4s->Scale(scf_sig);
  pm5s->Scale(scf_sig);
  njt3s->Scale(scf_sig);
  njl3s->Scale(scf_sig);
  njt4s->Scale(scf_sig);
  njl4s->Scale(scf_sig);
  htas->Scale(scf_sig);
  ht3s->Scale(scf_sig);
  ht4s->Scale(scf_sig);
  ht4l1s->Scale(scf_sig);
  ht4l2s->Scale(scf_sig);
  ht4t1s->Scale(scf_sig);
  ht4t2s->Scale(scf_sig);
  ht3l1s->Scale(scf_sig);
  ht3l2s->Scale(scf_sig);
  ht3t1s->Scale(scf_sig);
  ht3t2s->Scale(scf_sig);
  Thotmasss->Scale(scf_sig);
  Lhotmasss->Scale(scf_sig);




 Thotmasss->SetFillColor(kRed);
 Lhotmasss->SetFillColor(kRed);
  ak8pts->SetFillColor(kRed);
  t31s->SetFillColor(kRed);

  
  ak8_phosubfs->SetFillColor(kRed);
  pm0s->SetFillColor(kRed);
  pm1s->SetFillColor(kRed);
  pm2s->SetFillColor(kRed);
  pm3s->SetFillColor(kRed);
  pm4s->SetFillColor(kRed);
  pm5s->SetFillColor(kRed);
  njt3s->SetFillColor(kRed);
  njl3s->SetFillColor(kRed);
  njt4s->SetFillColor(kRed);
  njl4s->SetFillColor(kRed);
  htas->SetFillColor(kRed);
  ht3s->SetFillColor(kRed);
  ht4s->SetFillColor(kRed);
  ht4l1s->SetFillColor(kRed);
  ht4l2s->SetFillColor(kRed);
  ht4t1s->SetFillColor(kRed);
  ht4t2s->SetFillColor(kRed);
  ht3l1s->SetFillColor(kRed);
  ht3l2s->SetFillColor(kRed);
  ht3t1s->SetFillColor(kRed);
  ht3t2s->SetFillColor(kRed);


  Thotmasss->SetLineColor(kRed);
  Lhotmasss->SetLineColor(kRed);
  
  ak8pts->SetLineColor(kRed);
  t31s->SetLineColor(kRed);
  ak8_phosubfs->SetLineColor(kRed);
  pm0s->SetLineColor(kRed);
  pm1s->SetLineColor(kRed);
  pm2s->SetLineColor(kRed);
  pm3s->SetLineColor(kRed);
  pm4s->SetLineColor(kRed);
  pm5s->SetLineColor(kRed);
  njt3s->SetLineColor(kRed);
  njl3s->SetLineColor(kRed);
  njt4s->SetLineColor(kRed);
  njl4s->SetLineColor(kRed);
  htas->SetLineColor(kRed);
  ht3s->SetLineColor(kRed);
  ht4s->SetLineColor(kRed);
  ht4l1s->SetLineColor(kRed);
  ht4l2s->SetLineColor(kRed);
  ht4t1s->SetLineColor(kRed);
  ht4t2s->SetLineColor(kRed);
  ht3l1s->SetLineColor(kRed);
  ht3l2s->SetLineColor(kRed);
  ht3t1s->SetLineColor(kRed);
  ht3t2s->SetLineColor(kRed);




  ak8ptq->Scale(scf_qcd);
  t31q->Scale(scf_qcd);
  ak8_phosubfq->Scale(scf_qcd);
  pm0q->Scale(scf_qcd);
  pm1q->Scale(scf_qcd);
  pm2q->Scale(scf_qcd);
  pm3q->Scale(scf_qcd);
  pm4q->Scale(scf_qcd);
  pm5q->Scale(scf_qcd);
  njt3q->Scale(scf_qcd);
  njl3q->Scale(scf_qcd);
  njt4q->Scale(scf_qcd);
  njl4q->Scale(scf_qcd);
  htaq->Scale(scf_qcd);
  ht3q->Scale(scf_qcd);
  ht4q->Scale(scf_qcd);
  ht4l1q->Scale(scf_qcd);
  ht4l2q->Scale(scf_qcd);
  ht4t1q->Scale(scf_qcd);
  ht4t2q->Scale(scf_qcd);
  ht3l1q->Scale(scf_qcd);
  ht3l2q->Scale(scf_qcd);
  ht3t1q->Scale(scf_qcd);
  ht3t2q->Scale(scf_qcd);

  Thotmassq->Scale(scf_qcd);
  Lhotmassq->Scale(scf_qcd);

  
  
  Thotmassq->SetFillColor(kGray+3);
  Lhotmassq->SetFillColor(kGray+3);

  ak8ptq->SetFillColor(kGray+3);
  t31q->SetFillColor(kGray+3);
  ak8_phosubfq->SetFillColor(kGray+3);
  pm0q->SetFillColor(kGray+3);
  pm1q->SetFillColor(kGray+3);
  pm2q->SetFillColor(kGray+3);
  pm3q->SetFillColor(kGray+3);
  pm4q->SetFillColor(kGray+3);
  pm5q->SetFillColor(kGray+3);
  njt3q->SetFillColor(kGray+3);
  njl3q->SetFillColor(kGray+3);
  njt4q->SetFillColor(kGray+3);
  njl4q->SetFillColor(kGray+3);
  htaq->SetFillColor(kGray+3);
  ht3q->SetFillColor(kGray+3);
  ht4q->SetFillColor(kGray+3);
  ht4l1q->SetFillColor(kGray+3);
  ht4l2q->SetFillColor(kGray+3);
  ht4t1q->SetFillColor(kGray+3);
  ht4t2q->SetFillColor(kGray+3);
  ht3l1q->SetFillColor(kGray+3);
  ht3l2q->SetFillColor(kGray+3);
  ht3t1q->SetFillColor(kGray+3);
  ht3t2q->SetFillColor(kGray+3);

  
  Thotmassq->SetLineColor(kGray+3);
  Lhotmassq->SetLineColor(kGray+3);

  ak8ptq->SetLineColor(kGray+3);
  t31q->SetLineColor(kGray+3);
  ak8_phosubfq->SetLineColor(kGray+3);
  pm0q->SetLineColor(kGray+3);
  pm1q->SetLineColor(kGray+3);
  pm2q->SetLineColor(kGray+3);
  pm3q->SetLineColor(kGray+3);
  pm4q->SetLineColor(kGray+3);
  pm5q->SetLineColor(kGray+3);
  njt3q->SetLineColor(kGray+3);
  njl3q->SetLineColor(kGray+3);
  njt4q->SetLineColor(kGray+3);
  njl4q->SetLineColor(kGray+3);
  htaq->SetLineColor(kGray+3);
  ht3q->SetLineColor(kGray+3);
  ht4q->SetLineColor(kGray+3);
  ht4l1q->SetLineColor(kGray+3);
  ht4l2q->SetLineColor(kGray+3);
  ht4t1q->SetLineColor(kGray+3);
  ht4t2q->SetLineColor(kGray+3);
  ht3l1q->SetLineColor(kGray+3);
  ht3l2q->SetLineColor(kGray+3);
  ht3t1q->SetLineColor(kGray+3);
  ht3t2q->SetLineColor(kGray+3);



 
  ak8ptt->Scale(scf_ttb);
  t31t->Scale(scf_ttb);
  ak8_phosubft->Scale(scf_ttb);
  pm0t->Scale(scf_ttb);
  pm1t->Scale(scf_ttb);
  pm2t->Scale(scf_ttb);
  pm3t->Scale(scf_ttb);
  pm4t->Scale(scf_ttb);
  pm5t->Scale(scf_ttb);
  njt3t->Scale(scf_ttb);
  njl3t->Scale(scf_ttb);
  njt4t->Scale(scf_ttb);
  njl4t->Scale(scf_ttb);
  htat->Scale(scf_ttb);
  ht3t->Scale(scf_ttb);
  ht4t->Scale(scf_ttb);
  ht4l1t->Scale(scf_ttb);
  ht4l2t->Scale(scf_ttb);
  ht4t1t->Scale(scf_ttb);
  ht4t2t->Scale(scf_ttb);
  ht3l1t->Scale(scf_ttb);
  ht3l2t->Scale(scf_ttb);
  ht3t1t->Scale(scf_ttb);
  ht3t2t->Scale(scf_ttb);


  Thotmasst->Scale(scf_ttb);
  Lhotmasst->Scale(scf_ttb);

  
  Thotmasst->SetFillColor(kMagenta);
  Lhotmasst->SetFillColor(kMagenta);
  
  ak8ptt->SetFillColor(kMagenta);
  t31t->SetFillColor(kMagenta);
  ak8_phosubft->SetFillColor(kMagenta);
  pm0t->SetFillColor(kMagenta);
  pm1t->SetFillColor(kMagenta);
  pm2t->SetFillColor(kMagenta);
  pm3t->SetFillColor(kMagenta);
  pm4t->SetFillColor(kMagenta);
  pm5t->SetFillColor(kMagenta);
  njt3t->SetFillColor(kMagenta);
  njl3t->SetFillColor(kMagenta);
  njt4t->SetFillColor(kMagenta);
  njl4t->SetFillColor(kMagenta);
  htat->SetFillColor(kMagenta);
  ht3t->SetFillColor(kMagenta);
  ht4t->SetFillColor(kMagenta);
  ht4l1t->SetFillColor(kMagenta);
  ht4l2t->SetFillColor(kMagenta);
  ht4t1t->SetFillColor(kMagenta);
  ht4t2t->SetFillColor(kMagenta);
  ht3l1t->SetFillColor(kMagenta);
  ht3l2t->SetFillColor(kMagenta);
  ht3t1t->SetFillColor(kMagenta);
  ht3t2t->SetFillColor(kMagenta);


  Thotmasst->SetLineColor(kMagenta);
  Lhotmasst->SetLineColor(kMagenta);
  
  ak8ptt->SetLineColor(kMagenta);
  t31t->SetLineColor(kMagenta);
  ak8_phosubft->SetLineColor(kMagenta);
  pm0t->SetLineColor(kMagenta);
  pm1t->SetLineColor(kMagenta);
  pm2t->SetLineColor(kMagenta);
  pm3t->SetLineColor(kMagenta);
  pm4t->SetLineColor(kMagenta);
  pm5t->SetLineColor(kMagenta);
  njt3t->SetLineColor(kMagenta);
  njl3t->SetLineColor(kMagenta);
  njt4t->SetLineColor(kMagenta);
  njl4t->SetLineColor(kMagenta);
  htat->SetLineColor(kMagenta);
  ht3t->SetLineColor(kMagenta);
  ht4t->SetLineColor(kMagenta);
  ht4l1t->SetLineColor(kMagenta);
  ht4l2t->SetLineColor(kMagenta);
  ht4t1t->SetLineColor(kMagenta);
  ht4t2t->SetLineColor(kMagenta);
  ht3l1t->SetLineColor(kMagenta);
  ht3l2t->SetLineColor(kMagenta);
  ht3t1t->SetLineColor(kMagenta);
  ht3t2t->SetLineColor(kMagenta);





  
  THStack *hpt     = new THStack("hpt","JetsPt");
  hpt->Add(ak8ptq);
  hpt->Add(ak8ptt);
  hpt->Add(ak8pts);


  THStack *ht31    = new THStack("ht31","JetsPt");
  ht31->Add(t31q);
  ht31->Add(t31t);
  ht31->Add(t31s);

  THStack *hphos   = new THStack("hphos","JetsPt");
  hphos->Add(ak8_phosubfq);
  hphos->Add(ak8_phosubft);
  hphos->Add(ak8_phosubfs);
  
  THStack *hhaspho = new THStack("hhaspho","JetsPt");
  //hhaspho->Add



  THStack *hm0 = new THStack("hm0","JetsPt");
  hm0->Add(pm0q);
  hm0->Add(pm0t);
  hm0->Add(pm0s);
  
  THStack *hm1 = new THStack("hm1","JetsPt");
  hm1->Add(pm1q);
  hm1->Add(pm1t);
  hm1->Add(pm1s);
 
  THStack *hm2 = new THStack("hm2","JetsPt");
  hm2->Add(pm2q);
  hm2->Add(pm2t);
  hm2->Add(pm2s);

  
  THStack *hm3 = new THStack("hm3","JetsPt");
  hm3->Add(pm3q);
  hm3->Add(pm3t);
  hm3->Add(pm3s);

  THStack *hm4 = new THStack("hm4","JetsPt");
  hm4->Add(pm4q);
  hm4->Add(pm4t);
  hm4->Add(pm4s);

  THStack *hm5 = new THStack("hm5","JetsPt");
  hm5->Add(pm5q);
  hm5->Add(pm5t);
  hm5->Add(pm5s);


  //************************


  THStack *nj3t = new THStack("nj3t","3 j Evs tight Jets");
  nj3t->Add(njt3q);
  nj3t->Add(njt3t);
  nj3t->Add(njt3s);

  THStack *nj3l = new THStack("nj3l","3 j Evs loose Jets");
  nj3l->Add(njl3q);
  nj3l->Add(njl3t);
  nj3l->Add(njl3s);

  THStack *nj4t = new THStack("nj4t","4 j Evs tight Jets");
  nj4t->Add(njt4q);
  nj4t->Add(njt4t);
  nj4t->Add(njt4s);

  THStack *nj4l = new THStack("nj4l","4 j Evs loose Jets");
  nj4l->Add(njl4q);
  nj4l->Add(njl4t);
  nj4l->Add(njl4s);

  //Rebinning the mass plots
  Lhotmassq->Rebin(2);
  Lhotmasst->Rebin(2);
  Lhotmasss->Rebin(2);
  Thotmassq->Rebin(2);
  Thotmasst->Rebin(2);
  Thotmasss->Rebin(2);



  THStack *nj4l2m = new THStack("nj4l2m","4 j mass Evs loose Jets");
  nj4l2m->Add(Lhotmassq);
  nj4l2m->Add(Lhotmasst);
  nj4l2m->Add(Lhotmasss);

  THStack *nj4T2m = new THStack("nj4T2m","4 j mass Evs Tight Jets");
  nj4T2m->Add(Thotmassq);
  nj4T2m->Add(Thotmasst);
  nj4T2m->Add(Thotmasss);


  
 


  TCanvas *c1 = new TCanvas("c1","step1",1200,600);
  c1->Divide(2,1); 
  c1->cd(1);
  hpt->Draw();
  hpt->GetXaxis()->SetTitle("Jet Pt GeVc^{-1}");
  
  c1->cd(2);
  hm1->Draw();
  hm1->GetXaxis()->SetTitle("Jet Prunned Mass GeVc^{-2}"); 
  c1->Update();
  c1->SaveAs("ptcut.png");
  
  TCanvas *c2 = new TCanvas("c2","step2",1200,600);
  c2->Divide(2,1); 
  c2->cd(1);
  ht31->Draw();
  ht31->GetXaxis()->SetTitle("#tau_3/#tau_1");

  c2->cd(2);
  hm2->Draw();
  hm2->GetXaxis()->SetTitle("Jet Prunned Mass GeVc^{-2}"); 
   c2->Update();
 
 c2->SaveAs("ht31.png");
  
  /* 
  TCanvas *c3 = new TCanvas("c3","step2",1200,600);
  c3->Divide(2,1); 
  c3->cd(1);
  hhasphos->Draw();
  hhasphos->GetXaxis()->SetTitle("Has Photon Pt > 20 GeVc^{-1}");
  
  c3->cd(2);
  hm3->Draw();
  hm3->GetXaxis()->SetTitle("Jet Prunned Mass GeVc^{-2}"); 
  c3->SaveAs("hasphos.png");
  */
  
  TCanvas *c4 = new TCanvas("c4","step2",1200,600);
  c4->Divide(2,1); 
  c4->cd(1);
  hphos->Draw();
  hphos->GetXaxis()->SetTitle("Pt_{#gamma}/Pt_{subjet}");
  
  c4->cd(2);
  hm4->Draw();
  hm4->GetXaxis()->SetTitle("Jet Prunned Mass GeVc^{-2}"); 
   c4->Update();
 
  c4->SaveAs("phos.png");
  
  
  TCanvas *c5 = new TCanvas("","",1200,800);
  c5->Divide(4,2);
  c5->cd(1);
  
  c5->cd(1);
  c5->cd(1);
  c5->cd(1);
  c5->cd(1);
  c5->cd(1);
  

  c5->SaveAs("HTplots.png");
  
  TCanvas *c6 = new TCanvas("c6","",1000,1000);
  c6->Divide(2,2);
  c6->cd(1)->SetLogy();
  nj3l->Draw();
  nj3l->GetXaxis()->SetTitle("Njets Loose per event"); 

  c6->cd(2)->SetLogy();
  nj3t->Draw();
  nj3t->GetXaxis()->SetTitle("Njets Tight per event"); 


  c6->cd(3)->SetLogy();
  nj4l->Draw();
  nj4l->GetXaxis()->SetTitle("Njets Loose per event"); 
 
 

  c6->cd(4)->SetLogy();
  nj4t->Draw();
  nj4t->GetXaxis()->SetTitle("Njets Tight per event"); 
 
  c6->Update();
  c6->SaveAs("NjTL.png");



  TCanvas *c7 = new TCanvas("c7","",1000,500);
  c7->Divide(2,1);
  c7->cd(1);
  nj4l2m->Draw();
  nj4l2m->GetXaxis()->SetTitle("Jet Prunned Mass GeVc^{-2}");

  c7->cd(2);
  nj4T2m->Draw();
  nj4T2m->GetXaxis()->SetTitle("Jet Prunned Mass GeVc^{-2}");


  c7->SaveAs("PrnM_sel.png");

 
 
  

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

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

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

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

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

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

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

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

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


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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  return c;

}
Example #27
0
void makeBkgdFilesEta(int charge=1, int two_or_four=4, int etaLow=0, int etaHigh=100) {

  // ******************************************************
  // Read in the data set and all the histograms needed 
  // to do the actual calculation
  // ******************************************************

  string dataDir="/star/data01/pwg/stevens4/wAnalysis/xSecPaper/sl11b/data/";
  string dataName="run9setABCD.wana.hist.root";
      
  gStyle->SetOptDate(0);
  TFile *f1 = new TFile(Form("%s%s",dataDir,dataName));
  
  // get the signal w/ and w/o the EEMC in the algo
  if (charge == 1) {
    TH1F *signal = (TH1F*)((TH2F*)f1->Get("pos_muclustpTbal_wE_etaBin"))->ProjectionY("signal_py",etaLow,etaHigh);
    TH1F *signal_wo_eemc = (TH1F*)((TH2F*)f1->Get("pos_muclustpTbal_noE_etaBin"))->ProjectionY("signal_no_eemc_py",etaLow,etaHigh);
  } else if (charge == -1) {
    TH1F *signal = (TH1F*)((TH2F*)f1->Get("neg_muclustpTbal_wE_etaBin"))->ProjectionY("signal_py",etaLow,etaHigh);
    TH1F *signal_wo_eemc = (TH1F*)((TH2F*)f1->Get("neg_muclustpTbal_noE_etaBin"))->ProjectionY("signal_no_eemc_py",etaLow,etaHigh);
  } else if (charge == 0) { //not eta dependent yet
    TH1F *signal = (TH1F*)f1->Get("muclustPtBal");
    TH1F *signal_wo_eemc = (TH1F*)f1->Get("muclustPtBalnoE");
  }

  // ******************************************************
  // Read in all the MC data sets for background 
  // subtractions and studies
  // ******************************************************

  TFile *MC_fs[6];
  string mcDir="/star/u/stevens4/wAnalysis/efficXsec/outEmb/gainUp2/";
  string tpcHV="";
  //string tpcHV="HighTpcHV";

  MC_fs[0] = new TFile(Form("%sWplus%s.wana.hist.root",mcDir,tpcHV)); // W+ -> e++nu
  MC_fs[1] = new TFile(Form("%sWminus%s.wana.hist.root",mcDir,tpcHV)); // W- -> e-+nu
  MC_fs[2] = new TFile(Form("%sWtau%s.wana.hist.root",mcDir,tpcHV)); // W -> tau+nu
  MC_fs[3] = new TFile(Form("%sZany%s.wana.hist.root",mcDir,tpcHV)); // Z -> any
  MC_fs[4] = new TFile(Form("%sZe+e-Interf%s.wana.hist.root",mcDir,tpcHV)); // Z/gamma* -> e+ e-

  //get eta dependent signal and background from MC
  TH1F *MC_dists_raw[5][3];
  for (int i=0; i<5; i++) {
    if (charge == 1) {
      MC_dists_raw[i][0] = (TH1F*)((TH2F*)MC_fs[i]->Get("pos_muclustpTbal_wE_etaBin"))->ProjectionY(Form("%d_0_py",i),etaLow,etaHigh);
      MC_dists_raw[i][1] = (TH1F*)((TH2F*)MC_fs[i]->Get("pos_muclustpTbal_noE_etaBin"))->ProjectionY(Form("%d_1_py",i),etaLow,etaHigh);
      MC_dists_raw[i][2] = (TH1F*)((TH2F*)MC_fs[i]->Get("pos_muclustpTbal_back_etaBin"))->ProjectionY(Form("%d_2_py",i),etaLow,etaHigh);
      //cout<<i<<" "<<MC_dists_raw[i][0]->Integral()<<endl;
    } else if (charge == -1) {
      MC_dists_raw[i][0] = (TH1F*)((TH2F*)MC_fs[i]->Get("neg_muclustpTbal_wE_etaBin"))->ProjectionY(Form("%d_0_py",i),etaLow,etaHigh);
      MC_dists_raw[i][1] = (TH1F*)((TH2F*)MC_fs[i]->Get("neg_muclustpTbal_noE_etaBin"))->ProjectionY(Form("%d_1_py",i),etaLow,etaHigh);
      MC_dists_raw[i][2] = (TH1F*)((TH2F*)MC_fs[i]->Get("neg_muclustpTbal_back_etaBin"))->ProjectionY(Form("%d_2_py",i),etaLow,etaHigh);
    } else if (charge == 0) { //not eta dependent yet
      MC_dists_raw[i][0] = (TH1F*)MC_fs[i]->Get("muclustPtBal");
      MC_dists_raw[i][1] = (TH1F*)MC_fs[i]->Get("muclustPtBalnoE");
      MC_dists_raw[i][2] = (TH1F*)MC_fs[i]->Get("muclustPtBal_bckgrd");
    }
  }
  
  //pure lumi from pythia to scale MC
  float lumi[5] = {128.6,385.0,96.2,53.1,531.9};

  //scale MC to match lumi of the dataset
  float lumi_fact[6];
  for (int i=0; i<5; i++) {lumi_fact[i] = 13.18/lumi[i];}
  for (int i=0; i<5; i++) {
    for (int j=0; j<3; j++) {
      MC_dists_raw[i][j]->Scale(lumi_fact[i]);
      //cout<<MC_dists_raw[i][j]->Integral()<<endl;
    }
  }

  // Repack the MC histograms to mesh with the odd staggered binning that
  // is being used
  char str[200];
  TH1F *MC_dists_repack[5][3];
  for (int i=0; i<5; i++) {
    sprintf(str,"mcclustPtBal_%d",i);
    MC_dists_repack[i][0] = new TH1F(str,str,49,1.,99.);
    sprintf(str,"mcclustPtBalnoE_%d",i);
    MC_dists_repack[i][1] = new TH1F(str,str,49,1.,99.);
    sprintf(str,"mcclustPtBal_bckgrd_%d",i);
    MC_dists_repack[i][2] = new TH1F(str,str,49,1.,99.);
  }

  for (int i=0; i<5; i++) {
    for (int j=0; j<3; j++) {
      for (int k=1; k<=49; k++) {
        MC_dists_repack[i][j]->SetBinContent(k,MC_dists_raw[i][j]->GetBinContent(2*k)+MC_dists_raw[i][j]->GetBinContent(2*k+1));
      }
    }
  }

  // Make the EEMC background the real one of interest now
  for (int i=0; i<5; i++) {
    MC_dists_repack[i][1]->Add(MC_dists_repack[i][0],-1);
    MC_dists_raw[i][1]->Add(MC_dists_raw[i][0],-1.);
  }

  // **********************************************
  // Do some other stuff
  // **********************************************

  TH1F *eemc_bkgd = signal_wo_eemc->Clone();
  eemc_bkgd->Add(signal,-1.); //this is the '2nd endcap' bkgd
  eemc_bkgd->Add(MC_dists_raw[4][1],-1.);//remove known Z from '2nd endcap' bkgd

  TH1F *signal_final = signal->Clone();
  signal_final->Add(eemc_bkgd,-1); 

  //all histos rebinned by to match binning starting at 25 GeV
  TH1F *eemc_bkgd2 = new TH1F("eemc_bkgd2","eemc_bkgd2",49,1,99);
  TH1F *zsig_bkgd2 = new TH1F("zsig_bkgd2","zsig_bkgd2",49,1,99);
  TH1F *zeemc_bkgd2 = new TH1F("zeemc_bgkd2","zeemc_bkgd2",49,1,99);
  TH1F *zback_bkgd2 = new TH1F("zback_bkgd2","zback_bkgd2",49,1,99);

  TH1F *zanysig_bkgd2 = new TH1F("zanysig_bkgd2","zanysig_bkgd2",49,1,99);
  TH1F *zanyeemc_bkgd2 = new TH1F("zanyeemc_bgkd2","zanyeemc_bkgd2",49,1,99);
  TH1F *zanyback_bkgd2 = new TH1F("zanyback_bkgd2","zanyback_bkgd2",49,1,99);

  TH1F *zsig = MC_dists_raw[4][0]->Clone();
  TH1F *zeemc = MC_dists_raw[4][1]->Clone();
  TH1F *zback = MC_dists_raw[4][2]->Clone();

  //subtract off MC Z contribution to signal
  signal_final->Add(zsig,-1.);

  // First get the "nominal" QCD background shape (charge summed)
  TH1F *bkgd_shape1 = (TH1F*)((TH2F*)f1->Get("pos_muclustpTbal_back_etaBin"))->ProjectionY("back1_py",etaLow,etaHigh);
  bkgd_shape1->Add((TH1F*)((TH2F*)f1->Get("neg_muclustpTbal_back_etaBin"))->ProjectionY("back2_py",etaLow,etaHigh));

  //rebin background shape
  TH1F *bkgd_shape_nom = new TH1F("bkgd_shape","bkgd_shape",49,1,99);
  for (int i=1; i<=49; i++) {
    bkgd_shape_nom->SetBinContent(i,bkgd_shape1->GetBinContent(2*i)+
                                    bkgd_shape1->GetBinContent(2*i+1));
  }
  TH1F *bkgd_shape_nom2 = bkgd_shape_nom->Clone();

  TH1F *signal_final2 = new TH1F("signal_final2","signal_final2",49,1,99);
  signal_final2->SetLineColor(2);
  signal_final2->SetLineWidth(2.*signal_final2->GetLineWidth());
  TH1F *signal2 = new TH1F("signal2","signal2",49,1,99);
  for (int i=1; i<=49; i++) { //repack all distributions
    signal_final2->SetBinContent(i,signal_final->GetBinContent(2*i)+
                                   signal_final->GetBinContent(2*i+1));
    signal2->SetBinContent(i,signal->GetBinContent(2*i)+
                             signal->GetBinContent(2*i+1));
    eemc_bkgd2->SetBinContent(i,eemc_bkgd->GetBinContent(2*i)+
                                eemc_bkgd->GetBinContent(2*i+1));
    zsig_bkgd2->SetBinContent(i,zsig->GetBinContent(2*i)+
                                zsig->GetBinContent(2*i+1));
    zeemc_bkgd2->SetBinContent(i,zeemc->GetBinContent(2*i)+
                                 zeemc->GetBinContent(2*i+1));
    zback_bkgd2->SetBinContent(i,zback->GetBinContent(2*i)+
                                 zback->GetBinContent(2*i+1));
    zanysig_bkgd2->SetBinContent(i,MC_dists_raw[3][0]->GetBinContent(2*i)+
                                   MC_dists_raw[3][0]->GetBinContent(2*i+1));
    zanyeemc_bkgd2->SetBinContent(i,MC_dists_raw[3][1]->GetBinContent(2*i)+
                                    MC_dists_raw[3][1]->GetBinContent(2*i+1));
    zanyback_bkgd2->SetBinContent(i,MC_dists_raw[3][2]->GetBinContent(2*i)+
                                    MC_dists_raw[3][2]->GetBinContent(2*i+1));
  }

  TCanvas *can2 = new TCanvas("can2","can2",0,0,600,400);
  signal2->Draw();
  signal_final2->Draw("same");
  //can2->Print("signal_w_eemc.eps");
  //can2->Print("signal_w_eemc.png");


  // **********************************************
  // plot all signals and backgrounds from data and simu
  // **********************************************
  eemc_bkgd->SetLineColor(8);
  eemc_bkgd->SetLineWidth(2.*eemc_bkgd->GetLineWidth());
  bkgd_shape_nom2->SetLineColor(4);
  bkgd_shape_nom2->SetLineWidth(2.*bkgd_shape_nom2->GetLineWidth());

  TCanvas *can8 = new TCanvas("can8","can8",0,0,3000,1800);
  can8->Divide(5,3);
  for (int i=0; i<5; i++) {
    for (int j=0; j<3; j++) {
      can8->cd(5*(j)+i+1);
      //cout << 5*(j)+i+1 << endl;
      gPad->SetGridx(0);
      gPad->SetGridy(0);
      if (j == 0) {
        signal_final2->Draw();
      } else if (j == 1) {
        gPad->SetLogy();
        eemc_bkgd->Draw();
      } else if (j == 2) {
        gPad->SetLogy();
        bkgd_shape_nom2->Draw();
      }
      MC_dists_repack[i][j]->Draw("same");
    }
  }
  //can8->Print("phys_bkgds.eps");
  //can8->Print("phys_bkgds.png");

  for (int i=0; i<5; i++) {
    float signal_sum = 0.;
    float eemc_sum = 0.;
    float back_sum = 0.;
    for (int j=13; j<=49; j++) {
      signal_sum += MC_dists_repack[i][0]->GetBinContent(j);
      eemc_sum += MC_dists_repack[i][1]->GetBinContent(j);
      back_sum += MC_dists_repack[i][2]->GetBinContent(j);
    }
  }

  float signal_in_normMC[3];
  if (charge == 1) {
    signal_in_normMC[0]=MC_dists_repack[0][0]->Integral(8,8);
    signal_in_normMC[1]=MC_dists_repack[0][0]->Integral(9,9);
    signal_in_normMC[2]=MC_dists_repack[0][0]->Integral(10,10);
  }
  if (charge == -1) {
    signal_in_normMC[0]=MC_dists_repack[1][0]->Integral(8,8);
    signal_in_normMC[1]=MC_dists_repack[1][0]->Integral(9,9);
    signal_in_normMC[2]=MC_dists_repack[1][0]->Integral(10,10);
  }


  //Tau needs to be scale due to polarized tau decay (note from Carl)
  float taufrac=1.5;
  // subtract off the tau background
  signal_final2->Add(MC_dists_repack[2][0],-1.*taufrac);
  
  // ******************************************************
  // Do the iterative normalization of the W signal to
  // to the background for the nominal shape
  // ****************************************************** 

  // Now lets try a new background function
  // Fit the peak with a line from 23<ET<39
  TF1 *func1 = new TF1("func1","[0]+[1]*x",23,39);
  func1->SetParameter(0,0.);
  func1->SetParameter(1,0.);

  TCanvas *can4 = new TCanvas("can4","can4",0,0,600,400);
  signal_final2->Draw();

  // Calculate the background for the nominal signal
  // by doing the 20 iterations over the signal peak 
  float signal_in_norm[50];
  TH1F *bkgd_shape_unnorm[20];
  TH1F *signal_for_new[20];
  for (int i=0; i<20; i++) {
    bkgd_shape_unnorm[i] = (TH1F*)bkgd_shape_nom->Clone();
    signal_for_new[i] = (TH1F*)signal_final2->Clone();

    // subtract off the remaining Z signal from the background
    bkgd_shape_unnorm[i]->Add(zback_bkgd2,-1.);
    
    // calculate the W signal in the normalization bins
    signal_in_norm[8] = func1->Integral(15,17);
    signal_in_norm[9] = func1->Integral(17,19);
    signal_in_norm[10] = func1->Integral(19,21);
    //cout << "Integrals = " << signal_in_norm[8] << " " << signal_in_norm[9] << " " << signal_in_norm[10] << endl;
    for (int j=8; j<=10; j++) {
      if (signal_in_norm[j] < 0) {signal_in_norm[j] = 0.;}
    }

    //use MC for signal in normalization window
    signal_in_norm[8]=signal_in_normMC[0];
    signal_in_norm[9]=signal_in_normMC[1];
    signal_in_norm[10]=signal_in_normMC[2];

    // calculate the normalization factor using the 
    // signal subtraction normalization bins
    float normt = 0, normb = 0.;
    for (int k=8; k<10; k++) {
      if (bkgd_shape_unnorm[i]->GetBinContent(k) > 0) {
        normt += signal_final2->GetBinContent(k)-signal_in_norm[k];
        normb += bkgd_shape_unnorm[i]->GetBinContent(k);
      }
    }
    if (normb > 0 && normt > 0) {
      float norm = normt/normb;
      bkgd_shape_unnorm[i]->Scale(norm);
      bkgd_shape_unnorm[i]->Draw("same");
      //cout << "norm " << i << " = " << norm << endl;
    }
    else if(normb > 0 && normt < 0){
      float norm = 0;
      bkgd_shape_unnorm[i]->Scale(norm);
      bkgd_shape_unnorm[i]->Draw("same");
    }
  
    // With the new signal estimate, calculate the normalization
    // factor 
    for (int j=1; j<=49; j++) {
      if (bkgd_shape_unnorm[i]->GetBinContent(j) < 0) {bkgd_shape_unnorm[i]->SetBinContent(j,0.);}
    }
    signal_for_new[i]->Add(bkgd_shape_unnorm[i],-1.); 
    signal_for_new[i]->Fit(func1,"RQ");
  }
  //can4->Print("new_norm.eps");
  //can4->Print("new_norm.png");

  TH1F *signal_in_norm_region = new TH1F("signal_in_norm_region","signal_in_norm_region",49,1.,99.);
  
  signal_in_norm_region->SetBinContent(8,signal_in_norm[8]);
  signal_in_norm_region->SetBinContent(9,signal_in_norm[9]); 
 
  TH1F *new_bkgd = new TH1F("new_bkgd","new_bkgd",49,1.,99.);
  new_bkgd = (TH1F*)bkgd_shape_unnorm[19]->Clone();
  new_bkgd->SetName("new_bkgd");

  TCanvas *can5 = new TCanvas("can5","can5",0,0,600,400);
  signal_final2->Draw();
  new_bkgd->Draw("same");
  signal_in_norm_region->Draw("same");
  //can5->Print("signal_new.eps"); 
  //can5->Print("signal_new.png");

  // ******************************************************
  // Calculate all the 60 shapes for the background
  // systematic shape study
  // ******************************************************

  // get the various background shapes made by
  // using different parameters for sPtBal cut
  TH1F *bkgd_hists_from_file[21];
  TH1F *bkgd_hists_from_file2[21];
  char str[200];
  for (int i=0; i<=20; i++) {

    //use projections from eta dependent histos
    sprintf(str,"pos_failsPtBal_sPtBal_bin_%d_py",i);
    bkgd_hists_from_file[i] = (TH1F*)((TH2F*)f1->Get(Form("pos_failsPtBal_sPtBal_bin_%d",i)))->ProjectionY(str,etaLow,etaHigh);
    sprintf(str,"neg_failsPtBal_sPtBal_bin_%d_py",i);
    bkgd_hists_from_file2[i] = (TH1F*)((TH2F*)f1->Get(Form("neg_failsPtBal_sPtBal_bin_%d",i)))->ProjectionY(str,etaLow,etaHigh);
    bkgd_hists_from_file[i]->Add(bkgd_hists_from_file2[i]);
    
  }

  // Now do the rebinning
  TH1F *bkgd_hists1[21];
  TH1F *bkgd_hists2[21];
  TH1F *bkgd_hists3[21];
  for (int i=0; i<=20; i++) {
    sprintf(str,"bkgd_hist1_%d",i);
    bkgd_hists1[i] = new TH1F(str,str,49,1,99);
    sprintf(str,"bkgd_hist2_%d",i);
    bkgd_hists2[i] = new TH1F(str,str,49,1,99);
    sprintf(str,"bkgd_hist3_%d",i);
    bkgd_hists3[i] = new TH1F(str,str,49,1,99);
    for (int k=1; k<=49; k++) {
      bkgd_hists1[i]->SetBinContent(k,bkgd_hists_from_file[i]->GetBinContent(2*k)+bkgd_hists_from_file[i]->GetBinContent(2*k+1));
      bkgd_hists2[i]->SetBinContent(k,bkgd_hists_from_file[i]->GetBinContent(2*k)+bkgd_hists_from_file[i]->GetBinContent(2*k+1));
      bkgd_hists3[i]->SetBinContent(k,bkgd_hists_from_file[i]->GetBinContent(2*k)+bkgd_hists_from_file[i]->GetBinContent(2*k+1));
    }
  }

  // initiaize the iterative fit functions
  TF1 *func2 = new TF1("func2","[0]+[1]*x",23,39);
  func2->SetParameter(0,0.);
  func2->SetParameter(1,0.);
  TF1 *func3 = new TF1("func3","[0]+[1]*x",23,39);
  func3->SetParameter(0,0.);
  func3->SetParameter(1,0.);

  // Now loop over the the 60 possibilities (20 loops and 3 normalization regions)
  float final_sig_in_norm[21][3];
  float final_chisquare[21];
  float signal_in_norm1[50];
  float signal_in_norm2[50];
  float signal_in_norm3[50];
  TH1F *new_bkgd_hists1[21];
  TH1F *new_bkgd_hists2[21];
  TH1F *new_bkgd_hists3[21];
  TH1F *bkgd_shape_unnorm1[20];
  TH1F *bkgd_shape_unnorm2[20];
  TH1F *bkgd_shape_unnorm3[20];
  TH1F *signal_for_new1[20];
  TH1F *signal_for_new2[20];
  TH1F *signal_for_new3[20];
  for (int i=0; i<=20; i++) { //loop over possible sPtBalance cuts

    func1->SetParameter(0,0.);
    func1->SetParameter(1,0.);
    func2->SetParameter(0,0.);
    func2->SetParameter(1,0.);
    func3->SetParameter(0,0.);
    func3->SetParameter(1,0.);
    
    for (int l=0; l<20; l++) { //loop over 20 iterations
      bkgd_shape_unnorm1[l] = (TH1F*)bkgd_hists1[i]->Clone();
      bkgd_shape_unnorm2[l] = (TH1F*)bkgd_hists2[i]->Clone();
      bkgd_shape_unnorm3[l] = (TH1F*)bkgd_hists3[i]->Clone();
      signal_for_new1[l] = (TH1F*)signal_final2->Clone();
      signal_for_new2[l] = (TH1F*)signal_final2->Clone();
      signal_for_new3[l] = (TH1F*)signal_final2->Clone();
      
      // subtract off the Z contamination
      bkgd_shape_unnorm1[l]->Add(zback_bkgd2,-1.);
      bkgd_shape_unnorm2[l]->Add(zback_bkgd2,-1.);
      bkgd_shape_unnorm3[l]->Add(zback_bkgd2,-1.);
      
      // calculate the signal in the normalization bins
      signal_in_norm1[8] = func1->Integral(15,17);
      signal_in_norm1[9] = func1->Integral(17,19);
      signal_in_norm1[10] = func1->Integral(19,21);
      signal_in_norm2[8] = func2->Integral(15,17);
      signal_in_norm2[9] = func2->Integral(17,19);
      signal_in_norm2[10] = func2->Integral(19,21);
      signal_in_norm3[8] = func3->Integral(15,17);
      signal_in_norm3[9] = func3->Integral(17,19);
      signal_in_norm3[10] = func3->Integral(19,21);

      for (int m=8; m<=10; m++) {
	if (signal_in_norm1[m] < 0) {signal_in_norm1[m] = 0.;}
	if (signal_in_norm2[m] < 0) {signal_in_norm2[m] = 0.;}
	if (signal_in_norm3[m] < 0) {signal_in_norm3[m] = 0.;}
      }
   
      //use MC for signal in normalization window
      signal_in_norm1[8]=signal_in_normMC[0];
      signal_in_norm1[9]=signal_in_normMC[1];
      signal_in_norm1[10]=signal_in_normMC[2];
      signal_in_norm2[8]=signal_in_normMC[0];
      signal_in_norm2[9]=signal_in_normMC[1];
      signal_in_norm2[10]=signal_in_normMC[2];
      signal_in_norm3[8]=signal_in_normMC[0];
      signal_in_norm3[9]=signal_in_normMC[1];
      signal_in_norm3[10]=signal_in_normMC[2];

      // calculate the normalization factor for 1 bin
      float normt = 0, normb = 0.;
      for (int k=8; k<=8; k++) {
	if (bkgd_shape_unnorm1[l]->GetBinContent(k) > 0) {
	  normt += signal_final2->GetBinContent(k)-signal_in_norm1[k];
	  normb += bkgd_shape_unnorm1[l]->GetBinContent(k);
	}
      }
      if (normb > 0 && normt > 0) {
	float norm = normt/normb;
	bkgd_shape_unnorm1[l]->Scale(norm);
      }
      else if(normb > 0 && normt < 0){
	float norm = 0;
	bkgd_shape_unnorm1[l]->Scale(norm);
      }
      for (int m=1; m<=49; m++) {
	if (bkgd_shape_unnorm1[l]->GetBinContent(m) < 0) {bkgd_shape_unnorm1[l]->SetBinContent(m,0.);}
      }
      signal_for_new1[l]->Add(bkgd_shape_unnorm1[l],-1.);
      signal_for_new1[l]->Fit(func1,"RQ");
      
      // calculate the normalization factor for 2 bins
      normt = 0.; normb = 0.;
      for (int k=8; k<=9; k++) {
	if (bkgd_shape_unnorm2[l]->GetBinContent(k) > 0) {
	  normt += signal_final2->GetBinContent(k)-signal_in_norm2[k];
	  normb += bkgd_shape_unnorm2[l]->GetBinContent(k);
	}
      }
      if (normb > 0 && normt > 0) {
	float norm = normt/normb;
	bkgd_shape_unnorm2[l]->Scale(norm);
	//cout << "norm " << i << " " << l << " = " << norm << endl;
      }
      else if(normb > 0 && normt < 0){
	float norm = 0;
	bkgd_shape_unnorm2[l]->Scale(norm);
      }
      for (int m=1; m<=49; m++) {
	if (bkgd_shape_unnorm2[l]->GetBinContent(m) < 0) {bkgd_shape_unnorm2[l]->SetBinContent(m,0.);}
      }
      signal_for_new2[l]->Add(bkgd_shape_unnorm2[l],-1.);
      signal_for_new2[l]->Fit(func2,"RQ");
      
      // calculate the normalization factor for 3 bins
      normt = 0.; normb = 0.;
      for (int k=8; k<=10; k++) {
	if (bkgd_shape_unnorm3[l]->GetBinContent(k) > 0) {
	  normt += signal_final2->GetBinContent(k)-signal_in_norm3[k];
	  normb += bkgd_shape_unnorm3[l]->GetBinContent(k);
	}
      }
      if (normb > 0 && normt > 0) {
	float norm = normt/normb;
	bkgd_shape_unnorm3[l]->Scale(norm);
      }
      else if(normb > 0 && normt < 0){
	float norm = 0;
	bkgd_shape_unnorm3[l]->Scale(norm);
      }

      for (int m=1; m<=49; m++) {
	if (bkgd_shape_unnorm3[l]->GetBinContent(m) < 0) {bkgd_shape_unnorm3[l]->SetBinContent(m,0.);}
      }
      signal_for_new3[l]->Add(bkgd_shape_unnorm3[l],-1.);
      signal_for_new3[l]->Fit(func3,"RQ");
    } // end of for loop over l
    
    // Save the last iteration as the background histogram
    new_bkgd_hists1[i] = (TH1F*)bkgd_shape_unnorm1[19]->Clone();
    new_bkgd_hists2[i] = (TH1F*)bkgd_shape_unnorm2[19]->Clone();
    new_bkgd_hists3[i] = (TH1F*)bkgd_shape_unnorm3[19]->Clone();
    
  }

  // plot all the 60 histograms
  gStyle->SetTitleBorderSize(0);
  TCanvas *can6 = new TCanvas("can6","can6",0,0,600,400);
  signal_final2->SetStats(kFALSE);
  if (charge == 1) {
    signal_final2->SetTitle("W+ Background Shapes");
  } else if (charge == -1) {
    signal_final2->SetTitle("W- Background Shapes");
  }
  signal_final2->GetXaxis()->SetRangeUser(0.,70.);
  signal_final2->GetXaxis()->SetTitle("2x2 Cluster E_{T} (GeV)");
  signal_final2->Draw();
  for (int i=0; i<=20; i++) {
    new_bkgd_hists1[i]->Draw("same");
    new_bkgd_hists2[i]->Draw("same");
    new_bkgd_hists3[i]->Draw("same");
  }
  new_bkgd->SetLineColor(4);
  //new_bkgd->SetLineWidth(4.*new_bkgd->GetLineWidth());
  new_bkgd->Draw("same");
  if (charge == 1) {
    //can6->Print("Wplus_bkgd_shapes.eps");
    //can6->Print("Wplus_bkgd_shapes.png");
  } else if (charge == -1) {
    //can6->Print("Wminus_bkgd_shapes.eps");
    //can6->Print("Wminus_bkgd_shapes.png");
  }
 
  TH1F *chi2s = new TH1F("chi2s","chi2s",50,0.,10.);
  for (int i=0; i<=20; i++) {
    chi2s->Fill(final_chisquare[i]);
  }
 
  TCanvas *can7 = new TCanvas("can7","can7",0,0,600,400);
  chi2s->Draw();
  //can7->Print("chi2s.eps"); 
  //can7->Print("chi2s.png");

  // ************************************************
  // Now calculate all background numbers and their 
  // systematic uncertainties (and spit them out to histograms)
  // ************************************************

  // First get the simple numbers (backgrounds and their statistical uncertainties)
  TH1F *tauhist = MC_dists_repack[2][0]->Clone();
  tauhist->Scale(taufrac);
  float tau_norm = lumi_fact[2];
  float Z_norm = lumi_fact[4];
  float bkgd_sum = 0.;
  float signal_sum = 0.;
  float raw_sum = 0.;
  float QCD_sum = 0., tau_sum = 0., eemc_sum = 0.;
  float QCD_raw_sum = 0.;
  float Zany_bkgd_sum = 0.;
  float Zany_eemc_sum = 0.;
  float zsig_sum = 0., zeemc_sum = 0.,zback_sum = 0.;
  float zanysig_sum = 0., zanyeemc_sum = 0.,zanyback_sum = 0.;
  for (int i=13; i<=49; i++) { //get counts in ET>25 for diff contrib.
    bkgd_sum += new_bkgd->GetBinContent(i);
    bkgd_sum += tauhist->GetBinContent(i);
    bkgd_sum += eemc_bkgd2->GetBinContent(i);
    QCD_raw_sum += bkgd_shape_nom->GetBinContent(i);
    QCD_sum += new_bkgd->GetBinContent(i);
    tau_sum += tauhist->GetBinContent(i);
    eemc_sum += eemc_bkgd2->GetBinContent(i);
    signal_sum += signal_final2->GetBinContent(i);
    raw_sum += signal2->GetBinContent(i);
    zsig_sum += zsig_bkgd2->GetBinContent(i);
    zeemc_sum += zeemc_bkgd2->GetBinContent(i);
    zback_sum += zback_bkgd2->GetBinContent(i);
    zanysig_sum += zanysig_bkgd2->GetBinContent(i);
    zanyeemc_sum += zanyeemc_bkgd2->GetBinContent(i);
    zanyback_sum += zanyback_bkgd2->GetBinContent(i);
  }
  cout << "The total background for ET>25 is " << bkgd_sum+zsig_sum << endl;
  cout << "QCD = " << QCD_sum << ", tau = " << tau_sum << ", eemc = " << eemc_sum << ", and Z = " << zsig_sum << endl;
  cout << "Raw = " << raw_sum << endl;
  cout << "W Signal (w/o tau) = " << signal_sum-QCD_sum << endl;
  cout << "Z in sig = " << zsig_sum << endl;
  cout << "Z in eemc = " << zeemc_sum << endl;
  cout << "Z in back = " << zback_sum << endl;
  cout << "Zany in sig = " << zanysig_sum << endl;
  cout << "Zany in eemc = " << zanyeemc_sum << endl;
  cout << "Zany in back = " << zanyback_sum << endl;
  cout << "QCD raw in back = " << QCD_raw_sum << endl; 
  cout << "The QCD stat unc. is " << sqrt(norm*QCD_sum) << endl;
  float tau_stat = tau_norm*taufrac*sqrt(tau_sum/(tau_norm*taufrac));
  float tau_syst = 0.13*tau_sum;
  cout << "The tau stat unc. is " << tau_stat << " syst is " << tau_syst << " and total is " << sqrt(tau_stat*tau_stat + tau_syst*tau_syst) << endl;
  float eemc_stat = sqrt(eemc_sum);
  float eemc_syst = 0.13*zeemc_sum;
  cout << "The eemc stat unc. is " << eemc_stat << " syst is " << eemc_syst << " and total is " << sqrt(eemc_stat*eemc_stat + eemc_syst*eemc_syst) << endl;
  float Z_stat = Z_norm*sqrt(zsig_sum/Z_norm);
  float Z_syst = 0.13*zsig_sum;
  cout << "The Z stat unc. is " << Z_stat << " syst is " << Z_syst << " and total is " << sqrt(Z_stat*Z_stat + Z_syst*Z_syst) << endl;
      
  //for use with asymmetry analysis
  //cout << "f_tau = " << tau_sum/raw_sum << endl;
  //cout << "f_QCD = " << QCD_sum/raw_sum << endl;
  //cout << "f_EEMC = " << eemc_sum/raw_sum << endl;
  //cout << "f_Z = " << zsig_sum/raw_sum << endl;

  // Set up some histograms to hold all the errors that are calculated
  TH1F *raw_stat_err2 = new TH1F("raw_stat_err2","raw_stat_err2",49,1.,99.);
  TH1F *QCD_stat_err2 = new TH1F("QCD_stat_err2","QCD_stat_err2",49,1.,99.);
  TH1F *eemc_stat_err2 = new TH1F("eemc_stat_err2","eemc_stat_err2",49,1.,99.);
  TH1F *tau_stat_err2 = new TH1F("tau_stat_err2","tau_stat_err2",49,1.,99.);
  TH1F *QCD_syst_high_err = new TH1F("QCD_syst_high_err","QCD_syst_high_err",49,1.,99.);
  TH1F *QCD_syst_low_err = new TH1F("QCD_syst_low_err","QCD_syst_low_err",49,1.,99.);
  TH1F *zsig_stat_err2 = new TH1F("zsig_stat_err2","zsig_stat_err2",49,1.,99.);
  TH1F *zback_stat_err2 = new TH1F("zback_stat_err2","zback_stat_err2",49,1.,99.);
  TH1F *zeemc_stat_err2 = new TH1F("zeemc_stat_err2","zeemc_stat_err2",49,1.,99.);
 
 
  for (int i=1; i<=49; i++) {
    raw_stat_err2->SetBinContent(i,signal2->GetBinContent(i));
    QCD_stat_err2->SetBinContent(i,fabs(norm*new_bkgd->GetBinContent(i)));
    eemc_stat_err2->SetBinContent(i,max(eemc_bkgd2->GetBinContent(i),0)); //remove negative error
    tau_stat_err2->SetBinContent(i,tau_norm*taufrac*tauhist->GetBinContent(i));
    zsig_stat_err2->SetBinContent(i,Z_norm*zsig_bkgd2->GetBinContent(i));
    zback_stat_err2->SetBinContent(i,norm*norm*Z_norm*zback_bkgd2->GetBinContent(i));
    zeemc_stat_err2->SetBinContent(i,Z_norm*zeemc_bkgd2->GetBinContent(i));
    //cout << "Error " << i << " " << raw_stat_err2->GetBinCenter(i) << " " << raw_stat_err2->GetBinContent(i) << " " << QCD_stat_err2->GetBinContent(i) << " " << eemc_stat_err2->GetBinContent(i) << " " << tau_stat_err2->GetBinContent(i) << endl;
  }

  // Now go through all the 60 background shapes and find the
  // high and low in each ET bin to give the maximum extent uncertainty
  // for each ET bin (and also sum the low and high to give the
  // overall number used in the xsec analysis)  

  TH1F *low_bkgd = new_bkgd->Clone();
  low_bkgd->SetName("low_bkgd");
  TH1F *high_bkgd = new_bkgd->Clone();
  high_bkgd->SetName("high_bkgd");

  float low_sum = 0.;
  float high_sum = 0.;
  for (int i=7; i<=49; i++) {
    float high = 0.;
    float low = 10000.;
    for (int j=0; j<=20; j++) {
      if (new_bkgd_hists1[j]->GetBinContent(i) < low) {
	if (new_bkgd_hists1[j]->GetBinContent(i) >= 0) {
	  low = new_bkgd_hists1[j]->GetBinContent(i);
	}
      }
      if (new_bkgd_hists1[j]->GetBinContent(i) > high) {
	high = new_bkgd_hists1[j]->GetBinContent(i);
      }
      
      if (new_bkgd_hists2[j]->GetBinContent(i) < low) {
	if (new_bkgd_hists2[j]->GetBinContent(i) >= 0) {
	  low = new_bkgd_hists2[j]->GetBinContent(i);
	}
      }
      if (new_bkgd_hists2[j]->GetBinContent(i) > high) {
	high = new_bkgd_hists2[j]->GetBinContent(i);
      }
      
      if (new_bkgd_hists3[j]->GetBinContent(i) < low) {
	if (new_bkgd_hists3[j]->GetBinContent(i) >= 0) {
	  low = new_bkgd_hists3[j]->GetBinContent(i);
	}
      }
      if (new_bkgd_hists3[j]->GetBinContent(i) > high) {
	high = new_bkgd_hists3[j]->GetBinContent(i);
      }
      //cout << i << " low = " << low << " high = " << high << endl;
      //} // end of k-loop
    } // end of j-loop

    // calculate the sum
    low_bkgd->SetBinContent(i,0.);
    if ((low != 10000) && (new_bkgd->GetBinContent(i)-low > 0)) {
      if ((i >= 13)&&(i<=49)) {low_sum += low;}
      low_bkgd->SetBinContent(i,low);
    }
    if ((i >= 13)&&(i<=49)) {high_sum += high;} 
    high_bkgd->SetBinContent(i,high);
    //cout << i << " " << low_sum << " " << high_sum << endl;
    //cout << QCD_syst_low_err->GetBinCenter(i) << " low = " << low << " high = " << high << " nom = " << new_bkgd->GetBinContent(i) << endl;  
    // set the bin-by-bin error too
    if ((low != 10000) && (new_bkgd->GetBinContent(i)-low > 0)) {
      QCD_syst_low_err->SetBinContent(i,new_bkgd->GetBinContent(i)-low);
    } else {
      QCD_syst_low_err->SetBinContent(i,0.);
    }
    QCD_syst_high_err->SetBinContent(i,high-new_bkgd->GetBinContent(i));

  } // end of i=loop 

  cout << "QCD shape sys. unc. calc************" << endl;
  cout << "The QCD low sum = " << low_sum << endl;
  cout << "The QCD high sum = " << high_sum << endl; 

  cout << "The QCD low error = " << QCD_sum-low_sum << endl;
  cout << "The QCD high error = " << high_sum-QCD_sum << endl; 

  //totals for ET > 25
  float tot_stat = sqrt(tau_stat*tau_stat+eemc_stat*eemc_stat+Z_stat*Z_stat+norm*QCD_sum);
  cout << "total stat unc. is " << tot_stat << endl;
  float tot_syst_low = sqrt(tau_syst*tau_syst+eemc_syst*eemc_syst+Z_syst*Z_syst+(QCD_sum-low_sum)*(QCD_sum-low_sum));
  float tot_syst_high = sqrt(tau_syst*tau_syst+eemc_syst*eemc_syst+Z_syst*Z_syst+(QCD_sum-high_sum)*(QCD_sum-high_sum));
  cout << "total syst unc. is low: " << tot_syst_low << " and high: " << tot_syst_high << endl;
  cout << "total unc is low: " << sqrt(tot_syst_low*tot_syst_low+tot_stat*tot_stat) << " high: " << sqrt(tot_syst_high*tot_syst_high+tot_stat*tot_stat) <<endl;
  
  //final signal histo
  TH1F *signal_final3 = new TH1F("signal_final3","signal_final3",49,1.,99.);
  for (int i=1; i<=49; i++) {
    signal_final3->SetBinContent(i,signal_final2->GetBinContent(i));
  }
  signal_final3->Add(new_bkgd,-1.);


  //need to get 4 GeV wide bins starting at ET=25 to correct yields
#if 1
  cout<<"ET min, ET max, N_obs, N_obs-Nbkgd, QCD stat, EEMC stat, Tau stat, Zee stat, QCD syst+, QCD syst-, total stat, MC bkgd tot"<<endl;
  for (int i=7; i<=49; i=i+2) {
    cout.setf(ios::fixed);
    cout.precision(2);
    float Qcd_stat_err2=QCD_stat_err2->GetBinContent(i)+QCD_stat_err2->GetBinContent(i+1);
    float Eemc_stat_err2=eemc_stat_err2->GetBinContent(i)+eemc_stat_err2->GetBinContent(i+1);
    float Tau_stat_err2=tau_stat_err2->GetBinContent(i)+tau_stat_err2->GetBinContent(i+1);
    float Z_stat_err2=zsig_stat_err2->GetBinContent(i)+zsig_stat_err2->GetBinContent(i+1);
    cout << signal2->GetBinCenter(i)-1 << "," << signal2->GetBinCenter(i)+3 << "," << signal2->GetBinContent(i)+signal2->GetBinContent(i+1) << "," << signal_final3->GetBinContent(i)+signal_final3->GetBinContent(i+1) << "," << sqrt(Qcd_stat_err2) << "," << sqrt(Eemc_stat_err2) << "," << sqrt(Tau_stat_err2) << "," << sqrt(Z_stat_err2) << "," << QCD_syst_high_err->GetBinContent(i)+QCD_syst_high_err->GetBinContent(i+1) << "," << QCD_syst_low_err->GetBinContent(i)+QCD_syst_low_err->GetBinContent(i+1) ;
    //total statistical uncertainty
    cout<< "," <<sqrt(Tau_stat_err2+Z_stat_err2+Qcd_stat_err2+Eemc_stat_err2);
    //total MC syst uncertainty
    cout<< "," << zsig_bkgd2->GetBinContent(i)+zsig_bkgd2->GetBinContent(i+1) + tauhist->GetBinContent(i)+tauhist->GetBinContent(i+1)<<endl;
    
  }
#endif

  // ******************************************************
  // Write out the histograms of interest to a
  // file
  // ******************************************************

  if (charge == 1) {
    TFile *f2 = new TFile("bkgd_histos_pos_final.root","recreate");
  } else if (charge == -1) {
    TFile *f2 = new TFile("bkgd_histos_neg_final.root","recreate");
  } else if (charge == 0) {
    TFile *f2 = new TFile("bkgd_histos_sum.root","recreate");
  }

  f2->cd();

  if (two_or_four == 2) { 

    TH1F *signal_final3 = new TH1F("signal_final3","signal_final3",49,1.,99.);
    for (int i=1; i<=49; i++) {
      signal_final3->SetBinContent(i,signal_final2->GetBinContent(i));
    }
    signal_final3->Add(new_bkgd,-1.);

    tauhist->Write();
    zsig_bkgd2->Write();
    signal2->Write();
    signal_final2->Write(); 
    signal_final3->Write();
    eemc_bkgd2->Write(); 
    new_bkgd->Write();
    low_bkgd->Write();
    high_bkgd->Write();
    signal_in_norm_region->Write();

    raw_stat_err2->Write();
    QCD_stat_err2->Write();
    eemc_stat_err2->Write();
    tau_stat_err2->Write();
    QCD_syst_high_err->Write();
    QCD_syst_low_err->Write();
    zsig_stat_err2->Write();
    zback_stat_err2->Write();
    zeemc_stat_err2->Write();

#if 0
    for (int i=1; i<=49; i++) {
      cout.setf(ios::fixed);
      cout.precision(2);
      cout << " " << signal2->GetBinCenter(i) << " & " << signal2->GetBinContent(i) << " & " << signal_final3->GetBinContent(i) << " & " << QCD_stat_err2->GetBinContent(i) << " & " << eemc_stat_err2->GetBinContent(i) << " & " << tau_stat_err2->GetBinContent(i) << " & " << zsig_stat_err2->GetBinContent(i) << " & " << zback_stat_err2->GetBinContent(i) << " & " << QCD_syst_high_err->GetBinContent(i) << " & " << QCD_syst_low_err->GetBinContent(i) << " \\\\" << endl;
      
    }
#endif
  
    f2->Close();
 
  } else if (two_or_four == 4) {

    TH1F *tauhist_repack = new TH1F("tauhist_r","tauhist_r",24,3.,99.);
    TH1F *zsig_bkgd2_repack = new TH1F("zsig_bkgd2_r","zsig_bkgd2_r",24,3,99.);
    TH1F *signal2_repack = new TH1F("signal2_r","signal2_r",24,3.,99.);
    TH1F *signal_final2_repack = new TH1F("signal_final2_r","signal_final2_r",24,3.,99.);
    TH1F *signal_final3_repack = new TH1F("signal_final3_r","signal_final3_r",24,3.,99.);
    TH1F *eemc_bkgd2_repack = new TH1F("eemc_bkgd2_r","eemc_bkgd2_r",24,3.,99.);
    TH1F *new_bkgd_repack = new TH1F("new_bkgd_r","new_bkgd_r",24,3.,99.);
    TH1F *low_bkgd_repack = new TH1F("low_bkgd_r","low_bkgd_r",24,3.,99.);
    TH1F *high_bkgd_repack = new TH1F("high_bkgd_r","high_bkgd_r",24,3.,99.);
    TH1F *signal_in_norm_region_repack = new TH1F("signal_in_norm_region_r","signal_in_norm_region_r",24,3.,99.);

    TH1F *raw_stat_err2_repack = new TH1F("raw_stat_err2_r","raw_stat_err2_r",24,3.,99.);
    TH1F *QCD_stat_err2_repack = new TH1F("QCD_stat_err2_r","QCD_stat_err2_r",24,3.,99.);
    TH1F *eemc_stat_err2_repack = new TH1F("eemc_stat_err2_r","eemc_stat_err2_r",24,3.,99.);
    TH1F *tau_stat_err2_repack = new TH1F("tau_stat_err2_r","tau_stat_err2_r",24,3.,99.);
    TH1F *QCD_syst_high_err_repack = new TH1F("QCD_syst_high_err_r","QCD_syst_high_err_r",24,3.,99.);
    TH1F *QCD_syst_low_err_repack = new TH1F("QCD_syst_low_err_r","QCD_syst_low_err_r",24,3.,99.);
    TH1F *zsig_stat_err2_repack = new TH1F("zsig_stat_err2_r","zsig_stat_err2_r",24,3.,99.);
    TH1F *zback_stat_err2_repack = new TH1F("zback_stat_err2_r","zback_stat_err2_r",24,3.,99.);
    TH1F *zeemc_stat_err2_repack = new TH1F("zeemc_stat_err2_r","zeemc_stat_err2_r",24,3.,99.);

    for (int i=1; i<=24; i++) {
      tauhist_repack->SetBinContent(i,tauhist->GetBinContent(2*i)+
                                      tauhist->GetBinContent(2*i+1));
      zsig_bkgd2_repack->SetBinContent(i,zsig_bkgd2->GetBinContent(2*i)+
                                      zsig_bkgd2->GetBinContent(2*i+1));;
      signal2_repack->SetBinContent(i,signal2->GetBinContent(2*i)+
                                      signal2->GetBinContent(2*i+1));
      signal_final2_repack->SetBinContent(i,signal_final2->GetBinContent(2*i)+
                                            signal_final2->GetBinContent(2*i+1));
      signal_final3_repack->SetBinContent(i,signal_final3->GetBinContent(2*i)+
                                            signal_final3->GetBinContent(2*i+1));
      eemc_bkgd2_repack->SetBinContent(i,eemc_bkgd2->GetBinContent(2*i)+
                                         eemc_bkgd2->GetBinContent(2*i+1));
      new_bkgd_repack->SetBinContent(i,new_bkgd->GetBinContent(2*i)+
                                       new_bkgd->GetBinContent(2*i+1));
      low_bkgd_repack->SetBinContent(i,low_bkgd->GetBinContent(2*i)+
                                       low_bkgd->GetBinContent(2*i+1));
      high_bkgd_repack->SetBinContent(i,high_bkgd->GetBinContent(2*i)+
                                        high_bkgd->GetBinContent(2*i+1));
      signal_in_norm_region_repack->SetBinContent(i,signal_in_norm_region->GetBinContent(2*i)+signal_in_norm_region->GetBinContent(2*i+1));

      raw_stat_err2_repack->SetBinContent(i,raw_stat_err2->GetBinContent(2*i)+
                                            raw_stat_err2->GetBinContent(2*i+1));
      QCD_stat_err2_repack->SetBinContent(i,QCD_stat_err2->GetBinContent(2*i)+
                                          QCD_stat_err2->GetBinContent(2*i+1));
      eemc_stat_err2_repack->SetBinContent(i,eemc_stat_err2->GetBinContent(2*i)+
                                             eemc_stat_err2->GetBinContent(2*i+1));
      tau_stat_err2_repack->SetBinContent(i,tau_stat_err2->GetBinContent(2*i)+
                                            tau_stat_err2->GetBinContent(2*i+1));
      QCD_syst_high_err_repack->SetBinContent(i,QCD_syst_high_err->GetBinContent(2*i)+QCD_syst_high_err->GetBinContent(2*i+1));
      QCD_syst_low_err_repack->SetBinContent(i,QCD_syst_low_err->GetBinContent(2*i)+QCD_syst_low_err->GetBinContent(2*i+1));
      zsig_stat_err2_repack->SetBinContent(i,zsig_stat_err2->GetBinContent(2*i)+
                                             zback_stat_err2->GetBinContent(2*i+1));
      zback_stat_err2_repack->SetBinContent(i,zback_stat_err2->GetBinContent(2*i)+
                                             zback_stat_err2->GetBinContent(2*i+1));
      zeemc_stat_err2_repack->SetBinContent(i,zeemc_stat_err2->GetBinContent(2*i)+
                                             zeemc_stat_err2->GetBinContent(2*i+1));
    }

    tauhist_repack->Write();
    zsig_bkgd2_repack->Write();
    signal2_repack->Write();
    signal_final2_repack->Write();
    signal_final3_repack->Write();
    eemc_bkgd2_repack->Write();
    new_bkgd_repack->Write();
    low_bkgd_repack->Write();
    high_bkgd_repack->Write();
    signal_in_norm_region_repack->Write();

    raw_stat_err2_repack->Write();
    QCD_stat_err2_repack->Write();
    eemc_stat_err2_repack->Write();
    tau_stat_err2_repack->Write();
    QCD_syst_high_err_repack->Write();
    QCD_syst_low_err_repack->Write();
    zsig_stat_err2_repack->Write();
    zback_stat_err2_repack->Write();
    zeemc_stat_err2_repack->Write();

#if 0
    for (int i=1; i<=24; i++) {
      cout.setf(ios::fixed);
      cout.precision(2);
      cout << " " << signal2_repack->GetBinCenter(i) << " & " << signal2_repack->GetBinContent(i) << " & " << signal_final3_repack->GetBinContent(i) << " & " << QCD_stat_err2_repack->GetBinContent(i) << " & " << eemc_stat_err2_repack->GetBinContent(i) << " & " << tau_stat_err2_repack->GetBinContent(i) << " & " << zsig_stat_err2_repack->GetBinContent(i) << " & " << zback_stat_err2_repack->GetBinContent(i) << " & " << QCD_syst_high_err_repack->GetBinContent(i) << " & " << QCD_syst_low_err_repack->GetBinContent(i) << " \\\\" << endl;
    }
#endif

    f2->Close();

  }

  
} // end of macro
Example #28
0
int binfit_ttree_genlvl_atlas() {
  gROOT->Reset();
  gErrorIgnoreLevel=kError;
  float scaledps,scalesps,scalenlo,siggg,siggu,sigug;
  float datamass[81]={0};
  int dpsmass[81]={0};
  int spsmass[81]={0};
  float nlomass[81]={0.0};
  int nloggmass[81]={0};
  int nlogumass[81]={0};
  int nlougmass[81]={0};
  //  float datapt[60],datady[20],datay[20];
  TChain dps("Events");
  TChain nlogg("Events");
  TChain sps("Events");

//  dps.Add("Modified_Input_To_Fit_2012DPS_TMTight_3MuL3Match.root");
  dps.Add("genevents/GENEventTree_dps_pu_old_1.root");
  dps.Add("genevents/GENEventTree_dps_pu_old_2.root");
  dps.Add("genevents/GENEventTree_dps_pu_old_3.root");
  nlogg.Add("genevents/GENEventTree_pythia8_PU_OffsetBS_fixp3_1.root");
  nlogg.Add("genevents/GENEventTree_pythia8_PU_OffsetBS_fixp3_2.root");
  nlogg.Add("genevents/GENEventTree_pythia8_PU_OffsetBS_fixp3_3.root");
  nlogg.Add("genevents/GENEventTree_pythia8_PU_OffsetBS_fixp3_4.root");
  nlogg.Add("genevents/GENEventTree_pythia8_PU_OffsetBS_fixp3_5.root");
  nlogg.Add("genevents/GENEventTree_pythia8_PU_OffsetBS_fixp3_6_1.root ");
  nlogg.Add("genevents/GENEventTree_pythia8_PU_OffsetBS_fixp3_6_2.root ");
  sps.Add("genevents/GENEventTree_SPSLO_xl21_1.root");
  sps.Add("genevents/GENEventTree_SPSLO_xl21_2.root");
  sps.Add("genevents/GENEventTree_SPSLO_xl22_1.root");
  sps.Add("genevents/GENEventTree_SPSLO_xl22_2.root");
  sps.Add("genevents/GENEventTree_SPSLO_xl23_1.root");
  sps.Add("genevents/GENEventTree_SPSLO_xl23_2.root");
  sps.Add("genevents/GENEventTree_SPSLO_xl26_1.root");
  sps.Add("genevents/GENEventTree_SPSLO_xl26_2.root");
  sps.Add("genevents/GENEventTree_SPSLO_xl27_1.root");
  sps.Add("genevents/GENEventTree_SPSLO_xl27_2.root");
  sps.Add("genevents/GENEventTree_SPSLO_xl28_1.root");
  sps.Add("genevents/GENEventTree_SPSLO_xl28_2.root");
  

  float massbins[]={6.2,7,9,11,14,18,25,30,60};
  //float ptbins[]={0.,7,12,16,20,25,50,80};
  float ptbins[]={0.,2.5,5.,7.5,10.,12.5,15.,17.5,20.,22.5,25.,27.5,30.,35.,40.,45.,50.,55.,60.,65.,70.};
  float dybins[]={0.,0.2,0.4,0.6,0.9,1.3,1.8,2.4,4.5};
  //float ybins[]={-2.2,-1.8,-1.6,-1.4,-1.2,-1.0,-0.8,-0.6,-0.4,-0.2,0,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.2};
  float ybins[]={0.,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8};
  int nmbins = 8; 
  int nptbins = 20;
  int ndybins = 8;
  int nybins = 9;
  //float massbins[]={0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60};
  //float ptbins[]={0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80};
  //float dybins[]={0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.1,2.2,2.3,2.4,2.5,2.6,2.7,2.8,2.9,3.0,3.1,3.2,3.3,3.4,3.5,3.6,3.7,3.8,3.9,4.0,4.1,4.2,4.3,4.4,4.5};
  //float ybins[]={0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8};
  //  int nmbins = 30;
  //  int nptbins = 40;
  //  int ndybins = 45;
  //  int nybins = 18;
  //int nybins = 20;
    int mbinerr = -99;
    int ptbinerr = -99;
    int dybinerr = -99;
    int ybinerr = -99;
  TH1F *mass_data = new TH1F("mass_data","mass_data",nmbins,massbins); 
  TH1F *mass_dps = new TH1F("mass_dps","mass_dps",nmbins,massbins); 
  TH1F *mass_nlogg = new TH1F("mass_nlogg","mass_nlogg",nmbins,massbins); 
  TH1F *mass_nlo = new TH1F("mass_nlo","mass_nlo",nmbins,massbins); 
  TH1F *mass_sps = new TH1F("mass_sps","mass_sps",nmbins,massbins); 
  TH1F *mass_width = new TH1F("mass_width","mass_width",nmbins,massbins); 
  TH1F *pt_data = new TH1F("pt_data","pt_data",nptbins,ptbins); 
  TH1F *pt_dps = new TH1F("pt_dps","pt_dps",nptbins,ptbins); 
  TH1F *pt_nlogg = new TH1F("pt_nlogg","pt_nlogg",nptbins,ptbins); 
  TH1F *pt_nlo = new TH1F("pt_nlo","pt_nlo",nptbins,ptbins); 
  TH1F *pt_sps = new TH1F("pt_sps","pt_sps",nptbins,ptbins); 
  TH1F *pt_width = new TH1F("pt_width","pt_width",nptbins,ptbins); 
  TH1F *dy_data = new TH1F("dy_data","dy_data",ndybins,dybins); 
  TH1F *dy_dps = new TH1F("dy_dps","dy_dps",ndybins,dybins); 
  TH1F *dy_nlogg = new TH1F("dy_nlogg","dy_nlogg",ndybins,dybins); 
  TH1F *dy_nlo = new TH1F("dy_nlo","dy_nlo",ndybins,dybins); 
  TH1F *dy_sps = new TH1F("dy_sps","dy_sps",ndybins,dybins); 
  TH1F *dy_width = new TH1F("dy_width","dy_width",ndybins,dybins); 
  TH1F *y_data = new TH1F("y_data","y_data",nybins,ybins); 
  TH1F *y_dps = new TH1F("y_dps","y_dps",nybins,ybins); 
  TH1F *y_nlogg = new TH1F("y_nlogg","y_nlogg",nybins,ybins); 
  TH1F *y_nlo = new TH1F("y_nlo","y_nlo",nybins,ybins); 
  TH1F *y_sps = new TH1F("y_sps","y_sps",nybins,ybins); 
  TH1F *y_width = new TH1F("y_width","y_width",nybins,ybins); 

  mass_data->SetBinContent(1,47.43199);
  mass_data->SetBinContent(2,22.88957);
  mass_data->SetBinContent(3,10.52912);
  mass_data->SetBinContent(4,7.297879);
  mass_data->SetBinContent(5,4.679995);
  mass_data->SetBinContent(6,2.752399);
  mass_data->SetBinContent(7,2.321633);
  mass_data->SetBinContent(8,0.4013286);
  mass_data->SetBinError(1,6.281534);
  mass_data->SetBinError(2,2.358319);
  mass_data->SetBinError(3,1.509835);
  mass_data->SetBinError(4,1.177612);
  mass_data->SetBinError(5,0.7126356);
  mass_data->SetBinError(6,0.3761612);
  mass_data->SetBinError(7,0.3408355);
  mass_data->SetBinError(8,0.05351048);


  pt_data->SetBinContent(1, 1.5 );
  pt_data->SetBinContent(2, 1.75);
  pt_data->SetBinContent(3, 1.85);
  pt_data->SetBinContent(4, 1.5);
  pt_data->SetBinContent(5, 0.35);
  pt_data->SetBinContent(6,0.61);
  pt_data->SetBinContent(7, 1.7);
  pt_data->SetBinContent(8, 2.05);
  pt_data->SetBinContent(9, 2.95);
  pt_data->SetBinContent(10,3.6);
  pt_data->SetBinContent(11,2.5);
  pt_data->SetBinContent(12,2.1);
  pt_data->SetBinContent(13,1.5);
  pt_data->SetBinContent(14,0.95);
  pt_data->SetBinContent(15,0.23);
  pt_data->SetBinContent(16,0.13);
  pt_data->SetBinContent(17,0.15);
  pt_data->SetBinContent(18,0.14);
  pt_data->SetBinContent(19,0.04);
  pt_data->SetBinContent(20,0.025);
  pt_data->SetBinError(1,0.25);
  pt_data->SetBinError(2, 0.25);
  pt_data->SetBinError(3,0.25);
  pt_data->SetBinError(4,0.25);
  pt_data->SetBinError(5,0.15);
  pt_data->SetBinError(6,0.15);
  pt_data->SetBinError(7,0.25);
  pt_data->SetBinError(8,0.25);
  pt_data->SetBinError(9,0.25);
  pt_data->SetBinError(10, 0.1);
  pt_data->SetBinError(11, 0.1);
  pt_data->SetBinError(12, 0.25);
  pt_data->SetBinError(13, 0.1);
  pt_data->SetBinError(14, 0.25);
  pt_data->SetBinError(15, 0.07);
  pt_data->SetBinError(16, 0.07);
  pt_data->SetBinError(17, 0.07);
  pt_data->SetBinError(18, 0.07);
  pt_data->SetBinError(19, 0.06);
  pt_data->SetBinError(20, 0.025);


  dy_data->SetBinContent(1,353.6836);
  dy_data->SetBinContent(2,208.9763);
  dy_data->SetBinContent(3,100.067);
  dy_data->SetBinContent(4,59.72152);
  dy_data->SetBinContent(5,39.28412);
  dy_data->SetBinContent(6,23.76292);
  dy_data->SetBinContent(7,22.76975);
  dy_data->SetBinContent(8,10.52381);
  dy_data->SetBinError(1,28.61261);
  dy_data->SetBinError(2,21.71715);
  dy_data->SetBinError(3,14.11659);
  dy_data->SetBinError(4,10.30196);
  dy_data->SetBinError(5,6.846661);
  dy_data->SetBinError(6,5.372485);
  dy_data->SetBinError(7,4.64503);
  dy_data->SetBinError(8,2.287784);
  y_data->SetBinContent(1,96.87107);
  y_data->SetBinContent(2,110.5371);
  y_data->SetBinContent(3,89.27422);
  y_data->SetBinContent(4,101.8527);
  y_data->SetBinContent(5,77.61348);
  y_data->SetBinContent(6,95.7653);
  y_data->SetBinContent(7,137.6607);
  y_data->SetBinContent(8,168.4277);
  y_data->SetBinContent(9,120.5354);
  y_data->SetBinError(1,14.97098);
  y_data->SetBinError(2,15.67618);
  y_data->SetBinError(3,12.3992);
  y_data->SetBinError(4,13.63791);
  y_data->SetBinError(5,10.98304);
  y_data->SetBinError(6,14.26707);
  y_data->SetBinError(7,17.44995);
  y_data->SetBinError(8,23.01054);
  y_data->SetBinError(9,22.7678);

  mass_width->SetBinContent(1,0.8);
  mass_width->SetBinContent(2,2.);
  mass_width->SetBinContent(3,2.);
  mass_width->SetBinContent(4,3.);
  mass_width->SetBinContent(5,4.);
  mass_width->SetBinContent(6,5.);
  mass_width->SetBinContent(7,5.);
  mass_width->SetBinContent(8,30.);


  pt_width->SetBinContent(1,2.5);
  pt_width->SetBinContent(2,2.5);
  pt_width->SetBinContent(3,2.5);
  pt_width->SetBinContent(4,2.5);
  pt_width->SetBinContent(5,2.5);
  pt_width->SetBinContent(6,2.5);
  pt_width->SetBinContent(7,2.5);
  pt_width->SetBinContent(8,2.5);
  pt_width->SetBinContent(9,2.5);
  pt_width->SetBinContent(10,2.5);
  pt_width->SetBinContent(11,2.5);
  pt_width->SetBinContent(12,2.5);
  pt_width->SetBinContent(13,5);
  pt_width->SetBinContent(14,5);
  pt_width->SetBinContent(15,5);
  pt_width->SetBinContent(16,5);
  pt_width->SetBinContent(17,5);
  pt_width->SetBinContent(18,5);
  pt_width->SetBinContent(19,5);
  pt_width->SetBinContent(20,5);


  dy_width->SetBinContent(1,0.2);
  dy_width->SetBinContent(2,0.2);
  dy_width->SetBinContent(3,0.2);
  dy_width->SetBinContent(4,0.3);
  dy_width->SetBinContent(5,0.4);
  dy_width->SetBinContent(6,0.5);
  dy_width->SetBinContent(7,0.6);
  dy_width->SetBinContent(8,2.1);
  y_width->SetBinContent(1,0.2);
  y_width->SetBinContent(2,0.2);
  y_width->SetBinContent(3,0.2);
  y_width->SetBinContent(4,0.2);
  y_width->SetBinContent(5,0.2);
  y_width->SetBinContent(6,0.2);
  y_width->SetBinContent(7,0.2);
  y_width->SetBinContent(8,0.2);
  y_width->SetBinContent(9,0.2);

  dps.Draw("FourMu_pT >> pt_dps","Sum$(Psi_pT>8.5&&abs(Psi_y)<2.1&&Psi_Mass[]<3.35&&Psi_Mass>2.85)==2","goff");
  nlogg.Draw("FourMu_pT >> pt_nlogg","Sum$(Psi_pT>8.5&&abs(Psi_y)<2.1&&Psi_Mass[]<3.35&&Psi_Mass>2.85)==2","goff");
  sps.Draw("FourMu_pT >> pt_sps","Sum$(Psi_pT>8.5&&abs(Psi_y)<2.1&&Psi_Mass[]<3.35&&Psi_Mass>2.85)==2","goff");
  pt_dps->Divide(pt_width);
  pt_nlogg->Divide(pt_width);
  pt_sps->Divide(pt_width);
  datamass[0]=pt_data->Integral("width");
  std::cout<<datamass[0]<<std::endl;
  dpsmass[0]=pt_dps->Integral("width");
  spsmass[0]=pt_sps->Integral("width");
  nloggmass[0]=pt_nlogg->Integral("width");
  nlomass[0]=nloggmass[0];

  scaledps = datamass[0]/ (float) dpsmass[0];
  scalesps= datamass[0]/ (float) spsmass[0];
  scalenlo= datamass[0]/ (float) nloggmass[0];
  float Chi2=0;
  float minchi2norm=99999999.9;
  float minchi2=9999999.9;
  float mina, minb, minc, minan, minbn, mincn;

  //   Chi2 = Chi2 + pow((datamass[1] - (0.00*scaledps*dpsmass[1] + 0.0*scalesps*spsmass[1] + 0.0*scalenlo*nlomass[1])),2)/sqrt(datamass[1]);
  //  std::cout<<"Scale: " <<datamass[0]<<" " << dpsmass[0]<<" "<<scaledps<<" "<<scalesps<<" "<<scalenlo<<" "<<std::endl;
  for(float a=0.0; a<1.0; a=a+0.01){
        dps.Draw("FourMu_Mass >> mass_dps","Sum$(Psi_pT>8.5&&abs(Psi_y)<2.1&&Psi_Mass[]<3.35&&Psi_Mass>2.85)==2","goff");
        nlogg.Draw("FourMu_Mass >> mass_nlogg","Sum$(Psi_pT>8.5&&abs(Psi_y)<2.1&&Psi_Mass[]<3.35&&Psi_Mass>2.85)==2","goff");
        sps.Draw("FourMu_Mass >> mass_sps","Sum$(Psi_pT>8.5&&abs(Psi_y)<2.1&&Psi_Mass[]<3.35&&Psi_Mass>2.85)==2","goff");
        dps.Draw("FourMu_pT >> pt_dps","Sum$(Psi_pT>8.5&&abs(Psi_y)<2.1&&Psi_Mass[]<3.35&&Psi_Mass>2.85)==2","goff");
        nlogg.Draw("FourMu_pT >> pt_nlogg","Sum$(Psi_pT>8.5&&abs(Psi_y)<2.1&&Psi_Mass[]<3.35&&Psi_Mass>2.85)==2","goff");
        sps.Draw("FourMu_pT >> pt_sps","Sum$(Psi_pT>8.5&&abs(Psi_y)<2.1&&Psi_Mass[]<3.35&&Psi_Mass>2.85)==2","goff");
        dps.Draw("Psi1To2_dY >> dy_dps","Sum$(Psi_pT>8.5&&abs(Psi_y)<2.1&&Psi_Mass[]<3.35&&Psi_Mass>2.85)==2","goff");
        nlogg.Draw("Psi1To2_dY >> dy_nlogg","Sum$(Psi_pT>8.5&&abs(Psi_y)<2.1&&Psi_Mass[]<3.35&&Psi_Mass>2.85)==2","goff");
        sps.Draw("Psi1To2_dY >> dy_sps","Sum$(Psi_pT>8.5&&abs(Psi_y)<2.1&&Psi_Mass[]<3.35&&Psi_Mass>2.85)==2","goff");
        dps.Draw("abs(FourMu_Rapidity)>> y_dps","Sum$(Psi_pT>8.5&&abs(Psi_y)<2.1&&Psi_Mass[]<3.35&&Psi_Mass>2.85)==2","goff");
        nlogg.Draw("abs(FourMu_Rapidity) >> y_nlogg","Sum$(Psi_pT>8.5&&abs(Psi_y)<2.1&&Psi_Mass[]<3.35&&Psi_Mass>2.85)==2","goff");
        sps.Draw("abs(FourMu_Rapidity) >> y_sps","Sum$(Psi_pT>8.5&&abs(Psi_y)<2.1&&Psi_Mass[]<3.35&&Psi_Mass>2.85)==2","goff");
  mass_dps->Divide(mass_width);
  mass_nlogg->Divide(mass_width);
  mass_sps->Divide(mass_width);
  pt_dps->Divide(pt_width);
  pt_nlogg->Divide(pt_width);
  pt_sps->Divide(pt_width);
  dy_dps->Divide(dy_width);
  dy_nlogg->Divide(dy_width);
  dy_sps->Divide(dy_width);
  y_dps->Divide(y_width);
  y_nlogg->Divide(y_width);
  y_sps->Divide(y_width);
//        for(int mbin=1; mbin<=nmbins; ++mbin){
//          if (mass_data->GetBinContent(mbin) == 0){
//            //mbinerr = 1.;
//            continue;
//          }
//          //else{mbinerr = sqrt(abs(mass_data->GetBinContent(mbin)));}
//          //Chi2=Chi2 + pow((mass_data->GetBinContent(mbin) - (a*scaledps*mass_dps->GetBinContent(mbin) + b*scalesps*mass_sps->GetBinContent(mbin) + c*scalenlo*mass_nlogg->GetBinContent(mbin))),2)/mbinerr;
////          Chi2=Chi2 + pow((mass_data->GetBinContent(mbin) - (a*scaledps*mass_dps->GetBinContent(mbin) + b*scalesps*mass_sps->GetBinContent(mbin) + c*scalenlo*mass_nlogg->GetBinContent(mbin)))/sqrt(abs(mass_data->GetBinContent(mbin))),2);
//          //           std::cout<<Chi2<<std::endl;
//        }
        for(int ptbin=1; ptbin<=nptbins; ++ptbin){
          Chi2=Chi2 + pow((pt_data->GetBinContent(ptbin) - (a*scaledps*pt_dps->GetBinContent(ptbin) + (1.-a)*scalenlo*pt_nlogg->GetBinContent(ptbin)))/pt_data->GetBinError(ptbin),2);
            //         std::cout<<pt_data->GetBinContent(ptbin)<<std::endl;
        }
//        for(int dybin=1; dybin<=ndybins; ++dybin){
//          if (dy_data->GetBinContent(dybin) == 0){
//            dybinerr = 1.;
//          }
//          else{dybinerr = dy_data->GetBinError(dybin);}
////          Chi2=Chi2 + pow((dy_data->GetBinContent(dybin) - (a*scaledps*dy_dps->GetBinContent(dybin) + b*scalesps*dy_sps->GetBinContent(dybin) + c*scalenlo*dy_nlogg->GetBinContent(dybin)))/dybinerr,2);
//          //           std::cout<<Chi2<<std::endl;
//        }
//        for(int ybin=1; ybin<=nybins; ++ybin){
//          Chi2=Chi2 + pow((y_data->GetBinContent(ybin) - (a*scaledps*y_dps->GetBinContent(ybin) + (1.-a)*scalenlo*y_nlogg->GetBinContent(ybin)))/y_data->GetBinError(ybin),2);
//          //           std::cout<<Chi2<<std::endl;
//        }
        //        std::cout<<"a, b, c: "<<a<<" "<<b<<" "<<c<<" Chi2: "<<Chi2<<std::endl;
        std::cout<<a<<" "<<Chi2<<std::endl;
        if (Chi2<=minchi2){
          minchi2=Chi2; minan = a; minbn = 0.; mincn=(1.-a); 
        }
        //        std::cout<<a<<" "<<b<<" "<<c<<" "<<Chi2<<std::endl;
        Chi2=0;
    }
    std::cout<<"Min Chi2: "<<minchi2<<" dps, sps, nlo: "<<minan<<" "<<minbn<<" "<<mincn<<std::endl;
    TCanvas* disp = new TCanvas("disp","disp",900,900);
    disp->Divide(2,2);
    TH1F *MassSum = new TH1F("MassSum","MassSum",nmbins,massbins);
    TH1F *MassBest = new TH1F("MassBest","MassBest",nmbins,massbins);
    TH1F *DpsBestM = new TH1F("DpsBestM","DpsBestM",nmbins,massbins);
    TH1F *SpsBestM = new TH1F("SpsBestM","SpsBestM",nmbins,massbins);
    TH1F *NloBestM = new TH1F("NloBestM","NloBestM",nmbins,massbins);
    TH1F *pTBest = new TH1F("pTBest","pTBest",nptbins,ptbins);
    TH1F *pTSum = new TH1F("pTSum","pTSum",nptbins,ptbins);
    TH1F *DpsBestpt = new TH1F("DpsBestpt","DpsBestpt",nptbins,ptbins);
    TH1F *NloBestpt = new TH1F("NloBestpt","NloBestpt",nptbins,ptbins);
    TH1F *SpsBestpt = new TH1F("SpsBestpt","SpsBestpt",nptbins,ptbins);
    TH1F *dyBest = new TH1F("dyBest","dyBest",ndybins,dybins);
    TH1F *dySum = new TH1F("dySum","dySum",ndybins,dybins);
    TH1F *DpsBestdy = new TH1F("DpsBestdy","DpsBestdy",ndybins,dybins);
    TH1F *NloBestdy = new TH1F("NloBestdy","NloBestdy",ndybins,dybins);
    TH1F *SpsBestdy = new TH1F("SpsBestdy","SpsBestdy",ndybins,dybins);
    TH1F *yBest = new TH1F("yBest","yBest",nybins,ybins);
    TH1F *ySum = new TH1F("ySum","ySum",nybins,ybins);
    TH1F *DpsBesty = new TH1F("DpsBesty","DpsBesty",nybins,ybins);
    TH1F *NloBesty = new TH1F("NloBesty","NloBesty",nybins,ybins);
    TH1F *SpsBesty = new TH1F("SpsBesty","SpsBesty",nybins,ybins);
    MassBest->SetMinimum(0);pTBest->SetMinimum(0);dyBest->SetMinimum(0);yBest->SetMinimum(0);
    mass_data->SetMinimum(0);pt_data->SetMinimum(0);dy_data->SetMinimum(0);y_data->SetMinimum(0);
    dps.Draw("FourMu_Mass>>DpsBestM","Sum$(Psi_pT>8.5&&abs(Psi_y)<2.1&&Psi_Mass[]<3.35&&Psi_Mass>2.85)==2","goff");
    nlogg.Draw("FourMu_Mass>>NloBestM","Sum$(Psi_pT>8.5&&abs(Psi_y)<2.1&&Psi_Mass[]<3.35&&Psi_Mass>2.85)==2","goff");
    sps.Draw("FourMu_Mass>>SpsBestM","Sum$(Psi_pT>8.5&&abs(Psi_y)<2.1&&Psi_Mass[]<3.35&&Psi_Mass>2.85)==2","goff");
    dps.Draw("FourMu_pT>>DpsBestpt","Sum$(Psi_pT>8.5&&abs(Psi_y)<2.1&&Psi_Mass[]<3.35&&Psi_Mass>2.85)==2","goff");
    nlogg.Draw("FourMu_pT>>NloBestpt","Sum$(Psi_pT>8.5&&abs(Psi_y)<2.1&&Psi_Mass[]<3.35&&Psi_Mass>2.85)==2","goff");
    sps.Draw("FourMu_pT>>SpsBestpt","Sum$(Psi_pT>8.5&&abs(Psi_y)<2.1&&Psi_Mass[]<3.35&&Psi_Mass>2.85)==2","goff");
    dps.Draw("Psi1To2_dY>>DpsBestdy","Sum$(Psi_pT>8.5&&abs(Psi_y)<2.1&&Psi_Mass[]<3.35&&Psi_Mass>2.85)==2","goff");
    nlogg.Draw("Psi1To2_dY>>NloBestdy","Sum$(Psi_pT>8.5&&abs(Psi_y)<2.1&&Psi_Mass[]<3.35&&Psi_Mass>2.85)==2","goff");
    sps.Draw("Psi1To2_dY>>SpsBestdy","Sum$(Psi_pT>8.5&&abs(Psi_y)<2.1&&Psi_Mass[]<3.35&&Psi_Mass>2.85)==2","goff");
    dps.Draw("abs(FourMu_Rapidity)>>DpsBesty","Sum$(Psi_pT>8.5&&abs(Psi_y)<2.1&&Psi_Mass[]<3.35&&Psi_Mass>2.85)==2","goff");
    nlogg.Draw("abs(FourMu_Rapidity)>>NloBesty","Sum$(Psi_pT>8.5&&abs(Psi_y)<2.1&&Psi_Mass[]<3.35&&Psi_Mass>2.85)==2","goff");
    sps.Draw("abs(FourMu_Rapidity)>>SpsBesty","Sum$(Psi_pT>8.5&&abs(Psi_y)<2.1&&Psi_Mass[]<3.35&&Psi_Mass>2.85)==2","goff");
  DpsBestM->Divide(mass_width);
  NloBestM->Divide(mass_width);
  SpsBestM->Divide(mass_width);
  DpsBestpt->Divide(pt_width);
  NloBestpt->Divide(pt_width);
  SpsBestpt->Divide(pt_width);
  DpsBestdy->Divide(dy_width);
  NloBestdy->Divide(dy_width);
  SpsBestdy->Divide(dy_width);
  DpsBesty->Divide(y_width);
  NloBesty->Divide(y_width);
  SpsBesty->Divide(y_width);
    //MassSum->Add(DpsBest,(float) mina);
    //MassSum->Add(SpsBest,minb);
    //MassSum->Add(NloBest,minc);
    mass_data->SetMinimum(0);
    mass_data->SetXTitle("Four Mu Mass (GeV)");
    pt_data->SetXTitle("Four Mu pT (GeV)");
    dy_data->SetXTitle("|#Delta Y| between J/#psi");
    y_data->SetXTitle("Four Mu Rapidity |Y|");
    mass_data->SetTitle("");
    pt_data->SetTitle("");
    dy_data->SetTitle("");
    y_data->SetTitle("");
    disp->cd(1);
    DpsBestM->SetLineColor(kRed);
    NloBestM->SetLineColor(kGreen);
    SpsBestM->SetLineColor(kBlue);
    DpsBestM->Scale(minan*scaledps);
    NloBestM->Scale(mincn*scalenlo);
    SpsBestM->Scale(minbn*scalesps);
    MassSum->Add(DpsBestM);
    MassSum->Add(NloBestM);
    MassSum->Add(SpsBestM);
    mass_data->Draw("E1");
    MassSum->Draw("same");
    DpsBestM->Draw("same");
    NloBestM->Draw("same");
    SpsBestM->Draw("same");
    TLegend *leg = new TLegend(0.6,0.7,0.90,0.9);
    leg->SetFillStyle(0);
    leg->SetBorderSize(0);
    leg->SetShadowColor(0);
    leg->AddEntry(DpsBestM,"DPS model","l");
    leg->AddEntry(NloBestM,"SPS NLO model","l");
    leg->AddEntry(MassSum,"MC model sum","l");
    leg->AddEntry(MassBest,"Data","lep");
    leg->Draw();
    disp->cd(2);
    DpsBestpt->SetLineColor(kRed);
    NloBestpt->SetLineColor(kGreen);
    SpsBestpt->SetLineColor(kBlue);
    DpsBestpt->Scale(minan*scaledps);
    NloBestpt->Scale(mincn*scalenlo);
    SpsBestpt->Scale(minbn*scalesps);
    pTSum->Add(DpsBestpt);
    pTSum->Add(NloBestpt);
    pTSum->Add(SpsBestpt);
    pt_data->Draw("e1");
    pTSum->Draw("same");
    DpsBestpt->Draw("same");
    NloBestpt->Draw("same");
    SpsBestpt->Draw("same");
    leg->Draw();
    disp->cd(3);
    DpsBestdy->SetLineColor(kRed);
    NloBestdy->SetLineColor(kGreen);
    SpsBestdy->SetLineColor(kBlue);
    DpsBestdy->Scale(minan*scaledps);
    NloBestdy->Scale(mincn*scalenlo);
    SpsBestdy->Scale(minbn*scalesps);
    dySum->Add(DpsBestdy);
    dySum->Add(NloBestdy);
    dySum->Add(SpsBestdy);
    dy_data->Draw("e1");
    dySum->Draw("same");
    DpsBestdy->Draw("same");
    NloBestdy->Draw("same");
    SpsBestdy->Draw("same");
    leg->Draw();
    disp->cd(4);
    DpsBesty->SetLineColor(kRed);
    NloBesty->SetLineColor(kGreen);
    SpsBesty->SetLineColor(kBlue);
    DpsBesty->Scale(minan*scaledps);
    NloBesty->Scale(mincn*scalenlo);
    SpsBesty->Scale(minbn*scalesps);
    ySum->Add(DpsBesty);
    ySum->Add(NloBesty);
    ySum->Add(SpsBesty);
    y_data->Draw("e1");
    ySum->Draw("same");
    DpsBesty->Draw("same");
    NloBesty->Draw("same");
    SpsBesty->Draw("same");
    leg->Draw();
  }
Example #29
0
void plotDimensionComparison(string file1, string file2){
  gROOT->Reset();
  gROOT->SetStyle("Plain");
  gStyle->SetOptStat(0);
  gROOT->ForceStyle();
  gStyle->SetPadGridY(1); 
  gStyle->SetPadGridX(1); 

  stringstream name; 
  int bias = 150; 


  if (DEBUG) cout << __LINE__ << endl;
  
  TFile *_file0 = TFile::Open(file1.c_str());
  TFile *_file1 = TFile::Open(file2.c_str());
  TCanvas * c = new TCanvas(); 
  c->Draw(); 
  c->SetLogy(1);
  if (DEBUG) cout << __LINE__ << endl;
  for (int ilayer=1; ilayer < 4; ilayer++){
    for (int imodule =1; imodule<9; imodule++){
      if (DEBUG) cout << __LINE__ << endl;
      name.str("");
      name << "clusterSize_layer" << ilayer<<"_module"<< imodule << "_bias150"; 
      cout << __LINE__ << " " << name.str().c_str()<< endl;
      TH1F * h = (TH1F *) _file0->Get(name.str().c_str());
      TH1F * h1 = (TH1F *) _file1->Get(name.str().c_str());
      if (DEBUG) cout << __LINE__ << endl;
      c->cd(); 
      h->Sumw2();
      h1->Sumw2();
      h->Scale(1./h->Integral());
      h1->Scale(1./h1->Integral());
      h->Draw("E");
      h->GetXaxis()->SetRangeUser(0,50);
      h->Draw("EP");
      h->SetMarkerStyle(20);
      h->Draw("EP");
      h1->SetMarkerStyle(20);
      h->Draw("EPSAME");
      h1->Draw("EPSAME");
      h1->SetMarkerColor(2);
      h1->Draw("EPSAME");

      name << "comparison.png";
      c->SaveAs(name.str().c_str());
      h->~TH1F();
      h1->~TH1F(); 

      name.str("");
      name << "clusterSizeX_layer" << ilayer<<"_module"<< imodule << "_bias150"; 
      cout << __LINE__ << " " << name.str().c_str()<< endl;
      TH1F * hx = (TH1F *) _file0->Get(name.str().c_str());
      TH1F * hx1 = (TH1F *) _file1->Get(name.str().c_str());
      if (DEBUG) cout << __LINE__ << endl;
      c->cd(); 
      hx->Sumw2();
      hx1->Sumw2();
      hx->Scale(1./hx->Integral());
      hx1->Scale(1./hx1->Integral());
      hx->Draw("E");
      hx->GetXaxis()->SetRangeUser(0,50);
      hx->Draw("EP");
      hx->SetMarkerStyle(20);
      hx->Draw("EP");
      hx1->SetMarkerStyle(20);
      hx->Draw("EPSAME");
      hx1->Draw("EPSAME");
      hx1->SetMarkerColor(2);
      hx1->Draw("EPSAME");

      name << "comparison.png";
      c->SaveAs(name.str().c_str());
      hx->~TH1F();
      hx1->~TH1F(); 

      name.str("");
      name << "clusterSizeY_layer" << ilayer<<"_module"<< imodule << "_bias150"; 
      cout << __LINE__ << " " << name.str().c_str()<< endl;
      TH1F * hy = (TH1F *) _file0->Get(name.str().c_str());
      TH1F * hy1 = (TH1F *) _file1->Get(name.str().c_str());
      if (DEBUG) cout << __LINE__ << endl;
      c->cd(); 
      hy->Sumw2();
      hy1->Sumw2();
      hy->Scale(1./hy->Integral());
      hy1->Scale(1./hy1->Integral());
      hy->Draw("E");
      hy->GetXaxis()->SetRangeUser(0,50);
      hy->Draw("EP");
      hy->SetMarkerStyle(20);
      hy->Draw("EP");
      hy1->SetMarkerStyle(20);
      hy->Draw("EPSAME");
      hy1->Draw("EPSAME");
      hy1->SetMarkerColor(2);
      hy1->Draw("EPSAME");

      name << "comparison.png";
      c->SaveAs(name.str().c_str());
      hy->~TH1F();
      hy1->~TH1F(); 

    }//imodule
  }//ilayer

}
void src_fit(){

  int CRunNumber=20591;
  int endCRunNumber=22461;
  int HeRunNumber=20596;
  int endHeRunNumber=20598;
//  int endHeRunNumber=22488;

  TString Q2 = "1.0";
  TString vartodraw = "PriKineR.Q2 / (PriKineR.nu * 2 * 0.9315)";
//Range is of the form (bins, start, end)
//  TString range = "(800,0.5,4.0)";
  double bins = 50;
  double plotmin = 0.5;
  double plotmax = 2.0;
  TString title = "12C/3He x with Target cut, Run # ";
  title += CRunNumber;
  title += " & ";
  title += HeRunNumber;

	TCut cut = "";  
	TCut kinematics = "PriKineR.Q2<10 && GoodElectron==1 && PriKineR.nu<10";
//	TCut eventtype = "D.evtypebits&(1<<1)>0";
	TCut eventtype = "(D.evtypebits&2)==2";
	TCut gold = "R.gold.dp>-0.04 && R.gold.dp<0.055";
	TCut target = "ReactPt_R.z>-0.172 && ReactPt_R.z<0.175";
	TCut sieve = "abs(R_sv_y)<0.03 && abs(R_sv_x)<0.06";

//	TCut cut = "";
//	TCut eventtype = "";
//	TCut target = "";
//	TCut sieve = "";
//	TCut gold = "";

  TCut cuts = kinematics && target && sieve && gold && eventtype;

  TString whattodraw = vartodraw;
//  whattodraw += ">>";
//  whattodraw += title;
//  whattodraw += range;
  TString whattodrawC = whattodraw;
  whattodrawC += ">>histC";
  TString whattodrawHe = whattodraw;
  whattodrawHe += ">>histHe";
  TChain* chainC = new TChain("T");
  TChain* chainHe = new TChain("T");

  gStyle->SetErrorX(.25);
  gStyle->SetEndErrorSize(.25);
  ifstream inp;
  ofstream out;

  TString filenameC;
  TString filenameHe;


// Below is the loop for adding chains for the Carbon run
  for (int thisCRunNumber=CRunNumber; thisCRunNumber<(endCRunNumber+1); thisCRunNumber++)
  {
 		if(thisCRunNumber==20592){thisCRunNumber=20731;}
		if(thisCRunNumber==20735){thisCRunNumber=20762;}
		if(thisCRunNumber==20765){thisCRunNumber=22380;}
		if(thisCRunNumber==22381){thisCRunNumber=22389;}
		if(thisCRunNumber==22390){thisCRunNumber=22425;}
		if(thisCRunNumber==22427){thisCRunNumber=22461;}
		if(thisCRunNumber==22462){thisCRunNumber=99999;}

   for (int t=0; t<1000;t++)
    {
      filenameC = "/home/ellie/physics/e05-102/terabyte/ROOTfiles/e05102_R_";
      filenameC += thisCRunNumber;
      if (t!=0)
      {
        filenameC += "_";
        filenameC += t;
      }
      filenameC += ".root";
      ifstream ifileC(filenameC);
      if (ifileC)
      {
        cout << "Adding file to chainC: " << filenameC << endl;
        chainC->Add(filenameC);
      }
      else
      {
        cout << "File " << filenameC << " does not exist. Ending here." << endl;
        t=9999999;
      }

    }
	
// Uncommenting the line below will let the code only go through one run (Good for debugging purposes)
//	thisCRunNumber = 99999999;

  }




// Below is the loop for adding chains for the 3He run

  for (int thisHeRunNumber=HeRunNumber;thisHeRunNumber<(endHeRunNumber+1); thisHeRunNumber++)
  {
	// Skipping Vertical Carbon Runs
	if(thisHeRunNumber==20591){thisHeRunNumber=20596;}
	if(thisHeRunNumber==20731){thisHeRunNumber=20738;}
	if(thisHeRunNumber==20732){thisHeRunNumber=20738;}
	if(thisHeRunNumber==20733){thisHeRunNumber=20738;}
	if(thisHeRunNumber==20734){thisHeRunNumber=20738;}
	if(thisHeRunNumber==20736){thisHeRunNumber=20738;}
	if(thisHeRunNumber==20737){thisHeRunNumber=20738;}
	if(thisHeRunNumber==20762){thisHeRunNumber=20789;}
	if(thisHeRunNumber==20763){thisHeRunNumber=20789;}
	if(thisHeRunNumber==20764){thisHeRunNumber=20789;}
	if(thisHeRunNumber==20791){thisHeRunNumber=20814;}
	if(thisHeRunNumber==20792){thisHeRunNumber=20814;}

	// Skipping Longitudinal Carbon Runs
	if(thisHeRunNumber==22380){thisHeRunNumber=22393;}
	if(thisHeRunNumber==22389){thisHeRunNumber=22393;}
	if(thisHeRunNumber==22425){thisHeRunNumber=22436;}
	if(thisHeRunNumber==22426){thisHeRunNumber=22436;}

	// Skipping Transverse Carbon Runs
	if(thisHeRunNumber==22461){thisHeRunNumber=22465;}
	if(thisHeRunNumber==20591){thisHeRunNumber=20596;}

   if(thisHeRunNumber==22397){thisHeRunNumber=22398;}
    for (int t=0; t<1000;t++)
    {
      filenameHe = "/home/ellie/physics/e05-102/terabyte/ROOTfiles/e05102_R_";
      filenameHe += thisHeRunNumber;
      if (t!=0)
      {
        filenameHe += "_";
        filenameHe += t;
      }
      filenameHe += ".root";
      ifstream ifileHe(filenameHe);
      if (ifileHe)
      {
        cout << "Adding file to chainHe: " << filenameHe << endl;
        chainHe->Add(filenameHe);
      }
      else
      {
        cout << "File " << filenameHe << " does not exist. Ending here." << endl;
        t=9999999;
      }

    }

// Uncommenting the line below will let the code only go through one run (Good for debugging purposes)
//	thisHeRunNumber = 999999999;

  }


	
	gStyle->SetPalette(1);
	gStyle->SetOptFit(0001);

	// Defines Canvas
	TCanvas *c1 = new TCanvas("c1","x of 12C and 3He",1360,800);//x,y
	pad01 = new TPad("pad01","pad01",0.0000,0.8333,0.2000,1.0000,0,0,0);
	pad02 = new TPad("pad02","pad02",0.2000,0.8333,0.4000,1.0000,0,0,0);
	pad03 = new TPad("pad03","pad03",0.4000,0.8333,0.6000,1.0000,0,0,0);
	pad04 = new TPad("pad04","pad04",0.6000,0.8333,0.8000,1.0000,0,0,0);
	pad05 = new TPad("pad05","pad05",0.0000,0.6666,0.2000,0.8333,0,0,0);
	pad06 = new TPad("pad06","pad06",0.2000,0.6666,0.4000,0.8333,0,0,0);
	pad07 = new TPad("pad07","pad07",0.4000,0.6666,0.6000,0.8333,0,0,0);
	pad08 = new TPad("pad08","pad08",0.6000,0.6666,0.8000,0.8333,0,0,0);
	pad09 = new TPad("pad09","pad09",0.0000,0.3333,0.3333,0.6666,0,0,0);
	pad10 = new TPad("pad10","pad10",0.3333,0.3333,0.6666,0.6666,0,0,0);
	pad11 = new TPad("pad11","pad11",0.6666,0.3333,1.0000,0.6666,0,0,0);
	pad12 = new TPad("pad12","pad12",0.0000,0.0000,0.3333,0.3333,0,0,0);
	pad13 = new TPad("pad13","pad13",0.3333,0.0000,0.6666,0.3333,0,0,0);
	pad14 = new TPad("pad14","pad14",0.6666,0.0000,1.0000,0.3333,0,0,0);
	pad15 = new TPad("pad15","pad15",0.8000,0.8333,1.0000,1.0000,0,0,0);
	pad16 = new TPad("pad16","pad16",0.8000,0.6666,1.0000,0.8333,0,0,0);
	pad01->Draw();pad02->Draw();pad03->Draw();pad04->Draw();pad05->Draw();pad06->Draw();pad07->Draw();pad08->Draw();pad09->Draw();pad10->Draw();pad11->Draw();pad12->Draw();pad13->Draw();pad14->Draw();pad15->Draw();pad16->Draw();

	// Everything below here makes graphs for each section of the canvas

	pad01->cd();
	TString titledpHe = "dp Cut from 3He Runs";
	cout << "Drawing " << titledpHe << "..." << endl;
	chainHe->Draw("R.gold.dp>>HedpNoCut(400,-0.08,0.08)", "", "");
	chainHe->Draw("R.gold.dp>>HedpCut(400,-0.08,0.08)", gold, "");
	HedpNoCut->SetTitle(titledpHe);
	HedpNoCut->Draw();
	HedpCut->SetLineColor(kBlack);
	HedpCut->SetFillColor(kViolet);
	HedpCut->Draw("same");

	pad05->cd();
	TString titledpC = "dp Cut from 12C Runs";
	cout << "Drawing " << titledpC << "..." << endl;
	chainC->Draw("R.gold.dp>>CdpNoCut(400,-0.08,0.08)", "", "");
	chainC->Draw("R.gold.dp>>CdpCut(400,-0.08,0.08)", gold, "");
	CdpNoCut->SetTitle(titledpC);
	CdpNoCut->Draw();
	CdpCut->SetLineColor(kBlack);
	CdpCut->SetFillColor(kViolet);
	CdpCut->Draw("same");

	pad02->cd();
	TString titleTargetHe = "Target Cut for 3He Runs";
	cout << "Drawing " << titleTargetHe << "..." << endl;
	chainHe->Draw("ReactPt_R.z>>HeReactZNoCut(400,-0.3,0.3)", "", "");
	chainHe->Draw("ReactPt_R.z>>HeReactZCut(400,-0.3,0.3)", target, "");
	HeReactZNoCut->SetTitle(titleTargetHe);
	HeReactZNoCut->Draw();
	HeReactZCut->SetLineColor(kBlack);
	HeReactZCut->SetFillColor(kViolet);
	HeReactZCut->Draw("same");

	pad06->cd();
	TString titleTargetC = "Target Cut for 12C Runs";
	cout << "Drawing " << titleTargetC << "..." << endl;
	chainC->Draw("ReactPt_R.z>>CReactZNoCut(400,-0.3,0.3)", "", "");
	chainC->Draw("ReactPt_R.z>>CReactZCut(400,-0.3,0.3)", target, "");
	CReactZNoCut->SetTitle(titleTargetC);
	CReactZNoCut->Draw();
	CReactZCut->SetLineColor(kBlack);
	CReactZCut->SetFillColor(kViolet);
	CReactZCut->Draw("same");

	pad03->cd();
	TString titleThetaPhiHe = "Theta and Phi, No Cut, for 3He";
	cout << "Drawing " << titleThetaPhiHe << "..." << endl;
	chainHe->Draw("R_sv_x:R_sv_y>>HeSieveNoCut(100,-0.05,0.05,100,-0.1,0.1)", target, "");
	HeSieveNoCut->SetTitle(titleThetaPhiHe);
	HeSieveNoCut->SetStats(kFALSE);
	HeSieveNoCut->Draw("COLZ");

	pad07->cd();
	TString titleThetaPhiC = "Theta and Phi, No Cut, for 12C";
	cout << "Drawing " << titleThetaPhiC << "..." << endl;
	chainC->Draw("R_sv_x:R_sv_y>>CSieveNoCut(100,-0.05,0.05,100,-0.1,0.1)", target, "");
	CSieveNoCut->SetTitle(titleThetaPhiC);
	CSieveNoCut->SetStats(kFALSE);
	CSieveNoCut->Draw("COLZ");

	pad04->cd();
	TString titleThetaCutHe = "Theta and Phi Cut for 3He";
	cout << "Drawing " << titleThetaCutHe << "..." << endl;
	chainHe->Draw("R_sv_x:R_sv_y>>HeSieveCut(100,-0.05,0.05,100,-0.1,0.1)", target && sieve, "");
	HeSieveCut->SetTitle(titleThetaCutHe);
	HeSieveCut->SetStats(kFALSE);
	HeSieveCut->Draw("COLZ");

	pad08->cd();
	TString titleThetaCutC = "Theta and Phi Cut for 12C";
	cout << "Drawing " << titleThetaCutC << "..." << endl;
	chainC->Draw("R_sv_x:R_sv_y>>CSieveCut(100,-0.05,0.05,100,-0.1,0.1)", target && sieve, "");
	CSieveCut->SetTitle(titleThetaCutC);
	CSieveCut->SetStats(kFALSE);
	CSieveCut->Draw("COLZ");

	pad15->cd();
	TString titleQ2WHe = "Q2 v. Nu for 3He";
	cout << "Drawing " << titleQ2WHe << "..." << endl;
	chainHe->Draw("PriKineR.Q2:PriKineR.nu>>Q2WHe(100,0.3,0.8,400,0,1.6)", cuts, "");
	Q2WHe->SetTitle(titleQ2WHe);
	Q2WHe->SetStats(kFALSE);
	Q2WHe->Draw("COLZ");

	pad16->cd();
	TString titleQ2WC = "Q2 v. Nu for 12C";
	cout << "Drawing " << titleQ2WC << "..." << endl;
	chainC->Draw("PriKineR.Q2:PriKineR.nu>>Q2WC(100,0.3,0.8,400,0,1.6,100)", cuts, "");
	Q2WC->SetTitle(titleQ2WC);
	Q2WC->SetStats(kFALSE);
	Q2WC->Draw("COLZ");


	pad09->cd();
	TString titleC = "x for 12C at Q2 of ";
	titleC += Q2;
//	titleC += " and Target Cut of ";
//	titleC += target;
	cout << "Drawing " << titleC << "..." << endl;
	TH1F *histC = new TH1F("histC",titleC,bins,plotmin,plotmax);
	histC->Sumw2();
	chainC->Draw(whattodrawC, cuts, "E");
	histC->Scale(1/0.0161297);
	histC->Draw();
	TF1 *fitC1 = new TF1("fitC1","[0]*exp(-x*[1])",1.45,1.6);
	fitC1->SetParNames("C Red p1","C Red p2");
	Double_t fitC1const = fitC1->GetParameter(0);
	Double_t fitC1expconst = fitC1->GetParameter(1);
//	Double_t fitC1exp = fitC1->GetParameter(2);
	Double_t fitC1consterror = fitC1->GetParError(0);
	Double_t fitC1expconsterror = fitC1->GetParError(1);
//	Double_t fitC1experror = fitC1->GetParError(2);
	fitC1->SetLineColor(kRed);
	TF1 *fit2 = new TF1("fitC2","[0]*exp(-x*[1])",1.6,1.8);
	fitC2->SetParNames("C Blue p1","C Blue p2");
	Double_t fitC2const = fitC2->GetParameter(0);
	Double_t fitC2expconst = fitC2->GetParameter(1);
//	Double_t fitC2exp = fitC2->GetParameter(2);
	Double_t fitC2consterror = fitC2->GetParError(0);
	Double_t fitC2expconsterror = fitC2->GetParError(1);
//	Double_t fitC2experror = fitC2->GetParError(2);
	fitC2->SetLineColor(kBlue);
	TF1 *fitC3 = new TF1("fitC3","[0]*exp(-x*[1])",1.35,1.45);
	fitC3->SetParNames("C Green p1","C Green p2");
	Double_t fitC3const = fitC3->GetParameter(0);
	Double_t fitC3expconst = fitC3->GetParameter(1);
//	Double_t fitC3exp = fitC3->GetParameter(2);
	Double_t fitC3consterror = fitC3->GetParError(0);
	Double_t fitC3expconsterror = fitC3->GetParError(1);
//	Double_t fitC3experror = fitC3->GetParError(2);
	fitC3->SetLineColor(kGreen);

	histC->Fit("fitC2","R");
	histC->Fit("fitC3","R+");
	histC->Fit("fitC1","R+");
	

	pad12->cd();
	pad12->SetLogy();
	cout << "Drawing " << titleC << " in log scale..." << endl;
	TH1F *histC = new TH1F("histC",titleC,bins,plotmin,plotmax);
	histC->Sumw2();
	chainC->Draw(whattodrawC, cuts, "E");
	histC->Draw();
	histC->Fit("fitC1","R");
	histC->Fit("fitC3","R+");
	histC->Fit("fitC2","R+");

	pad10->cd();
	TString titleHe = "x for 3He at Q2 of ";
	titleHe += Q2;
//	titleHe += " and Target Cut of ";
//	titleHe += target;
	cout << "Drawing " << titleHe << "..." << endl;
	TH1F *histHe = new TH1F("histHe",titleHe,bins,plotmin,plotmax);
	histHe->Sumw2();
	chainHe->Draw(whattodrawHe, cuts, "E");
	histHe->Scale(1/3.69904);
	histHe->Draw();
	TF1 *fitHe1 = new TF1("fitHe1","[0]*exp(-x*[1])",1.45,1.6);
	fitHe1->SetParNames("He Red p1", "He Red p2");
	Double_t fitHe1const = fitHe1->GetParameter(0);
	Double_t fitHe1expconst = fitHe1->GetParameter(1);
//	Double_t fitHe1exp = fitHe1->GetParameter(2);
	Double_t fitHe1consterror = fitHe1->GetParError(0);
	Double_t fitHe1expconsterror = fitHe1->GetParError(1);
//	Double_t fitHe1experror = fitHe1->GetParError(2);
	fitHe1->SetLineColor(kRed);
	TF1 *fitHe2 = new TF1("fitHe2","[0]*exp(-x*[1])",1.6,1.8);
	fitHe2->SetParNames("He Blue p1","He Blue p2");
	Double_t fitHe2const = fitHe2->GetParameter(0);
	Double_t fitHe2expconst = fitHe2->GetParameter(1);
//	Double_t fitHe2exp = fitHe2->GetParameter(2);
	Double_t fitHe2consterror = fitHe2->GetParError(0);
	Double_t fitHe2expconsterror = fitHe2->GetParError(1);
//	Double_t fitHe2experror = fitHe2->GetParError(2);
	fitHe2->SetLineColor(kBlue);
	TF1 *fitHe3 = new TF1("fitHe3","[0]*exp(-x*[1])",1.35,1.45);
	fitHe3->SetParNames("He Green p1","He Green p2");
	Double_t fitHe3const = fitHe3->GetParameter(0);
	Double_t fitHe3expconst = fitHe3->GetParameter(1);
//	Double_t fitHe3exp = fitHe3->GetParameter(2);
	Double_t fitHe3consterror = fitHe3->GetParError(0);
	Double_t fitHe3expconsterror = fitHe3->GetParError(1);
//	Double_t fitHe3experror = fitHe3->GetParError(2);
	fitHe3->SetLineColor(kGreen);

	histHe->Fit("fitHe2","R+");
	histHe->Fit("fitHe3","R+");
	histHe->Fit("fitHe1","R+");
	
	pad13->cd();
	pad13->SetLogy();
	cout << "Drawing " << titleHe << " in log scale..." << endl;
	TH1F *histHe = new TH1F("histHe",titleHe,bins,plotmin,plotmax);
	histHe->Sumw2();
	chainHe->Draw(whattodrawHe, cuts, "E");
	histHe->Draw();
	histHe->Fit("fitHe1","R+");
	histHe->Fit("fitHe3","R+");
	histHe->Fit("fitHe2","R+");

	pad11->cd();
	TString titleCoverHe = "12C/3He for Q2 of ";
	titleCoverHe += Q2;
//	titleCoverHe += " and Target Cut of ";
//	titleCoverHe += target;
	cout << "Drawing " << titleCoverHe << "..." << endl;
	TH1F *histCoverHe = new TH1F("histCoverHe",titleCoverHe,bins,plotmin,plotmax);
	histCoverHe->Sumw2();
	histCoverHe->Divide(histC,histHe,1,0.0918143);
	histCoverHe->Draw("E");

	pad14->cd();
	pad14->SetLogy();
	cout << "Drawing " << titleCoverHe << " in log scale..." << endl;
	TH1F *histCoverHe = new TH1F("histCoverHe",titleCoverHe,bins,plotmin,plotmax);
	histCoverHe->Sumw2();
	histCoverHe->Divide(histC,histHe,1,0.0918143);
	histCoverHe->Draw("E");

   
	TString imagename = "xbj_scaling_plots/xbj_scaling_plots_all_at_Q2_of_";
	imagename += Q2;
	imagename += ".png";
	c1->Print(imagename);

	cout << "All done!" << endl;


}