Example #1
0
 double YZGetChisquare(){return (yzfitfunc->GetChisquare());};
void fitResolandScale(int collision = 2, int flvOpt = 0, int genOpt = 0){
    /*  const int kHIcentral = 0; // 0-30%
        const int kHIperipheral = 1;//30-100%
        const int kPP = 2;
        const int kPA = 3;
        const int kHI010 = 4; //0-10%
        const int kHI1030 = 5; //10-30%
        const int kHI3050 = 6;//30-50%
        const int kHI50100 = 7;//50-100%

*/
   // const int collision = 3;
    TLegend *l1 = new TLegend(0.4365615,0.6445304,0.9577623,0.846736,NULL,"brNDC");

    TCut centCut = "";
    if ( (collision ==0) )   {   
        centCut = "cBin > 0 && cBin< 12";
        easyLeg(l1,"Pb+Pb 0-30%");
    }
    else if (  (collision ==1) ){  // if it's pp 
        centCut = "cBin >=12";
        easyLeg(l1,"Pb+Pb 30-100%");
    }
    else if (collision == 2 || collision == 3){ // pPb
        centCut = "";
        if (collision == 2) easyLeg(l1,"p+p");
        else easyLeg(l1, "p+Pb");
    }
    else if (  (collision ==4) ){  //HI
        centCut = "cBin > 0 && cBin < 4";
        easyLeg(l1,"Pb+Pb 0-10%");
    } else if (  (collision ==5) ){  //HI
        centCut = "cBin >= 4 && cBin < 12";
        easyLeg(l1,"Pb+Pb 10-30%");
    } else if (  (collision ==6) ){  //HI
        centCut = "cBin >= 12 && cBin < 20";
        easyLeg(l1,"Pb+Pb 30-50%");
    } else if (  (collision ==7) ){  //HI
        centCut = "cBin >= 20";
        easyLeg(l1,"Pb+Pb 50-100%");
    }    

    //        
    TH1::SetDefaultSumw2();

    // gStyle->SetOptFit(0);
    gStyle -> SetOptStat(0);
    //  gStyle -> SetTitleYOffset(2.35);
    gStyle -> SetTitleYSize(0.04);


    TCut partonCut = "";
    if (flvOpt ==0 ) partonCut = "";
    else if (flvOpt == 1 ) partonCut = "refPartonFlv == 21";
    else if (flvOpt == 2 ) partonCut = "abs(refPartonFlv) < 21";
    else partonCut = "refPartonFlv < -200";


    const int nPtBin = 12;
    //const int nPtBin = 17;
    //double ptBin[nPtBin+1] = {30.0, 40.0, 50.0, 80.0, 9999.0}; 
    //double AvePtBin[nPtBin+1] = { 35.0, 45.0, 65.0, 100.0};
    double ptBin[nPtBin+1];
    double AvePtBin[nPtBin];

    ptBin[0] = 30.0;
    ptBin[1] = 40.0;
    ptBin[2] = 50.0;
    ptBin[3] = 60.0;
    ptBin[4] = 70.0;
    ptBin[5] = 80.0;
    ptBin[6] = 90.0;
    ptBin[7] = 100.0;
    ptBin[8] = 120.0;
    ptBin[9] = 140.0;
    ptBin[10] = 160.0;
    ptBin[11] = 180.0;
    ptBin[12] = 200.0;

    /*
       for(int i=0;i<=nPtBin;i++){
       ptBin[i] = 30.0+i*10.0;
       }
       */  
    for(int i=0;i<nPtBin;i++){
        AvePtBin[i] = (ptBin[i+1]+ptBin[i])/2.0;
    }

    //    const int nCentBinPa = 3;
    //   double centBinPa[nCentBinPa+1] = {0,20,30,100};
    //
    // fake rate
    //
    int nJetmax = 100;
    float refPt[nJetmax], pt[nJetmax], eta[nJetmax], dphi[nJetmax];
    int nJet, cBin, refPartonFlv[nJetmax];
    EvtSel evtImb;
    TBranch *b_evt;

    multiTreeUtil* yJet = new multiTreeUtil();
    //:PbPb
    if(collision ==1 || collision == 0  || collision == 4 || collision == 5 || collision == 6|| collision == 7){
        yJet -> addFile("/home/jazzitup/forestFiles/yskimmedFiles/yskim_qcdAllPhoton30to50_genPhotonPtCut40_allCent.root", "yJet", "",32796./32796);
        yJet -> addFile("/home/jazzitup/forestFiles/yskimmedFiles/yskim_qcdAllPhoton50to80_genPhotonPtCut40_allCent.root", "yJet", "",21470./53876);
        yJet -> addFile("/home/jazzitup/forestFiles/yskimmedFiles/yskim_qcdAllPhoton80to9999_genPhotonPtCut40_allCent.root", "yJet", "",6462./58781);  
    } else if (collision ==3){
        // pA
        yJet->addFile("/home/jazzitup/forestFiles/yskimmedFiles/yskim_PA2013_pyquen_allQCDPhoton30to50_forestv85.root", "yJet","", 56669./50385);
        yJet->addFile("/home/jazzitup/forestFiles/yskimmedFiles/yskim_PA2013_pyquen_allQCDPhoton50to80_forestv85.root", "yJet","", 41906./114136);
        yJet->addFile("/home/jazzitup/forestFiles/yskimmedFiles/yskim_PA2013_pyquen_allQCDPhoton80to120_forestv85.root", "yJet","",12044./103562);
        yJet->addFile("/home/jazzitup/forestFiles/yskimmedFiles/yskim_PA2013_pyquen_allQCDPhoton120to9999_forestv85.root", "yJet","", 4481./151511);
    } else if (collision ==2){
        //pp 
        yJet->addFile("/home/jazzitup/forestFiles/yskimmedFiles/yskim_merged_allQCDPhoton30to50_genPhotonPtCut30_CMSSW538HIp2.root", "yJet", "",29329. / 29329.);
        yJet->addFile("/home/jazzitup/forestFiles/yskimmedFiles/yskim_merged_allQCDPhoton50to80_genPhotonPtCut30_CMSSW538HIp2.root", "yJet", "",8098. / 87988.);
        yJet->addFile("/home/jazzitup/forestFiles/yskimmedFiles/yskim_merged_allQCDPhoton80to120_genPhotonPtCut30_CMSSW538HIp2.root", "yJet", "",1680. / 96756.);
        yJet->addFile("/home/jazzitup/forestFiles/yskimmedFiles/yskim_merged_allQCDPhoton120to9999_genPhotonPtCut30_CMSSW538HIp2.root", "yJet", "", 438.   / 90972.);
    }

    yJet -> AddFriend("tgj");
    yJet->AddFriend("yPhotonTree");


    TCanvas* c4 = new TCanvas("c4","",400,800);
    c4->Divide(1,2);
    c4->cd(1);
    TH1D* hpt1 = new TH1D("hpt1",";p_{T}^{RECO};Entries",20,0,200);
    TH1D* hpt0 = (TH1D*)hpt1->Clone("hpt2");
    TH1D* hpt2 = (TH1D*)hpt1->Clone("hpt2");
    TH1D* hpt3 = (TH1D*)hpt1->Clone("hpt3");

    yJet -> Draw2(hpt0, "refPt", Form(" photonEt>40 && genPhotonEt> 30 && abs(genMomId)<=22 && (abs(eta) < 1.6) && (dphi > 7*3.141592/8.0) "),"");
    yJet -> Draw2(hpt1, "refPt", Form("  photonEt>40 &&  genPhotonEt> 30 && abs(genMomId)<=22 && (abs(eta) < 1.6) && (dphi > 7*3.141592/8.0) && refPartonFlv == 21"),"");
    yJet -> Draw2(hpt2, "refPt", Form(" photonEt>40 &&  genPhotonEt> 30 && abs(genMomId)<=22 && (abs(eta) < 1.6) && (dphi > 7*3.141592/8.0) && abs(refPartonFlv)<21 "),"");
    yJet -> Draw2(hpt3, "refPt", Form(" photonEt>40 &&  genPhotonEt> 30 && abs(genMomId)<=22 && (abs(eta) < 1.6) && (dphi > 7*3.141592/8.0) && refPartonFlv < -200"),"");

    handsomeTH1(hpt0,1);
    handsomeTH1(hpt1,1);
    handsomeTH1(hpt2,2);
    handsomeTH1(hpt3,4);

    hpt0->GetYaxis()->SetTitleOffset(1.8);

    hpt0->DrawCopy("hist");
    hpt1->DrawCopy("same");
    hpt2->DrawCopy("same");
    hpt3->DrawCopy("same");
    jumSun(30,0,30,7400,2);

    c4->cd(2);
    hpt1->Divide(hpt0);
    hpt2->Divide(hpt0);
    hpt3->Divide(hpt0);
    hpt1->SetAxisRange(0,1,"Y");
    hpt1->SetYTitle("Ratio");
    hpt1->DrawCopy();
    hpt2->DrawCopy("same");
    hpt3->DrawCopy("same");
    jumSun(30,0,30,1,2);

    //    return;


    // pt spectrum
    //    TCanvas* c1=  new TCanvas("c1", "", 500,500);
    //   TH1D* hptHat = new TH1D("hptHat",";pt hat;Entries",200,0,200);
    //   yJet->Draw3( hptHat, "yPhotonTree.ptHat"," photonEt>40 && genPhotonEt> 30 && abs(genMomId)<=22","");
    //yJet->Draw3( hptHat, "yPhotonTree.pt","","");
    //    return;


    // Energy Scale
    TCanvas* c2 = new TCanvas("c2", "pt/refPt distribution", 1200, 900); 
    TCanvas* ccc = new TCanvas("ccc", "pt/refpt 30-40GeV", 400, 400); 
    makeMultiPanelCanvas(c2,5,4,0.0,0.0,0.2,0.15,0.02);


    TH1D* Escale[nCentBinPa+5][nPtBin];
    double mean[nCentBinPa+5][nPtBin], var[nCentBinPa+5][nPtBin], resol[nCentBinPa+5][nPtBin], resolVar[nCentBinPa+5][nPtBin];
    int icent =1;
    // for(int icent=1; icent <= nCentBinPa ; icent++){
    for(int i=0; i < nPtBin ; i++){
        //  c2 -> cd((icent-1)*4+i+1);
        c2 -> cd(i+1);
        Escale[icent][i] = new TH1D(Form("Escale%d_%d",icent, i) , " ;  p_{T}^{RECO}/p_{T}^{GEN}", 50, 0, 2);

        if ( genOpt == 0 )  {
            yJet -> Draw2(Escale[icent][i], "pt/refPt", centCut && partonCut && Form(" (abs(eta) < 1.6) && (dphi > 7*3.141592/8.0) && (refPt >= %d && refPt < %d)", (int)ptBin[i], (int)ptBin[i+1]),""); 
        }
        else if (genOpt == 1)  {
            yJet -> Draw2(Escale[icent][i], "pt/refPt", centCut && partonCut && Form(" (abs(eta) < 1.6) && (dphi > 7*3.141592/8.0) && (pt >= %d && pt < %d) ", (int)ptBin[i], (int)ptBin[i+1]),"");
        }
        //         Escale[icent][i] -> Draw(); 
        TF1* ff = cleverGaus(Escale[icent][i]);
        gPad->SetLogy();
        mean[icent][i] = ff->GetParameter(1);
        var[icent][i] = ff->GetParError(1);
        resol[icent][i] = ff->GetParameter(2);
        resolVar[icent][i] = ff->GetParError(2);

        float dx1;    
        // ((icent==1)||(icent==4))? dx1=0.15 : dx1=0 ;
        dx1=0;
        //            if ( icent == nCentBinPa )
        //  drawText(Form("E_{T}^{HF|#eta|>4} > %dGeV, ", (int)centBinPa[icent-1]), 0.12+dx1,0.929118,1,15);//yeonju 130805
        //else
        //    drawText(Form("%dGeV < E_{T}^{HF|#eta|>4} < %dGeV, ", (int)centBinPa[icent-1], (int)centBinPa[icent]), 0.12+dx1,0.929118,1,15);

        if ( i+1 == nPtBin ) 
            drawText(Form("p_{T}^{GEN Jet} > %dGeV, ", (int)ptBin[i]), 0.17+dx1,0.84,1,15);//yeonju 130823
        else
            drawText(Form("%dGeV < p_{T}^{GEN Jet} < %dGeV, ", (int)ptBin[i], (int)ptBin[i+1]), 0.17+dx1,0.84,1,12);//yeonju 130823

        //            TLegend *l1 = new TLegend(0.6365615,0.6445304,0.9577623,0.846736,NULL,"brNDC");
        //            easyLeg(l1,"p+Pb 5.02TeV");
        //    l1->AddEntry(hxjgNorm[kPADATA][icent + kPADATA*50][j],"pPb ","p");
        //                  if ( icent==1 && j==1)   l1->Draw();
    }
    // }
    c2 -> Update();

    ccc -> Divide(2,1);
    ccc -> cd(1);
    Escale[1][0]->Draw();
    ccc -> cd(2);
    Escale[1][1]->Draw();



    //
    // Energy Scale
    //

    TCanvas *c3 = new TCanvas("c3", "Energy Scale vs. jet pt",147,37,930,465);
    c3->Divide(2,1);
    c3->cd(1);
    
    double bin[nPtBin+1];
    
    for(int ibin=0; ibin<nPtBin+1; ibin++){
        bin[ibin]=ptBin[ibin];
    }
    
    TH1D* hscale = new TH1D("hscale", ";JetP_{T}^{GEN} (GeV); Energy Scale ", nPtBin, bin);
    l1 -> Draw();
    handsomeTH1(hscale,1);
    hscale -> SetAxisRange(0.9, 1.15, "Y");
    hscale -> Draw();
    jumSun(30,1,200,1);
    
    TLegend *l3=new TLegend(0,0,0.4490239,0.08695652,NULL,"brNDC");
    l3->SetTextFont(42);
    l3->SetTextSize(0.04);
    l3->SetFillColor(0);
    l3->SetLineColor(0);

    for(int i=0; i < nPtBin ; i++){ 
        hscale -> SetBinContent(i+1, mean[icent][i]);
        hscale -> SetBinError(i+1, var[icent][i]);
        hscale -> SetMarkerStyle(20);
        hscale -> SetMarkerSize(1);
        hscale -> Draw("same p");
    }

    TF1 *fs = new TF1("fs", myFunc, 30, 200, 3);
    fs -> SetParameters(0.9,0.8,0.001);
    fs -> SetParNames("scale_C", "scale_S", "scale_N");

    double params[3];

    hscale -> Fit("fs", "RLL");
    fs->GetParameters(params);
    cout << " scale C : " << params[0] << ", S : " << params[1] << ", N : : " << params[2] << endl;
    // cout << " N : " << param[0] << endl;

    fs->Draw("same");


    //
    // Energy Resolution
    //
    c3->cd(2);

    TH1D* hresol = new TH1D("hresol", ";JetP_{T} (GeV); Energy Resolution ", nPtBin, bin);
    handsomeTH1(hresol,1);
    hresol -> SetAxisRange(0.0, 0.3, "Y");
    hresol->GetYaxis()->CenterTitle();
    hresol -> Draw();

    jumSun(30,0.0,30,0.3,2);

    TLegend *l_resol=new TLegend(0.40,0.20,0.85,0.42);
    l_resol->SetTextFont(42);
    l_resol->SetTextSize(0.04);
    l_resol->SetFillColor(0);
    l_resol->SetLineColor(0);

    for(int i=0; i < nPtBin ; i++){ 
        hresol -> SetBinContent(i+1, resol[icent][i]);
        hresol -> SetBinError(i+1, resolVar[icent][i]);
        hresol -> SetMarkerStyle(20);
        hresol -> SetMarkerSize(1);
        hresol -> Draw("same p");
    }
    
    TF1 *f;
  //  if(collision==2){ 
        f = new TF1("f", myFunc3, 30, 200, 3);
        f -> SetParameters(0.03, 0.8, 0.01);
        f -> SetParNames("C", "S", "N");

    //   } else { 
 //       f = new TF1("f", myFunc3, 30, 200, 3);
   //     f -> SetParameters(0.041, 0.956,0.001);
  //      f -> SetParNames("N");
  //  }

    double param[3];

    hresol -> Fit("f", "RLL");
    f->GetParameters(param);
 //   cout << " resol_N : " << param[0]<< endl;
//  if(collision==2) cout << " resol C : " << param[0] << ", S : " << param[1] << ", N : : " << param[2] << endl;
    cout << " resol C : " << param[0] << ", S : " << param[1] << ", N : : " << param[2] << endl;
 //  else cout << " N : " << param[0] << endl;

    f->Draw("same");
    l1 -> Draw();
    //  l_resol->Draw();
    //flvOpt = 0, int genOpt
    // c1 -> SaveAs(".gif");
    //c2 -> SaveAs(Form("./graph/CSnotFix_scale_distribution_collision%d.pdf",collision));
    //c3 -> SaveAs(Form("./graph/CSnotFix_scale_resolution_fit_collision%d.pdf",collision));
    //    c_fake -> SaveAs(".gif");
}
Example #3
0
void checkRsnPIDqa(TString filename, TString foldername, Bool_t savePng,
		   TString plotTPCpi, TString plotTPCka, TString plotTPCpro,
		   TString plotTTOFpi, TString plotTOFka, TString plotTOFpro)
{
  //Open input file 
  TFile * fin = TFile::Open(filename.Data());
  if (!fin) return 0x0;
  
  //Access output of specific wagon
  TList * list = (TList*) fin->Get(foldername.Data());
  if (!list) return 0x0;

  //Set range for fit
  Float_t RangeFitMomMin = 0.1; //range in momentum where to check the mean and pull
  Float_t RangeFitMomMax = 2.0;
  Int_t xbinFitMin = 0;
  Int_t xbinFitMax = -1;
  Float_t RangeFitNsigmaPIDmin = -2.0; //range in Nsigma where the fit is to be performed
  Float_t RangeFitNsigmaPIDmax = 2.0;

  //Set range for visualisation
  Float_t RangeShowTPC[2] = {0.1, 2.0}; 
  Float_t RangeShowTOF[2] = {0.25, 2.0};
    
  //--------------------------
  // TPC PID Nsigma
  // fit with simple gaussian
  //--------------------------
  //Gaussian function
  TF1 *fGaus = new TF1("f","gaus", -7.0, 7.0);

  //--- pions
  TH2F * hTPCsigmaPi = (TH2F*)list->FindObject(plotTPCpi.Data());
  hTPCsigmaPi->RebinX(2);
  hTPCsigmaPi->SetTitle("TPC Pions");
  MakeUpHisto(hTPCsigmaPi,"p_{TPC} (GeV/c)", "N#sigma_{TPC}", 1, kBlack, 2);
  hTPCsigmaPi->GetYaxis()->SetRangeUser(-5.1,5.1);
  hTPCsigmaPi->GetXaxis()->SetRangeUser(RangeShowTPC[0], RangeShowTPC[1]);
  xbinFitMin = hTPCsigmaPi->GetXaxis()->FindBin(RangeFitMomMin);
  xbinFitMax = hTPCsigmaPi->GetXaxis()->FindBin(RangeFitMomMax);
  hTPCsigmaPi->FitSlicesY(fGaus, xbinFitMin, xbinFitMax );
  TH1D * hTPCsigmaPi_mean = ((TH1D*)gDirectory->FindObject(Form("%s_1", plotTPCpi.Data())))->Clone("hNsigmaTPCpi_mean");
  TH1D * hTPCsigmaPi_pull = ((TH1D*)gDirectory->FindObject(Form("%s_2", plotTPCpi.Data())))->Clone("hNsigmaTPCpi_pull");
  MakeUpHisto(hTPCsigmaPi_mean, "", "", 1, kBlack, 2);
  MakeUpHisto(hTPCsigmaPi_pull, "", "", 1, kRed+2, 2);

  //--- kaons
  TH2F * hTPCsigmaKa = (TH2F*)list->FindObject(plotTPCka.Data());
  hTPCsigmaKa->RebinX(2);
  hTPCsigmaKa->SetTitle("TPC Kaons");
  hTPCsigmaKa->GetYaxis()->SetRangeUser(-5.1,5.1);
  hTPCsigmaKa->GetXaxis()->SetRangeUser(RangeShowTPC[0], RangeShowTPC[1]);
  hTPCsigmaKa->FitSlicesY(fGaus, xbinFitMin, xbinFitMax );
  MakeUpHisto(hTPCsigmaKa,"p_{TPC} (GeV/c)", "N#sigma_{TPC}", 1, kBlack, 2);
  TH1D * hTPCsigmaKa_mean = ((TH1D*)gDirectory->FindObject(Form("%s_1", plotTPCka.Data())))->Clone("hNsigmaTPCka_mean");
  TH1D * hTPCsigmaKa_pull = ((TH1D*)gDirectory->FindObject(Form("%s_2", plotTPCka.Data())))->Clone("hNsigmaTPCka_pull");
  MakeUpHisto(hTPCsigmaKa_mean, "", "", 1, kBlack, 2);
  MakeUpHisto(hTPCsigmaKa_pull, "", "", 1, kRed+2, 2);

  //--- protons
  TH2F * hTPCsigmaPro = (TH2F*)list->FindObject(plotTPCpro.Data());
  hTPCsigmaPro->RebinX(2);
  hTPCsigmaPro->SetTitle("TPC Protons");
  MakeUpHisto(hTPCsigmaPro,"p_{TPC} (GeV/c)", "N#sigma_{TPC}", 1, kBlack, 2);
  hTPCsigmaPro->GetYaxis()->SetRangeUser(-5.1,5.1);
  hTPCsigmaPro->GetXaxis()->SetRangeUser(RangeShowTPC[0], RangeShowTPC[1]);
  hTPCsigmaPro->FitSlicesY(fGaus, xbinFitMin, xbinFitMax );
  TH1D * hTPCsigmaPro_mean = ((TH1D*)gDirectory->FindObject(Form("%s_1", plotTPCpro.Data())))->Clone("hNsigmaTPCpro_mean");
  TH1D * hTPCsigmaPro_pull = ((TH1D*)gDirectory->FindObject(Form("%s_2", plotTPCpro.Data())))->Clone("hNsigmaTPCpro_pull");
  MakeUpHisto(hTPCsigmaPro_mean, "", "", 1, kBlack, 2);
  MakeUpHisto(hTPCsigmaPro_pull, "", "", 1, kRed+2, 2);

   //--- plot TPC
  TLine *l11=new TLine(RangeShowTPC[0],0.,RangeShowTPC[1],0.); l11->SetLineWidth(1); l11->SetLineStyle(7);
  TLine *l12=new TLine(RangeShowTPC[0],1.,RangeShowTPC[1],1.); l12->SetLineWidth(1); l12->SetLineStyle(7);

  gStyle->SetOptStat(0);
  TCanvas *cPidPerformance4 = new TCanvas("cPIDperformance4","TPC PID",1200,500);
  cPidPerformance4->Divide(3,1);
  cPidPerformance4->cd(1);
  gPad->SetLogz(); gPad->SetLogx(); gPad->SetGridx(); gPad->SetGridy();
  hTPCsigmaPi->DrawCopy("colz");
  hTPCsigmaPi_mean->DrawCopy("same");
  hTPCsigmaPi_pull->DrawCopy("same");
  l11->Draw("same"); l12->Draw("same");

  cPidPerformance4->cd(2);
  gPad->SetLogz(); gPad->SetLogx(); gPad->SetGridx(); gPad->SetGridy();
  hTPCsigmaKa->DrawCopy("colz");
  hTPCsigmaKa_mean->DrawCopy("same");
  hTPCsigmaKa_pull->DrawCopy("same");
  l11->Draw("same"); l12->Draw("same");

  cPidPerformance4->cd(3);
  gPad->SetLogz(); gPad->SetLogx(); gPad->SetGridx(); gPad->SetGridy();
  hTPCsigmaPro->DrawCopy("colz");
  hTPCsigmaPro_mean->DrawCopy("same");
  hTPCsigmaPro_pull->DrawCopy("same");
  l11->Draw("same"); l12->Draw("same");

  TLegend * pidLegTPC = new TLegend(0.15,0.8,0.88,0.88);
  pidLegTPC->SetBorderSize(0); pidLegTPC->SetFillStyle(1001); pidLegTPC->SetFillColor(kWhite);
  pidLegTPC->SetTextSize(0.04); pidLegTPC->SetNColumns(2);
  pidLegTPC->AddEntry(hTPCsigmaPro_mean,"Mean","lp");
  pidLegTPC->AddEntry(hTPCsigmaPro_pull,Form("#sigma, Gaus fit (%2.1f,%2.1f)",RangeFitNsigmaPIDmin,RangeFitNsigmaPIDmax),"lp");
  pidLegTPC->Draw("same");

  if (savePng) cPidPerformance4->SaveAs("RsnQA_TPC_Nsigma.png");
  
  //----------------------------------------------------
  // TOF
  // fit with signal model = gaussian + exponential tail
  //----------------------------------------------------
  //Signal model for TOF signal = gaus + exp tail
  const Int_t npars = 6;
  TF1 *fSignalModel = new TF1("fSignalModel", TOFsignal, -7.0, 7.0, npars);
  fSignalModel->SetTitle("TOF Signal");
  fSignalModel->SetParameter(0, 1.);
  fSignalModel->SetParameter(1, 0.);
  fSignalModel->SetParLimits(1, -2., 1.);
  fSignalModel->SetParameter(2, 1.);
  fSignalModel->SetParLimits(2, 0.5, 2.);
  fSignalModel->SetParameter(3, 1.);
  fSignalModel->SetParLimits(3, 0.5, 1.5);
  fSignalModel->SetParameter(4, 1.);
  fSignalModel->SetParLimits(4, 0., 1.e8);
  fSignalModel->SetParameter(5, 0.);
  fSignalModel->SetParLimits(5, -10., 10.);
  fSignalModel->SetNpx(2000);
  fSignalModel->SetParNames("Norm", "Mean", "Sigma", "Tail", "Shift", "Slope"/*, "Square"*/);
  fSignalModel->SetLineColor(kRed+1);

  //results
  TObjArray *results[3];
  for(Int_t i = 0; i < 3; i++){
    results[i] = new TObjArray(10);
  }
  TH1D * par[3][npars];
  //--- pions
  TH2F * hTOFsigmaPi = (TH2F*)list->FindObject(plotTOFpi.Data());
  hTOFsigmaPi->SetTitle("TOF Pions");
  hTOFsigmaPi->RebinX(2);
  MakeUpHisto(hTOFsigmaPi,"p (GeV/c)", "N#sigma_{TOF}", 1, kBlack, 2);
  hTOFsigmaPi->GetYaxis()->SetRangeUser(-5.1,5.1);
  hTOFsigmaPi->GetXaxis()->SetRangeUser(RangeShowTOF[0], RangeShowTOF[1]);
  fSignalModel->SetParLimits(4, 0., hTOFsigmaPi->GetMaximum()*0.5);
  fSignalModel->SetParLimits(0, 0., hTOFsigmaPi->GetMaximum()*1.2);
  hTOFsigmaPi->FitSlicesY(fSignalModel, xbinFitMin, xbinFitMax, 0, "QR", results[0] );
  for(Int_t cc = 0; cc < npars ; cc++) {
    par[0][cc] = (TH1D*)gDirectory->FindObject(Form("%s_%i", plotTOFpi.Data(), cc));
  }
  MakeUpHisto(par[0][1], "", "", 1, kBlue, 2);
  MakeUpHisto(par[0][2], "", "", 1, kMagenta+2, 2);
  
  //--- KAONS
  TH2F * hTOFsigmaKa = (TH2F*)list->FindObject(plotTOFka.Data());
  hTOFsigmaKa->SetTitle("TOF Kaons");
  hTOFsigmaKa->RebinX(2);
  MakeUpHisto(hTOFsigmaKa,"p (GeV/c)", "N#sigma_{TOF}", 1, kBlack, 2);
  hTOFsigmaKa->GetYaxis()->SetRangeUser(-5.1,5.1);
  hTOFsigmaKa->GetXaxis()->SetRangeUser(RangeShowTOF[0], RangeShowTOF[1]);
  fSignalModel->SetParLimits(4, 0., hTOFsigmaKa->GetMaximum()*0.5);
  fSignalModel->SetParLimits(0, 0., hTOFsigmaKa->GetMaximum()*1.2);
  hTOFsigmaKa->FitSlicesY(fSignalModel, xbinFitMin, xbinFitMax, 0, "QR", results[0] );
  for(Int_t cc = 0; cc < npars ; cc++) {
    par[1][cc] = (TH1D*)gDirectory->FindObject(Form("%s_%i", plotTOFka.Data(), cc));
  }
  MakeUpHisto(par[1][1], "", "", 1, kBlue, 2);
  MakeUpHisto(par[1][2], "", "", 1, kMagenta+2, 2);

  //--- protons
  TH2F * hTOFsigmaPro = (TH2F*)list->FindObject(plotTOFpro.Data());
  hTOFsigmaPro->SetTitle("TOF Protons");
  hTOFsigmaPro->RebinX(2);
  MakeUpHisto(hTOFsigmaPro,"p (GeV/c)", "N#sigma_{TOF}", 1, kBlack, 2);
  hTOFsigmaPro->GetYaxis()->SetRangeUser(-5.1,5.1);
  hTOFsigmaPro->GetXaxis()->SetRangeUser(RangeShowTOF[0], RangeShowTOF[1]);
  fSignalModel->SetParLimits(4, 0., hTOFsigmaPro->GetMaximum()*0.5);
  fSignalModel->SetParLimits(0, 0., hTOFsigmaPro->GetMaximum()*1.2);
  hTOFsigmaPro->FitSlicesY(fSignalModel, xbinFitMin, xbinFitMax, 0, "QR", results[0] );
  for(Int_t cc = 0; cc < npars ; cc++) {
    par[2][cc] = (TH1D*)gDirectory->FindObject(Form("%s_%i", plotTOFpro.Data(), cc));
  }
  MakeUpHisto(par[2][1], "", "", 1, kBlue, 2);
  MakeUpHisto(par[2][2], "", "", 1, kMagenta+2, 2);

  //--- plot TOF
  gStyle->SetOptStat(0);
  TCanvas *cPidPerformance3 = new TCanvas("cPidPerformance3","TOF PID performance",1200,500);
  cPidPerformance3->Divide(3,1);
  cPidPerformance3->cd(1);
  gPad->SetLogz(); gPad->SetLogx(); gPad->SetGridx(); gPad->SetGridy();
  hTOFsigmaPi->DrawCopy("colz");
  if(par[0][1]) par[0][1]->DrawCopy("same");
  if(par[0][2]) par[0][2]->DrawCopy("same");
  l11->Draw("same"); l12->Draw("same");

  cPidPerformance3->cd(2);
  gPad->SetLogz(); gPad->SetLogx(); gPad->SetGridx(); gPad->SetGridy();
  hTOFsigmaKa->DrawCopy("colz");
  if(par[1][1]) par[1][1]->DrawCopy("same");
  if(par[1][2]) par[1][2]->DrawCopy("same");
  l11->Draw("same"); l12->Draw("same");

  cPidPerformance3->cd(3);
  gPad->SetLogz(); gPad->SetLogx(); gPad->SetGridx(); gPad->SetGridy();
  hTOFsigmaPro->DrawCopy("colz");
  if(par[2][1]) par[2][1]->DrawCopy("same");
  if(par[2][2]) par[2][2]->DrawCopy("same");
  l11->Draw("same"); l12->Draw("same");

  TLegend * pidLegTOF = new TLegend(0.15,0.8,0.88,0.88);
  pidLegTOF->SetBorderSize(0); pidLegTOF->SetFillStyle(1001); pidLegTOF->SetFillColor(kWhite);
  pidLegTOF->SetTextSize(0.04); pidLegTOF->SetNColumns(2);
  pidLegTOF->AddEntry(par[0][1],"Mean","lp");
  pidLegTOF->AddEntry(par[0][2], Form("#sigma, Gaus+Tail fit (%2.1f,%2.1f)",RangeFitNsigmaPIDmin, RangeFitNsigmaPIDmax),"lp");
  pidLegTOF->Draw("same");
  
  if (savePng) cPidPerformance3->Print("RsnQA_TOF_Nsigma.png");
  return;
}
Example #4
0
//_________________________________________________________________________________________
Int_t checkPullTree(TString pathTree,  TString pathNameThetaMap, TString pathNameSigmaMap,
                    TString mapSuffix, const Int_t collType /*0: pp, 1: pPb, 2: PbPb*/, const Bool_t plotPull = kTRUE,
                    const Double_t downScaleFactor = 1,
                    TString pathNameSplinesFile = "", TString prSplinesName = "",
                    TString fileNameTree = "bhess_PIDetaTree.root", TString treeName = "fTree")
{
  const Bool_t isNonPP = collType != 0;
  const Double_t massProton = AliPID::ParticleMass(AliPID::kProton);
  
  Bool_t recalculateExpecteddEdx = pathNameSplinesFile != "";
  
  TFile* f = 0x0;
	
  f = TFile::Open(Form("%s/%s", pathTree.Data(), fileNameTree.Data()));
  if (!f)  {
    std::cout << "Failed to open tree file \"" << Form("%s/%s", pathTree.Data(), fileNameTree.Data()) << "\"!" << std::endl;
    return -1;
  }
      
  // Extract the data Tree
  TTree* tree = dynamic_cast<TTree*>(f->Get(treeName.Data()));
  if (!tree) {
    std::cout << "Failed to load data tree!" << std::endl;
    return -1;
  }
  
  // Extract the splines, if desired
  TSpline3* splPr = 0x0;
  if (recalculateExpecteddEdx) {
    std::cout << "Loading splines to recalculate expected dEdx!" << std::endl << std::endl;
    
    TFile* fSpl = TFile::Open(pathNameSplinesFile.Data());
    if (!fSpl) {
      std::cout << "Failed to open spline file \"" << pathNameSplinesFile.Data() << "\"!" << std::endl;
      return 0x0;
    }
    
    TObjArray* TPCPIDResponse = (TObjArray*)fSpl->Get("TPCPIDResponse");
    if (!TPCPIDResponse) {
      splPr = (TSpline3*)fSpl->Get(prSplinesName.Data());
      
      // If splines are in file directly, without TPCPIDResponse object, try to load them
      if (!splPr) {
        std::cout << "Failed to load object array from spline file \"" << pathNameSplinesFile.Data() << "\"!" << std::endl;
        return 0x0;
      }
    }
    else {
      splPr = (TSpline3*)TPCPIDResponse->FindObject(prSplinesName.Data());
      
      if (!splPr) {
        std::cout << "Failed to load splines from file \"" << pathNameSplinesFile.Data() << "\"!" << std::endl;
        return 0x0;
      }
    }
  }
  else
    std::cout << "Taking dEdxExpected from Tree..." << std::endl << std::endl;

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

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

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

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

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

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

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

  Long64_t nTreeEntries = tree->GetEntriesFast();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    if (!hMap)
      continue;

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

        multCorrectionFactor = 1. + relSlope * fMultiplicity;
      }

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

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

    hPullAdditionalCorr->Fill(pTPC, pull);

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

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

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

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

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

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

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

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

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

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

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

  TNamed* info = new TNamed(Form("Theta map: %s\n\nSigma map: %s\n\nSplines file: %s\n\nSplines name: %s", pathNameThetaMap.Data(), 
                                 pathNameSigmaMap.Data(), pathNameSplinesFile.Data(), prSplinesName.Data()),
                            "info");
  info->Write();
  fSave->Close();
  
  return 0;
}
Example #5
0
int fit_dscb(TH1F*& hrsp,
             const double nsigma,
             const double jtptmin,
             const int niter,
             const string alg,
	     const double fitmin,
	     const double fitmax

)
{
  if (0==hrsp) {
    cout<<"ERROR: Empty pointer to fit_dscb()"<<endl;return -1;
  }


  // first use a gaussian to constrain crystal ball gaussian core
  fit_gaussian(hrsp, nsigma, jtptmin, niter, alg);
  TF1* fgaus = hrsp->GetFunction("fgaus");
  if (0==fgaus) {
    hrsp->GetListOfFunctions()->Delete();
    return -1;
  }

  // implementation of the low pt bias threshold 
  string histname = hrsp->GetName();
  double ptRefMax(1.0),rspMax(0.0);
  int pos1     = histname.find("RefPt");
  int pos2     = histname.find("to",pos1);
  string ss    = histname.substr(pos1+5,pos2);
  if (from_string(ptRefMax,ss,std::dec)) {
    if (histname.find("RelRsp")==0)
      rspMax = jtptmin/ptRefMax;
    if (histname.find("AbsRsp")==0)
      rspMax = jtptmin-ptRefMax;
  }

  double fitrange_min(fitmin);
  double fitrange_max(fitmax);

  fitrange_min = std::max(rspMax,fitmin);
  adjust_fitrange(hrsp,fitrange_min,fitrange_max);

  TF1* fdscb = new TF1("fdscb",fnc_dscb,fitrange_min,fitrange_max,7);
  fdscb->SetLineWidth(2);
  fdscb->SetLineStyle(2);

  double norm = 2*fgaus->GetParameter(0);
  double mean = fgaus->GetParameter(1);
  double sigma= fgaus->GetParameter(2);

  //cout << hrsp->GetName() << "  fgaus "<< mean << " \t "  << hrsp->GetMean() << endl;

  // double norm = 2*hrsp->GetMaximum();
  // double mean = hrsp->GetMean();
  // //double mean = GetPeak(hrsp);
  // cout << "  mean : " << mean << "  hist mean : "<< hrsp->GetMean() << endl;
  // double sigma= hrsp->GetRMS();


  double aone(2.0),atwo(2.0),pone(10.0),ptwo(10.0);
  //double aone(1.0),atwo(1.0),pone(10.0),ptwo(10.0);
  TVirtualFitter::SetDefaultFitter("Minuit");
  
  int fitstatus(0);
  for (int i=0;i<niter;i++) {
    fdscb->SetParameter(0,norm); // N
    fdscb->SetParameter(1,mean); // mean
    fdscb->SetParameter(2,sigma);// sigma
    fdscb->SetParameter(3,aone); // a1
    fdscb->SetParameter(4,pone); // p1
    fdscb->SetParameter(5,atwo); // a2
    fdscb->SetParameter(6,ptwo); // p2                

    fdscb->FixParameter(1,mean);
    fdscb->FixParameter(2,sigma);

    if (i>0) fdscb->FixParameter(3,aone);
    else{
      fdscb->SetParLimits(3,0.,20.); //! best
    }
    if (i>1) fdscb->FixParameter(5,atwo);
    else{
      fdscb->SetParLimits(5,0.,20.); //! best
    }

    //! best
    fdscb->SetParLimits(4,0.,60.);
    fdscb->SetParLimits(6,0.,60.);

    fitstatus = hrsp->Fit(fdscb,"RQ+");
    if (0==fitstatus) i=999;
    delete fdscb;
    fdscb = hrsp->GetFunction("fdscb");
    if (0==fdscb) return -1;

    norm  = fdscb->GetParameter(0);
    aone  = fdscb->GetParameter(3);
    pone  = fdscb->GetParameter(4);
    atwo  = fdscb->GetParameter(5);
    ptwo  = fdscb->GetParameter(6);

    //cout << " aone : "  << aone << " atwo : " << atwo << " pone : " << pone << " ptwo : "  << ptwo << endl;

    //reset sigma and mean to gauss values...
    fdscb->SetParameter(1,fgaus->GetParameter(1));
    fdscb->SetParError (1,fgaus->GetParError(1));
    fdscb->SetParameter(2,fgaus->GetParameter(2));
    fdscb->SetParError (2,fgaus->GetParError(2));
  }

  if (0!=fitstatus){
    cout<<"fit_fdscb() to "<<alg.c_str()<<"  " <<hrsp->GetName()
        <<" failed. Fitstatus: "<<fitstatus<<endl;
    hrsp->GetFunction("fdscb")->Delete();
  }
  else fdscb->ResetBit(TF1::kNotDraw);
  //cout << " aone : "  << aone << " atwo : " << atwo << " pone : " << pone << " ptwo : "  << ptwo << endl;
  return fitstatus;
}
Example #6
0
void ConfidenceIntervals()
{
   TCanvas *myc = new TCanvas("myc",
      "Confidence intervals on the fitted function",1200, 500);
   myc->Divide(3,1);

/////1. A graph
   //Create and fill a graph
   Int_t ngr = 100;
   TGraph *gr = new TGraph(ngr);
   gr->SetName("GraphNoError");
   Double_t x, y;
   Int_t i;
   for (i=0; i<ngr; i++){
      x = gRandom->Uniform(-1, 1);
      y = -1 + 2*x + gRandom->Gaus(0, 1);
      gr->SetPoint(i, x, y);
   }
   //Create the fitting function
   TF1 *fpol = new TF1("fpol", "pol1", -1, 1);
   fpol->SetLineWidth(2);
   gr->Fit(fpol, "Q");

   //Create a TGraphErrors to hold the confidence intervals
   TGraphErrors *grint = new TGraphErrors(ngr);
   grint->SetTitle("Fitted line with .95 conf. band");
   for (i=0; i<ngr; i++)
      grint->SetPoint(i, gr->GetX()[i], 0);
   //Compute the confidence intervals at the x points of the created graph
   (TVirtualFitter::GetFitter())->GetConfidenceIntervals(grint);
   //Now the "grint" graph contains function values as its y-coordinates
   //and confidence intervals as the errors on these coordinates
   //Draw the graph, the function and the confidence intervals
   myc->cd(1);
   grint->SetLineColor(kRed);
   grint->Draw("ap");
   gr->SetMarkerStyle(5);
   gr->SetMarkerSize(0.7);
   gr->Draw("psame");

/////2. A histogram
   myc->cd(2);
   //Create, fill and fit a histogram
   Int_t nh=5000;
   TH1D *h = new TH1D("h",
      "Fitted gaussian with .95 conf.band", 100, -3, 3);
   h->FillRandom("gaus", nh);
   TF1 *f = new TF1("fgaus", "gaus", -3, 3);
   f->SetLineWidth(2);
   h->Fit(f, "Q");
   h->Draw();

   //Create a histogram to hold the confidence intervals
   TH1D *hint = new TH1D("hint",
      "Fitted gaussian with .95 conf.band", 100, -3, 3);
   (TVirtualFitter::GetFitter())->GetConfidenceIntervals(hint);
   //Now the "hint" histogram has the fitted function values as the
   //bin contents and the confidence intervals as bin errors
   hint->SetStats(kFALSE);
   hint->SetFillColor(2);
   hint->Draw("e3 same");

/////3. A 2d graph
   //Create and fill the graph
   Int_t ngr2 = 100;
   Double_t z, rnd, e=0.3;
   TGraph2D *gr2 = new TGraph2D(ngr2);
   gr2->SetName("Graph2DNoError");
   TF2  *f2 = new TF2("f2",
      "1000*(([0]*sin(x)/x)*([1]*sin(y)/y))+250",-6,6,-6,6);
   f2->SetParameters(1,1);
   for (i=0; i<ngr2; i++){
      f2->GetRandom2(x,y);
      // Generate a random number in [-e,e]
      rnd = 2*gRandom->Rndm()*e-e;
      z = f2->Eval(x,y)*(1+rnd);
      gr2->SetPoint(i,x,y,z);
   }
   //Create a graph with errors to store the intervals
   TGraph2DErrors *grint2 = new TGraph2DErrors(ngr2);
   for (i=0; i<ngr2; i++)
      grint2->SetPoint(i, gr2->GetX()[i], gr2->GetY()[i], 0);

   //Fit the graph
   f2->SetParameters(0.5,1.5);
   gr2->Fit(f2, "Q");
   //Compute the confidence intervals
   (TVirtualFitter::GetFitter())->GetConfidenceIntervals(grint2);
   //Now the "grint2" graph contains function values as z-coordinates
   //and confidence intervals as their errors
   //draw
   myc->cd(3);
   f2->SetNpx(30);
   f2->SetNpy(30);
   f2->SetFillColor(kBlue);
   f2->Draw("surf4");
   grint2->SetNpx(20);
   grint2->SetNpy(20);
   grint2->SetMarkerStyle(24);
   grint2->SetMarkerSize(0.7);
   grint2->SetMarkerColor(kRed);
   grint2->SetLineColor(kRed);
   grint2->Draw("E0 same");
   grint2->SetTitle("Fitted 2d function with .95 error bars");

   myc->cd();

}
void DrawCalibrationPlotsEE (
 			     Char_t* infile1 = "data_LC_20120131_ALPHA_test_prompt/SingleElectron_Run2011AB-WElectron-data_LC_20120131_ALPHA_test_prompt_EoPcaibEE_11032011_Z_R9_EE.root",
 			     Char_t* infile2 = "data_LC_20120131_ALPHA_test_prompt/Even_SingleElectron_Run2011AB-WElectron-data_LC_20120131_ALPHA_test_prompt_EoPcaibEE_11032011_Z_R9_EE.root",
 			     Char_t* infile3 = "data_LC_20120131_ALPHA_test_prompt/Odd_SingleElectron_Run2011AB-WElectron-data_LC_20120131_ALPHA_test_prompt_EoPcaibEE_11032011_Z_R9_EE.root",
 			     //Char_t* infile1 = "FT_R_42_V21B/WZAnalysis_PromptSkim_W-DoubleElectron_FT_R_42_V21B_Z_R9_EE.root",
 			     //Char_t* infile2 = "FT_R_42_V21B/Even_WZAnalysis_PromptSkim_W-DoubleElectron_FT_R_42_V21B_Z_R9_EE.root",
 			     //Char_t* infile3 = "FT_R_42_V21B/Odd_WZAnalysis_PromptSkim_W-DoubleElectron_FT_R_42_V21B_Z_R9_EE.root",
			     int evalStat = 1,
                             bool isMC=false,
			     Char_t* fileType = "png", 
			     Char_t* dirName = ".")
{

  bool  printPlots = false;

  /// by xtal

  int nbins = 250;

  /// Set style options
  gROOT->Reset();
  gROOT->SetStyle("Plain");

  gStyle->SetPadTickX(1);
  gStyle->SetPadTickY(1);
  gStyle->SetOptTitle(0); 
  gStyle->SetOptStat(11110); 
  gStyle->SetOptFit(0); 
  gStyle->SetFitFormat("6.3g"); 
  gStyle->SetPalette(1); 
 
  gStyle->SetTextFont(42);
  gStyle->SetTextSize(0.05);
  gStyle->SetTitleFont(42,"xyz");
  gStyle->SetTitleSize(0.05);
  gStyle->SetLabelFont(42,"xyz");
  gStyle->SetLabelSize(0.05);
  gStyle->SetTitleXOffset(0.8);
  gStyle->SetTitleYOffset(1.1);
  gROOT->ForceStyle();

  if ( !infile1 ) {
    cout << " No input file specified !" << endl;
    return;
  }


  if ( evalStat && (!infile2 || !infile3 )){
    cout << " No input files to evaluate statistical precision specified !" << endl;
    return;
  }

  cout << "Making calibration plots for: " << infile1 << endl;
  
  
  /// imput file with full statistic normlized to the mean in a ring

  TFile *f = new TFile(infile1);
  TH2F *hcmap[2];
  hcmap[0] = (TH2F*)f->Get("h_scale_map_EEM");
  hcmap[1] = (TH2F*)f->Get("h_scale_map_EEP");
    

  /// ring geometry for the endcap
  TH2F *hrings[2];
  hrings[0] = (TH2F*)hcmap[0]->Clone("hringsEEM");
  hrings[1] = (TH2F*)hcmap[0]->Clone("hringsEEP");
  hrings[0] ->Reset("ICMES");
  hrings[1] ->Reset("ICMES");
  hrings[0] ->ResetStats();
  hrings[1] ->ResetStats();

  FILE *fRing;
  fRing = fopen("macros/eerings.dat","r");
  int x,y,z,ir;
  while(fscanf(fRing,"(%d,%d,%d) %d \n",&x,&y,&z,&ir) !=EOF ) {
    if(z>0) hrings[1]->Fill(x,y,ir); 
    if(z<0) hrings[0]->Fill(x,y,ir);
  }

  TFile *f4 = TFile::Open("MCtruthIC_EE.root");
  TFile *f5 = TFile::Open("MCRecoIC_EE.root");

  TH2F *hcmapMcT_EEP = (TH2F*)f4->Get("h_scale_EEP");
  TH2F *hcmapMcT_EEM = (TH2F*)f4->Get("h_scale_EEM");
  TH2F *hcmapMcR_EEP = (TH2F*)f5->Get("h_scale_EEP");
  TH2F *hcmapMcR_EEM = (TH2F*)f5->Get("h_scale_EEM");
 
 
  ///--------------------------------------------------------------------------------
  ///--- Build the precision vs ring plot starting from the TH2F of IC folded and not
  ///--------------------------------------------------------------------------------

  char hname[100];
  char htitle[100];
  TH1F *hspread[2][50];
  TH1F* hspreadAll [40];

  TH2F* ICComparison [2];
  ICComparison[0] = (TH2F*) hcmapMcT_EEP->Clone("ICComparison_EEM");
  ICComparison[1] = (TH2F*) hcmapMcT_EEM->Clone("ICComparison_EEP");
  ICComparison[0]->Reset("ICMES");
  ICComparison[1]->Reset("ICMES");
  ICComparison[0]->ResetStats();
  ICComparison[1]->ResetStats();


  for (int k = 0; k < 2; k++){
         
    for (int iring = 0; iring < 40 ; iring++){
      if (k==0)
      {
       sprintf(hname,"hspreadAll_ring%02d",iring);
       hspreadAll[iring] = new TH1F(hname, hname, nbins,0.,2.);
       sprintf(hname,"hspreadEEM_MCTruth_ring%02d",iring);
       hspread[k][iring] = new TH1F(hname, hname, nbins,0.,2.);

      }
      else{ 
	
        sprintf(hname,"hspreadEEP_ring%02d",iring);
         hspread[k][iring] = new TH1F(hname, hname, nbins,0.,2.);
 
     }
    }
 }
  
 /// spread all distribution, spread for EE+ and EE- and comparison with the MC truth
  for (int k = 0; k < 2 ; k++){
    for (int ix = 1; ix < 101; ix++){
      for (int iy = 1; iy < 101; iy++){
	int iz = k;
	if (k==0) iz = -1;
	int mybin = hcmap[k] -> FindBin(ix,iy);
	int ring  = hrings[1]-> GetBinContent(mybin);
	float ic = hcmap[k]->GetBinContent(mybin);
        float ic2=0;
          if(k==0 && hcmapMcT_EEM->GetBinContent(mybin)!=0 && hcmapMcR_EEM->GetBinContent(mybin)!=0 ) ic2 = hcmapMcT_EEM->GetBinContent(mybin)/hcmapMcR_EEM->GetBinContent(mybin);
          else if(hcmapMcT_EEP->GetBinContent(mybin)!=0 && hcmapMcR_EEP->GetBinContent(mybin)!=0 ) ic2 = hcmapMcT_EEP->GetBinContent(mybin)/hcmapMcR_EEP->GetBinContent(mybin);
          
 	if ( ic>0 && ic2>0 )    {
	  hspread[k][ring]->Fill(ic);
          hspreadAll[ring]->Fill(ic);
          ICComparison[k]->Fill(ix,iy,ic/ic2);
	}
      }
    }
  }
  
  /// Graph Error for spread EE+ and EE-

  TGraphErrors *sigma_vs_ring[3];
  sigma_vs_ring[0] = new TGraphErrors();
  sigma_vs_ring[0]->SetMarkerStyle(20);
  sigma_vs_ring[0]->SetMarkerSize(1);
  sigma_vs_ring[0]->SetMarkerColor(kBlue+2);
  
  sigma_vs_ring[1] = new TGraphErrors();
  sigma_vs_ring[1]->SetMarkerStyle(20);
  sigma_vs_ring[1]->SetMarkerSize(1);
  sigma_vs_ring[1]->SetMarkerColor(kBlue+2);

  sigma_vs_ring[2] = new TGraphErrors();
  sigma_vs_ring[2]->SetMarkerStyle(20);
  sigma_vs_ring[2]->SetMarkerSize(1);
  sigma_vs_ring[2]->SetMarkerColor(kBlue+2);
 
  /// Graph for scale vs ring EE+, EE- and folded

  TGraphErrors *scale_vs_ring[3];
  scale_vs_ring[0] = new TGraphErrors();
  scale_vs_ring[0]->SetMarkerStyle(20);
  scale_vs_ring[0]->SetMarkerSize(1);
  scale_vs_ring[0]->SetMarkerColor(kBlue+2);

  scale_vs_ring[1] = new TGraphErrors();
  scale_vs_ring[1]->SetMarkerStyle(20);
  scale_vs_ring[1]->SetMarkerSize(1);
  scale_vs_ring[1]->SetMarkerColor(kBlue+2);

  scale_vs_ring[2] = new TGraphErrors();
  scale_vs_ring[2]->SetMarkerStyle(20);
  scale_vs_ring[2]->SetMarkerSize(1);
  scale_vs_ring[2]->SetMarkerColor(kBlue+2);
    
  
  TF1 *fgaus = new TF1("fgaus","gaus",-10,10);
  int np[3] = {0};

  /// Gaussian fit for EE+ and EE-

  for (int k = 0; k < 2 ; k++){
    for (int iring = 0; iring < 40; iring++){
      if (hspread[k][iring]-> GetEntries() == 0) continue;
      float e     = 0.5*hcmap[k]-> GetYaxis()->GetBinWidth(1);
      fgaus->SetParameter(1,1);
      fgaus->SetParameter(2,hspread[k][iring]->GetRMS());
      fgaus->SetRange(1-5*hspread[k][iring]->GetRMS(),1+5*hspread[k][iring]->GetRMS());
      hspread[k][iring]->Fit("fgaus","QR");
      sigma_vs_ring[k]-> SetPoint(np[k],iring,fgaus->GetParameter(2));
      sigma_vs_ring[k]-> SetPointError(np[k], e ,fgaus->GetParError(2));
      scale_vs_ring[k]-> SetPoint(np[k],iring,fgaus->GetParameter(1));
      scale_vs_ring[k]-> SetPointError(np[k],e,fgaus->GetParError(1));
      np[k]++;    
    }
  }
  
    for (int iring = 0; iring < 40; iring++){
      if (hspreadAll[iring]-> GetEntries() == 0) continue;
      float e     = 0.5*hcmap[0]-> GetYaxis()->GetBinWidth(1);
      fgaus->SetParameter(1,1);
      fgaus->SetParameter(2,hspreadAll[iring]->GetRMS());
      fgaus->SetRange(1-5*hspreadAll[iring]->GetRMS(),1+5*hspreadAll[iring]->GetRMS());
      hspreadAll[iring]->Fit("fgaus","QR");
      sigma_vs_ring[2]-> SetPoint(np[2],iring,fgaus->GetParameter(2));
      sigma_vs_ring[2]-> SetPointError(np[2], e ,fgaus->GetParError(2));
      scale_vs_ring[2]-> SetPoint(np[2],iring,fgaus->GetParameter(1));
      scale_vs_ring[2]-> SetPointError(np[2],e,fgaus->GetParError(1));
      np[2]++;    
    }

  /// Intercalibration constant vs phi
 
 /* TGraphErrors *IC_vs_phi[2];
  IC_vs_phi[0] = new TGraphErrors();
  IC_vs_phi[0]->SetMarkerStyle(20);
  IC_vs_phi[0]->SetMarkerSize(1);
  IC_vs_phi[0]->SetMarkerColor(kBlue+2);
  
  IC_vs_phi[1] = new TGraphErrors();
  IC_vs_phi[1]->SetMarkerStyle(20);
  IC_vs_phi[1]->SetMarkerSize(1);
  IC_vs_phi[1]->SetMarkerColor(kBlue+2);

  TH1F* Spread_vs_phi[2][360];
  
  for (int k = 0; k < 2; k++){
    for (int iphi = 0; iphi < 360 ; iphi++){
      if (k==0)
      {
       sprintf(hname,"hspread_vs_phi%02d_EEP",iphi);
       Spread_vs_phi[k][iphi] = new TH1F(hname, hname, nbins,0.,2.);

      }
      else{ 
        sprintf(hname,"hspread_vs_ring%02d_EEM",iphi);
        Spread_vs_phi[k][iphi] = new TH1F(hname, hname, nbins,0.,2.);}
     } 
   }
  

  for (int k = 0; k < 2 ; k++){
    for (int ix = 1; ix < 101; ix++){
      for (int iy = 1; iy < 101; iy++){
	float iphibin;
        if((atan2(iy-50.,ix-50.)-int(atan2(iy-50.,ix-50.)))*(360./(2.*3.14159)) <0.5) iphibin=floor(180.+atan2(iy-50.,ix-50.)*(360./(2.*3.14159)));
        else iphibin=ceil(180.+atan2(iy-50.,ix-50.)*(360./(2.*3.14159)));
       
        if(iphibin>359) iphibin=359;
	int mybin = hcmap[k] -> FindBin(ix,iy);
	float ic = hcmap[k]->GetBinContent(mybin);          
	if ( ic>0 )    {
	 Spread_vs_phi[k][iphibin] ->Fill(ic);
	}
      }
    }
  }
 
 int N[2]={0};
  for (int k = 0; k < 2 ; k++){
    for (int iphi = 0; iphi < 360; iphi++){
      if (Spread_vs_phi[k][iphi]-> GetEntries() == 0) continue;
      IC_vs_phi[k]-> SetPoint(N[k],iphi,Spread_vs_phi[k][iphi]->GetMean());
      IC_vs_phi[k]-> SetPointError(N[k],0,Spread_vs_phi[k][iphi]->GetRMS()/sqrt(Spread_vs_phi[k][iphi]->GetEntries()));

      N[k]++;    
    }
  }
  */

 ///----------------- Statistical Precision  and Residual --------------------

    TGraphErrors *statprecision_vs_ring[3];
    statprecision_vs_ring[0]  = new TGraphErrors();
    statprecision_vs_ring[0]->SetMarkerStyle(20);
    statprecision_vs_ring[0]->SetMarkerSize(1);
    statprecision_vs_ring[0]->SetMarkerColor(kRed+2);

    statprecision_vs_ring[1]  = new TGraphErrors();
    statprecision_vs_ring[1]->SetMarkerStyle(20);
    statprecision_vs_ring[1]->SetMarkerSize(1);
    statprecision_vs_ring[1]->SetMarkerColor(kRed+2);

    statprecision_vs_ring[2]  = new TGraphErrors();
    statprecision_vs_ring[2]->SetMarkerStyle(20);
    statprecision_vs_ring[2]->SetMarkerSize(1);
    statprecision_vs_ring[2]->SetMarkerColor(kRed+2);
    
    TGraphErrors *residual_vs_ring[3];
    residual_vs_ring[0] = new TGraphErrors();
    residual_vs_ring[0]->SetMarkerStyle(20);
    residual_vs_ring[0]->SetMarkerSize(1);
    residual_vs_ring[0]->SetMarkerColor(kGreen+2);
  
    residual_vs_ring[1] = new TGraphErrors();
    residual_vs_ring[1]->SetMarkerStyle(20);
    residual_vs_ring[1]->SetMarkerSize(1);
    residual_vs_ring[1]->SetMarkerColor(kGreen+2);
  
    residual_vs_ring[2] = new TGraphErrors();
    residual_vs_ring[2]->SetMarkerStyle(20);
    residual_vs_ring[2]->SetMarkerSize(1);
    residual_vs_ring[2]->SetMarkerColor(kGreen+2);

  
  if (evalStat){
    
    /// acquisition file for statistical precision

    TFile *f2 = new TFile(infile2);
    TFile *f3 = new TFile(infile3);
    TH2F *hcmap2[2];
    hcmap2[0] = (TH2F*)f2->Get("h_scale_map_EEM"); 
    hcmap2[1] = (TH2F*)f2->Get("h_scale_map_EEP");

    TH2F *hcmap3[2];
    hcmap3[0] = (TH2F*)f3->Get("h_scale_map_EEM"); 
    hcmap3[1] = (TH2F*)f3->Get("h_scale_map_EEP");

    TH1F *hstatprecision[2][40];
    TH1F *hstatprecisionAll[40];

    /// stat precision histos for each EE ring
    for (int k = 0; k < 2; k++){
      for (int iring = 0; iring < 40 ; iring ++){
      
	if (k==0)
	 { sprintf(hname,"hstatprecisionAll_ring%02d",iring);
           hstatprecisionAll[iring] = new TH1F(hname, hname, nbins,-2.,2.);
           sprintf(hname,"hstatprecisionEEM_ring%02d",iring);
           hstatprecision[k][iring] = new TH1F(hname, hname, nbins,-2.,2.);
          }
	else {
	      sprintf(hname,"hstatprecisionEEP_ring%02d",iring);
              hstatprecision[k][iring] = new TH1F(hname, hname, nbins,-2.,2.);
            }

      }
    }
    
    for (int k = 0; k < 2 ; k++){
      for (int ix = 1; ix < 102; ix++){
	for (int iy = 1; iy < 102; iy++){
	  int iz = k;
	  if (k==0) iz = -1;
	  int mybin = hcmap2[k] -> FindBin(ix,iy);
	  int ring  = hrings[1]-> GetBinContent(mybin);
	  float ic1 = hcmap2[k]->GetBinContent(mybin);
	  float ic2 = hcmap3[k]->GetBinContent(mybin);
          if (ic1>0 && ic2 >0){
	    hstatprecision[k][ring]->Fill((ic1-ic2)/(ic1+ic2)); /// sigma (diff/sum) gives the stat. precision on teh entire sample
            hstatprecisionAll[ring]->Fill((ic1-ic2)/(ic1+ic2));
	  }
	}
      }
    }

  
    TCanvas* c44 [120];
    /// Gaussian fit of the even/odd distribution (rms of the distribution can be also used)
    int n[3] = {0};
    for (int k = 0; k < 2; k++){
      for (int iring = 0; iring < 40 ; iring++){
	if ( hstatprecision[k][iring]->GetEntries() == 0) continue;
	float e     = 0.5*hcmap2[k]-> GetYaxis()->GetBinWidth(1);
	fgaus->SetParameter(1,1);
	fgaus->SetParameter(2,hstatprecision[k][iring]->GetRMS());
	fgaus->SetRange(-5*hstatprecision[k][iring]->GetRMS(),5*hstatprecision[k][iring]->GetRMS());
	TString name = Form("ff%d_%d",iring,k);

        hstatprecision[k][iring]->Fit("fgaus","QR");
       
	statprecision_vs_ring[k]-> SetPoint(n[k],iring,fgaus->GetParameter(2));
	statprecision_vs_ring[k]-> SetPointError(n[k],e,fgaus->GetParError(2));
	n[k]++;
      }
    }
    
    for (int iring = 0; iring < 40 ; iring++){
	if ( hstatprecisionAll[iring]->GetEntries() == 0) continue;
	float e     = 0.5*hcmap2[0]-> GetYaxis()->GetBinWidth(1);
	fgaus->SetParameter(1,1);
	fgaus->SetParameter(2,hstatprecisionAll[iring]->GetRMS());
	fgaus->SetRange(-5*hstatprecisionAll[iring]->GetRMS(),5*hstatprecisionAll[iring]->GetRMS());
	TString name = Form("ffAll%d",iring);
        hstatprecisionAll[iring]->Fit("fgaus","QR");
       
	statprecision_vs_ring[2]-> SetPoint(n[2],iring,fgaus->GetParameter(2));
	statprecision_vs_ring[2]-> SetPointError(n[2],e,fgaus->GetParError(2));
	n[2]++;
      }
     
    
    TH1F *hresidual[3];
    hresidual[0] = new TH1F("hresidualEEM","hresidualEEM",1000,0,1);
    hresidual[1] = new TH1F("hresidualEEP","hresidualEEP",1000,0,1);
    hresidual[2] = new TH1F("hresidualAll","hresidualAll",1000,0,1);

    TH1F *hstat[3];
    hstat[0] = new TH1F("hstatEEM","hstatEEM",1000,0,0.5);
    hstat[1] = new TH1F("hstatEEP","hstatEEP",1000,0,0.5);
    hstat[2] = new TH1F("hstatAll","hstatAll",1000,0,0.5);
   
    TH1F *hspre[3];
    hspre[0] = new TH1F("hspreEEM","hspreEEM",1000,0,0.5);
    hspre[1] = new TH1F("hspreEEP","hspreEEP",1000,0,0.5);
    hspre[2] = new TH1F("hspreAll","hspreAll",1000,0,0.5);

    /// Residual spread plot

    for (int k = 0; k < 3 ; k++){
      for (int i= 0; i < statprecision_vs_ring[k]-> GetN(); i++){
	double spread, espread;
	double stat, estat;
	double residual, eresidual;
	double xdummy,ex;
	sigma_vs_ring[k]-> GetPoint(i, xdummy, spread );
	espread = sigma_vs_ring[k]-> GetErrorY(i);
	statprecision_vs_ring[k]-> GetPoint(i, xdummy, stat );
	estat = statprecision_vs_ring[k]-> GetErrorY(i);
	ex = statprecision_vs_ring[k]-> GetErrorX(i);
	if (spread > stat ){
	  residual  = sqrt( spread*spread - stat*stat );
	  eresidual = sqrt( pow(spread*espread,2) + pow(stat*estat,2))/residual;
	}
	else {
	  residual = 0;
	  eresidual = 0;
	}
	residual_vs_ring[k]->SetPoint(i,xdummy, residual);
	residual_vs_ring[k]->SetPointError(i,ex,eresidual);
      }
    }
 
 }
  
  ///-----------------------------------------------------------------
  ///--- Draw plots
  ///-----------------------------------------------------------------
  TCanvas *cEEP[12];
  TCanvas *cEEM[12];

  /// --- plot 0 : map of coefficients 
  cEEP[0] = new TCanvas("cmapEEP","cmapEEP");
  cEEP[0] -> cd();
  cEEP[0]->SetLeftMargin(0.1); 
  cEEP[0]->SetRightMargin(0.13); 
  cEEP[0]->SetGridx();
  cEEP[0]->SetGridy();
  //  hcmap[1]->GetXaxis()->SetNdivisions(1020);
  hcmap[1]->GetXaxis() -> SetLabelSize(0.03);
  hcmap[1]->Draw("COLZ");
  hcmap[1]->GetXaxis() ->SetTitle("ix");
  hcmap[1]->GetYaxis() ->SetTitle("iy");
  hcmap[1]->GetZaxis() ->SetRangeUser(0.8,1.2);

  cEEM[0] = new TCanvas("cmapEEM","cmapEEM");
  cEEM[0] -> cd();
  cEEM[0]->SetLeftMargin(0.1); 
  cEEM[0]->SetRightMargin(0.13); 
  cEEM[0]->SetGridx();
  cEEM[0]->SetGridy();
  //hcmap[0]->GetXaxis()->SetNdivisions(1020);
  hcmap[0]->GetXaxis() -> SetLabelSize(0.03);
  hcmap[0]->Draw("COLZ");
  hcmap[0]->GetXaxis() ->SetTitle("ix");
  hcmap[0]->GetYaxis() ->SetTitle("iy");
  hcmap[0]->GetZaxis() ->SetRangeUser(0.8,1.2);

  /// --- plot 1 : ring precision vs ieta
  cEEP[1] = new TCanvas("csigmaEEP","csigmaEEP");
  cEEP[1]->SetGridx();
  cEEP[1]->SetGridy();
  sigma_vs_ring[1]->GetHistogram()->GetYaxis()-> SetRangeUser(0.00,0.20);
  sigma_vs_ring[1]->GetHistogram()->GetXaxis()-> SetRangeUser(-85,85);
  sigma_vs_ring[1]->GetHistogram()->GetYaxis()-> SetTitle("#sigma_{c}");
  sigma_vs_ring[1]->GetHistogram()->GetXaxis()-> SetTitle("ring");
  sigma_vs_ring[1]->Draw("ap");
  if (evalStat){
    statprecision_vs_ring[1]->Draw("psame");
    sigma_vs_ring[1]->Draw("psame");
    TLegend * leg = new TLegend(0.6,0.7,0.89, 0.89);
    leg->SetFillColor(0);
    leg->AddEntry(statprecision_vs_ring[1],"statistical precision", "LP");
    leg->AddEntry(sigma_vs_ring[1],"spread", "LP");
    leg->Draw("same");
  }

  cEEM[1] = new TCanvas("csigmaEEM","csigmaEEM");
  cEEM[1]->SetGridx();
  cEEM[1]->SetGridy();
  sigma_vs_ring[0]->GetHistogram()->GetYaxis()-> SetRangeUser(0.00,0.20);
  sigma_vs_ring[0]->GetHistogram()->GetXaxis()-> SetRangeUser(-85,85);
  sigma_vs_ring[0]->GetHistogram()->GetYaxis()-> SetTitle("#sigma_{c}");
  sigma_vs_ring[0]->GetHistogram()->GetXaxis()-> SetTitle("ring");
  sigma_vs_ring[0]->Draw("ap");
  if (evalStat){
    statprecision_vs_ring[0]->Draw("psame");
    sigma_vs_ring[0]->Draw("psame");
    TLegend * leg = new TLegend(0.6,0.7,0.89, 0.89);
    leg->SetFillColor(0);
    leg->AddEntry(statprecision_vs_ring[0],"statistical precision", "LP");
    leg->AddEntry(sigma_vs_ring[0],"spread", "LP");
    leg->Draw("same");
  }


  /// --- plot 5 : statistical precision vs ieta
  if (evalStat){
    cEEP[5] = new TCanvas("cstat","cstat");
    cEEP[5]->SetGridx();
    cEEP[5]->SetGridy();
    statprecision_vs_ring[1]->GetHistogram()->GetYaxis()-> SetRangeUser(0.0001,0.10);
    statprecision_vs_ring[1]->GetHistogram()->GetXaxis()-> SetRangeUser(-85,85);
    statprecision_vs_ring[1]->GetHistogram()->GetYaxis()-> SetTitle("#sigma((c_{P}-c_{D})/(c_{P}+c_{D}))");
    statprecision_vs_ring[1]->GetHistogram()->GetXaxis()-> SetTitle("i#eta");
    statprecision_vs_ring[1]->Draw("ap");
    
    cEEP[6] = new TCanvas("cresidualP","cresidualP");
    cEEP[6]->SetGridx();
    cEEP[6]->SetGridy();
    residual_vs_ring[1]->GetHistogram()->GetYaxis()-> SetRangeUser(0.0001,0.10);
    residual_vs_ring[1]->GetHistogram()->GetXaxis()-> SetRangeUser(-85,85);
    residual_vs_ring[1]->GetHistogram()->GetYaxis()-> SetTitle("residual spread");
    residual_vs_ring[1]->GetHistogram()->GetXaxis()-> SetTitle("i#eta");
    residual_vs_ring[1]->Draw("ap");
 
    cEEM[5] = new TCanvas("cstatM","cstatM");
    cEEM[5]->SetGridx();
    cEEM[5]->SetGridy();
    statprecision_vs_ring[0]->GetHistogram()->GetYaxis()-> SetRangeUser(0.0001,0.10);
    statprecision_vs_ring[0]->GetHistogram()->GetXaxis()-> SetRangeUser(-85,85);
    statprecision_vs_ring[0]->GetHistogram()->GetYaxis()-> SetTitle("#sigma((c_{P}-c_{D})/(c_{P}+c_{D}))");
    statprecision_vs_ring[0]->GetHistogram()->GetXaxis()-> SetTitle("i#eta");
    statprecision_vs_ring[0]->Draw("ap");
    
    cEEM[6] = new TCanvas("cresidualM","cresidualM");
    cEEM[6]->SetGridx();
    cEEM[6]->SetGridy();
    residual_vs_ring[0]->GetHistogram()->GetYaxis()-> SetRangeUser(0.0001,0.10);
    residual_vs_ring[0]->GetHistogram()->GetXaxis()-> SetRangeUser(-85,85);
    residual_vs_ring[0]->GetHistogram()->GetYaxis()-> SetTitle("residual spread");
    residual_vs_ring[0]->GetHistogram()->GetXaxis()-> SetTitle("i#eta");
    residual_vs_ring[0]->Draw("ap");
 
    cEEP[8] = new TCanvas("csigmaFolded","csigmaFolded");
    cEEP[8]->SetGridx();
    cEEP[8]->SetGridy();
    sigma_vs_ring[2]->GetHistogram()->GetYaxis()-> SetRangeUser(0.00,0.20);
    sigma_vs_ring[2]->GetHistogram()->GetXaxis()-> SetRangeUser(-85,85);
    sigma_vs_ring[2]->GetHistogram()->GetYaxis()-> SetTitle("#sigma_{c}");
    sigma_vs_ring[2]->GetHistogram()->GetXaxis()-> SetTitle("ring");
    sigma_vs_ring[2]->Draw("ap");
    if (evalStat){
    statprecision_vs_ring[2]->Draw("psame");
    sigma_vs_ring[2]->Draw("psame");
    TLegend * leg = new TLegend(0.6,0.7,0.89, 0.89);
    leg->SetFillColor(0);
    leg->AddEntry(statprecision_vs_ring[2],"statistical precision", "LP");
    leg->AddEntry(sigma_vs_ring[2],"spread", "LP");
    leg->Draw("same");
    }

    cEEP[9] = new TCanvas("cresidualFolded","cresidualFolded");
    cEEP[9]->SetGridx();
    cEEP[9]->SetGridy();
    residual_vs_ring[2]->GetHistogram()->GetYaxis()-> SetRangeUser(0.0001,0.10);
    residual_vs_ring[2]->GetHistogram()->GetXaxis()-> SetRangeUser(-85,85);
    residual_vs_ring[2]->GetHistogram()->GetYaxis()-> SetTitle("residual spread");
    residual_vs_ring[2]->GetHistogram()->GetXaxis()-> SetTitle("i#eta");
    residual_vs_ring[2]->Draw("ap");

    /// save precision for MC comparison

    if(isMC==true)
    {
     TFile * output = new TFile ("StatPrec_MC_EE.root","RECREATE");
     output->cd();
     statprecision_vs_ring[0]->SetName("gr_stat_prec_EEP");
     statprecision_vs_ring[1]->SetName("gr_stat_prec_EEM");
     statprecision_vs_ring[2]->SetName("gr_stat_prec");

     statprecision_vs_ring[0]->Write();
     statprecision_vs_ring[1]->Write();
     statprecision_vs_ring[2]->Write();
    }
  }
 
  /// Comparison Plot MC - Data
  TCanvas* canEEP[10], *canEEM[10];
  if(isMC == true)
  {
 
   canEEM[0] = new TCanvas("ICComparison MC EEM","ICComparison MC EEM");
   canEEM[0]->SetGridx();
   canEEM[0]->SetGridy();
   ICComparison[0]->GetXaxis() -> SetLabelSize(0.03);
   ICComparison[0]->Draw("COLZ");
   ICComparison[0]->GetXaxis() ->SetTitle("ix");
   ICComparison[0]->GetYaxis() ->SetTitle("iy");
   ICComparison[0]->GetZaxis() ->SetRangeUser(0.85,1.15);
 
   canEEP[0] = new TCanvas("ICComparison MC EEP","ICComparison MC EEP");
   canEEP[0]->SetGridx();
   canEEP[0]->SetGridy();
   ICComparison[1]->GetXaxis() -> SetLabelSize(0.03);
   ICComparison[1]->Draw("COLZ");
   ICComparison[1]->GetXaxis() ->SetTitle("ix");
   ICComparison[1]->GetYaxis() ->SetTitle("iy");
   ICComparison[1]->GetZaxis() ->SetRangeUser(0.85,1.15);

   TFile* output = new TFile ("IC_MC_4Correction.root","RECREATE");
   output->cd();
   ICComparison[0]->Write();
   ICComparison[1]->Write();
   output->Close();
  }

  TFile *exisistingEE = new TFile ("existingEE.root","READ");
  TH2F* exmap = (TH2F*) exisistingEE->Get("endcap");

  TH2F* warning_Map_EEP = (TH2F*) exmap->Clone("warning_Map_EEP");
  warning_Map_EEP->Reset("ICMES");
  warning_Map_EEP->Reset();

  TH2F* warning_Map_EEM = (TH2F*) exmap->Clone("warning_Map_EEM");
  warning_Map_EEM->Reset("ICMES");
  warning_Map_EEM->Reset();


  if(isMC == false)
  {
   std::ofstream outTxt ("Calibration_Coefficient_EE_dinamic_alpha.txt",std::ios::out);

   outTxt << "---------------------------------------------------------------" << std::endl;
   outTxt << std::fixed << std::setprecision(0) << std::setw(10) << "iX"
          << std::fixed << std::setprecision(0) << std::setw(10) << "iY"
          << std::fixed << std::setprecision(0) << std::setw(10) << "iZ"
          << std::fixed << std::setprecision(6) << std::setw(15) << "IC"
          << std::fixed << std::setprecision(6) << std::setw(15) << "error"
          << std::endl;
   outTxt << "---------------------------------------------------------------" << std::endl;

   for (int ix = 1; ix < hcmap[0]->GetNbinsX()+1 ; ix ++)
     {
       for (int iy = 1; iy < hcmap[0] -> GetNbinsY()+1; iy++)
	 {
	   if( exmap->GetBinContent(ix,iy) !=1) continue;
	   
	   double x,statPrec;
	   statprecision_vs_ring[0]->GetPoint(hrings[0]->GetBinContent(ix,iy),x,statPrec);
	   
	   outTxt << std::fixed << std::setprecision(0) << std::setw(10) << hcmap[0]->GetXaxis()->GetBinLowEdge(ix)
		  << std::fixed << std::setprecision(0) << std::setw(10) << hcmap[0]->GetYaxis()->GetBinLowEdge(iy)
		  << std::fixed << std::setprecision(0) << std::setw(10) << "-1";
	   
	   if( hcmap[0]->GetBinContent(ix,iy) == 0. )
	     {  
               outTxt << std::fixed << std::setprecision(6) << std::setw(15) << "-1."
                      << std::fixed << std::setprecision(6) << std::setw(15) << "999."
                      << std::endl;
	     }
	   else
	     {
	       outTxt << std::fixed << std::setprecision(6) << std::setw(15) << hcmap[0]->GetBinContent(ix,iy)
		      << std::fixed << std::setprecision(6) << std::setw(15) << statPrec
		      << std::endl;
	       
	       //warning_Map_EEM->Fill(ix,iy);
	     }
	  
	}
    }
    
    for (int ix = 1; ix < hcmap[1]->GetNbinsX()+1 ; ix ++)
      {
	for (int iy = 1; iy < hcmap[1] -> GetNbinsY()+1; iy++)
	  {
	    if( exmap->GetBinContent(ix,iy) !=1) continue;
	    
	    double x,statPrec;
	    statprecision_vs_ring[1]->GetPoint(hrings[1]->GetBinContent(ix,iy),x,statPrec);
	    
	    outTxt << std::fixed << std::setprecision(0) << std::setw(10) << hcmap[1]->GetXaxis()->GetBinLowEdge(ix)
		   << std::fixed << std::setprecision(0) << std::setw(10) << hcmap[1]->GetYaxis()->GetBinLowEdge(iy)
		   << std::fixed << std::setprecision(0) << std::setw(10) << "1";
	    
	    if( hcmap[1]->GetBinContent(ix,iy) == 0. )
	      {
		outTxt << std::fixed << std::setprecision(6) << std::setw(15) << "-1."
		       << std::fixed << std::setprecision(6) << std::setw(15) << "999."
		       << std::endl;
	      }
	    else
	      {
		outTxt << std::fixed << std::setprecision(6) << std::setw(15) << hcmap[1]->GetBinContent(ix,iy)
		       << std::fixed << std::setprecision(6) << std::setw(15) << statPrec
		       << std::endl;
		
		//warning_Map_EEM->Fill(ix,iy);                                                                                                                               
	      }
	    
	  }
      }
  }
  
  
  canEEP[1] = new TCanvas("Warning_EEP","Warning_EEP");
  canEEP[1]->SetGridx();
  canEEP[1]->SetGridy();
  warning_Map_EEP->GetXaxis() -> SetLabelSize(0.03);
  warning_Map_EEP->Draw("COLZ");
  warning_Map_EEP->GetXaxis() ->SetTitle("ix");
  warning_Map_EEP->GetYaxis() ->SetTitle("iy");
  warning_Map_EEP->GetZaxis() ->SetRangeUser(0.85,1.15);

  canEEM[1] = new TCanvas("Warning_EEM","Warning_EEM");
  canEEM[1]->SetGridx();
  canEEM[1]->SetGridy();
  warning_Map_EEM->GetXaxis() -> SetLabelSize(0.03);
  warning_Map_EEM->Draw("COLZ");
  warning_Map_EEM->GetXaxis() ->SetTitle("ix");
  warning_Map_EEM->GetYaxis() ->SetTitle("iy");
  warning_Map_EEM->GetZaxis() ->SetRangeUser(0.85,1.15);



}
void DoAnalysisWithTree(TFile* file, int run, int x, int y)
{

  gout << 0 << " " << run << " " << x << " " << y << " ";

  TF1* flandau = new TF1("flandau","landau",0,400);

  TCanvas *c1 = new TCanvas("c1","",1280,960);
  c1->Divide(4,2);

  TCanvas *c2 = new TCanvas("c2","",1280,960);
  c2->Divide(4,2);

  TCanvas *c3 = new TCanvas("c3","",1280,960);
  c3->Divide(4,2);

  TCanvas *c4 = new TCanvas("c4","",1280,960);
  c4->Divide(4,2);

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

  tree->SetAlias("Average_HODO_HORIZONTAL","Sum$(TOWER_CALIB_HODO_HORIZONTAL.towerid * (abs(TOWER_CALIB_HODO_HORIZONTAL.energy)>30) * abs(TOWER_CALIB_HODO_HORIZONTAL.energy))/Sum$((abs(TOWER_CALIB_HODO_HORIZONTAL.energy)>30) * abs(TOWER_CALIB_HODO_HORIZONTAL.energy))");
  tree->SetAlias("Average_HODO_VERTICAL","Sum$(TOWER_CALIB_HODO_VERTICAL.towerid * (abs(TOWER_CALIB_HODO_VERTICAL.energy)>30) * abs(TOWER_CALIB_HODO_VERTICAL.energy))/Sum$((abs(TOWER_CALIB_HODO_VERTICAL.energy)>30) * abs(TOWER_CALIB_HODO_VERTICAL.energy))");
  tree->SetAlias("Valid_HODO_HORIZONTAL","Sum$(abs(TOWER_CALIB_HODO_HORIZONTAL.energy)>30) > 0");
  tree->SetAlias("Valid_HODO_VERTICAL","Sum$(abs(TOWER_CALIB_HODO_VERTICAL.energy)>30) > 0");

  ofstream fout((const char*)Form("DataRunByRun/mapper_run%d.dat",run));

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

      TString drawstring1 = "TOWER_CALIB_TILE_MAPPER[";
      drawstring1 += i*2;
      drawstring1 += "].energy>>hs1_";
      drawstring1 += i+1;
      drawstring1 += "(100,0,400)";

      c1->cd(i+1);
      tree->Fit("flandau",drawstring1,"","","");

      TString drawstring2 = "TOWER_CALIB_TILE_MAPPER[";
      drawstring2 += i*2;
      drawstring2 += "].energy>>hs2_";
      drawstring2 += i+1;
      drawstring2 += "(100,0,400)";

      c2->cd(i+1);
      tree->Fit("flandau",drawstring2,"Valid_HODO_VERTICAL && Valid_HODO_HORIZONTAL","","");
      fout << run << " " << 9999 << " " << 9999 << " " << flandau->GetParameter(1) << " " << flandau->GetParError(1) << endl;
      gout << flandau->GetParameter(1) << " " << flandau->GetParError(1) << " ";

      TString drawstring3 = "TOWER_CALIB_TILE_MAPPER[";
      drawstring3 += i*2;
      drawstring3 += "].energy>>hs3_";
      drawstring3 += i+1;
      drawstring3 += "(100,0,400)";

      c3->cd(i+1);
      tree->Fit("flandau",drawstring3,"Valid_HODO_VERTICAL && Valid_HODO_HORIZONTAL && abs(TOWER_CALIB_C2[3].energy)<200","","");

      TString drawstring4 = "TOWER_CALIB_TILE_MAPPER[";
      drawstring4 += i*2;
      drawstring4 += "].energy>>hs4_";
      drawstring4 += i+1;
      drawstring4 += "(100,0,400)";

      c4->cd(i+1);
      tree->Fit("flandau",drawstring4,"Valid_HODO_VERTICAL && Valid_HODO_HORIZONTAL && abs(TOWER_CALIB_C2[3].energy)>200","","");

    }

  c1->Print(Form("FigsRunByRun/mapper_run%d_step1.png",run));
  c2->Print(Form("FigsRunByRun/mapper_run%d_step2.png",run));
  c3->Print(Form("FigsRunByRun/mapper_run%d_step3.png",run));
  c4->Print(Form("FigsRunByRun/mapper_run%d_step4.png",run));
  c1->Print(Form("FigsRunByRun/mapper_run%d_step1.pdf",run));
  c2->Print(Form("FigsRunByRun/mapper_run%d_step2.pdf",run));
  c3->Print(Form("FigsRunByRun/mapper_run%d_step3.pdf",run));
  c4->Print(Form("FigsRunByRun/mapper_run%d_step4.pdf",run));

  delete c1;
  delete c2;
  delete c3;
  delete c4;

  gout << endl;

  return;

  // --- let's try to have a look at the hodoscope positions

  TCanvas* c5 = new TCanvas("c5","",800,800);
  TH2D* th2d_hodo_fine = new TH2D("th2d_hodo_fine","",40,-0.5,7.5,40,-0.5,7.5);
  TH2D* th2d_hodo_coarse = new TH2D("th2d_hodo_coarse","",8,-0.5,7.5,8,-0.5,7.5);
  th2d_hodo_fine->GetXaxis()->SetTitle("Horizontal Hodoscope");
  th2d_hodo_fine->GetYaxis()->SetTitle("Vertical Hodoscope");
  th2d_hodo_coarse->GetXaxis()->SetTitle("Horizontal Hodoscope");
  th2d_hodo_coarse->GetYaxis()->SetTitle("Vertical Hodoscope");
  tree->Draw("Average_HODO_HORIZONTAL:Average_HODO_VERTICAL>>th2d_hodo_fine","Valid_HODO_VERTICAL && Valid_HODO_HORIZONTAL","colz");
  c5->Print(Form("FigsRunByRun/hodoscope_fine_run%d.png",run));
  c5->Print(Form("FigsRunByRun/hodoscope_fine_run%d.pdf",run));
  tree->Draw("Average_HODO_HORIZONTAL:Average_HODO_VERTICAL>>th2d_hodo_coarse","Valid_HODO_VERTICAL && Valid_HODO_HORIZONTAL","colz");
  c5->Print(Form("FigsRunByRun/hodoscope_coarse_run%d.png",run));
  c5->Print(Form("FigsRunByRun/hodoscope_coarse_run%d.pdf",run));
  delete c5;

  // --- now lets try to look at the distributions for each hodoscope position

  TCanvas* c6 = new TCanvas("c6","",1280,960);
  c6->Divide(4,2);

  for ( int indexHorizontal = 0; indexHorizontal < 8; ++indexHorizontal)
    {
      for ( int indexVertical = 0; indexVertical < 8; ++indexVertical )
        {
          for ( int indexTile = 0; indexTile < 8; ++indexTile )
            {
              TString drawstring = "TOWER_CALIB_TILE_MAPPER[";
              drawstring += indexTile*2;
              drawstring += "].energy>>hs_";
              drawstring += indexTile+1;
              drawstring += "(100,0,400)";
              cout << "drawstring is " << drawstring << endl;

              TString cutstring = "Valid_HODO_VERTICAL && Valid_HODO_HORIZONTAL";
              cutstring += " && abs(Average_HODO_HORIZONTAL-";
              cutstring += indexHorizontal;
              cutstring += ")<0.5";
              cutstring += " && abs(Average_HODO_VERTICAL-";
              cutstring += indexVertical;
              cutstring += ")<0.5";
              cout << "cutstring is " << cutstring << endl;

              c6->cd(indexTile+1);
              tree->Fit("flandau",drawstring,cutstring,"","");
              fout << run << " " << indexHorizontal << " " << indexVertical << " " << flandau->GetParameter(1) << " " << flandau->GetParError(1) << endl;
            }
          c6->Print(Form("FigsRunByRun/HodoscopeGridFigs/mapper_run%d_H%dV%d.png",run,indexHorizontal,indexVertical));
          c6->Print(Form("FigsRunByRun/HodoscopeGridFigs/mapper_run%d_H%dV%d.pdf",run,indexHorizontal,indexVertical));
        }
    }
  fout.close();

  delete c6;

}
Example #9
0
double extractLimitAtQuantile(TString inFileName, TString plotName, double d_quantile ){
	TFile *f = TFile::Open(inFileName);
	TF1 *expoFit = new TF1("expoFit","[0]*exp([1]*(x-[2]))", rMin, rMax);
	TGraphErrors *limitPlot_ =  new TGraphErrors();

/* 	bool done = false; */
	if (_debug > 0) std::cout << "Search for upper limit using pre-computed grid of p-values" << std::endl;

	readAllToysFromFile(limitPlot_, f, d_quantile ); 
	f->Close();
	limitPlot_->Sort();
	double minDist=1e3;
	int n= limitPlot_->GetN();
	cout<<" Number of points in limitPlot_ : "<<n<<endl;
	if(n<=0) return 0;

	clsMin.first=0;
	clsMin.second=0;
	clsMax.first=0;
	clsMax.second=0;

	limit = 0; limitErr = 0;
	for (int i = 0; i < n; ++i) {
		double x = limitPlot_->GetX()[i], y = limitPlot_->GetY()[i]; //, ey = limitPlot_->GetErrorY(i);
		if (fabs(y-clsTarget) < minDist) { limit = x; minDist = fabs(y-clsTarget); }
	}
	int ntmp =0;
	for (int j = 0; j < n; ++j) {
		int i = n-j-1;
		double x = limitPlot_->GetX()[i], y = limitPlot_->GetY()[i], ey = limitPlot_->GetErrorY(i);
		if (y-3*ey >= clsTarget && ntmp<=2) { 
			rMin = x; clsMin = CLs_t(y,ey); 
			ntmp ++ ;
		}
	}
	ntmp =0;
	for (int i = 0; i < n; ++i) {
		double x = limitPlot_->GetX()[i], y = limitPlot_->GetY()[i], ey = limitPlot_->GetErrorY(i);
		if (y+3*ey <= clsTarget && ntmp<=2) {
		       	rMax = x; clsMax = CLs_t(y,ey);
			ntmp ++ ;
		}
	}
	if((clsMin.first==0 and clsMin.second==0) )
	{
		rMin = limitPlot_->GetX()[0]; clsMin=CLs_t(limitPlot_->GetY()[0], limitPlot_->GetErrorY(0)); 
	}
	if((clsMax.first==0 and clsMax.second==0))
	{
		rMax = limitPlot_->GetX()[n-1]; clsMax=CLs_t(limitPlot_->GetY()[n-1], limitPlot_->GetErrorY(n-1));
	}

	if (_debug > 0) std::cout << " after scan x ~ " << limit << ", bounds [ " << rMin << ", " << rMax << "]" << std::endl;
	limitErr = std::max(limit-rMin, rMax-limit);
	expoFit->SetRange(rMin,rMax);
	//expoFit.SetRange(limitPlot_->GetXaxis()->GetXmin(),limitPlot_->GetXaxis()->GetXmax());
	//expoFit->SetRange(1.7,2.25);

	if (limitErr < std::max(rAbsAccuracy_, rRelAccuracy_ * limit)) {
		if (_debug > 1) std::cout << "  reached accuracy " << limitErr << " below " << std::max(rAbsAccuracy_, rRelAccuracy_ * limit) << std::endl;
/* 		done = true;  */
	}

	//if (!done) { // didn't reach accuracy with scan, now do fit
	if (1) { // didn't reach accuracy with scan, now do fit
		if (_debug) {
			std::cout << "\n -- HybridNew, before fit -- \n";
			std::cout << "Limit: r" << " < " << limit << " +/- " << limitErr << " [" << rMin << ", " << rMax << "]\n";

			std::cout<<"rMin="<<rMin<<" clsMin="<<clsMin.first<<",  rMax="<<rMax<<" clsMax="<<clsMax.first<<endl;
		}

		expoFit->FixParameter(0,clsTarget);
		expoFit->SetParameter(1,log(clsMax.first/clsMin.first)/(rMax-rMin));
		expoFit->SetParameter(2,limit);
		double rMinBound, rMaxBound; expoFit->GetRange(rMinBound, rMaxBound);
		limitErr = std::max(fabs(rMinBound-limit), fabs(rMaxBound-limit));
		int npoints = 0; 
		for (int j = 0; j < limitPlot_->GetN(); ++j) { 
			if (limitPlot_->GetX()[j] >= rMinBound && limitPlot_->GetX()[j] <= rMaxBound) npoints++; 
		}
		for (int i = 0, imax = 0; i <= imax; ++i, ++npoints) {
			limitPlot_->Sort();
			limitPlot_->Fit(expoFit,(_debug <= 1 ? "QNR EX0" : "NR EXO"));
			if (_debug) {
				std::cout << "Fit to " << npoints << " points: " << expoFit->GetParameter(2) << " +/- " << expoFit->GetParError(2) << std::endl;
			}

			// only when both  "cls+3e<0.05 and cls-3e>0.05" are satisfied, we require below ...
			//	if ((rMin < expoFit->GetParameter(2))  && (expoFit->GetParameter(2) < rMax) && (expoFit->GetParError(2) < 0.5*(rMaxBound-rMinBound))) { 
			// sanity check fit result
			limit = expoFit->GetParameter(2);
			limitErr = expoFit->GetParError(2);
			if (limitErr < std::max(rAbsAccuracy_, rRelAccuracy_ * limit)) break;
			//	}
		} 
	}

	if (limitPlot_) {
		TCanvas *c1 = new TCanvas("c1","c1");
		limitPlot_->Sort();
		limitPlot_->SetLineWidth(2);
		double rMinBound, rMaxBound; expoFit->GetRange(rMinBound, rMaxBound);
		if(bPlotInFittedRange){
			limitPlot_->GetXaxis()->SetRangeUser(rMinBound, rMaxBound);
			limitPlot_->GetYaxis()->SetRangeUser(0.5*clsTarget, 1.5*clsTarget);
		}
		limitPlot_->Draw("AP");
		expoFit->Draw("SAME");
		TLine line(limitPlot_->GetX()[0], clsTarget, limitPlot_->GetX()[limitPlot_->GetN()-1], clsTarget);
		line.SetLineColor(kRed); line.SetLineWidth(2); line.Draw();
		line.DrawLine(limit, 0, limit, limitPlot_->GetY()[0]);
		line.SetLineWidth(1); line.SetLineStyle(2);
		line.DrawLine(limit-limitErr, 0, limit-limitErr, limitPlot_->GetY()[0]);
		line.DrawLine(limit+limitErr, 0, limit+limitErr, limitPlot_->GetY()[0]);
		limitPlot_->SetTitle(";#mu;CLs");
		c1->Print(plotName+".gif");
		c1->Print(plotName+".root");

		if(_debug)limitPlot_->Print("v");
	}

	std::cout << "\n -- Hybrid New -- \n";
	if(limit<0) { limit=0; cout<<"  WARNING: fitted limit <0,   need more toys and more points of signal strength"<<endl; }
	std::cout << "Limit: r" << " < " << limit << " +/- " << limitErr << " @ " << (1-clsTarget) * 100 << "% CL\n";
	return limit;
}
Example #10
0
void mk_sigaccjecupdown(string flavor = "112",  const string uncert = "jec")
{
    // gStyle->SetOptFit(1100); // chi2 and prob, not parameters
    // gStyle->SetOptFit(1); // chi2 and prob, not parameters
    // gStyle->SetOptStat("irme"); // integral, RMS, mean, # of entries
    // gStyle->SetStatFontSize(0.005);
    // gStyle->SetStatY(0.4);
    TLatex *   tex = new TLatex(0.678392,0.9283217,"CMS Preliminary 9.95 fb^{-1} at #sqrt{s}  =  8 TeV");
    tex->SetNDC();
    tex->SetTextAlign(22);
    tex->SetTextFont(42);
    // tex->SetTextSize(0.03846154);
    tex->SetLineWidth(2);
    cout<<"blabl"<<endl;
    // for(int k=0; k<3; k++){
    // for(int k=0; k<2; k++){
    for(int k=2; k<3; k++) {
        //Which plots to make
        //define input variables
        vector <string > namelist;
        vector <string > VarList;
        vector <TFile* > data;
        vector <TFile* > filelist;
        vector <TFile* > filelist_btag;
        vector <TFile* > filelist_2D;
        vector <TFile* > filelist_kin;
        vector <TFile* > filelist_param;
        vector <TFile* > filelist_diag;
        vector <TFile* > filelist_stealth;
        vector <TFile* > filelist0b;
        vector <float > EvtGen;
        vector <float > Xsec;
        vector <float > GlunioMass;

        vector<float> nEvtTot;
        vector<float> McXsec;
        vector<float> lumis;
        vector<float> DataLumi;
        vector<float> GaussMeanIni;
        vector<float> LeftEdge;
        vector<float> RightEdge;
        vector<vector<float  > > MassBins;

        // string uncert="btagup";
        // if(k==1) uncert="btagdown";
        // if(k==1) uncert="down";
        // if(k==2) uncert="";

        namelist.push_back("KinematicOptimization");
        // filelist_kin.push_back(TFile::Open(("Acc_Gluino_NoLumi_pt110_8TeVxsec_BtagMap_2500GeV"+uncert+".root").c_str()));
        // filelist_kin.push_back(TFile::Open("Acc_Gluino_NoLumi_pt60_pt110_8TeVxsec_BtagMap.root"));
        // filelist_kin.push_back(TFile::Open(("Acc_RPV112" + uncert + ".root").c_str()));
        filelist_kin.push_back(TFile::Open(("Acc_RPV" + flavor + "_Sph4.root").c_str()));
        filelist_kin.push_back(TFile::Open(("Acc_RPV" + flavor + uncert +  "up_Sph4.root").c_str()));
        filelist_kin.push_back(TFile::Open(("Acc_RPV" + flavor + uncert +  "down_Sph4.root").c_str()));
//   filelist_kin.push_back(TFile::Open(("Acc_Gluino_NoLumi_pt60_pt110_8TeVxsec_BtagMap" + uncert + ".root").c_str()));

        TFile f1(("RPV_" + flavor + "_accandwdith"+uncert+".root").c_str(), "recreate");
        f1.cd();

        string nameIN;
        string cuts;
        string prefix;
        string postfix;
        string folder;
        string ptcut;
        folder="plots/";
        postfix=".pdf";
        /////////////Plots for each Mass separatly//////////////
        /////////////----------------------------------------/////////////

        for (int p = 0; p < 2; p++) {
            // ptcut="112";
            // if(p==1) ptcut="" + flavor;
            ptcut="60";
            if(p==1) ptcut="110";
            ///////////////////////////////////////////////////////////////////
            ///////////Plot nice Mjjj plots
            //////////////////////////////////////////////////////////////////
            // string histname = string("GausWidth_vs_Mass_112") + ptcut;
            string histname = string("GausWidth_vs_Mass_" + flavor) + "_" + ptcut;
            cout<< histname << endl;
            TGraphErrors *h_gauswidth = (TGraphErrors*) filelist_kin[0]->Get(histname.c_str())->Clone();
            TGraphErrors *h_gauswidthup = (TGraphErrors*) filelist_kin[1]->Get(histname.c_str())->Clone();
            TGraphErrors *h_gauswidthdown = (TGraphErrors*) filelist_kin[2]->Get(histname.c_str())->Clone();
            histname = string("GausAcceptance_vs_Mass_" + flavor) + "_" + ptcut;
            // histname = string("GausAcceptance_vs_Mass_112") + ptcut;
            cout<< histname << endl;
            TGraphErrors *h_gausacc = (TGraphErrors*) filelist_kin[0]->Get(histname.c_str())->Clone();
            TGraphErrors *h_gausaccup = (TGraphErrors*) filelist_kin[1]->Get(histname.c_str())->Clone();
            TGraphErrors *h_gausaccdown = (TGraphErrors*) filelist_kin[2]->Get(histname.c_str())->Clone();

            TCanvas * cGluinoFitsOpti = new TCanvas(("RPV_"+ptcut+"_"+cuts).c_str(), ("RPV_" + ptcut+"_"+cuts).c_str(), 800, 600);
            //h_gauswidth->SetFillColor(kOrange-2);
            // h_gauswidth->SetLineColor(kBlack);
            string title;
            string systematic = "pile-up";
            // title="Gaussian Width vs. Mass for Light-ptcut RPV";
            string tag = "Heavy", sphericity = " Sphericity Cut";
            if (flavor.compare("112") == 0)
                tag = "Light";
            else if (ptcut == "60")
                sphericity = "";
            string titlepart = tag + "-flavor RPV " + flavor + " p_{T} = " + ptcut + sphericity;
            title = "Width for " + titlepart;
            /*
            if(k==0){
            title="RPV gluino #bf{" + systematic + " up} m="+to_string(masses[i])+", ptcut = "+ptcut+", #Delta = 110 GeV, #bf{6^{th} Jet p_{T} = 60 GeV}";
            if (i>=5 || p==0) title="RPV gluino #bf{" + systematic + " up} m="+to_string(masses[i])+", ptcut = "+ptcut+", #Delta = 110 GeV, #bf{6^{th} Jet p_{T} = 110 GeV}";
            }

            		if(k==1){
            title="RPV gluino #bf{" + systematic + " down} m="+to_string(masses[i])+", ptcut = "+ptcut+", #Delta = 110 GeV, #bf{6^{th} Jet p_{T} = 60 GeV}";
            if (i>=5 || p==0) title="RPV gluino #bf{" + systematic + " down} m="+to_string(masses[i])+", ptcut = "+ptcut+", #Delta = 110 GeV, #bf{6^{th} Jet p_{T} = 110 GeV}";
            		}

            				if(k==2){
            title="RPV gluino m="+to_string(masses[i])+", ptcut = "+ptcut+", #Delta = 110 GeV, #bf{6^{th} Jet p_{T} = 60 GeV}";
            if (i>=5 || p==0) title="RPV gluino m="+to_string(masses[i])+", ptcut = "+ptcut+", #Delta = 110 GeV, #bf{6^{th} Jet p_{T} = 110 GeV}";
            				}
            				*/
            TLegend *leg;
            leg = new TLegend(0.6,0.2,0.8994975,0.5,NULL,"brNDC");
            float linesiz = 2.0;
            h_gauswidthup->SetLineColor(kBlue);
            h_gauswidthup->SetLineWidth(linesiz);
            h_gauswidthup->SetMarkerColor(kBlue);
            TF1 *fitfunc = h_gauswidthup->GetFunction("GausWidth");
            if (fitfunc != NULL)
                fitfunc->SetLineColor(kBlue);
            leg->AddEntry(h_gauswidthup,"JES up", "L");
            h_gauswidthup->GetYaxis()->SetTitle("Width [GeV]");
            h_gauswidthup->GetYaxis()->SetTitleOffset(1.3);
            h_gauswidthup->GetXaxis()->SetTitle("RPV Mass [GeV]");
            h_gauswidthup->SetTitle(title.c_str());
            h_gauswidthup->Draw("A*");
            fitfunc = h_gauswidth->GetFunction("GausWidth");
            if (fitfunc != NULL)
                fitfunc->SetLineColor(kBlack);
            else cout << "Bad func name\n";
            h_gauswidth->SetLineColor(kBlack);
            h_gauswidth->SetMarkerColor(kBlack);
            h_gauswidth->SetLineWidth(linesiz);
            // h_gauswidth->SetTitleSize(0.01);
            // h_gauswidth->Draw("AL");
            leg->AddEntry(h_gauswidth,"Nominal JES", "L");
            h_gauswidth->Draw("same*");
            h_gauswidthdown->SetLineWidth(linesiz);
            h_gauswidthdown->SetMarkerColor(kRed);
            h_gauswidthdown->SetLineColor(kRed);
            fitfunc = h_gauswidthdown->GetFunction("GausWidth");
            if (fitfunc != NULL)
                fitfunc->SetLineColor(kRed);
            leg->AddEntry(h_gauswidthdown,"JES down", "L");
            h_gauswidthdown->Draw("same*");
            leg->Draw();
            cGluinoFitsOpti->Write();
            cGluinoFitsOpti->SaveAs((folder + "RPVwidthjesupdn" +flavor + ptcut+uncert+postfix).c_str());
            TCanvas * cGluinoFitsOpt2 = new TCanvas(("RPVacc_"+ptcut+"_"+cuts).c_str(), ("RPV_" + ptcut+"_"+cuts).c_str(), 800, 600);
            leg = new TLegend(0.6,0.2,0.8994975,0.5,NULL,"brNDC");
            title="Acceptance for " + titlepart;
            h_gausacc->SetTitle(title.c_str());
            h_gausacc->GetYaxis()->SetTitle("Acceptance");
            h_gausacc->GetYaxis()->SetTitleOffset(1.4);
            h_gausacc->GetXaxis()->SetTitle("RPV Mass [GeV]");
            // if (flavor.compare("113_223") == 0 && ptcut == "110") {
            // gStyle->SetStatY(0.8);
            // h_gausacc->GetYaxis()->SetRangeUser(0.0, 0.035);
            //}

            fitfunc = h_gausacc->GetFunction("total");
            if (fitfunc != NULL)
                fitfunc->SetLineColor(kBlack);
            else cout << "Bad func name\n";
            h_gausacc->SetLineColor(kBlack);
            h_gausacc->SetMarkerColor(kBlack);
            h_gausacc->SetLineWidth(linesiz);
            leg->AddEntry(h_gausacc,"Nominal JES", "L");
            // h_gausacc->Draw("AL");
            h_gausacc->Draw("A*");
            fitfunc = h_gausaccup->GetFunction("total");
            if (fitfunc != NULL)
                fitfunc->SetLineColor(kBlue);
            else cout << "Bad func name\n";
            h_gausaccup->SetLineColor(kBlue);
            h_gausaccup->SetMarkerColor(kBlue);
            h_gausaccup->SetLineWidth(linesiz);
            leg->AddEntry(h_gausaccup,"JES up", "L");
            h_gausaccup->Draw("same*");
            fitfunc = h_gausaccdown->GetFunction("total");
            if (fitfunc != NULL)
                fitfunc->SetLineColor(kRed);
            else cout << "Bad func name\n";
            h_gausaccdown->SetLineColor(kRed);
            h_gausaccdown->SetMarkerColor(kRed);
            h_gausaccdown->SetLineWidth(linesiz);
            leg->AddEntry(h_gausaccdown,"JES down", "L");
            h_gausaccdown->Draw("same*");
            leg->Draw();

            cGluinoFitsOpt2->Write();
            cGluinoFitsOpt2->SaveAs((folder + "RPVaccjesupdn" +flavor + ptcut+uncert+postfix).c_str());
            f1.cd();




            /////////////////Make some DataPlots///////////////////////
        }

    }


}
Example #11
0
void Calibrate()
{


  TCanvas *mycan1 = (TCanvas*)gROOT->FindObject("mycan1");
  if(!mycan1)
    {
      mycan1 = new TCanvas("mycan1","",1200,1000);
      mycan1->Divide(4,4,0.0000001,0.0000001);
    }

  float energy[2][32][5] = {0.};
  float peak[2][32][5] = {0.};



  ifstream file("SiCalibPoints.txt");
  if(!file.is_open())
    {
      cout << "No Si Calib Data" << endl;
      return;
    }

  ofstream out("SiRecalib.cal");

  int  itele = -1;
  int istrip = -1;

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

      file >> itele >> istrip;
      itele = itele-6;
      file >>energy[itele][istrip][0];
      file >> energy[itele][istrip][1] >> energy[itele][istrip][2];
      file >> energy[itele][istrip][3] >> energy[itele][istrip][4];
      file >> peak[itele][istrip][0] >> peak[itele][istrip][1];
      file >> peak[itele][istrip][2] >> peak[itele][istrip][3];
      file >> peak[itele][istrip][4];

    }

  float slope = 0.;
  float inter = 0.;
  for(int i = 0;i<16;i++)
    {
      mycan1->cd(i+1);
      TGraph *mygraph = new TGraph(5,peak[0][i],energy[0][i]);
      mygraph->SetMarkerStyle(20);
      mygraph->Draw("AP");

      TF1 *fit = new TF1("fit","pol1",0,500);
      mygraph->Fit("fit","RQ");

      slope = fit->GetParameter(1);
      inter = fit->GetParameter(0);
      cout << istrip <<" Slope = " << slope;
      cout << " inter = " << inter << endl;
      out << 0 << " " << i << " " << slope << " " << inter << endl;

    }

  TCanvas *mycan2 = (TCanvas*)gROOT->FindObject("mycan2");
  if(!mycan2)
    {
      mycan2 = new TCanvas("mycan2","",1200,1000);
      mycan2->Divide(4,4,0.0000001,0.0000001);
    }
  for(int i = 0;i<16;i++)
    {
      int istrip = i+16;
      mycan2->cd(i+1);
      TGraph *mygraph = new TGraph(5,peak[0][istrip],energy[0][istrip]);
      mygraph->SetTitle(Form("Strip %i",istrip));
      mygraph->SetMarkerStyle(20);
      mygraph->Draw("AP");

      TF1 *fit = new TF1("fit","pol1",0,500);
      mygraph->Fit("fit","RQ");

      cout << istrip << " Slope = " << fit->GetParameter(1);
      cout << " inter = " << fit->GetParameter(0) << endl;
      slope = fit->GetParameter(1);
      inter = fit->GetParameter(0);
      out << 0 << " " << istrip << " " << slope << " " << inter << endl;

    }
  TCanvas *mycan3 = (TCanvas*)gROOT->FindObject("mycan3");
  if(!mycan3)
    {
      mycan3 = new TCanvas("mycan3","",1200,1000);
      mycan3->Divide(4,4,0.0000001,0.0000001);
    }
  for(int i = 0;i<16;i++)
    {
      int istrip = i;
      mycan3->cd(i+1);
      TGraph *mygraph = new TGraph(5,peak[1][istrip],energy[1][istrip]);
      mygraph->SetTitle(Form("Strip %i",istrip));
      mygraph->SetMarkerStyle(20);
      mygraph->Draw("AP");

      TF1 *fit = new TF1("fit","pol1",0,500);
      mygraph->Fit("fit","RQ");

      cout << istrip << " Slope = " << fit->GetParameter(1);
      cout << " inter = " << fit->GetParameter(0) << endl;

      slope = fit->GetParameter(1);
      inter = fit->GetParameter(0);
      out << 1 << " " << istrip << " " << slope << " " << inter << endl;


    }
  TCanvas *mycan4 = (TCanvas*)gROOT->FindObject("mycan4");
  if(!mycan4)
    {
      mycan4 = new TCanvas("mycan4","",1200,1000);
      mycan4->Divide(4,4,0.0000001,0.0000001);
    }
  for(int i = 0;i<16;i++)
    {
      int istrip = i+16;
      mycan4->cd(i+1);
      TGraph *mygraph = new TGraph(5,peak[1][istrip],energy[1][istrip]);
      mygraph->SetTitle(Form("Strip %i",istrip));
      mygraph->SetMarkerStyle(20);
      mygraph->Draw("AP");

      TF1 *fit = new TF1("fit","pol1",0,500);
      mygraph->Fit("fit","RQ");

      cout << istrip << " Slope = " << fit->GetParameter(1);
      cout << " inter = " << fit->GetParameter(0) << endl;

      slope = fit->GetParameter(1);
      inter = fit->GetParameter(0);
      out << 1 << " " << istrip << " " << slope << " " << inter << endl;


    }


  return;
}
// /r06/lc/sg568/HCAL_Optimisation_Studies/EnergyResolutionResults/Detector_Model_103/Reco_Stage_38/Photon
// EnergyResolution_PandoraSettingsDefault_DetectorModel_103_ReconstructionVariant_38_Photon.root
void DrawNumLayersSiECal100GeV() 
{
    const int recoVar(71);
    const int energy(100);

    std::vector<int> detectorModels;
    detectorModels.push_back(96);
    detectorModels.push_back(97);
    detectorModels.push_back(98);
    detectorModels.push_back(99);

    std::map<int, int> detModelToLayerNumber;
    detModelToLayerNumber[96] = 30;
    detModelToLayerNumber[97] = 26;
    detModelToLayerNumber[98] = 20;
    detModelToLayerNumber[99] = 16;

    TCanvas *pTCanvas = new TCanvas();

    TGraphErrors *pTGraphErrors = new TGraphErrors("EResVsLayer","EResVsLayer");

    for (std::vector<int>::iterator it = detectorModels.begin(); it != detectorModels.end(); it++)
    {
        const int detModel(*it);
        const int layerNumber(detModelToLayerNumber.find(detModel)->second);

        std::string rootFile("/r06/lc/sg568/HCAL_Optimisation_Studies/EnergyResolutionResults/Detector_Model_" + NumberToString(detModel) + "/Reco_Stage_" + NumberToString(recoVar) + "/Photon/EnergyResolution_PandoraSettingsDefault_DetectorModel_" + NumberToString(detModel) + "_ReconstructionVariant_" + NumberToString(recoVar) + "_Photon.root");
        std::cout << rootFile << std::endl;
        TFile *pTFile = new TFile(rootFile.c_str());

        std::string histogramName("Resolution_DetectorModel_" + NumberToString(detModel) + "_ReconstructionVariant_" + NumberToString(recoVar) + "/PFOEnergyHistogram_DetectorModel_" + NumberToString(detModel) + "_ReconstructionVariant_" + NumberToString(recoVar) + ";4");

        std::cout << histogramName << std::endl;
 
        TH1F *pTH1F = (TH1F*)pTFile->Get(histogramName.c_str());

        std::string fitTitle = "PFOEnergyHistogramGaussianFit_DetectorModel_" + NumberToString(detModel) + "_ReconstructionVariant_" + NumberToString(recoVar) + "_Energy" + NumberToString(energy) + "GeV";
        TF1 *pGaussianFit = new TF1(fitTitle.c_str(),"gaus",0,1000);

        pTH1F->Fit(fitTitle.c_str());
        const float fitAmplitude(pGaussianFit->GetParameter(0));
        const float fitMean(pGaussianFit->GetParameter(1));
        const float fitStdDev(pGaussianFit->GetParameter(2));
        const float energyResolution(fitStdDev/fitMean);

        const float meanError(pGaussianFit->GetParError(1));
        const float meanFracError(meanError / fitMean);
        const float stdDevError(pGaussianFit->GetParError(2));
        const float stdDevFracError(stdDevError / fitStdDev);

        const float energyResolutionError = energyResolution * std::pow( (meanFracError*meanFracError) + (stdDevFracError*stdDevFracError) ,0.5);

        pTGraphErrors->SetPoint(pTGraphErrors->GetN(),layerNumber,energyResolution*100.f);
        pTGraphErrors->SetPointError(pTGraphErrors->GetN()-1,0,energyResolutionError*100.f);

        std::cout << "For energy : " << energy << std::endl;
        std::cout << "Amplitude          : " << fitAmplitude << std::endl;
        std::cout << "Mean               : " << fitMean << std::endl;
        std::cout << "Standard Deviation : " << fitStdDev << std::endl;
        std::cout << "Det model " << detModel << std::endl;
        std::cout << "Energy Resolution  : " << energyResolution*100 << std::endl;
    }

    TH2F *pAxes = new TH2F("axesEj","",100,14,32,1000,2.4,3.4);
    pAxes->SetTitle("100 GeV Photon Energy Resolution vs Number of Layers in ECal (Si)");
    pAxes->GetYaxis()->SetTitle("#sigma_{Reco} / E_{Reco}");
    pAxes->GetXaxis()->SetTitle("Number of ECal Layers");
    pAxes->Draw();

    pTGraphErrors->Draw("same PL");
    const std::string name("SiECal" + NumberToString(energy) + "GeVPhotonResVsLayerNumber.C");
    pTCanvas->SaveAs(name.c_str());
}
Example #13
0
 double GetTheta(){
   phi = GetPhi();
   //   if((xzfitfunc->GetParameter(1)*fabs(cos(phi))) != 0)
   theta = absval(atan(1/(yzfitfunc->GetParameter(1)*(sin(phi)))));
     return theta;};
Example #14
0
 double YZGetParameter(int i){return (yzfitfunc->GetParameter(i));};
Example #15
0
void fitB_extend(bool ispPb=true,TString infname="",bool doweight = 1)
{

  
  if(ispPb==true){
  
    inputdata="/afs/cern.ch/work/w/wangj/public/nt_20140727_PAMuon_HIRun2013_Merged_y24_Using03090319Bfinder.root";
    inputmc="/afs/cern.ch/work/w/wangj/public/nt_20140801_mixed_fromQMBFinder_Kp.root";
    luminosity=34.6*1e-3;
    outputname="../ResultsBplus/SigmaBplus_extend.root";
    cut="abs(y)<2.4&&(HLT_PAMu3_v1)&&abs(mumumass-3.096916)<0.15&&mass>5&&mass<6&& isbestchi2&&trk1Pt>0.9&&chi2cl>1.32e-02&&(d0/d0Err)>3.41&&cos(dtheta)>-3.46e01&&mu1pt>1.5&&mu2pt>1.5";

  }
  else{
  
    //inputdata="/data/bmeson/data//nt_20141022_PPMuon_Run2013A_PromptReco_v1_resub20141126.root";
    //inputmc="/afs/cern.ch/work/w/wangj/public/nt_20140801_mixed_fromQMBFinder_Kp.root";
    inputdata="/data/bmeson/data/nt_20141022_PPMuon_Run2013A_PromptReco_v1_resub20141126_HLT_PAL1DoubleMu0_HighQ_v1.root";
    inputmc="/data/bmeson/MC/nt_2015251_PYTHIA6_BuJpsiK_pp_PAL1DoubleMu0_HighQ_v1.root";

    luminosity=5400*1e-3;
    outputname="../ResultsBplus_pp/SigmaBplus_extend.root";
    cut="abs(y)<2.4&&(HLT_PAL1DoubleMu0_HighQ_v1)&&abs(mumumass-3.096916)<0.15&&mass>5&&mass<6&& isbestchi2&&trk1Pt>0.9&&chi2cl>1.32e-02&&(d0/d0Err)>3.41&&cos(dtheta)>-3.46e01&&mu1pt>1.5&&mu2pt>1.5";
  }
  
  seldata_2y=Form("%s",cut.Data());
  selmc=Form("abs(y)<2.4&&gen==23333&&%s",cut.Data());
  selmcgen="abs(y)<2.4&&abs(pdgId)==521&&isSignal==1";

  if (doweight==0) weight="1";
  if (infname=="") infname=inputdata.Data();
  TFile *inf = new TFile(infname.Data());
  TTree *nt = (TTree*) inf->Get("ntKp");

  TFile *infMC = new TFile(inputmc.Data());
  TTree *ntGen = (TTree*)infMC->Get("ntGen");
  TTree *ntGen2 = (TTree*)inf->Get("ntGen");
  TTree *ntMC = (TTree*)infMC->Get("ntKp");
    
  ntGen->AddFriend(ntMC);
  ntGen2->AddFriend(ntMC);
    
  const int nBins = 5;
  double ptBins[nBins+1] = {10,15,20,25,30,60};
  //const int nBins = 1;
  //double ptBins[nBins+1] = {10,60};
  TH1D *hPt = new TH1D("hPt","",nBins,ptBins);
  TH1D *hPtRecoTruth = new TH1D("hPtRecoTruth","",nBins,ptBins);
  TH1D *hGenPtSelected = new TH1D("hGenPtSelected","",nBins,ptBins);
  TH1D *hPtMC = new TH1D("hPtMC","",nBins,ptBins);
  TH1D *hPtGen = new TH1D("hPtGen","",nBins,ptBins);
  TH1D *hPtGen2 = new TH1D("hPtGen2","",nBins,ptBins);

  TFile *outf = new TFile(outputname.Data(),"recreate");

  for (int i=0;i<nBins+1;i++)
    {
      if (i==nBins) {fit(nt,ntMC,10,60,ispPb,i);continue;}
      TF1 *f = fit(nt,ntMC,ptBins[i],ptBins[i+1],ispPb,i);
      double yield = f->Integral(5,6)/0.02;
      double yieldErr = f->Integral(5,6)/0.02*f->GetParError(0)/f->GetParameter(0);
      hPt->SetBinContent(i+1,yield/(ptBins[i+1]-ptBins[i]));
      hPt->SetBinError(i+1,yieldErr/(ptBins[i+1]-ptBins[i]));
    }  

  TCanvas *c=  new TCanvas("cResult","",600,600);
  hPt->SetXTitle("B^{+} p_{T} (GeV/c)");
  hPt->SetYTitle("Uncorrected B^{+} dN/dp_{T}");
  hPt->Sumw2();
  hPt->Draw();
  
  ntMC->Project("hPtMC","pt",TCut(weight)*(TCut(selmc.Data())&&"gen==23333"));
  nt->Project("hPtRecoTruth","pt",TCut(seldata_2y.Data())&&"gen==23333");
  ntGen->Project("hPtGen","pt",TCut(weight)*(TCut(selmcgen.Data())));
  ntGen2->Project("hPtGen2","pt",(TCut(selmcgen.Data())));
  divideBinWidth(hPtRecoTruth);
  
  hPtRecoTruth->Draw("same hist");
  divideBinWidth(hPtMC);
  divideBinWidth(hPtGen);
  divideBinWidth(hPtGen2);
  
  hPtMC->Sumw2();
  TH1D *hEff = (TH1D*)hPtMC->Clone("hEff");
  hPtMC->Sumw2();
  hEff->Divide(hPtGen);
  
  TH1D *hPtCor = (TH1D*)hPt->Clone("hPtCor");
  hPtCor->Divide(hEff);
  TCanvas *cCor=  new TCanvas("cCorResult","",600,600);
  hPtCor->SetYTitle("Corrected B^{+} dN/dp_{T}");
  hPtCor->Draw();
  hPtGen->Draw("same hist");
  hPtGen2->Draw("same hist");

  TH1D *hPtSigma= (TH1D*)hPtCor->Clone("hPtSigma");
  double BRchain=6.09604e-5;

  hPtSigma->Scale(1./(2*luminosity*BRchain));
  hPtSigma->SetYTitle("d#sigma (B^{+})/dp_{T}");

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

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

    TF1* f = new TF1(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"[0]*([7]*([9]*Gaus(x,[1],[2]*(1+[11]))/(sqrt(2*3.14159)*[2]*(1+[11]))+(1-[9])*Gaus(x,[1],[10]*(1+[11]))/(sqrt(2*3.14159)*[10]*(1+[11])))+(1-[7])*Gaus(x,[1],[8]*(1+[11]))/(sqrt(2*3.14159)*[8]*(1+[11])))+[3]+[4]*x+[5]*x*x+[6]*x*x*x", 1.7, 2.0);
    f->SetParLimits(4,-1000,1000);
    f->SetParLimits(10,0.001,0.05);
    f->SetParLimits(2,0.01,0.1);
    f->SetParLimits(8,0.02,0.2);
    f->SetParLimits(7,0,1);
    f->SetParLimits(9,0,1);

    f->SetParameter(0,setparam0);
    f->SetParameter(1,setparam1);
    f->SetParameter(2,setparam2);
    f->SetParameter(10,setparam10);
    f->SetParameter(9,setparam9);

    f->FixParameter(8,setparam8);
    f->FixParameter(7,1);
    f->FixParameter(1,fixparam1);
    f->FixParameter(3,0);
    f->FixParameter(4,0);
    f->FixParameter(5,0);
    f->FixParameter(6,0);
    f->FixParameter(11,0);
    h->GetEntries();

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

    f->FixParameter(1,f->GetParameter(1));
    f->FixParameter(2,f->GetParameter(2));
    f->FixParameter(10,f->GetParameter(10));
    f->FixParameter(9,f->GetParameter(9));
    f->FixParameter(7,0);
    f->ReleaseParameter(8);
    f->SetParameter(8,setparam8);

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

    f->FixParameter(7,hMC->Integral(0,1000)/(hSW->Integral(0,1000)+hMC->Integral(0,1000)));
    f->FixParameter(8,f->GetParameter(8));
    f->ReleaseParameter(3);
    f->ReleaseParameter(4);
    f->ReleaseParameter(5);
    f->ReleaseParameter(6);

    f->SetLineColor(kRed);

    h->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"q","",1.7,2.0);
    h->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"q","",1.7,2.0);
    f->ReleaseParameter(1);
    f->SetParLimits(1,1.86,1.87);
    f->ReleaseParameter(11);
    f->SetParLimits(11,-1.,1.);
    h->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"L q","",1.7,2.0);
    h->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"L q","",1.7,2.0);
    h->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"L q","",1.7,2.0);
    h->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"L m","",1.7,2.0);
    h->SetMarkerSize(0.8);
    h->SetMarkerStyle(20);

    TF1* background = new TF1(Form("background%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"[0]+[1]*x+[2]*x*x+[3]*x*x*x");
    background->SetParameter(0,f->GetParameter(3));
    background->SetParameter(1,f->GetParameter(4));
    background->SetParameter(2,f->GetParameter(5));
    background->SetParameter(3,f->GetParameter(6));
    background->SetLineColor(4);
    background->SetRange(1.7,2.0);
    background->SetLineStyle(2);

    TF1* mass = new TF1(Form("fmass%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"[0]*([3]*([4]*Gaus(x,[1],[2]*(1+[6]))/(sqrt(2*3.14159)*[2]*(1+[6]))+(1-[4])*Gaus(x,[1],[5]*(1+[6]))/(sqrt(2*3.14159)*[5]*(1+[6]))))");
    mass->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(2),f->GetParameter(7),f->GetParameter(9),f->GetParameter(10),f->GetParameter(11));
    mass->SetParError(0,f->GetParError(0));
    mass->SetParError(1,f->GetParError(1));
    mass->SetParError(2,f->GetParError(2));
    mass->SetParError(3,f->GetParError(7));
    mass->SetParError(4,f->GetParError(9));
    mass->SetParError(5,f->GetParError(10));
    mass->SetFillColor(kOrange-3);
    mass->SetFillStyle(3002);
    mass->SetLineColor(kOrange-3);
    mass->SetLineWidth(3);
    mass->SetLineStyle(2);

    TF1* massSwap = new TF1(Form("fmassSwap%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"[0]*(1-[2])*Gaus(x,[1],[3]*(1+[4]))/(sqrt(2*3.14159)*[3]*(1+[4]))");
    massSwap->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(7),f->GetParameter(8),f->GetParameter(11));
    massSwap->SetParError(0,f->GetParError(0));
    massSwap->SetParError(1,f->GetParError(1));
    massSwap->SetParError(2,f->GetParError(7));
    massSwap->SetParError(3,f->GetParError(8));
    massSwap->SetFillColor(kGreen+4);
    massSwap->SetFillStyle(3005);
    massSwap->SetLineColor(kGreen+4);
    massSwap->SetLineWidth(3);
    massSwap->SetLineStyle(1);

    h->SetXTitle("m_{#piK} (GeV/c^{2})");
    h->SetYTitle("Entries / (5 MeV/c^{2})");
    h->GetXaxis()->CenterTitle();
    h->GetYaxis()->CenterTitle();
    h->SetAxisRange(0,h->GetMaximum()*1.4*1.2,"Y");
    h->GetXaxis()->SetTitleOffset(1.3);
    h->GetYaxis()->SetTitleOffset(1.8);
    h->GetXaxis()->SetLabelOffset(0.007);
    h->GetYaxis()->SetLabelOffset(0.007);
    h->GetXaxis()->SetTitleSize(0.045);
    h->GetYaxis()->SetTitleSize(0.045);
    h->GetXaxis()->SetTitleFont(42);
    h->GetYaxis()->SetTitleFont(42);
    h->GetXaxis()->SetLabelFont(42);
    h->GetYaxis()->SetLabelFont(42);
    h->GetXaxis()->SetLabelSize(0.04);
    h->GetYaxis()->SetLabelSize(0.04);
    h->SetMarkerSize(0.8);
    h->SetMarkerStyle(20);
    h->SetStats(0);
    h->Draw("e");

    background->Draw("same");   
    mass->SetRange(1.7,2.0);	
    mass->Draw("same");
    massSwap->SetRange(1.7,2.0);
    massSwap->Draw("same");
    f->Draw("same");

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

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

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

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

  return hDistrib;
}
Example #17
0
TF1 *fit(TTree *nt,TTree *ntMC,double ptmin,double ptmax, bool ispPb, int count){   
   //cout<<cut.Data()<<endl;
   //static int count=0;
   //count++;
   TCanvas *c= new TCanvas(Form("c%d",count),"",600,600);
   TH1D *h = new TH1D(Form("h%d",count),"",50,5,6);
   TH1D *hMC = new TH1D(Form("hMC%d",count),"",50,5,6);

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

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


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

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

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

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

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

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

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

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


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

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

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

   return mass;
}
Example #18
0
TF1* fit(Double_t ptmin, Double_t ptmax)
{
  TCanvas* c = new TCanvas(Form("c_%.0f_%.0f",ptmin,ptmax),"",600,600);
  TFile* infile = new TFile(Form("%s_%s_%.0f_%.0f.root",infname.Data(),collisionsystem.Data(),ptmin,ptmax));
  TH1D* h = (TH1D*)infile->Get("h");                    h->SetName(Form("h_%.0f_%.0f",ptmin,ptmax));
  TH1D* hMCSignal = (TH1D*)infile->Get("hMCSignal");    hMCSignal->SetName(Form("hMCSignal_%.0f_%.0f",ptmin,ptmax));
  TH1D* hMCSwapped = (TH1D*)infile->Get("hMCSwapped");  hMCSwapped->SetName(Form("hMCSwapped_%.0f_%.0f",ptmin,ptmax));
  TF1* f = new TF1(Form("f_%.0f_%.0f",ptmin,ptmax),"[0]*([7]*([9]*Gaus(x,[1],[2])/(sqrt(2*3.14159)*[2])+(1-[9])*Gaus(x,[1],[10])/(sqrt(2*3.14159)*[10]))+(1-[7])*Gaus(x,[1],[8])/(sqrt(2*3.14159)*[8]))+[3]+[4]*x+[5]*x*x", 1.7, 2.0);

  f->SetParLimits(4,-1000,1000);
  f->SetParLimits(10,0.001,0.05);
  f->SetParLimits(2,0.01,0.1);
  f->SetParLimits(8,0.02,0.2);
  f->SetParLimits(7,0,1);
  f->SetParLimits(9,0,1);
  
  f->SetParameter(0,setparam0);
  f->SetParameter(1,setparam1);
  f->SetParameter(2,setparam2);
  f->SetParameter(10,setparam10);
  f->SetParameter(9,setparam9);

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

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

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

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

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

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

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

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

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

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

  return mass;
}
Example #19
0
/**
 * This function fits TH2F slices with a selected fitType function (gaussian, lorentz, ...).
 */
TGraphErrors* fit2DProj(TString name, TString path, int minEntries, int rebinX, int rebinY, int fitType,
                        TFile * outputFile, const TString & resonanceType, const double & xDisplace, const TString & append) {

  //Read the TH2 from file
  TFile *inputFile = new TFile(path);
  TH2 * histo = (TH2*) inputFile->Get(name);
  if( rebinX > 0 ) histo->RebinX(rebinX);
  if( rebinY > 0 ) histo->RebinY(rebinY);

  //Declare some variables
  TH1 * histoY;
  TString nameY;
  std::vector<double> Ftop;
  std::vector<double> Fwidth;
  std::vector<double> Fmass;
  std::vector<double> Etop;
  std::vector<double> Ewidth;
  std::vector<double> Emass;
  std::vector<double> Fchi2;
  std::vector<double> Xcenter;
  std::vector<double> Ex;

  TString fileOutName("fitCompare2"+name);
  fileOutName += append;
  fileOutName += ".root";
  TFile *fileOut=new TFile(fileOutName,"RECREATE");

  for (int i=1; i<=(histo->GetXaxis()->GetNbins());i++) {

    //Project on Y (set name and title)
    std::stringstream number;
    number << i;
    TString numberString(number.str());
    nameY = name + "_" + numberString;
    // std::cout << "nameY  " << nameY << std::endl;

    histoY = histo->ProjectionY(nameY, i, i);

    double xBin = histo->GetXaxis()->GetBinCenter(i);
    std::stringstream xBinString;
    xBinString << xBin;
    TString title("Projection of x = ");
    title += xBinString.str();

    histoY->SetName(title);

    if (histoY->GetEntries() > minEntries) {

      //Make the dirty work!
      TF1 *fit;
      std::cout << "fitType = " << fitType << std::endl;
      if(fitType == 1) fit = gaussianFit(histoY, resonanceType);
      else if(fitType == 2) fit = lorentzianFit(histoY, resonanceType);
      else if(fitType == 3) fit = linLorentzianFit(histoY);
      else {
	std::cout<<"Wrong fit type: 1=gaussian, 2=lorentzian, 3=lorentzian+linear."<<std::endl;
	abort();
      }

      double *par = fit->GetParameters();
      double *err = fit->GetParErrors();

      // Check the histogram alone
      TCanvas *canvas = new TCanvas(nameY+"alone", nameY+" alone");
      histoY->Draw();
      canvas->Write();

      // Only for check
      TCanvas *c = new TCanvas(nameY, nameY);

      histoY->Draw();
      fit->Draw("same");
      fileOut->cd();
      c->Write();

      if( par[0] == par[0] ) {
        //Store the fit results
        Ftop.push_back(par[0]);
        Fwidth.push_back(fabs(par[1]));//sometimes the gaussian has negative width (checked with Rene Brun)
        Fmass.push_back(par[2]);
        Etop.push_back(err[0]);
        Ewidth.push_back(err[1]);
        Emass.push_back(err[2]);

        Fchi2.push_back(fit->GetChisquare()/fit->GetNDF());

        double xx= histo->GetXaxis()->GetBinCenter(i);
        Xcenter.push_back(xx);
        double ex = 0;
        Ex.push_back(ex); 
      }
      else {
        // Skip nan
        std::cout << "Skipping nan" << std::endl;
        Ftop.push_back(0);
        Fwidth.push_back(0);
        Fmass.push_back(0);
        Etop.push_back(1);
        Ewidth.push_back(1);
        Emass.push_back(1);

        Fchi2.push_back(100000);

        Xcenter.push_back(0);
        Ex.push_back(1); 
      }
    }
  }

  fileOut->Close();

  //Plots the fit results in  TGraphs
  const int nn= Ftop.size();                   
  double x[nn],ym[nn],e[nn],eym[nn];
  double yw[nn],eyw[nn],yc[nn];

  // std::cout << "number of bins = " << nn << std::endl;
  // std::cout << "Values:" << std::endl;

  for (int j=0;j<nn;j++){
    // std::cout << "xCenter["<<j<<"] = " << Xcenter[j] << std::endl;
    x[j]=Xcenter[j]+xDisplace;
    // std::cout << "Fmass["<<j<<"] = " << Fmass[j] << std::endl;
    ym[j]=Fmass[j];
    // std::cout << "Emass["<<j<<"] = " << Emass[j] << std::endl;
    eym[j]=Emass[j];
    // std::cout << "Fwidth["<<j<<"] = " << Fwidth[j] << std::endl;
    yw[j]=Fwidth[j];
    // std::cout << "Ewidth["<<j<<"] = " << Ewidth[j] << std::endl;
    eyw[j]=Ewidth[j];
    // std::cout << "Fchi2["<<j<<"] = " << Fchi2[j] << std::endl;
    yc[j]=Fchi2[j];
    e[j]=0;
  }

  TGraphErrors *grM = new TGraphErrors(nn,x,ym,e,eym);
  grM->SetTitle(name+"_M");
  grM->SetName(name+"_M");
  TGraphErrors *grW = new TGraphErrors(nn,x,yw,e,eyw);
  grW->SetTitle(name+"_W");
  grW->SetName(name+"_W");
  TGraphErrors *grC = new TGraphErrors(nn,x,yc,e,e);
  grC->SetTitle(name+"_chi2");
  grC->SetName(name+"_chi2");

  grM->SetMarkerColor(4);
  grM->SetMarkerStyle(20);
  grW->SetMarkerColor(4);
  grW->SetMarkerStyle(20);
  grC->SetMarkerColor(4);
  grC->SetMarkerStyle(20);

  //Draw and save the graphs
  outputFile->cd();
  TCanvas * c1 = new TCanvas(name+"_W",name+"_W");
  c1->cd();
  grW->Draw("AP");
  c1->Write();
  TCanvas * c2 = new TCanvas(name+"_M",name+"_M");
  c2->cd();
  grM->Draw("AP");
  c2->Write();
  TCanvas * c3 = new TCanvas(name+"_C",name+"_C");
  c3->cd();
  grC->Draw("AP");
  c3->Write();

  return grM;
}
Example #20
0
void v2_cent_plotter(int jpsiCategory      = 2, // 1 : Prompt, 2 : Non-Prompt, 3: Bkg
		     string nDphiBins      = "4",
		     const char* outputDir = "output", 
		     const char* inputDir  = "outputNumbers",// where phi and v2 numbers are (root, and txt format)
		     bool bDoDebug         = true,
		     bool bAddCent010      = false, 
		     bool bSavePlots       = true
		     ) 
{
  gSystem->mkdir(Form("./%s/png",outputDir), kTRUE);
  gSystem->mkdir(Form("./%s/pdf",outputDir), kTRUE);
  
// set the style
  setTDRStyle();
  gStyle->SetOptFit(0);
  gStyle->SetOptStat(0);
  gStyle->SetOptTitle(kFALSE);

  // input files: prompt and non-prompt ones
  const char* v2InFileDirs[1] = {"histsV2Yields_20150823_v2W_Lxyz_pTtune_PRMC_dPhiBins4"};
  const char* legend[4]       = {"","Prompt J/#psi","Non-prompt J/#psi","Background"};
  const char* signal[4]       = {"", "Prp","NPrp","Bkg"};
 
  // Reminder for TGraphAssymError: gr = new TGraphAsymmErrors(n,x,y,exl,exh,eyl,eyh);// n,x,y,err_x, err_y
  int nBins                   =  nCentBins_pr; 
  if(jpsiCategory==2) nBins   =  nCentBins_np;
  
  cout<<" !!!!! Number of Y bins: "<< nBins<<endl;
  
  double adXaxis[nBins];//   location on x-axis  

  double adV2[nBins]      ; // v2 values
  double adV2_stat[nBins] ;// stat uncert
  double adV2_syst[nBins] ;// stat uncert
  double adV2_err0[nBins] ;// error  0
  double adWidth_systBox[nBins]; // width of the systm. uncert.

  for(int ib=0; ib<nBins; ib++)
    {
      adWidth_systBox[ib] = 10;
      adV2_syst[ib]       = adV2Cent_pr_syst[ib];
      adXaxis[ib]         = adXaxisCent_pr[ib];

      if(jpsiCategory==2)
	{
	  adV2_syst[ib]    = adV2Cent_np_syst[ib];
	  adXaxis[ib]      = adXaxisCent_np[ib];
	}

      if(bDoDebug) cout<<"Bin "<<ib<<"\t adAxis= "<<adXaxis[ib]<<endl;
    }
  
  // // open the files with yields and do the math
  ifstream in;
  std::string nameVar   = outFilePlot[3]; // cent
  std::string nameSig   = signal[jpsiCategory]; // prompt, non-pro or bkg
  std::string nameDir   = v2InFileDirs[0];
  string inputFile      = nameVar + "_"+ nameSig + "_nphibin" + nDphiBins + ".dat";
  
  cout << "!!!!!! Input file name: "<< inputFile <<endl;
  in.open(Form("%s/%s/data/%s",inputDir,nameDir.c_str(),inputFile.c_str()));
  

  // read the v2 and v2_stat uncert from input file
  string whatBin[3];
  double x[4]={0};
  int iline=0;
  string tmpstring;
  getline(in,tmpstring);
  while ( in.good() && iline<nBins)
    {
      in >> whatBin[0] >> whatBin[1] >> whatBin[2] >> x[0] >> x[1] >> x[2] >> x[3];

      adV2[nBins-iline-1]      = x[2];
      adV2_stat[nBins-iline-1] = x[3];

      cout<< "Bin " << whatBin[0] << "\t"<< whatBin[1] << "\t" << whatBin[2]<<"\t";
      cout <<"v2= "<< x[2] << "\t error= "<< x[3]<<endl;
      iline++;
    }
  in.close();
  if(bDoDebug)
    {
      for(int ib=0; ib<nBins; ib++)
	cout<<"Bin "<<ib<<"\t adXaxis: "<< adXaxis[ib]<<"\t v2= "<<adV2[ib]<<endl;
    }
  // high-pt
  TGraphErrors *pgV2          = new TGraphErrors(nBins, adXaxis, adV2, adV2_stat, adV2_stat);
  TGraphAsymmErrors *pgV2_sys = new TGraphAsymmErrors(nBins, adXaxis, adV2, adWidth_systBox,adWidth_systBox, adV2_syst, adV2_syst);
  TGraphErrors *pgV2_cont     = new TGraphErrors(nBins, adXaxis, adV2, adV2_err0, adV2_err0);
  
    // //-------------------------------------------------- Drawing stuff
  // colors and symbols
  // high-pt
  pgV2->SetMarkerColor(kRed+1);
  pgV2_sys->SetFillColor(kRed-9);

  pgV2->SetMarkerStyle(21);
  pgV2_sys->SetMarkerStyle(21);
  pgV2_cont->SetMarkerStyle(25); 
 
  pgV2->SetMarkerSize(1.1);
  pgV2_cont->SetMarkerSize(1.1);

  if(jpsiCategory==2)
    {
      pgV2->SetMarkerColor(kOrange+2);
      pgV2_sys->SetFillColor(kOrange-9);
    }
  if(jpsiCategory==3)// bkg
    {
      pgV2->SetMarkerColor(1);
      pgV2_sys->SetFillColor(19);
    }
 
  //-------------------------------------------------------
  // general labels 
  TLatex *lt1  = new TLatex();
  lt1->SetNDC();

  TH1F *phAxis = new TH1F("phAxis",";N_{part};v_{2}",10,0,400);
  phAxis->GetYaxis()->SetRangeUser(-0.05,0.25);
  phAxis->GetXaxis()->CenterTitle();
  phAxis->GetYaxis()->CenterTitle();

  TF1 *line    = new TF1("line","0",0,400);
  line->SetLineWidth(1);
 
  TLatex *pre = new TLatex(20.0,0.22,Form("%s",legend[jpsiCategory]));
  pre->SetTextFont(42);
  pre->SetTextSize(0.05);

  TLatex *ly     = new TLatex(20.0,0.18,Form("%s",yBinsLegend[0]));
  ly->SetTextFont(42);
  ly->SetTextSize(0.04);

  TLatex *lpt     = new TLatex(20.0,0.2,Form("%s",ptBinsLegend[0]));
  lpt->SetTextFont(42);
  lpt->SetTextSize(0.04);

  TLatex *lcent = new TLatex(10.0,-0.025,Form("Cent."));
  lcent->SetTextFont(42);
  lcent->SetTextSize(0.04);

 //-------------- Drawing 
  TCanvas *pc = new TCanvas("pc","pc");
  phAxis->Draw();
  CMS_lumi(pc,101,33);
  pre->Draw();
  lpt->Draw();
  ly->Draw();
  lcent->Draw();

 int write2 = nBins;
  if(!bAddCent010) 
    {
      write2 = nBins-1;
      pgV2_sys->RemovePoint(write2);
      pgV2->RemovePoint(write2);
      pgV2_cont->RemovePoint(write2);
    }

  for(int ib=0; ib<write2; ib++)
    {
     if(jpsiCategory==2) lcent->DrawLatex(adXaxis[ib]-30,-0.025,Form("%s",centBinsLegend[nCentBins-1-ib]));
     else lcent->DrawLatex(adXaxis[ib]-30,-0.025,Form("%s",centBinsLegend[nCentBins-nBins-ib]));
    }
  
  pgV2_sys->Draw("2");
  pgV2->Draw("PZ");
  pgV2_cont->Draw("P");
  gPad->RedrawAxis();

 
  if(bSavePlots)
    {
      pc->SaveAs(Form("%s/png/v2_%s_%s_nphi%s.png",outputDir,outFilePlot[2],signal[jpsiCategory],nDphiBins.c_str()));
      pc->SaveAs(Form("%s/pdf/v2_%s_%s_nphi%s.pdf",outputDir,outFilePlot[2],signal[jpsiCategory],nDphiBins.c_str()));
    }

}
Example #21
0
void toyMC_testFitter(int runIeta=-1, int runIpt=-1, int startExp=0){
	
  cout << "ROOT version = " << gROOT->GetVersion() << endl;
//   gSystem->mkdir("toysPlot");
  char tmp[1000];
  TRandom2* r2 = new TRandom2();

  TH1D* htoyResult_pull[nEtaBin][nPtBin];
  TH1D* htoyResult_bias[nEtaBin][nPtBin];

  TFile *fsumFile = new TFile("/afs/cern.ch/user/s/syu/scratch0/LxplusArea/proj_comb_comb3Iso_template.root");
  TFile* finFile = new TFile("/afs/cern.ch/user/s/syu/scratch0/LxplusArea/template_comb3Iso_template.root");  
  TFile* zeeFile = new TFile("/afs/cern.ch/user/s/syu/scratch0/LxplusArea/anadipho_Zee_Vg_3pb.root");
  TH1D* hTemplate = (TH1D*)finFile->FindObjectAny("h_EB_comb3Iso_EGdata_pt21");
  hTemplate->Reset();

  
  char* dec[2] = {"EB","EE"};
  for(int ieta=0; ieta<nEtaBin; ieta++){
    for(int ipt=0; ipt < nPtBin; ipt++){

      htoyResult_pull[ieta][ipt] = new TH1D(Form("hpull_%s_pt_%d",		
						 dec[ieta],
						 (int)fBinsPt[ipt]),
 					    "",50,-5.0,5.0);


      htoyResult_bias[ieta][ipt] = new TH1D(Form("hbias_%s_pt_%d",		
						 dec[ieta],
						 (int)fBinsPt[ipt]),
 					    "",100,-0.5,0.5);


    }
  }



  TH1D* hfit_sig;
  TH1D* hfit_bkg;

  TH1D* hTemplate_S[nEtaBin][nPtBin];
  TH1D* hTemplate_B[nEtaBin][nPtBin];
  TH1D* hZeeTemplate_S[nEtaBin];
  TH1D* hdata_data[nEtaBin][nPtBin];
  TH1D* htemp;


  for(int ieta=0; ieta< nEtaBin; ieta++){

    // getting a different signal template
    if(ieta==0){
      sprintf(tmp,"h_%s_combIso",dec[ieta]);
      cout << "looking for histogram " << tmp << " in file " << 
	zeeFile->GetName() << endl;
      hZeeTemplate_S[ieta]= (TH1D*)zeeFile->FindObjectAny(tmp);	
      hZeeTemplate_S[ieta]->Rebin(REBINNINGS_TEMP);
    }
    else {
      sprintf(tmp,"h_%s_comb3Iso_sig_sum_SIG",dec[ieta]); //no pt dep.
      cout << "looking for histogram " << tmp << " in file " << 
	fsumFile->GetName() << endl;
      hZeeTemplate_S[ieta]= (TH1D*)fsumFile->FindObjectAny(tmp);	
      hZeeTemplate_S[ieta]->Rebin(REBINNINGS_TEMP);
    }

    for(int ipt=0; ipt < nPtBin; ipt++){

      if(runIeta>=0 && ieta!=runIeta)continue;
      if(runIpt>=0 && ipt!=runIpt)continue;
      
      // getting histograms from data root file
      sprintf(tmp,"h_%s_comb3Iso_EGdata_pt%d",dec[ieta],(int)fBinsPt[ipt]);
      cout << "looking for histogram " << tmp << " in file " << 
	finFile->GetName() << endl;
      hdata_data[ieta][ipt] = (TH1D*)finFile->FindObjectAny(tmp);
      hdata_data[ieta][ipt]->Rebin(REBINNINGS_DATA);

      // filling unbinned data
      htemp = (TH1D*)hdata_data[ieta][ipt]->Clone("htemp");
      htemp->Reset();


      sprintf(tmp,"h_%s_comb3Iso_sig_pt%d",dec[ieta],(int)fBinsPt[ipt]);
      cout << "looking for histogram " << tmp << " in file " << 
	finFile->GetName() << endl;
      hTemplate_S[ieta][ipt] = (TH1D*)finFile->FindObjectAny(tmp);
      hTemplate_S[ieta][ipt]->Rebin(REBINNINGS_TEMP);

      if(ieta==0 && fBinsPt[ipt]>=50)
	sprintf(tmp,"h_%s_comb3Iso_bkg_pt%d",dec[ieta],50);
      else if(ieta==0 )
	sprintf(tmp,"h_%s_comb3Iso_bkg_pt%d",dec[ieta],(int)fBinsPt[ipt]);  
      else if(ieta==1 && fBinsPt[ipt]>=60)
	sprintf(tmp,"h_%s_comb3IsoSB_EGdata_pt%d",dec[ieta],60);       
      else if(ieta==1)
	sprintf(tmp,"h_%s_comb3IsoSB_EGdata_pt%d",dec[ieta],(int)fBinsPt[ipt]);
      cout << "looking for histogram " << tmp << " in file " << 
	finFile->GetName() << endl;
      hTemplate_B[ieta][ipt] = (TH1D*)finFile->FindObjectAny(tmp);
      hTemplate_B[ieta][ipt]->Rebin(REBINNINGS_TEMP);



      const int NRETURN = 3*NPAR;
      Double_t myFitPar[NRETURN]={0};
      Double_t* FuncFitResult;
      FuncFitResult = Ifit("/afs/cern.ch/user/s/syu/scratch0/LxplusArea/EGdata_comb3Iso_et.dat",
			   hZeeTemplate_S[ieta],hTemplate_B[ieta][ipt],
			   hdata_data[ieta][ipt], myFitPar,
			   (int)fBinsPt[ipt], dec[ieta],2);

      Double_t nsig_input    = FuncFitResult[0];
      Double_t nsigerr_input = FuncFitResult[1];
      Double_t nbkg_input    = FuncFitResult[2];
      Double_t nbkgerr_input = FuncFitResult[3];
      Double_t nsig_input5GeV = FuncFitResult[4];
      Double_t nsigerr_input5GeV = FuncFitResult[5];

       // force the parameters since EE pt=40 fails
       if(ieta==1 && ipt==5)
	 {
	   nsig_input = 3172.0;
	   nbkg_input = 10031.0;
	   nsig_input5GeV = 3158.7;
	   
	   Double_t tempPar[NRETURN]={
	     22517.049862,
	     0.900766,
	     0.044772,
	     0.191920,
	     313.878244,
	     -0.545069,
	     -0.281830,
	     0.026143,
	     2.549494,
	     0.,
	     0.,
	     22517.049862,
	     0.900766,
	     0.044772,
	     0.191920,
	     313.878244,
	     -0.545069,
	     -0.281830,
	     0.026143,
	     2.549494,
	     0.,
	     0.,
	     22517.049862,
	     0.900766,
	     0.044772,
	     0.191920,
	     313.878244,
	     -0.545069,
	     -0.281830,
	     0.026143,
	     2.549494,
	     0.,
	     0.
	   };

	   for(int ipar=0; ipar <NRETURN; ipar++)
	     myFitPar[ipar] = tempPar[ipar];
	 } // end if EE, Et=40 GeV


      Double_t sigFitPar[NPAR]={0};
      for(int ipar=0; ipar<NPAR; ipar++)
	sigFitPar[ipar] = myFitPar[ipar];

      Double_t bkgFitPar[NPAR]={0};
      for(int ipar=0; ipar<NPAR; ipar++)
	bkgFitPar[ipar] = myFitPar[ipar+NPAR];


      Double_t sumFitPar[NPAR]={0};
      for(int ipar=0; ipar<NPAR; ipar++)
	sumFitPar[ipar] = myFitPar[ipar+NPAR*2];


      TF1* fsig = new TF1("fsig", exp_conv, fit_lo, fit_hi, 11);
      fsig->SetParameters(sigFitPar);       
      fsig->SetParameter(0,1.0);

      mySigPDFnorm = fsig->Integral(fit_lo,fit_hi);
      cout << "mySigPDFnorm = " << mySigPDFnorm << endl;
      
      TF1* fbkg = new TF1("fbkg", expinv_power, fit_lo, fit_hi, 11);
      fbkg->SetParameters(bkgFitPar);
      fbkg->SetParameter(4,1.0);

      myBkgPDFnorm = fbkg->Integral(fit_lo, fit_hi);
      cout << "myBkgPDFnorm = " << myBkgPDFnorm << endl;
 
      TF1* fsum = new TF1("fsum",mysum_norm, fit_lo, fit_hi,11);
      fsum->SetParameters(sumFitPar);

      cout << "Using nsig_input = " << nsig_input << endl;
      cout << "Using nbkg_input = " << nbkg_input << endl;
      cout << "Using nsig_input5GeV = " << nsig_input5GeV << endl;

      fsum->SetParameter(0, nsig_input*hdata_data[ieta][ipt]->GetBinWidth(2));
      fsum->SetParameter(4, nbkg_input*hdata_data[ieta][ipt]->GetBinWidth(2));
      fsum->SetLineColor(2);
      fsum->SetNpx(2500);

      //        cout << "fsum integral = " << fsum->Integral(fit_lo,fit_hi) << endl;
      //        for(int ipar=0; ipar<NPAR; ipar++)cout << "fsum par " << ipar << " = " << fsum->GetParameter(ipar) << endl;

//       FILE *infile =  fopen("/afs/cern.ch/user/s/syu/scratch0/LxplusArea/EGdata_comb3Iso_et.dat","r");  
//       float xdata, xdata1, xdata2; // combined isolation, pt, eta
//       int flag = 1;
//       while (flag!=-1){
// 	flag =fscanf(infile,"%f %f %f",&xdata, &xdata1, &xdata2);
// 	if( xdata1 >= fBinsPt[ipt] && xdata1 < fBinsPt[ipt+1] && xdata<20.) {
// 	  if((ieta==0 && TMath::Abs(xdata2)<1.5) ||
// 	     (ieta==1 && TMath::Abs(xdata2)>1.5) ) {
// 	    htemp->Fill(xdata);
// 	  }
// 	} 
//       }// keep reading files as long as text exists

    
//       TCanvas* myCanvas = new TCanvas("myCanvas","myCanvas");
//       htemp->Draw();
//       fsum->Draw("same");

      ofstream dumpout;
      dumpout.open(Form("pull_bias%d_%s_pt%d.dat",startExp, dec[ieta],(int)fBinsPt[ipt]));
 
      //        // loops over toys
      for(int iexp=NEXP*startExp; iexp<NEXP*(startExp+1); iexp++){

	TH1D* htoyMC_data = (TH1D*)hdata_data[ieta][ipt]->Clone("htoyMC_data");
	htoyMC_data->Reset();
	 
	TH1D* htoyMC_sig  = (TH1D*)hZeeTemplate_S[ieta]->Clone("htoyMC_sig");
	 
	TH1D* htoyMC_bkg  = (TH1D*)hTemplate_B[ieta][ipt]->Clone("htoyMC_bkg");




	UInt_t nowSeed = (unsigned long)gSystem->Now();
	r2->SetSeed(nowSeed);
	int nsiggen  = r2->Poisson(nsig_input);
	int nbkggen  = r2->Poisson(nbkg_input);
	int ndata = nsiggen + nbkggen;

	// reset toy MC data
	htoyMC_data->Reset();
	ofstream fout;
	std::string toyData = Form("/tmp/syu/testtoy%d_%d_%d.dat",startExp,ieta,ipt);
	fout.open(toyData.data());
	for(int ieve=0; ieve < nsiggen; ieve++)
	  {
	    Double_t xvalue = fsig->GetRandom(fit_lo,fit_hi);
	    fout << xvalue << " " << 
	      0.5*(fBinsPt[ipt]+fBinsPt[ipt+1]) << " " << fBinsEta[ieta] << endl;
	    htoyMC_data->Fill(xvalue);
	  }
	     
	for(int ieve=0; ieve < nbkggen; ieve++)
	  {
	    Double_t xvalue = fbkg->GetRandom(fit_lo,fit_hi);
	    fout << xvalue << " " << 
	      0.5*(fBinsPt[ipt]+fBinsPt[ipt+1]) << " " << fBinsEta[ieta] << endl;
	    htoyMC_data->Fill(xvalue);
	  }
	     
	fout.close();


	Double_t* toyFitResult;
	Double_t toyMyFitPar[NRETURN]={0};

	toyFitResult =  Ifit(toyData.data(), 
			     htoyMC_sig, htoyMC_bkg,
			     htoyMC_data, toyMyFitPar,
			     (int)fBinsPt[ipt], dec[ieta],2);

	Double_t nsigtoyfit    = toyFitResult[0];
	Double_t errnsigtoyfit = toyFitResult[1];
	Double_t nbkgtoyfit    = toyFitResult[2];
  	Double_t errnbkgtoyfit = toyFitResult[3];
	Double_t nsigtoyfit_5GeV = toyFitResult[4];
	Double_t errnsigtoyfit_5GeV = toyFitResult[5];


	if(errnsigtoyfit < 1e-6 || errnbkgtoyfit < 1e-6 || 
	   nsigtoyfit < 1e-6 || nbkgtoyfit < 1e-6 || 
	   nsig_input < 1e-6 || fabs(nsigtoyfit - nsig_input)<1e-4)continue;
	   

	Double_t toySumFitPar[NPAR]={0};
	for(int ipar=0; ipar<NPAR; ipar++)
	  toySumFitPar[ipar] = toyMyFitPar[ipar+NPAR*2];


 	fsum->SetParameters(toySumFitPar);
 	fsum->SetParameter(0, nsigtoyfit*hdata_data[ieta][ipt]->GetBinWidth(2));
 	fsum->SetParameter(4, nbkgtoyfit*hdata_data[ieta][ipt]->GetBinWidth(2));
	// 	fsum->SetParameter(0, (float)nsiggen*hdata_data[ieta][ipt]->GetBinWidth(2));
	// 	fsum->SetParameter(4, (float)nbkggen*hdata_data[ieta][ipt]->GetBinWidth(2));

// 	 	if(iexp%20==0){
// 	 	  TCanvas* myCanvas = new TCanvas("myCanvas","SHIT");
// 	 	  htoyMC_data->SetMaximum(htoyMC_data->GetMaximum()*1.5);
// 	 	  htoyMC_data->Draw();
// 	 	  fsum->Draw("same");
// 	 	  myCanvas->Print(Form("toysPlot/fit_%03i.gif",iexp));
// 	 	  delete myCanvas;
// 	 	}

	// 	 cout << "fsum integral = " << fsum->Integral(-1,20) << endl;
	// 	 for(int ipar=0; ipar<NPAR; ipar++)cout << "fsum par " << ipar << " = " << fsum->GetParameter(ipar) << endl;

	
	Double_t pull = (nsigtoyfit - nsig_input)/errnsigtoyfit;
	Double_t bias = (nsigtoyfit - nsig_input)/nsig_input;
	dumpout << pull << " " << bias << endl; 
    
   	htoyResult_pull[ieta][ipt]->Fill(pull);
	htoyResult_bias[ieta][ipt]->Fill(bias);


      } // end loops of toys
      dumpout.close();

      delete fsig;
      delete fbkg;


    } // end of loop over pt bins


  }


//   TFile* outFile = new TFile(Form("fittertest%d_%s_pt%d.root",
// 				  startExp,
// 				  dec[runIeta], (int)fBinsPt[runIpt]),
// 			     "recreate");

//   for(int ieta=0; ieta < nEtaBin; ieta++){
//     for(int ipt=0; ipt < nPtBin; ipt++){      
 
//       if(htoyResult_pull[ieta][ipt]->GetEntries()>0)
// 	htoyResult_pull[ieta][ipt]->Write();

//       if(htoyResult_bias[ieta][ipt]->GetEntries()>0)
// 	htoyResult_bias[ieta][ipt]->Write();      
//     }
//   }
   
//   outFile->Close();

}
Example #22
0
//==============================================
void RecoEff::Loop(Int_t selDimuType, Bool_t useMCWeight)
{
  if (fChain == 0) return;

  Long64_t nentries = fChain->GetEntries();
  Long64_t cutAtRecEvent = nentries;
  Long64_t countRecEvent = 0;
  Long64_t nb = 0;
  printf("<RecoEff> number of entries = %d\n", (Int_t) nentries);

  //apply a weight as the ratio of pT distributions:
  //1.) default Pythia (parametrization)
  TF1 *fPT = new TF1("fPT", "[0]*x*pow(1.+(1./([1]-2.))*x*x/[2],-[1])", 0., 50.);
  fPT->FixParameter(0, 0.61554); fPT->SetParName(0, "norm");
  fPT->FixParameter(1, 4.05847); fPT->SetParName(1, "beta");
  fPT->FixParameter(2, 19.93); fPT->SetParName(2, "<pT2> [GeV2]");

  //alternatively, the pT distribution can be taken from
  //a CASCADE calculation:
  TF1 *fPTCASCADE = new TF1("fPTCASCADE", "[0]*x*pow(1.+(1./([1]-2.))*x*x/[2],-[1])", 0., 50.);
  fPTCASCADE->FixParameter(0, 1.); fPTCASCADE->SetParName(0, "norm");
  fPTCASCADE->FixParameter(1, 3.87004); fPTCASCADE->SetParName(1, "beta");
  fPTCASCADE->FixParameter(2, 15.5821); fPTCASCADE->SetParName(2, "<pT2> [GeV2]");
    
  //alternatively, the pT distribution can be taken from the
  //preliminary ATLAS data shown in Moriond, 17th April
  TF1 *fPTATLAS = new TF1("fPTATLAS", "[0]*x*pow(1.+(1./([1]-2.))*x*x/[2],-[1])", 0., 50.);
  fPTATLAS->FixParameter(0, 1.); fPTATLAS->SetParName(0, "norm");
  fPTATLAS->FixParameter(1, 3.87004); fPTATLAS->SetParName(1, "beta");
  fPTATLAS->FixParameter(2, 15.5821); fPTATLAS->SetParName(2, "<pT2> [GeV2]");

  //loop over the events
  for (Long64_t jentry=0; jentry<nentries;jentry++) {

    if(jentry % 100000 == 0) printf("event %d\n", (Int_t) jentry);

    Long64_t ientry = LoadTree(jentry);
    if (ientry < 0) break;
    nb = fChain->GetEntry(jentry);

    //===================================================================
    //1.) check all generated (and filtered) events and 
    //fill the corresponding histograms
    //===================================================================

    Bool_t genMuonsInPS = kTRUE;
    Double_t etaMuPos_Gen = muPos_Gen->PseudoRapidity();
    Double_t etaMuNeg_Gen = muNeg_Gen->PseudoRapidity();
    Double_t pTMuPos_Gen = muPos_Gen->Pt();
    Double_t pTMuNeg_Gen = muNeg_Gen->Pt();
    Double_t pMuPos_Gen = muPos_Gen->P();
    Double_t pMuNeg_Gen = muNeg_Gen->P();

    //take muons only within a certain eta range
    if((fabs(etaMuPos_Gen) < jpsi::etaPS[0] && pTMuPos_Gen < jpsi::pTMuMin[0]) || //mid-rapidity cut
       (fabs(etaMuPos_Gen) > jpsi::etaPS[0] && fabs(etaMuPos_Gen) < jpsi::etaPS[1] && pMuPos_Gen < jpsi::pMuMin[1]) ||
       (fabs(etaMuPos_Gen) > jpsi::etaPS[1] && fabs(etaMuPos_Gen) < jpsi::etaPS[2] && pTMuPos_Gen < jpsi::pTMuMin[2]))
      genMuonsInPS = kFALSE;
//       continue;
    //(b) on the negative muon
    if((fabs(etaMuNeg_Gen) < jpsi::etaPS[0] && pTMuNeg_Gen < jpsi::pTMuMin[0]) || //mid-rapidity cut
       (fabs(etaMuNeg_Gen) > jpsi::etaPS[0] && fabs(etaMuNeg_Gen) < jpsi::etaPS[1] && pMuNeg_Gen < jpsi::pMuMin[1]) ||
       (fabs(etaMuNeg_Gen) > jpsi::etaPS[1] && fabs(etaMuNeg_Gen) < jpsi::etaPS[2] && pTMuNeg_Gen < jpsi::pTMuMin[2]))
      genMuonsInPS = kFALSE;
//     continue;

    Double_t weight = 1.; //allows to weigh with different input distributions (pT, cosTheta, phi, ...)
    if(useMCWeight)
      weight *= MCweight;

    if(genMuonsInPS){ //fill the generator level info only if the muons are emitted in the PS

      Double_t onia_Gen_mass = onia_Gen->M();
      Double_t onia_Gen_pt = onia_Gen->Pt();
      Double_t onia_Gen_P = onia_Gen->P();
      Double_t onia_Gen_eta = onia_Gen->PseudoRapidity();
      Double_t onia_Gen_rap = onia_Gen->Rapidity();
      Double_t onia_Gen_phi = onia_Gen->Phi();
      Double_t onia_Gen_mT = sqrt(onia_Gen_mass*onia_Gen_mass + onia_Gen_pt*onia_Gen_pt);

      Int_t rapIndex_Gen = -1;
      for(int iRap = 0; iRap < 2*jpsi::kNbRapBins; iRap++){
	if(onia_Gen_rap > jpsi::rapRange[iRap] && onia_Gen_rap < jpsi::rapRange[iRap+1]){
	  rapIndex_Gen = iRap;
	  break;
	}
      }
      Int_t rapForPTIndex_Gen = -1;
      for(int iRap = 0; iRap < jpsi::kNbRapForPTBins; iRap++){
	if(TMath::Abs(onia_Gen_rap) > jpsi::rapForPTRange[iRap] && 
	   TMath::Abs(onia_Gen_rap) < jpsi::rapForPTRange[iRap+1]){
	  rapForPTIndex_Gen = iRap+1;
	  break;
	}
      }
      Int_t pTIndex_Gen = -1;
      for(int iPT = 0; iPT < jpsi::kNbPTBins[rapForPTIndex_Gen]; iPT++){
	if(onia_Gen_pt > jpsi::pTRange[rapForPTIndex_Gen][iPT] && onia_Gen_pt < jpsi::pTRange[rapForPTIndex_Gen][iPT+1]){
	  pTIndex_Gen = iPT+1;
	  break;
	}
      }
      Int_t rapIntegratedPTIndex_Gen = -1;
      for(int iPT = 0; iPT < jpsi::kNbPTBins[0]; iPT++){
	if(onia_Gen_pt > jpsi::pTRange[0][iPT] && onia_Gen_pt < jpsi::pTRange[0][iPT+1]){
	  rapIntegratedPTIndex_Gen = iPT+1;
	  break;
	}
      }
//       if(rapIndex_Gen < 0){
// 	// printf("rapIndex_Gen %d, rap(onia) = %f\n", rapIndex_Gen, onia_rap);
// 	continue;
//       }
//       if(rapForPTIndex_Gen < 1){
// 	// printf("rapForPTIndex_Gen %d, rap(onia) = %f\n", rapForPTIndex_Gen, onia_rap);
// 	continue;
//       }
//       if(pTIndex_Gen < 1){
// 	// printf("pTIndex_Gen %d, pT(onia) = %f\n", pTIndex_Gen, onia_pt);
// 	continue;
//       }

      Bool_t DimuonInPS = kTRUE;
      //select events within a narrow mass window around the J/psi
      //(rapidity dependence of the resolution --> different mass windows)
      //values obtained from Gaussian fits in "plotMass.C"
      Double_t jPsiMassMin = jpsi::polMassJpsi[rapForPTIndex_Gen] - jpsi::nSigMass*jpsi::sigmaMassJpsi[rapForPTIndex_Gen];
      Double_t jPsiMassMax = jpsi::polMassJpsi[rapForPTIndex_Gen] + jpsi::nSigMass*jpsi::sigmaMassJpsi[rapForPTIndex_Gen];
      if(onia_Gen_mass < jPsiMassMin || onia_Gen_mass > jPsiMassMax)
	DimuonInPS = kFALSE;

      if(TMath::Abs(onia_Gen_rap) > jpsi::rapYPS)
	DimuonInPS = kFALSE;

      if(rapIndex_Gen >= 0 && rapForPTIndex_Gen > 0 && pTIndex_Gen > 0 && DimuonInPS == kTRUE){

	//==============================
	calcPol(*muPos_Gen, *muNeg_Gen);
	//==============================
      
//   	weight *= fPTCASCADE->Eval(onia_Gen_pt) / fPT->Eval(onia_Gen_pt);
  	weight *= fPTATLAS->Eval(onia_Gen_pt) / fPT->Eval(onia_Gen_pt);

	//fill the generator level histograms
	for(int iFrame = 0; iFrame < jpsi::kNbFrames; iFrame++){

	  //weight = CalcPolWeight(thisCosTh[iFrame]);

	  //histos for neg. and pos. rapidity separately:
	  if(rapIndex_Gen >= 0)
	    hGen2D_pol_pT_rapNP[iFrame][0][rapIndex_Gen]->Fill(thisCosTh[iFrame], thisPhi[iFrame], weight);
	  if(pTIndex_Gen > 0 && rapIndex_Gen >= 0)
	    hGen2D_pol_pT_rapNP[iFrame][pTIndex_Gen][rapIndex_Gen]->Fill(thisCosTh[iFrame], thisPhi[iFrame], weight);
	
	  //histos taking together +y and -y
	  hGen2D_pol_pT_rap[iFrame][0][0]->Fill(thisCosTh[iFrame], thisPhi[iFrame], weight);
	  if(rapIntegratedPTIndex_Gen > 0)
	    hGen2D_pol_pT_rap[iFrame][rapIntegratedPTIndex_Gen][0]->Fill(thisCosTh[iFrame], thisPhi[iFrame], weight);
	  if(rapForPTIndex_Gen > 0)
	    hGen2D_pol_pT_rap[iFrame][0][rapForPTIndex_Gen]->Fill(thisCosTh[iFrame], thisPhi[iFrame], weight);
	  if(pTIndex_Gen > 0 && rapForPTIndex_Gen > 0)
	    hGen2D_pol_pT_rap[iFrame][pTIndex_Gen][rapForPTIndex_Gen]->Fill(thisCosTh[iFrame], thisPhi[iFrame], weight);
	  
	  //histos taking together +y and -y and phi-4-folding
	  Double_t phiFolded = thisPhi[iFrame];
	  Double_t thetaAdjusted = thisCosTh[iFrame];
	  if(thisPhi[iFrame] > -90. && thisPhi[iFrame] < 0.)
	    phiFolded *= -1;
	  else if(thisPhi[iFrame] > 90 && thisPhi[iFrame] < 180){
	    phiFolded = 180. - thisPhi[iFrame];
	    thetaAdjusted *= -1;
	  }
	  else if(thisPhi[iFrame] > -180. && thisPhi[iFrame] < -90.){
	    phiFolded = 180. + thisPhi[iFrame];
	    thetaAdjusted *= -1;
	  }
	  hGen2D_pol_pT_rap_phiFolded[iFrame][0][0]->Fill(thetaAdjusted, phiFolded, weight);
	  if(rapIntegratedPTIndex_Gen > 0)
	    hGen2D_pol_pT_rap_phiFolded[iFrame][rapIntegratedPTIndex_Gen][0]->Fill(thetaAdjusted, phiFolded, weight);
	  if(rapForPTIndex_Gen > 0)
	    hGen2D_pol_pT_rap_phiFolded[iFrame][0][rapForPTIndex_Gen]->Fill(thetaAdjusted, phiFolded, weight);
	  if(pTIndex_Gen > 0 && rapForPTIndex_Gen > 0)
	    hGen2D_pol_pT_rap_phiFolded[iFrame][pTIndex_Gen][rapForPTIndex_Gen]->Fill(thetaAdjusted, phiFolded, weight);
	}
      }
    }
    //===================================================================
    //end of Generator level block
    //===================================================================

    //continue only to process RECO info if
    //there is really a RECO dimuon in the event:
    if(onia->Pt() > 990.) 
      continue;

    //reject processing of events where the dimuon type (GG, GT or TT)
    //does not correspond to the chosen one
    if(selDimuType < 3 && JpsiType != selDimuType)
      continue;
    else if(selDimuType == 3 && JpsiType > 1) //only GG or GT
      continue;

//     Reco_StatEv->Fill(2.5);//count all events

    Double_t etaMuPos = muPos->PseudoRapidity();
    Double_t etaMuNeg = muNeg->PseudoRapidity();
    Double_t pTMuPos = muPos->Pt();
    Double_t pTMuNeg = muNeg->Pt();
    Double_t pMuPos = muPos->P();
    Double_t pMuNeg = muNeg->P();

    //take muons only within a certain eta range
    if((fabs(etaMuPos) < jpsi::etaPS[0] && pTMuPos < jpsi::pTMuMin[0]) || //mid-rapidity cut
       (fabs(etaMuPos) > jpsi::etaPS[0] && fabs(etaMuPos) < jpsi::etaPS[1] && pMuPos < jpsi::pMuMin[1]) ||
       (fabs(etaMuPos) > jpsi::etaPS[1] && fabs(etaMuPos) < jpsi::etaPS[2] && pTMuPos < jpsi::pTMuMin[2]))
      continue;
    //(b) on the negative muon
    if((fabs(etaMuNeg) < jpsi::etaPS[0] && pTMuNeg < jpsi::pTMuMin[0]) || //mid-rapidity cut
       (fabs(etaMuNeg) > jpsi::etaPS[0] && fabs(etaMuNeg) < jpsi::etaPS[1] && pMuNeg < jpsi::pMuMin[1]) ||
       (fabs(etaMuNeg) > jpsi::etaPS[1] && fabs(etaMuNeg) < jpsi::etaPS[2] && pTMuNeg < jpsi::pTMuMin[2]))
      continue;

//     Reco_StatEv->Fill(4.5);

    Double_t onia_mass = onia->M();
    Double_t onia_pt = onia->Pt();
    Double_t onia_P = onia->P();
    Double_t onia_eta = onia->PseudoRapidity();
    Double_t onia_rap = onia->Rapidity();
    Double_t onia_phi = onia->Phi();
    Double_t onia_mT = sqrt(onia_mass*onia_mass + onia_pt*onia_pt);

    Int_t rapIndex = -1;
    for(int iRap = 0; iRap < 2*jpsi::kNbRapBins; iRap++){
      if(onia_rap > jpsi::rapRange[iRap] && onia_rap < jpsi::rapRange[iRap+1]){
    	rapIndex = iRap;
    	break;
      }
    }
    Int_t rapForPTIndex = -1;
    for(int iRap = 0; iRap < jpsi::kNbRapForPTBins; iRap++){
      if(TMath::Abs(onia_rap) > jpsi::rapForPTRange[iRap] && 
	 TMath::Abs(onia_rap) < jpsi::rapForPTRange[iRap+1]){
	 rapForPTIndex = iRap+1;
	break;
      }
    }
    Int_t pTIndex = -1;
    for(int iPT = 0; iPT < jpsi::kNbPTBins[rapForPTIndex]; iPT++){
      if(onia_pt > jpsi::pTRange[rapForPTIndex][iPT] && onia_pt < jpsi::pTRange[rapForPTIndex][iPT+1]){
	pTIndex = iPT+1;
	break;
      }
    }
    Int_t rapIntegratedPTIndex = -1;
    for(int iPT = 0; iPT < jpsi::kNbPTBins[0]; iPT++){
      if(onia_pt > jpsi::pTRange[0][iPT] && onia_pt < jpsi::pTRange[0][iPT+1]){
	rapIntegratedPTIndex = iPT+1;
	break;
      }
    }
    if(rapIndex < 0){
      // printf("rapIndex %d, rap(onia) = %f\n", rapIndex, onia_rap);
      continue;
    }
    if(rapForPTIndex < 1){
      // printf("rapForPTIndex %d, rap(onia) = %f\n", rapForPTIndex, onia_rap);
      continue;
    }
    if(pTIndex < 1){
      // printf("pTIndex %d, pT(onia) = %f\n", pTIndex, onia_pt);
      continue;
    }

//     Reco_StatEv->Fill(5.5);

//     //select events with a cut on the lifetime to reject NP J/psis:
//     if(Jpsict > jpsi::JpsiCtauMax)
//       continue;

//     Reco_StatEv->Fill(6.5);

    //select events within a narrow mass window around the J/psi
    //(rapidity dependence of the resolution --> different mass windows)
    //values obtained from Gaussian fits in "plotMass.C"
    Double_t jPsiMassMin = jpsi::polMassJpsi[rapForPTIndex] - jpsi::nSigMass*jpsi::sigmaMassJpsi[rapForPTIndex];
    Double_t jPsiMassMax = jpsi::polMassJpsi[rapForPTIndex] + jpsi::nSigMass*jpsi::sigmaMassJpsi[rapForPTIndex];
    if(onia_mass < jPsiMassMin || onia_mass > jPsiMassMax)
      continue;

//     Reco_StatEv->Fill(7.5);

    if(TMath::Abs(onia_rap) > jpsi::rapYPS)
      continue;

//     Reco_StatEv->Fill(8.5);


    //remaining of the events will be used for the analysis
    countRecEvent++;

    //fill mass, phi, pt, eta and rap distributions
    //a) all bins
    Reco_Onia_mass[0][0]->Fill(onia_mass);
    Reco_Onia_mass[rapIntegratedPTIndex][0]->Fill(onia_mass);
    Reco_Onia_mass[0][rapForPTIndex]->Fill(onia_mass);
    //
    if(onia_mass > (jpsi::polMassJpsi[rapForPTIndex] - 2.*jpsi::sigmaMassJpsi[rapForPTIndex]) &&
       onia_mass < (jpsi::polMassJpsi[rapForPTIndex] + 2.*jpsi::sigmaMassJpsi[rapForPTIndex])){
	 Reco_Onia_phi[0][0]->Fill(onia_phi);
	 Reco_Onia_phi[rapIntegratedPTIndex][0]->Fill(onia_phi);
	 Reco_Onia_phi[0][rapForPTIndex]->Fill(onia_phi);
	 //      
	 Reco_Onia_pt[0]->Fill(onia_pt);
    }
    //b) individual pT and rap bins:
    Reco_Onia_mass[pTIndex][rapForPTIndex]->Fill(onia_mass);
    if(onia_mass > (jpsi::polMassJpsi[rapForPTIndex] - 2.*jpsi::sigmaMassJpsi[rapForPTIndex]) &&
       onia_mass < (jpsi::polMassJpsi[rapForPTIndex] + 2.*jpsi::sigmaMassJpsi[rapForPTIndex])){

      Reco_Onia_phi[pTIndex][rapForPTIndex]->Fill(onia_phi);
      Reco_Onia_pt[rapForPTIndex]->Fill(onia_pt);

      Reco_Onia_rap_pT->Fill(onia_rap, onia_pt);
    }

    //=====================
    calcPol(*muPos, *muNeg);
    //=====================

//     //===================================================
//     //calculate delta, the angle between the CS and HX frame
//     //Formula from: EJP C69 (2010) 657
//     Double_t deltaHXToCS = TMath::ACos(onia_mass * onia->Pz() / (onia_mT * onia_P));
//     //     Double_t deltaCSToHX = -deltaHXToCS;
//     Double_t sin2Delta = pow((onia_pt * onia->Energy() / (onia_P * onia_mT)),2);
//     //sin2Delta does not change sign when going from HX-->CS or vice versa
//     hDelta[pTIndex][rapForPTIndex]->Fill(deltaHXToCS * 180./TMath::Pi());
//     hSin2Delta[pTIndex][rapForPTIndex]->Fill(sin2Delta);
//     //===================================================

//     Double_t deltaPhi = muPos->Phi() - muNeg->Phi();
//     if(deltaPhi < -TMath::Pi()) deltaPhi += 2.*TMath::Pi();
//     else if(deltaPhi > TMath::Pi()) deltaPhi -= 2.*TMath::Pi();

//     //debugging histos
//     hPhiPos_PhiNeg[pTIndex][rapForPTIndex]->Fill(180./TMath::Pi() * muNeg->Phi(), 180./TMath::Pi() * muPos->Phi());
//     hPtPos_PtNeg[pTIndex][rapForPTIndex]->Fill(muNeg->Pt(), muPos->Pt());
//     hEtaPos_EtaNeg[pTIndex][rapForPTIndex]->Fill(muNeg->PseudoRapidity(), muPos->PseudoRapidity());
//     hDeltaPhi[pTIndex][rapForPTIndex]->Fill(deltaPhi);

//     Reco_mupl_pt[pTIndex][rapForPTIndex]->Fill(muPos->Pt());
//     Reco_mupl_eta[pTIndex][rapForPTIndex]->Fill(muPos->PseudoRapidity());
//     Reco_mupl_phi[pTIndex][rapForPTIndex]->Fill(muPos->Phi());
      
//     Reco_mumi_pt[pTIndex][rapForPTIndex]->Fill(muNeg->Pt());
//     Reco_mumi_eta[pTIndex][rapForPTIndex]->Fill(muNeg->PseudoRapidity());
//     Reco_mumi_phi[pTIndex][rapForPTIndex]->Fill(muNeg->Phi());

    //fill the histos for all the different frames
    for(int iFrame = 0; iFrame < jpsi::kNbFrames; iFrame++){

// 	weight *= CalcPolWeight(thisCosTh[iFrame]);

	//histos for neg. and pos. rapidity separately:
	if(rapIndex >= 0)
	  Reco2D_pol_pT_rapNP[iFrame][0][rapIndex]->Fill(thisCosTh[iFrame], thisPhi[iFrame], weight);
	if(pTIndex > 0 && rapIndex >= 0)
	  Reco2D_pol_pT_rapNP[iFrame][pTIndex][rapIndex]->Fill(thisCosTh[iFrame], thisPhi[iFrame], weight);
	
	//histos taking together +y and -y
	Reco2D_pol_pT_rap[iFrame][0][0]->Fill(thisCosTh[iFrame], thisPhi[iFrame], weight);
	if(rapIntegratedPTIndex > 0)
	  Reco2D_pol_pT_rap[iFrame][rapIntegratedPTIndex][0]->Fill(thisCosTh[iFrame], thisPhi[iFrame], weight);
	if(rapForPTIndex > 0)
	  Reco2D_pol_pT_rap[iFrame][0][rapForPTIndex]->Fill(thisCosTh[iFrame], thisPhi[iFrame], weight);
	if(pTIndex > 0 && rapForPTIndex > 0)
	  Reco2D_pol_pT_rap[iFrame][pTIndex][rapForPTIndex]->Fill(thisCosTh[iFrame], thisPhi[iFrame], weight);
	  
	//histos taking together +y and -y and phi-4-folding
	Double_t phiFolded = thisPhi[iFrame];
	Double_t thetaAdjusted = thisCosTh[iFrame];
	if(thisPhi[iFrame] > -90. && thisPhi[iFrame] < 0.)
	  phiFolded *= -1;
	else if(thisPhi[iFrame] > 90 && thisPhi[iFrame] < 180){
	  phiFolded = 180. - thisPhi[iFrame];
	  thetaAdjusted *= -1;
	}
	else if(thisPhi[iFrame] > -180. && thisPhi[iFrame] < -90.){
	  phiFolded = 180. + thisPhi[iFrame];
	  thetaAdjusted *= -1;
	}
	Reco2D_pol_pT_rap_phiFolded[iFrame][0][0]->Fill(thetaAdjusted, phiFolded, weight);
	if(rapIntegratedPTIndex > 0)
	  Reco2D_pol_pT_rap_phiFolded[iFrame][rapIntegratedPTIndex][0]->Fill(thetaAdjusted, phiFolded, weight);
	if(rapForPTIndex > 0)
	  Reco2D_pol_pT_rap_phiFolded[iFrame][0][rapForPTIndex]->Fill(thetaAdjusted, phiFolded, weight);
	if(pTIndex > 0 && rapForPTIndex > 0)
	  Reco2D_pol_pT_rap_phiFolded[iFrame][pTIndex][rapForPTIndex]->Fill(thetaAdjusted, phiFolded, weight);
      }

  }//loop over entries

  printf("nb. of rec. events is %d of a total of %d events\n", (Int_t) countRecEvent, (Int_t) nentries);
}
void fillTree(TTree*& tree, TGraph*& graph, double& limit, double& lowlimit, unsigned int itype, std::map<double, std::string>& tanb_values, bool upper_exclusion, unsigned int verbosity)
{
  double value=-99;
  double tanb_help=-99;
  unsigned int ibin=0;
  // fill graph with scanned points
  cout << "now looping on  map" << endl;
  for(std::map<double, std::string>::const_iterator tanb = tanb_values.begin(); tanb!=tanb_values.end(); ++tanb){
    value = singlePointLimit(tanb->second, tanb->first, itype, verbosity);
    cout << "value = " << value << " = singlePointLimit(" << tanb->second <<", " << tanb->first << ", " << itype << ", " << verbosity << ");" << endl;
    if( value>0 ){
      graph->SetPoint(ibin++, tanb->first, value); 
      cout << "graph->SetPoint("<< ibin++ <<", " << tanb->first<<",  "<< value << ");"<< endl; 
    }
    tanb_help=tanb->first;
  }
  cout << "Filled graph. Will now determine the smooth curve on graph for interpolation" << endl;
  // determine smooth curve on graph for interpolation
  TSpline3* spline = new TSpline3("spline", graph, "r", 3., 10.);
  // linear polarisation func
  TF1 *fnc = 0;
  // determine all crossing points with y==1 
  std::vector<CrossPoint> points = crossPoints(graph);
  
  int dist = 1;
  bool filled = false, lowfilled=false;
  unsigned int np = 0;
  unsigned int steps = 10e6; 
  if(points.size()>0) limit = graph->GetX()[upper_exclusion ? points.begin()->first : points.end()->first];

  cout << "Starting loop on the points for determining crossings. Points.size()=" << points.size() << endl;
  for(std::vector<CrossPoint>::const_reverse_iterator point = points.rbegin(); point!=points.rend(); ++point, ++np){
  //for(std::vector<CrossPoint>::iterator point = points.begin(); point!=points.end(); ++point, ++np){
    //double min = (point->first-dist)>0 ? graph->GetX()[point->first-dist] : graph->GetX()[0]; 
    double min = (point->first)>0 ? graph->GetX()[point->first] : graph->GetX()[0]; 
    double max = (point->first+dist)<graph->GetN() ? graph->GetX()[point->first+dist] : graph->GetX()[graph->GetN()-1];

    //double y_min = (point->first-dist)>0 ? graph->GetY()[point->first-dist] : graph->GetY()[0]; 
    double y_min = (point->first)>0 ? graph->GetY()[point->first] : graph->GetY()[0];
    double y_max = (point->first+dist)<graph->GetN() ? graph->GetY()[point->first+dist] : graph->GetY()[graph->GetN()-1];

    vector<double> crossing;
    crossing.push_back((min-max-y_max*min+y_min*max)/(y_min-y_max));
    //double crossing;
    //crossing = (1.-y_min)/(y_max-y_min)*(max-min); 
				  
    double deltaM = -999.;
    double offset = min; double step_size = (max-min)/steps;
    double splinelimit;
    for(unsigned int scan=0; scan<=steps; ++scan){
      if(deltaM<0 || fabs(spline->Eval(offset+scan*step_size)-1.)<deltaM){
	splinelimit=offset+scan*step_size;
	deltaM=fabs(spline->Eval(offset+scan*step_size)-1.);
      }
    }
    std::cout << "****************************************************************" << std::endl;
    std::cout << "* [" << np+1 << "|" << point->second << "] asymptotic limit(";
    std::cout << limitType(itype) << ") :" << crossing[np] << " -- " << splinelimit << " deltaM : " << deltaM;
//     if(((upper_exclusion && point->second) || (!upper_exclusion && !(point->second))) && !filled){
//       //std::cout << "limit is taken from linear interpolation at the moment" << std::endl;
//       //limit = crossing;
//       std::cout << "    [-->to file]"; filled=true; tree->Fill();
//     }
    if(np==0){
      fnc = new TF1("fnc", "[0]*x+[1]", min, max);
      fnc->SetParameter(0, (y_min-y_max)/(min-max));
      fnc->SetParameter(1, (y_max*min-y_min*max)/(min-max));
      std::cout << std::endl;
      std::cout << "high limit is taken from linear interpolation at the moment" << std::endl;
      limit = crossing[np];
      std::cout << "high limit = " << limit << std::endl;
      filled=true;
      //std::cout << "    [-->to file]"; filled=true; tree->Fill();
    }
    if(np==1){
       fnc = new TF1("fnc", "[0]*x+[1]", min, max);
       fnc->SetParameter(0, (y_min-y_max)/(min-max));
       fnc->SetParameter(1, (y_max*min-y_min*max)/(min-max));
       std::cout << std::endl;
       std::cout << "low limit is taken from a spline fit at the moment" << std::endl;
       lowlimit = splinelimit; //crossing[np];
       std::cout << "low limit = " << lowlimit << std::endl;
       lowfilled=true; 
       //std::cout << "    [-->to file]"; lowfilled=true; tree->Fill();
    }
    std::cout << endl;
    std::cout << "****************************************************************" << std::endl;
  }
  if(filled){ 
    if(lowfilled) {std::cout << "    [-->to file]"; tree->Fill();}
    else{ lowlimit = 0.5; std::cout << "    [-->to file]"; tree->Fill();}
  }
  // catch cases where no crossing point was found
  if(!filled){
    if(value<1)
      {
	std::cout << "WARNING: no crossing found - all tanb values excluded: " << value << std::endl;
 	if(itype == observed)     { limit=1.00; lowlimit=1.00;}
 	if(itype == plus_2sigma)  { limit=3.00; lowlimit=3.00;}
 	if(itype == plus_1sigma)  { limit=2.00; lowlimit=2.00;}
 	if(itype == expected)     { limit=1.50; lowlimit=1.50;}
 	if(itype == minus_1sigma) { limit=1.00; lowlimit=1.00;}
 	if(itype == minus_2sigma) { limit=0.50; lowlimit=0.50;}
//	limit=2;
//	lowlimit=2;
	tree->Fill();
      }
    else
      {
	std::cout << "WARNING: no crossing found - no tanb value excluded: " << value << " -- " << tanb_help << std::endl;
	if(itype == observed)     { limit=tanb_help*value; }
	if(itype == plus_2sigma)  { limit=tanb_help*value; }
	if(itype == plus_1sigma)  { limit=tanb_help*value; }
	if(itype == expected)     { limit=tanb_help*value; }
	if(itype == minus_1sigma) { limit=tanb_help*value; }
	if(itype == minus_2sigma) { limit=tanb_help*value; }
	lowlimit=0.2;///////0.5;
	tree->Fill();
      }
  }
  cout << "Evaluated crossings. Now plotting" << endl;
  //if( verbosity>0 ){
    std::string monitor = std::string("SCAN-")+limitType(itype);
    TCanvas* canv = new TCanvas(monitor.c_str(), monitor.c_str(), 600, 600);
    cout << "Canva created. Now creating frame taking values from graph" << endl;
    cout << "Graph getx " << graph->GetX()[0] << endl;
    cout << "Graph getn " << graph->GetN() << endl;
    cout << "Graph getxn " << graph->GetX()[graph->GetN()-1];
    TH1F* frame = canv->DrawFrame(graph->GetX()[0]-0.1, 0., graph->GetX()[graph->GetN()-1]+0.1, 10.);
    cout << "Frame created, taking values from graph" << endl;
    canv->SetGridx(1); canv->SetGridy(1); canv->cd(); 
    graph->SetMarkerStyle(20.); 
    graph->SetMarkerColor(kBlack); 
    graph->SetMarkerSize(1.3); 
    graph->Draw("P");
    //spline->SetLineColor(kBlue); 
    //spline->SetLineWidth(3.); 
    //spline->Draw("same");
    if(filled) fnc->SetLineColor(kRed);
    if(filled) fnc->SetLineWidth(3.);
    if(filled) fnc->Draw("same");
    canv->Print(monitor.append(".png").c_str(), "png");
    delete frame; delete canv; delete spline;
    if(filled) delete fnc;
    //}
  return;
}
Example #24
0
void bToDRawYield()
{
  gStyle->SetTextSize(0.05);
  gStyle->SetTextFont(42);
  gStyle->SetPadRightMargin(0.04);
  gStyle->SetPadLeftMargin(0.14);
  gStyle->SetPadTopMargin(0.1);
  gStyle->SetPadBottomMargin(0.14);
  gStyle->SetTitleX(.0f);
  gStyle->SetOptFit(1111);
  gStyle->SetOptStat(0);
  gStyle->SetOptTitle(0);

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

  TCanvas* c1 = new TCanvas();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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



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

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

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

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

      c2->cd(1);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      hD0DcaMCPSignal = hD0DcaMCPSignal0;
      hD0DcaMCNPSignal = hD0DcaMCNPSignal0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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



      divideBinWidth(hD0DcaDataFit);

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

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

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

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

      setColorTitleLabel(hD0DcaData, 1);

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

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

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

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

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

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

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

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

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

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

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

      int nSmear = 1000;

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

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

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

      c4->cd(4);

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

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

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

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

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

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

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

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

      c1->cd();

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

      delete hD0DcaMCPSignal;
      delete hD0DcaMCNPSignal;

    }
  c1->cd();

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

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

  c1->SetLogy();

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

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

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

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

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

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

	cout<<"end of main"<<endl;
}
Example #25
0
int CaloL3(const char *ctype="Calo")
{

  bool iSave=false;

  double minx=1.0;

  LoadStyle();
  gStyle->SetOptStat(1);
  gStyle->SetOptFit(1);

  //string outdir="txtfiles/";
  string outdir="junk/";
  cout << " # of bins in pt : "  << nbins << endl;
  //return 0;
  
  TVirtualFitter::SetDefaultFitter("Minuit");
  TH1F *hrsp[knj][nbins];
  TGraphErrors *grsp[knj], *gcor[knj];
  TH1F *hMean[knj], *hRMS[knj];

  //TFile *fin = new TFile("jra_hiF_akcalo_ppReco_757p1_dijet.root","r");

  //TFile *fin = new TFile("jra_hiF_akcalo_ppReco_757p1_dijet_fulleta_fullpt.root","r");

  TFile *fin = new TFile("jra_hiF_akcalo_ppReco_757p1_HcalRespCorrs_v4_00_mc_dijet.root","r");
  double refptmin=0;
  double refptmax=1000;

  TLegend *l0 = getLegend(0.6349664,0.3265565,0.8491835,0.7128335);
  l0->SetHeader(Form("Anti-k_{T}, %s",ctype));
  TLegend *l1 = getLegend(0.1500646,0.5052258,0.3653091,0.7490942);
  l1->SetHeader("");

  TF1 *fgaus=0;
  TH1F *hrefpt=0, *hjetpt=0;

  int njmin=0;
  int njmax=knj;
  for(int i=njmin; i<njmax; i++){

    grsp[i] = new TGraphErrors(nbins);
    gcor[i] = new TGraphErrors(nbins);

    //grsp[i]->SetName(Form("L3RspVsRefPt_%d",i));
    grsp[i]->SetName(Form("L3RspVsRefPt_%s",calgo[i]));
    grsp[i]->SetTitle(Form("L3RspVsRefPt %s",calgo[i]));
    grsp[i]->SetLineColor(1);
    grsp[i]->SetMarkerColor(1);
    grsp[i]->SetMarkerStyle(20);
    grsp[i]->SetMarkerSize(1.2);

    //gcor[i]->SetName(Form("L3CorVsJetPt_%d",i));
    gcor[i]->SetName(Form("L3CorVsJetPt_%s",calgo[i]));
    gcor[i]->SetTitle(Form("L3CorVsJetPt %s",calgo[i]));
    gcor[i]->SetLineColor(1);
    gcor[i]->SetMarkerColor(1);
    gcor[i]->SetMarkerStyle(20);
    gcor[i]->SetMarkerSize(1.2);


    hMean [i] = new TH1F(Form("hMean_%d",i),Form("%s%s",calgo[i],ctype),nbins,ptbins);
    hMean [i]->SetMarkerColor(1);
    hMean [i]->SetMarkerStyle(20);
    hMean [i]->SetLineColor(1);
    hMean [i]->GetXaxis()->SetMoreLogLabels();
    hMean [i]->GetXaxis()->SetNoExponent();

    hRMS [i] = new TH1F(Form("hRMS_%d",i),Form("%s%s",calgo[i],ctype),nbins,ptbins);
    hRMS [i]->SetMarkerColor(1);
    hRMS [i]->SetMarkerStyle(20);
    hRMS [i]->SetLineColor(1);


    std::ostringstream strs;
    //strs << "ak"   << i+1 << "CaloJetAnalyzer/";
    strs << calgo[i] << "CaloJetAnalyzer/";
    cout << " Running for : " << strs.str().c_str() << endl;

    for(int j=0; j<nbins; j++){
      
      if(ptbins[j]<minx)continue;

      //if(j<2)continue;
      std::ostringstream spt; 
      spt << ptbins[j] << "to" << ptbins[j+1];
      //cout << " ptbins : "  << ptbins[j] << endl;
      
      std::string sone  (strs.str()+"RefPt_Barrel_RefPt"+spt.str());
      std::string stwo  (strs.str()+"JetPt_Barrel_RefPt"+spt.str());
      std::string sthree(strs.str()+"RelRsp_Barrel_RefPt"+spt.str());

      hrefpt     = (TH1F*)fin->Get(sone.c_str());
      hjetpt     = (TH1F*)fin->Get(stwo.c_str());
      hrsp[i][j] = (TH1F*)fin->Get(sthree.c_str());
      
      //hrsp[i][j]->Rebin(2);

      assert(hrefpt->GetEntries()>0 && hjetpt->GetEntries()>0);

      // if( ptbins[j] < 30.0 ){
      // 	SetHistRange(hrsp[i][j]);
      // }

      double refpt   =hrefpt->GetMean();
      double erefpt  =hrefpt->GetMeanError();
      double jetpt   =hjetpt->GetMean();
      double ejetpt  =hjetpt->GetMeanError();


      hrsp[i][j]->SetLineColor(1);
      hrsp[i][j]->SetMarkerColor(1);
      hrsp[i][j]->SetMarkerStyle(20);
      if(j==0)l0->AddEntry(hrsp[i][j],Form("R = %0.1f",(i+1)*0.1),"p");

      //if(i==0)cout <<"  refpt : " << refpt << " rawpt : " << jetpt << endl;

      //if(j<10)hrsp[i][j]->Rebin(2);
      //hrsp[i][j]->Rebin(5);

      double norm  = hrsp[i][j]->GetMaximumStored(); 
      double rms   = hrsp[i][j]->GetRMS(); 
      double peak  = hrsp[i][j]->GetMean();
      //double peak  = (GetPeak(hrsp[i][j]) +  hrsp[i][j]->GetMean())/2.;
      double epeak = hrsp[i][j]->GetMeanError();

      // double tmppeak = GetPeak(hrsp[i][j]);
      // fgaus = new TF1("fgaus","gaus", 0.07, 1.2);
      // fgaus->SetParameters(norm, peak, 0.15);
      // //fgaus->SetParLimits(1, peak - 1.5*rms, peak + 1.5*rms);
      // int fitstatus = hrsp[i][j]->Fit(fgaus,"QR");      
      // peak    = (fgaus==0) ? hrsp[i][j]->GetMean()      :  fgaus->GetParameter(1);
      // epeak   = (fgaus==0) ? hrsp[i][j]->GetMeanError() :  fgaus->GetParError(1);

      
       // if(i==0)fit_dscb(hrsp[i][j], 1.03, minx, 5, Form("%s%s",calgo[i],ctype), 0.17, 1.70);      
       // else if(i==5)fit_dscb(hrsp[i][j], 1.00, minx, 5, Form("%s%s",calgo[i],ctype), 0.05, 1.45);      
       // else fit_dscb(hrsp[i][j], 1.03, minx, 5, Form("%s%s",calgo[i],ctype), 0.10, 1.50);      

      if(i==0)fit_dscb(hrsp[i][j], 1.03, minx, 5, Form("%s%s",calgo[i],ctype), 0.17, 1.70);      
      else if(i !=5 )fit_dscb(hrsp[i][j], 1.03, minx, 5, Form("%s%s",calgo[i],ctype), 0.10, 1.50);      

      //! pp reco
      // if( i==0 )fit_dscb(hrsp[i][j], 0.85, minx, 5, Form("%s%s",calgo[i],ctype));      
      // else if(i==1)fit_dscb(hrsp[i][j], 1.03, minx, 5, Form("%s%s",calgo[i],ctype));      
      // else if(i==2)fit_dscb(hrsp[i][j], 1.00, minx, 5, Form("%s%s",calgo[i],ctype));      
      // else if(i==3)fit_dscb(hrsp[i][j], 1.05, minx, 5, Form("%s%s",calgo[i],ctype));      
      // else if(i==4)fit_dscb(hrsp[i][j], 1.05, minx, 5, Form("%s%s",calgo[i],ctype));      
      // else fit_dscb(hrsp[i][j], 1.00, minx, 5, Form("%s%s",calgo[i],ctype));      

      //! HI reco
      // if( i==0 )fit_dscb(hrsp[i][j], 0.75, minx, 5, Form("ak%d%s",i+1,ctype));      
      // else if(i==1)fit_dscb(hrsp[i][j], 0.95, minx, 5, Form("ak%d%s",i+1,ctype));      
      // else if(i==2)fit_dscb(hrsp[i][j], 1.45, minx, 5, Form("ak%d%s",i+1,ctype));      
      // else if(i==3 || i==4)fit_dscb(hrsp[i][j], 1.50, minx, 4, Form("ak%d%s",i+1,ctype));      
      // else fit_dscb(hrsp[i][j], 1.30, minx, 5, Form("ak%d%s",i+1,ctype));      


      TF1*  frelrsp = (TF1*)hrsp[i][j]->GetListOfFunctions()->Last();
      peak    = (frelrsp==0) ? hrsp[i][j]->GetMean()      :  frelrsp->GetParameter(1);
      epeak   = (frelrsp==0) ? hrsp[i][j]->GetMeanError() :  frelrsp->GetParError(1);

      //cout << " peak : " << peak << "  mean : " << hrsp[i][j]->GetMean()  << "  " << frelrsp->GetParameter(1) << endl;

      double cor  = 1.0/peak;
      double ecor = cor*cor*epeak;

      //if(i==0)cout <<ptbins[j] << " ratio of  " << refpt/jetpt << " " << cor << "  " <<  ftemp->Eval(jetpt) << " " << 1/ ftemp->Eval(jetpt) << endl;
      grsp[i]->SetPoint     (j, refpt,  peak);
      grsp[i]->SetPointError(j, erefpt, epeak);
      gcor[i]->SetPoint     (j, jetpt,  cor);
      gcor[i]->SetPointError(j, ejetpt, ecor);
    }
  }
  if( gPad )gPad->Close();
  //hrsp[0][0]->Draw("p");
  //return 0;
  
  int ipad=0;
  //! 0 - 20 GeV
  TCanvas *c98[knj];
  for(int nj=njmin;nj<njmax;nj++){
    c98[nj] = new TCanvas(Form("c99_%d",nj),Form("Fine %s Fitting plots",calgo[nj]),100,102,1399,942);
    c98[nj]->Divide(6,3,0,0);
    //c98[nj]->Divide(10,5,0,0);
    //c98[nj]->Divide(6,5,0,0);
    //c98[nj]->Divide(7,4,0,0);
    //c98[nj]->Divide(6,4,0,0);
    ipad=0;
    for(int ip=0;ip<nbins;ip++){      
      if(ptbins[ip]<minx)continue;
      c98[nj]->cd(++ipad);
      gPad->SetLeftMargin(0.15);
      gPad->SetRightMargin(0.01);
      gPad->SetBottomMargin(0.15);
      gPad->SetLogy();
      //if(ipad%10==0)gPad->SetRightMargin(0.02);
      //if(ipad%(ip+1)==0)gPad->SetLeftMargin(0.15);
    
      //hrsp[nj][ip]->SetMaximum(hrsp[nj][ip]->GetMaximum() + 0.25*hrsp[nj][ip]->GetMaximum());
      hrsp[nj][ip]->SetMaximum(hrsp[nj][ip]->Integral()*2e-00);
      hrsp[nj][ip]->SetMinimum(hrsp[nj][ip]->Integral()*1e-07);
      hrsp[nj][ip]->SetTitle(0);
      hrsp[nj][ip]->GetXaxis()->SetTitle("<reco jet p_{T} / gen jet p_{T}>");
      hrsp[nj][ip]->GetXaxis()->SetTitleFont(42);
      hrsp[nj][ip]->GetXaxis()->SetLabelFont(42);
      hrsp[nj][ip]->GetXaxis()->SetLabelSize(0.08);
      hrsp[nj][ip]->GetXaxis()->SetTitleSize(0.07);
      hrsp[nj][ip]->GetXaxis()->SetNdivisions(507);
      hrsp[nj][ip]->GetYaxis()->SetTitle("");
      hrsp[nj][ip]->GetYaxis()->SetTitleFont(42);
      hrsp[nj][ip]->GetYaxis()->SetLabelFont(42);
      hrsp[nj][ip]->GetYaxis()->SetLabelSize(0.08);
      hrsp[nj][ip]->GetYaxis()->SetNdivisions(507);
      
      hrsp[nj][ip]->SetMarkerStyle(20);
      hrsp[nj][ip]->SetMarkerColor(1);
      hrsp[nj][ip]->SetLineColor(1);
      hrsp[nj][ip]->SetMarkerSize(1.1);
      hrsp[nj][ip]->Draw("hist");  
      
      TF1 *fdscb = (TF1*)hrsp[nj][ip]->GetFunction("fdscb");
      if(fdscb){
	fdscb->SetLineWidth(1);
   	fdscb->SetLineColor(2);
   	fdscb->SetLineColor(2);
   	fdscb->Draw("lsame");
      }
      TF1 *fgaus = (TF1*)hrsp[nj][ip]->GetFunction("fgaus");
      if(fgaus){
	fgaus->SetLineWidth(1);
   	fgaus->SetLineColor(4);
   	fgaus->Draw("lsame");
      }
      // TF1 *fdg = (TF1*)hrsp[nj][ip]->GetFunction("fdgaus");
      // if(fdg){
      // 	TF1 *fg1 = (TF1*)hrsp[nj][ip]->GetFunction("fg1");      
      // 	TF1 *fg2 = (TF1*)hrsp[nj][ip]->GetFunction("fg2");      
      // 	fdg->Draw("lsame");
      // 	fg1->Draw("lsame");
      // 	fg2->Draw("lsame");
      // }
      
      std::ostringstream strs; 
      strs << ptbins[ip] << "< p_{T} (GeV/c) <" << ptbins[ip+1];
      std::string spt = strs.str();
      
      if(ipad==1){drawText2(Form("%s%s",calgo[nj],ctype),0.28,0.90,18);      
	
   	drawText2(spt.c_str(),0.22,0.80,15);		
      } else drawText2(spt.c_str(),0.17,0.80,15);		
    }
    //if(nj!=0)c98[nj]->Close();
    //if( strcmp(calgo[nj],"ak4")!=0 )c98[nj]->Close();
  }
  //return 0;
  
  cout << endl;
  cout << endl;

  cout << "Fitting the L3 Response "  << endl;

  //cout << endl;
  //cout << endl;


  TF1 *fitrsp=0, *fitcor=0;
  std::string fcn_rsp="";
  std::string fcn_cor="";

  //! Org
  // fcn_rsp="[0]-[1]/(pow(log10(x),[2])+[3])";
  // fcn_cor="[0]+[1]/(pow(log10(x),[2])+[3])";

  //! Using this one
  //fcn_rsp="[0]-[1]/(pow(log10(x),[2])+[3])+[4]/x";
  //fcn_cor="[0]+[1]/(pow(log10(x),[2])+[3])-[4]/x";

  fcn_rsp="[0]-[1]/(pow(log10(x),[2])+[3])+[4]/x+[5]/x/x";
  fcn_cor="[0]+[1]/(pow(log10(x),[2])+[3])-[4]/x-[5]/x/x";

  // double *rawpt = 0;
  // double *genpt = 0;


  TCanvas *c11 = new TCanvas("c11","L3 Response",1217,707/*1531,683*/);
  c11->Divide(3,2);
  TCanvas *c12 = new TCanvas("c12","L3 Corrections",1217,707/*1531,683*/);
  c12->Divide(3,2);
  for(int i=njmin; i<njmax; i++){  
    c11->cd(i+1);
    fitrsp = new TF1("fitrsp",fcn_rsp.c_str(), minx, grsp[i]->GetX()[grsp[i]->GetN()-1]);
    fitrsp->SetParameter(0,1.0);
    fitrsp->SetParameter(1,1.0);
    fitrsp->SetParameter(2,1.0);
    fitrsp->SetParameter(3,1.0);
    fitrsp->SetParameter(4,1.0);
    fitrsp->SetParameter(5,1.0);
    
    
    grsp[i]->Fit(fitrsp,"QR");
    //if( i<knj )grsp[i]->Fit(fitrsp,"QR","",grsp[i]->GetX()[1],grsp[i]->GetX()[grsp[i]->GetN()-1]);
    //else grsp[i]->Fit(fitrsp,"QR");
    grsp[i]->SetMaximum(1.2);
    grsp[i]->SetMinimum(0.2);
    grsp[i]->Draw("ap");
    gPad->SetLogx();
    gPad->SetLeftMargin(0.15);
    gPad->SetBottomMargin(0.15);
    gPad->Update();

    grsp[i]->GetXaxis()->SetTitle("< Ref p_{T} > (GeV/c)");
    grsp[i]->GetXaxis()->SetTitleFont(42);
    grsp[i]->GetXaxis()->SetLabelFont(42);
    grsp[i]->GetXaxis()->SetLabelSize(0.06);
    grsp[i]->GetXaxis()->SetTitleSize(0.06);
    grsp[i]->GetXaxis()->SetNdivisions(507);
    grsp[i]->GetXaxis()->SetNoExponent();
    grsp[i]->GetXaxis()->SetMoreLogLabels();
    grsp[i]->GetYaxis()->SetTitle("L3 Response");
    grsp[i]->GetYaxis()->SetTitleFont(42);
    grsp[i]->GetYaxis()->SetLabelFont(42);
    grsp[i]->GetYaxis()->SetLabelSize(0.06);
    grsp[i]->GetYaxis()->SetTitleSize(0.06);
    grsp[i]->GetYaxis()->SetNdivisions(507);

    grsp[i]->GetYaxis()->SetRangeUser(0,1.160);
    //grsp[i]->GetXaxis()->SetRangeUser(15,600);
    drawText2(Form("%s%s",calgo[i],ctype),0.20,0.78,21);

    TPaveStats *strsp = (TPaveStats*)grsp[i]->FindObject("stats");
    strsp->SetX1NDC(0.46);
    strsp->SetY1NDC(0.18);
    strsp->SetX2NDC(0.87);
    strsp->SetY2NDC(0.59);
    strsp->Draw();
    //delete fitrsp;
    //continue;
    
    c12->cd(i+1);
    //cout << endl;
    //cout << endl;
    
    // cout << "Fitting the L3 Corrections "  << endl;
    // cout << endl;
  
    fitcor = new TF1("fitcor",fcn_cor.c_str(), minx, gcor[i]->GetX()[gcor[i]->GetN()-1]);
    fitcor->SetParameter(0,1.0);
    fitcor->SetParameter(1,1.0);
    fitcor->SetParameter(2,1.0);
    fitcor->SetParameter(3,1.0);
    fitcor->SetParameter(4,1.0);
    fitcor->SetParameter(5,1.0);    
    
    gcor[i]->Fit(fitcor,"QR");
    //if(i<knj)gcor[i]->Fit(fitcor,"QR","",gcor[i]->GetX()[1],gcor[i]->GetX()[gcor[i]->GetN()-1]);
    //else gcor[i]->Fit(fitcor,"QR");

    string algn=Form("%d",i+1);
    string era="JEC_pp_PYTHIA_TuneCUETP8M1_5020GeV_patch3";
    //string era="JEC_pp_HIReco_PYTHIA_TuneCUETP8M1_5020GeV_patch3";
    string txtfilename = outdir+era+"_L3Absolute_AK"+algn+"Calo.txt";
    ofstream outf(txtfilename.c_str());
    //outf.setf(ios::left);
    //cout<<"{1 JetEta 1 JetPt "<<fcn_cor<<" Correction L3Absolute}"<<endl;
    outf<<"{1 JetEta 1 JetPt "<<fcn_cor<<" Correction L3Absolute}"<<endl;
    // cout<<setw(12)<<-3.000                // eta_min
    //   	<<setw(12)<<+3.000                // eta_max
    //   	<<setw(12)<<fitcor->GetNpar()+2   // number of parameters + 2
    //   	<<setw(12)<<7.0                   // minimum pT
    //   	<<setw(11)<<1000.0;               // maximum pT

    outf<<setw(12)<<-3.000                // eta_min
     	<<setw(12)<<+3.000                // eta_max
     	<<setw(12)<<fitcor->GetNpar()+2   // number of parameters + 2
     	<<setw(12)<<7.0                   // minimum pT
     	<<setw(12)<<1000.0;               // maximum pT

    for(int p=0; p<fitcor->GetNpar(); p++){
      //cout<<setw(12)<<fitcor->GetParameter(p); // p0-p4
      outf<<setw(12)<<fitcor->GetParameter(p); // p0-p4
    }
    outf.close();
    //cout<<endl;

    // if(i==0)cout <<Form("if(i==%d)fl3cor->SetParameters(",i);
    // else cout <<Form("else if(i==%d)fl3cor->SetParameters(",i);
    // for(int p=0; p<fitcor->GetNpar(); p++){
    //   if(p==fitcor->GetNpar()-1)cout<<setw(12)<<fitcor->GetParameter(p); // p0-p4
    //   else cout<<setw(12)<<fitcor->GetParameter(p)<<","; // p0-p4
    // }
    // cout <<");"<<endl;
    
    // rawpt = gcor[i]->GetX();
    // genpt = grsp[i]->GetX();
    // for(int ix=0; ix<gcor[i]->GetN(); ix++){
    //   double cor_fac = fitcor->Eval(rawpt[ix]);
    //   double corrpt  =  cor_fac*rawpt[ix];
    //   //std::cout << " genpt : " << genpt[ix] << " rawpt : " << rawpt[ix] << " corrpt : "  << corrpt << " cor_fac : "  << cor_fac << std::endl;
    //   std::cout << genpt[ix] << "  : " << (fabs(corrpt - genpt[ix])/genpt[ix])*100. << std::endl;
    // }



    // gcor[i]->GetXaxis()->SetRangeUser(15,600);
    gcor[i]->SetMaximum(3.35);
    gcor[i]->SetMinimum(0.89);
    gcor[i]->Draw("ap");
    gPad->SetLogx();
    gPad->SetLeftMargin(0.15);
    gPad->SetBottomMargin(0.15);
    gPad->Update();

    gcor[i]->GetXaxis()->SetTitle("< raw jet p_{T} > (GeV/c)");
    gcor[i]->GetXaxis()->SetTitleFont(42);
    gcor[i]->GetXaxis()->SetLabelFont(42);
    gcor[i]->GetXaxis()->SetLabelSize(0.06);
    gcor[i]->GetXaxis()->SetTitleSize(0.06);
    gcor[i]->GetXaxis()->SetNdivisions(507);
    gcor[i]->GetXaxis()->SetNoExponent();
    gcor[i]->GetXaxis()->SetMoreLogLabels();
    gcor[i]->GetYaxis()->SetTitle("L3 Correction");
    gcor[i]->GetYaxis()->SetTitleFont(42);
    gcor[i]->GetYaxis()->SetLabelFont(42);
    gcor[i]->GetYaxis()->SetLabelSize(0.06);
    gcor[i]->GetYaxis()->SetTitleSize(0.06);
    gcor[i]->GetYaxis()->SetNdivisions(507);

    gcor[i]->GetXaxis()->SetMoreLogLabels();
    gcor[i]->GetXaxis()->SetNoExponent();
    drawText2(Form("%s%s",calgo[i],ctype),0.20,0.78,21);


    TPaveStats *stcor = (TPaveStats*)gcor[i]->FindObject("stats");
    stcor->SetX1NDC(0.48);
    stcor->SetY1NDC(0.53);
    stcor->SetX2NDC(0.89);
    stcor->SetY2NDC(0.89);
    stcor->Draw();
  
    // cout << endl;
    //delete fitcor;
    
  }
  if(iSave){
    c12->SaveAs("CorrectionPlots/L3Absolute_Corrections_ppReco_CaloJets_757p1.pdf");
  }

  TFile *fout = new TFile("l3calo_input.root","RECREATE");
  for(int nj=njmin;nj<njmax;nj++){
    fout->mkdir(Form("%sCaloJetAnalyzer",calgo[nj]),Form("%sCaloJetAnalyzer",calgo[nj]));
    fout->cd(Form("%sCaloJetAnalyzer",calgo[nj]));
    grsp[nj]->Write();
    gcor[nj]->Write();
    fout->cd("../");
  }
  fout->Close();

  return 0;
}
Example #26
0
TF1* fitMass(TH1D* hData, TH1D* hMCSignal, TH1D* hMCSwapped)
{
  Double_t setparam0=100.;
  Double_t setparam1=1.865;
  Double_t setparam2=0.03;
  Double_t setparam10=0.005;
  Double_t setparam8=0.1;
  Double_t setparam9=0.1;
  Double_t fixparam1=1.865;
  Double_t minhisto=1.7;
  Double_t maxhisto=2.0;

  TF1* f = new TF1("fMass","[0]*([7]*([9]*Gaus(x,[1],[2]*(1+[11]))/(sqrt(2*3.1415927)*[2]*(1+[11]))+(1-[9])*Gaus(x,[1],[10]*(1+[11]))/(sqrt(2*3.1415927)*[10]*(1+[11])))+(1-[7])*Gaus(x,[1],[8]*(1+[11]))/(sqrt(2*3.1415927)*[8]*(1+[11])))+[3]+[4]*x+[5]*x*x+[6]*x*x*x", 1.7, 2.0);
  f->SetParLimits(4,-1000,1000);
  f->SetParLimits(10,0.005,0.05);
  f->SetParLimits(2,0.01,0.1);
  f->SetParLimits(8,0.02,0.2);
  f->SetParLimits(7,0,1);
  f->SetParLimits(9,0,1);

  f->SetParameter(0,setparam0);
  f->SetParameter(1,setparam1);
  f->SetParameter(2,setparam2);
  f->SetParameter(10,setparam10);
  f->SetParameter(9,setparam9);

  f->FixParameter(8,setparam8);
  f->FixParameter(7,1);
  f->FixParameter(1,fixparam1);
  f->FixParameter(3,0);
  f->FixParameter(4,0);
  f->FixParameter(5,0);
  f->FixParameter(6,0);
  f->FixParameter(11,0);

  hMCSignal->Fit("fMass","q","",minhisto,maxhisto);
  hMCSignal->Fit("fMass","q","",minhisto,maxhisto);
  f->ReleaseParameter(1);
  hMCSignal->Fit("fMass","L q","",minhisto,maxhisto);
  hMCSignal->Fit("fMass","L q","",minhisto,maxhisto);
  hMCSignal->Fit("fMass","L m","",minhisto,maxhisto);

  f->FixParameter(1,f->GetParameter(1));
  f->FixParameter(2,f->GetParameter(2));
  f->FixParameter(10,f->GetParameter(10));
  f->FixParameter(9,f->GetParameter(9));
  f->FixParameter(7,0);
  f->ReleaseParameter(8);
  f->SetParameter(8,setparam8);

  hMCSwapped->Fit("fMass","L q","",minhisto,maxhisto);
  hMCSwapped->Fit("fMass","L q","",minhisto,maxhisto);
  hMCSwapped->Fit("fMass","L q","",minhisto,maxhisto);
  hMCSwapped->Fit("fMass","L m","",minhisto,maxhisto);

  f->FixParameter(7,hMCSignal->Integral(0,1000)/(hMCSwapped->Integral(0,1000)+hMCSignal->Integral(0,1000)));
  f->FixParameter(8,f->GetParameter(8));
  f->ReleaseParameter(3);
  f->ReleaseParameter(4);
  f->ReleaseParameter(5);
  f->ReleaseParameter(6);

  f->SetLineColor(kRed);

  hData->Fit("fMass","q","",minhisto,maxhisto);
  hData->Fit("fMass","q","",minhisto,maxhisto);
  f->ReleaseParameter(1);
  f->SetParLimits(1,1.86,1.87);
  f->ReleaseParameter(11);
  f->SetParLimits(11,-0.2,0.2);
  hData->Fit("fMass","L q","",minhisto,maxhisto);
  hData->Fit("fMass","L q","",minhisto,maxhisto);
  hData->Fit("fMass","L q","",minhisto,maxhisto);
  hData->Fit("fMass","L m","",minhisto,maxhisto);

  TF1* background = new TF1("fBackground","[0]+[1]*x+[2]*x*x+[3]*x*x*x");
  background->SetParameter(0,f->GetParameter(3));
  background->SetParameter(1,f->GetParameter(4));
  background->SetParameter(2,f->GetParameter(5));
  background->SetParameter(3,f->GetParameter(6));
  background->SetLineColor(4);
  background->SetRange(minhisto,maxhisto);
  background->SetLineStyle(2);

  TF1* mass = new TF1("fSignal","[0]*([3]*([4]*Gaus(x,[1],[2]*(1+[6]))/(sqrt(2*3.1415927)*[2]*(1+[6]))+(1-[4])*Gaus(x,[1],[5]*(1+[6]))/(sqrt(2*3.1415927)*[5]*(1+[6]))))");
  mass->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(2),f->GetParameter(7),f->GetParameter(9),f->GetParameter(10),f->GetParameter(11));
  mass->SetParError(0,f->GetParError(0));
  mass->SetParError(1,f->GetParError(1));
  mass->SetParError(2,f->GetParError(2));
  mass->SetParError(3,f->GetParError(7));
  mass->SetParError(4,f->GetParError(9));
  mass->SetParError(5,f->GetParError(10));
  mass->SetFillColor(kOrange-3);
  mass->SetFillStyle(3002);
  mass->SetLineColor(kOrange-3);
  mass->SetLineWidth(3);
  mass->SetLineStyle(2);

  TF1* massSwap = new TF1("fBackground","[0]*(1-[2])*Gaus(x,[1],[3]*(1+[4]))/(sqrt(2*3.1415927)*[3]*(1+[4]))");
  massSwap->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(7),f->GetParameter(8),f->GetParameter(11));
  massSwap->SetParError(0,f->GetParError(0));
  massSwap->SetParError(1,f->GetParError(1));
  massSwap->SetParError(2,f->GetParError(7));
  massSwap->SetParError(3,f->GetParError(8));
  massSwap->SetFillColor(kGreen+4);
  massSwap->SetFillStyle(3005);
  massSwap->SetLineColor(kGreen+4);
  massSwap->SetLineWidth(3);
  massSwap->SetLineStyle(1);

  hData->SetXTitle("m_{#piK} (GeV/c^{2})");
  hData->SetYTitle("Entries / (5 MeV/c^{2})");
  hData->SetAxisRange(0,hData->GetBinContent(hData->GetMaximumBin())*1.4*1.2,"Y");
  hData->SetMarkerSize(0.3);
  hData->Draw("e");

  cout<<"hData->GetMaximum(): "<<hData->GetMaximum()<<endl;

  background->Draw("same");
  mass->SetRange(minhisto,maxhisto);
  mass->Draw("same");
  massSwap->SetRange(minhisto,maxhisto);
  massSwap->Draw("same");
  f->Draw("same");

  Double_t yield = mass->Integral(minhisto,maxhisto)/hData->GetBinWidth(1);
  Double_t yieldErr = mass->Integral(minhisto,maxhisto)/hData->GetBinWidth(1)*mass->GetParError(0)/mass->GetParameter(0);

  std::cout<<"integral function yield: "<<yield<<"    fit yield: "<<f->GetParameter(0)*f->GetParameter(7)/hData->GetBinWidth(1)<<" +- "<<f->GetParError(0)*f->GetParameter(7)/hData->GetBinWidth(1)<<std::endl;

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

  hData->GetFunction("fMass")->Delete();
  TH1D* hDataNoFitFun = (TH1D*) hData->Clone("hDataNoFitFun");
  hDataNoFitFun->Draw("esame");

  return f;
}
Example #27
0
void printhistos(){
   /// print muon resolution data, MC and MC sim
   gStyle->SetOptFit(1111);
   TString gifname[NPThist];
   //TString gifname_inv[NPThist];
   TString gifmethod = "DoubleGauss";
   //TString gifmethodinv = "DoubleGauss";
   //TString gifmethod = "BWnonrel";
   //TString gifmethodinv = "Voigtian";
   gStyle->SetPalette(1,0);            // blue to red false color palette. Use 9 for b/w
   gStyle->SetOptTitle(1); 

  TF1* fitDoubleGauss = new TF1("fitDoubleGauss", DoubleGauss, -0.1, 0.1, 5);
  TF1* fitDoubleGauss2 = new TF1("fitDoubleGauss2", DoubleGauss, -0.1, 0.1, 5);
  for(int iPT = 0; iPT < NPThist; iPT++){
    gifname[iPT] = Form("plots/ResolutionPTScaleFactor%1.2f_"+gifmethod+"_%d", ScaleFactor, iPT);
    gifname[iPT] = gifname[iPT]+Extra;
    TCanvas *c20 = new TCanvas("c20","Resolution",3000,1700);
    TCanvas *c21 = new TCanvas("c21","Resolution mass",3000,1700);
    c20-> Divide(4,2);
    c21-> Divide(4,2);
    int Neta = NETAhist;
    if(Neta > 8) {Neta = 8; cout << "more then 8 bins, change canvas size" << endl;}
    for(int iETA = 0; iETA < Neta; iETA++){
      int iK = iPT + iETA*NPThist;
       c20 -> cd(iETA+1);
       if(ETAbin[iETA] < 0.) c20 -> cd(int(Neta/2) - iETA); 
       // 
       fitDoubleGauss->SetParameters(0., 0.85*hmuonRes[iK] -> GetRMS(), 0.07,0.85*hmuonRes[iK] -> GetRMS()+0.015, 1000.);
       //if(ETAbin[iETA] > 0.75 || ETAbin[iETA] < -0.85) fitDoubleGauss->SetParameters(0., hmuonRes[iK] -> GetRMS(), 0.035, 0.03, 1000.); 
       //if(PTbin[iPT] > 90.) fitDoubleGauss->SetParameters(0., 0.024, 0.08, 0.054, 160.); 
       //if( (PTbin[iPT] > 65. && ( ETAbin[iETA] > 0.75 || ETAbin[iETA] < -0.85) ) 
       if( (PTbin[iPT] > 65. && ( ETAbin[iETA] > 1.15 || ETAbin[iETA] < -1.25) ) 
           || (PTbin[iPT] > 145.) ){ 
          fitDoubleGauss->SetParameters(0., hmuonRes[iK] -> GetRMS(), 0.0, 0.03, 100.); 
          fitDoubleGauss->FixParameter(2,0.);//fix Asig2 to 0
          fitDoubleGauss->FixParameter(3,3.); // fix sig2 to any big value (sig1 < sig2)
          fitDoubleGauss->SetParLimits(1, 0.005, 0.1);//restrict sigma1
       }
       else{
          fitDoubleGauss->SetParLimits(2, 0.01, 0.4);//restrict Asig2
          fitDoubleGauss->SetParLimits(3,0.005, 0.1); //restrict sig2
          fitDoubleGauss->SetParLimits(1, 0.005, hmuonRes[iK] -> GetRMS());//restrict sigma1
       } 
       //fitDoubleGauss->FixParameter(0,0.); // fix mean of resolution
       fitDoubleGauss->SetParName(0,"mean");
       fitDoubleGauss->SetParName(1,"sig1");
       fitDoubleGauss->SetParName(2,"Asig2");
       fitDoubleGauss->SetParName(3,"sig2");
       fitDoubleGauss->SetParName(4,"Norm");

       hmuonRes[iK] -> Fit(fitDoubleGauss,"RLE");
       fitDoubleGauss2->SetParameters(fitDoubleGauss->GetParameter(0),fitDoubleGauss->GetParameter(1),fitDoubleGauss->GetParameter(2),fitDoubleGauss->GetParameter(3),fitDoubleGauss->GetParameter(4));
       //if( (PTbin[iPT] > 65. && ( ETAbin[iETA] > 0.75 || ETAbin[iETA] < -0.85) ) 
       if( (PTbin[iPT] > 65. && ( ETAbin[iETA] > 1.15 || ETAbin[iETA] < -1.25) ) 
           || (PTbin[iPT] > 145.) ){ 
          fitDoubleGauss2->FixParameter(2,0.);//fix Asig2 to 0
          fitDoubleGauss2->FixParameter(3,3.); // fix sig2 to any big value (sig1 < sig2)
          fitDoubleGauss2->SetParLimits(1, 0.005, 0.1);//restrict sigma1
       }
       else{
          fitDoubleGauss2->SetParLimits(2, 0.01, 0.4);//restrict Asig2
          fitDoubleGauss2->SetParLimits(3,0.005, 0.1); //restrict sig2
          fitDoubleGauss2->SetParLimits(1, 0.005, hmuonRes[iK] -> GetRMS());//restrict sigma1
       } 
       //fitDoubleGauss2->FixParameter(0,0.); // fix mean of resolution
       fitDoubleGauss2->SetParName(0,"mean");
       fitDoubleGauss2->SetParName(1,"sig1");
       fitDoubleGauss2->SetParName(2,"Asig2");
       fitDoubleGauss2->SetParName(3,"sig2");
       fitDoubleGauss2->SetParName(4,"Norm");

       hmuonRes[iK] -> Fit(fitDoubleGauss2,"RLE");

        TLegend* histinfo = SetLegend(.6,.57,1.,.73);
        histinfo->AddEntry(hmuonRes[iK], "MC reco + Fit","lep");
        histinfo->AddEntry(fitDoubleGauss2, Form("Fit, RMS = %4.3f#pm%4.3f", ResRMS[iK], ErrResRMS[iK]),"l");


       hmuonRes[iK] ->  GetXaxis() ->SetNdivisions(505);// n = n1 + 100*n2 + 10000*n3
       hmuonRes[iK] -> GetXaxis()->SetTitle("p_{T}^{reco}(#mu)/p_{T}^{gen}(#mu)-1");
       hmuonRes[iK] -> GetYaxis()->SetTitle("Entries");

       hmuonRes[iK] -> Draw("e");
       histinfo -> Draw("same");
       //c21 -> cd(iETA+1);
       //hDimuonRes[iK] -> Draw("e");
     }
     c20 ->Print(gifname[iPT]+".png");
     c20 ->Print(gifname[iPT]+".root");
     //c21 ->Print(gifname_inv[iPT]); 
   }
  /// end: print muon resolution data, MC and MC sim

}
Example #28
0
int main(int argc, char** argv){

	// because root is a piece of shit	
	gSystem->Load("libTree");

	if (argc != 2){
		printf("Usage: ./pulse_shape <gain_meas root file>\n\te.g. ./pulse_shape test.root\n");
		return -1;
	}

	char* file_name = argv[1];
//	float t_min = -70e-9, t_max = 130e-9, u_min = -1., u_max = 2.; 
	int sample_len;
	float baseline;
	

	// open root file and extract tree
 	printf("[Pulse Shape] - Opening file '%s'..\n", file_name);
	TFile* in_file = TFile::Open(file_name, "READ");
	TTree* in_tree = (TTree*)in_file->Get("outtree");
	in_tree->SetBranchAddress("len", &sample_len);
	in_tree->SetBranchAddress("baseline", &baseline);
	in_tree->GetEntry(0);

	double* u = new double[sample_len];
	double* t = new double[sample_len];
	in_tree->SetBranchAddress("amplitude", u);
	in_tree->SetBranchAddress("time", t);
	const int nEvents = in_tree->GetEntries();

 	printf("[Pulse Shape] - Found tree with %i events, %i samples per event.\n", nEvents, sample_len);

	TFile* out_file = new TFile("out.root", "RECREATE");
	TTree* out_tree = new TTree("out_tree", "outtree");
	double riseTime, fallTime, pulseDuration;
	out_tree->Branch("risetime", &riseTime);
	out_tree->Branch("falltime", &fallTime);
	out_tree->Branch("pulseduration", &pulseDuration);
	
	TCanvas* c1 = new TCanvas();
	TGraph* pulse = new TGraph();
	pulse->SetTitle("Output pulse;t [s];U [V]");
	pulse->SetMarkerStyle(7);
	TGraph* rf = new TGraph();	// drawing rise and fall time points
	rf->SetMarkerStyle(8);
	rf->SetMarkerColor(46);
	TF1* bl = new TF1("baseline", "[0]", -100, 100);	// baseline
	bl->SetLineColor(38);
	
        // loop over data
	float uMax, lPos, hPos, lTime, hTime, rTime, buf;
	int maxEntry;
        for (int iEvent = 0; iEvent < nEvents; iEvent++){
                uMax = -1.;
                in_tree->GetEntry(iEvent);
                for (int i = 0; i < sample_len; i++){
                        u[i] *= -1;
                        pulse->SetPoint(i, t[i], u[i]);
                        // find Maximum by Hand because root apparently isnt able to do so
                        if (u[i] > uMax){
                                uMax = u[i];
                                maxEntry = i;
                        }
                }
		// get 10% and 90% amplitude
                lPos = 0.1*(uMax - baseline) + baseline;
                hPos = 0.9*(uMax - baseline) + baseline;
                
		// get rise time -> start at maximum and go left
		lTime = -1;
                hTime = -1;
                for (int i = maxEntry; (buf = pulse->GetY()[i]) > 0.9*lPos; i--){
                        if ( buf > hPos )
                                hTime = pulse->GetX()[i];
                        if ( buf > lPos ){
                                lTime = pulse->GetX()[i];
                        }
                }
                riseTime = hTime - lTime;
		rf->SetPoint(0, lTime, lPos);               
		rf->SetPoint(1, hTime, hPos);               
 
		// get fall time -> start at maximum and go right
		rTime = -1;
                hTime = -1;
                for (int i = maxEntry; (buf = pulse->GetY()[i]) > 0.9*lPos; i++){
                        if ( buf > hPos )
                                hTime = pulse->GetX()[i];
                        if ( buf > lPos ){
                                rTime = pulse->GetX()[i];
                        }
                }
                fallTime = rTime - hTime;
		pulseDuration = rTime - lTime; 
		rf->SetPoint(2, rTime, lPos);               
		rf->SetPoint(3, hTime, hPos);               

		out_tree->Fill();

                // draw & save every 500th event
                if (iEvent%100 == 0) {
 			printf("[Pulse Shape] - Risetime = %e s\n", riseTime);
			printf("[Pulse Shape] - Falltime = %e s\n", pulseDuration);
 			printf("[Pulse Shape] - Pulse duration = %e s\n", fallTime);
			
			bl->SetParameter(0, baseline);
                        pulse->Draw("A*");
			bl->Draw("SAME");
			rf->Draw("SAME*");
			c1->Write();
                }
	}




	// cleanup
	out_tree->Write();
	out_file->Close();
	in_file->Close();
	return 0;
}
Example #29
0
int macro_004_8 ()
{
  TFile input ("../testBkg_004.root") ;

  //PG get the histograms
  //PG ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----

  THStack * stack_m4_upper = (THStack *) input.Get ("stack_m4_upper") ;
  TH1F * m4_upper_total = (TH1F*) stack_m4_upper->GetStack ()->Last () ;
  TH1F * m4_upper_Wjet = (TH1F *) input.Get ("m4_upper_Wjet") ;
    
  THStack * stack_m4_lower = (THStack *) input.Get ("stack_m4_lower") ;
  TH1F * m4_lower_total = (TH1F *) stack_m4_lower->GetStack ()->Last () ;
  TH1F * m4_lower_Wjet = (TH1F *) input.Get ("m4_lower_Wjet") ;
    
  THStack * stack_m4_signal = (THStack *) input.Get ("stack_m4_signal") ;
  TH1F * m4_signal_total = (TH1F *) stack_m4_signal->GetStack ()->Last () ;
  TH1F * m4_signal_Wjet = (TH1F *) input.Get ("m4_signal_Wjet") ;

  THStack * stack_m4_sideband = (THStack *) input.Get ("stack_m4_sideband") ;
  TH1F * m4_sideband_total = (TH1F *) stack_m4_sideband->GetStack ()->Last () ;
  TH1F * m4_sideband_Wjet = (TH1F *) input.Get ("m4_sideband_Wjet") ;

  TH1F * m4_upper_DATA = (TH1F *) input.Get ("m4_upper_DATA") ;      
  TH1F * m4_signal_DATA = (TH1F *) input.Get ("m4_signal_DATA") ;    
  TH1F * m4_lower_DATA = (TH1F *) input.Get ("m4_lower_DATA") ;      
  TH1F * m4_sideband_DATA = (TH1F *) input.Get ("m4_sideband_DATA") ;

  //PG fit separately numerator and denominator
  //PG ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----

  TF1 * numFitFunc = new TF1 ("numFitFunc", attenuatedCB, 0., 1000., 7) ;
  numFitFunc->SetLineWidth (1) ;
  numFitFunc->SetLineColor (kBlue+2) ;
  numFitFunc->SetNpx (10000) ;
  numFitFunc->SetParameter (0, m4_signal_total->Integral ()) ;  //PG N
  numFitFunc->SetParameter (1, 200.) ;                          //PG gaussian mean
  numFitFunc->SetParameter (2, 20.) ;                           //PG gaussian sigma
  numFitFunc->SetParameter (3, 0.1) ;                           //PG joint point
  numFitFunc->SetParameter (4, 10) ;                            //PG power law exponent
  numFitFunc->SetParameter (5, 200) ;                           //PG fermi E
  numFitFunc->SetParameter (6, 10) ;                            //PG kT
  m4_signal_total->Fit (numFitFunc, "L", "", 100., 800.) ;
  TH1F * num_fit_error = new TH1F ("num_fit_error", "", 70, 100., 800.) ;
  (TVirtualFitter::GetFitter ())->GetConfidenceIntervals (num_fit_error, 0.68) ;

  TF1 * denFitFunc = new TF1 ("denFitFunc", attenuatedCB, 0., 1000., 7) ;
  denFitFunc->SetLineWidth (1) ;
  denFitFunc->SetLineColor (kBlue+2) ;
  denFitFunc->SetNpx (10000) ;
  denFitFunc->SetParameter (0, m4_sideband_total->Integral ()) ;
  denFitFunc->SetParameter (1, 200.) ;
  denFitFunc->SetParameter (2, 20.) ;
  denFitFunc->SetParameter (3, 0.1) ;
  denFitFunc->SetParameter (4, 10) ;
  denFitFunc->SetParameter (5, 200) ;
  denFitFunc->SetParameter (6, 10) ;
  m4_sideband_total->Fit (denFitFunc, "L", "", 100., 800.) ;
  TH1F * den_fit_error = new TH1F ("den_fit_error", "", 70, 100., 800.) ;
  (TVirtualFitter::GetFitter ())->GetConfidenceIntervals (den_fit_error, 0.68) ;

  TCanvas c1 ;
  den_fit_error->SetFillColor (kGray+2) ;
  den_fit_error->Draw ("E3") ;
  m4_sideband_total->Draw ("same") ;
  c1.Print ("denominator_fit.pdf", "pdf") ;

  //PG calculate the ratio of the functions
  //PG ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----

  TH1F * func_ratio = (TH1F *) m4_signal_total->Clone ("func_ratio") ;
  func_ratio->Reset () ;
  for (int j = 1 ; j <= func_ratio->GetNbinsX () ; ++j)
    {
      double x = func_ratio->GetBinCenter (j) ;
      func_ratio->SetBinContent (j, numFitFunc->Eval (x) / denFitFunc->Eval (x)) ;
      double sqRelError = num_fit_error->GetBinError (j) * num_fit_error->GetBinError (j) / 
                           (num_fit_error->GetBinContent (j) * num_fit_error->GetBinContent (j)) +
                          den_fit_error->GetBinError (j) * den_fit_error->GetBinError (j) / 
                           (den_fit_error->GetBinContent (j) * den_fit_error->GetBinContent (j)) ;
      double error = sqrt (sqRelError) * func_ratio->GetBinContent (j) ;
      func_ratio->SetBinError (j, error) ;
    }

  //PG look at the ratio of the functions
  //PG ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
  
  stack_m4_signal->Draw ("hist") ;
  c1.Print ("numerator.pdf", "pdf") ;

  stack_m4_sideband->Draw ("hist") ;
  c1.Print ("denominator.pdf", "pdf") ;

  TH1F * ratio_total = (TH1F *) m4_signal_total->Clone ("ratio") ;
  ratio_total->Divide (m4_sideband_total) ;
  
  func_ratio->SetLineColor (kBlue) ;
  func_ratio->SetFillStyle (0) ;
  
  c1.DrawFrame (100., 0., 1000., 2.) ;
  ratio_total->Draw ("same") ;
  func_ratio->Draw ("histE2same") ;
  c1.Print ("ratio.pdf", "pdf") ;
  
  //PG extrapolate the background from side-band
  //PG ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
  
//  TH1F * extrapolated_bkg = m4_sideband_total->Clone ("extrapolated_bkg") ; //PG simil-closure test --> stats issue
  TH1F * extrapolated_bkg = m4_sideband_DATA->Clone ("extrapolated_bkg") ; //PG analysis
  extrapolated_bkg->Multiply (func_ratio) ;

  TLegend leg_compare (0.2, 0.2, 0.6, 0.4, NULL, "brNDC") ;
  leg_compare.SetBorderSize (0) ;
  leg_compare.SetTextFont (42) ;
  leg_compare.SetTextSize (0.04) ;
  leg_compare.SetLineColor (1) ;
  leg_compare.SetLineStyle (1) ;
  leg_compare.SetLineWidth (1) ;
  leg_compare.SetFillColor (0) ;
  leg_compare.SetFillStyle (0) ;
  leg_compare.AddEntry (m4_signal_total, "simulation in signal region", "lp") ;
  leg_compare.AddEntry (extrapolated_bkg, "extrapolated bkg in SR", "lp") ;

  c1.SetLogy () ;
  c1.DrawFrame (100, 0.1, 800, 5000) ;
  extrapolated_bkg->SetStats (0) ;
  extrapolated_bkg->SetTitle ("") ;
  extrapolated_bkg->SetLineColor (kRed) ;
  extrapolated_bkg->Draw ("same") ;
//  m4_signal_total->SetStats (0) ;
//  m4_signal_total->SetMarkerStyle (5) ;
//  m4_signal_total->SetMarkerColor (kBlack) ;
//  m4_signal_total->Draw ("same") ;
//  leg_compare.Draw () ;
  c1.Print ("compare_signal_region_new.pdf", "pdf") ;
 
}
Example #30
0
 double XZGetParameter(int i){return (xzfitfunc->GetParameter(i));};