Exemple #1
0
// -----------------------------------------------------------------------------
//
TCanvas* aDrawBkgdPlots( TString path, 
			 TString canvas_name, 
			 TString name, 
			 TString dirmame, 
			 int rebin, 
			 bool norm, 
			 bool log,
			 TDirectory* file )
{

  // SetSomeStyles();

  // Create legend
  TLegend* legend = new TLegend( 0.75, 0.65, 0.92, 0.92, NULL, "brNDC" );
  legend->SetFillColor(0);
  legend->SetLineColor(0); 
  
  // Create canvas
  TCanvas* aCanvas = getaCanvas( canvas_name, file, log );
  
  // Create histograms
  TH1D* qcd     = readHist( path, name, "IC5Calo_QCD_Pythia_Merged.root", dirmame, rebin );
  TH1D* tt_jets = readHist( path, name, "IC5Calo_TTbarJets.root", dirmame, rebin );
  TH1D* w_jets  = readHist( path, name, "IC5Calo_WJets.root", dirmame, rebin );
  TH1D* z_inv   = readHist( path, name, "IC5Calo_Zinv.root", dirmame, rebin );
  TH1D* z_jets  = readHist( path, name, "IC5Calo_ZJets.root", dirmame, rebin );
  TH1D* lm0     = readHist( path, name, "IC5Calo_LM0.root", dirmame, rebin );
  TH1D* lm1     = readHist( path, name, "IC5Calo_LM1.root", dirmame, rebin );

  // Combine Z+jets and Z->inv
  TH1D* z_all = z_inv->Clone(); 
  z_all->Add(z_jets,1);

//   TH1D* z_all = 0;
//   if ( z_inv && z_jets ) { 
//     z_all = z_inv->Clone(); 
//     z_all->Add(z_jets,1);
//   } else if ( z_inv ) { 
//     z_all = z_inv->Clone(); 
//   } else if ( z_jets ) { 
//     z_all = z_jets->Clone(); 
//   }
  
  // Select Z+jets and Z->inv separate or not
  bool combine = true;
  
  // Line colour and fill
  if ( qcd ) qcd->SetLineColor(kGreen+2);
  if ( qcd ) qcd->SetFillColor(kGreen+2);
  if ( qcd ) qcd->SetFillStyle(3003);
  if ( tt_jets ) tt_jets->SetLineColor(kBlue);
  if ( tt_jets ) tt_jets->SetLineStyle(1);
  if ( tt_jets ) tt_jets->SetLineWidth(1);
  w_jets->SetLineColor(kBlue);
  w_jets->SetLineStyle(3);
  w_jets->SetLineWidth(1);
  if ( combine ) {
    z_all->SetLineColor(kBlack);
    z_all->SetLineStyle(3);
    z_all->SetLineWidth(1);
  } else {
    z_inv->SetLineColor(kBlack);
    z_inv->SetLineStyle(1);
    z_inv->SetLineWidth(1);
    z_jets->SetLineColor(kBlack);
    z_jets->SetLineStyle(3);
    z_jets->SetLineWidth(1);
  }
  lm0->SetLineColor(kRed);
  lm0->SetLineStyle(1);
  lm0->SetLineWidth(2);
  lm1->SetLineColor(kRed);
  lm1->SetLineStyle(3);
  lm1->SetLineWidth(2);

  // Populate legend
  legend->AddEntry( qcd, " QCD", "f" );
  legend->AddEntry( lm0, " SUSY LM0", "L" );
  legend->AddEntry( lm1, " SUSY LM1", "L" );
  legend->AddEntry( tt_jets, " t#bar{t}+jets", "L" );
  legend->AddEntry( w_jets, " W+jets", "L" );
  if ( combine ) {
    legend->AddEntry( z_all, " Z", "L" );
  } else {
    legend->AddEntry( z_jets, " Z+jets", "L" );
    legend->AddEntry( z_inv, " Z#rightarrow#nu#nu", "L" );
  }

  // Calc maximum number of entries
  double aMax = 0.;
  if ( qcd->GetMaximum()     > aMax ) { aMax = qcd->GetMaximum(); }
  if ( lm0->GetMaximum()     > aMax ) { aMax = lm0->GetMaximum(); }
  if ( lm1->GetMaximum()     > aMax ) { aMax = lm1->GetMaximum(); }
  if ( tt_jets->GetMaximum() > aMax ) { aMax = tt_jets->GetMaximum(); }  
  if ( w_jets->GetMaximum()  > aMax ) { aMax = w_jets->GetMaximum(); }  
  if ( combine ) {
    if ( z_all->GetMaximum()  > aMax ) { aMax = z_all->GetMaximum(); }  
  } else {
    if ( z_inv->GetMaximum()   > aMax ) { aMax = z_inv->GetMaximum(); }  
    if ( z_jets->GetMaximum()  > aMax ) { aMax = z_jets->GetMaximum(); }  
  }

  // Calc minimum number of entries
  double aMin = 1.e12;
  if ( qcd->GetMinimum(1.e-12)     < aMin ) { aMin = qcd->GetMinimum(1.e-12); }
  if ( lm0->GetMinimum(1.e-12)     < aMin ) { aMin = lm0->GetMinimum(1.e-12); }
  if ( lm1->GetMinimum(1.e-12)     < aMin ) { aMin = lm1->GetMinimum(1.e-12); }
  if ( tt_jets->GetMinimum(1.e-12) < aMin ) { aMin = tt_jets->GetMinimum(1.e-12); }  
  if ( w_jets->GetMinimum(1.e-12)  < aMin ) { aMin = w_jets->GetMinimum(1.e-12); }  
  if ( combine ) {
    if ( z_all->GetMinimum(1.e-12)   < aMin ) { aMin = z_all->GetMinimum(1.e-12); }  
  } else {
    if ( z_inv->GetMinimum(1.e-12)   < aMin ) { aMin = z_inv->GetMinimum(1.e-12); }  
    if ( z_jets->GetMinimum(1.e-12)  < aMin ) { aMin = z_jets->GetMinimum(1.e-12); }  
  }

  if ( qcd ) qcd->GetYaxis()->SetTitleOffset(1.43);
  if ( qcd ) qcd->GetYaxis()->SetTitleSize(0.06);
  if ( qcd ) qcd->GetXaxis()->SetTitleSize(0.06);
  if ( qcd ) qcd->GetXaxis()->SetTitleOffset(0.9);

  if ( log ) {
    if ( qcd ) qcd->SetMaximum( aMax * 10. );
    if ( qcd ) qcd->SetMinimum( aMin * 0.1 );
  } else {
    if ( qcd ) qcd->SetMaximum( aMax * 1.1 );
    if ( qcd ) qcd->SetMinimum( aMin * 0.9 );
  }

  if ( norm ) {
    if ( qcd ) qcd->DrawNormalized("Ehist");
    if ( lm0->GetEntries() > 0. )     { lm0->DrawNormalized("hsame"); }
    if ( lm1->GetEntries() > 0. )     { lm1->DrawNormalized("hsame"); }
    if ( tt_jets->GetEntries() > 0. ) { tt_jets->DrawNormalized("hsame"); }
    if ( w_jets->GetEntries() > 0. )  { w_jets->DrawNormalized("hsame"); }
    if ( combine ) {
      if ( z_all->GetEntries() > 0. )   { z_all->DrawNormalized("hsame"); }
    } else {
      if ( z_inv->GetEntries() > 0. )   { z_inv->DrawNormalized("hsame"); }
      if ( z_jets->GetEntries() > 0. )  { z_jets->DrawNormalized("hsame"); }
    }
  } else {
    if ( qcd ) qcd->Draw("h");
    lm0->Draw("sameH");
    lm1->Draw("sameH");
    if ( tt_jets ) tt_jets->Draw("sameh");
    w_jets->Draw("sameH");
    if ( combine ) {
      z_all->Draw("sameH");
    } else {
      z_inv->Draw("sameH");
      z_jets->Draw("sameH");
    }
  }
  
  file->cd();
  legend->Draw("same");
  aCanvas->Write();
  return aCanvas;

}
void balanceMetVsAj(TString infname = "dj_HCPR-J50U-hiGoodMergedTracks_OfficialSelv2_Final0_120_50.root",
                    TCut myCut = "cent<30", TString metType = "",bool drawLegend = false,
                    bool drawSys = true
                   )
{
    // ===========================================================
    // Get Input
    // ===========================================================
    TFile *inf = new TFile(infname);
    TTree *t = (TTree*)inf->Get("ntjt");

    vector<TString> mergedPt,target;
    mergedPt.push_back("metxMergedAll");
    target.push_back("(metx0+metx1+metx2+metx3+metx4+metx5)");
    mergedPt.push_back("metxMerged0");
    target.push_back("(metx0)");
    mergedPt.push_back("metxMerged1");
    target.push_back("(metx1)");
    mergedPt.push_back("metxMerged2");
    target.push_back("(metx2)");
    mergedPt.push_back("metxMerged3");
    target.push_back("(metx3)");
    mergedPt.push_back("metxMerged4");
    target.push_back("(metx4+metx5)");
    for (Int_t i=0; i<mergedPt.size(); ++i) {
        if (metType!="") {
            target[i].ReplaceAll("metx",metType);
        }
        cout << "Alias: " << mergedPt[i] << " target: " << target[i] << endl;
        t->SetAlias(mergedPt[i],target[i]);
    }

    // ===========================================================
    // Analysis Setup
    // ===========================================================
    const int nBin = 5;
    double bins[nBin+1] = {0.5,1.0,2,4,8,1000};

    const int nBinAj = 4;
    double ajBins[nBinAj+1] = {0.0001,0.11,0.22,0.33,0.49999};
    // Selection cut
    TCut evtCut = "nljet>120&&abs(nljetacorr)<1.6&&aljet>50&&abs(aljetacorr)<1.6&&jdphi>5./6*TMath::Pi()&&!maskEvt";

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

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

    // ===========================================================
    // Draw Weighted Averages
    // ===========================================================
    TH1D *ppos[nBin];
    TH1D *pneg[nBin];
    TH1D *pe[nBin];
    for (int i=0; i<nBin; i++)
    {
        TH1D *h1 = new TH1D(Form("h1%d",i),"",nBinAj,ajBins);
        TH1D *h2 = new TH1D(Form("h2%d",i),"",nBinAj,ajBins);
        TH1D *he[nBinAj];

        // =================================
        // Get Weighted Mean for each Aj bin
        // =================================
        h1->Sumw2();
        h2->Sumw2();
        t->Draw(Form("Aj>>h1%d",i), "weight"*(evtCut&&myCut));
        t->Draw(Form("Aj>>h2%d",i), Form("((-weight*metxMerged%d))",i)*(evtCut&&myCut));

        pe[i]=(TH1D*)h2->Clone();
        pe[i]->SetName(Form("p%d",i));
        pe[i]->Divide(h1);
        ppos[i] = new TH1D(Form("ppos%d",i),"",nBinAj,ajBins);
        ppos[i]->SetLineColor(1);
        ppos[i]->SetMarkerColor(colors[i]);
        ppos[i]->SetFillColor(colors[i]);
        ppos[i]->SetFillStyle(1001);
        pneg[i] = new TH1D(Form("pneg%d",i),"",nBinAj,ajBins);
        pneg[i]->SetLineColor(1);
        pneg[i]->SetMarkerColor(colors[i]);
        pneg[i]->SetFillColor(colors[i]);
        pneg[i]->SetFillStyle(1001);

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

    // Stack
    for (int i=nBin-1; i>=0; i--)
    {
        for(int iaj = 0 ; iaj< nBinAj ; iaj++) {
            double posVal=0, negVal=0;
            double posValErr=0, negValErr=0;
            if (i!=nBin-1) {
                posVal = ppos[i+1]->GetBinContent(iaj+1);
                posValErr = ppos[i+1]->GetBinError(iaj+1);
                negVal = pneg[i+1]->GetBinContent(iaj+1);
                negValErr = pneg[i+1]->GetBinError(iaj+1);
            }
            if (pe[i]->GetBinContent(iaj+1)<0) {
                negVal+=pe[i]->GetBinContent(iaj+1);
                negValErr=pe[i]->GetBinError(iaj+1);
                posValErr=0;
            } else if (pe[i]->GetBinContent(iaj+1)>0) {
                posVal+=pe[i]->GetBinContent(iaj+1);
                posValErr=pe[i]->GetBinError(iaj+1);
                negValErr=0;
            }
            ppos[i]->SetBinContent(iaj+1,posVal);
            ppos[i]->SetBinError(iaj+1,posValErr);
            pneg[i]->SetBinContent(iaj+1,negVal);
            pneg[i]->SetBinError(iaj+1,negValErr);
        }
    }

    TH1D *pall;
    TH1D *pallE;
    TH1D *h1 = new TH1D(Form("hAll1"),"",nBinAj,ajBins);
    TH1D *h2 = new TH1D(Form("hAll2"),"",nBinAj,ajBins);

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

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

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

    // ====================
    // Finally Draw
    // ====================
    for (int i=0; i<nBin; ++i) {
        ppos[i]->SetLineWidth(1);
        ppos[i]->Draw("hist same");
        pneg[i]->SetLineWidth(1);
        pneg[i]->Draw("hist same");
    }

    // ====================
    // Draw Statistical Error bars
    // ====================
    for (int i=0; i<nBin; ++i) {
        if ( i==0 )       drawErrorShift(ppos[i],-0.016, addSys);
        if ( i==1 || i==4)       drawErrorShift(ppos[i],-0.008,addSys);
        if ( i==2 )       drawErrorShift(ppos[i],0.008,addSys);
        if ( i==3 )       drawErrorShift(ppos[i],0.016,addSys);
        if ( i==0 )       drawErrorShift(pneg[i],-0.016, addSys);
        if ( i==1 || i==4)       drawErrorShift(pneg[i],-0.008,addSys);
        if ( i==2 )       drawErrorShift(pneg[i],0.008,addSys);
        if ( i==3 )       drawErrorShift(pneg[i],0.016,addSys);
    }
    pall->Draw("E same");

    // ====================
    // Draw Systematic Errors
    // ====================
    if (drawSys == 1) {
        for(int i = 0; i < nBinAj; ++i) {
            double x = pall->GetBinCenter(i+1);
            double y = pall->GetBinContent(i+1);
            // Quote the difference between GEN and RECO in >8 Bin (20%) before adjusting eff as systematics
            double errReco = -pe[nBin-1]->GetBinContent(i+1)*0.2;
            double errBck = 3.0; // compare HYDJET+SIG to SIG
            double err = sqrt(errReco*errReco+errBck*errBck);
            DrawTick(y,err,err,x,1,0.02,1);
        }
    }

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

    if (drawLegend) leg->Draw();

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


    TLine * l1 = new TLine(0.0001,-10,0.0001,10);
    l1->Draw();
}
Exemple #3
0
void slopevscentrality(){
	TFile *f;
	TH1D* c2_pos[5][2];
	TH1D* c2_neg[5][2];
	TH1D* ach_hist[5];
	TH1D* cbinHist;
	TGraphErrors* gr_diff;
	TF1* fit1;

	double x_centrality[6] = {35, 45, 55, 65, 75, 85};
	double y_slope[6];
	double statErr[6];

	double variance_pos = 0.0;
	double variance_neg = 0.0;
	double variance_diff = 0.0;
	double err_neg[5];
	double err_pos[5];
	double err_diff[5];
	double cmean;
	double errmean;
	double sum;

	for (int n = 0; n <6; ++n)
	{

		f = new TFile(Form("../../../rootfiles/slope_vs_centrality/PbPb502_%d.root",n+1));
		for (Int_t i = 0; i < 5; i++){
			ach_hist[i] = (TH1D*)f->Get(Form("demo/ach_%d",i+1));

			c2_pos[i][0] = (TH1D*)f->Get(Form("demo/c2pos_%d_cos",i));
			c2_pos[i][1] = (TH1D*)f->Get(Form("demo/c2pos_%d_sin",i));


			c2_neg[i][0] = (TH1D*)f->Get(Form("demo/c2neg_%d_cos",i));
			c2_neg[i][1] = (TH1D*)f->Get(Form("demo/c2neg_%d_sin",i));

		}

		cbinHist = (TH1D*)f->Get("demo/cbinHist");
		double x[5];
		double v2_pos[5];
		double v2_neg[5];
		double v2_diff[5];
		double r;
		for(Int_t i=0; i<5; i++){

			x[i]=ach_hist[i]->GetMean();

			cmean = c2_pos[i][0] -> GetMean();
			v2_pos[i] = sqrt(cmean);
			errmean = c2_pos[i][0] -> GetMeanError();
			variance_pos = (errmean*errmean)/(4*cmean);


			cmean = c2_neg[i][0] -> GetMean();
			v2_neg[i] = sqrt(cmean);
			errmean = c2_neg[i][0] -> GetMeanError();
			variance_neg = (errmean*errmean)/(4*cmean);

			v2_diff[i] = (v2_neg[i] - v2_pos[i]);

			sum = v2_pos[i] + v2_neg[i];

			variance_diff = variance_pos+variance_neg;


//error calculation

			err_pos[i] = sqrt(variance_pos);
			err_neg[i] = sqrt(variance_neg);
			err_diff[i] = sqrt(variance_diff);




		}

		gr_diff = new TGraphErrors(5,x,v2_diff,NULL, err_diff);
		fit1 = new TF1("Linear fitting case 1", "[0]+x*[1]", -0.09, 0.09);
		gr_diff->Fit(fit1);
		r = fit1->GetParameter(1);
		statErr[n] = fit1->GetParError(1);
		cout << "slope is: " << r << endl; 
		y_slope[n] = r;

	}

	double x_alice[] = {5,15,25,35,45,55,65,75};
	double y_alice[] = { 0.0188127, 0.0252774, 0.0290478, 0.0315681, 0.0313678, 0.0334533, 0.0326948, 0.027709 };
	double alice_statErrors[] = { 0.00276672, 0.00491256, 0.00542907, 0.00499819, 0.00427076, 0.00421142, 0.00436631, 0.00480683 };
	double alice_sysminus[] = { 0.003345731066792428, 0.005524736668946313, 0.006157316616294797, 0.00591162859559022, 0.0052989413797474684, 0.0053784097301432885, 0.0054547376184835876, 0.005548288155719744 };
	double alice_sysplus[] = { 0.003345731066792428, 0.005524736668946313, 0.006157316616294797, 0.00591162859559022, 0.0052989413797474684, 0.0053784097301432885, 0.0054547376184835876, 0.005548288155719744 };
	double xsysalice[] = {1,1,1,1,1,1,1,1};


	double x_star[] = {2.5,7.5,15.0,25.0,35.0,45.0,55.0,65.0,75.0};
	double y_star[] = {-0.033529,0.001979,0.015917,0.028232,0.031986,0.026516,0.028016,0.012459,-0.02195};
	double star_statErrors[] = { 0.0010554, 0.00701, 0.003874, 0.003091, 0.002903, 0.002921, 0.003657, 0.005119, 0.009593 };
	double star_sysminus[] = { 2.156594920238847, 1.1474282374074642, 0.41413973487218053, 0.40721102637330436, 0.46464817873311415, 0.48750025641018896, 1.2743975557101481, 0.6065696744810114, 0.9645708786812922 };
	double star_sysplus[] = { 3.152323796820371, 1.1348034014753392, 0.6881948851887814, 0.3091, 0.3775553601791398, 0.6362180836788593, 0.39244649316817704, 1.060086081410373, 4.931994052105091 };
	double xsysstar[] = {1,1,1,1,1,1,1,1,1};

	for(i=0;i<9;i++){
		star_sysminus[i]/=100;
		star_sysplus[i]/=100;
	}
	gStyle->SetLegendFont(42);

	TGraphErrors* slopevscent = new TGraphErrors(6,x_centrality,y_slope,NULL,statErr);
	TGraphErrors* ALICE = new TGraphErrors(8,x_alice,y_alice,NULL,alice_statErrors);
	TGraphErrors* STAR = new TGraphErrors(9,x_star,y_star,NULL,star_statErrors);
	TGraphAsymmErrors* ALICE_sys = new TGraphAsymmErrors(8, x_alice, y_alice, xsysalice, xsysalice, alice_sysminus, alice_sysplus);
	TGraphAsymmErrors* STAR_sys = new TGraphAsymmErrors(9, x_star, y_star, xsysstar, xsysstar, star_sysminus, star_sysplus);


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

	ALICE -> SetMarkerStyle(25);
	ALICE -> SetMarkerColor(kRed);
	ALICE -> SetLineColor(kRed);

	STAR -> SetMarkerStyle(kOpenStar);
	STAR -> SetMarkerColor(kBlue);
	STAR -> SetLineColor(kBlue);

	TH1D* base = new TH1D("base","base",1,0,100);
	base->GetYaxis()->SetRangeUser(0.00,0.06);
	base->GetXaxis()->SetTitle("Centrality(%)");
	base->GetYaxis()->SetTitle("Slope parameter(v_{2})");
	base->GetXaxis()->CenterTitle();
	base->GetYaxis()->CenterTitle();
	base->SetTitleSize  (0.040,"X");
	base->SetTitleOffset(1.4,"X");
	base->SetTitleFont  (42,"X");
	base->SetLabelOffset(0.006,"X");
	base->SetLabelSize  (0.040,"X");
	base->SetLabelFont  (42   ,"X");

	base->SetTitleSize  (0.040,"Y");
	base->SetTitleOffset(2.2,"Y");
	base->SetTitleFont  (42,"Y");
	base->SetLabelOffset(0.006,"Y");
	base->SetLabelSize  (0.040,"Y");
	base->SetLabelFont  (42   ,"Y");
	base->SetLineWidth(0);

	TCanvas* c3 = MakeCanvas("c3","c3");
	TLatex* text_a = makeLatex("CMS pPb #sqrt{s_{NN}}=5.02TeV",0.25,0.85) ;
	TLatex* text_b = makeLatex("185 #leq N_{trk}^{offline} < 260",0.25,0.80) ;
	TLatex* text_c = makeLatex("0.3 < p_{T} < 3 GeV/c",0.25,0.85) ;
	TLatex* text_d = makeLatex("|#Delta#eta| > 2",0.25,0.80) ;

	text_a->SetTextFont(42);
	text_b->SetTextFont(42);
	text_c->SetTextFont(42);
	text_d->SetTextFont(42);
	slopevscent->SetFillStyle(0);
	slopevscent->SetFillColor(0);
	slopevscent->SetFillStyle(0);
	slopevscent->SetFillColor(0);

	gStyle->SetOptTitle(0);


	TLegend* leg = new TLegend(.58,.70,.93,.90);
	leg->SetLineColor(kWhite);
	leg->SetFillColor(0);
	leg->SetFillStyle(0);
	leg->AddEntry(slopevscent, "CMS, Pb-Pb 5.02TeV","p");
	leg->AddEntry(ALICE, "ALICE, Pb-Pb 2.76TeV","p");
	leg->AddEntry(STAR, "STAR, Au-Au 200GeV","p");

	//leg->AddEntry(gr_neg, "neg","p");

	
	c3->cd();
	base->Draw("");
	ALICE->Draw("PSame");
	STAR->Draw("PSame");


	slopevscent->Draw("PSame");

//	STAR_sys->Draw("2Same");

	leg->DrawClone("PSame");
//	text_c->DrawClone("Same");
//	text_d->DrawClone("Same");

    //Define a linear function
	//SaveCanvas(c3,"pics","slopevscent_comparison");






}
void dressingValidator_2D() {

  TString channel = "";//"_MuMu";

  TFile* f = new TFile("../root_files_preFSR_emothers_2D"+channel+"/constants/DY_j22_19712pb/fsrDET_good_unfolding_constants2D_PU.root");
  //TFile* f = new TFile("/group/cms/users/asvyatko/BACKUPCOPY_LATEST2/root_files_NOFEWZ_NEWILYA_2D/constants/DY_j22_19712pb/fsrDET_good_unfolding_constants2D_PU.root");
  f->cd();
  TH1D* hpreFSR_pre = new TH1D(*yieldsMcPreFsrGenDETFIArray);
  TH1D* hpostFSR_pre = new TH1D(*yieldsMcPostFsrGenDETFIArray);
  TH1D* hpreFSR = new TH1D("hpreFSR","hpreFSR",132,0,132);
  TH1D* hpostFSR = new TH1D("hpostFSR","hpostFSR",132,0,132);

  TFile* ff = new TFile("../root_files_R01_emothers_2D"+channel+"/constants/DY_j22_19712pb/fsrDET_good_unfolding_constants2D_PU.root");
  ff->cd();
  TH1D* hdressedR01_pre = new TH1D(*yieldsMcPreFsrGenDETFIArray);
  TH1D* hdressedR01 = new TH1D("hdressedR01","hdressedR01",132,0,132);

  //extrapolate in the first bin
/*
  TFile* f = new TFile("/group/cms/users/asvyatko/BACKUPCOPY_LATEST2/root_files_NOFEWZ_NEWILYA_2D/constants/DY_j22_19712pb/fsrDET_good_unfolding_constants2D_PU.root");
  f->cd();
  TH1D* hpreFSR_main_pre = new TH1D(*yieldsMcPreFsrGenDETFIArray);
  TH1D* hpostFSR_main_pre = new TH1D(*yieldsMcPostFsrGenDETFIArray);
  TH1D* hpreFSR_main = new TH1D("hpreFSR_main","hpreFSR_main",132,0,132);
  TH1D* hpostFSR_main = new TH1D("hpostFSR_main","hpostFSR_main",132,0,132);
*/

  for (int i = 0; i < 132; i++) {
    hpreFSR->SetBinContent(i+1,hpreFSR_pre->GetBinContent(i+1+24));
    hpreFSR->SetBinError(i+1,hpreFSR_pre->GetBinError(i+1+24));
    hpostFSR->SetBinContent(i+1,hpostFSR_pre->GetBinContent(i+1+24));
    hpostFSR->SetBinError(i+1,hpostFSR_pre->GetBinError(i+1+24));
    hdressedR01->SetBinContent(i+1,hdressedR01_pre->GetBinContent(i+1+24));
    hdressedR01->SetBinError(i+1,hdressedR01_pre->GetBinError(i+1+24));
  }


  //introduce smoothing
 gROOT->ProcessLine(".L ~/DYStudy/CMSSW_5_3_3_patch2/src/DimuonAnalysis/DYPackage/test/tools/histotools.C");
 TH1D* hpreFSR_slice1 = get2DSlice(hpreFSR, "absrap2030",false,true);
 TH1D* hpreFSR_slice2 = get2DSlice(hpreFSR, "absrap3045",false,true);
 TH1D* hpreFSR_slice3 = get2DSlice(hpreFSR, "absrap4560",false,true);
 TH1D* hpreFSR_slice4 = get2DSlice(hpreFSR, "absrap60120",false,true);
 TH1D* hpreFSR_slice5 = get2DSlice(hpreFSR, "absrap120200",false,true);
 TH1D* hpreFSR_slice6 = get2DSlice(hpreFSR, "absrap200",false,true);
 hpreFSR_slice1->Smooth(10,"R");
 hpreFSR_slice2->Smooth(10,"R");
 hpreFSR_slice3->Smooth(10,"R");
 hpreFSR_slice4->Smooth(10,"R");
 hpreFSR_slice5->Smooth(10,"R");
 hpreFSR_slice6->Smooth(10,"R");
 hpreFSR = sliceCombiner(hpreFSR_slice1,hpreFSR_slice2,hpreFSR_slice3,hpreFSR_slice4,hpreFSR_slice5,hpreFSR_slice6,true); 

 TH1D* hpostFSR_slice1 = get2DSlice(hpostFSR, "absrap2030",false,true);
 TH1D* hpostFSR_slice2 = get2DSlice(hpostFSR, "absrap3045",false,true);
 TH1D* hpostFSR_slice3 = get2DSlice(hpostFSR, "absrap4560",false,true);
 TH1D* hpostFSR_slice4 = get2DSlice(hpostFSR, "absrap60120",false,true);
 TH1D* hpostFSR_slice5 = get2DSlice(hpostFSR, "absrap120200",false,true);
 TH1D* hpostFSR_slice6 = get2DSlice(hpostFSR, "absrap200",false,true);
 hpostFSR_slice1->Smooth(10,"R");
 hpostFSR_slice2->Smooth(10,"R");
 hpostFSR_slice3->Smooth(10,"R");
 hpostFSR_slice4->Smooth(10,"R");
 hpostFSR_slice5->Smooth(10,"R");
 hpostFSR_slice6->Smooth(10,"R");
 hpostFSR = sliceCombiner(hpostFSR_slice1,hpostFSR_slice2,hpostFSR_slice3,hpostFSR_slice4,hpostFSR_slice5,hpostFSR_slice6,true);       

 TH1D* hdressedR01_slice1 = get2DSlice(hdressedR01, "absrap2030",false,true);
 TH1D* hdressedR01_slice2 = get2DSlice(hdressedR01, "absrap3045",false,true);
 TH1D* hdressedR01_slice3 = get2DSlice(hdressedR01, "absrap4560",false,true);
 TH1D* hdressedR01_slice4 = get2DSlice(hdressedR01, "absrap60120",false,true);
 TH1D* hdressedR01_slice5 = get2DSlice(hdressedR01, "absrap120200",false,true);
 TH1D* hdressedR01_slice6 = get2DSlice(hdressedR01, "absrap200",false,true);
 hdressedR01_slice1->Smooth(10,"R");
 hdressedR01_slice2->Smooth(10,"R");
 hdressedR01_slice3->Smooth(10,"R");
 hdressedR01_slice4->Smooth(10,"R");
 hdressedR01_slice5->Smooth(10,"R");
 hdressedR01_slice6->Smooth(10,"R");
 hdressedR01 = sliceCombiner(hdressedR01_slice1,hdressedR01_slice2,hdressedR01_slice3,hdressedR01_slice4,hdressedR01_slice5,hdressedR01_slice6,true);       
 //smoothing end

  TH1D* hpostpreFSR = (TH1D*)hpostFSR->Clone();
  hpostpreFSR->Divide(hpostFSR,hpreFSR);

  TH1D* hpostFSRdressed = (TH1D*)hpostFSR->Clone();
  hpostFSRdressed->Divide(hpostFSR,hdressedR01);

 TH1D* hpostFSRdressed_slice1 = get2DSlice(hpostFSRdressed, "absrap2030",false,true);
 TH1D* hpostFSRdressed_slice2 = get2DSlice(hpostFSRdressed, "absrap3045",false,true);
 TH1D* hpostFSRdressed_slice3 = get2DSlice(hpostFSRdressed, "absrap4560",false,true);
 TH1D* hpostFSRdressed_slice4 = get2DSlice(hpostFSRdressed, "absrap60120",false,true);
 TH1D* hpostFSRdressed_slice5 = get2DSlice(hpostFSRdressed, "absrap120200",false,true);
 TH1D* hpostFSRdressed_slice6 = get2DSlice(hpostFSRdressed, "absrap200",false,true);
 hpostFSRdressed_slice1->Smooth(5,"R");
 hpostFSRdressed_slice2->Smooth(100,"R");
 hpostFSRdressed_slice3->Smooth(100,"R");
 hpostFSRdressed_slice4->Smooth(100,"R");
 hpostFSRdressed_slice5->Smooth(100,"R");
 //hpostFSRdressed_slice6->Smooth(10,"R");
 hpostFSRdressed = sliceCombiner(hpostFSRdressed_slice1,hpostFSRdressed_slice2,hpostFSRdressed_slice3,hpostFSRdressed_slice4,hpostFSRdressed_slice5,hpostFSRdressed_slice6,true);

 TH1D* hpostpreFSR_slice1 = get2DSlice(hpostpreFSR, "absrap2030",false,true);
 TH1D* hpostpreFSR_slice2 = get2DSlice(hpostpreFSR, "absrap3045",false,true);
 TH1D* hpostpreFSR_slice3 = get2DSlice(hpostpreFSR, "absrap4560",false,true);
 TH1D* hpostpreFSR_slice4 = get2DSlice(hpostpreFSR, "absrap60120",false,true);
 TH1D* hpostpreFSR_slice5 = get2DSlice(hpostpreFSR, "absrap120200",false,true);
 TH1D* hpostpreFSR_slice6 = get2DSlice(hpostpreFSR, "absrap200",false,true);
 //hpostpreFSR_slice1->Smooth(5,"R");
 //hpostpreFSR_slice2->Smooth(100,"R");
 hpostpreFSR_slice3->Smooth(100,"R");
 //hpostpreFSR_slice4->Smooth(100,"R");
 //hpostpreFSR_slice5->Smooth(100,"R");
 hpostpreFSR_slice6->Smooth(10,"R");
 hpostpreFSR = sliceCombiner(hpostpreFSR_slice1,hpostpreFSR_slice2,hpostpreFSR_slice3,hpostpreFSR_slice4,hpostpreFSR_slice5,hpostpreFSR_slice6,true);

  //pre-FSR, post-FSR and dressed R01
  TCanvas* c = new TCanvas("val2");
  c->cd();
  hpostFSR->GetXaxis()->SetTitle("Bin number");
  if (channel == "") {
    hpostFSR->GetYaxis()->SetTitle("Dielectron events");
  } else {
    hpostFSR->GetYaxis()->SetTitle("Dimuon events");
  }
  hpostFSR->Draw("hist");
  hdressedR01->SetLineColor(kRed);
  hdressedR01->Draw("histsame");
  hpreFSR->SetLineColor(kBlue);
  hpreFSR->Draw("histsame");

  //add legend
  TLegend *leg2= new TLegend(0.20,0.15,0.35,0.30);
  leg2->SetTextFont(72);
  leg2->SetTextSize(0.060);
  leg2->SetBorderSize(0);
  leg2->SetFillColor(0);
  leg2->AddEntry(hpostFSR,"Standard post-FSR","l");
  leg2->AddEntry(hpreFSR,"Standard pre-FSR","l");
  leg2->AddEntry(hdressedR01,"Dressed in #DeltaR < 0.1 cone","l");
  leg2->Draw("same");

  //add the ratios
  TCanvas* c3 = new TCanvas("val3");
  c3->cd();
  hpostFSRdressed->GetXaxis()->SetTitle("Bin number");
  hpostFSRdressed->GetYaxis()->SetRangeUser(0.7,2.0);
  if (channel == "") {
   hpostFSRdressed->GetYaxis()->SetTitle("Dielectron event ratios");
  } else {
   hpostFSRdressed->GetYaxis()->SetTitle("Dimuon event ratios");
  }
  hpostFSRdressed->SetMarkerStyle(22);
  hpostFSRdressed->SetMarkerColor(kRed);
  hpostFSRdressed->SetLineColor(kRed);
  hpostFSRdressed->Draw("PE");
  hpostpreFSR->SetMarkerStyle(22);
  hpostpreFSR->Draw("PEsame");
  
  //add legend
  TLegend *leg3= new TLegend(0.20,0.15,0.35,0.30);
  leg3->SetTextFont(72);
  leg3->SetTextSize(0.060);
  leg3->SetBorderSize(0);
  leg3->SetFillColor(0);
  leg3->AddEntry(hpostFSRdressed,"N_{post-FSR}/N_{dressed, #DeltaR<0.1}","lp");
  leg3->AddEntry(hpostpreFSR,"N_{post-FSR}/N_{pre-FSR}","lp");
  leg3->Draw("same");

}
Exemple #5
0
void weightPbPbFONLL(int minfit=2,int maxfit=100,TString pthat="pthatall")
{
  TString label;
  TString selmcgen="((GisSignal==1||GisSignal==2)&&(Gy>-1&&Gy<1))";
  TString myweightfunctiongen,myweightfunctionreco;
  
  //TCut weighpthat="pow(10,-0.075415*Gpt+1.748668+Gpt*Gpt*0.000388)+pow(10,-0.166406*Gpt+2.887856+Gpt*Gpt*0.000105) +0.003157";
  TCut weighpthat="1";

  gStyle->SetOptTitle(0);
  gStyle->SetOptStat(0);
  gStyle->SetEndErrorSize(0);
  gStyle->SetMarkerStyle(20);
 
  TFile*infMC=new TFile("/data/HeavyFlavourRun2/MC2015/Dntuple/PbPb/ntD_EvtBase_20160513_DfinderMC_PbPb_20160502_dPt1tkPt0p5_D0_prompt_Dpt2Dy1p1tkPt0p7tkEta2Decay2p9Dalpha0p14Skim_pthatweight.root");
  TTree* ntGen = (TTree*)infMC->Get("ntGen");
  TTree *ntHiMC = (TTree*)infMC->Get("ntHi");
  ntGen->AddFriend(ntHiMC);
  
  TH1D* hPtGenFONLL = new TH1D("hPtGenFONLL","",nBinsReweight,ptBinsReweight);
  ntGen->Project("hPtGenFONLL","Gpt",(TCut(weighpthat)*TCut(selmcgen.Data())));
  divideBinWidth(hPtGenFONLL);
    
  TString fonll="/afs/cern.ch/work/g/ginnocen/public/output_pp_d0meson_5TeV_y1.root";
  TFile* filePPReference = new TFile(fonll.Data());  
  TGraphAsymmErrors* gaeBplusReference = (TGraphAsymmErrors*)filePPReference->Get("gaeSigmaDzero");

  TH1D* hFONLL = new TH1D("hFONLL","",nBinsReweight,ptBinsReweight);
  double x,y;
  for(int i=0;i<nBinsReweight;i++){
    gaeBplusReference->GetPoint(i,x,y);
    hFONLL->SetBinContent(i+1,y);
  }
  TH1D* hFONLLOverPt=(TH1D*)hFONLL->Clone("hFONLLOverPt");
  TH1D* hFONLLOverPtWeight=(TH1D*)hFONLL->Clone("hFONLLOverPtWeight");

  hFONLLOverPt->Divide(hPtGenFONLL);

/*
  TF1 *myfit = new TF1("myfit","[0]+[1]*x+x*x*[2]+x*x*x*[3]+x*x*x*x*[4]+x*x*x*x*x*[5]",0, 100);  
  hFONLLOverPt->Fit("myfit","","",0,100);

  double par0=myfit->GetParameter(0);
  double par1=myfit->GetParameter(1);
  double par2=myfit->GetParameter(2);
  double par3=myfit->GetParameter(3);
  double par4=myfit->GetParameter(4);
  double par5=myfit->GetParameter(5);

  std::cout<<"weight="<<par0<<"+Gpt*("<<par1<<")+Gpt*Gpt*("<<par2<<")+Gpt*Gpt*Gpt*("<<par3<<")"<<"+Gpt*Gpt*Gpt*Gpt*("<<par4<<")+Gpt*Gpt*Gpt*Gpt*Gpt*("<<par5<<")"<<endl;
  std::cout<<"weight="<<par0<<"+Dgenpt*("<<par1<<")+Dgenpt*Dgenpt*("<<par2<<")+Dgenpt*Dgenpt*Dgenpt*("<<par3<<")"<<"+Dgenpt*Dgenpt*Dgenpt*Dgenpt*("<<par4<<")+Dgenpt*Dgenpt*Dgenpt*Dgenpt*Dgenpt*("<<par5<<")"<<endl;
  
  std::cout<<myweightfunctiongen<<std::endl;
  std::cout<<myweightfunctionreco<<std::endl;
  std::cout<<"fit function parameters="<<weightfunctiongen<<std::endl;
*/
    TF1 *myfit = new TF1("myfit","pow(10,[0]*x+[1]+x*x*[2])+pow(10,[3]*x+[4]+x*x*[5])+[6]", 2, 100);
    hFONLLOverPt->Fit("myfit","","",minfit,maxfit);
    double par0=myfit->GetParameter(0);
    double par1=myfit->GetParameter(1);
    double par2=myfit->GetParameter(2);
    double par3=myfit->GetParameter(3);
    double par4=myfit->GetParameter(4);
    double par5=myfit->GetParameter(5);
    double par6=myfit->GetParameter(6);

   myweightfunctiongen=Form("pow(10,%f*Gpt+%f+Gpt*Gpt*%f)+pow(10,%f*Gpt+%f+Gpt*Gpt*%f)+%f",par0,par1,par2,par3,par4,par5,par6);
   myweightfunctionreco=Form("pow(10,%f*Gpt+%f+Gpt*Gpt*%f)+pow(10,%f*Gpt+%f+Gpt*Gpt*%f)+%f",par0,par1,par2,par3,par4,par5,par6);
   std::cout<<myweightfunctiongen<<std::endl;
   std::cout<<myweightfunctionreco<<std::endl;

  TCanvas*canvasPtReweight=new TCanvas("canvasPtReweight","canvasPtReweight",1000.,500.); 
  canvasPtReweight->Divide(3,1);
  canvasPtReweight->cd(1);
  gPad->SetLogy();
  hPtGenFONLL->SetXTitle("Gen p_{T}");
  hPtGenFONLL->SetYTitle("#entries");
  hPtGenFONLL->SetMinimum(1e-4);  
  hPtGenFONLL->SetMaximum(1e11);  
  hPtGenFONLL->GetYaxis()->SetTitleOffset(1.4);
  hPtGenFONLL->Draw();
  canvasPtReweight->cd(2);
  gPad->SetLogy();
  hFONLL->SetXTitle("p_{T}");
  hFONLL->SetYTitle("FONLL, #entries");
  hFONLL->SetMinimum(1e-4);  
  hFONLL->SetMaximum(1e11);  
  hFONLL->GetYaxis()->SetTitleOffset(1.4);
  hFONLL->Draw();
  canvasPtReweight->cd(3);
  hFONLLOverPt->SetXTitle("Gen p_{T}");
  hFONLLOverPt->SetYTitle("FONLL/PYTHIA ");
  hFONLLOverPt->SetMinimum(0.01);  
  hFONLLOverPt->SetMaximum(10.);  
  hFONLLOverPt->GetYaxis()->SetTitleOffset(1.4);
  hFONLLOverPt->Draw();

}
Exemple #6
0
void plotHist3D() {

  RiceStyle();

  gStyle->SetOptStat(0);

  TFile *f = new TFile("../rootfile/PbPb_eff_MC_v1.root");

  char ndir[256] = "HITrackCorrections";
  double ptmax = 300.;

  // sim-to-reco hists
  TH3F *hSim = (TH3F*) f->Get(Form("%s/hsim3D",ndir)); hSim->GetYaxis()->SetRangeUser(0.2,ptmax);
  TH3F *hEff = (TH3F*) f->Get(Form("%s/heff3D",ndir)); hEff->GetYaxis()->SetRangeUser(0.2,ptmax);
  TH3F *hMul = (TH3F*) f->Get(Form("%s/hmul3D",ndir)); hMul->GetYaxis()->SetRangeUser(0.2,ptmax);

  // reco-to-sim hists
  TH3F *hRec = (TH3F*) f->Get(Form("%s/hrec3D",ndir)); hRec->GetYaxis()->SetRangeUser(0.2,ptmax);
  TH3F *hFak = (TH3F*) f->Get(Form("%s/hfak3D",ndir)); hFak->GetYaxis()->SetRangeUser(0.2,ptmax);
  TH3F *hSec = (TH3F*) f->Get(Form("%s/hsec3D",ndir)); hSec->GetYaxis()->SetRangeUser(0.2,ptmax);

  // ratio histograms
  TH3F *rEff = (TH3F*) hEff->Clone("rEff");
  TH3F *rMul = (TH3F*) hMul->Clone("rMul");
  TH3F *rFak = (TH3F*) hFak->Clone("rFak");
  TH3F *rSec = (TH3F*) hSec->Clone("rSec");

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

  // find bins corresponding to projections for below
  int ptbin04=hSim->GetYaxis()->FindBin(0.41);
  int ptbin10=hSim->GetYaxis()->FindBin(1.01);
  int ptbins=hSim->GetYaxis()->GetNbins();

  int etabin24m=hSim->GetXaxis()->FindBin(-2.39);
  int etabin24p=hSim->GetXaxis()->FindBin(2.39);
  int etabin10m=hSim->GetXaxis()->FindBin(-0.99);
  int etabin10p=hSim->GetXaxis()->FindBin(0.99);

  int occbin0 = hSim->GetZaxis()->FindBin(0);
  int occbin50 = hSim->GetZaxis()->FindBin(99);
  int occbin51 = hSim->GetZaxis()->FindBin(100);
  int occbin100 = hSim->GetZaxis()->FindBin(199);

  cout << "etabin10m: " << etabin10m << " etabin10p: " << etabin10p << endl;
  cout << "etabin10m: " << etabin24m << " etabin10p: " << etabin24p << endl;
  cout << "occbin0: " << occbin0 << "occbin50: " << occbin50 << endl;

  // projected hists: pt > 1.0 GeV/c, cBin (0,50%)
  TH1D* hSimEta = (TH1D*) hSim->ProjectionX("hSimEta",ptbin10,ptbins,occbin0,occbin50,"e");
  TH1D* hEffEta = (TH1D*) hEff->ProjectionX("hEffEta",ptbin10,ptbins,occbin0,occbin50,"e");
  TH1D* hMulEta = (TH1D*) hMul->ProjectionX("hMulEta",ptbin10,ptbins,occbin0,occbin50,"e");
  TH1D* hRecEta = (TH1D*) hRec->ProjectionX("hRecEta",ptbin10,ptbins,occbin0,occbin50,"e");
  TH1D* hFakEta = (TH1D*) hFak->ProjectionX("hFakEta",ptbin10,ptbins,occbin0,occbin50,"e");
  TH1D* hSecEta = (TH1D*) hSec->ProjectionX("hSecEta",ptbin10,ptbins,occbin0,occbin50,"e");

  // projected hists: pt > 1.0 GeV/c. cBin (50-100%)
  TH1D* hSimEta2 = (TH1D*) hSim->ProjectionX("hSimEta2",ptbin10,ptbins,occbin50,occbin100,"e");
  TH1D* hEffEta2 = (TH1D*) hEff->ProjectionX("hEffEta2",ptbin10,ptbins,occbin50,occbin100,"e");
  TH1D* hMulEta2 = (TH1D*) hMul->ProjectionX("hMulEta2",ptbin10,ptbins,occbin50,occbin100,"e");
  TH1D* hRecEta2 = (TH1D*) hRec->ProjectionX("hRecEta2",ptbin10,ptbins,occbin50,occbin100,"e");
  TH1D* hFakEta2 = (TH1D*) hFak->ProjectionX("hFakEta2",ptbin10,ptbins,occbin50,occbin100,"e");
  TH1D* hSecEta2 = (TH1D*) hSec->ProjectionX("hSecEta2",ptbin10,ptbins,occbin50,occbin100,"e");

  TH1D* hDumEta = new TH1D("hDumEta",";#eta",60,-2.4,2.4); hDumEta->SetMaximum(1.0); hDumEta->SetTitle("p_{T} > 1.0");
  hDumEta->GetXaxis()->CenterTitle(); hDumEta->GetYaxis()->SetTitleOffset(1.8);
  TH1D* hDumEta2 = (TH1D*) hDumEta->Clone("hDumEta2"); hDumEta2->SetMaximum(0.1); 
  TH1D* hDumEta3 = (TH1D*) hDumEta->Clone("hDumEta3"); hDumEta3->SetMaximum(0.00049); 

  // projected hists: abs(eta) < 1.0, cBin(0-50%)
  TH1D* hSimPt  = (TH1D*) hSim->ProjectionY("hSimPt",etabin10m,etabin10p,occbin0,occbin50,"e");
  TH1D* hEffPt  = (TH1D*) hEff->ProjectionY("hEffPt",etabin10m,etabin10p,occbin0,occbin50,"e");
  TH1D* hMulPt  = (TH1D*) hMul->ProjectionY("hMulPt",etabin10m,etabin10p,occbin0,occbin50,"e");
  TH1D* hRecPt  = (TH1D*) hRec->ProjectionY("hRecPt",etabin10m,etabin10p,occbin0,occbin50,"e");
  TH1D* hFakPt  = (TH1D*) hFak->ProjectionY("hFakPt",etabin10m,etabin10p,occbin0,occbin50,"e");
  TH1D* hSecPt  = (TH1D*) hSec->ProjectionY("hSecPt",etabin10m,etabin10p,occbin0,occbin50,"e");

  // projected hists: abs(eta) < 1.0, cBin(50-100%)
  TH1D* hSimPt2  = (TH1D*) hSim->ProjectionY("hSimPt2",etabin10m,etabin10p,occbin50,occbin100,"e");
  TH1D* hEffPt2  = (TH1D*) hEff->ProjectionY("hEffPt2",etabin10m,etabin10p,occbin50,occbin100,"e");
  TH1D* hMulPt2  = (TH1D*) hMul->ProjectionY("hMulPt2",etabin10m,etabin10p,occbin50,occbin100,"e");
  TH1D* hRecPt2  = (TH1D*) hRec->ProjectionY("hRecPt2",etabin10m,etabin10p,occbin50,occbin100,"e");
  TH1D* hFakPt2  = (TH1D*) hFak->ProjectionY("hFakPt2",etabin10m,etabin10p,occbin50,occbin100,"e");
  TH1D* hSecPt2  = (TH1D*) hSec->ProjectionY("hSecPt2",etabin10m,etabin10p,occbin50,occbin100,"e");
  
  TH1D* hDumPt = new TH1D("hDumPt",";p_{T} [GeV/c]",80,0.1,300.0); hDumPt->SetMaximum(1.0);
  hDumPt->GetXaxis()->CenterTitle(); hDumPt->GetYaxis()->SetTitleOffset(1.8); hDumPt->SetTitle("|#eta| < 1");
  TH1D* hDumPt2 = (TH1D*) hDumPt->Clone("hDumPt2"); hDumPt2->SetMaximum(0.1); 
  TH1D* hDumPt3 = (TH1D*) hDumPt->Clone("hDumPt3"); hDumPt3->SetMaximum(0.00049); 

  // Efficiency
  TGraphAsymmErrors *gEffEta = new TGraphAsymmErrors(); gEffEta->SetName("gEffEta");
  gEffEta->BayesDivide(hEffEta,hSimEta);
  gEffEta->SetMarkerStyle(25);
  gEffEta->SetLineStyle(2);
  gEffEta->SetLineColor(2);
  gEffEta->SetMarkerColor(2);

  TGraphAsymmErrors *gEffPt = new TGraphAsymmErrors(); gEffPt->SetName("gEffPt");
  gEffPt->BayesDivide(hEffPt,hSimPt);
  gEffPt->SetMarkerStyle(25);
  gEffPt->SetLineColor(2);
  gEffPt->SetMarkerColor(2);

  TGraphAsymmErrors *gEffEta2 = new TGraphAsymmErrors(); gEffEta2->SetName("gEffEta2");
  gEffEta2->BayesDivide(hEffEta2,hSimEta2);
  gEffEta2->SetMarkerStyle(24);
  gEffEta2->SetLineColor(4);
  gEffEta2->SetMarkerColor(4);

  TGraphAsymmErrors *gEffPt2 = new TGraphAsymmErrors(); gEffPt2->SetName("gEffPt2");
  gEffPt2->BayesDivide(hEffPt2,hSimPt2);
  gEffPt2->SetMarkerStyle(24);
  gEffPt2->SetLineStyle(4);
  gEffPt2->SetLineColor(4);
  gEffPt2->SetMarkerColor(4);

  TLegend *legEta = new TLegend(0.35,0.15,0.65,0.30);
  legEta->SetFillColor(0); legEta->SetBorderSize(0);
  legEta->AddEntry(gEffEta,"0-50%","lp");
  legEta->AddEntry(gEffEta2,"50-100%","lp");

  TLegend *legPt = new TLegend(0.35,0.2,0.65,0.35);
  legPt->SetFillColor(0); legPt->SetBorderSize(0);
  legPt->AddEntry(gEffPt,"0-50%","lp");
  legPt->AddEntry(gEffPt2,"50-100%","lp");

  TCanvas* c7 = makeMultiCanvas("c7", "Efficiency Fraction", 2,1 );
  hDumEtaEff=(TH1F*) hDumEta->Clone("hDumEtaEff"); fixedFontHist1D(hDumEtaEff,1.05,1.2);
  hDumEtaEff->GetYaxis()->SetTitle("Absolute efficiency");
  hDumPtEff=(TH1F*) hDumPt->Clone("hDumPtEff"); fixedFontHist1D(hDumPtEff,1.05,1.2);
  hDumPtEff->GetYaxis()->SetTitle("Absolute efficiency");
  c7->cd(1); gPad->SetTicks(); c7->GetPad(1)->SetLeftMargin(0.12); c7->GetPad(1)->SetBottomMargin(0.13); c7->GetPad(1)->SetLogx(0); hDumEtaEff->Draw(); gEffEta->Draw("pc"); gEffEta2->Draw("pc"); legEta->Draw();
  c7->cd(2); gPad->SetTicks(); c7->GetPad(2)->SetLeftMargin(0.12); c7->GetPad(2)->SetBottomMargin(0.13); c7->GetPad(2)->SetLogx(); hDumPtEff->Draw(); gEffPt->Draw("pc"); gEffPt2->Draw("pc"); legPt->Draw();
  saveCanvas(c7, "files", "AbsoluteEfficiency3D");

  // Multiple Reco
  TGraphAsymmErrors *gMulEta = new TGraphAsymmErrors(); gMulEta->SetName("gMulEta");
  gMulEta->BayesDivide(hMulEta,hSimEta);
  gMulEta->SetMarkerStyle(25);
  gMulEta->SetLineStyle(2);
  gMulEta->SetLineColor(2);
  gMulEta->SetMarkerColor(2);

  TGraphAsymmErrors *gMulPt = new TGraphAsymmErrors(); gMulPt->SetName("gMulPt");
  gMulPt->BayesDivide(hMulPt,hSimPt);
  gMulPt->SetMarkerStyle(25);
  gMulPt->SetLineColor(2);
  gMulPt->SetMarkerColor(2);

  TGraphAsymmErrors *gMulEta2 = new TGraphAsymmErrors(); gMulEta2->SetName("gMulEta2");
  gMulEta2->BayesDivide(hMulEta2,hSimEta2);
  gMulEta2->SetMarkerStyle(24);
  gMulEta2->SetLineColor(4);
  gMulEta2->SetMarkerColor(4);

  TGraphAsymmErrors *gMulPt2 = new TGraphAsymmErrors(); gMulPt2->SetName("gMulPt2");
  gMulPt2->BayesDivide(hMulPt2,hSimPt2);
  gMulPt2->SetMarkerStyle(24);
  gMulPt2->SetLineStyle(4);
  gMulPt2->SetLineColor(4);
  gMulPt2->SetMarkerColor(4);

  TCanvas *c8 = makeMultiCanvas("c8","Multiple Fraction", 2,1);
  hDumEtaMul=(TH1F*) hDumEta3->Clone("hDumEtaMul"); fixedFontHist1D(hDumEtaMul, 1.05,1.2); hDumEtaMul->GetYaxis()->SetRangeUser(0,0.0009);
  hDumEtaMul->GetYaxis()->SetTitle("Multiple Reconstruction Fraction");
  hDumPtMul=(TH1F*) hDumPt3->Clone("hDumPtMul"); fixedFontHist1D(hDumPtMul, 1.05, 1.2); hDumPtMul->GetYaxis()->SetRangeUser(0,0.0009);
  hDumPtMul->GetYaxis()->SetTitle("Multiple Reconstruction Fraction");
  legEta2 = (TLegend*) legEta->Clone(); legEta2->SetY1(0.65); legEta2->SetY2(0.85);
  legPt2 = (TLegend*) legPt->Clone(); legPt2->SetY1(0.65); legPt2->SetY2(0.85);
  c8->cd(1); gPad->SetLogx(0); gPad->SetTicks(); c8->GetPad(1)->SetLeftMargin(0.12); c8->GetPad(1)->SetBottomMargin(0.13); hDumEtaMul->Draw(); gMulEta->Draw("pc"); gMulEta2->Draw("pc"); legEta2->Draw();
  c8->cd(2); gPad->SetLogx(1); gPad->SetTicks(); c8->GetPad(2)->SetLeftMargin(0.12); c8->GetPad(2)->SetBottomMargin(0.13); hDumPtMul->Draw(); gMulPt->Draw("pc"); gMulPt2->Draw("pc"); legPt2->Draw();
  saveCanvas(c8, "files", "MultipleReconstruction3D");
  
  // Fakes
  TGraphAsymmErrors *gFakEta = new TGraphAsymmErrors();  gFakEta->SetName("gFakEta");
  gFakEta->BayesDivide(hFakEta,hRecEta);
  gFakEta->SetMarkerStyle(25);
  gFakEta->SetLineStyle(2);
  gFakEta->SetLineColor(2);
  gFakEta->SetMarkerColor(2);

  TGraphAsymmErrors *gFakPt = new TGraphAsymmErrors(); gFakPt->SetName("gFakPt");
  gFakPt->BayesDivide(hFakPt,hRecPt);
  gFakPt->SetMarkerStyle(25);
  gFakPt->SetLineColor(2);
  gFakPt->SetMarkerColor(2);

  TGraphAsymmErrors *gFakEta2 = new TGraphAsymmErrors(); gFakEta2->SetName("gFakEta2");
  gFakEta2->BayesDivide(hFakEta2,hRecEta2);
  gFakEta2->SetMarkerStyle(24);
  gFakEta2->SetLineColor(4);
  gFakEta2->SetMarkerColor(4);

  TGraphAsymmErrors *gFakPt2 = new TGraphAsymmErrors();  gFakPt2->SetName("gFakPt2");
  gFakPt2->BayesDivide(hFakPt2,hRecPt2);
  gFakPt2->SetMarkerStyle(24);
  gFakPt2->SetLineStyle(4);
  gFakPt2->SetLineColor(4);
  gFakPt2->SetMarkerColor(4);

  TCanvas* c9 = makeMultiCanvas("c9", "Fake Fraction", 2,1);
  hDumEtaFak=(TH1F*) hDumEta2->Clone("hDumEtaMul"); fixedFontHist1D(hDumEtaFak, 1.05,1.2); hDumEtaFak->GetYaxis()->SetRangeUser(0.,0.09);
  hDumEtaFak->GetYaxis()->SetTitle("Fake Reconstruction Fraction");
  hDumPtFak=(TH1F*) hDumPt2->Clone("hDumPtMul"); fixedFontHist1D(hDumPtFak, 1.05,1.2); hDumPtFak->GetYaxis()->SetRangeUser(0,1);
  hDumPtFak->GetYaxis()->SetTitle("Fake Reconstruction Fraction");
  c9->cd(1); hDumEtaFak->Draw(); gFakEta->Draw("pc"); gFakEta2->Draw("pc"); legEta2->Draw();
  gPad->SetTicks(); gPad->SetLeftMargin(0.12); gPad->SetBottomMargin(0.13);
  c9->cd(2); hDumPtFak->Draw(); gFakPt->Draw("pc"); gFakPt2->Draw("pc"); legPt2->Draw();
  gPad->SetTicks(); gPad->SetLeftMargin(0.12); gPad->SetBottomMargin(0.13); gPad->SetLogx(1);
  saveCanvas(c9, "files", "FakeRate3D");

  // Secondaries
  TGraphAsymmErrors *gSecEta = new TGraphAsymmErrors(); gSecEta->SetName("gSecEta");
  gSecEta->BayesDivide(hSecEta,hRecEta);
  gSecEta->SetMarkerStyle(25);
  gSecEta->SetLineStyle(2);
  gSecEta->SetLineColor(2);
  gSecEta->SetMarkerColor(2);

  TGraphAsymmErrors *gSecPt = new TGraphAsymmErrors(); gSecPt->SetName("gSecPt");
  gSecPt->BayesDivide(hSecPt,hRecPt);
  gSecPt->SetMarkerStyle(25);
  gSecPt->SetLineColor(2);
  gSecPt->SetMarkerColor(2);

  TGraphAsymmErrors *gSecEta2 = new TGraphAsymmErrors(); gSecEta2->SetName("gSecEta2");
  gSecEta2->BayesDivide(hSecEta2,hRecEta2);
  gSecEta2->SetMarkerStyle(24);
  gSecEta2->SetLineColor(4);
  gSecEta2->SetMarkerColor(4);

  TGraphAsymmErrors *gSecPt2 = new TGraphAsymmErrors();  gSecPt2->SetName("gSecPt2");
  gSecPt2->BayesDivide(hSecPt2,hRecPt2);
  gSecPt2->SetMarkerStyle(24);
  gSecPt2->SetLineStyle(4);
  gSecPt2->SetLineColor(4);
  gSecPt2->SetMarkerColor(4);

  TCanvas* c10 = makeMultiCanvas("c10", "Secondary Fraction", 2, 1);
  hDumEtaSec=(TH1F*) hDumEta2->Clone("hDumEtaMul"); fixedFontHist1D(hDumEtaSec, 1.05,1.3); hDumEtaSec->GetYaxis()->SetRangeUser(0.,0.012);
  hDumEtaSec->GetYaxis()->SetTitle("Non-Primary Reconstruction Fraction");
  hDumPtSec=(TH1F*) hDumPt2->Clone("hDumPtMul"); fixedFontHist1D(hDumPtSec, 1.05, 1.3);hDumPtSec->GetYaxis()->SetRangeUser(0.,0.1);
  hDumPtSec->GetYaxis()->SetTitle("Non-Primary Reconstruction Fraction");
  c10->cd(1); hDumEtaSec->Draw(); gSecEta->Draw("pc"); gSecEta2->Draw("pc"); legEta2->Draw();
  gPad->SetTicks(); gPad->SetLeftMargin(0.15); gPad->SetBottomMargin(0.13); 
  c10->cd(2); hDumPtSec->Draw(); gSecPt->Draw("pc"); gSecPt2->Draw("pc"); legPt2->Draw();
  gPad->SetTicks(); gPad->SetLeftMargin(0.15); gPad->SetBottomMargin(0.13); gPad->SetLogx(1);
  saveCanvas(c10, "files", "SecondaryReconstruction3D");

  TFile *fout = new TFile("test.root","RECREATE");
  gEffPt->Write(); gEffPt2->Write(); gEffEta->Write(); gEffEta2->Write();
  gMulPt->Write(); gMulPt2->Write(); gMulEta->Write(); gMulEta2->Write();
  gFakPt->Write(); gFakPt2->Write(); gFakEta->Write(); gFakEta2->Write();
  gSecPt->Write(); gSecPt2->Write(); gSecEta->Write(); gSecEta2->Write();
  fout->Close();
}
Exemple #7
0
void draw_R2m(void)
{
	const double er[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
	double ccnt[9];
	double eccnt[9];
	double dcnt[9];
	TGraphErrors *gr;
	TGraphErrors *grd;
	TH1D *hst;
	TH1D *hstd;
	double effUp, effDown, C, shift, size;
	double eeffUp, eeffDown, eC, eshift, esize;
	double fmin, fedm, errdef;
	int npari, nparx;
	int i, irc;
	char str[1024];
	TF1 *fR2;
	TVirtualPad *pd;
	
	gStyle->SetOptStat(0);
	gStyle->SetOptFit(0);
	
	MyMinuit = new TMinuit(5);
	MyMinuit->SetFCN(chi2fun);
	MyMinuit->DefineParameter(0, "Const", 1000, 10, 0, 1E10);
	MyMinuit->DefineParameter(1, "EffUp", 1, 0.1, 0.5, 1.5);
	MyMinuit->DefineParameter(2, "EffDown", 1, 0.1, 0.5, 1.5);
	MyMinuit->DefineParameter(3, "Shift", 0, 0.1, -10, 10);
	MyMinuit->DefineParameter(4, "Size", 3, 1, 0, 10);
	MyMinuit->FixParameter(3);
	MyMinuit->FixParameter(4);
	MyMinuit->Migrad();
	MyMinuit->GetParameter(0, C, eC);
	MyMinuit->GetParameter(1, effUp, eeffUp);
	MyMinuit->GetParameter(2, effDown, eeffDown);
	MyMinuit->GetParameter(3, shift, eshift);
	MyMinuit->GetParameter(4, size, esize);
	MyMinuit->mnstat(fmin, fedm, errdef, npari, nparx, irc);

//		Renorm top and bottom sections to the middle
	for (i=0; i<3; i++) {
		ccnt[i] = DataArray.cnt[i] / effUp;
		ccnt[i+3] = DataArray.cnt[i+3];
		ccnt[i+6] = DataArray.cnt[i+6] / effDown;
		eccnt[i] = DataArray.ecnt[i] / effUp;
		eccnt[i+3] = DataArray.ecnt[i+3];
		eccnt[i+6] = DataArray.ecnt[i+6] / effDown;
	}
//	for (i=0; i<9; i++) printf("L = %8.3f    CNT = %6.1f +- %4.1f\n", r[i], cnt[i], ecnt[i]);
	gr = new TGraphErrors(9, DataArray.r, ccnt, er, eccnt);
	gr->SetLineColor(kBlue);
	gr->SetLineWidth(4);
	gr->SetMarkerStyle(20);
	gr->SetMarkerColor(kBlue);
	gr->SetMarkerSize(2);
	
	fR2 = new TF1("fR2", "[0] / ((x - [1]) * (x - [1]) - [2] * [2] / 4.0)", 1, 100);
	fR2->SetParameter(0, C);
	fR2->SetParameter(1, shift);
	fR2->SetParameter(2, size);
	fR2->SetLineColor(kRed);
	fR2->SetLineWidth(3);
	
	hst = new TH1D("H", ";Distance to reactor core center, m;Events per day", 35, 10, 13.5);
	hst->SetMinimum(DataArray.cnt[4] * 0.5);
	hst->SetMaximum(DataArray.cnt[4] * 1.5);
	hst->GetXaxis()->SetLabelSize(0.06);
	hst->GetYaxis()->SetLabelSize(0.06);
	hst->GetXaxis()->SetTitleSize(0.06);
	hst->GetYaxis()->SetTitleSize(0.06);
	hst->GetYaxis()->SetTitleOffset(1.25);

	hstd = new TH1D("H", ";Distance to reactor core center, m;Events per day", 35, 10, 13.5);
	hstd->SetMinimum(-40);
	hstd->SetMaximum(40);
	hstd->GetXaxis()->SetLabelSize(0.06);
	hstd->GetYaxis()->SetLabelSize(0.06);
	hstd->GetXaxis()->SetTitleSize(0.06);
	hstd->GetYaxis()->SetTitleSize(0.06);
	hstd->GetYaxis()->SetTitleOffset(1.25);
	
	TCanvas *cv = new TCanvas("CV", "R2", 800, 1200);
	cv->Divide(1, 2);
//		Do common fit and draw
	pd = cv->cd(1);
	pd->SetLeftMargin(0.15);
	pd->SetBottomMargin(0.15);
	pd->SetTopMargin(0.03);
	hst->Draw();
	gr->Draw("p");
	fR2->Draw("same");
	TLatex txt;
	txt.SetTextSize(0.07);
	sprintf(str, "#chi^{2}/n.d.f. = %6.2f/5", fmin);
	txt.DrawLatex(11.3, DataArray.cnt[4] * 1.3, str);
//		Draw difference
	for (i=0; i<9; i++) dcnt[i] = ccnt[i] - fR2->Eval(DataArray.r[i]);
	grd = new TGraphErrors(9, DataArray.r, dcnt, er, eccnt);
	grd->SetLineColor(kBlue);
	grd->SetLineWidth(4);
	grd->SetMarkerStyle(20);
	grd->SetMarkerColor(kBlue);
	grd->SetMarkerSize(2);
	
	pd = cv->cd(2);
	pd->SetLeftMargin(0.15);
	pd->SetBottomMargin(0.15);
	pd->SetTopMargin(0.03);
	hstd->Draw();
	grd->Draw("p");
}
Exemple #8
0
TF1 *fitSignal(TTree *ntMC,double ptmin,double ptmax){   
   //cout<<cut.Data()<<endl;
   TCanvas *cSignal= new TCanvas("cSignal","",600,600);
   TH1D *hMC = new TH1D("hMC","",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("f1","[0]*([5]*Gaus(x,[1],[2])/(sqrt(2*3.14159)*[2])+(1-[5])*Gaus(x,[1],[6])/(sqrt(2*3.14159)*[6]))+[3]+[4]*x");
   ntMC->Project("hMC","mass",Form("%s&&pt>%f&&pt<%f",selmc.Data(),ptmin,ptmax));

   f->SetParLimits(4,-1000,0);
   f->SetParLimits(2,0.01,0.05);
   f->SetParLimits(6,0.01,0.05);
   f->SetParLimits(5,0,1);

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

   hMC->Fit("f1","q","",5,6);
   hMC->Fit("f1","q","",5,6);
   f->ReleaseParameter(1);
   hMC->Fit("f1","L q","",5,6);
   hMC->Fit("f1","L q","",5,6);
   hMC->Fit("f1","L q","",5,6);
   hMC->Fit("f1","L m","",5,6);

   // function for background shape plotting. take the fit result from f
   TF1 *background = new TF1("backgroundSignal","[0]+[1]*x");
   background->SetParameter(0,f->GetParameter(3));
   background->SetParameter(1,f->GetParameter(4));
   background->SetLineColor(4);
   background->SetRange(5,6);
   background->SetLineStyle(2);
   
   // function for signal shape plotting. take the fit result from f
   TF1 *mass = new TF1("fmassSignal","[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(5),f->GetParameter(6));
   cout<<"[0]Signal: "<<f->GetParameter(0)<<endl;
   mass->SetLineColor(2);
   mass->SetLineStyle(2);

   hMC->SetMarkerStyle(24);
   hMC->SetStats(0);
   hMC->Draw("e");
   hMC->SetXTitle("M_{B} (GeV/c^{2})");
   hMC->SetYTitle("Entries / (20 MeV/c^{2})");
   hMC->GetXaxis()->CenterTitle();
   hMC->GetYaxis()->CenterTitle();
   hMC->SetTitleOffset(1.,"Y");
   hMC->SetAxisRange(0,hMC->GetMaximum()*1.2,"Y");

   background->Draw("same");   

   mass->SetRange(5,6);
   mass->Draw("same");
   mass->SetLineStyle(2);
   mass->SetFillStyle(3004);
   mass->SetFillColor(2);
   f->Draw("same");

   double yield = mass->Integral(5,6)/0.02;

   // Draw the legend:)   
   TLegend *leg = myLegend(0.50,0.5,0.86,0.92);
   leg->AddEntry(hMC,"CMS Preliminary","");
   leg->AddEntry(hMC,"p+Pb #sqrt{s_{NN}}= 5.02 TeV","");
   leg->AddEntry(hMC,Form("%.0f<p_{T}^{B}<%.0f GeV/c",ptmin,ptmax),"");
   leg->AddEntry(f,"Fit","l");
   leg->AddEntry(mass,"Signal","f");
   leg->AddEntry(background,"Combinatorial Background","l");
   leg->Draw();
   TLegend *leg2 = myLegend(0.44,0.33,0.89,0.50);
   leg2->AddEntry(hMC,"B meson","");
   leg2->AddEntry(hMC,Form("N_{B}=%.0f", yield),"");
   leg2->Draw();

   cSignal->SaveAs("NonpromptBplus/BMassSignal.gif");

   return mass;
}
Exemple #9
0
void spectraSysEff() {

  // === General Settings ===

  // Note centrality is by 2.5% bins, low bin is inclusive, high bin is exclusive
  // i.e. for 0-10% use minCent=0, maxCent=4. 


  int minCent[12] = {0,2,4,6,8,10,12,14,16,20,24,28};
  int maxCent[12] = {2,4,6,8,10,12,14,16,20,24,28,32};
  
  // absolute values of eta are used, negative eta values are included
  // for full eta range set etaMin=0 etaMax=2.4
  Double_t  etaMin = 2.0;
  Double_t  etaMax = 2.4;

double dndeta[12]= {1612,1313,1082,893.9,731.6,596.8, 482.3,383.9, 266.5, 153.2,79.5, 36.3 };
 
  double ptbins[18]={0.3,0.4,0.5,0.6,0.8,1.0,1.2,1.6,2.0,2.5,3.0,3.5,4.0,5.0,6.0,8.0,10.0,12.0};
 
  // Input File
  TFile *f = new TFile("LowPtSpectrum_fine_Full_d.root");
  TFile *fcorr = new TFile("validation3D_HydjetNoWedge_100k_flowSQ_vertexZ10.root");
  TFile *fcorrAMPT;
  TFile *fcorrDataMix = new TFile("validation3D_20pionBadWedge_SQ12_vertexZ10.root");
  // =========================

  gStyle->SetErrorX(0);
  gStyle->SetOptStat(0);


  set_plot_style();

  char dirname[256] = "spectrumGoodz14chi80";
  TH1D * spec[10][12];
  TH1D * eff[10][12];
  TH1D * fak[10][12];
  TH1D * sim[10][12];
  TH1D * rec[10][12];

  TGraphErrors * gSpectrum[10][12];
  TF1 * f1[10][12];

  Double_t  meanpt[10][12];
  Double_t  meanpterr[10][12];

  
    Double_t px[100],py[100],pxe[100],pye[100];
  for( int c=0; c<12; c++)
  {
    for( int j=0; j<3; j++)
    {
      spec[j][c] = getSpectrum( f, Form("%s/tracks3D",dirname), minCent[c], maxCent[c], etaMin, etaMax ); 
      if ( j==0 )
      {
        eff[j][c] = getSpectrum( fcorr, "hitrkPixelEffAnalyzer/heff3D", minCent[c], maxCent[c], etaMin, etaMax );
        sim[j][c] = getSpectrum( fcorr, "hitrkPixelEffAnalyzer/hsim3D", minCent[c], maxCent[c], etaMin, etaMax );
        fak[j][c] = getSpectrum( fcorr, "hitrkPixelEffAnalyzer/hfak3D", minCent[c], maxCent[c], etaMin, etaMax );
        rec[j][c] = getSpectrum( fcorr, "hitrkPixelEffAnalyzer/hrec3D", minCent[c], maxCent[c], etaMin, etaMax );
      }
      if ( j==1 )
      {
        eff[j][c] = getSpectrum( fcorrDataMix, "hitrkPixelEffAnalyzer/heff3D", minCent[c], maxCent[c], etaMin, etaMax );
        sim[j][c] = getSpectrum( fcorrDataMix, "hitrkPixelEffAnalyzer/hsim3D", minCent[c], maxCent[c], etaMin, etaMax );
        fak[j][c] = getSpectrum( fcorr, "hitrkPixelEffAnalyzer/hfak3D", minCent[c], maxCent[c], etaMin, etaMax );
        rec[j][c] = getSpectrum( fcorr, "hitrkPixelEffAnalyzer/hrec3D", minCent[c], maxCent[c], etaMin, etaMax );
      }
      if ( j==2 )
      {
        eff[j][c] = getSpectrum( fcorr, "hitrkPixelEffAnalyzer/heff3D", minCent[c], maxCent[c]+1, etaMin, etaMax );
        sim[j][c] = getSpectrum( fcorr, "hitrkPixelEffAnalyzer/hsim3D", minCent[c], maxCent[c]+1, etaMin, etaMax );
        fak[j][c] = getSpectrum( fcorr, "hitrkPixelEffAnalyzer/hfak3D", minCent[c], maxCent[c]+1, etaMin, etaMax );
        rec[j][c] = getSpectrum( fcorr, "hitrkPixelEffAnalyzer/hrec3D", minCent[c], maxCent[c]+1, etaMin, etaMax );
      }

      // determine correction factors


      TH1F * nevts = (TH1F *) f->Get(Form("%s/nevts",dirname));
      double Nevt = nevts->Integral( nevts->GetXaxis()->FindBin(minCent[c]+0.001), 
                                     nevts->GetXaxis()->FindBin(maxCent[c]-0.001) );


      Double_t maxy = 0.;
      Double_t miny = 100000.;

    for( int i=0; i<=16;i++)
    {
      double ptmin = ptbins[i]; double ptmax = ptbins[i+1];

      double iptmin = spec[j][c]->FindBin(ptmin+1e-3);
      double iptmax = spec[j][c]->FindBin(ptmax-1e-3);
      double icptmin = eff[j][c]->FindBin(ptmin+1e-3);
      double icptmax = eff[j][c]->FindBin(ptmax-1e-3);
      double pt = 0.;
      for( int k=iptmin;k<=iptmax;k++) pt += spec[j][c]->GetBinCenter(k) * spec[j][c]->GetBinContent(k);
      pt /= spec[j][c]->Integral(iptmin,iptmax);

      double yielderr;
      double yield = spec[j][c]->IntegralAndError(iptmin,iptmax,yielderr);
      yield /= (ptmax-ptmin) * Nevt * 2 * (etaMax-etaMin);
      yielderr /= (ptmax-ptmin) * Nevt * 2 * (etaMax-etaMin);

      double efmin = eff[j][c]->GetBinContent(icptmin)/sim[j][c]->GetBinContent(icptmin);
      double efmax = eff[j][c]->GetBinContent(icptmax)/sim[j][c]->GetBinContent(icptmax);
      double famin = fak[j][c]->GetBinContent(icptmin)/rec[j][c]->GetBinContent(icptmin);
      double famax = fak[j][c]->GetBinContent(icptmax)/rec[j][c]->GetBinContent(icptmax);

      double ef = (pt-ptmin)*(efmax-efmin)/(ptmax-ptmin)+efmin;
      double fa = (pt-ptmin)*(famax-famin)/(ptmax-ptmin)+famin;
      yield *= (1-fa)/ef;

      px[i] = pt;
      py[i] = yield;
      if( py[i] > maxy ) maxy = py[i];
      if( py[i] < miny ) miny = py[i];
      pxe[i] = 0.;
      pye[i] = yielderr;
    }

      gSpectrum[j][c] = new TGraphErrors( 16, px, py, pxe, pye );
      gSpectrum[j][c]->SetMarkerStyle(20);
      f1[j][c] = new TF1(Form("f1_%d_%d",c,j),PowerFuncScaled,0,6,3);
      f1[j][c]->SetParNames("n","p0","dN/dy");
      f1[j][c]->SetParameters(28,5,dndeta[c]);
      f1[j][c]->FixParameter(2,dndeta[c]);
      f1[j][c]->SetLineColor(kBlue);
      f1[j][c]->SetLineWidth(1);
      f1[j][c]->SetLineStyle(1);
      TFitResultPtr r =  gSpectrum[j][c]->Fit(Form("f1_%d_%d",c,j),"0RQNS");
  //    TFitResultPtr r;
      meanpt[j][c] = f1[j][c]->Mean(0,6);

    //  TF1 * me;
    //  me  = new TF1(Form("me_%d_%d",c,j),PowerFuncME,0,6,3);
    //  double intmeerror =  me->IntegralError(0,6,r->GetParams(), r->GetCovarianceMatrix()->GetMatrixArray() );
    //  double intme = me->Integral(0,6,r->GetParams() );
    //  double intspec = f1[j][c]->Integral(0,6);
    //  double intspecerr = f1[j][c]->IntegralError(0,6);
    //  meanpterr[j][c] = intme / intspec * sqrt( intmeerror * intmeerror / intme / intme
     //                                       + intspecerr * intspecerr / intspec / intspec );
     meanpterr[j][c] = 0.;
    }
    
  }

 
  TH1D* hDumCen = new TH1D("hDumCen",";Centrality (%);<p_{T}> Ratio",40,0.,80.); 
  hDumCen->GetXaxis()->CenterTitle(); hDumCen->GetYaxis()->SetTitleOffset(1.1);
  hDumCen->SetMaximum(1.5); hDumCen->SetMinimum(0.5);

  TCanvas *c1 = new TCanvas("c1","Mean Pt",600,600);
 
  c1->cd();
  hDumCen->Draw();

  TGraphErrors * gmean[3];
  
  int colors[4] = {0,kRed, kBlack, kBlue};

  for( int j=1; j<3; j++)
  {
    Double_t mx[12], mxe[12], my[12], mye[12];
    for(int i=0;i<12;i++) 
    { 
      mx[i] = (double)(maxCent[i]+minCent[i]) * 1.25;
      mxe[i] = 0; 
      my[i] = meanpt[j][i] / meanpt[0][i];
      mye[i] = my[i] * sqrt( meanpterr[j][i]*meanpterr[j][i]/meanpt[j][i]/meanpt[j][i] 
                           + meanpterr[0][i]*meanpterr[0][i]/meanpt[0][i]/meanpt[0][i] );
    
    }  

    gmean[j] = new TGraphErrors(12, mx, my, mxe, mye);
    gmean[j]->SetMarkerStyle(20);
    gmean[j]->SetMarkerColor(colors[j]);
    gmean[j]->SetLineColor(colors[j]);
    gmean[j]->Draw("p");
  
  }
  TLegend *legPt = new TLegend(0.45,0.7,0.89,0.89);
  legPt->SetFillColor(0); legPt->SetBorderSize(0);
  legPt->AddEntry(gmean[1],"Pion Datamixing Tables","lp");
  legPt->AddEntry(gmean[2],"HYDJET+2.5 Tables","lp");

  legPt->Draw();

  TLatex *  tex = new TLatex(20,0.8,Form( "GoodMergedTracks, %4.1f < |#eta| < %4.1f",etaMin, etaMax ));
    tex->SetTextSize(0.035);
    tex->Draw();

  TH1D* hDumPt = new TH1D("hDumPt",";p_{T} [GeV/c];ratio 1/N_{evt} d^{2}N_{ch}/d#etadp_{T}",40,0.,3.); hDumPt->SetMaximum(1.5);
  hDumPt->GetXaxis()->CenterTitle(); hDumPt->GetYaxis()->SetTitleOffset(1.1);

  hDumPt->SetMaximum(1.2); hDumPt->SetMinimum(0.8);

  TCanvas *c8 = new TCanvas("c8","Spectrum",1000,500);
  c8->Divide(3,1,0,0);

  TGraphErrors * gRatio[4][12]; 

  for( int q=0;q<3; q++)
  {
    c8->cd(q+1);
    int i;
    if (q==0) i=0; 
    if (q==1) i=5; 
    if (q==2) i=11; 
    hDumPt->Draw();
    for( int j=1; j<3; j++)
    { 
      Double_t rx[100],ry[100],rxe[100],rye[100];
      Double_t dx, nx, ny, dy, dye, nye; 
      for( int p=0;p<gSpectrum[0][i]->GetN();p++)
      {
        gSpectrum[0][i]->GetPoint(p,dx,dy);
        dye = gSpectrum[0][i]->GetErrorY(p);
        gSpectrum[j][i]->GetPoint(p,nx,ny);
        nye = gSpectrum[j][i]->GetErrorY(p);
        rx[p] = nx; rxe[p]=0;
        ry[p] = ny / dy;
        rye[p] = ry[p] * sqrt ( nye*nye/ny/ny + dye*dye/dy/dy);        
      }
      gRatio[j][i] = new TGraphErrors(gSpectrum[0][i]->GetN(), rx, ry, rxe, rye);
      gRatio[j][i]->SetMarkerStyle(20);
      gRatio[j][i]->SetMarkerColor(colors[j]);
      gRatio[j][i]->SetLineColor(colors[j]);
      gRatio[j][i]->Draw("p"); 
    tex = new TLatex(1,0.87,Form("%d-%d Cent.",(int)(minCent[i]*2.5),(int)(maxCent[i]*2.5)));
    tex->SetTextSize(0.045);
    tex->Draw();

    if( i==0) legPt->Draw();
  
    tex = new TLatex(1,0.85,Form("%4.1f < |#eta| < %4.1f",etaMin,etaMax));
    tex->SetTextSize(0.045);
    if( i==0) tex->Draw();
    tex = new TLatex(1,0.83,Form("GoodMergedTracks",etaMin,etaMax));
    tex->SetTextSize(0.045);
    if( i==0) tex->Draw();
    }
  } 
}
Exemple #10
0
TF1 *fit(TTree *nt,TTree *ntMC,double ptmin,double ptmax){   
   //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);
   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)*1.20);
   f->FixParameter(7,f->GetParameter(7));
   f->FixParameter(8,f->GetParameter(8)*1.20);
   
   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",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",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");

   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,"p+Pb #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();

   //c->SaveAs(Form("PDFVariation/data/width1p2/ResultsBplus/BMass-%d.pdf",count));
   c->SaveAs(Form("PDFVariation1Bin/data/width1p2/ResultsBplus/BMass-%d.pdf",count));

   return mass;
}
Exemple #11
0
TF1 *fitNP(TTree* nt,double ptmin,double ptmax){   

   TCanvas *cNP= new TCanvas("cNP","",600,600);
   TH1D *hNP = new TH1D("hNP","",50,5,6);

   TString iNP="7.26667*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("fNP","[0]+[1]*x+[2]*("+iNP+")");
   
   nt->Project("hNP","mass",Form("%s&&pt>%f&&pt<%f&&gen!=23333",seldata_2y.Data(),ptmin,ptmax));   
   //ntMC->Project(Form("hMC%d",count),"mass",Form("%s&&pt>%f&&pt<%f",seldata_2y.Data(),ptmin,ptmax));   
   clean0(hNP);
   hNP->Draw();
   f->SetParLimits(1,-1000,0);
   f->SetParLimits(2,0,1000);

   hNP->Fit("fNP","q","",5,6);
   hNP->Fit("fNP","q","",5,6);

   hNP->SetMarkerSize(0.8);
   hNP->SetMarkerStyle(20);

   // function for background shape plotting. take the fit result from f
   TF1 *background = new TF1("backgroundNP","[0]+[1]*x");
   background->SetParameter(0,f->GetParameter(0));
   background->SetParameter(1,f->GetParameter(1));
   background->SetLineColor(4);
   background->SetRange(5,6);
   background->SetLineStyle(2);
   
   // function for signal shape plotting. take the fit result from f
   TF1 *mass = new TF1("massNP","[0]*("+iNP+")");
   //cout<<"miaomiaomiao   "<<f->GetParameter(2)<<endl;
   mass->SetParameter(0,f->GetParameter(2));
   cout<<"[0]NP: "<<f->GetParameter(2)<<endl;
   mass->SetLineColor(kGreen+1);
   mass->SetLineStyle(3);
   mass->SetFillStyle(3004);
   mass->SetRange(5,6);

   hNP->SetMarkerStyle(24);
   hNP->SetStats(0);
   hNP->Draw("e");
   hNP->SetXTitle("M_{B} (GeV/c^{2})");
   hNP->SetYTitle("Entries / (20 MeV/c^{2})");
   hNP->GetXaxis()->CenterTitle();
   hNP->GetYaxis()->CenterTitle();
   hNP->SetTitleOffset(1.,"Y");
   hNP->SetAxisRange(0,hNP->GetMaximum()*1.5,"Y");

   background->Draw("same");   
   mass->Draw("same");
   f->Draw("same");

   double yield = mass->Integral(5,6)/0.02;

   // Draw the legend:)   
   TLegend *leg = myLegend(0.50,0.5,0.86,0.92);
   leg->AddEntry(hNP,"CMS Preliminary","");
   leg->AddEntry(hNP,"p+Pb #sqrt{s_{NN}}= 5.02 TeV","");
   leg->AddEntry(hNP,Form("%.0f<p_{T}^{B}<%.0f GeV/c",ptmin,ptmax),"");
   leg->AddEntry(hNP,"Non-prompt","pl");
   leg->AddEntry(f,"Fit","l");
   leg->AddEntry(mass,"Real Non-prompt","f");
   leg->AddEntry(background,"Combinatorial Background","l");
   leg->Draw();
   TLegend *leg2 = myLegend(0.44,0.33,0.89,0.50);
   leg2->AddEntry(hNP,"B meson","");
   leg2->AddEntry(hNP,Form("N_{B}=%.0f", yield),"");
   leg2->Draw();

   cNP->SaveAs("NonpromptBplus/BMassNP.gif");

   return mass;
}
Exemple #12
0
TH1D* readData(TString dataset, TString name, TString wavel, Double_t peak1, Double_t peak2, Double_t intTime, Double_t shift){

    TString fileName = "./Data/" + dataset + ".txt";

    Double_t histoMin = 99999, histoMax = 0;

    ifstream ifs(fileName); if(!ifs.is_open()){cout << "Error. File " << fileName << " not found. Exiting...\n"; return NULL;}

    Double_t entry, wavelength, photons, stepsize;
    
    while(ifs >> entry >> wavelength >> photons){

        if(entry == 1) stepsize = wavelength;
        else if(entry == 2) stepsize = wavelength - stepsize;
        
        if(wavelength < histoMin) histoMin = wavelength;
        if(wavelength > histoMax) histoMax = wavelength;

    }

    ifs.close();

    TH1D *histo = new TH1D(name + wavel + TString::Format(" %1.2f", shift), name + wavel + TString::Format(" %1.2f", shift), Nint(entry), histoMin + shift - stepsize/2.0, histoMax + shift + stepsize/2.0);


    ifs.open(fileName); if(!ifs.is_open()){cout << "Error. File " << fileName << " not found. Exiting...\n"; return NULL;}
    
    while(ifs >> entry >> wavelength >> photons){
        
        for(Int_t x = 0; x< photons/(1000.0/intTime); x++){
            histo->Fill(wavelength + shift);
        }

    }

    ifs.close();

    TF1 *f;
    if(peak2 == 0.){
        f = new TF1("fit", "[0]+[1]*TMath::Voigt(x-[2],[3],[4])");
        f->SetParameter(0, histo->GetMinimum());
        f->SetParameter(1, histo->GetMaximum()/25.);
        f->SetParameter(2, peak1 + shift);
        f->SetParameter(3, .02);
        f->SetParameter(4, .02);
        f->SetParName(0, "Offset");
        f->SetParName(1, "Normalization");
        f->SetParName(2, "Mean");
        f->SetParName(3, "Sigma");
        f->SetParName(4, "Gamma");
    }
    else{
        f = new TF1("fit", "[0]+[1]*TMath::Voigt(x-[2],[3],[4])+[5]*TMath::Voigt(x-[6],[7],[8])");
        f->SetParameter(0, histo->GetMinimum());
        f->SetParameter(1, histo->GetMaximum()/20.);
        f->SetParameter(2, peak1+shift-0.1);
        f->SetParameter(3, .02);
        f->SetParameter(4, .02);
        f->SetParameter(5, histo->GetMaximum()/20.);
        f->SetParameter(6, peak2+shift+0.1);
        f->SetParameter(7, .02);
        f->SetParameter(8, .02);
        f->SetParName(0, "Offset");
        f->SetParName(1, "Normalization 1");
        f->SetParName(2, "Mean 1");
        f->SetParName(3, "Sigma 1");
        f->SetParName(4, "Gamma 1");
        f->SetParName(5, "Normalization 2");
        f->SetParName(6, "Mean 2");
        f->SetParName(7, "Sigma 2");
        f->SetParName(8, "Gamma 2");
    }

    histo->SetLineWidth(2);
    histo->SetMarkerStyle(20);
    histo->SetMarkerSize(1.5);
    histo->SetMarkerColor(kRed);
    histo->SetLineColor(kBlack);
    histo->GetXaxis()->SetTitle("Wavelength (#AA)");
    histo->GetXaxis()->CenterTitle();
    histo->GetXaxis()->SetTitleSize(0.045);
    histo->GetXaxis()->SetTitleOffset(1.00);
    histo->GetXaxis()->SetLabelOffset(0.010);
    histo->GetXaxis()->SetLabelSize(0.045);
    histo->GetYaxis()->SetTitle("Photon count");
    histo->GetYaxis()->CenterTitle();
    histo->GetYaxis()->SetTitleSize(0.050);
    histo->GetYaxis()->SetTitleOffset(0.95);
    histo->GetYaxis()->SetLabelSize(0.045);
    gStyle->SetTitleSize(0.070, "t");
    if(peak2 == 0.) histo->SetTitle(name + TString::Format(" %4.2f #AA", f->GetParameter(2)));
    else histo->SetTitle(name + TString::Format(" %4.2f / %4.2f #AA", f->GetParameter(2), f->GetParameter(6)));
    //histo->SetTitle("Sodium 5890.522 / 5890.567 #AA");
    cout << shift << endl;

    f->SetLineColor(kBlue);
    f->SetLineWidth(4);
    cout << "Fitting " << name << endl;
    histo->Fit(f, "ME");

    return histo;

}
Exemple #13
0
TH1D *GetHisto(float ptcut = 0.15, char *name, char *filename, float etacut){
  TFile *file = new TFile(filename);
  TList *list = file->FindObject("out2");
  //TH2F *allhad = ((TH2F*) out2->FindObject("EtSimulatedAllHadron"))->Clone("allhad");
  TH2F *allhad = ((TH2F*) out2->FindObject("EtSimulatedChargedHadron"))->Clone("allhad");
  TH2F *ptlow = ((TH2F*) out2->FindObject("EtSimulatedChargedHadronAssumingNoPt"))->Clone("ptlow");
  TH2F *pthigh;
  if(ptcut>0.14){//TPC cut off
    (TH2F*)pthigh =(TH2F*) ((TH2F*) out2->FindObject("EtSimulatedChargedHadronAssumingPtTPCCut"))->Clone("pthigh");
  }
  else{
    (TH2F*)pthigh =(TH2F*) ((TH2F*) out2->FindObject("EtSimulatedChargedHadronAssumingPtITSCut"))->Clone("pthigh");
  }

  int lowbin = allhad->GetXaxis()->FindBin(0.0);//make sure we don't accidentally get the wrong bin
  int highbin = allhad->GetXaxis()->FindBin(ptcut);
  int nbins = allhad->GetXaxis()->GetNbins();
  cout<<"Projecting from "<<allhad->GetXaxis()->GetBinLowEdge(lowbin)<<" to "<<allhad->GetXaxis()->GetBinLowEdge(highbin+1)<<endl;
  cout<<"Projecting from "<<allhad->GetXaxis()->GetBinLowEdge(lowbin)<<" to "<<allhad->GetXaxis()->GetBinLowEdge(nbins)<<endl;

  //allhad->Sumw2();


  TH1D *numerator = allhad->ProjectionY("name",lowbin,highbin);
  TH1D *denominator = allhad->ProjectionY("denominator",lowbin,nbins);
  TH1D *numeratorLow = ptlow->ProjectionY("nameLow",lowbin,highbin);
  TH1D *denominatorLow = allhad->ProjectionY("denominatorLow",highbin,nbins);
  denominatorLow->Add(ptlow);
  TH1D *numeratorHigh = pthigh->ProjectionY("nameHigh",lowbin,highbin);
  TH1D *denominatorHigh = allhad->ProjectionY("denominatorHigh",highbin,nbins);
  denominatorHigh->Add(pthigh);

  numerator->Divide(denominator);
  numeratorLow->Divide(denominatorLow);
  numeratorHigh->Divide(denominatorHigh);

  TF1 *funcLow = new TF1("funcLow","[0]",-.7,.7);
  funcLow->SetParameter(0,0.01);
  numeratorLow->Fit(funcLow);
  TF1 *func = new TF1("func","[0]",-.7,.7);
  func->SetParameter(0,0.02);
  numerator->Fit(func);
  TF1 *funcHigh = new TF1("funcHigh","[0]",-.7,.7);
  funcHigh->SetParameter(0,0.02);
  numeratorHigh->Fit(funcHigh);

  mean = 1.0-func->GetParameter(0);
  lowbound = 1.0-funcHigh->GetParameter(0);
  highbound = 1.0-funcLow->GetParameter(0);
  cout<<"fpTcut = "<<mean<<","<<lowbound<<","<<highbound<<endl;
  cout<<"1/fpTcut = "<<1.0/mean<<","<<1.0/lowbound<<","<<1.0/highbound<<endl;
  //cout<<"fpTcut = "<<mean<<"-"<<mean-lowbound<<"+"<<highbound-mean<<endl;
  syserr = highbound-mean;
  if(mean-lowbound>syserr) syserr = mean-lowbound;
  cout<<Form("%2.4f^{+%2.4f}_{-%2.4f}",mean,highbound-mean,mean-lowbound)<<endl;
  cout<<"latex here ";
  cout<<Form("%2.4f \\pm %2.4f",mean,syserr)<<endl;
  cout<<"1/fpTcut = "<<1.0/mean<<"+"<<1.0/lowbound-1.0/mean<<"-"<<1.0/mean-1.0/highbound<<endl;
  numerator->SetYTitle("E_{T}^{had, p_{T}<cut-off}/E_{T}^{had, all p_{T}}");
  numerator->GetYaxis()->SetTitleOffset(1.);
  numerator->GetYaxis()->SetTitleSize(0.08);
  numerator->GetYaxis()->SetLabelSize(0.05);
  numerator->GetXaxis()->SetTitleSize(0.08);
  numerator->GetXaxis()->SetLabelSize(0.05);
  numerator->GetXaxis()->SetTitleOffset(.6);
  //numerator->Rebin(2);
  //numerator->Scale(0.5);
  //numerator->Draw("e");
  return numerator;

}
Exemple #14
0
void Plot(TString var,TCut cut,TString bins,Double_t xmax,TString cutpoint){
  setstyle(); 
 TH1::SetDefaultSumw2(true);
TCanvas *c2 = new TCanvas("canvas"+var+cutpoint,"canname"+var+cutpoint,800,800);
  TPad *mainPad = new TPad("","",0.01,0.25,0.99,0.99);
   mainPad->SetNumber(1);
   mainPad->Draw();
    TPad *ratioPad = new TPad("","",0.01,0.01,0.99,0.25);
   ratioPad->SetNumber(2);
   ratioPad->Draw();
c2->cd(1);
//   if (cutpoint == "noHT"){ TCut cut = numpj; TCut cutData = numpjData;}
//  else if (cutpoint == "HT200"){ TCut cut = HT200; TCut cutData = HT200Data; }//
//  else if (cutpoint == "anoHT"){ TCut cut = anumpj; TCut cutData = anumpjData;}
//  else if (cutpoint == "aHT200"){ TCut cut = aHT200; TCut cutData = aHT200Data; }
// else if (cutpoint == "HT300"){ TCut cut = HT300;  TCut cutData = HT300Data;}
// else if (cutpoint == "HT350"){ TCut cut = HT350; TCut cutData = HT350Data; }
//  else if (cutpoint == "aT"){ TCut cut = aT;  TCut cutData = aTData;}
//  else if (cutpoint == "early"){TCut cut = earlyaT; TCut cutData = earlyaTData;}

//else{cout << "ERRORRRR: BRaaaaaaaaaaaaaaaaaains" << endl; }
  TCut cutData = trig && hbhe && cut;
  TH1D* lm0 = GetHist("LM0",kRed,var,cut,bins,tLM0,cutpoint);
  ///  cout << "lm0" << endl;
  TH1D* lm1 = GetHist("LM1",kRed,var,cut,bins,tLM1,cutpoint);
  //  cout << "lm1" << endl;
  TH1D* qcd = GetHist("QCD_AllPtBins_7TeV_Pythia",kOrange+4,var,cut && mu_pt_hi,bins,tQCD,cutpoint);
  // cout << "qcd" << endl;
  TH1D* data = GetHist("Data",1,var,cutData,bins,tData,cutpoint);
  // cout << "data" << endl;
  TH1D* W = GetHist("Wjets_vols",kBlue,var,cut,bins,tW,cutpoint);
  //cout << "W" << endl;
  TH1D* tt = GetHist("ttbarTauola",kGreen,var,cut,bins,tTT,cutpoint);
  // cout << "tt" << endl;
  TH1D* Z = GetHist("ZJets_madgraph",kYellow,var,cut,bins,tZ,cutpoint);
  // cout << "Z" << endl;


  //TH1D* qcd_lo = GetHist("QCD_AllPtBins_7TeV_Pythia",kOrange+4,var,cut && mu_pt_lo,bins,tQCD,cutpoint);
 

  //   qcd_lo->Scale(1.94);
  // qcd->Add(qcd_lo);
 // TH1D* SM = GetHist("SM",kGray+2,var,cut,binstLM0,cutpoint);
 lm1->SetLineStyle(2);
 W->Scale(1.29557302);
 tt->Scale(1.65789474);
 Z->Scale(3048./2400.);

 TH1::SetDefaultSumw2(true);

 TH1D *SM   = (TH1D*)qcd->Clone();
 SM->Add(Z);
 SM->Add(tt);
 SM->Add(W);
 //SM->SetLineColor(kGray+2);
 // SM->SetFillStyle(3001);
 // SM->SetFillColor(kGray+2);
 // SM->SetMarkerSize(0.);
 //for(int bnum = 1; bnum <9; bnum++){
 //  if(data->GetBinContent(bnum)>0){
 // cout << "Bin Number " << bnum << " has qcd " << qcd->GetBinContent(bnum) << " and data " << data->GetBinContent(bnum) <<  " and SM " << SM->GetBinContent(bnum) <<  " and scale factor to QCD " << data->GetBinContent(bnum)/qcd->GetBinContent(bnum) << " and scale factor to SM " << data->GetBinContent(bnum)/SM->GetBinContent(bnum) << endl; 
 // }
 //  }
 c2->cd(1)->SetLogy();
 //  data->Draw("PE0");
 SM->Draw("E");
   THStack bkg("bkg","test stacked histograms");
   bkg.Add(Z);
   bkg.Add(tt);
   bkg.Add(W);
   bkg.Add(qcd);

   bkg.Draw("HIST0SAME");
   //  data->Draw("PE0SAME");
   
   
   //qcd->Draw("HIST0same");
   /*  
      W->Draw("HIST0same");
         Z->Draw("HIST0same");
       tt->Draw("HIST0same");
   */
    lm0->Draw("HIST0same"); lm0->SetLineColor(1); lm0->SetFillColor(0);
    lm1->Draw("HIST0same"); lm1->SetLineColor(1); lm1->SetFillColor(0); lm1->SetLineStyle(2);
	//  data->Draw("EPSAME");  
  if(xmax == 1337){
      double ymax=SM->GetMaximum()*12.6;}
  else{
    double ymax=SM->GetMaximum()*10.6;}
	SM->GetYaxis()->SetRangeUser(0.05,ymax);
	if (var=="AlphaT_Lep") { data->GetXaxis()->SetRangeUser(0.,xmax);}
	SM->GetXaxis()->SetTitle(var);
	SM->SetTitle();
  TLegend *leg = new TLegend(0.73803,0.591026,0.88137,0.880819);
  // leg->SetShadowColor(0);
  //leg->SetBorderSize(0);
  //leg->SetFillStyle(4100);
  leg->SetTextSize(0.04);
  leg->SetFillColor(0);
  leg->SetLineColor(0);
  
  // leg->AddEntry(data,"DATA","PL");
   leg->AddEntry(qcd,"QCD","FL");
  leg->AddEntry(W,"W","FL");
  leg->AddEntry(Z,"Z","FL");
  leg->AddEntry(tt,"TTbar","FL");
  leg->AddEntry(lm0,"LM0","FL");
  leg->AddEntry(lm1,"LM1","FL");
  
  //leg->AddEntry(SM,"SM BKGD","FL");
  leg->Draw("same");
  
   TLatex  *prelim = new TLatex(0.1152,0.81981,"CMS preliminary 2010");



  TLatex *lumi = new TLatex(0.1015,.9403,"#scale[0.8]{#int L dt = " +luminum+ "pb^{-1}, #sqrt{s} = 7 TeV}");
    prelim->SetNDC();
    lumi->SetNDC();
    //   prelim->Draw("same");
   lumi->Draw("same");

   TH1D *RatioBottom = (TH1D*)SM->Clone("Ratiob");
   TH1D *RatioTop = (TH1D*)data->Clone("Ratiot");
   RatioTop->GetYaxis()->SetTitle("data / sim");
 RatioTop->GetXaxis()->SetTitle();
      RatioTop->Divide(RatioBottom);

      c2->cd(2);
      gPad->SetGridx(); gPad->SetGridy();
   RatioTop->SetTitleSize(0.1, "XYZ");
    RatioTop->SetTitleOffset(0.55, "X");
    RatioTop->SetTitleOffset(0.3, "Y");
    RatioTop->SetLabelSize(0.06,"XY");
    RatioTop->GetYaxis()->SetRangeUser(-2.,4.0);
    RatioTop->Draw();
    RatioTop->GetYaxis()->SetLabelSize(0.05);
    TBox *unity = new TBox(RatioTop->GetXaxis()->GetBinLowEdge(RatioTop->GetXaxis()->GetFirst()), 0.89,RatioTop->GetXaxis()->GetBinLowEdge(RatioTop->GetXaxis()->GetLast()), 1.11);
    unity->SetLineWidth(2);
unity->SetLineColor(2);
    unity->SetFillColor(2);
    unity->SetFillStyle(3002);
    unity->Draw();

    c2->Update();
    if(cutpoint == "early"){
      c2->SaveAs(plots+erlee+"Muon_ND"+selec+var+"_"+cutpoint+".png");
    }
    else if (xmax == 90003){
      c2->SaveAs(plots+"Muon_ND"+selec+"_zooomed_"+var+"_"+cutpoint+".png");}
    else{
      c2->SaveAs(plots+"Muon_ND"+ptsec++selec+var+"_"+cutpoint+".png");}



 
       c2->Close();
}
void zlljets_ZpT_recoGenAna(const string fmumuName = "zmumujets_resoResp_noSkim_light.root", const string feeName = "zeejets_resoResp_noSkim_light.root", const char* suffix = "") {

  TH1::SetDefaultSumw2();   

  string plotDirectoryPath = "/cmshome/ciprianim/CMSSW721/pdfsFromAnalysis/plots/ZtoLLSamples/ZpTAnalysis/";
  //string plotDirectoryPath = "./tmpPlots/";  used when working in my pc
  string plotFileExtension = ".pdf";

  // index 0 of array is for muons, index 1 is for electrons, thus recoZpt[0] refers to Z->mumu ((maybe it will be better to change it)

  vector<string> fileName;
  fileName.push_back(fmumuName);
  fileName.push_back(feeName);

  vector<string> sample;
  sample.push_back("Z(#mu#mu)+jets");
  sample.push_back("Z(ee)+jets");

  vector<TH1D*> hZpTreco;
  vector<TH1D*> hZpTgen;
  vector<TH1D*> hZpTrecoGenRatio;
  vector<TH1D*> hZpTrecoGenRatio_pdf;

  Int_t nFiles = (Int_t)fileName.size();
  Int_t histColor[] = {kBlue,kOrange,kRed,kGreen};

  Double_t zptStart = 400.0;
  Double_t zptEnd = 800.0;
  TH1D *HZtoLLPt_RecoGenRatio_pdf_inRange[2];

  for(Int_t i = 0; i < 2; i++) {
	
    HZtoLLPt_RecoGenRatio_pdf_inRange[i] = new TH1D(Form("HZtoLLPt_RecoGenRatio_pdf_%d_Zpt%2.0lfTo%2.0lf",i+1,zptStart,zptEnd),"",100,0.5,1.5);

  }

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

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

    TFile* f = TFile::Open(fileName[i].c_str(),"READ");
    
    if (!f || !f->IsOpen()) {

      cout<<"*******************************"<<endl;
      cout<<"Error opening file \""<<fileName[i]<<"\".\nApplication will be terminated."<<endl;
      cout<<"*******************************"<<endl;
      exit(EXIT_FAILURE);

    }

    hZpTreco.push_back((TH1D*)f->Get("HZtoLLRecoPt"));
    hZpTgen.push_back((TH1D*)f->Get("HZtoLLGenPt"));
    hZpTrecoGenRatio.push_back((TH1D*)f->Get("HZtoLLPt_RecoGenRatio"));
    hZpTrecoGenRatio_pdf.push_back((TH1D*)f->Get("HZtoLLPt_RecoGenRatio_pdf"));

    if ( !(hZpTreco[i] && hZpTgen[i] && hZpTrecoGenRatio[i] && hZpTrecoGenRatio_pdf[i] ) ) {

      cout << "Error: could not get histograms from file " << fileName[i] << endl;
      exit(EXIT_FAILURE);

    }
	 
  }

  Int_t startingBin = hZpTrecoGenRatio[0]->FindBin(zptStart) ;  // will consider ratio pdf for Zpt > 600 GeV  (they should be equal for Z->ee and Z->nunu)
  Int_t endingBin = hZpTrecoGenRatio[0]->FindBin(zptEnd) ;     // will consider ratio pdf for Zpt < 1000 GeV  (they should be equal for Z->ee and Z->nunu)
  cout << "ZpT bins from "<<startingBin<<" to "<<endingBin<< endl;

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

    for (Int_t i = startingBin; i < endingBin; i++) {

      HZtoLLPt_RecoGenRatio_pdf_inRange[j]->Fill(hZpTrecoGenRatio[j]->GetBinContent(i));

    }

    HZtoLLPt_RecoGenRatio_pdf_inRange[j]->Scale(1./HZtoLLPt_RecoGenRatio_pdf_inRange[j]->Integral(0,1 + HZtoLLPt_RecoGenRatio_pdf_inRange[j]->GetNbinsX()));

  }   // note that this distribution will be almost empty because it's the distribution of the mean of various ZpT points.

  //cout << " ****************  check ************** " << endl;

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

    hZpTreco[j]->SetStats(kFALSE);   // to avoid drawing statistic box
    hZpTreco[j]->SetLineColor(histColor[j]);
    // no need to use TH1::Scale() between reco and gen of Z->mumu or Z->ee, because histogram are filled for the same set of events, so integral
    // should be the same in principle
    //hZpTreco[j]->SetFillColorAlpha(histColor[j], 0.80);
    hZpTgen[j]->SetStats(kFALSE);   // to avoid drawing statistic box
    hZpTgen[j]->SetLineColor(histColor[j+2]);
    hZpTrecoGenRatio[j]->SetStats(kFALSE);
    //hZpTrecoGenRatio[j]->SetLineColor(histColor[j]);
    hZpTrecoGenRatio_pdf[j]->SetStats(kFALSE);
    hZpTrecoGenRatio_pdf[j]->SetLineColor(histColor[j+2]);
    HZtoLLPt_RecoGenRatio_pdf_inRange[j]->SetStats(kFALSE);
    HZtoLLPt_RecoGenRatio_pdf_inRange[j]->SetLineColor(histColor[j*2]);
    
  }

  TPad *subpad1 = NULL;  // will use it to access specific subpad in canvas
  TPad *subpad2 = NULL; 

  TCanvas *cZtomumuPtRecoGen = new TCanvas("cZtomumuPtRecoGen","",700,700);
  TLegend *legZtomumuPtRecoGen = new TLegend(0.70,0.7,0.89,0.89); 
  subpad1 = new TPad("pad1","",0.0,0.36,1.0,1.0);
  subpad1->SetLogy();
  subpad1->SetBottomMargin(0);
  subpad2 = new TPad("pad2","",0.0,0.0,1.0,0.36);
  subpad2->SetGrid();
  subpad2->SetTopMargin(0);
  subpad2->SetBottomMargin(0.2);
  subpad1->Draw();
  subpad2->Draw();
  //cout <<"Drawing histograms and ratio"<<endl;
  subpad1->cd();
  // hZpTreco[0]->GetXaxis()->SetTitle("Z_{pT}[GeV]");
  // hZpTreco[0]->GetXaxis()->SetTitleSize(0.04);
  //hZpTreco[0]->GetXaxis()->SetLabelSize(0.04);
  hZpTreco[0]->GetYaxis()->SetTitle("# events");
  hZpTreco[0]->GetYaxis()->SetTitleSize(0.04);
  hZpTreco[0]->GetYaxis()->SetLabelSize(0.04);
  hZpTreco[0]->GetYaxis()->CenterTitle();
  //hZpTreco[0]->GetYaxis()->SetLabelSize(0.04);
  hZpTreco[0]->Draw("HE");
  hZpTgen[0]->Draw("HE SAME");
  legZtomumuPtRecoGen->AddEntry(hZpTreco[0],"Z(#mu#mu) reco","l");
  legZtomumuPtRecoGen->AddEntry(hZpTgen[0],"Z(#mu#mu) gen","l");
  gStyle->SetStatStyle(0);
  legZtomumuPtRecoGen->Draw(); 
  legZtomumuPtRecoGen->SetMargin(0.3); 
  legZtomumuPtRecoGen->SetBorderSize(0);
  subpad2->cd();
  hZpTrecoGenRatio[0]->GetXaxis()->SetLabelSize(0.08);
  hZpTrecoGenRatio[0]->GetXaxis()->SetTitle("Z_{pT}[GeV]");
  hZpTrecoGenRatio[0]->GetXaxis()->SetTitleSize(0.07);
  hZpTrecoGenRatio[0]->GetXaxis()->SetTitleOffset(1.2);
  hZpTrecoGenRatio[0]->GetYaxis()->SetLabelSize(0.07);
  hZpTrecoGenRatio[0]->GetYaxis()->SetTitle("reco/gen ZpT");
  hZpTrecoGenRatio[0]->GetYaxis()->SetTitleSize(0.07);
  hZpTrecoGenRatio[0]->GetYaxis()->SetTitleOffset(0.5);
  hZpTrecoGenRatio[0]->GetYaxis()->CenterTitle();
  hZpTrecoGenRatio[0]->Draw("E");
  hZpTrecoGenRatio[0]->SetMarkerStyle(7);  //medium dot
  cZtomumuPtRecoGen->SaveAs( (plotDirectoryPath + cZtomumuPtRecoGen->GetName() + suffix + plotFileExtension).c_str() );

  TPad *subpad1_bis = NULL;
  TPad *subpad2_bis = NULL;

  TCanvas *cZtoeePtRecoGen = new TCanvas("cZtoeePtRecoGen","",700,700);
  TLegend *legZtoeePtRecoGen = new TLegend(0.70,0.7,0.89,0.89); 
  subpad1_bis = new TPad("pad1","",0.0,0.36,1.0,1.0);
  subpad1_bis->SetLogy();
  subpad1_bis->SetBottomMargin(0);
  subpad2_bis = new TPad("pad2","",0.0,0.0,1.0,0.36);
  subpad2_bis->SetGrid();
  subpad2_bis->SetTopMargin(0);
  subpad2_bis->SetBottomMargin(0.2);
  subpad1_bis->Draw();
  subpad2_bis->Draw();
  //cout <<"Drawing histograms and ratio"<<endl;
  subpad1_bis->cd();
  // hZpTreco[1]->GetXaxis()->SetTitle("Z_{pT}[GeV]");
  // hZpTreco[1]->GetXaxis()->SetTitleSize(0.04);
  //hZpTreco[1]->GetXaxis()->SetLabelSize(0.04);
  hZpTreco[1]->GetYaxis()->SetTitle("# events");
  hZpTreco[1]->GetYaxis()->SetTitleSize(0.04);
  hZpTreco[1]->GetYaxis()->SetLabelSize(0.04);
  hZpTreco[1]->GetYaxis()->CenterTitle();
  //hZpTreco[1]->GetYaxis()->SetLabelSize(0.04);
  hZpTreco[1]->Draw("HE");
  hZpTgen[1]->Draw("HE SAME");
  legZtoeePtRecoGen->AddEntry(hZpTreco[0],"Z(ee) reco","l");
  legZtoeePtRecoGen->AddEntry(hZpTgen[0],"Z(ee) gen","l");
  gStyle->SetStatStyle(0);
  legZtoeePtRecoGen->Draw(); 
  legZtoeePtRecoGen->SetMargin(0.3); 
  legZtoeePtRecoGen->SetBorderSize(0);
  subpad2_bis->cd();
  hZpTrecoGenRatio[1]->GetXaxis()->SetLabelSize(0.08);
  hZpTrecoGenRatio[1]->GetXaxis()->SetTitle("Z_{pT}[GeV]");
  hZpTrecoGenRatio[1]->GetXaxis()->SetTitleSize(0.07);
  hZpTrecoGenRatio[1]->GetXaxis()->SetTitleOffset(1.2);
  hZpTrecoGenRatio[1]->GetYaxis()->SetLabelSize(0.07);
  hZpTrecoGenRatio[1]->GetYaxis()->SetTitle("reco/gen ZpT");
  hZpTrecoGenRatio[1]->GetYaxis()->SetTitleOffset(0.5);
  hZpTrecoGenRatio[1]->GetYaxis()->SetTitleSize(0.07);
  hZpTrecoGenRatio[1]->GetYaxis()->CenterTitle();
  hZpTrecoGenRatio[1]->Draw("E");
  hZpTrecoGenRatio[1]->SetMarkerStyle(7);  //medium dot
  cZtoeePtRecoGen->SaveAs( (plotDirectoryPath + cZtoeePtRecoGen->GetName() + suffix + plotFileExtension).c_str() );

  // TCanvas *cZtoeePtRecoGen = new TCanvas("cZtoeePtRecoGen","",700,700);
  // TLegend *legZtoeePtRecoGen = new TLegend(0.70,0.7,0.89,0.89);
  // cZtoeePtRecoGen->Divide(1,2,0,0);
  // cZtoeePtRecoGen->cd(1);
  // subpad1 = (TPad*)cZtoeePtRecoGen->GetPad(1);
  // subpad1->SetPad(0.0,0.36,0.98,0.99);
  // subpad1->SetLogy();
  // //cout <<"Drawing histograms and ratio"<<endl;
  // // hZpTreco[1]->GetXaxis()->SetTitle("Z_{pT}[GeV]");
  // // hZpTreco[1]->GetXaxis()->SetTitleSize(0.04);
  // hZpTreco[1]->GetYaxis()->SetTitle("# events");
  // hZpTreco[1]->GetYaxis()->SetTitleSize(0.045);
  // hZpTreco[1]->GetYaxis()->CenterTitle();
  // //hZpTreco[1]->GetYaxis()->SetLabelSize(0.1);
  // hZpTreco[1]->Draw("HE");
  // hZpTgen[1]->Draw("HE SAME");
  // legZtoeePtRecoGen->AddEntry(hZpTreco[1],"Z(ee) reco","l");
  // legZtoeePtRecoGen->AddEntry(hZpTgen[1],"Z(ee) gen","l");
  // gStyle->SetStatStyle(0);
  // legZtoeePtRecoGen->Draw(); 
  // legZtoeePtRecoGen->SetMargin(0.3); 
  // legZtoeePtRecoGen->SetBorderSize(0);
  // cZtoeePtRecoGen->cd(2);
  // subpad2 = (TPad*)cZtoeePtRecoGen->GetPad(2);
  // subpad2->SetPad(0.0,0.0,0.98,0.36);
  // subpad2->SetGrid();
  // hZpTrecoGenRatio[1]->GetXaxis()->SetLabelSize(0.08);
  // hZpTrecoGenRatio[1]->GetXaxis()->SetTitle("Z_{pT}[GeV]");
  // hZpTrecoGenRatio[1]->GetXaxis()->SetTitleSize(0.06);
  // hZpTrecoGenRatio[1]->GetXaxis()->SetTitleOffset(1.2);
  // hZpTrecoGenRatio[1]->GetYaxis()->SetLabelSize(0.08);
  // hZpTrecoGenRatio[1]->Draw("E");
  // hZpTrecoGenRatio[1]->SetMarkerStyle(7);  //medium dot
  // cZtoeePtRecoGen->SaveAs( (plotDirectoryPath + cZtoeePtRecoGen->GetName() + suffix + plotFileExtension).c_str() );

  // now I normalize histograms to same area (here is 1) to compare Z->mumu and Z->ee which have different numbers of events

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

    hZpTreco[j]->Scale(1./hZpTreco[j]->Integral(0,1 + hZpTreco[j]->GetNbinsX()));  // normalize to unity, use integral including underflow & overflow bin
    hZpTgen[j]->Scale(1./hZpTgen[j]->Integral(0,1 + hZpTgen[j]->GetNbinsX()));
    hZpTrecoGenRatio_pdf[j]->Scale(1./hZpTrecoGenRatio_pdf[j]->Integral(0,1 + hZpTrecoGenRatio_pdf[j]->GetNbinsX()));

  }

  TCanvas *cZtollPtRecoGen = new TCanvas("cZtollPtRecoGen","");
  TLegend *legZtollPtRecoGen = new TLegend(0.70,0.7,0.89,0.89); 
  cZtollPtRecoGen->SetLogy();
  //cout <<"Drawing histograms and ratio"<<endl;
  hZpTreco[0]->GetXaxis()->SetTitle("Z_{pT}[GeV]");
  hZpTreco[0]->GetXaxis()->SetTitleSize(0.04);
  hZpTreco[0]->GetYaxis()->SetTitle("# events");
  hZpTreco[0]->GetYaxis()->SetTitleSize(0.045);
  hZpTreco[0]->GetYaxis()->CenterTitle();
  hZpTreco[0]->Draw("HE");
  hZpTgen[0]->Draw("HE SAME");
  hZpTreco[1]->Draw("HE SAME");
  hZpTgen[1]->Draw("HE SAME");
  legZtollPtRecoGen->AddEntry(hZpTreco[0],"Z(#mu#mu) reco","l");
  legZtollPtRecoGen->AddEntry(hZpTgen[0],"Z(#mu#mu) gen","l");
  legZtollPtRecoGen->AddEntry(hZpTreco[1],"Z(ee) reco","l");
  legZtollPtRecoGen->AddEntry(hZpTgen[1],"Z(ee) gen","l");
  gStyle->SetStatStyle(0);
  legZtollPtRecoGen->Draw(); 
  legZtollPtRecoGen->SetMargin(0.3); 
  legZtollPtRecoGen->SetBorderSize(0);
  cZtollPtRecoGen->SaveAs( (plotDirectoryPath + cZtollPtRecoGen->GetName() + suffix + plotFileExtension).c_str() );

  Int_t bins;
  Double_t firstEdge;
  Double_t lastEdge;
  TH1D *hZpTMuEleRecoRatio;
  TCanvas *cZpTMuEleRecoRatio;

  if( hZpTreco[0]->GetNbinsX() == hZpTreco[1]->GetNbinsX() ) {

    bins = hZpTreco[0]->GetNbinsX();
    firstEdge = hZpTreco[0]->GetXaxis()->GetBinLowEdge(1);
    lastEdge = hZpTreco[0]->GetXaxis()->GetBinUpEdge(bins);
    hZpTMuEleRecoRatio = new TH1D("hZpTMuEleRecoRatio","",bins,firstEdge,lastEdge);
    

    // cout << "hZpTreco[0]->GetNbinsX() : "<< hZpTreco[0]->GetNbinsX() << endl;
    // cout << "hZpTreco[1]->GetNbinsX() : "<< hZpTreco[1]->GetNbinsX() << endl;
    // cout << "hZpTMuEleGenRatio->GetNbinsX() : "<< hZpTMuEleGenRatio->GetNbinsX() << endl;

    if (!hZpTMuEleRecoRatio->Divide(hZpTreco[0],hZpTreco[1])) cout << " Error in hZpTMuEleRecoRatio->Divide(hZpTreco[0],hZpTreco[1])" << endl;
    hZpTMuEleRecoRatio->SetStats(kFALSE);
   
    cZpTMuEleRecoRatio = new TCanvas("cZpTMuEleRecoRatio","");
    hZpTMuEleRecoRatio->GetXaxis()->SetTitle("Z_{pT}[GeV]");
    hZpTMuEleRecoRatio->GetXaxis()->SetTitleSize(0.04);
    hZpTMuEleRecoRatio->GetYaxis()->SetTitle("reco pT_{Z(#mu#mu)} / pT_{Z(ee)} ");
    hZpTMuEleRecoRatio->GetYaxis()->SetTitleSize(0.045);
    hZpTMuEleRecoRatio->GetYaxis()->SetRangeUser(0.5,1.5);
    hZpTMuEleRecoRatio->GetYaxis()->CenterTitle();
    hZpTMuEleRecoRatio->Draw("E");
    gStyle->SetStatStyle(0);
    cZpTMuEleRecoRatio->SaveAs( (plotDirectoryPath + cZpTMuEleRecoRatio->GetName() + suffix + plotFileExtension).c_str() );
    
  }

  TH1D *hZpTMuEleGenRatio;
  TCanvas *cZpTMuEleGenRatio;

  if (hZpTgen[0]->GetNbinsX() == hZpTgen[1]->GetNbinsX()) {

    bins = hZpTgen[0]->GetNbinsX();
    firstEdge = hZpTgen[0]->GetXaxis()->GetBinLowEdge(1);
    lastEdge = hZpTgen[0]->GetXaxis()->GetBinUpEdge(bins);
    hZpTMuEleGenRatio = new TH1D("hZpTMuEleGenRatio","",bins,firstEdge,lastEdge);

    if (!hZpTMuEleGenRatio->Divide(hZpTgen[0],hZpTgen[1])) cout << " Error in hZpTMuEleGenRatio->Divide(hZpTgen[0],hZpTgen[1])" << endl;
    hZpTMuEleGenRatio->SetStats(kFALSE);

    cZpTMuEleGenRatio = new TCanvas("cZpTMuEleGenRatio","");
    hZpTMuEleGenRatio->GetXaxis()->SetTitle("Z_{pT}[GeV]");
    hZpTMuEleGenRatio->GetXaxis()->SetTitleSize(0.04);
    hZpTMuEleGenRatio->GetYaxis()->SetTitle("gen pT_{Z(#mu#mu)} / pT_{Z(ee)} ");
    hZpTMuEleGenRatio->GetYaxis()->SetTitleSize(0.045);
    hZpTMuEleGenRatio->GetYaxis()->SetRangeUser(0.5,1.5);
    hZpTMuEleGenRatio->GetYaxis()->CenterTitle();
    hZpTMuEleGenRatio->Draw("E");
    gStyle->SetStatStyle(0);
    cZpTMuEleGenRatio->SaveAs( (plotDirectoryPath + cZpTMuEleGenRatio->GetName() + suffix + plotFileExtension).c_str() );
 
  }


  TCanvas *cZpTRecoGenRatio_pdf = new TCanvas("cZpTRecoGenRatio_pdf","");
  TLegend *legZpTRecoGenRatio_pdf = new TLegend(0.78,0.78,0.89,0.89);
  hZpTrecoGenRatio_pdf[0]->GetXaxis()->SetTitle("reco Z_{pT}/gen Z_{pT}");
  hZpTrecoGenRatio_pdf[0]->GetXaxis()->SetTitleSize(0.04);
  hZpTrecoGenRatio_pdf[0]->GetXaxis()->SetRangeUser(0.7,1.3);
  hZpTrecoGenRatio_pdf[0]->GetYaxis()->SetTitle("a.u. ");
  hZpTrecoGenRatio_pdf[0]->GetYaxis()->SetTitleSize(0.045);
  hZpTrecoGenRatio_pdf[0]->GetYaxis()->SetRangeUser(0.0,0.4);
  hZpTrecoGenRatio_pdf[0]->GetYaxis()->CenterTitle();
  hZpTrecoGenRatio_pdf[0]->Draw("HE");
  hZpTrecoGenRatio_pdf[1]->Draw("HE SAME");
  legZpTRecoGenRatio_pdf->AddEntry(hZpTrecoGenRatio_pdf[0],"Z(#mu#mu)","l");
  legZpTRecoGenRatio_pdf->AddEntry(hZpTrecoGenRatio_pdf[1],"Z(ee)","l");
  gStyle->SetStatStyle(0);
  legZpTRecoGenRatio_pdf->Draw(); 
  legZpTRecoGenRatio_pdf->SetMargin(0.3); 
  legZpTRecoGenRatio_pdf->SetBorderSize(0);
  cZpTRecoGenRatio_pdf->SaveAs( (plotDirectoryPath + cZpTRecoGenRatio_pdf->GetName() + suffix + plotFileExtension).c_str() );

  TCanvas *cZpTRecoGenRatio_pdf_inRange = new TCanvas(Form("ZpTRecoGenRatio_pdf_Zpt%2.0lfTo%2.0lf",zptStart,zptEnd),"");
  TLegend *legZpTRecoGenRatio_pdf_inRange = new TLegend(0.78,0.78,0.89,0.89);
  TPaveLabel *title = new TPaveLabel(0.1,0.94,0.9,0.98,Form("Zpt recoGen ratio: %2.0lf < ZpT < %2.0lf",zptStart,zptEnd));
  title->Draw();
  HZtoLLPt_RecoGenRatio_pdf_inRange[0]->GetXaxis()->SetTitle("reco Z_{pT}/gen Z_{pT}");
  HZtoLLPt_RecoGenRatio_pdf_inRange[0]->GetXaxis()->SetTitleSize(0.04);
  HZtoLLPt_RecoGenRatio_pdf_inRange[0]->GetXaxis()->SetRangeUser(0.7,1.3);
  HZtoLLPt_RecoGenRatio_pdf_inRange[0]->GetYaxis()->SetTitle("a.u. ");
  HZtoLLPt_RecoGenRatio_pdf_inRange[0]->GetYaxis()->SetTitleSize(0.045);
  HZtoLLPt_RecoGenRatio_pdf_inRange[0]->GetYaxis()->SetRangeUser(0.0,0.4);
  HZtoLLPt_RecoGenRatio_pdf_inRange[0]->GetYaxis()->CenterTitle();
  HZtoLLPt_RecoGenRatio_pdf_inRange[0]->Draw("HE");
  HZtoLLPt_RecoGenRatio_pdf_inRange[1]->Draw("HE SAME");
  legZpTRecoGenRatio_pdf_inRange->AddEntry(HZtoLLPt_RecoGenRatio_pdf_inRange[0],"Z(#mu#mu)","l");
  legZpTRecoGenRatio_pdf_inRange->AddEntry(HZtoLLPt_RecoGenRatio_pdf_inRange[1],"Z(ee)","l");
  gStyle->SetStatStyle(0);
  legZpTRecoGenRatio_pdf_inRange->Draw(); 
  legZpTRecoGenRatio_pdf_inRange->SetMargin(0.3); 
  legZpTRecoGenRatio_pdf_inRange->SetBorderSize(0);
  cZpTRecoGenRatio_pdf_inRange->SaveAs( (plotDirectoryPath + cZpTRecoGenRatio_pdf_inRange->GetName() + suffix + plotFileExtension).c_str() );

}
Exemple #16
0
void MakeClosurePlot(TH1D* hObs, TH1D* hPred, TString name, bool logy=true) {
  set_style(hObs,"data_obs");
  set_style(hPred,"pred");

  // Setup canvas and pads
  TCanvas * c1 = new TCanvas("c1", "c1", 700, 700);
  c1->SetFillStyle(4000);
  TPad * pad1 = new TPad("pad1", "top pad" , 0.0, 0.3, 1.0, 1.0);
  pad1->SetFillStyle(4000);
  pad1->SetBottomMargin(0.0);
  pad1->Draw();
  TPad * pad2 = new TPad("pad2", "bottom pad", 0.0, 0.0, 1.0, 0.3);
  pad2->SetFillStyle(4000);
  pad2->SetTopMargin(0.0);
  pad2->SetBottomMargin(0.35);
  pad2->Draw();
  pad1->cd();
  pad1->SetLogy(logy);

  TH1D * staterr = (TH1D *) hPred->Clone("staterr");
  //  staterr->Sumw2();
  //staterr->SetFillColor(kRed);
  staterr->SetFillColor(kGray+3);
  staterr->SetMarkerSize(0);
  staterr->SetFillStyle(3013);

  //cout << "Compute ratio hist..." << endl;
  TH1D * ratio = (TH1D *) hPred->Clone("ratio");
  //ratio->Sumw2();
  ratio->SetMarkerSize(0.8);
  ratio->SetMarkerColor(1);
  //ratio->SetMarkerSize(0.5);
  ratio->Divide(hObs, hPred, 1., 1., "B");
  ratio->Print("all");
  TH1D * ratiostaterr = (TH1D *) hObs->Clone("ratiostaterr");
  //  ratiostaterr->Sumw2();
  ratiostaterr->SetStats(0);
  ratiostaterr->SetTitle(hPred->GetTitle());
  ratiostaterr->GetYaxis()->SetTitle("Obs/Pred.");
  ratiostaterr->SetMaximum(2.2);
  ratiostaterr->SetMinimum(0);
  ratiostaterr->SetMarkerSize(0);
  //ratiostaterr->SetFillColor(kRed);
  ratiostaterr->SetFillColor(kGray+3);
  ratiostaterr->SetFillStyle(3013);
  ratiostaterr->GetXaxis()->SetLabelSize(0.2);
  ratiostaterr->GetXaxis()->SetLabelOffset(0.03);
  ratiostaterr->GetXaxis()->SetTitleSize(0.14);
  ratiostaterr->GetXaxis()->SetTitleOffset(1.10);
  ratiostaterr->GetYaxis()->SetLabelSize(0.10);
  ratiostaterr->GetYaxis()->SetTitleSize(0.12);
  ratiostaterr->GetYaxis()->SetTitleOffset(0.6);
  ratiostaterr->GetYaxis()->SetNdivisions(505);
  TLine* ratiounity = new TLine(hPred->GetBinLowEdge(1),1,hPred->GetBinLowEdge(hPred->GetNbinsX()+1),1);
  ratiounity->SetLineStyle(2);
  for (Int_t i = 0; i < hPred->GetNbinsX()+2; i++) {
    // if (hObs->GetBinContent(i)>0.) ratio->SetBinError(i, hObs->GetBinError(i)/hObs->GetBinContent(i)); // just the fractional uncertainty on the observation
    ratiostaterr->SetBinContent(i, 1.0);
    if (hPred->GetBinContent(i) > 1e-6) { //< not empty
      double binerror = hPred->GetBinError(i) / hPred->GetBinContent(i);
      ratiostaterr->SetBinError(i, binerror);
    } else {
      ratiostaterr->SetBinError(i, 999.);
    }
  }
  TH1D * ratiosysterr = (TH1D *) ratiostaterr->Clone("ratiosysterr");
  //  ratiosysterr->Sumw2();
  ratiosysterr->SetMarkerSize(0);
  ratiosysterr->SetFillColor(kYellow-4);
  //ratiosysterr->SetFillStyle(3002);
  ratiosysterr->SetFillStyle(1001);
  for (Int_t i = 0; i < hPred->GetNbinsX()+2; i++) {
    if (hPred->GetBinContent(i) > 1e-6) { //< not empty
      double binerror2 = (pow(hPred->GetBinError(i), 2));
      double binerror = sqrt(binerror2);
      ratiosysterr->SetBinError(i, binerror / hPred->GetBinContent(i));
    }
  }


  double max = hObs->GetMaximum();
  if (hPred->GetMaximum() > max) max = hPred->GetMaximum();

  if (logy) {
    hPred->SetMaximum(max*10);
    hPred->SetMinimum(0.09);
  } else {
    hPred->SetMaximum(max*1.5);
    hPred->SetMinimum(0.);
  }

  hPred->GetYaxis()->SetTitle("Events / bin");
  hPred->Draw("hist");
  hObs->Draw("e1,same");
  staterr->Draw("e2 same");
  hPred->GetXaxis()->SetTitleSize(0.035);
  hPred->GetXaxis()->SetLabelSize(0.035);
  /* hObs->GetYaxis()->SetTitleSize(0.035); */
  /* hObs->GetYaxis()->SetLabelSize(0.035); */

  TLegend * leg2 = new TLegend(0.72, 0.68, 0.94, 0.92);
  set_style(leg2,0.035);
  leg2->AddEntry(hObs,"Obs.","elp");
  leg2->AddEntry(hPred,"Pred.","f");
  leg2->AddEntry(staterr, "Syst. uncert.", "f");
  leg2->Draw();
  TLatex * latex = new TLatex();
  latex->SetNDC();
  latex->SetTextAlign(12);
  latex->SetTextFont(62);
  latex->SetTextSize(0.042);
  latex->DrawLatex(0.19, 0.89, "CMS Simulation");
  latex->SetTextSize(0.03);
  TString stamp = Form("#sqrt{s} = 13 TeV, L = %3.1f fb^{-1}", int_lumi);
  latex->DrawLatex(0.19, 0.84, stamp);

  pad2->cd();
  pad2->SetGridy(0);
  ratiostaterr->GetXaxis()->SetRangeUser(0,6);
  ratiostaterr->Draw("e2");
  //ratiosysterr->Draw("e2 same");
  ratiostaterr->Draw("e2 same");
  ratiounity->Draw();
  ratio->Draw("e1 same");

  TPaveText * pave = new TPaveText(0.18, 0.86, 0.4, 0.96, "brNDC");
  pave->SetLineColor(0);
  pave->SetFillColor(kWhite);
  pave->SetShadowColor(0);
  pave->SetBorderSize(1);
  double nchisq = hObs->Chi2Test(hPred, "UWCHI2/NDF, P"); // MC uncert. (stat)
  double p_value = hObs->Chi2Test(hPred, "UW"); // MC uncert. (stat)
  // //double kolprob = hdata_obs->KolmogorovTest(hmc_pred); // MC uncert. (stat)
  TText * text = pave->AddText(Form("#chi_{#nu}^{2}/ndf = %.3f, p = %.3f", nchisq, p_value));
  // //TText * text = pave->AddText(Form("#chi_{#nu}^{2} = %.3f, K_{s} = %.3f", nchisq, kolprob));
  text->SetTextFont(62);
  text->SetTextSize(0.07);
  // text->SetTextSize(0.06);
  pave->Draw();
  
  /* TLegend * ratioleg = new TLegend(0.72, 0.88, 0.94, 0.96); */
  /* set_style(ratioleg); */
  /* ratioleg->SetTextSize(0.07); */
  /* ratioleg->AddEntry(ratiostaterr, "MC uncert. (stat)", "f"); */
  /* ratioleg->Draw(); */

  pad1->cd();
  gPad->RedrawAxis();
  gPad->Modified();
  gPad->Update();
  pad2->cd();
  gPad->RedrawAxis();
  gPad->Modified();
  gPad->Update();

  c1->cd();
  
  c1->Print("Closure/plots/no_dp_cut/"+name+".pdf");

  delete staterr;
  delete ratio;
  delete ratiostaterr;
  delete ratiosysterr;
  delete leg2;
  // delete ratioleg;
  delete pad1;
  delete pad2;
  delete c1;
  delete latex;
  
}
void makeEfficiency_74X_setBr(bool isPrompt=false, bool isPair=true, bool isEmbedded=true, bool isPtCut = false, bool doWeight = false)
{
	gROOT->Macro("./JpsiStyle.C");
	gStyle->SetPaintTextFormat(".3f"); // for text colz
	
	//string strDir = "eff_74X_setBr"; // directory name
	//string strDir = "eff_74X_setBr_wDetached"; // directory name
	string strDir = "eff_74X_noRegitMuDetached"; // directory name

	int initev =0;
	int nevt = -1; //all
	//int nevt = 1000;

	int ptbin = 11.;
	double ptmin = 0.;
	double ptmax = 11.;
	if (isEmbedded && !isPrompt) { ptbin = 22.; ptmax = 22.; }
	int rapbin = 12;
	double rapmin = -2.4;
	double rapmax = 2.4;
	int lxybin = 10;
	double lxymin = 0.;
	double lxymax = 1.;

	string strPrompt;
	string strEmbd;
	string strPair;
	if(isPrompt){ strPrompt = "prompt"; }
	else { strPrompt = "nonprompt"; }
	if(isEmbedded){ strEmbd = "embd";	}
	else { strEmbd = "nonembd"; }
	if(isPair){ strPair = "Pair";	}
	else { strPair = "Trk"; }
	cout << "strPrompt = " << strPrompt.c_str() << endl;
	cout << "strEmbd = " << strEmbd.c_str() << endl;
	cout << "strPair = " << strPair.c_str() << endl;

	////// read-in file & tree
	TFile * refFile;
	if (isEmbedded){
		////// 740pre3 -embd
		//if (isPrompt){	refFile = new TFile("/home/songkyo/kyo/regitSample/tot_Pythiagun_PromptJpsi_step2nMatch_KYO_regit_embd_20150211.root");}
		//else { refFile = new TFile("/home/songkyo/kyo/regitSample/tot_Pythiagun_B2JpsiMuMu_step2nMatch_KYO_regit_embd_20150211.root");}
		////// 740pre3 -embd with HiDetachedTripletStep
		//if (isPrompt){	refFile = new TFile("/home/songkyo/kyo/regitSample/tot_Pythiagun_PromptJpsi_step2nMatch_KYO_regit_wDetached_embd_20150224.root");}
		//else { refFile = new TFile("/home/songkyo/kyo/regitSample/tot_Pythiagun_B2JpsiMuMu_step2nMatch_KYO_regit_wDetached_embd_20150224.root");}
		////// 740pre3 - remove some regit : noRegitMuDetached
		if (isPrompt){	refFile = new TFile("/home/songkyo/kyo/regitSample/tot_Pythiagun_PromptJpsi_step2nMatch_KYO_regit_noRegitMuDetached_embd_20150310.root");}
		else { refFile = new TFile("/home/songkyo/kyo/regitSample/tot_Pythiagun_B2JpsiMuMu_step2nMatch_KYO_regit_noRegitMuDetached_embd_20150310.root");}
	}
	else {
		//730pre2 -nonembd
		if (isPrompt){	refFile = new TFile("/home/songkyo/kyo/regitSample/tot_Pythiagun_PromptJpsi_step2nMatch_KYO_regit_20141121.root");}
		else { refFile = new TFile("/home/songkyo/kyo/regitSample/tot_Pythiagun_B2Jpsi_step2nMatch_KYO_regit_20141203_no9_32_90.root");}
	}
	
	TTree *tr = new TTree(); 
	if(isPair) { tr = (TTree*)refFile->Get("mcmatchanalysis/pnSimRecoPairType1");} 
	else { tr = (TTree*)refFile->Get("mcmatchanalysis/pnSimRecoTrkType1"); }

/*
	//for pT-|y| weight
	TFile *fWeight;
	if (isPrompt){ fWeight = new TFile("./pTdist_diffY/pTdist_diffY_prompt.root");}
	else {fWeight = new TFile("./pTdist_diffY/pTdist_diffY_nonprompt.root");}

	const int nYBin = 4;	
	TH1D* hWeight[nYBin];
	for (int i=0; i< nYBin; i++){
		if (isPair) { hWeight[i] = (TH1D*)fWeight->Get(Form("hPairRatio_%d",i)); }
		else { hWeight[i] = (TH1D*)fWeight->Get(Form("hTrkRatio_%d",i)); };
		//cout << i << "th hWeight = " << hWeight[i] << endl;
		cout << i << "th hWeight Name= " << hWeight[i]->GetName() << endl;
	}
*/

	///////////////////////////////////////
	////// Pair //////
	//gen
	Float_t			pt;	
	Float_t			y;	
	Float_t			pt1;	
	Float_t			eta1;	
	Float_t			npixelhits1;	
	Float_t			nmuonhits1;	
	Float_t			pt2;	
	Float_t			eta2;	
	Float_t			npixelhits2;	
	Float_t			nmuonhits2;	
	//reco
	Float_t			ptreco;	
	Float_t			yreco;	
	Float_t			minvreco;	
	Float_t			ptreco1;	
	Float_t			etareco1;	
	Float_t			nvalidpixelhitsreco1;	
	Float_t			nvalidmuonhitsreco1;	
	Float_t			nmatch1;	
	Float_t			chi2ndofreco1;	
	Float_t			ptreco2;	
	Float_t			etareco2;	
	Float_t			nvalidpixelhitsreco2;	
	Float_t			nvalidmuonhitsreco2;	
	Float_t			nmatch2;	
	Float_t			chi2ndofreco2;	
	// for lxy
	Float_t			vtxz1;
	Float_t			vtxy1;
	Float_t			bx;
	Float_t			by;
		
	////// Trk (additional)//////
	//gen
	Float_t			eta;	
	Float_t			idparent;	
	Float_t			npixelhits;	
	Float_t			nmuonhits;	
	//reco
	Float_t			etareco;	
	Float_t			nvalidpixelhitsreco;	
	Float_t			nvalidmuonhitsreco;	
	Float_t			nmatch;	
	Float_t			chi2ndofreco;	
	// for lxy
	Float_t			vtxz;
	Float_t			vtxy;

	///////////////////////////////////////
	//Branches
	///////////////////////////////////////
	
	TBranch			*b_pt;	
	TBranch			*b_y;	
	TBranch			*b_pt1;	
	TBranch			*b_eta1;	
	TBranch			*b_npixelhits1;	
	TBranch			*b_nmuonhits1;	
	TBranch			*b_pt2;	
	TBranch			*b_eta2;	
	TBranch			*b_npixelhits2;	
	TBranch			*b_nmuonhits2;	
	//reco
	TBranch			*b_ptreco;	
	TBranch			*b_yreco;	
	TBranch			*b_minvreco;	
	TBranch			*b_ptreco1;	
	TBranch			*b_etareco1;	
	TBranch			*b_nvalidpixelhitsreco1;	
	TBranch			*b_nvalidmuonhitsreco1;	
	TBranch			*b_nmatch1;	
	TBranch			*b_chi2ndofreco1;	
	TBranch			*b_ptreco2;	
	TBranch			*b_etareco2;	
	TBranch			*b_nvalidpixelhitsreco2;	
	TBranch			*b_nvalidmuonhitsreco2;	
	TBranch			*b_nmatch2;	
	TBranch			*b_chi2ndofreco2;	
	// for lxy
	TBranch			*b_vtxz1;
	TBranch			*b_vtxy1;
	TBranch			*b_bx;
	TBranch			*b_by;
		
	////// Trk (additional)//////
	//gen
	TBranch			*b_eta;	
	TBranch			*b_idparent;	
	TBranch			*b_npixelhits;	
	TBranch			*b_nmuonhits;	
	//reco
	TBranch			*b_etareco;	
	TBranch			*b_nvalidpixelhitsreco;	
	TBranch			*b_nvalidmuonhitsreco;	
	TBranch			*b_nmatch;	
	TBranch			*b_chi2ndofreco;	
	// for lxy
	TBranch			*b_vtxz;
	TBranch			*b_vtxy;

	///////////////////////////////////////
	//BranchAddress
	///////////////////////////////////////

	tr->SetBranchAddress("pt",&pt,&b_pt);
	tr->SetBranchAddress("ptreco",&ptreco,&b_ptreco);
	tr->SetBranchAddress("bx",&bx,&b_bx);
	tr->SetBranchAddress("by",&by,&b_by);
	if (isPair) {
		tr->SetBranchAddress("y",&y,&b_y);
		tr->SetBranchAddress("pt1",&pt1,&b_pt1);
		tr->SetBranchAddress("eta1",&eta1,&b_eta1);
		tr->SetBranchAddress("npixelhits1",&npixelhits1,&b_npixelhits1);
		tr->SetBranchAddress("nmuonhits1",&nmuonhits1,&b_nmuonhits1);
		tr->SetBranchAddress("pt2",&pt2,&b_pt2);
		tr->SetBranchAddress("eta2",&eta2,&b_eta2);
		tr->SetBranchAddress("npixelhits2",&npixelhits2,&b_npixelhits2);
		tr->SetBranchAddress("nmuonhits2",&nmuonhits2,&b_nmuonhits2);
		tr->SetBranchAddress("yreco",&yreco,&b_yreco);
		tr->SetBranchAddress("minvreco",&minvreco,&b_minvreco);
		tr->SetBranchAddress("ptreco1",&ptreco1,&b_ptreco1);
		tr->SetBranchAddress("etareco1",&etareco1,&b_etareco1);
		tr->SetBranchAddress("nvalidpixelhitsreco1",&nvalidpixelhitsreco1,&b_nvalidpixelhitsreco1);
		tr->SetBranchAddress("nvalidmuonhitsreco1",&nvalidmuonhitsreco1,&b_nvalidmuonhitsreco1);
		tr->SetBranchAddress("nmatch1",&nmatch1,&b_nmatch1);
		tr->SetBranchAddress("chi2ndofreco1",&chi2ndofreco1,&b_chi2ndofreco1);
		tr->SetBranchAddress("ptreco2",&ptreco2,&b_ptreco2);
		tr->SetBranchAddress("etareco2",&etareco2,&b_etareco2);
		tr->SetBranchAddress("nvalidpixelhitsreco2",&nvalidpixelhitsreco2,&b_nvalidpixelhitsreco2);
		tr->SetBranchAddress("nvalidmuonhitsreco2",&nvalidmuonhitsreco2,&b_nvalidmuonhitsreco2);
		tr->SetBranchAddress("nmatch2",&nmatch2,&b_nmatch2);
		tr->SetBranchAddress("chi2ndofreco2",&chi2ndofreco2,&b_chi2ndofreco2);
		tr->SetBranchAddress("vtxz1",&vtxz1,&b_vtxz1);
		tr->SetBranchAddress("vtxy1",&vtxy1,&b_vtxy1);
	}	
	else {
		tr->SetBranchAddress("eta",&eta,&b_eta);
		tr->SetBranchAddress("etareco",&etareco,&b_etareco);
		tr->SetBranchAddress("idparent",&idparent,&b_idparent);
		tr->SetBranchAddress("npixelhits",&npixelhits,&b_npixelhits);
		tr->SetBranchAddress("nmuonhits",&nmuonhits,&b_nmuonhits);
		tr->SetBranchAddress("nvalidpixelhitsreco",&nvalidpixelhitsreco,&b_nvalidpixelhitsreco);
		tr->SetBranchAddress("nvalidmuonhitsreco",&nvalidmuonhitsreco,&b_nvalidmuonhitsreco);
		tr->SetBranchAddress("nmatch",&nmatch,&b_nmatch);
		tr->SetBranchAddress("chi2ndofreco",&chi2ndofreco,&b_chi2ndofreco);
		tr->SetBranchAddress("vtxz",&vtxz,&b_vtxz);
		tr->SetBranchAddress("vtxy",&vtxy,&b_vtxy);
	}

	//2D hist. just check
	TH2D* hGenPtY = new TH2D("hGenPtY","hGenPtY",50,rapmin,rapmax,50,ptmin,ptmax);
	TH2D* hRecoPtY = new TH2D("hRecoPtY","hRecoPtY",50,rapmin,rapmax,50,ptmin,ptmax);
	TH2D* hEffPtY = new TH2D("hEffPtY","hEffPtY",50,rapmin,rapmax,50,ptmin,ptmax);
	
	TH1D* hGenPt = new TH1D("hGenPt","hGenPt",ptbin,ptmin,ptmax);
	TH1D* hRecoPt = new TH1D("hRecoPt","hRecoPt",ptbin,ptmin,ptmax);
	TH1D* hEffPt = new TH1D("hEffPt","hEffPt",ptbin,ptmin,ptmax);
	TH1D* hGenRap = new TH1D("hGenRap","hGenRap",rapbin,rapmin,rapmax);
	TH1D* hRecoRap = new TH1D("hRecoRap","hRecoRap",rapbin,rapmin,rapmax);
	TH1D* hEffRap = new TH1D("hEffRap","hEffRap",rapbin,rapmin,rapmax);
	TH1D* hGenLxy = new TH1D("hGenLxy","hGenLxy",lxybin,lxymin,lxymax);
	TH1D* hRecoLxy = new TH1D("hRecoLxy","hRecoLxy",lxybin,lxymin,lxymax);
	TH1D* hEffLxy = new TH1D("hEffLxy","hEffLxy",lxybin,lxymin,lxymax);

	hGenPtY->Sumw2();
	hRecoPtY->Sumw2();
	hEffPtY->Sumw2();
	hGenPt->Sumw2();
	hRecoPt->Sumw2();
	hEffPt->Sumw2();
	hGenRap->Sumw2();
	hRecoRap->Sumw2();
	hEffRap->Sumw2();
	hGenLxy->Sumw2();
	hRecoLxy->Sumw2();
	hEffLxy->Sumw2();

	//event loop start
	if(nevt == -1) nevt = tr->GetEntries();	
	for (int iev=initev; iev<nevt; iev++){
		tr->GetEntry(iev);	
		
		bool yngen = false;	
		bool ynreco = false;	
	  float weightF = 1.;
		float lxy = -531.;

		/// give a cut to Gen and Reco separately 
		if (isPair) {
			if (isPtCut) { if ( !(pt<15.) ) continue; }	
			/// define IP
			lxy = TMath::Sqrt((vtxz1-bx)*(vtxz1-bx)+(vtxy1-by)*(vtxy1-by));	
			
			if (kineCut(pt1,eta1) && kineCut(pt2,eta2) 
			&& idCut(npixelhits1,nmuonhits1) 
			&& idCut(npixelhits2,nmuonhits2) )
				{ yngen=true; }
			if (kineCut(ptreco1,etareco1) && kineCut(ptreco2,etareco2) 
			&& idCut(nvalidpixelhitsreco1,nvalidmuonhitsreco1)
			&& idCut(nvalidpixelhitsreco2,nvalidmuonhitsreco2)
			//&& idRecoCut(nmatch1, chi2ndofreco1)
			//&& idRecoCut(nmatch2, chi2ndofreco2)
			&& chi2ndofreco1 < 4.
			&& chi2ndofreco2 < 4.
			&& massCut(minvreco) ) 
				{ ynreco=true;}
		}
		else {
			if (isPtCut) { if (!(pt >1. && pt<15. ) ) continue; }	
			/// define IP
			lxy = TMath::Sqrt((vtxz-bx)*(vtxz-bx)+(vtxy-by)*(vtxy-by));	
			
			if ( (!isEmbedded)
		 	&& TMath::Abs(eta) < 2.4
			&& TMath::Abs(idparent)>442 
			&& TMath::Abs(idparent)<550 
			&& idCut(npixelhits,nmuonhits) )
				{ yngen=true; }
			else if ( isEmbedded
		 	&& TMath::Abs(eta) < 2.4
			//&& TMath::Abs(idparent)>442 
			//&& TMath::Abs(idparent)<550 
			&& idCut(npixelhits,nmuonhits) )
				{ yngen=true; }
			if ( (!isEmbedded) 
			//TMath::Abs(etareco) < 2.4
			&& TMath::Abs(eta) < 2.4
			&& TMath::Abs(idparent)>442 
			&& TMath::Abs(idparent)<550 
			&& idCut(nvalidpixelhitsreco,nvalidmuonhitsreco)
			&& idRecoCut(nmatch, chi2ndofreco) )
				{ ynreco=true;}
			else if ( isEmbedded 
			//TMath::Abs(etareco) < 2.4
			&& TMath::Abs(eta) < 2.4
			//&& TMath::Abs(idparent)>442 
			//&& TMath::Abs(idparent)<550 
			&& idCut(nvalidpixelhitsreco,nvalidmuonhitsreco)
			&& idRecoCut(nmatch, chi2ndofreco) )
				{ ynreco=true;}
		}

		/// weight if "doWeight" && fill the histogram
		if (isPair){
			if (doWeight) {weightF = getWeight(isPrompt, isPair, pt,y);}
//				cout << "weightF = " <<weightF << endl;
			if (yngen)	{
				hGenPtY->Fill(y,pt,weightF);
				hGenPt->Fill(pt,weightF);
				hGenRap->Fill(y,weightF); 
				hGenLxy->Fill(lxy,weightF); 
			}
			if (ynreco) {
				hRecoPtY->Fill(yreco,ptreco,weightF);
				hRecoPt->Fill(ptreco, weightF);
				hRecoRap->Fill(yreco, weightF); 
				hRecoLxy->Fill(lxy, weightF); 
			}
		}else { 
			if (doWeight) {weightF = getWeight(isPrompt, isPair, pt,eta);}
//				cout << "weightF = " <<weightF << endl;
			if (yngen)	{
				hGenPtY->Fill(eta,pt,weightF);
				hGenPt->Fill(pt,weightF);
				hGenRap->Fill(eta,weightF); 
				hGenLxy->Fill(lxy,weightF); 
			}
			if (ynreco) {
				hRecoPtY->Fill(etareco,ptreco,weightF);
				hRecoPt->Fill(ptreco,weightF);
				hRecoRap->Fill(etareco,weightF);
				hRecoLxy->Fill(lxy, weightF); 
			}
		}
	}// end of event loop

	cout << "hGenPt integral = " << hGenPt->Integral() << endl;
	cout << "hRecoPt integral = " << hRecoPt->Integral() << endl;
	cout << "hGenRap integral = " << hGenRap->Integral() << endl;
	cout << "hRecoRap integral = " << hRecoRap->Integral() << endl;
	cout << "hGenLxy integral = " << hGenLxy->Integral() << endl;
	cout << "hRecoLxy integral = " << hRecoLxy->Integral() << endl;

	//calculate efficiency
	hEffPtY->Divide(hRecoPtY,hGenPtY,1,1,"b");
	hEffPt->Divide(hRecoPt,hGenPt,1,1,"b");
	hEffRap->Divide(hRecoRap,hGenRap,1,1,"b");
	hEffLxy->Divide(hRecoLxy,hGenLxy,1,1,"b");

	//Legend
	TLegend *legUR = new TLegend(0.56,0.68,0.90,0.90,NULL,"brNDC");
	TLegend *legUL = new TLegend(0.17,0.68,0.51,0.90,NULL,"brNDC");
	TLegend *legBM = new TLegend(0.40,0.20,0.75,0.35,NULL,"brNDC");
	TLegend *legBR = new TLegend(0.56,0.20,0.90,0.42,NULL,"brNDC");
	SetLegendStyle(legUR);
	SetLegendStyle(legUL);
	SetLegendStyle(legBM);
	SetLegendStyle(legBR);

	TCanvas *c1 = new TCanvas("c1","c1",600,600); 
	
	//draw 2D Pt-y
	TPaletteAxis* pal; 
	hEffPtY->SetMinimum(0.0);
	hEffPtY->SetMaximum(1.0);
	if (isPair) hEffPtY->GetXaxis()->SetTitle("y");
	else hEffPtY->GetXaxis()->SetTitle("#eta");
	hEffPtY->GetXaxis()->CenterTitle();
	hEffPtY->GetYaxis()->SetTitle("p_{T} (GeV)");
	hEffPtY->Draw("colz");
	c1->Update();
	pal = (TPaletteAxis*)hEffPtY->GetListOfFunctions()->FindObject("palette"); 
	pal->SetX2NDC(0.92);
	c1->Modified();
	c1->Update();
	c1->SaveAs(Form("%s/EffPtY_isPtCut%d_doWeight%d_isEmbedded%d_%s_%s_%s.pdf",strDir.c_str(),(int)isPtCut,(int)doWeight,(int)isEmbedded,strPrompt.c_str(),strEmbd.c_str(),strPair.c_str()));
	c1->Clear();

	//draw EffPt
	SetHistStyle(hEffPt,3,0);
	hEffPt->SetMinimum(0.0);
	hEffPt->SetMaximum(1.0);
	if (isPair) hEffPt->GetXaxis()->SetTitle("Pair p_{T} (GeV)");
	else hEffPt->GetXaxis()->SetTitle("Trk p_{T} (GeV)");
	hEffPt->GetYaxis()->SetTitle("Efficiency");
	hEffPt->Draw("pe");
	c1->SaveAs(Form("%s/EffPt_isPtCut%d_doWeight%d_isEmbedded%d_%s_%s_%s.pdf",strDir.c_str(),(int)isPtCut,(int)doWeight,(int)isEmbedded,strPrompt.c_str(),strEmbd.c_str(),strPair.c_str()));
	c1->Clear();

	//draw EffRap
	SetHistStyle(hEffRap,3,0);
	hEffRap->SetMinimum(0.0);
	hEffRap->SetMaximum(1.0);
	if (isPair) hEffRap->GetXaxis()->SetTitle("y");
	else hEffRap->GetXaxis()->SetTitle("#eta");
	hEffRap->GetXaxis()->CenterTitle();
	hEffRap->GetYaxis()->SetTitle("Efficiency");
	hEffRap->Draw("pe");
	c1->SaveAs(Form("%s/EffRap_isPtCut%d_doWeight%d_isEmbedded%d_%s_%s_%s.pdf",strDir.c_str(),(int)isPtCut,(int)doWeight,(int)isEmbedded,strPrompt.c_str(),strEmbd.c_str(),strPair.c_str()));
	c1->Clear();

	//draw EffLxy
	SetHistStyle(hEffLxy,3,0);
	hEffLxy->SetMinimum(0.0);
	hEffLxy->SetMaximum(1.0);
	hEffLxy->GetXaxis()->SetTitle("Lxy");
	hEffLxy->GetYaxis()->SetTitle("Efficiency");
	hEffLxy->Draw("pe");
	c1->SaveAs(Form("%s/EffLxy_isPtCut%d_doWeight%d_isEmbedded%d_%s_%s_%s.pdf",strDir.c_str(),(int)isPtCut,(int)doWeight,(int)isEmbedded,strPrompt.c_str(),strEmbd.c_str(),strPair.c_str()));
	c1->Clear();

	//save as a root file
	TFile* outFile = new TFile(Form("%s/Eff_isPtCut%d_doWeight%d_isEmbedded%d_%s_%s_%s.root",strDir.c_str(),(int)isPtCut,(int)doWeight,(int)isEmbedded,strPrompt.c_str(),strEmbd.c_str(),strPair.c_str()),"RECREATE");	
	outFile->cd();
	hGenPtY->Write();
	hRecoPtY->Write();
	hEffPtY->Write();
	
	hGenPt->Write();
	hGenRap->Write();
	hGenLxy->Write();
	hRecoPt->Write();
	hRecoRap->Write();
	hRecoLxy->Write();
	hEffPt->Write();
	hEffRap->Write();
	hEffLxy->Write();
	outFile->Close();	
	
	return;

}
Plot_searchBin(string sample="TTbar_",string histname="searchH",int choice=1){

  ///////////////////////////////////////////////////////////////////////////////////////////
  ////Some cosmetic work for official documents.
  //
  // Set basic style
  //
  gROOT->LoadMacro("tdrstyle.C");
  setTDRStyle();
  gStyle->SetPalette(1) ; // for better color output
  gROOT->LoadMacro("CMS_lumi_v2.C");

  int W = 600;
  int H = 600;
  int H_ref = 600;
  int W_ref = 800;
  float T = 0.08*H_ref;
  float B = 0.12*H_ref;
  float L = 0.12*W_ref;
  float R = 0.08*W_ref;

  ///////////////////////////////////////////////////////////////////////////////////////////
  //
  // More specific style set, opening input files etc

  gStyle->SetOptStat(0);  ///to avoid the stat. on the plots
  char tempname[200];
  char xtitlename[200];
  char ytitlename[200];

  if(sample.find("stack")==string::npos)sprintf(tempname,"TauHad/GenInfo_HadTauEstimation_%s.root",sample.c_str());
  else sprintf(tempname,"TauHad/Stack/GenInfo_HadTauEstimation_%s.root",sample.c_str());
//cout << "warning:\n Warning \n \n  using elog195 for pre and  exp \n \n ";
  TFile * GenFile = new TFile(tempname,"R");
  if(sample.find("stack")==string::npos)sprintf(tempname,"TauHad2/HadTauEstimation_%s.root",sample.c_str());
  else sprintf(tempname,"TauHad2/Stack/HadTauEstimation_%s.root",sample.c_str());
  TFile * EstFile = new TFile(tempname,"R");

  //
  // Define legend
  //
  Float_t legendX1 = .55; //.50;
  Float_t legendX2 = .85; //.70;
  Float_t legendY1 = .75; //.65;
  Float_t legendY2 = .90;

  TLegend* catLeg1 = new TLegend(legendX1,legendY1,legendX2,legendY2);
  catLeg1->SetTextSize(0.032);
  catLeg1->SetTextFont(42);

  catLeg1->SetTextSize(0.042);
  catLeg1->SetTextFont(42);
  catLeg1->SetFillColor(0);
  catLeg1->SetLineColor(0);
  catLeg1->SetBorderSize(0);

  //
  // Define canvas
  //
  TCanvas *canvas = new TCanvas("canvas","canvas",10,10,W,H);

  canvas->SetFillColor(0);
  canvas->SetBorderMode(0);
  canvas->SetFrameFillStyle(0);
  canvas->SetFrameBorderMode(0);
  canvas->SetLeftMargin( L/W );
  canvas->SetRightMargin( R/W );
  canvas->SetRightMargin( 0.2 );
  canvas->SetTopMargin( T/H );
  canvas->SetBottomMargin( B/H );
  canvas->SetTickx(0);
  canvas->SetTicky(0);

  canvas->Divide(1, 2);

  //
  // Define pads
  //
  TPad* canvas_up = (TPad*) canvas->GetListOfPrimitives()->FindObject("canvas_1");
  TPad* canvas_dw = (TPad*) canvas->GetListOfPrimitives()->FindObject("canvas_2");
 
  // define the size
  double up_height     = 0.8;  // please tune so that the upper figures size will meet your requirement
  double dw_correction = 1.30; // please tune so that the smaller canvas size will work in your environment
  double font_size_dw  = 0.1;  // please tune the font size parameter for bottom figure
  double dw_height    = (1. - up_height) * dw_correction;
  double dw_height_offset = 0.040; // KH, added to put the bottom one closer to the top panel
 
  // set pad size
  canvas_up->SetPad(0., 1 - up_height, 0.97, 1.);
  canvas_dw->SetPad(0., dw_height_offset, 0.97, dw_height+dw_height_offset);
  canvas_up->SetFrameFillColor(0);
  canvas_up->SetFillColor(0);
  canvas_dw->SetFillColor(0);
  canvas_dw->SetFrameFillColor(0);
  canvas_dw->SetBottomMargin(0.25);
  
  // set top margin 0 for bottom figure
  canvas_dw->SetTopMargin(0);
  
  // draw top figure
  canvas_up->cd();

  TH1D * GenHist, * EstHist,* thist;
  TH1D * histTemplate;
  THStack * tempstack;

  double HT_x_max=2500.;
  double HT_x_min=400.;
  double MHT_x_max=1000.;
  double NJet_x_max=15.;
  double NBtag_x_max=4.;
  double search_x_max=19.;
  double search_x_min=1.;


  sprintf(tempname,"%s",histname.c_str());
  if(sample.find("stacked")!=string::npos){
    tempstack=(THStack*)EstFile->Get(tempname)->Clone();
    EstHist=(TH1D*) tempstack->GetStack()->Last();
    tempstack=(THStack*)GenFile->Get(tempname)->Clone();   
    GenHist=(TH1D*) tempstack->GetStack()->Last();
    tempstack=(THStack*)EstFile->Get(tempname)->Clone();
    EstHistD=(TH1D*) tempstack->GetStack()->Last();
    tempstack=(THStack*)GenFile->Get(tempname)->Clone();
    GenHistD=(TH1D*) tempstack->GetStack()->Last();
    
  }
  else{
    EstHist=(TH1D*) EstFile->Get(tempname)->Clone();
    GenHist=(TH1D*) GenFile->Get(tempname)->Clone();
    EstHistD=(TH1D*) EstFile->Get(tempname)->Clone();
    GenHistD=(TH1D*) GenFile->Get(tempname)->Clone();
  }

  GenHist->SetLineColor(2);
  EstHist->SetLineColor(4);
  //GenHist->GetXaxis()->SetLabelFont(42);
  //GenHist->GetXaxis()->SetLabelOffset(0.007);
  //GenHist->GetXaxis()->SetLabelSize(0.04);
  GenHist->GetXaxis()->SetTitleSize(0.05);
  GenHist->GetXaxis()->SetTitleOffset(0.9);
  GenHist->GetXaxis()->SetTitleFont(42);
  //GenHist->GetYaxis()->SetLabelFont(42);
  //GenHist->GetYaxis()->SetLabelOffset(0.007);
  //GenHist->GetYaxis()->SetLabelSize(0.04);
  GenHist->GetYaxis()->SetTitleSize(0.05);
  GenHist->GetYaxis()->SetTitleOffset(1.25);
  GenHist->GetYaxis()->SetTitleFont(42);

  //EstHist->GetXaxis()->SetLabelFont(42);
  //EstHist->GetXaxis()->SetLabelOffset(0.007);
  //EstHist->GetXaxis()->SetLabelSize(0.04);
  EstHist->GetXaxis()->SetTitleSize(0.05);
  EstHist->GetXaxis()->SetTitleOffset(0.9);
  EstHist->GetXaxis()->SetTitleFont(42);
  //EstHist->GetYaxis()->SetLabelFont(42);
  //EstHist->GetYaxis()->SetLabelOffset(0.007);
  //EstHist->GetYaxis()->SetLabelSize(0.04);
  EstHist->GetYaxis()->SetTitleSize(0.05);
  EstHist->GetYaxis()->SetTitleOffset(1.25);
  EstHist->GetYaxis()->SetTitleFont(42);
  sprintf(xtitlename,"search bins");
  sprintf(ytitlename,"Events");
  gPad->SetLogy();
  GenHist->SetMaximum(200000);
  GenHist->SetMinimum(0.1);
  GenHist->GetXaxis()->SetRangeUser(search_x_min,search_x_max);

  GenHist->SetFillStyle(3004);
  GenHist->SetFillColor(kGreen-3);
  GenHist->SetTitle("");
  GenHist->Draw("e2");
  //KH GenHist->Draw("same");
  EstHist->Draw("same");

  TH1D * GenHist_Clone = static_cast<TH1D*>(GenHist->Clone("denominator"));

  sprintf(tempname,"#tau_{hadronic} BG");
  catLeg1->AddEntry(GenHist,tempname,"l");
  sprintf(tempname,"Data driven prediction");
  catLeg1->AddEntry(EstHist,tempname,"l");
  GenHist->GetXaxis()->SetTitle(xtitlename);
  GenHist->GetYaxis()->SetTitle(ytitlename);
  catLeg1->Draw();

  TText * ttext = new TText(10. , 1700. , "4 fb-1");
  //  ttext->Draw();
  //
  // Bottom ratio plot
  //
  // ----------

  if(choice==0){
      //KH -- flip the numerator and denominator
      EstHistD->Divide(GenHistD);

      // draw bottom figure
      canvas_dw->cd();
      // font size
      EstHistD->GetXaxis()->SetLabelSize(font_size_dw);
      EstHistD->GetXaxis()->SetTitleSize(font_size_dw);
      EstHistD->GetYaxis()->SetLabelSize(font_size_dw);
      EstHistD->GetYaxis()->SetTitleSize(font_size_dw);
      
      //
      // Common to all bottom plots
      //
      sprintf(ytitlename,"Estimate / #tau_{had} BG");
      EstHistD->SetMaximum(2.65);
      EstHistD->SetMinimum(0.0);

      //
      // Specific to each bottom plot
      //
      sprintf(xtitlename,"search bin");
      EstHistD->GetXaxis()->SetRangeUser(search_x_min,search_x_max);
      TLine *tline = new TLine(search_x_min,1.,search_x_max,1.);

      // Setting style
      //EstHistD->SetMaximum(1.4);
      //EstHistD->GetXaxis()->SetLabelFont(42);
      //EstHistD->GetXaxis()->SetLabelOffset(0.007);
      //EstHistD->GetXaxis()->SetLabelSize(0.04);
      EstHistD->GetXaxis()->SetTitleSize(0.12);
      EstHistD->GetXaxis()->SetTitleOffset(0.9);
      EstHistD->GetXaxis()->SetTitleFont(42);
      //EstHistD->GetYaxis()->SetLabelFont(42);
      //EstHistD->GetYaxis()->SetLabelOffset(0.007);
      //EstHistD->GetYaxis()->SetLabelSize(0.04);
      EstHistD->GetYaxis()->SetTitleSize(0.13);
      EstHistD->GetYaxis()->SetTitleOffset(0.5);
      EstHistD->GetYaxis()->SetTitleFont(42);

      EstHistD->GetXaxis()->SetTitle(xtitlename);
      EstHistD->GetYaxis()->SetTitle(ytitlename);

      EstHistD->SetTitle("");
      EstHistD->Draw();
      tline->SetLineStyle(2);
      tline->Draw();
  }

  if(choice==1){

    /*
      TH1D * denominator = static_cast<TH1D*>(EstHist->Clone("denominator"));
      EstHistD->Add(GenHistD,-1);
      denominator->Divide(EstHistD,GenHistD,1,1,"");
    */
      TH1D * denominator = static_cast<TH1D*>(EstHist->Clone("denominator"));
      //EstHistD->Add(GenHistD,-1);
      denominator->Divide(GenHistD,EstHistD,1,1,"");

      // draw bottom figure
      canvas_dw->cd();
      // font size
      denominator->GetXaxis()->SetLabelSize(font_size_dw);
      denominator->GetXaxis()->SetTitleSize(font_size_dw);
      denominator->GetYaxis()->SetLabelSize(font_size_dw);
      denominator->GetYaxis()->SetTitleSize(font_size_dw);
      
      TLine *tline = new TLine(search_x_min,1.,search_x_max,1.);

      //
      // Common to all bottom plots
      //
      //sprintf(ytitlename,"#frac{Estimate - #tau_{had} BG}{#tau_{had} BG} ");
      sprintf(ytitlename,"#frac{Expectation}{Prediction} ");
      denominator->SetMaximum(2.65);
      denominator->SetMinimum(0.0);

      //
      // Specific to each bottom plot
      //
      // Setting style
      //denominator->SetMaximum(1.4);
      //denominator->GetXaxis()->SetLabelFont(42);
      //denominator->GetXaxis()->SetLabelOffset(0.007);
      //denominator->GetXaxis()->SetLabelSize(0.04);
      denominator->GetXaxis()->SetTitleSize(0.12);
      denominator->GetXaxis()->SetTitleOffset(0.9);
      denominator->GetXaxis()->SetTitleFont(42);
      //denominator->GetYaxis()->SetLabelFont(42);
      //denominator->GetYaxis()->SetLabelOffset(0.007);
      //denominator->GetYaxis()->SetLabelSize(0.04);
      denominator->GetYaxis()->SetTitleSize(0.13);
      denominator->GetYaxis()->SetTitleOffset(0.5);
      denominator->GetYaxis()->SetTitleFont(42);

      denominator->GetXaxis()->SetTitle(xtitlename);
      denominator->GetYaxis()->SetTitle(ytitlename);

      denominator->SetTitle("");
      denominator->Draw();
      tline->SetLineStyle(2);
      tline->Draw();
  }

  sprintf(tempname,"%s_%s_SearchBin_Plot.png",sample.c_str(),histname.c_str());
  canvas->Print(tempname);

}
Exemple #19
0
void Draw3paneleff() {
    gStyle->SetOptStat(kFALSE);
    TString outG="G1.root";
    TCanvas *c1  = new TCanvas("","",1000,400);
    c1->Divide(3);
    gStyle->SetErrorX(0);
    double hfbin[]= {0,1,2,3,4,6,8,10,13,16,20,25,30,40,55,70,90};
    int nhfbin = 16;
    TString name, dirname;
    TFile *fDSeff = TFile::Open("/scratch/xuq7/Centrality/pPbHijing_EffCorr_forNBD.root");
    TFile *ftreff = TFile::Open("/scratch/xuq7/Centrality/pPbHist_Hijing_TrandEs.root");
    TH1D* hbef = (TH1D*)ftreff->Get("hHFEnergy4");
    TH1D* rehbef = (TH1D*)hbef->Rebin(nhfbin,"rehHFEnergy4",hfbin);
    TH1D* haft = (TH1D*)ftreff->Get("hHFEnergy4_tr");
    TH1D* rehaft = (TH1D*)haft->Rebin(nhfbin,"rehHFEnergy4_tr",hfbin);
    TGraphAsymmErrors *gtreff = new TGraphAsymmErrors();
    gtreff->BayesDivide(rehaft,rehbef);

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

    geff->SetTitle("");
    geff->SetMarkerStyle(33);
    geff->SetMarkerColor(5);
    geff->SetMarkerSize(1.3);

    gtreff->SetTitle("");
    gtreff->SetMarkerStyle(21);
    gtreff->SetMarkerColor(6);
    gtreff->SetMarkerSize(1.3);

    for(int cenvar=0; cenvar<3; cenvar++) {
        TFile *f = TFile::Open(Form("%s/%s",cenvardir[cenvar].Data(),outG.Data()));
        c1->cd(cenvar+1);
        TObjString* dataname = (TObjString*)f->Get(Form("dataname"));
        TObjString* histoname = (TObjString*)f->Get(Form("histoname"));
        TFile *fdata = TFile::Open(dataname->GetString());
        TH1D *histo_obs = (TH1D*)fdata->Get(histoname->GetString());
        histo_obs->Sumw2();
        TH1D* hFrame = histo_obs->Clone();
        hFrame->Reset();
        hFrame->SetTitle("");
        hFrame->SetMaximum(1.2);
        hFrame->SetMinimum(0);
        if(cenvar==0)hFrame->GetYaxis()->SetTitle("ratio");
        else hFrame->GetYaxis()->SetTitle("");
        hFrame->GetXaxis()->SetRangeUser(0,100);
        hFrame->GetXaxis()->CenterTitle(0);
        hFrame->GetYaxis()->CenterTitle(1);
        hFrame->GetYaxis()->SetTitleOffset(1.1);
        hFrame->GetXaxis()->SetTitleOffset(1.1);
        hFrame->GetXaxis()->SetTitleSize(0.056);
        hFrame->GetYaxis()->SetTitleSize(0.056);
        hFrame->GetXaxis()->SetLabelSize(0.05);
        hFrame->GetYaxis()->SetLabelSize(0.05);

        int binnum = histo_obs->GetNbinsX();
        double Minx = histo_obs->GetXaxis()->GetXmin();
        double Maxx = histo_obs->GetXaxis()->GetXmax();
        double binsize = (Double_t)(Maxx-Minx)/binnum;
        hFrame->Draw();
        TLegend *leg = new TLegend(0.40, 0.2, 0.65, 0.4);

        for(int sth=0; sth<3; sth++) {
            int Gth=0;
            if(sth==0) {
                dirname = "std";
            }
            else if(sth==1) {
                dirname ="Gri055";
            }
            else {
                dirname ="Gri101";
            }
            hFrame->GetXaxis()->SetTitle(cenvariable[cenvar]);

            if(Gth==0)
                name = "G0";
            else if(Gth<nGlau)
                name = Form("Glau_%d",Gth);
            else
                name = Form("bin_%d",Gth-nGlau+1);
            TObjString* Glaubername = (TObjString*)f->Get(Form("%s/%s/Glaubername",dirname.Data(),name.Data()));
            TVectorD* xmin = (TVectorD*)f->Get(Form("%s/%s/xmin",dirname.Data(),name.Data()));
            TVectorD* xmax = (TVectorD*)f->Get(Form("%s/%s/xmax",dirname.Data(),name.Data()));
            TVectorD* mubest = (TVectorD*)f->Get(Form("%s/%s/mubest",dirname.Data(),name.Data()));
            TVectorD* kbest = (TVectorD*)f->Get(Form("%s/%s/kbest",dirname.Data(),name.Data()));
            TVectorD* Ndf = (TVectorD*)f->Get(Form("%s/%s/Ndf",dirname.Data(),name.Data()));
            TVectorD* chis = (TVectorD*)f->Get(Form("%s/%s/chis",dirname.Data(),name.Data()));
            TVectorD *kpoint = (TVectorD*)f->Get(Form("%s/%s/kpoint",dirname.Data(),name.Data()));
            int xbinmin=(int)(((*xmin)[0]-Minx)/binsize);
            int xbinmax=(int)(((*xmax)[0]-Minx)/binsize);
            TFile *fGlauber = TFile::Open(Glaubername->GetString());
            TH1D *histo_exp = new TH1D("histo_exp","Simulated distribution;Multiplicity;Event Fraction",binnum,Minx,Maxx);
            histo_exp->Sumw2();
            Int_t ibin;

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

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

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

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

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

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


            rehisto_obs_norm = (TH1D*)histo_obs_norm->Rebin(nhfbin,"rehisto_obs_norm",hfbin);
            normalizeByBinWidth(rehisto_obs_norm);
            rehisto_exp_norm = (TH1D*)histo_exp_norm->Rebin(nhfbin,"rehisto_exp_norm",hfbin);
            normalizeByBinWidth(rehisto_exp_norm);
            TH1D* ratio = (TH1D*)rehisto_obs_norm->Clone("ratio");
            ratio->Divide(rehisto_exp_norm);

            ratio->SetTitle("");
            ratio->SetLineColor(1);
            ratio->SetMarkerStyle(20);
            ratio->SetMarkerColor(color_[sth]);
            ratio->SetMarkerSize(1.3);
            ratio->Draw("Psame");
            geff->Draw("Psame");
            gtreff->Draw("Psame");
            leg->AddEntry(ratio,Form("data/fit %s",Grilist[sth].Data()),"p");
        }

        leg->SetFillColor(10);
        leg->SetFillStyle(0);
        leg->SetBorderSize(0.035);
        leg->SetTextFont(42);
        leg->SetTextSize(0.045);
        leg->AddEntry(geff,"DS efficiency","p");
        leg->AddEntry(gtreff,"Event selection efficiency","p");
        if(cenvar==2) leg->Draw("same");

        TLine *l = new TLine(0,1,90,1);
        l->SetLineStyle(2);
        l->Draw("same");
    }
    c1->SaveAs(Form("ratiovseff.png"));
    c1->SaveAs(Form("ratiovseff.pdf"));
}
Exemple #20
0
// -----------------------------------------------------------------------------
//
TCanvas* createPlot( TString path, 
		     TString canvas_name, 
		     TString name, 
		     TString dirmame, 
		     int rebin, 
		     bool norm, 
		     bool log,
		     TDirectory* file )
{

  // SetSomeStyles();

  float lumi = 250.0;// 15.04;//10.9;//6.8;
 
  // Create legend
  TLegend* legend = new TLegend(0.75, 0.6, 0.99, 0.99, "", "brNDC" );
  legend->SetFillColor(0);
  legend->SetLineColor(0); 
  legend->SetShadowColor(0);
  TLatex* prelim = new TLatex(0.6,0.54,"#scale[0.8]{CMS preliminary 2010}");
  prelim->SetNDC();
  TLatex* alumi = new TLatex(0.6,.45,"#scale[0.8]{#int L dt = 35 pb^{-1}, #sqrt{s} = 7 TeV}");
  alumi->SetNDC();

  // Create canvas 
  TCanvas* aCanvas = createCanvas( canvas_name, file, log );

  // Create histogram
  TString aname("nAll");
  // TH1D* data1    = getHisto( path+"S14datacleaned/Edward_Data_Skim/",name,"data.root",aname,rebin);
  // TH1D* data    = getHisto( path+"S14datacleaned/Edward_Data_Skim/",name,"data.root",dirmame,rebin);
 
  TH1D* data    = getHisto( path+"", name, "tt.root", dirmame, rebin );
  TH1D* qcd     = getHisto( path+"", name, "lm1.root", dirmame, rebin );
  TH1D* w_jets  = getHisto( path+"", name, "w.root", dirmame, rebin );
  TH1D* tt_jets = getHisto( path+"", name, "tt.root", dirmame, rebin );
  TH1D* z_jets  = getHisto( path+"", name, "z.root", dirmame, rebin );
  TH1D* lm3     = getHisto( path+"", name, "lm3.root", dirmame, rebin );
  TH1D* lm1     = getHisto( path+"", name, "lm1.root", dirmame, rebin );
  TH1D* lm6     = getHisto( path+"", name, "data.root", dirmame, rebin );
  TH1D* wm     = getHisto( path+"", name, "w.root", dirmame, rebin );
  data->Scale(lumi/100.);
  qcd->Scale(lumi/100.);
  tt_jets->Scale(lumi/100);
  w_jets->Scale(lumi/100);
  //  w_jets->Scale(10);
  //  z_inv->Scale(lumi/100);
  //  lm6->Scale(lumi/100);
  lm1->Scale(lumi/100);
  lm3->Scale(lumi/100);
  z_jets->Scale(lumi/100);
  wm->Scale(lumi/100);
  // Combine Z+jets and Z->inv
  // TH1D* z_all = z_inv->Clone(); 
  //  z_all->Add(z_jets,1);
  //z_jets->Add(z_inv,1);
  TH1D* total = tt_jets->Clone();
  total->Add(w_jets);
  total->Add(z_jets);

  // total->
 
  Int_t binMax =   total->GetNbinsX();
  Double_t& err = new Double_t(0.);
  total->IntegralAndError(10,binMax ,err);
  Double_t& errW = new Double_t(0.);
  w_jets->IntegralAndError(10,binMax ,errW);
  Double_t& errtt = new Double_t(0.);
  tt_jets->IntegralAndError(10,binMax ,errtt);
  Double_t& errZ = new Double_t(0.);
  z_jets->IntegralAndError(10,binMax ,errZ);
  Double_t& errQCD = new Double_t(0.);
  qcd->IntegralAndError(10,binMax ,errQCD );


  cout  <<endl;
  //  cout << "MC:" <<  total->IntegralAndError(11,binMax ,err) <<" && " <<  w_jets->Integral(11,binMax)<<" && "<<tt_jets->Integral(11,binMax) << "&&  "<<z_jets->Integral(11,binMax)<<" && "<< "\/\ /\hline"<<endl;
  //  cout << total->IntegralAndError(0,binMax ,err) <<" & " << lm1->Integral(0,binMax) <<" & " << lm3->Integral(0,binMax)<<" & " << lm6->Integral(0,binMax)   <<"\\\\ \\hline"<<endl;
  //  cout <<"270: " <<  total->IntegralAndError(27,binMax ,err) <<" & " << lm1->Integral(27,binMax) <<" & " << lm3->Integral(27,binMax)<<" & " << lm6->Integral(27,binMax)   <<"\\\\ \\hline"<<endl;


  cout <<"250& " <<  total->IntegralAndError(6,binMax ,err) <<" & " << lm1->Integral(6,binMax) <<" & " << lm3->Integral(6,binMax)<<" & " << lm6->Integral(6,binMax)   <<"\\\\ \\hline"<<endl;
 
  // cout << "300: " <<  total->IntegralAndError(7,binMax ,err) <<" & " << lm1->Integral(7,binMax) <<" & " << lm3->Integral(7,binMax)<<" &" << lm6->Integral(7,binMax)   <<"\\\\ \\hline"<<endl;

  cout <<"350& " <<  total->IntegralAndError(8,binMax ,err) <<" & " << lm1->Integral(8,binMax) <<" & " << lm3->Integral(8,binMax)<<" & " << lm6->Integral(8,binMax)    <<"\\\\ \\hline"<<endl;

  //   cout << "400: " <<  total->IntegralAndError(9,binMax ,err) <<" & " << lm1->Integral(9,binMax) <<" & " << lm3->Integral(9,binMax)<<" & " << lm6->Integral(9,binMax)    <<"\\\\ \\hline"<<endl;

cout << "450& " <<  total->IntegralAndError(10,binMax ,err) <<" & " << lm1->Integral(10,binMax) <<" & " << lm3->Integral(10,binMax)<<" & " << lm6->Integral(10,binMax)    <<"\\\\ \\hline"<<endl;

//cout << "500: " <<   total->IntegralAndError(11,binMax ,err) <<" & " << lm1->Integral(11,binMax) <<" & " << lm3->Integral(11,binMax)<<" & " << lm6->Integral(11,binMax)    <<"\\\\ \\hline"<<endl;

  cout <<"550& " <<  total->IntegralAndError(12,binMax ,err) <<" & " << lm1->Integral(12,binMax) <<" & " << lm3->Integral(12,binMax)<<" & " << lm6->Integral(12,binMax)    <<"\\\\ \\hline"<<endl;
  /*
 cout << "MC:" <<  total->IntegralAndError(7,binMax ,err) <<" && " << lm1->Integral(7,binMax) <<" && " << lm3->Integral(7,binMax)<<" && " << lm6->Integral(6,binMax)   <<"/\/\ /\hline"<<endl;
  cout << "MC:" <<  total->IntegralAndError(8,binMax ,err) <<" && " << lm1->Integral(8,binMax) <<" && " << lm3->Integral(8,binMax)<<" && " << lm6->Integral(7,binMax)   <<"/\/\ /\hline"<<endl;
  cout << "MC:" <<  total->IntegralAndError(10,binMax ,err) <<" && " << lm1->Integral(10,binMax) <<" && " << lm3->Integral(10,binMax)<<" && " << lm6->Integral(10,binMax)   <<"/\/\ /\hline"<<endl;
 cout << "MC:" <<  total->IntegralAndError(11,binMax ,err) <<" && " << lm1->Integral(11,binMax) <<" && " << lm3->Integral(11,binMax)<<" && " << lm6->Integral(11,binMax)   <<"/\/\ /\hline"<<endl;
 cout << "MC:" <<  total->IntegralAndError(12,binMax ,err) <<" && " << lm1->Integral(12,binMax) <<" && " << lm3->Integral(12,binMax)<<" && " << lm6->Integral(12,binMax)   <<"/\/\ /\hline"<<endl;
  // cout << "MC:" << err  <<", W: " << errW<<", tt: "<<errtt << ", Z: "<<errZ<<", QCD: "<<  errQCD<< endl;
  */

  //  cout << "data:" << data->Integral() << endl;


  TH1D* hcen = total->Clone();
  TH1D* herr = total->Clone();
  
  herr->SetLineColor(kTeal+3);
  herr->SetMarkerColor(kAzure+6);
  herr->SetFillColor(kAzure+6);
  herr->SetLineWidth(3);
  
  total->SetLineWidth(3);
  total->SetFillColor(kAzure+2);
  total->SetLineColor(kAzure+2);
  total->SetFillStyle(3245);
 
  hcen->SetFillStyle(0);
  hcen->SetMarkerColor(kTeal+3);
  hcen->SetLineColor(kTeal+3);
  hcen->SetLineWidth(3);

  // Merge Z+jets and Z->inv
  bool combine = false;
  
  // Line colour and fill
  qcd->SetLineColor(kPink+4);
  qcd->SetLineWidth(3);
  tt_jets->SetLineColor(kBlue+1);
  tt_jets->SetLineWidth(3);
  
  w_jets->SetLineColor(kPink+7);
  w_jets->SetLineWidth(3);

  z_jets->SetLineWidth(3);
  z_jets->SetLineColor(kTeal-7);
  
  if ( combine ) {
    z_all->SetLineColor(kBlack);
    z_all->SetLineStyle(3);
    z_all->SetLineWidth(1);
  } else {
    data->SetLineColor(1);
    data->SetLineStyle(1);
    data->SetLineWidth(3);
    data->SetMarkerStyle(20);
    data->SetFillColor(0);
  }
  //  lm0->SetLineColor(kRed);
  //  lm0->SetLineWidth(3);
  // lm1->SetLineColor(kRed+3);
  // lm1->SetLineWidth(3);

  // Populate legend
  // legend->AddEntry( data, "tt fully leptonic/", "LP" );
   legend->AddEntry( herr, "full SM", "LP" );
    legend->AddEntry( z_jets, " Z+jets ", "LP" );
    legend->AddEntry( w_jets, " W+jets", "LP" );
    legend->AddEntry( tt_jets, " t#bar{t}", "LP" );
    //  legend->AddEntry( lm3, " SUSY LM3", "LP" );
    //   legend->AddEntry( lm1, " SUSY LM1", "LP" );
    legend->AddEntry( lm6, " data", "LP" );
    // legend->AddEntry(wm,"W Mad","lp");
    
  // Calc maximum number of entries
  double aMax = 0.;
  if( data->GetMaximum()     > aMax ) { aMax = data->GetMaximum()+data->GetBinError(data->GetMaximumBin()); }
  if ( qcd->GetMaximum()     > aMax ) { aMax = qcd->GetMaximum(); }
  //  if ( lm0->GetMaximum()     > aMax ) { aMax = lm0->GetMaximum(); }
  //  if ( lm1->GetMaximum()     > aMax ) { aMax = lm1->GetMaximum(); }
  if ( tt_jets->GetMaximum() > aMax ) { aMax = tt_jets->GetMaximum(); }  
  if ( w_jets->GetMaximum()  > aMax ) { aMax = w_jets->GetMaximum(); }  
  if ( combine ) {
    if ( z_all->GetMaximum()  > aMax ) { aMax = z_all->GetMaximum(); }  
  } else {
    //   if ( data->GetMaximum()   > aMax ) { aMax = z_inv->GetMaximum(); }  
    if ( z_jets->GetMaximum()  > aMax ) { aMax = z_jets->GetMaximum(); }  
  }

  // Calc minimum number of entries
  double aMin = 1.e12;
  if ( qcd->GetMinimum(1.e-12)     < aMin ) { aMin = qcd->GetMinimum(1.e-12); }
  //  if ( lm0->GetMinimum(1.e-12)     < aMin ) { aMin = lm0->GetMinimum(1.e-12); }
  //  if ( lm1->GetMinimum(1.e-12)     < aMin ) { aMin = lm1->GetMinimum(1.e-12); }
  if ( tt_jets->GetMinimum(1.e-12) < aMin ) { aMin = tt_jets->GetMinimum(1.e-12); }  
  if ( w_jets->GetMinimum(1.e-12)  < aMin ) { aMin = w_jets->GetMinimum(1.e-12); }  
  if ( combine ) {
    if ( z_all->GetMinimum(1.e-12)   < aMin ) { aMin = z_all->GetMinimum(1.e-12); }  
  } else {
    // if ( data->GetMinimum(1.e-12)   < aMin ) { aMin = z_inv->GetMinimum(1.e-12); }  
    if ( z_jets->GetMinimum(1.e-12)  < aMin ) { aMin = z_jets->GetMinimum(1.e-12); }  
  }

  if ( qcd ) qcd->GetYaxis()->SetTitleOffset(1.43);
  if ( qcd ) qcd->GetYaxis()->SetTitleSize(0.06);
  if ( qcd ) qcd->GetXaxis()->SetTitleSize(0.06);
  if ( qcd ) qcd->GetXaxis()->SetTitleOffset(0.9);

 
  if ( log ) {
    if ( qcd ) herr->SetMaximum( aMax * 10. );
    //   if ( qcd ) herr->SetMinimum( aMin * 0.1 );
    if ( qcd ) herr->SetMinimum( 0.005);
  } else {
    if ( qcd ) herr->SetMaximum( aMax * 1.1 );
    //   if ( qcd ) herr->SetMinimum( aMin * 0.9 );
  if ( qcd ) herr->SetMinimum( 0.005);

  }

  /*  TPad* mainPad = new TPad("","",0.01,0.25,0.99,0.99);
  mainPad->SetNumber(1);
  mainPad->SetFillColor(0);
  // mainPad->Range(-288.2483,-2.138147,1344.235,6.918939);
  mainPad->SetFillColor(0);
  mainPad->SetBorderMode(0);
  mainPad->SetBorderSize(2);
  if ( log == true)mainPad->SetLogy();
   mainPad->SetLeftMargin(0.1765705);
  mainPad->SetRightMargin(0.05772496);
  mainPad->SetTopMargin(0.04778761);
  mainPad->SetBottomMargin(0.1256637);
  mainPad->SetFrameFillStyle(0);
  mainPad->SetFrameLineWidth(2);
  mainPad->SetFrameBorderMode(0);
  mainPad->SetFrameFillStyle(0);
  mainPad->SetFrameLineWidth(2);
  mainPad->SetFrameBorderMode(0);
  if ( log == true)mainPad->SetLogy();
  mainPad->Draw();
  TPad*  ratioPad = new TPad("","",0.01,0.01,0.99,0.25);
  ratioPad->SetNumber(2);
  ratioPad->SetFillColor(0);
  ratioPad->SetFillColor(0);
  ratioPad->SetBorderMode(0);
  ratioPad->SetBorderSize(2);
  // if ( log == true)ratioPad->SetLogy();
   ratioPad->SetLeftMargin(0.1765705);
  ratioPad->SetRightMargin(0.05772496);
  ratioPad->SetTopMargin(0.04778761);
  ratioPad->SetBottomMargin(0.1256637);
  ratioPad->SetFrameFillStyle(0);
  ratioPad->SetFrameLineWidth(2);
  ratioPad->SetFrameBorderMode(0);
  ratioPad->SetFrameFillStyle(0);
  ratioPad->SetFrameLineWidth(2);
  ratioPad->SetFrameBorderMode(0);
  //  if ( log == true)ratioPad->SetLogy();
  ratioPad->Draw();
 

  aCanvas->cd(1);
  */

  herr->GetYaxis()->SetTitle("events");


  if ( norm ) {
    if ( qcd ) qcd->DrawNormalized("Ehist");
    // if ( lm0->GetEntries() > 0. )     { lm0->DrawNormalized("hsame"); }
    if ( lm1->GetEntries() > 0. )     { lm1->DrawNormalized("hsame"); }
    if ( tt_jets->GetEntries() > 0. ) { tt_jets->DrawNormalized("hsame"); }
    if ( w_jets->GetEntries() > 0. )  { w_jets->DrawNormalized("hsame"); }
    if ( combine ) {
      if ( z_all->GetEntries() > 0. )   { z_all->DrawNormalized("hsame"); }
    } else {
      if ( data->GetEntries() > 0. )   { z_inv->DrawNormalized("hsame"); }
      if ( z_jets->GetEntries() > 0. )  { z_jets->DrawNormalized("hsame"); }
    }
  } else {
     herr->Draw("hist");
   
   
     // qcd->SetFillStyle(3240);
     // qcd->SetFillColor(kPink+4);
    // qcd->Draw("hist");
    w_jets->Draw("hSameh");
    z_jets->Draw("9Sameh");
    w_jets->Draw("9Sameh");
    tt_jets->Draw("9SAMEh");
    //data1->Draw("9SAMEh");
     //lm0->Draw("9SAMEh");
     lm1->SetLineColor(12);
     lm1->SetLineStyle(2);
     lm1->SetLineWidth(2);
     //     lm1->Draw("9SAMEh");
     lm3->SetLineColor(14);
     lm3->SetLineStyle(2);
     lm3->SetLineWidth(2);
     //  lm3->Draw("9SAMEh");
     lm6->Draw("9SAMEh");
     wm->SetLineStyle(2);
     wm->SetLineColor(kPink+7);
     // wm->Draw("9Sameh");

     // total->DrawNormalized("9E2same");
     //      data->Draw("SAMEh");
    //  tt_jets->Divide(data);
    //  tt_jets->Draw("h");
  //  data->SetLineColor(kRed);
  //  data->Draw("sameh");
     //     data1->SetLineColor(kRed);
     //  data1->Draw("9SAMEP");
  }
  
    legend->Draw();
  // prelim->Draw();
  // alumi->Draw();



  /*  TH1D* ratioBottom = total->Clone();
  TH1D* ratioTop = data->Clone();
  ratioTop->GetYaxis()->SetTitle("data / sim");
  ratioTop->Divide(ratioBottom);
  
  aCanvas->cd(1)->Update();
 
  aCanvas->cd(2);

  ratioTop->SetTitleSize(0.1, "XYZ");
  ratioTop->SetTitleOffset(0.55, "X");
  ratioTop->SetTitleOffset(0.3, "Y");
  ratioTop->SetLabelSize(0.06,"XY");
    
  // ratioTop->GetXaxis().SetRangeUser(MinX,MaxX);
  ratioTop->GetYaxis()->SetRangeUser(0.,2.0);
  ratioTop->Draw();*/
  /* TBox* unity = TBox(ratioTop->GetXaxis()->GetBinLowEdge(ratioTop->GetXaxis()->GetFirst()), 0.89,ratioTop->GetXaxis()->GetBinLowEdge(ratioTop->GetXaxis()->GetLast()), 1.11);
  unity->SetLineWidth(2);
   
  unity->SetLineColor(2);
  unity->SetFillColor(2);
  unity->SetFillStyle(3002);
  unity->Draw();

  */
  file->cd();
 
  aCanvas->SaveAs( std::string(canvas_name+".pdf").c_str() );
  aCanvas->Write();



  //   aCanvas->Print(".png");
 return aCanvas;

}
void AnalyzeBKGShape(TString folder, TString sample1, TString sample2){
	gStyle->SetOptStat(000000);
	
	TH1::SetDefaultSumw2();
	
	TFile *f= TFile::Open("/Users/Tita/Desktop/analysis_HH_bbTauTau/src/HHbbTauTau/data/datacards_TauTau_ZTT/htt_tt.inputs-Hhh-8TeV_m_ttbb_kinfit_KinFitConvergedWithMassWindow.root");
	

	
	TH1D *histoDY = (TH1D*)f->Get((folder+"/"+sample1));
	TH1D *histoTT = (TH1D*)f->Get((folder+"/"+sample2));
	
		
	TCanvas * c1 = new TCanvas("c1","c1", 800,800);

	histoDY->SetLineColor(kBlue);
	histoDY->SetMarkerColor(kBlue);
	histoDY->SetMarkerStyle(20);
	

	histoTT->SetLineColor(kRed);
	histoTT->SetMarkerColor(kRed);
	histoTT->SetMarkerStyle(20);

	
	
	
	
    // double error_histo = 0;
//     double integral_histo = histo->IntegralAndError(1, histo->GetNbinsX(),error_histo);
//     cout<<"--------------------------------------------------------------"<<sample<<"--------------------------------------------------------------"<<endl;
//     cout<<"*************"<<folder<<"  "<<sample<<"*************"<<endl;
//     cout<<" MC Shape "<<integral_histo<<"   ----  "<<error_histo<<endl;
//     cout<<" MC Shape Loose B "<<histoBLoose->Integral()<<endl;
//     cout<<" MC Shape Loose B + Relax Tau Iso "<<histoBLooseTauLoose->Integral()<<endl;
    
    
//     histoBLooseTauLoose->Scale(1/(histoBLooseTauLoose->Integral()));
    // histoTT->Scale(1/(histoTT->Integral()));
//     histoDY->Scale(1/(histoDY->Integral()));
	
	cout << "Integral DY = " << histoDY->Integral() << ", Integral TT = " << histoTT->Integral() << endl;
	cout << "percentage = " << histoTT->Integral()/histoDY->Integral() << endl;
    
    histoDY->Draw("");
    histoTT->Draw("same");
    
//     histoBLooseTauLoose->Draw("same");
    
    

    
    // cout<<"--------------------------------------------------------------KS   "<<sample<<"--------------------------------------------------------------"<<endl;
//     cout<<"*************"<<folder<<"  "<<sample<<"*************"<<endl;
//     cout<<" Kolmogorov Test "<<histoDY->KolmogorovTest(histoBLoose,"")<<endl;
	histoDY->SetTitle("M_{H}");
	histoDY->GetXaxis()->SetTitle("M_{H} [GeV]");
	histoDY->GetYaxis()->SetTitleOffset(1.5);
	histoDY->GetYaxis()->SetTitle("N Events");
	
	
	
		
	
	TLegend* legend = new TLegend(0.6, 0.65, 0.99, 0.9);
	legend->SetFillColor(0);
	legend->SetTextSize(0.05);
	legend->SetEntrySeparation(0.05);
	legend->AddEntry(histoDY, " DY embedded ");
	legend->AddEntry(histoTT, " TT embedded ");
	//legend->AddEntry(histoBLooseTauLoose, " No Btagging, TauIso<1 ");
	
	legend->Draw();
	
	c1->SaveAs("./plots_embedded/"+folder+"_embComparison.eps");
}
Exemple #22
0
void CompareDifftheta(){

const int npt24=9;
const double pt[npt24]={0.4,0.7,1.2,1.7,2.2,2.7,3.4,4.4,5.4};
const double v24[5][npt24]={
{0.02809,0.04599,0.06869,0.08440,0.09715,0.09357,0.07924,0.04701,0.01620},
{0.02682,0.04447,0.06771,0.08586,0.09932,0.09782,0.08714,0.06139,0.05068},
{0.02582,0.04324,0.06644,0.08396,0.09725,0.1032,0.09603,0.07668,0.0605},
{0.02507,0.04214,0.06471,0.08294,0.09241,0.09917,0.09663,0.08479,0.06271},
};
const double v24err[5][npt24]={
{0.0007,0.00057,0.00085,0.0014,0.0022,0.0034,0.0041,0.0072,0.011},
{0.00058,0.00043,0.00063,0.00099,0.0016,0.0025,0.0031,0.0054,0.0086},
{0.00053,0.00038,0.00056,0.00088,0.0014,0.0022,0.0027,0.0049,0.0076},
{0.00079,0.00057,0.00084,0.0013,0.002,0.0032,0.004,0.0075,0.012},
};

//TString dirname = "PFcandpt03to6tracknormcpt03to6";TString name = "PFcandi03to6";
//TString dirname = "PFcandpt01to10tracknormcpt03to6";
//TString dirname = "tracknormcpt03to6"; TString name = "trackpt03to6";
TString dirname = "tracknormcpt03to3tracknormcpt03to6"; TString name = "trackpt03to3";

c1 = new TCanvas("c1"," ",1200,700);
makeMultiPanelCanvas(c1,3,2,0,0,0.25,0.2,0.03);
    gStyle->SetOptFit(1);
    gStyle->SetOptStat(0);
    gStyle->SetOptTitle(0);
    gStyle->SetErrorX(0);
    TH1D *hFrame = new TH1D("","",80,-1,7);
    hFrame->SetTitle("v_{2} vs momentum");
    hFrame->GetXaxis()->SetTitle("p_{T} (GeV/c)");
    hFrame->GetYaxis()->SetTitle("v_{2}");	
    hFrame->GetXaxis()->SetTitleSize(0.04);
    hFrame->GetYaxis()->SetTitleSize(0.04);
    hFrame->GetXaxis()->SetRangeUser(-0.3,6.3);
    hFrame->SetMaximum(0.2);

for(int i=0;i<ntotbin;i++){
	c1->cd(i+1);
	if(i!=ntotbin-1)
	TGraphErrors *gr24=new TGraphErrors(npt24,pt,v24[i],0,v24err[i]);
	TGraphErrors *grProd_theta8=plotTG(i,0,10,dirname,20,2);
	TGraphErrors *grProd_theta15=plotTG(i,0,15,dirname,27,2);
	TGraphErrors *grProd=plotTG(i,0,5,dirname,24,4);
	gr24->SetMarkerSize(1.3);
	gr24->SetMarkerColor(1);
	gr24->SetMarkerStyle(20);
	hFrame->Draw();
	gr24->Draw("Psame");
	grProd_theta8->Draw("Psame");
	grProd_theta15->Draw("Psame");
	grProd->Draw("Psame");
	TLegend *tl = new TLegend(0.4,0.5,0.7,0.70);
	tl->SetFillColor(0);
	tl->SetBorderSize(0);
	tl->SetTextSize(0.05);
	tl->AddEntry(gr24,"v2 4-particle cum","lp");
	tl->AddEntry(grProd_theta8,"LYZ n_{#theta} = 10","lp");
	tl->AddEntry(grProd_theta15,"LYZ n_{#theta} = 15","lp");
	tl->AddEntry(grProd,"LYZ n_{#theta} = 5","lp");
	if(i==0 || i==3) 
		TLatex *tlx2 = new TLatex(0.3,0.8,Form("%d<Ntrkoffline<%d",trkpointmin[i],trkpointmax[i]));
	else
		TLatex *tlx2 = new TLatex(0.1,0.8,Form("%d<Ntrkoffline<%d",trkpointmin[i],trkpointmax[i]));
	tlx2->SetNDC();
	tlx2->Draw("same");
	}
	c1->cd(ntotbin+1);
	TLatex *tlx0 = new TLatex(0.12,0.3,Form("%s",dirname.Data()));
        TLatex *tlx1 = new TLatex(0.12,0.25,Form("%.1f<p_{T}<%.1f (GeV/c)",0.3,6.0));
	tlx0->SetNDC();
	tlx1->SetNDC();
	tlx0->SetTextSize(0.045);
	tlx1->SetTextSize(0.045);
	tlx2->SetTextSize(0.045);
	hFrame->Draw();
	tlx0->Draw("same");
	tlx1->Draw("same");
	tl->Draw("same");
	c1->Print(Form("v2vspt_difftheta_%s.png",name.Data()));

}
Exemple #23
0
void DetermineAnchorsPP(const Char_t* inputDir, TString lPeriodName = "LHC18f", Int_t runNo, const Char_t* chunkName = "", Bool_t automaticMode=kFALSE) {
   //
   // In automatic mode the function does not request any standard input and creates anchor points if the fit was ok
   // using the anchor value determined automatically.
   // One must check the QA plots for individual run to make sure the automatic values are fine and eventually run this 
   // function again in manual mode.
   //
   
    Bool_t lUseDefaultAnchorPercentile = kFALSE;
    Double_t  lDefaultAnchorPercentile = 0.10;
    Double_t  lMinimumAnchorPercentile = 0.05;

    // open minimum bias OADB file
    TString lOADBfile = Form("OADB-%s-MB.root", lPeriodName.Data());

    cout << "Opening minimum bias info ... " << endl;
    TFile *foadb = new TFile( lOADBfile.Data(), "READ" );
    AliOADBContainer *lOADBcontainer = (AliOADBContainer*)foadb->Get("MultSel");

    // set percentile boundaries for the estimator histos
    // (based on what is implemented in the calibration)
    Double_t lDesiredBoundaries[1000];
    Long_t   lNDesiredBoundaries=0;
    lDesiredBoundaries[0] = 0.0;
    //From High To Low Multiplicity
    for( Int_t ib = 1; ib < 101; ib++) { // 100 bins  ] 0.0 , 0.1 ]
      lNDesiredBoundaries++;
      lDesiredBoundaries[lNDesiredBoundaries] = lDesiredBoundaries[lNDesiredBoundaries-1] + 0.01;
    }
    for( Int_t ib = 1; ib < 91; ib++) { // 90 bins ] 1.0 , 10. ]
        lNDesiredBoundaries++;
        lDesiredBoundaries[lNDesiredBoundaries] = lDesiredBoundaries[lNDesiredBoundaries-1] + 0.1;
    }
    for( Int_t ib = 1; ib < 91; ib++) { // 90 bins ] 10.0 , 100.0 ]
        lNDesiredBoundaries++;
        lDesiredBoundaries[lNDesiredBoundaries] = lDesiredBoundaries[lNDesiredBoundaries-1] + 1.0;
    }
    
    FILE *fap = 0x0;

    // auxiliary objects
    TLegend *legEstimator = 0x0;
    //
    TLine *anchorLine = new TLine();
    anchorLine->SetLineStyle(2);
    //
    TLatex *latex = new TLatex();
    latex->SetTextFont(42);
    latex->SetTextSize(0.025);

    // constant function for the scaling factor determination
    TF1 *fpol0 = new TF1("fpol0", "[0]", 0.005, lMinimumAnchorPercentile);
    fpol0->SetLineStyle(3);
    fpol0->SetLineWidth(1);
    fpol0->SetLineColor(kBlack);
    TF1 *fpol0_hi = (TF1*)fpol0->Clone("fpol0_hi");
    TF1 *fpol0_lo = (TF1*)fpol0->Clone("fpol0_lo");
    //
    Int_t npar = 3;
    TF1 *fturnon = new TF1("fturnon", func_turnon, 0., 1., npar);
    fturnon->SetParameters(1., 0.1, -1.);
    fturnon->SetParLimits(1, lMinimumAnchorPercentile, 1.0);
    fturnon->SetParLimits(2, -1.e15, 0.);
    fturnon->SetLineColor(1);

    // open input AnalysisResults.root file for the VHM sample
    TString fileIdentifier = Form("%d", runNo);
    if(chunkName[0]!='\0') fileIdentifier = chunkName;
    TFile *fin = TFile::Open(Form("%s/AnalysisResults_%s.root", inputDir, fileIdentifier.Data()), "READ");
    TTree *treeEvent = (TTree*)fin->Get("MultSelection/fTreeEvent");

    cout << "   - run number....................: " << runNo << endl;

    // define estimator histo for this run
    TH1D* hEstimator = new TH1D(Form("hEstimator_%d", runNo), "", lNDesiredBoundaries, lDesiredBoundaries);
    hEstimator->Sumw2();
    hEstimator->GetXaxis()->SetTitle("V0M Percentile");
    hEstimator->GetYaxis()->SetTitle("Counts");
    hEstimator->SetStats(0);
    hEstimator->SetLineColor(kRed);

    // get corresponding calibration histogram from OADB
    AliOADBMultSelection* lOADB = (AliOADBMultSelection*)lOADBcontainer->GetObject( runNo, "Default" );
    if( (Int_t)lOADBcontainer->GetIndexForRun( runNo )<0 ) {
      cout << "   ---> Warning: no calibration histo found for this run - skipping..." << endl;
      return;
    }

    // set the pointer to the calib histo for this run
    hCalib = (TH1D*)lOADB->GetCalibHisto( "hCalib_V0M" );;
    //
    Double_t nall = treeEvent->Draw(Form("get_percentile(fAmplitude_V0A+fAmplitude_V0C)>>hEstimator_%d", runNo), 
                                        Form("fRunNumber==%d && fEvSel_Triggered && fEvSel_IsNotPileupInMultBins && fEvSel_PassesTrackletVsCluster && fEvSel_INELgtZERO && fEvSel_HasNoInconsistentVertices && TMath::Abs(fEvSel_VtxZ)<=10.0 && isSelectedHM(fEvSel_TriggerMask)", runNo),
                                        "goff"); 

    hEstimator->Scale(1., "width");
    Double_t nevents = (Double_t)hEstimator->GetEntries();
    cout << "   - number of events (selected)...: " << nevents << endl;

    // draw histogram
    TCanvas *cEstimator = new TCanvas(Form("cEstimator_%d", runNo), "Estimator Distribution", 10, 10, 1000, 750);
    cEstimator->SetRightMargin(0.05);
    cEstimator->SetTopMargin(0.11);

    hEstimator->GetXaxis()->SetRangeUser(0., 0.2);
    hEstimator->Draw("hist e0");
    latex->SetNDC();
    latex->SetTextSize(0.06);
    latex->DrawLatex(0.1, 0.93, Form("Run: %d", runNo));

    // first, fit a pol0 in the flat region (usually up to 0.05)
    hEstimator->Fit(fpol0, "RQ0");
    Double_t flat_top = fpol0->GetParameter(0);

    // get standard deviantion of bin contents in the flat region
    Double_t flat_top_stdev = 0.;
    for(Int_t ibin=1; ibin<=hEstimator->FindBin(lMinimumAnchorPercentile); ++ibin) {
      Double_t content = hEstimator->GetBinContent(ibin);
      Double_t   width = hEstimator->GetBinWidth(ibin);
      flat_top_stdev += TMath::Power((content-flat_top), 2.)*width;
    }
    flat_top_stdev = TMath::Sqrt(flat_top_stdev/lMinimumAnchorPercentile) / 2.;
    fpol0_hi->SetParameter(0, flat_top+flat_top_stdev);
    fpol0_lo->SetParameter(0, flat_top-flat_top_stdev);
        
    // now, fix the constant parameter in the turnon function
    fturnon->SetParameters(1., 0.1, -1.);
    fturnon->FixParameter(0, flat_top);
        
    // get the maximum range to perform the fit
    Double_t range_max = (hEstimator->GetBinLowEdge(hEstimator->FindLastBinAbove())) / 1.8;
    fturnon->SetRange(0.005, (range_max>0.1) ? range_max : 0.1);

    // get anchor percentile
    Double_t anchor_percentile = -1.;
    TString fitstatus = "";
    if(nevents>0) {
      TFitResultPtr fitr = hEstimator->Fit(fturnon, "RQM");
      fturnon->Draw("lsame");
      fitstatus = gMinuit->fCstatu;
    }
    cEstimator->Flush();
    cEstimator->Update();
    cout << "   - fit status....................: " << fitstatus << endl;
    if( !fitstatus.Contains("OK") ) {
      if(gROOT->IsBatch()) {
         cout << "   ---> Warning: fit failed! -- skipping this run..." << endl;
         if(!automaticMode) {
            fap = fopen(Form("temp/anchors/Anchor_%s_%d_VHM.txt", lPeriodName.Data(), runNo), "w");
            fprintf(fap, "%d %d %.2lf %lf\n", runNo, runNo, -1., -1.);
         }
         return;
      }
      
      if(!automaticMode) {
         cout << "   - Please, provide an anchor percentile to continue: " << endl;
         cout << "     (entering a negative value will skip this run)" << endl;
         cout << "     >>>> anchor percentile: "; 
         cin >> anchor_percentile;
         if(anchor_percentile<0.) {
            cout << "   ---> Warning: percentile provided is negative -- skipping this run..." << endl;
            fap = fopen(Form("temp/anchors/Anchor_%s_%d_VHM.txt", lPeriodName.Data(), runNo), "w");
            fprintf(fap, "%d %d %.2lf %lf\n", runNo, runNo, -1., -1.);
            return;
         }
      }
      else return;      // in automatic mode we do not create an anchor file
void fakerate (int min = 0 , int max = 999) {

    TStyle * ts = (TStyle*)gROOT->GetStyle("Plain");
    ts->cd();
    ts->SetTitle(0);
    ts->SetOptStat(0000000);
    //ts->SetPalette(1);

    //cross sections in mb

    double sigma_15_20 = 1.46;
    double sigma_20_30 = 0.632;
    double sigma_30_50 = 0.163;
    double sigma_50_80 = 0.0216;
    double sigma_80_120 = 0.00308;

    std::vector<std::string> files;
    std::vector<double> weights;

    files.push_back("new1/FakeRate_qcd_loose_20_30.root");
    files.push_back("new1/FakeRate_qcd_loose_30_50.root");
    files.push_back("new1/FakeRate_qcd_loose_50_80.root");
    files.push_back("new1/FakeRate_qcd_loose_80_120.root");

    weights.push_back(sigma_20_30);
    weights.push_back(sigma_30_50);
    weights.push_back(sigma_50_80);
    weights.push_back(sigma_80_120);

    std::vector<std::string> files1;
    files1.push_back("new1/FakeRate_qcd_medium_20_30.root");
    files1.push_back("new1/FakeRate_qcd_medium_30_50.root");
    files1.push_back("new1/FakeRate_qcd_medium_50_80.root");
    files1.push_back("new1/FakeRate_qcd_medium_80_120.root");

    std::vector<std::string> files2;
    files2.push_back("new1/FakeRate_qcd_tight_20_30.root");
    files2.push_back("new1/FakeRate_qcd_tight_30_50.root");
    files2.push_back("new1/FakeRate_qcd_tight_50_80.root");
    files2.push_back("new1/FakeRate_qcd_tight_80_120.root");

    std::vector<TFile*> tfiles;
    std::vector<TFile*> tfiles1;
    std::vector<TFile*> tfiles2;

    for (int i=0; i<files.size(); i++) {
        tfiles.push_back(new TFile(files[i].c_str()));
    }

    for (int i=0; i<files1.size(); i++) {
        tfiles1.push_back(new TFile(files1[i].c_str()));
    }

    for (int i=0; i<files2.size(); i++) {
        tfiles2.push_back(new TFile(files2[i].c_str()));
    }


    TCanvas* cFakeIdDiv = new TCanvas ("cFakeIdDiv","Electron Id Fake Rate vs Jet Et");
    cFakeIdDiv->SetLogy();
    cFakeIdDiv->SetGridy();
    cFakeIdDiv->SetGridx();
    TH1D* hSelPT = (TH1D*)plot("HFakeNumSelEt","HFakeDenEt",tfiles,weights);
    TH1D* hSelPT1 = (TH1D*)plot("HFakeNumSelEt","HFakeDenEt",tfiles1,weights);
    TH1D* hSelPT2 = (TH1D*)plot("HFakeNumSelEt","HFakeDenEt",tfiles2,weights);
    TH1D* hRecoPT = (TH1D*)plot("HFakeNumEt","HFakeDenEt",tfiles,weights);
    hSelPT->SetTitle(0);
    hRecoPT->SetTitle(0);
    hSelPT->GetXaxis()->SetRangeUser(10,65);
    hSelPT->GetYaxis()->SetRangeUser(1e-3,1);
    //hSelPT->SetMaximum(1.0);
    hSelPT->GetXaxis()->SetTitle("E_{T} of Reco Jet (GeV)");
    hSelPT->GetYaxis()->SetTitle("Electron fake rate from jets (d#epsilon/dE_{T})");
    hSelPT->Draw("E");
    hSelPT->SetLineColor(4);
    hSelPT1->SetLineColor(8);
    hSelPT2->SetLineColor(2);
    hRecoPT->Draw("sameE");
    hSelPT1->Draw("sameE");
    hSelPT2->Draw("sameE");

    TLegend* legA = new TLegend(0.6,0.2,0.85,0.4);
    legA->AddEntry(hRecoPT,"Reconstruction","l");
    legA->AddEntry(hSelPT,"Id loose","l");
    legA->AddEntry(hSelPT1,"Id medium","l");
    legA->AddEntry(hSelPT2,"Id tight","l");
    legA->SetFillColor(0);
    legA->SetTextSize(0.04);
    legA->Draw();
    gPad->Update();


    TCanvas* cFakeIdDiv1 = new TCanvas ("cFakeIdDiv1","Electron Id Fake Rate vs Jet Et (Rel)");
    cFakeIdDiv1->SetLogy();
    cFakeIdDiv1->SetGridy();
    cFakeIdDiv1->SetGridx();
    TH1D* hSelPTA = (TH1D*)plot("HFakeNumSelEt","HFakeNumEt",tfiles,weights);
    TH1D* hSelPT1A = (TH1D*)plot("HFakeNumSelEt","HFakeNumEt",tfiles1,weights);
    TH1D* hSelPT2A = (TH1D*)plot("HFakeNumSelEt","HFakeNumEt",tfiles2,weights);
    hSelPTA->SetTitle(0);
    hSelPTA->GetXaxis()->SetRangeUser(10,65);
    hSelPTA->GetYaxis()->SetRangeUser(1e-2,1);
    //hSelPT->SetMaximum(1.0);
    hSelPTA->GetXaxis()->SetTitle("E_{T} of Reco Jet (GeV)");
    hSelPTA->GetYaxis()->SetTitle("Electron fake rate from jets (d#epsilon/dE_{T})");
    hSelPTA->Draw("E");
    hSelPTA->SetLineColor(4);
    hSelPT1A->SetLineColor(8);
    hSelPT2A->SetLineColor(2);
    hSelPT1A->Draw("sameE");
    hSelPT2A->Draw("sameE");

    TLegend* legAA = new TLegend(0.6,0.2,0.85,0.4);
    legAA->AddEntry(hSelPTA,"Id loose","l");
    legAA->AddEntry(hSelPT1A,"Id medium","l");
    legAA->AddEntry(hSelPT2A,"Id tight","l");
    legAA->SetFillColor(0);
    legAA->SetTextSize(0.04);
    legAA->Draw();
    gPad->Update();



    TCanvas* cFakeIdNum = new TCanvas ("cFakeIdNum","Et spectrum of jets that match reco electrons");
    cFakeIdNum->SetLogy();
    cFakeIdNum->SetGridy();
    cFakeIdNum->SetGridx();
    TH1D* hSelJetPT = (TH1D*)Plot1D("HFakeNumSelEt",tfiles,weights);
    TH1D* hSelJetPT1 = (TH1D*)Plot1D("HFakeNumSelEt",tfiles1,weights);
    TH1D* hSelJetPT2 = (TH1D*)Plot1D("HFakeNumSelEt",tfiles2,weights);
    TH1D* hRecoJetPT = (TH1D*)Plot1D("HFakeNumEt",tfiles,weights);
    hSelJetPT->SetTitle(0);
    hRecoJetPT->SetTitle(0);
    hSelJetPT->GetXaxis()->SetRangeUser(10,65);
    //hSelJetPT->GetYaxis()->SetRangeUser(1e-6,1);
    hSelJetPT->SetMaximum(1e5);
    hSelJetPT->SetMinimum(1.0001);
    hSelJetPT->GetXaxis()->SetTitle("E_{T} of Reco Jet that fakes an electron(GeV)");
    hSelJetPT->GetYaxis()->SetTitle("Arbitrary Scale");
    hSelJetPT->Draw("E");
    hSelJetPT->SetLineColor(4);
    hSelJetPT1->SetLineColor(8);
    hSelJetPT2->SetLineColor(2);
    hRecoJetPT->Draw("sameE");
    hSelJetPT1->Draw("sameE");
    hSelJetPT2->Draw("sameE");

    TLegend* legA1 = new TLegend(0.6,0.2,0.85,0.4);
    legA1->AddEntry(hRecoJetPT,"Reconstruction","l");
    legA1->AddEntry(hSelJetPT,"Id loose","l");
    legA1->AddEntry(hSelJetPT1,"Id medium","l");
    legA1->AddEntry(hSelJetPT2,"Id tight","l");
    legA1->SetFillColor(0);
    legA1->SetTextSize(0.04);
    legA1->Draw();
    gPad->Update();

    TCanvas* cFakeIdDen = new TCanvas ("cFakeIdDen","Et spectrum of jets");
    cFakeIdDen->SetLogy();
    cFakeIdDen->SetGridy();
    cFakeIdDen->SetGridx();
    TH1D* hJetPT = (TH1D*)Plot1D("HFakeDenEt",tfiles,weights);
    //hJetPT->Scale(1.0/hJetPT->Integral());
    hJetPT->SetTitle(0);
    hJetPT->GetXaxis()->SetRangeUser(10,65);
    //hJetPT->GetYaxis()->SetRangeUser(1e-6,1);
    hJetPT->SetMaximum(1e5);
    hJetPT->SetMinimum(1.0001);
    hJetPT->SetLineColor(1);
    hJetPT->GetXaxis()->SetTitle("E_{T} of Reco Jet (GeV)");
    hJetPT->GetYaxis()->SetTitle("Arbitrary Scale");
    hJetPT->Draw("E");



    TCanvas* cFakeIdDivEta = new TCanvas ("cFakeIdDivEta","Electron Id Fake Rate vs Jet Eta");
    cFakeIdDivEta->SetLogy();
    cFakeIdDivEta->SetGridy();
    cFakeIdDivEta->SetGridx();
    TH1D* hSelEta = (TH1D*)plot("HFakeNumSelEta","HFakeDenEta",tfiles,weights);
    TH1D* hSelEta1 = (TH1D*)plot("HFakeNumSelEta","HFakeDenEta",tfiles1,weights);
    TH1D* hSelEta2 = (TH1D*)plot("HFakeNumSelEta","HFakeDenEta",tfiles2,weights);
    TH1D* hRecoEta = (TH1D*)plot("HFakeNumEta","HFakeDenEta",tfiles,weights);
    hSelEta->SetTitle(0);
    hRecoEta->SetTitle(0);
    hSelEta->GetXaxis()->SetRangeUser(10,65);
    hSelEta->GetYaxis()->SetRangeUser(1e-4,1);
    //hSelEta->SetMaximum(1.0);
    hSelEta->GetXaxis()->SetTitle("#eta of Reco Jet (GeV)");
    hSelEta->GetYaxis()->SetTitle("Electron fake rate from jets (d#epsilon/d#eta)");
    hSelEta->Draw("E");
    hSelEta->SetLineColor(4);
    hSelEta1->SetLineColor(8);
    hSelEta2->SetLineColor(2);
    hRecoEta->Draw("sameE");
    hSelEta1->Draw("sameE");
    hSelEta2->Draw("sameE");

    TLegend* legB = new TLegend(0.6,0.2,0.85,0.4);
    legB->AddEntry(hRecoEta,"Reconstruction","l");
    legB->AddEntry(hSelEta,"Id loose","l");
    legB->AddEntry(hSelEta1,"Id medium","l");
    legB->AddEntry(hSelEta2,"Id tight","l");
    legB->SetFillColor(0);
    legB->SetTextSize(0.04);
    legB->Draw();
    gPad->Update();

    TCanvas* cFakeIdDivEta1 = new TCanvas ("cFakeIdDivEta1","Electron Id Fake Rate vs Jet Eta (Rel)");
    cFakeIdDivEta1->SetLogy();
    cFakeIdDivEta1->SetGridy();
    cFakeIdDivEta1->SetGridx();
    TH1D* hSelEtaB = (TH1D*)plot("HFakeNumSelEta","HFakeNumEta",tfiles,weights);
    TH1D* hSelEta1B = (TH1D*)plot("HFakeNumSelEta","HFakeNumEta",tfiles1,weights);
    TH1D* hSelEta2B = (TH1D*)plot("HFakeNumSelEta","HFakeNumEta",tfiles2,weights);
    hSelEtaB->SetTitle(0);
    hSelEtaB->GetXaxis()->SetRangeUser(10,65);
    hSelEtaB->GetYaxis()->SetRangeUser(1e-4,1);
    //hSelEta->SetMaximum(1.0);
    hSelEtaB->GetXaxis()->SetTitle("#eta of Reco Jet (GeV)");
    hSelEtaB->GetYaxis()->SetTitle("Electron fake rate from jets (d#epsilon/d#eta)");
    hSelEtaB->Draw("E");
    hSelEtaB->SetLineColor(4);
    hSelEta1B->SetLineColor(8);
    hSelEta2B->SetLineColor(2);
    hSelEta1B->Draw("sameE");
    hSelEta2B->Draw("sameE");

    TLegend* legBB = new TLegend(0.6,0.2,0.85,0.4);
    legBB->AddEntry(hSelEtaB,"Id loose","l");
    legBB->AddEntry(hSelEta1B,"Id medium","l");
    legBB->AddEntry(hSelEta2B,"Id tight","l");
    legBB->SetFillColor(0);
    legBB->SetTextSize(0.04);
    legBB->Draw();
    gPad->Update();

    TCanvas* cFakeIdNumEta = new TCanvas ("cFakeIdNumEta","#eta spectrum of jets that match reco electrons");
    cFakeIdNumEta->SetLogy();
    cFakeIdNumEta->SetGridy();
    cFakeIdNumEta->SetGridx();
    TH1D* hSelJetEta = (TH1D*)Plot1D("HFakeNumSelEta",tfiles,weights);
    TH1D* hSelJetEta1 = (TH1D*)Plot1D("HFakeNumSelEta",tfiles1,weights);
    TH1D* hSelJetEta2 = (TH1D*)Plot1D("HFakeNumSelEta",tfiles2,weights);
    TH1D* hRecoJetEta = (TH1D*)Plot1D("HFakeNumEta",tfiles,weights);
    hSelJetEta->SetTitle(0);
    hRecoJetEta->SetTitle(0);
    hSelJetEta->GetXaxis()->SetRangeUser(10,65);
    //hSelJetEta->GetYaxis()->SetRangeUser(1e-6,1);
    hSelJetEta->SetMaximum(1e4);
    hSelJetEta->SetMinimum(1.0001);
    hSelJetEta->GetXaxis()->SetTitle("#eta of Reco Jet that fakes an electron(GeV)");
    hSelJetEta->GetYaxis()->SetTitle("Arbitrary Scale");
    hSelJetEta->Draw("E");
    hSelJetEta->SetLineColor(4);
    hSelJetEta1->SetLineColor(8);
    hSelJetEta2->SetLineColor(2);
    hRecoJetEta->Draw("sameE");
    hSelJetEta1->Draw("sameE");
    hSelJetEta2->Draw("sameE");

    TLegend* legB1 = new TLegend(0.6,0.2,0.85,0.4);
    legB1->AddEntry(hRecoJetPT,"Reconstruction","l");
    legB1->AddEntry(hSelJetPT,"Id loose","l");
    legB1->AddEntry(hSelJetPT1,"Id medium","l");
    legB1->AddEntry(hSelJetPT2,"Id tight","l");
    legB1->SetFillColor(0);
    legB1->SetTextSize(0.04);
    legB1->Draw();
    gPad->Update();

    TCanvas* cFakeIdDenEta = new TCanvas ("cFakeIdDenEta","#eta spectrum of jets");
    cFakeIdDenEta->SetLogy();
    cFakeIdDenEta->SetGridy();
    cFakeIdDenEta->SetGridx();
    TH1D* hJetEta = (TH1D*)Plot1D("HFakeDenEta",tfiles,weights);
    hJetEta->SetTitle(0);
    hJetEta->GetXaxis()->SetRangeUser(10,65);
    //hJetEta->GetYaxis()->SetRangeUser(1e-6,1);
    hJetEta->SetMaximum(1e4);
    hJetEta->SetMinimum(1.0001);
    hJetEta->SetLineColor(1);
    hJetEta->GetXaxis()->SetTitle("#eta of Reco Jet (GeV)");
    hJetEta->GetYaxis()->SetTitle("Arbitrary Scale");
    hJetEta->Draw("E");

    TCanvas* cEtJetvsEtElec = new TCanvas ("cEtJetvsEtElec","E_{T} of Electron vs E_{T} of Jet");
    cEtJetvsEtElec->SetLogz();
    TH2D* hJetvsElec = (TH2D*)Plot2D("HEtJetvsEtElectron",tfiles,weights);
    hJetvsElec->SetTitle(0);
    hJetvsElec->GetXaxis()->SetTitle("E_{T} of Reco Jet (GeV)");
    hJetvsElec->GetYaxis()->SetTitle("E_{T} of Reco Electron (GeV)");
    hJetvsElec->Draw("COLZ");

    TCanvas* cDRJetElec = new TCanvas ("cDRJetElec","minimum #DeltaR between electron and jets ");
    cDRJetElec->SetLogy();
    cDRJetElec->SetGridy();
    cDRJetElec->SetGridx();
    TH1D* hDRJetElec = (TH1D*)Plot1D("HdRminElecjet",tfiles,weights);
    hDRJetElec->SetTitle(0);
    hDRJetElec->SetLineColor(1);
    hDRJetElec->GetXaxis()->SetTitle("Minimum #DeltaR between electrons and jets");
    hDRJetElec->GetYaxis()->SetTitle("Arbitrary Scale");
    hDRJetElec->Draw();



}
Exemple #25
0
void chipSummary(const char *dirName, int chipId)
{
        directory = TString(dirName);
	
	if (f && f->IsOpen()) f->Close();
	if (f1 && f1->IsOpen()) f1->Close();
	if (g && g->IsOpen()) g->Close();

	gROOT->SetStyle("Plain");
	gStyle->SetPalette(1);
	gStyle->SetOptStat(0);
	gStyle->SetTitle(0);

	gStyle->SetStatFont(132);
	gStyle->SetTextFont(132);
	gStyle->SetLabelFont(132, "X");
	gStyle->SetLabelFont(132, "Y");
	gStyle->SetLabelSize(0.08, "X");
	gStyle->SetLabelSize(0.08, "Y");
	gStyle->SetNdivisions(6, "X");
	gStyle->SetNdivisions(8, "Y");
	gStyle->SetTitleFont(132);

	gROOT->ForceStyle();

	tl = new TLatex;
	tl->SetNDC(kTRUE);
	tl->SetTextSize(0.09);

	ts = new TLatex;
	ts->SetNDC(kTRUE);
	ts->SetTextSize(0.08);

	line = new TLine;
	line->SetLineColor(kRed);
	line->SetLineStyle(kSolid);
	
	box = new TBox;
	box->SetFillColor(kRed);
	box->SetFillStyle(3002);

	f = new TFile(Form("%s/%s", dirName, fileName), "READ");
	
	if (strcmp(fileName, adFileName) == 0) f1 = f;
	else f1 = new TFile(Form("%s/%s", dirName, adFileName), "READ");
	
	if (strcmp(fileName, trimFileName) == 0) g = f;
	else g = new TFile(Form("%s/%s", dirName, trimFileName), "READ");
 
	sprintf(fname, "%s/../../macros/criteria-full.dat", dirName);
	if ( !readCriteria(fname) ) { 
	  
	  printf("\nchipSummary> ----> COULD NOT READ GRADING CRITERIA !!!");
	  printf("chipSummary> ----> Aborting execution of chipgSummaryPage.C ... \n\n", fileName, dirName);  
	  break;
	}

	TH1D *h1;
	TH2D *h2;

	c1 = new TCanvas("c1", "", 800, 800);
	c1->Clear();
	c1->Divide(4,4, 0.01, 0.04);

  //	shrinkPad(0.1, 0.1, 0.1, 0.3);

	FILE *sCurveFile, *phLinearFile, *phTanhFile;

        TString noslash(dirName);
        noslash.ReplaceAll("/", " ");
        noslash.ReplaceAll(".. ", "");
	
	char string[200];
	int pixel_alive;

	int nDeadPixel(0);
	int nIneffPixel(0);
	int nMaskDefect(0);
	int nNoisy1Pixel(0);
	int nDeadBumps(0);
	int nDeadTrimbits(0);
	int nAddressProblems(0);

	int nNoisy2Pixel(0);
	int nThrDefect(0);
	int nGainDefect(0);
	int nPedDefect(0);
	int nPar1Defect(0);

	int nRootFileProblems(0);

	int nDoubleFunctCounts(0);
	int nDoublePerfCounts(0);
	int nDoubleCounts(0);
	int nDoubleTrims(0);
	int nDoublePHs(0);

        int vcal = dac_findParameter(dirName, "Vcal", chipId);
	
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	// Row 1
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

	// -- Dead pixels
	c1->cd(1);

	TH2D *hpm;
	hpm = (TH2D*)f->Get(Form("PixelMap_C%i", chipId));

        if (hpm) {

	  for (int icol = 0; icol < 52; ++icol) {
	    for (int irow = 0; irow < 80; ++irow) {      
	      
	      hpm->SetTitle("");
	      hpm->Draw("colz");
	      tl->DrawLatex(0.1, 0.92, "Pixel Map");
	    }
	  }

	} else { 
	  
	  ++nRootFileProblems; 
	}


	// -- sCurve width and noise level
	TH1D *hw = new TH1D("hw", "", 100, 0., 600.);
	TH1D *hd = new TH1D("hd", "", 100, 0., 600.);  // Noise in unbonded pixel (not displayed)
	TH2D *ht = new TH2D("ht", "", 52, 0., 52., 80, 0., 80.);
	TH1D *htmp;

	float mN(0.), sN(0.), nN(0.), nN_entries(0.);
	int over(0), under(0);

	double htmax(255.), htmin(0.);
	
	float thr, sig;
	int a,b;

	double minThrDiff(-5.);
	double maxThrDiff(5.);

	h2 = (TH2D*)f->Get(Form("vcals_xtalk_C%i", chipId));
        
	sprintf(string, "%s/SCurve_C%i.dat", dirName, chipId);
	sCurveFile = fopen(string, "r");

	if (!sCurveFile) {

	  printf("chipSummary> !!!!!!!!!  ----> SCurve: Could not open file %s to read fit results\n", string);
	
	} else {
	  
	  for (int i = 0; i < 2; i++) fgets(string, 200, sCurveFile);
	  
	  for (int icol = 0; icol < 52; ++icol)	{
	    for (int irow = 0; irow < 80; ++irow) {
	      
	      fscanf(sCurveFile, "%e %e %s %2i %2i", &thr, &sig, string, &a, &b);
	      //  				printf("chipSummary> sig %e thr %e\n", sig, thr);
	      
	      hw->Fill(sig);
	      thr = thr / 65.;
	      
	      ht->SetBinContent(icol+1, irow+1, thr); 
	      
	      if ( h2 ) {
		if( h2->GetBinContent(icol+1, irow+1)  >= minThrDiff) {
		  
		  hd->Fill(sig);
		}
	      }
	    }
	  }
	  
	  fclose(sCurveFile);

	  c1->cd(2);
	  hw->Draw();
	  tl->DrawLatex(0.1, 0.92, "S-Curve widths: Noise (e^{-})");
	  
	  
	  /*		c1->cd(15);
			hd->SetLineColor(kRed);
			hd->Draw();
			tl->DrawLatex(0.1, 0.92, "S-Curve widths of dead bumps");
			if ( hd->GetEntries() > 0 ) {
			ts->DrawLatex(0.55, 0.82, Form("entries: %4.0f", hd->GetEntries()));
			ts->DrawLatex(0.55, 0.74, Form("#mu:%4.2f", hd->GetMean()));
			ts->DrawLatex(0.55, 0.66, Form("#sigma: %4.2f", hd->GetRMS()));
			}
	  */
	  
	  mN =  hw->GetMean();
	  sN =  hw->GetRMS();
	  nN =  hw->Integral(hw->GetXaxis()->GetFirst(), hw->GetXaxis()->GetLast());
	  nN_entries =  hw->GetEntries();
	  
	  under = hw->GetBinContent(0);
	  over  = hw->GetBinContent(hw->GetNbinsX()+1);
	  
	  
	  ts->DrawLatex(0.65, 0.82, Form("N: %4.0f", nN));
	  ts->DrawLatex(0.65, 0.74, Form("#mu: %4.1f", mN));
	  ts->DrawLatex(0.65, 0.66, Form("#sigma: %4.1f", sN));
	  
	  if ( under ) ts->DrawLatex(0.15, 0.55, Form("<= %i", under));			               
	  if ( over  ) ts->DrawLatex(0.75, 0.55, Form("%i =>", over ));
	  
	  c1->cd(3);
	  if ( ht->GetMaximum() < htmax ) { 
	    htmax = ht->GetMaximum();
	  }
	  if ( ht->GetMinimum() > htmin ) {
	    htmin = ht->GetMinimum();
	  }
	  ht->GetZaxis()->SetRangeUser(htmin,htmax);
	  ht->Draw("colz");
	  tl->DrawLatex(0.1, 0.92, "Vcal Threshold Untrimmed");
	  
	}
	
	// -- Noise level map
	c1->cd(4);
        gPad->SetLogy(1);
 	gStyle->SetOptStat(1);

	float mV(0.), sV(0.), nV(0.), nV_entries(0.);
	over = 0.; under = 0.;

	if (!g->IsZombie())
	{
	      h1 = (TH1D*)g->Get(Form("VcalThresholdMap_C%iDistribution;7", chipId));
              if (h1) {
		h1->SetTitle("");
		h1->SetAxisRange(0., 100.);
		h1->Draw();

		mV = h1->GetMean();
		sV = h1->GetRMS();
		nV = h1->Integral(h1->GetXaxis()->GetFirst(), h1->GetXaxis()->GetLast());
		nV_entries = h1->GetEntries();

		under = h1->GetBinContent(0);
		over  = h1->GetBinContent(h1->GetNbinsX()+1);
              }
              else {

	        ++nRootFileProblems;
		mV = 0.;
		sV = 0.;
               
              }

	      ts->DrawLatex(0.15, 0.82, Form("N: %4.0f", nV));
	      ts->DrawLatex(0.15, 0.74, Form("#mu: %4.1f", mV));
	      ts->DrawLatex(0.15, 0.66, Form("#sigma: %4.1f", sV));
	      
	      if ( under ) ts->DrawLatex(0.15, 0.55, Form("<= %i", under));			               
	      if ( over  ) ts->DrawLatex(0.75, 0.55, Form("%i =>", over ));
	}

	tl->DrawLatex(0.1, 0.92, "Vcal Threshold Trimmed");

	
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	// Row 2
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

	// -- Bump Map
	TH2D *hbm;

	c1->cd(5);
	gStyle->SetOptStat(0);
	hbm = (TH2D*)f->Get(Form("vcals_xtalk_C%i", chipId));
        
        if (hbm) {

	  h2->SetTitle("");
	  h2->GetZaxis()->SetRangeUser(minThrDiff, maxThrDiff);
	  h2->Draw("colz");
	  tl->DrawLatex(0.1, 0.92, "Bump Bonding Problems");
	}

	else { ++nRootFileProblems; }

	// -- Bump Map
	c1->cd(6);  
	gPad->SetLogy(1);
	//gStyle->SetOptStat(1);
	h1 = (TH1D*)f->Get(Form("vcals_xtalk_C%iDistribution", chipId));

        if (h1) {
  	  h1->SetTitle("");
	  h1->GetXaxis()->SetRangeUser(-50., 50.);
	  h1->GetYaxis()->SetRangeUser(0.5, 5.0*h1->GetMaximum());
	  h1->DrawCopy();
	  tl->DrawLatex(0.1, 0.92, "Bump Bonding");
	
	} else { 
	  
	  ++nRootFileProblems; 
	}
	
	// -- Trim bits
	int trimbitbins(3);
	c1->cd(7); 
	gPad->SetLogy(1);
	h1 = (TH1D*)f->Get(Form("TrimBit14_C%i", chipId));
	if (h1) {
	  h1->SetTitle("");
	  h1->SetAxisRange(0., 60.);
	  h1->SetMinimum(0.5);
	  h1->Draw("");
	  tl->DrawLatex(0.1, 0.92, "Trim Bit Test");          
	}
	else { ++nRootFileProblems; }

	h1 = (TH1D*)f->Get(Form("TrimBit13_C%i", chipId));
	if (h1) {
	  h1->SetLineColor(kRed);
	  h1->Draw("same");
	}
	else { ++nRootFileProblems; }

	h1 = (TH1D*)f->Get(Form("TrimBit11_C%i", chipId));
	if (h1) {
	  h1->SetLineColor(kBlue);
	  h1->Draw("same");
	}
	else { ++nRootFileProblems; }

	h1 = (TH1D*)f->Get(Form("TrimBit7_C%i", chipId));
	if (h1) {
	  h1->SetLineColor(kGreen);
	  h1->Draw("same");
	}	
	else { ++nRootFileProblems; }
	
	// -- For numerics and titels see at end


	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	// Row 3
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

	// -- Address decoding	
	// --------------------

	TH2D *ham;
	ham = (TH2D*)f1->Get(Form("AddressDecoding_C%i", chipId));

	c1->cd(9);
	gStyle->SetOptStat(0);
        if (ham) {

	  ham->SetTitle("");
	  ham->Draw("colz");
	  tl->DrawLatex(0.1, 0.92, "Address decoding");
	}

	else { ++nRootFileProblems; }

	// -- Address levels

	c1->cd(10); 
	gPad->SetLogy(1);
	h1 = (TH1D*)f1->Get(Form("AddressLevels_C%i", chipId));
        if (h1) {
	  h1->SetTitle("");
	  h1->SetAxisRange(-1500., 1500.);
	  h1->Draw();
	  tl->DrawLatex(0.1, 0.92, "Address Levels");
	
	} else { 
	  
	  ++nRootFileProblems; 
	}


	// -- PHCalibration: Linear Fit (Gain & Pedesdtal)
	// -----------------------------------------------

	TH1D *hg = new TH1D("hg", "", 300, -2.0, 5.5);
	TH2D *hgm = new TH2D("hgm", "", 52, 0., 52., 80, 0., 80.);
	
	TH1D *hp = new TH1D("hp", "", 900, -300., 600.);
	hp->StatOverflows(kTRUE);

	TH1D *rp = new TH1D("rp", "", 900, -300., 600.);
	rp->StatOverflows(kFALSE);

	TH1D *htmp;

	float par0, par1, par2, par3, par4, par5; // Parameters of Vcal vs. Pulse Height Fit

	float mG(0.), sG(0.), nG(0.), nG_entries(0.);
	float mP(0.), sP(0.), nP(0.), nP_entries(0.); 
	over = 0.; under = 0.;

	float ped, gain;
	int a,b;
	
	int mPbin(0), xlow(-100), xup(255), extra(0);       // for restricted RMS
	float pedMin(0), pedMax(1000);
	double integral(0.);

	sprintf(string, "%s/phCalibrationFit_C%i.dat", dirName, chipId);
	phLinearFile = fopen(string, "r");

	if (!phLinearFile) {
	  
	  printf("chipSummary> !!!!!!!!!  ----> phCal: Could not open file %s to read fit results\n", string);
	
	} else {
		
	  for (int i = 0; i < 2; i++) fgets(string, 200, phLinearFile);
	  
	  for (int icol = 0; icol < 52; ++icol)	{
	    for (int irow = 0; irow < 80; ++irow) {
	      fscanf(phLinearFile, "%e %e %e %e %e %e %s %2i %2i", 
		     &par0, &par1, &par2, &par3, &par4, &par5, string, &a, &b);
	      
	      if (par2 != 0.)  {  // dead pixels have par2 == 0.
		
		gain = 1./par2;
		ped = par3;
		hp->Fill(ped);
		hg->Fill(gain);
		hgm->SetBinContent(icol + 1, irow + 1, gain);
	      }
	    }
	  }
	  
	  fclose(phLinearFile);
	  

	  // -- Gain

	  c1->cd(11);

	  mG =  hg->GetMean();
	  sG =  hg->GetRMS();
	  nG =  hg->Integral(hg->GetXaxis()->GetFirst(), hg->GetXaxis()->GetLast());
	  nG_entries = hg->GetEntries();
	  
	  under = hg->GetBinContent(0);
	  over  = hg->GetBinContent(hp->GetNbinsX()+1);
	  	  
	  gPad->SetLogy(1);
	  hg->GetYaxis()->SetRangeUser(0.5, 5.0*hg->GetMaximum());
	  hg->Draw();
	  tl->DrawLatex(0.1, 0.92, "PH Calibration: Gain (ADC/DAC)");
	  
	  if ( hg->GetMean() > 1.75 ) {

	    ts->DrawLatex(0.15, 0.80, Form("N: %4.0f", nG));
	    ts->DrawLatex(0.15, 0.72, Form("#mu: %4.2f", mG));
	    ts->DrawLatex(0.15, 0.64, Form("#sigma: %4.2f", sG));

	  } else {

	    ts->DrawLatex(0.65, 0.80, Form("N: %4.0f", nG));
	    ts->DrawLatex(0.65, 0.72, Form("#mu: %4.2f", mG));
	    ts->DrawLatex(0.65, 0.64, Form("#sigma: %4.2f", sG));
	  }
	  
	    
	  if ( under ) ts->DrawLatex(0.15, 0.55, Form("<= %i", under));			               
	  if ( over  ) ts->DrawLatex(0.75, 0.55, Form("%i =>", over ));
	  
	  c1->cd(15);

	  hgm->Draw("colz");
	  tl->DrawLatex(0.1, 0.92, "PH Calibration: Gain (ADC/DAC)");

	  // -- Pedestal

	  c1->cd(12);

	  mP =  hp->GetMean();
	  sP =  hp->GetRMS();
	  nP =  hp->Integral(hp->GetXaxis()->GetFirst(), hp->GetXaxis()->GetLast());
	  nP_entries = hp->GetEntries();
	  
	  if ( nP > 0 ) {
	    
	    // -- restricted RMS
	    integral = 0.;
	    mPbin = -1000; xlow = -1000; xup = 1000;
	    over = 0.; under = 0.;
	    
	    mPbin = hp->GetXaxis()->FindBin(mP);
	    
	    for (int i = 0; integral <  pedDistr; i++) { 
		    
	      xlow = mPbin-i;
	      xup =  mPbin+i;
	      integral = hp->Integral(xlow, xup)/nP;
		    
	    }
		  
	    extra = xup - xlow;
	  }
	  else {

	    xlow = -300; xup = 600; extra = 0;
	    over = 0.; under = 0.;
	  }

  	  under = hp->Integral(0, xlow - extra);
  	  over  = hp->Integral(xup + 1.5*extra, hp->GetNbinsX());
		  
	  hp->GetXaxis()->SetRange(xlow - extra, xup + 1.5*extra);

	  nP    = hp->Integral(hp->GetXaxis()->GetFirst(), hp->GetXaxis()->GetLast());

	  pedMin = hp->GetBinCenter(xlow-extra);
	  pedMax = hp->GetBinCenter(xup+1.5*extra);


	  cout<< " ========> Ped min  " << pedMin << " Ped max " << pedMax 
	      << ", over: " << over << " under: " << under << endl;		

	  hp->DrawCopy();

	  rp->Add(hp);
	  rp->GetXaxis()->SetRange(xlow, xup);

	  mP =  rp->GetMean();
	  sP =  rp->GetRMS();

	  // box->DrawBox( rp->GetBinCenter(xlow), 0, rp->GetBinCenter(xup), 1.05*rp->GetMaximum());
	  rp->SetFillColor(kRed);
	  rp->SetFillStyle(3002);
	  rp->Draw("same");
	  line->DrawLine(rp->GetBinCenter(xlow), 0, rp->GetBinCenter(xlow), 0.6*rp->GetMaximum());
	  line->DrawLine(rp->GetBinCenter(xup),  0, rp->GetBinCenter(xup),  0.6*rp->GetMaximum());
	 
	  tl->DrawLatex(0.1, 0.92, "PH Calibration: Pedestal (DAC)");
		
	  if ( hp->GetMean() < 126. ) {

	    ts->DrawLatex(0.65, 0.82, Form("N: %4.0f", nP));
	    ts->SetTextColor(kRed);
	    ts->DrawLatex(0.65, 0.74, Form("#mu: %4.1f", mP));
	    ts->DrawLatex(0.65, 0.66, Form("#sigma: %4.1f", sP));
				
	  } else {

	    ts->DrawLatex(0.16, 0.82, Form("N: %4.0f", nP));
	    ts->SetTextColor(kRed);
	    ts->DrawLatex(0.16, 0.74, Form("#mu: %4.1f", mP));
	    ts->DrawLatex(0.16, 0.66, Form("#sigma: %4.1f", sP));
	  }

	  if ( under ) ts->DrawLatex(0.15, 0.55, Form("<= %i", under));			               
	  if ( over  ) ts->DrawLatex(0.75, 0.55, Form("%i =>", over ));
	  ts->SetTextColor(kBlack);
	  

		
	}

	
	// -- PHCalibration: Tanh Fit (Parameter1)
	// ----------------------------------------
	
	c1->cd(11);

	over = 0.; under = 0.;

	float nPar1(0.), nPar1_entries(0.), mPar1(0.), sPar1(0.);
	
        TH1D *hPar1 = new TH1D("par1", "", 350, -1., 6.);

	sprintf(string, "%s/phCalibrationFitTan_C%i.dat", dirName, chipId);
	phTanhFile = fopen(string, "r");
	
	if (!phTanhFile) {
	  
	  printf("chipSummary> !!!!!!!!!  ----> phCal: Could not open file %s to read fit results\n", string);
	
	} else {
	  
	  for (int i = 0; i < 2; i++) fgets(string, 200, phTanhFile);
	  
	  for (int icol = 0; icol < 52; ++icol) {
	    for (int irow = 0; irow < 80; ++irow) {
	      
	      fscanf(phTanhFile, "%e %e %e %e %s %2i %2i", &par0, &par1, &par2, &par3, string, &a, &b);		
	      hPar1->Fill(par1);
	    }
	  }
	  
	  fclose(phTanhFile);	


	  // -- Parameter 1

	  hPar1->SetLineColor(kBlue);
	  hPar1->Draw("same");
	  
	  mPar1 =  hPar1->GetMean();
	  sPar1 =  hPar1->GetRMS();
	  nPar1 =  hPar1->Integral(hPar1->GetXaxis()->GetFirst(), hPar1->GetXaxis()->GetLast());	
	  nPar1_entries = hPar1->GetEntries();
	  
	  under = hPar1->GetBinContent(0);
	  over  = hPar1->GetBinContent(hPar1->GetNbinsX()+1);
	  
	  ts->SetTextColor(kBlue);
	  
	  if ( hg->GetMean() > 1.75 ) {
	  
	    ts->DrawLatex(0.15, 0.40, "Par1:");
	    ts->DrawLatex(0.15, 0.30, Form("N: %4.0f", nPar1));
	    ts->DrawLatex(0.15, 0.22, Form("#mu: %4.2f", mPar1));
	    ts->DrawLatex(0.15, 0.14, Form("#sigma: %4.2f", sPar1));
	  
	  } else {

	    ts->DrawLatex(0.65, 0.40, "Par1:");
	    ts->DrawLatex(0.65, 0.30, Form("N: %4.0f", nPar1));
	    ts->DrawLatex(0.65, 0.22, Form("#mu: %4.2f", mPar1));
	    ts->DrawLatex(0.65, 0.14, Form("#sigma: %4.2f", sPar1));
	  }
	  
	    
	  if ( under ) ts->DrawLatex(0.15, 0.48, Form("<= %i", under));			               
	  if ( over  ) ts->DrawLatex(0.75, 0.48, Form("%i =>", over ));
	  ts->SetTextColor(kBlack);
	}



	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	// Row 4
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	
	// Trim Bits
	// ----------

	TH2D *htm = new TH2D("htm", "", 80, 0., 80., 52, 0., 52.);

	c1->cd(13);
	
	gStyle->SetOptStat(0);
	h2 = (TH2D*)f->Get(Form("TrimMap_C%i;8", chipId));

        if (h2) {
	  for (int icol = 0; icol < 52; ++icol) {
	    for (int irow = 0; irow < 80; ++irow) {
	      
	      htm->SetBinContent(irow+1, icol+1, h2->GetBinContent(icol+1, irow+1));
	    }
	  }
  	  h2->SetTitle("");
	  h2->GetZaxis()->SetRangeUser(0., 16.);
	  h2->Draw("colz");
	}

	else { ++nRootFileProblems; }

	tl->DrawLatex(0.1, 0.92, "Trim Bits");


	FILE *tCalFile;
	sprintf(string, "%s/../T-calibration/TemperatureCalibration_C%i.dat", dirName, chipId);
	tCalFile = fopen(string, "r");
	char tCalDir[200];
	sprintf(tCalDir, "%s/../T-calibration", dirName);

	if ( tCalFile ) {
	
	  analyse(tCalDir, chipId);
	}
	else {

	  c1->cd(14);
	  TGraph *graph = (TGraph*)f->Get(Form("TempCalibration_C%i", chipId));
	  if ( graph ) { graph->Draw("A*"); }
	  else { ++nRootFileProblems; }
	  tl->DrawLatex(0.1, 0.92, "Temperature calibration");
	}



	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	// -- Count defects and double counting
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

	float fl0, fl1, fl2, fl3, fl4, fl5, tmp;
	int   i1, i2;
	char hname[200];

//  	TH2D *get = 0, *hget = 0, *htb0 = 0, *htb1 = 0, *htb2 = 0, *htb3 = 0, *htb4 = 0;

//  	for (int i = 1; i < 6; ++i) {
	  
//  	  get = (TH2D*)f->Get(Form("CalThresholdMap_C%i;%i", chipId, i));

//  	  if (get) {
//  	    hget = (TH2D*)get->Clone();
//  	    hget->SetName(Form("TB0C%i", i));

//  	    if (i == 1) htb0 = hget;
//  	    if (i == 2) htb1 = hget;
//  	    if (i == 3) htb2 = hget;
//  	    if (i == 4) htb3 = hget;
//  	    if (i == 5) htb4 = hget;

//  	  }
//  	}


 	TH2D *htb[5];
 	for (int i = 0; i < 5; ++i) {

 	  htb[i] = (TH2D*)f->Get(Form("CalThresholdMap_C%i;%i", chipId, i+1));
	  htb[i]->SetName(Form("tbC%i%i", chipId, i+1));
 	}

	TH2D *htthr = 0;
 	htthr = (TH2D*)f->Get(Form("VcalThresholdMap_C%d;8", chipId));

	sprintf(string, "%s/SCurve_C%i.dat", dirName, chipId);
	sCurveFile = fopen(string, "r");

	sprintf(string, "%s/phCalibrationFit_C%i.dat", dirName, chipId);
	phLinearFile = fopen(string, "r");
	
	sprintf(string, "%s/phCalibrationFitTan_C%i.dat", dirName, chipId);
	phTanhFile = fopen(string, "r");
	
	if (sCurveFile)   for (int i = 0; i < 2; i++) fgets(string, 200, sCurveFile);
	if (phLinearFile) for (int i = 0; i < 2; i++) fgets(string, 200, phLinearFile);
	if (phTanhFile)   for (int i = 0; i < 2; i++) fgets(string, 200, phTanhFile);

	int px_counted    = 0;
	int px_funct_counted    = 0;
	int px_perf_counted    = 0;
	int trim_counted    = 0;
	int ph_counted    = 0;
	float tb_diff = 0;
	float tb, tb0;
	    
	for (int icol = 0; icol < 52; ++icol) {
	  for (int irow = 0; irow < 80; ++irow) {
	    
	    pixel_alive   = 1;
	    px_funct_counted = 0;
	    px_perf_counted = 0;
	    px_counted = 0;

	    trim_counted = 0;
	    ph_counted = 0;
	    
	    // -- Pixel alive
	    if (hpm && hpm->GetBinContent(icol+1, irow+1)  == 0)  { 
	      
	      pixel_alive = 0; 
	      
	      ++nDeadPixel;   
	      cout << Form("chipSummary> dead pixel %3d %3d: %7.5f", 
			   icol, irow, hpm->GetBinContent(icol+1, irow+1)) << endl;
	    }

	    if (hpm && hpm->GetBinContent(icol+1,irow+1)  > 10) { ++nNoisy1Pixel; px_counted = 1; px_funct_counted = 1;}
	    if (hpm && hpm->GetBinContent(icol+1, irow+1)  < 0) { ++nMaskDefect;  px_counted = 1; px_funct_counted = 1;}

	    if (hpm && (hpm->GetBinContent(icol+1, irow+1) < 10) 
		  && (hpm->GetBinContent(icol+1, irow+1) > 0) ) { ++nIneffPixel;  px_counted = 1; px_funct_counted = 1;}
	    
	    
	    // -- Bump bonding
	    if ( pixel_alive && hbm ) {
	      if ( hbm->GetBinContent(icol+1, irow+1)  >= minThrDiff ) {

		if ( px_counted )      nDoubleCounts++;
		px_counted = 1;

		if ( px_funct_counted ) nDoubleFunctCounts++;
		px_funct_counted = 1;
		
		++nDeadBumps;	
		
		cout << Form("chipSummary> bump defect %3d %3d: %7.5f", 
			     icol, irow, hbm->GetBinContent(icol+1, irow+1)) << endl;
	      }
	    }
	    
	    
	    // -- Trim bits 1 - 4
	    if ( pixel_alive && htb[0] ) {

	      tb0 = htb[0]->GetBinContent(icol+1, irow+1);
	      
	      for ( int i = 1; i <= 4; i++ ) {

		if ( htb[i] ) {
		  
		  tb = htb[i]->GetBinContent(icol+1, irow+1);

		  tb_diff = TMath::Abs(tb-tb0);

		  if (tb_diff  <= 2) {
		    
		    if ( px_counted ) nDoubleCounts++;
		    px_counted = 1;
		    
		    if ( px_funct_counted ) nDoubleFunctCounts++;
		    px_funct_counted = 1;
		    
		    if ( trim_counted ) nDoubleTrims++;
		    trim_counted = 1;
		    
		    ++nDeadTrimbits;
		    
		    cout << Form("chipSummary> trim bit defect %3d %3d: %4.2f", icol, irow, tb_diff) << endl;
		  }
		}
	      }
	    }

	    // -- Address decoding
	    if (pixel_alive && ham) {

	      if( ham->GetBinContent(icol+1, irow+1) < 1 ) {

		if ( px_counted ) nDoubleCounts++;
		px_counted = 1;
		    
		if ( px_funct_counted ) nDoubleFunctCounts++;
		px_funct_counted = 1;

		++nAddressProblems;

		cout << Form("chipSummary> address problem %3d %3d: %7.5f", 
			     icol, irow, ham->GetBinContent(icol+1, irow+1)) << endl;
	      }
	    }
	    
	    // -- Threshold
	    if (pixel_alive && htthr) {

	      if ( TMath::Abs(htthr->GetBinContent(icol+1, irow+1) - vcalTrim) > tthrTol ) {

		if ( px_counted ) nDoubleCounts++;
		px_counted = 1;
		    
		if ( px_perf_counted ) nDoublePerfCounts++;
		px_perf_counted = 1;

		++nThrDefect;

		cout << Form("chipSummary> threshold problem %3d %3d: %7.5f", 
			     icol, irow, htthr->GetBinContent(icol+1, irow+1)) << endl;
	      }
	    }

	    // -- Noise
	    fscanf(sCurveFile, "%e %e %s %2i %2i", &fl1, &fl2, string, &i1, &i2);

	    if (pixel_alive) {
	      if ( (fl2 < noiseMin) 
		   || (fl2 > noiseMax) ) {
		
		if ( px_counted ) nDoubleCounts++;
		px_counted = 1;
		    
		if ( px_perf_counted ) nDoublePerfCounts++;
		px_perf_counted = 1;
		
		++nNoisy2Pixel; 

		cout << Form("chipSummary> noise defect %3d %3d: %7.5f (%2i %2i)", 
			     icol, irow, fl2, i1, i2) << endl;
	      } 
	    }
	    
	    // -- Gain & Pedestal
	    fscanf(phLinearFile, "%e %e %e %e %e %e %s %2i %2i", 
		   &fl0, &fl1, &fl2, &fl3, &fl4, &fl5, string, &i1, &i2);

	    if (pixel_alive) {
	      
	      if (fl2 != 0) gain = 1./fl2;
	      ped = fl3;

	      if ( (gain < gainMin) || (gain > gainMax) ) {
		
		if ( px_counted ) nDoubleCounts++;
		px_counted = 1;
		    
		if ( px_perf_counted ) nDoublePerfCounts++;
		px_perf_counted = 1;

		if ( ph_counted ) nDoublePHs++;
		ph_counted = 1;

		++nGainDefect;

		cout << Form("chipSummary> gain defect %3d %3d: %7.5f (%2i %2i)", 
			     icol, irow, gain, i1, i2) << endl;
	      }

	      if ( (ped < pedMin) 
		   || (ped > pedMax) ) {
		
		if ( px_counted ) nDoubleCounts++;
		px_counted = 1;

		if ( px_perf_counted ) nDoublePerfCounts++;
		px_perf_counted = 1;

		if ( ph_counted ) nDoublePHs++;
		ph_counted = 1;

		++nPedDefect;

		cout << Form("chipSummary> pedestal defect %3d %3d: %7.5f (%2i %2i)", 
			     icol, irow, ped, i1, i2) << endl;
	      }
		
	      
	    }
	    

	    // -- Par1
	    fscanf(phTanhFile, "%e %e %e %e %s %2i %2i", 
		   &fl0, &fl1, &fl2, &fl3, string, &i1, &i2);
	    
	    if (pixel_alive && phTanhFile) {
	      
	      if ( (fl1 < par1Min) 
		   || (fl1 > par1Max) ) {
		
		if ( px_counted ) nDoubleCounts++;
		px_counted = 1;

		if ( px_perf_counted ) nDoublePerfCounts++;
		px_perf_counted = 1;

		if ( ph_counted ) nDoublePHs++;
		ph_counted = 1;

		++nPar1Defect;

		cout << Form("chipSummary> par1 defect %3d %3d: %7.5f (%2i %2i)", 
			     icol, irow, par1, i1, i2) << endl;
	      }
	    }
	    
	  }
	}
			
	fclose(sCurveFile); 
	fclose(phLinearFile);
	fclose(phTanhFile);
	      

	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	// Numerics and Titles
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

	// -- Compute the final verdict on this chip  //?? FIXME (below is pure randomness)
	float finalVerdict(0);
	if (nDeadTrimbits > 0)    finalVerdict += 1;
	if (nDeadPixel > 0)       finalVerdict += 10;
	if (nNoisy1Pixel > 0)     finalVerdict += 10;
	if (nAddressProblems > 0) finalVerdict += 10;
	if (nDeadBumps > 0)       finalVerdict += 100;
	if (nNoisy2Pixel > 0)     finalVerdict += 1000;
	if (nThrDefect > 0)       finalVerdict += 10000;
	if (nGainDefect > 0)      finalVerdict += 100000;
	if (nPedDefect > 0)       finalVerdict += 100000;
	if (nPar1Defect > 0)      finalVerdict += 100000;

	// -- Defects
	c1->cd(8);
	tl->SetTextSize(0.10);
	tl->SetTextFont(22);
	double y = 0.98;

	y -= 0.11;
	tl->DrawLatex(0.1, y, "Summary");
// 	tl->DrawLatex(0.6, y, Form("%06d", finalVerdict));

	tl->SetTextFont(132);
	tl->SetTextSize(0.09);
	y -= 0.11;
	tl->DrawLatex(0.1, y, Form("Dead Pixels: "));
	tl->DrawLatex(0.7, y, Form("%4d", nDeadPixel));

// 	y -= 0.10;
// 	tl->DrawLatex(0.1, y, Form("Noisy Pixels 1: "));
// 	tl->DrawLatex(0.7, y, Form("%4d", nNoisy1Pixel));
	
	y -= 0.10;
	tl->DrawLatex(0.1, y, "Mask defects: ");
	tl->DrawLatex(0.7, y, Form("%4d", nMaskDefect));

	y -= 0.10;
	tl->DrawLatex(0.1, y, "Dead Bumps: ");
	tl->DrawLatex(0.7, y, Form("%4d", nDeadBumps));

	y -= 0.10;
	tl->DrawLatex(0.1, y, "Dead Trimbits: ");
	tl->DrawLatex(0.7, y, Form("%4d", nDeadTrimbits));

	y -= 0.10;
	tl->DrawLatex(0.1, y, "Address Probl: ");
	tl->DrawLatex(0.7, y, Form("%4d", nAddressProblems));

	y -= 0.10;
	tl->DrawLatex(0.1, y, Form("Noisy Pixels 2: "));
	tl->DrawLatex(0.7, y, Form("%4d", nNoisy2Pixel));

	y -= 0.10;
	tl->DrawLatex(0.1, y, Form("Trim Probl.: "));
	tl->DrawLatex(0.7, y, Form("%4d", nThrDefect));

	y -= 0.10;
	tl->DrawLatex(0.1, y, Form("PH defects: "));
	tl->DrawLatex(0.5, y, Form("%4d/", nGainDefect));

	tl->SetTextColor(kRed);
	tl->DrawLatex(0.6, y, Form("%4d/",nPedDefect));
	tl->SetTextColor(kBlack);

	tl->SetTextColor(kBlue);
	tl->DrawLatex(0.7, y, Form("%4d",nPar1Defect));
	tl->SetTextColor(kBlack);

// 	y -= 0.10;
// 	tl->DrawLatex(0.1, y, Form("Par1 defect: "));
// 	tl->DrawLatex(0.7, y, Form("%4d", nPar1Defect));


	// -- Operation Parameters
	c1->cd(16);
	
	y = 0.92;
	tl->SetTextSize(0.10);
	tl->SetTextFont(22);
	y -= 0.11;
	tl->DrawLatex(0.1, y, Form("Op. Parameters"));

	tl->SetTextFont(132);
	tl->SetTextSize(0.09);

	y -= 0.11;
	int vana(-1.);
        vana = dac_findParameter(dirName, "Vana", chipId);
	tl->DrawLatex(0.1, y, "VANA: ");
	if (vana >= 0.) tl->DrawLatex(0.6, y, Form("%3i DAC", vana));
	else tl->DrawLatex(0.7, y, "N/A");

	y -= 0.10;
	int caldel(-1.);
        caldel = dac_findParameter(dirName, "CalDel", chipId);
	tl->DrawLatex(0.1, y, "CALDEL: ");
	if (vana >= 0.) tl->DrawLatex(0.6, y, Form("%3d DAC", caldel));
	else tl->DrawLatex(0.7, y, "N/A");

	y -= 0.10;
	int vthrcomp(-1.);
        vthrcomp = dac_findParameter(dirName, "VthrComp", chipId);
	tl->DrawLatex(0.1, y, "VTHR: ");
	if (vana >= 0.) tl->DrawLatex(0.6, y, Form("%3d DAC", vthrcomp));
	else tl->DrawLatex(0.7, y, "N/A");

	y -= 0.10;
	int vtrim(-1.);
        vtrim = dac_findParameter(dirName, "Vtrim", chipId);
	tl->DrawLatex(0.1, y, "VTRIM: ");
	if (vana >= 0.) tl->DrawLatex(0.6, y, Form("%3d DAC", vtrim));
	else tl->DrawLatex(0.7, y, "N/A");
	
	y -= 0.10;
	int ibias(-1.);
        ibias = dac_findParameter(dirName, "Ibias_DAC", chipId);
	tl->DrawLatex(0.1, y, "IBIAS_DAC: ");
	if (vana >= 0.) tl->DrawLatex(0.6, y, Form("%3d DAC", ibias));
	else tl->DrawLatex(0.7, y, "N/A");
       
	y -= 0.10;
	int voffset(-1.);
        voffset = dac_findParameter(dirName, "VoffsetOp", chipId);
	tl->DrawLatex(0.1, y, "VOFFSETOP: ");
	if (vana >= 0.) tl->DrawLatex(0.6, y, Form("%3d DAC", voffset));
	else tl->DrawLatex(0.7, y, "N/A");

	// -- Page title
	c1->cd(0);
	tl->SetTextSize(0.04);
	tl->SetTextFont(22);
	tl->DrawLatex(0.02, 0.97, Form("%s (C%i)", noslash.Data(), chipId));

	TDatime date;
	tl->SetTextSize(0.02);
	tl->DrawLatex(0.75, 0.97, Form("%s", date.AsString()));

	c1->SaveAs(Form("%s/chipSummary_C%i.ps", dirName, chipId));
	c1->SaveAs(Form("%s/C%i.png", dirName, chipId));
		

	// -- Dump into logfile
	ofstream OUT(Form("%s/summary_C%i.txt", dirName, chipId));
	OUT << "nDeadPixel: "         << nDeadPixel << endl;
	OUT << "nNoisy1Pixel: "       << nNoisy1Pixel << endl;
	OUT << "nDeadTrimbits: "      << nDeadTrimbits << endl;
	OUT << "nDeadBumps: "         << nDeadBumps << endl;
	OUT << "nMaskDefect: "        << nMaskDefect << endl;
	OUT << "nAddressProblems: "   << nAddressProblems << endl;
	OUT << "nNoisy2Pixel: "       << nNoisy2Pixel << endl;
	OUT << "nTThrDefect: "        << nThrDefect << endl;
	OUT << "nGainDefect: "        << nGainDefect << endl;
	OUT << "nPedDefect: "         << nPedDefect << endl;
	OUT << "nParDefect: "         << nPar1Defect << endl;
	OUT << "nDoubleCounts: "      << nDoubleCounts << endl;
	OUT << "nDoubleFunctCounts: " << nDoubleFunctCounts << endl;
	OUT << "nDoublePerfCounts: "  << nDoublePerfCounts << endl;
	OUT << "nDoubleTrims: "       << nDoubleTrims << endl;
	OUT << "nDoublePHs: "         << nDoublePHs << endl;
        OUT << "nRootFileProblems: "  << nRootFileProblems << endl;
	OUT << "SCurve "              << nN_entries    << " " << mN << " " << sN << endl;
	OUT << "Threshold "           << nV_entries    << " " << mV  << " " << sV << endl;
	OUT << "Gain "                << nG_entries    << " " << mG << " " << sG << endl;
	OUT << "Pedestal "            << nP_entries    << " " << mP << " " << sP << endl;
	OUT << "Parameter1 "          << nPar1_entries << " " << mPar1 << " " << sPar1 << endl;
	OUT.close();
	
}
Exemple #26
0
void compIsol(int varnum)
{
  TString varname, vartitle;
  if(varnum==1) {
    varname="hHEIsoPt";
    vartitle="H/E Isolation";
  }
  if(varnum==2) {
    varname="hHcalIsoPt";
    vartitle="HCAL Isolation";
  }
  if(varnum==3) {
    varname="hEcalIsoPt";
    vartitle="ECAL Isolation";
  }
  if(varnum==4) {
    varname="hTrkIsoPt";
    vartitle="Track Isolation";
  }
  if(varnum==5) {
    varname="hJetEt";
    vartitle="Jet E_{T} [GeV]";
  }
  if(varnum==6) {
    varname="hNJets";
    vartitle="Number of Jets";
  }
  
  
  TH1D* hBorn;
  TH1D* hADD;
  if(varnum<=4) {
    TH2D* hBorn2d = dynamic_cast<TH2D*>(GetPlot(1, varname));
    TH2D* hADD2d = dynamic_cast<TH2D*>(GetPlot(3, varname));
    hBorn = hBorn2d->ProjectionX(varname+"born");
    hADD = hADD2d->ProjectionX(varname+"add");
    cout << "asdf" << endl;
  } else {
    hBorn = dynamic_cast<TH1D*>(GetPlot(1, varname));
    hADD = dynamic_cast<TH1D*>(GetPlot(3, varname));
  }
  
  hBorn->Scale(1/hBorn->GetSumOfWeights());
  hADD->Scale(1/hADD->GetSumOfWeights());

  hBorn->SetLineColor(kBlue+2);
  hADD->SetLineColor(kCyan+4);
  hBorn->SetFillColor(0);
  hADD->SetFillColor(0);
  hBorn->SetLineStyle(1);
  hADD->SetLineStyle(2);
  
  //  hBorn->SetStats(0);
  //  hADD->SetStats(0);

  gPad->SetLogy(1);
  
  hBorn->GetXaxis()->SetTitle(vartitle);
  hBorn->GetYaxis()->SetTitle("Normalized Units");
  hBorn->SetTitle("Leading Photons in Pythia/Sherpa Samples");

  hBorn->Draw();
  hADD->Draw("sames");

  hBorn->SetMaximum(1);

  gPad->Update();
  TPaveStats *st1=(TPaveStats*)hBorn->GetListOfFunctions()->FindObject("stats");
  TPaveStats *st2=(TPaveStats*)hADD->GetListOfFunctions()->FindObject("stats");
  st1->SetName("Born");
  st2->SetName("ADD");
  st1->SetOptStat(101100);
  st2->SetOptStat(101100);
  st1->SetX1NDC(.25);
  st1->SetX2NDC(.55);
  st1->SetY1NDC(.56);
  st1->SetY2NDC(.80);
  st2->SetX1NDC(.56);
  st2->SetX2NDC(.86);
  st2->SetY1NDC(.56);
  st2->SetY2NDC(.80);

  TLegend* leg=new TLegend(.25,.78,.55,.85);
  leg->AddEntry(hBorn, "Pythia (Born)", "l");
  leg->SetBorderSize(0);
  leg->SetFillColor(0);
  leg->SetTextSize(0.045);
  leg->Draw();

  TLegend* leg=new TLegend(.56,.78,.86,.85);
  leg->AddEntry(hADD, "Sherpa (ADD)", "l");
  leg->SetBorderSize(0);
  leg->SetFillColor(0);
  leg->SetTextSize(0.045);
  leg->Draw();

  gPad->Update();
  

  return;
}
void get_nn_ptpt_FROM_FB_TREE() // TString inputFileName = "MergedOutput.root")
{
    //            TFile *myFile = new TFile( "/Users/macbook/alice/aliceAnalysis/results/task_2016_02_09_PbPb_Data_AOD_3etaWins_phi1_pt02_20_FB_TREE_blocks123/block1/AnalysisResults.139465.root" );
    TFile *myFile = new TFile( "/Users/macbook/alice/aliceAnalysis/results/task_2016_02_21_PbPb_Data_AOD_3etaWins_phi1_pt02_20_FB_TREE_TEST_NEW_DATA_5_02TeV_tryAOD2/MergedOutput.root" );
    if (!myFile)
    {
        cout << "No input file!" << endl;
        return;
    }
    myFile->ls();
    TList *listKeys = myFile->GetListOfKeys();
    cout << "going into list: " << listKeys->At(1)->GetName() << endl;

    //return;
    myFile->cd( listKeys->At(1)->GetName() );
    TList *listKeys2 = gDirectory->GetListOfKeys();
    TList *myTask = (TList*) gDirectory->Get( listKeys2->At(0)->GetName() );
    TTree *t1 = (TTree*)  myTask->FindObject( "treeFB" );


    //    cout << t1->GetEntries() << endl;
    //t1->Print();
    //return;
    //    TFile *f = new TFile( "file_event_tree_merged_impPar_2files.root" );
    //    TTree *t1 = (TTree*) f->Get( "t1" );

    //    TFile *f = new TFile( "output_1_list.grid.root" );
    //    TList *list = (TList*) f->Get( "coutput_V0_mult_0.000000_100000.000000" );
    //    TTree *t1 = (TTree*) list->FindObject( "t1" );

    //other vars:
    //    const int nVars = 3;
    //    TString strVarName[] = {
    //        "centr_V0M" ,
    //        "centr_CL1" ,
    //        "centr_ZEMvsZDC"     ,
    //    };
    //    Float_t varBranch[nVars];

    //    for(Int_t var = 0; var < nVars; var++)
    //        t1->SetBranchAddress(strVarName[var],&varBranch[var]);

    Float_t brV0M;
    //    t1->SetBranchAddress( "centr_V0M", &brV0M );
    t1->SetBranchAddress( "centrV0M_NEW_MULT_SEL", &brV0M );

    Float_t brZEMvsZDC;
    t1->SetBranchAddress( "centr_ZEMvsZDC", &brZEMvsZDC );

    //        const int nCW = 1; //nCentrWidths
    //        const double cWidths[nCW] = { 10 }; //width of the centrality bins
    //        const double cStep[nCW] = { 5 }; //centrality bins step
    //        const int nCentrBins[nCW] = { 17 }; //n centrality bins

//    const int nCW = 2; //nCentrWidths
//    const double cWidths[nCW] = { 10, 5.001 }; //width of the centrality bins
//    const double cStep[nCW] = { 5, 2.5 }; //centrality bins step
//    const int nCentrBins[nCW] = { 17, 35 }; //n centrality bins

    const int nCW = 2; //nCentrWidths
    const double cWidths[nCW] = { 10, 5 }; //width of the centrality bins
    const double cStep[nCW] = { 10, 5 }; //centrality bins step
    const int nCentrBins[nCW] = { 9, 18 }; //n centrality bins


    //    const int nCW = 5; //nCentrWidths
    //    const double cWidths[nCW] = { 10, 5, 2.5, 1.0, 0.5 }; //width of the centrality bins
    //    const double cStep[nCW] = { 5, 2.5, 2.5, 1.0, 1.0 }; //centrality bins step
    //    const int nCentrBins[nCW] = { 17, 35, 36, 90, 90 }; //n centrality bins

    const int nEtaWins = 3;
    const int nPhiWins = 1;

    const int maxNCentrBins = 100; //TMath::MaxElement(nCW, &nCentrBins);
    WinPair wins[nCW][maxNCentrBins][nEtaWins][nPhiWins];
    CentralityOccupancy cOccupancy[nCW][maxNCentrBins];

    for ( int cW = 0; cW < nCW; cW++ )
        for ( int cBin = 0; cBin < nCentrBins[cW]; cBin++ )
        {
            float cBinMin = cStep[cW] * cBin;
            float cBinMax = cWidths[cW] + cStep[cW] * cBin;

            cOccupancy[cW][cBin].cBinMin = cBinMin;
            cOccupancy[cW][cBin].cBinMax = cBinMax;

            for ( int etaW = 0; etaW < nEtaWins; etaW++ )
                for ( int phiW = 0; phiW < nPhiWins; phiW++ )
                    wins[cW][cBin][etaW][phiW].init(cBinMin, cBinMax, etaW, phiW);
        }


    BranchFB br[nEtaWins][nPhiWins];

    for ( int etaW = 0; etaW < nEtaWins; etaW++ )
        for ( int phiW = 0; phiW < nPhiWins; phiW++ )
        {
            int ptW = 0;
            TString brNamePostfix = Form("eta_%d_phi%d_pt_%d"
                                         , etaW, phiW, ptW );
            t1->SetBranchAddress( Form("nF_%s", brNamePostfix.Data() ),  &br[etaW][phiW].nF );
            t1->SetBranchAddress( Form("nB_%s", brNamePostfix.Data() ),  &br[etaW][phiW].nB );
            t1->SetBranchAddress( Form("PtF_%s", brNamePostfix.Data() ), &br[etaW][phiW].PtF );
            t1->SetBranchAddress( Form("PtB_%s", brNamePostfix.Data() ), &br[etaW][phiW].PtB );
        }



    TH1D *hist1D_QA_percentilesEstimator = new TH1D( "hist1D_QA_percentilesEstimator", "hist1D_QA_percentilesEstimator;percentile;entries", 3001, -0.5, 300.5);
    TH1D *hist1D_QA_multALL = new TH1D( "hist1D_QA_multALL", "hist1D_QA_multALL;mult;entries", 3001, -0.5, 3000.5);


    // ##### prepare for tree loop
    int nEvents = t1->GetEntries();
    cout <<"nEvents = " << nEvents << endl;

    //    float **BS_Nf = new float*[nPhiWins];
    //    float **BS_Nb = new float*[nPhiWins];
    //    for ( int w = 0; w < nPhiWins; w++ )
    //    {
    //        BS_Nf[w] = new float[nEvents];
    //        BS_Nb[w] = new float[nEvents];
    //    }

    // ##### main loop over events
    int flag_V0M_ZDC = 0;//1;
    int nAccepted = 0;
    for (Long64_t i=0; i < nEvents; i++)
    {
        if ( i % 100000 == 0 )
            cout << "getting " << (int)i << endl;
        //                cout <<"getting " << (int)i << "\r"; cout.flush();

        t1->GetEntry( i );
        //            t1->GetEntry( TMath::Nint( gRandom->Uniform(-0.5,nEvents-0.5) ) );

        float cEstimator = -1;
        if ( flag_V0M_ZDC==0 )
        {
            if ( brV0M > 90 ) //V0M cut
                continue;
            cEstimator = brV0M;
        }
        else
        {
            if ( brZEMvsZDC > 50 ) //ZDCvsZEM cut
                continue;
            cEstimator = brZEMvsZDC;
        }
        hist1D_QA_percentilesEstimator->Fill(cEstimator);


        //calc mult in whole TPC using wins:
        int multTPC = 0;
        for ( int phiW = 0; phiW < nPhiWins; phiW++ )
            multTPC += (br[0][phiW].nF + br[2][phiW].nF) + (br[0][phiW].nB + br[2][phiW].nB);
        hist1D_QA_multALL->Fill(multTPC);


        //        for ( int w = 0; w < nPhiWins; w++ )
        //        {
        //            BS_Nf[w][nAccepted] = Nf[w];
        //            BS_Nb[w][nAccepted] = Nb[w];
        //        }

        for ( int cW = 0; cW < nCW; cW++ )
            for ( int cBin = 0; cBin < nCentrBins[cW]; cBin++ )
            {
                cOccupancy[cW][cBin].fill(brV0M, brZEMvsZDC);
                for ( int etaW = 0; etaW < nEtaWins; etaW++ )
                    for ( int phiW = 0; phiW < nPhiWins; phiW++ )
                        wins[cW][cBin][etaW][phiW].fill( cEstimator, br[etaW][phiW].nF, br[etaW][phiW].nB, br[etaW][phiW].PtF, br[etaW][phiW].PtB );
            }

        nAccepted++;


    } // end of events
    cout << "nAccepted = " << nAccepted << endl;
    cout << "nAccepted/nAll = " << (float)nAccepted/nEvents << endl;


    // ########## QA PLOTTING:
    TCanvas *canv_estimatorPercentiles_QA_all = new TCanvas("canv_estimatorPercentiles_QA_all","canv_estimatorPercentiles_QA_all",0,0,700,600 );
    hist1D_QA_percentilesEstimator->DrawCopy();

    TCanvas *canv_hist1D_QA_multALL = new TCanvas("canv_hist1D_QA_multALL","canv_hist1D_QA_multALL",50,50,700,600 );
    hist1D_QA_multALL->DrawCopy();


    // MULT BINNING:
    int nCentrBinsMult = 10;
    cout << "nCentrBins=" << nCentrBinsMult << endl;
    double *estBounds = new double[nCentrBinsMult]; // array to contain the quantiles
    getQuantiles(hist1D_QA_multALL, nCentrBinsMult, estBounds);
    drawCanvasWithClasses( hist1D_QA_multALL, "byMultTPC", nCentrBinsMult, estBounds );




    // ##########MAIN PLOTTING FOR CORRS:

    TGraphErrors *grNN [nCW][nEtaWins];
    TGraphErrors *grPtPt[nCW][nEtaWins];
    TGraphErrors *grPtN[nCW][nEtaWins];

    TGraphErrors *grFractEstByV0M[nCW];
    TGraphErrors *grFractEstByZDC[nCW];

    for ( int cW = 0; cW < nCW; cW++ )
    {
        grFractEstByV0M[cW] = new TGraphErrors;
        grFractEstByZDC[cW] = new TGraphErrors;
        for ( int etaW = 0; etaW < nEtaWins; etaW++ )
        {
            grNN[cW][etaW] = new TGraphErrors;
            grPtPt[cW][etaW] = new TGraphErrors;
            grPtN[cW][etaW] = new TGraphErrors;
        }
    }


    //calc (1) - occupancies in centr bins, (2) - corr coeffs
    for ( int cW = 0; cW < nCW; cW++ )
        for ( int cBin = 0; cBin < nCentrBins[cW]; cBin++ )
        {
            if ( cOccupancy[cW][cBin].nEventsV0M > 0 )
            {
                CentralityOccupancy *c = &cOccupancy[cW][cBin];
                float centr = c->cBinMin + (c->cBinMax - c->cBinMin)/2;
                float cRatio = 0;
                if (c->nEventsV0M>0)
                    cRatio = (float)c->nEventsV0M_and_ZDCZEM / c->nEventsV0M;
                grFractEstByV0M[cW]->SetPoint(grFractEstByV0M[cW]->GetN(), centr, cRatio);
                if (c->nEventsZDCZEM>0)
                    cRatio = (float)c->nEventsV0M_and_ZDCZEM / c->nEventsZDCZEM;
                grFractEstByZDC[cW]->SetPoint(grFractEstByZDC[cW]->GetN(), centr, cRatio);
            }
            for ( int etaW = 0; etaW < nEtaWins; etaW++ )
                for ( int phiW = 0; phiW < nPhiWins; phiW++ )
                {
                    WinPair *w = &wins[cW][cBin][etaW][phiW];
                    float centr = w->cBinMin + (w->cBinMax - w->cBinMin)/2;
                    w->calcCorrCoeffs();
                    if(0)cout << "cMin=" << w->cBinMin << ", cMax=" << w->cBinMax << ", etaW=" << etaW
                              << ", NN_bCorr= " << w->NN_bCorr
                              << ", PtPt_bCorr= " << w->PtPt_bCorr
                              << endl;

                    //fill graphs
                    TGraphErrors *gr;
                    //gr NN
                    gr = grNN[cW][etaW];
                    if ( fabs(w->NN_bCorr) < 10 )
                        gr->SetPoint(gr->GetN(), centr, w->NN_bCorr);
                    //gr PtPt
                    gr = grPtPt[cW][etaW];
                    if ( fabs(w->PtPt_bCorr) < 10 )
                        gr->SetPoint(gr->GetN(), centr, w->PtPt_bCorr);
                    //gr PtN
                    gr = grPtN[cW][etaW];
                    if ( fabs(w->PtN_bCorr) < 10 )
                        gr->SetPoint(gr->GetN(), centr, w->PtN_bCorr);

                }
        }

    int colors[] = { kBlack, kBlack, kBlue, kRed, kMagenta };
    int markers[] = { 20, 24, 5, 2, 21 };

    // NN
    TCanvas *canv_grNN = new TCanvas("canv_grNN","canv_grNN",20,50,700,600 );
    tuneCanvas(canv_grNN);
    grNN[0][0]->SetTitle( ";centrality percentile;b_{corr}" ); //C_{2}
    tuneGraphAxisLabels(grNN[0][0]);


    //centr 10
    drawGraph(grNN[0][0], 20, kBlack, "AP");
    //    drawGraph(grNN[0][1], 21, kBlack, "P");
    //    drawGraph(grNN[0][2], 22, kBlack, "P");

    for ( int cW = 1; cW < nCW; cW++ )
        drawGraph(grNN[cW][0], markers[cW], colors[cW], "P");

    grNN[0][0]->SetMinimum( 0 );

    TLegend *leg = new TLegend(0.65,0.65,0.999,0.95);
    leg->SetFillColor(kWhite);
    leg->SetFillStyle(0);
    leg->SetBorderSize(0);
    for ( int cW = 0; cW < nCW; cW++ )
        leg->AddEntry(grNN[cW][0], Form("class width %.1f", cWidths[cW]), "p");
    leg->Draw();

    TLatex *tex = new TLatex(0.7,0.4, "#eta_{gap}=0.8, #delta#eta=0.4");
    drawTex(tex, 0.045);

    tex = new TLatex(0.4,0.89, "NN");
    drawTex(tex, 0.045);


    TString strPostfix;

    if (flag_V0M_ZDC==0)
        strPostfix = Form("V0M.eps");
    else
        strPostfix = Form("ZDCZEM.eps");

    canv_grNN->SaveAs( Form("NN_%s", strPostfix.Data() ) );

    // PtPt
    TCanvas *canv_grPtPt = new TCanvas("canv_grPtPt","canv_grPtPt",250,50,700,600 );
    tuneCanvas(canv_grPtPt);
    grPtPt[0][0]->SetTitle( ";centrality percentile;b_{corr}" ); //C_{2}
    tuneGraphAxisLabels(grPtPt[0][0]);


    //centr 10
    drawGraph(grPtPt[0][0], 20, kBlack, "AP");
    //    drawGraph(grPtPt[0][1], 21, kBlack, "P");
    //    drawGraph(grPtPt[0][2], 22, kBlack, "P");

    for ( int cW = 1; cW < nCW; cW++ )
        drawGraph(grPtPt[cW][0], markers[cW], colors[cW], "P");

    grPtPt[0][0]->SetMinimum( 0 );

    leg = new TLegend(0.65,0.65,0.999,0.95);
    leg->SetFillColor(kWhite);
    leg->SetFillStyle(0);
    leg->SetBorderSize(0);
    for ( int cW = 0; cW < nCW; cW++ )
        leg->AddEntry(grPtPt[cW][0], Form("class width %.1f", cWidths[cW]), "p");
    leg->Draw();

    tex = new TLatex(0.7,0.4, "#eta_{gap}=0.8, #delta#eta=0.4");
    drawTex(tex, 0.045);

    tex = new TLatex(0.4,0.89, "PtPt");
    drawTex(tex, 0.045);


    canv_grNN->SaveAs( Form("PtPt_%s", strPostfix.Data() ) );

    // PtN
    TCanvas *canv_grPtN = new TCanvas("canv_grPtN","canv_grPtN",450,50,700,600 );
    tuneCanvas(canv_grPtN);
    grPtN[0][0]->SetTitle( ";centrality percentile;b_{corr}" ); //C_{2}
    tuneGraphAxisLabels(grPtN[0][0]);


    //centr 10
    drawGraph(grPtN[0][0], 20, kBlack, "AP");
    //    drawGraph(grPtN[0][1], 21, kBlack, "P");
    //    drawGraph(grPtN[0][2], 22, kBlack, "P");

    for ( int cW = 1; cW < nCW; cW++ )
        drawGraph(grPtN[cW][0], markers[cW], colors[cW], "P");

    grPtN[0][0]->SetMinimum( 0 );
    leg = new TLegend(0.65,0.65,0.999,0.95);
    leg->SetFillColor(kWhite);
    leg->SetFillStyle(0);
    leg->SetBorderSize(0);
    for ( int cW = 0; cW < nCW; cW++ )
        leg->AddEntry(grPtN[cW][0], Form("class width %.1f", cWidths[cW]), "p");
    leg->Draw();

    tex = new TLatex(0.7,0.4, "#eta_{gap}=0.8, #delta#eta=0.4");
    drawTex(tex, 0.045);

    tex = new TLatex(0.4,0.89, "PtN");
    drawTex(tex, 0.045);


    canv_grNN->SaveAs( Form("PtN_%s", strPostfix.Data() ) );



    TCanvas *canv_grPtN_2D = new TCanvas("canv_grPtN_2D","canv_grPtN_2D",450,50,700,600 );
    tuneCanvas(canv_grPtN_2D);


    //    wins[0][0][0][0].hist2D_PtN->DrawCopy();
    wins[0][0][0][0].hist2D_PtN->ProfileX()->DrawCopy();



    // CENTR ESTIMATOR EVENT RATIO:
    TCanvas *canv_grCentrRatio = new TCanvas("canv_grCentrRatio","canv_grCentrRatio",450,250,700,600 );
    tuneCanvas(canv_grCentrRatio);
    grFractEstByV0M[0]->SetTitle(";centrality percentile;ratio");
    tuneGraphAxisLabels(grFractEstByV0M[0]);
    //centr 10
    drawGraph(grFractEstByV0M[0], 20, kBlack, "AP");
    //    drawGraph(grFractEstByZDC[0], 20, kBlack, "L");

    for ( int cW = 1; cW < nCW; cW++ )
        drawGraph(grFractEstByV0M[cW], markers[cW], colors[cW], "P");

    leg = new TLegend(0.65,0.65,0.999,0.95,"ratio #frac{V0M-and-ZEMZDC}{V0M}");
    leg->SetFillColor(kWhite);
    leg->SetFillStyle(0);
    leg->SetBorderSize(0);

    for ( int cW = 0; cW < nCW; cW++ )
        leg->AddEntry(grFractEstByV0M[cW], Form("class width %.1f", cWidths[cW]), "p");
    leg->Draw();
    //    leg->SetHeader("ratio #frac{V0M-and-ZEMZDC}/{V0M}");

    canv_grCentrRatio->SaveAs("ratio_V0M-and-ZEMZDC_by_V0M.eps");

    // CENTR ESTIMATOR PERCENTILES QA:
    TCanvas *canv_estimatorPercentiles_QA = new TCanvas("canv_estimatorPercentiles_QA","canv_estimatorPercentiles_QA",50,350,700,600 );
    for ( int cBin = 0; cBin < nCentrBins[0]; cBin++ )
    {
        TH1D *h = wins[0][cBin][0][0].hist1D_EstimatorEntries;
        h->SetLineColor(kOrange-9+cBin);
        if ( cBin == 0 )
            h->DrawCopy();
        else
            h->DrawCopy("same");
    }


    // MULT F IN CENTR CLASSES QA:
    TCanvas *canv_mult_F_in_centr_QA = new TCanvas("canv_mult_F_in_centr_QA","canv_mult_F_in_centr_QA",50,400,700,600 );
    gPad->SetLogy();
    for ( int cBin = 0; cBin < nCentrBins[0]; cBin++ )
    {
        TH1D *h = wins[0][cBin][0][0].hist1D_multDistrF;
        h->SetLineColor(kOrange-9+cBin);

        if ( cBin == 0 )
        {
            h->SetLineColor(kRed);
            h->GetYaxis()->SetRangeUser(1,100000);
        }

        if ( cBin == 0 )
            h->DrawCopy();
        else
            h->DrawCopy("same");
    }


    // Check entries in centrality bins:
    for ( int cW = 0; cW < nCW; cW++ )
    {
        cout << " ###### cW = " << cW << endl;
        for ( int cBin = 0; cBin < nCentrBins[cW]; cBin++ )
        {
            TH1D *h = wins[cW][cBin][0][0].hist1D_multDistrF;
            cout << "cBin = " << h->GetEntries() << endl;
//            h->SetLineColor(kOrange-9+cBin);
//            if ( cBin == 0 )
//                h->DrawCopy();
//            else
//                h->DrawCopy("same");
        }
    }

    return;
}
Exemple #28
0
void DrawPileupCorrVsMuNPV(Str jetAlgo) {
  JetCalibrationTool *theJES = new JetCalibrationTool(jetAlgo,_jesFile);
  bool residual = theJES->JetAreaJES();

  TH1D *tempNPV = new TH1D("","",12,0,20);
  TH1D *tempmu  = new TH1D("","",15,0,25);
  tempNPV->SetXTitle("Number of vertices, #it{N}_{PV}");
  tempmu->SetXTitle("Average number of interactions, #LT#it{#mu}#GT"); 
  double etaBins[] = {0, 0.3, 0.8, 1.2, 2.1, 2.8, 3.2, 3.6, 4.5};
  Str tit=residual?"Residual jet offset":"Jet offset";
  tempNPV->SetYTitle(tit+" at "+GetConstScale(jetAlgo)+"-scale [GeV]");
  tempmu->SetYTitle(tit+" at "+GetConstScale(jetAlgo)+"-scale [GeV]");
  tempNPV->SetMinimum(-8); tempNPV->SetMaximum(8); tempNPV->SetStats(0); 
  tempNPV->GetYaxis()->SetTitleOffset(1.0); tempNPV->GetXaxis()->SetTitleOffset(1.0);
  tempmu->SetMinimum(-8); tempmu->SetMaximum(8); tempmu->SetStats(0); 
  tempmu->GetYaxis()->SetTitleOffset(1.0); tempmu->GetXaxis()->SetTitleOffset(1.0);
  if (residual && theJES->ResidualOffsetCorr_Description()=="") return;

  Can->Clear(); tempNPV->Draw();
  for (int ei=0;ei<5;++ei) {
    double eta=0.5;
    if (ei==1) eta=1.0;
    if (ei==2) eta=2.0;
    if (ei==3) eta=3.0;
    if (ei==4) eta=4.0;
    Graph *g = new Graph();
    FormatGraph(g,ei);
    for (int npv=1;npv<=20;++npv)
      if (residual)
	g->SetPoint(g->GetN(),npv,theJES->GetResidualOffset(eta,0.0,npv)/1000);
      else
	g->SetPoint(g->GetN(),npv,theJES->GetOffset(eta,0.0,npv)/1000);
    g->Draw("PL");
  }
  DrawLabel("0.3 #leq |#eta| < 0.8",0.7,0.37,0);
  DrawLabel("0.8 #leq |#eta| < 1.2",0.7,0.37-0.05,1);
  DrawLabel("2.1 #leq |#eta| < 2.8",0.7,0.37-0.1,2);
  DrawLabel("2.8 #leq |#eta| < 3.2",0.7,0.37-0.15,3);
  DrawLabel("3.6 #leq |#eta| < 4.5",0.7,0.37-0.2,4);
  tex->SetNDC(); tex->SetTextAlign(12);
  //tex->DrawLatex(0.18,0.975,myJES->OffsetCorr_Description());
  int jetR=jetAlgo.Contains("Kt4")?4:6;
  tex->DrawLatex(0.18,0.9,Form("Anti-k_{t} #it{R} = 0.%d, %s+JES",jetR,GetConstScale(jetAlgo).Data()));
  Can->Print(ps); 
  
  Can->Clear(); tempmu->Draw();
  for (int ei=0;ei<5;++ei) {
    double eta=0.5;
    if (ei==1) eta=1.0;
    if (ei==2) eta=2.0;
    if (ei==3) eta=3.0;
    if (ei==4) eta=4.0;
    Graph *g = new Graph();
      FormatGraph(g,ei);
      for (int mu=0;mu<=25;++mu) 
	if (residual)
	  g->SetPoint(g->GetN(),mu,theJES->GetResidualOffset(eta,mu,1)/1000);
	else
	  g->SetPoint(g->GetN(),mu,theJES->GetOffset(eta,mu,1)/1000);
      g->Draw("PL");
  }
  DrawLabel("0.3 #leq |#eta| < 0.8",0.2,0.37,0);
  DrawLabel("0.8 #leq |#eta| < 1.2",0.2,0.37-0.05,1);
  DrawLabel("2.1 #leq |#eta| < 2.8",0.2,0.37-0.1,2);
  DrawLabel("2.8 #leq |#eta| < 3.2",0.2,0.37-0.15,3);
  DrawLabel("3.6 #leq |#eta| < 4.5",0.2,0.37-0.2,4);
  tex->SetNDC(); tex->SetTextAlign(12);
  //tex->DrawLatex(0.18,0.975,myJES->OffsetCorr_Description());
  tex->DrawLatex(0.18,0.9,Form("Anti-k_{t} #font[52]{R} = 0.%d, %s+JES",jetR,GetConstScale(jetAlgo).Data()));
  Can->Print(ps);
}
Exemple #29
0
int MC_Ratio(int leptonId, double par_low, double par_upp, int nbins, TString sel_den , TString sel_num, double cut_den = 0., double cut_num = 0., TString par_x = "Pt", TString option = ""){

	setTDRStyle();

	///////////////
	//Get the TTree
	///////////////

	//Location of the .root file
	TString location = "/Users/GLP/Desktop/CERN_data/2014-11-13_skim2ll-mva-softbtag/postprocessed/";

	//Reading the tree 
	//
	TChain* tree = new TChain("treeProducerSusyMultilepton");

	//DY events
	tree->Add(location+"DYJetsToLLM50_PU_S14_POSTLS170.root");

	//Plot the result

	Long64_t n = tree->GetEntries();

	//Path for input and output file. Written in FitDataPath.txt
	TString _path = "/Users/GLP/Dropbox/Physique/Master_Thesis/plots_root/MC_ratio/";

	//////////////////////
	//Name for the plots//
	//////////////////////

	TString pname;
	TString _pname;
	TString _par;
	TString _sel_num;
	TString _sel_den;
	TString _cut_den;
	TString _option;

	//Writing string
	if (leptonId == 11) {pname = "e";_pname = "e";}
	else if (leptonId == 13){pname = " #mu";_pname = "mu";}
	if(par_x == "Pt"){_par = "P_{t}";}
	else if(par_x == "eta"){_par = "#eta";}
	else if(par_x == "phi"){_par = "#phi";}
	else{cout<<"ERROR: wrong parameter name !";return 1;}
	if(sel_num == ""){_sel_num = "unsel";}
	else if(sel_num == "tight"){_sel_num = "tight";}
	else if(sel_num == "tightmva"){_sel_num = "tightmva";}
	if((sel_num == "tightmva")&&(leptonId == 13)){cout<<"ERROR: no tightId MVA defined for the muon !";return 1;}
	//else if(sel_num == "mvaid"){_sel_num = Form("tightmva%0.3lf",cut_num) ;}
	else if(sel_num == "loose"){_sel_num = "loose";}
	else if(sel_num == "reliso3"){_sel_num = Form("reliso3_%0.3lf",cut_num);}
	else if(sel_num == "reliso4"){_sel_num = Form("reliso4_%0.3lf",cut_num);}
	else if(sel_num == "chiso3"){_sel_num = Form("chiso3_%0.3lf",cut_num);}
	else if(sel_num == "chiso4"){_sel_num = Form("chiso4_%0.3lf",cut_num);}
	else if(sel_num == "dxy"){_sel_num = Form("dxy_%0.3lf",cut_num);}
	else if(sel_num == "dz"){_sel_num = Form("dz_%0.3lf",cut_num);}
	else{cout<<"ERROR: wrong numerator name !";return 1;}
	//Selection on the denominator
	if(sel_den == ""){_sel_den = "unsel";}
	else if(sel_den == "tight"){_sel_den = "tight";}
	else if(sel_den == "tightmva"){_sel_den = "tightmva";}
	if((sel_den == "tightmva")&&(leptonId == 13)){cout<<"ERROR: no tightId MVA defined for the muon !";return 1;}
	//else if(sel_den == "mvaid"){_sel_den = Form("tightmva%0.3lf",cut_den) ;}
	else if(sel_den == "loose"){_sel_den = "loose";}
	else{cout<<"ERROR: wrong denominator selection name !";return 1;}
	option.Append(" ");
	option.Prepend(" ");
	if(option.Contains(" ll ")){_option += "_ll";}
	if(option.Contains(" unmatched ")){_option += "_unmatched";}
	if(option.Contains(" alleta ")){_option += "_alleta";}
	_option += "_";

	//Name of the output

	//TString _fname = file_name("eff3",leptonId, par_low,par_upp,sel_den,sel_num,cut_den,cut_num,par_x,option);
	//TString _output= _path+_fname + ".root";
	TString _output = _path+"eff4"+_option+_pname+"_den_"+_sel_den+"_num_"+_sel_num+"_"+par_x+".root";

	//Declaration of histogram
	
	//
	//Preparation for general range in eta/pt
	//TH1D **histo_num = new TH1D*[nrange];
	//TH1D **histo_den = new TH1D*[nrange];
	//TH1D **eff = new TH1D*[nrange];
	//int nrange = 3;
	//double par2[nrange] = {0,1.2,2.4};
	//for(int _i = 0; _i < nrange; ++_i){ 

	//	//Barrel
	//	histo_num[_i] = new TH1D("histo_num","Pt",nbins,min(par_low,0.),par_upp);
	//	histo_den[_i] = new TH1D("histo_den","Pt",nbins,min(par_low,0.),par_upp);
	//	eff[_i] = new TH1D("eff","Pt",nbins,min(par_low,0.),par_upp);
	//	
	//}
	
	
	//efficiency of the isolation cut
	TH1D *histo_numB= new TH1D("histo_numB","Pt",nbins,min(par_low,0.),par_upp);
	TH1D *histo_denB= new TH1D("histo_denB","Pt",nbins,min(par_low,0.),par_upp);
	TH1D *histo_numE= new TH1D("histo_numE","Pt",nbins,min(par_low,0.),par_upp);
	TH1D *histo_denE= new TH1D("histo_denE","Pt",nbins,min(par_low,0.),par_upp);

	//Histo in all eta region
	TH1D *histo_num= new TH1D("histo_num","Pt",nbins,min(par_low,0.),par_upp);
	TH1D *histo_den= new TH1D("histo_den","Pt",nbins,min(par_low,0.),par_upp);

	//efficiency of the selection
	TH1D* effB = new TH1D ("effB","Pt",nbins,min(par_low,0.),par_upp);
	TH1D* effE = new TH1D ("effE","Pt",nbins,min(par_low,0.),par_upp);

	//efficiency all eta 
	TH1D* eff = new TH1D ("eff","Pt",nbins,min(par_low,0.),par_upp);k
	//Event variables
	Int_t evt_id;
	Float_t scale;
	//Generated
	Float_t gen_phi[200];
	Float_t gen_eta[200];
	Float_t Pt[200];
	Float_t m[200];
	Int_t Id[200];
	Int_t Mo[200];
	Float_t charge[200];
	Int_t status[200];
	Int_t GrMa[200];
	Int_t ngenPart;
	Int_t source[200];
	Int_t pile_up;
	//not loose
	Int_t On;
	Int_t Oid[200];
	Float_t Opt[200];
	Float_t Om[200];
	Float_t Oeta[200];
	Float_t Ophi[200];
	Int_t   Oq[200];
	Int_t Otight[200];
	Int_t Otighte[200];
	//Float_t Omvaid[200];
	Int_t Oloose[200];
	Float_t Oiso3[200];
	Float_t Oiso4[200];
	Float_t Ochiso3[200];
	Float_t Ochiso4[200];
	Float_t Odxy[200];
	Float_t Odz[200];
	//loose
	Int_t Gn;
	Int_t Gid[200];
	Float_t Gpt[200];
	Float_t Gm[200];
	Float_t Geta[200];
	Float_t Gphi[200];
	Int_t   Gq[200];
	Int_t Gtight[200];
	Int_t Gtighte[200];
	//Float_t Gmvaid[200];
	Int_t Gloose[200];
	Float_t Giso3[200];
	Float_t Giso4[200];
	Float_t Gchiso3[200];
	Float_t Gchiso4[200];
	Float_t Gdxy[200];
	Float_t Gdz[200];

	//Assigne branches tree->SetBranchAddress("evt_scale1fb", &scale);
	tree->SetBranchAddress("evt_id", &evt_id);
	//generated
	tree->SetBranchAddress("ngenLep", &ngenPart);
	tree->SetBranchAddress("genLep_pdgId", &Id);
	tree->SetBranchAddress("genLep_sourceId", &source);
	tree->SetBranchAddress("genLep_eta", &gen_eta);
	tree->SetBranchAddress("genLep_phi", &gen_phi);
	tree->SetBranchAddress("genLep_pt", &Pt);
	tree->SetBranchAddress("genLep_mass", &m);
	tree->SetBranchAddress("genLep_charge", &charge);
	tree->SetBranchAddress("genLep_status", &status);
	tree->SetBranchAddress("nTrueInt",&pile_up);
	//not loose
	tree->SetBranchAddress("nLepOther",&On);
	tree->SetBranchAddress("LepOther_pdgId",&Oid);
	tree->SetBranchAddress("LepOther_pt",&Opt);
	tree->SetBranchAddress("LepOther_mass",&Om);
	tree->SetBranchAddress("LepOther_eta",&Oeta);
	tree->SetBranchAddress("LepOther_phi",&Ophi);
	tree->SetBranchAddress("LepOther_charge",&Oq);
	tree->SetBranchAddress("LepOther_tightId",&Otight);
	tree->SetBranchAddress("LepOther_eleCutIdCSA14_50ns_v1",&Otighte);
	//tree->SetBranchAddress("LepOther_mvaId",&Omvaid);
	tree->SetBranchAddress("LepOther_looseIdSusy",Oloose);
	tree->SetBranchAddress("LepOther_relIso03",&Oiso3);
	tree->SetBranchAddress("LepOther_relIso04",&Oiso4);
	tree->SetBranchAddress("LepOther_chargedHadRelIso03",&Ochiso3);
	tree->SetBranchAddress("LepOther_chargedHadRelIso04",&Ochiso4);
	tree->SetBranchAddress("LepOther_dxy",&Odxy);
	tree->SetBranchAddress("LepOther_dz",&Odz);
	//Loose
	tree->SetBranchAddress("nLepGood",&Gn);
	tree->SetBranchAddress("LepGood_pdgId",&Gid);
	tree->SetBranchAddress("LepGood_pt",&Gpt);
	tree->SetBranchAddress("LepGood_mass",&Gm);
	tree->SetBranchAddress("LepGood_eta",&Geta);
	tree->SetBranchAddress("LepGood_phi",&Gphi);
	tree->SetBranchAddress("LepGood_charge",&Gq);
	tree->SetBranchAddress("LepGood_tightId",&Gtight);
	tree->SetBranchAddress("LepGood_eleCutIdCSA14_50ns_v1",&Gtighte);
	//tree->SetBranchAddress("LepGood_mvaId",&Gmvaid);
	tree->SetBranchAddress("LepGood_looseIdSusy",&Gloose);
	tree->SetBranchAddress("LepGood_relIso03",&Giso3);
	tree->SetBranchAddress("LepGood_relIso04",&Giso4);
	tree->SetBranchAddress("LepGood_chargedHadRelIso03",&Gchiso3);
	tree->SetBranchAddress("LepGood_chargedHadRelIso04",&Gchiso4);
	tree->SetBranchAddress("LepGood_dxy",&Gdxy);
	tree->SetBranchAddress("LepGood_dz",&Gdz);

	int count = 0;

	//Start loop over all events
	for (int k = 0; k < 100000; ++k) {

		if( 100*(double)k/n> count){cout<<count<<endl;++count;}

		tree->GetEntry(k);

		//loop on loose 
	if(sel_den != "loose"){
		for(int j=0; j<On;++j){
			if((!option.Contains(" ll "))||((option.Contains(" ll "))&&(On == 2)&&(Oid[0] == -Oid[1]))){
				if(abs(Oid[j]) == leptonId){
					if((sel_den != "tight")||((sel_den == "tight")&&(Otight[j] == 1 ))){
					//if((sel_den != "mvaid")||((sel_den == "mvaid")&&(abs(Omvaid[j]) > cut_den))){
						//Veto the EE-EB gape

						//Variable for matching
						double R = 999;
						double delta_P = 999;
						double delta_charge = 999;

						//Parameter on the xaxis

						double par;

						//loop over all generated particles to do the matching
						for (int i = 0; i < ngenPart; ++i) {
							if((abs(Id[i]) == leptonId)&&(status[i]== 1)){ 

								//Electrons selection
								double R2 = DeltaR(gen_eta[i],Oeta[j],gen_phi[i],Ophi[j] );

								//Minimise DeltaR and Fill the other variables
								if (R > R2) {

									R = R2;
									delta_P = abs(Opt[j]-Pt[i])/Pt[i];
									delta_charge = abs(Oq[j] - charge[i]);
								}
							}
						}

						//Choose the parameter to be filled for the eff.
						if(par_x == "Pt"){par = Opt[j];}
						else if(par_x == "eta"){par = Oeta[j];}
						else if(par_x == "phi"){par = Ophi[j];}

						//Fill Pt only for matched events
						if(((R<0.1)&&(delta_P < 0.2)&&(delta_charge < 0.5))||option.Contains("unmat")){
							//Filling the den
									if(option.Contains(" alleta ")){
											histo_den->Fill(par);
											}else{
							if(abs(Oeta[j]) < 1.2){histo_denB->Fill(par);}
							if(abs(Oeta[j]) >= 1.2){histo_denE->Fill(par);}
											}

							//Additional cut on the numerator
							int a = 0;

							if((sel_num == "tight")&&(Otight[j] == 1)){a = 1;}
							if((sel_num == "reliso3")&&(Oiso3[j] <= cut_num)){a = 2;}
							if((sel_num == "reliso4")&&(Oiso4[j] <= cut_num)){a = 3;}
							if((sel_num == "chiso3")&&(Ochiso3[j] <= cut_num)){a = 4;}
							if((sel_num == "chiso4")&&(Ochiso4[j] <= cut_num)){a = 5;}
							if((sel_num == "dxy")&&(abs(Odxy[j]) <= cut_num)){a = 6;}
							if((sel_num == "dz")&&(abs(Odz[j]) <= cut_num)){a = 7;}
							//Never filled here
							if(sel_num == "loose"){a = 8;}
							//cout<<"again, the mva value is"<<abs(Omvaid[j])<<endl;
							//if((sel_num == "mvaid")&&(abs(Omvaid[j]) >= cut_num)){a = 9;}
			

							switch(a){

								case 0:

									break;

								case 1:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
											if(abs(Oeta[j]) < 1.2){histo_numB->Fill(par);}
											if(abs(Oeta[j]) >= 1.2){histo_numE->Fill(par);};
											}
									break;

								case 2:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
									if(abs(Oeta[j]) < 1.2)histo_numB->Fill(par);
									if(abs(Oeta[j]) >= 1.2)histo_numE->Fill(par);
											}
									break;
								case 3:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
									if(abs(Oeta[j]) < 1.2)histo_numB->Fill(par);
									if(abs(Oeta[j]) >= 1.2)histo_numE->Fill(par);
											}
									break;
								case 4:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
									if(abs(Oeta[j]) < 1.2)histo_numB->Fill(par);
									if(abs(Oeta[j]) >= 1.2)histo_numE->Fill(par);
											}
									break;
								case 5:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
									if(abs(Oeta[j]) < 1.2)histo_numB->Fill(par);
									if(abs(Oeta[j]) >= 1.2)histo_numE->Fill(par);
											}
									break;
								case 6:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
									if(abs(Oeta[j]) < 1.2)histo_numB->Fill(par);
									if(abs(Oeta[j]) >= 1.2)histo_numE->Fill(par);
											}
									break;

								case 7:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
									if(abs(Oeta[j]) < 1.2)histo_numB->Fill(par);
									if(abs(Oeta[j]) >= 1.2)histo_numE->Fill(par);
											}
									break;

								case 8:
									//Nothing to fill
									break;

								case 9:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
									if(abs(Oeta[j]) < 1.2)histo_numB->Fill(par);
									if(abs(Oeta[j]) >= 1.2)histo_numE->Fill(par);
											}
									break;
							}
						}
					}
				}
			}
		}
	}
	//}

		//loop on tight 
		for(int j=0; j<Gn;++j){
			if((!option.Contains(" ll "))||((option.Contains(" ll "))&&(Gn == 2)&&(Gid[0] == -Gid[1]))){
				if(abs(Gid[j]) == leptonId){
					//Cut on the denominator
					if((sel_den != "tight")||((sel_den == "tight")&&(Gtight[j] == 1 ))){
					//if((sel_den != "mvaid")||((sel_den == "mvaid")&&(abs(Gmvaid[j]) > cut_den))){
						//Veto the EE-EB gape

						//Variable for matching
						double R = 999;
						double delta_P = 999;
						double delta_charge = 999;

						//Parameter on the xaxis

						double par;

						//loop over all generated particles to do the matching
						for (int i = 0; i < ngenPart; ++i) {
							if((abs(Id[i]) == leptonId)&&(status[i]== 1)){ 

								//Electrons selection
								double R2 = DeltaR(gen_eta[i],Geta[j],gen_phi[i],Gphi[j] );

								//Minimise DeltaR and Fill the other variables
								if (R > R2) {

									R = R2;
									delta_P = abs(Gpt[j]-Pt[i])/Pt[i];
									delta_charge = abs(Gq[j] - charge[i]);
								}
							}
						}

						//Choose the parameter to be filled for the eff.
						if(par_x == "Pt"){par = Gpt[j];}
						else if(par_x == "eta"){par = Geta[j];}
						else if(par_x == "phi"){par = Gphi[j];}

						//Fill Pt only for matched events
						if(((R<0.1)&&(delta_P < 0.2)&&(delta_charge < 0.5))||option.Contains("unmat")){
							//Filling the den
									if(option.Contains(" alleta ")){
											histo_den->Fill(par);
											}else{
							if(abs(Geta[j]) < 1.2){histo_denB->Fill(par);}
							if(abs(Geta[j]) >= 1.2){histo_denE->Fill(par);}
											}

							//Additional cut on the numerator
							int a = 0;

							if((sel_num == "tight")&&(Gtight[j] == 1)){a = 1;}
							if((sel_num == "reliso3")&&(Giso3[j] <= cut_num)){a = 2;}
							if((sel_num == "reliso4")&&(Giso4[j] <= cut_num)){a = 3;}
							if((sel_num == "chiso3")&&(Gchiso3[j] <= cut_num)){a = 4;}
							if((sel_num == "chiso4")&&(Gchiso4[j] <= cut_num)){a = 5;}
							if((sel_num == "dxy")&&(abs(Gdxy[j]) <= cut_num)){a = 6;}
							if((sel_num == "dz")&&(abs(Gdz[j]) <= cut_num)){a = 7;}
							//Only loose leptons here, so this is filled anyway
							if((sel_num == "loose")){a = 8;}
							//if((sel_num == "mvaid")&&(abs(Gmvaid[j]) >= cut_num)){a = 9;}


							switch(a){

								case 0:

									break;

								case 1:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
									if(abs(Geta[j]) < 1.2){histo_numB->Fill(par);}
									if(abs(Geta[j]) >= 1.2){histo_numE->Fill(par);}
											}
									break;

								case 2:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
									if(abs(Geta[j]) < 1.2)histo_numB->Fill(par);
									if(abs(Geta[j]) >= 1.2)histo_numE->Fill(par);
											}
									break;
								case 3:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
									if(abs(Geta[j]) < 1.2)histo_numB->Fill(par);
									if(abs(Geta[j]) >= 1.2)histo_numE->Fill(par);
											}
									break;
								case 4:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
									if(abs(Geta[j]) < 1.2)histo_numB->Fill(par);
									if(abs(Geta[j]) >= 1.2)histo_numE->Fill(par);
											}
									break;
								case 5:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
									if(abs(Geta[j]) < 1.2)histo_numB->Fill(par);
									if(abs(Geta[j]) >= 1.2)histo_numE->Fill(par);
											}
									break;
								case 6:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
									if(abs(Geta[j]) < 1.2)histo_numB->Fill(par);
									if(abs(Geta[j]) >= 1.2)histo_numE->Fill(par);
											}
									break;

								case 7:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
									if(abs(Geta[j]) < 1.2)histo_numB->Fill(par);
									if(abs(Geta[j]) >= 1.2)histo_numE->Fill(par);
											}
									break;

								case 8:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
									if(abs(Geta[j]) < 1.2)histo_numB->Fill(par);
									if(abs(Geta[j]) >= 1.2)histo_numE->Fill(par);
											}
									break;

								case 9:
									if(option.Contains(" alleta ")){
											histo_num->Fill(par);
											}else{
									if(abs(Geta[j]) < 1.2)histo_numB->Fill(par);
									if(abs(Geta[j]) >= 1.2)histo_numE->Fill(par);
											}
									break;
							}
						}
					}
				}
			}
		}
	}
	//}

	if(option.Contains(" alleta ")){
	histo_num->Sumw2();
	histo_den->Sumw2();

	//Divide histograms to get the efficiency
	eff->Divide(histo_num,histo_den,1,1,"B"); 

	//Efficiency of the iso cut.
	TCanvas* c = new TCanvas("c","c");
	eff->Draw();
	eff->GetYaxis()->SetTitle("#epsilon");
	eff->GetXaxis()->SetTitle(_par);
	//eff->GetXaxis()->SetRangeUser(0,250);
	eff->SetMarkerStyle(20);
	eff->SetMarkerSize(1);
	eff->SetMarkerColor(4);
	eff->SetLineColor(4);
	eff->SetTitle(_sel_num+" for "+_sel_den+" "+pname);

	//Define the name of the canvas
	TString cname = "eff4"+option+_pname+"_den_"+_sel_den+"_num_"+_sel_num+"_"+par_x;

	c->SaveAs(_path+"PDF/"+cname+".pdf");

	TFile* output = new TFile(_output,"recreate");
	eff->Write("eff");
	output->Close();

	}else{
		//cout<<"Problem"<<endl;

	histo_numB->Sumw2();
	histo_numE->Sumw2();
	histo_denB->Sumw2();
	histo_denE->Sumw2();

	//Divide histograms to get the efficiency
	effB->Divide(histo_numB,histo_denB,1,1,"B"); 
	effE->Divide(histo_numE,histo_denE,1,1,"B"); 

	//Efficiency of the iso cut.
	TCanvas* c1 = new TCanvas("c1","c1");
	effB->Draw();
	effB->GetYaxis()->SetTitle("#epsilon");
	effB->GetXaxis()->SetTitle(_par);
	//effB->GetXaxis()->SetRangeUser(0,250);
	effB->SetMarkerStyle(20);
	effB->SetMarkerSize(1);
	effB->SetMarkerColor(4);
	effB->SetLineColor(4);
	effB->SetTitle(_sel_num+" for "+_sel_den+" "+pname+" #||{#eta}<1.2");
	TCanvas* c2 = new TCanvas("c2","c2");
	effE->Draw();
	effE->GetYaxis()->SetRangeUser(0,1.1);
	effE->GetYaxis()->SetTitle("#epsilon");
	effE->GetXaxis()->SetTitle(_par);
	//effE->GetXaxis()->SetRangeUser(0,250);
	effE->SetMarkerStyle(20);
	effE->SetMarkerSize(1);
	effE->SetMarkerColor(4);
	effE->SetLineColor(4);
	effE->SetTitle(_sel_num+" for "+_sel_den+" "+pname+" #||{#eta}>1.2");

	//Define the name of the canvas
	TString c1name = "eff4"+option+_pname+"_den_"+_sel_den+"_num_"+_sel_num+"_"+par_x+"_eta<1.2";
	TString c2name = "eff4"+option+_pname+"_den_"+_sel_den+"_num_"+_sel_num+"_"+par_x+"_eta>1.2";

	c1->SaveAs(_path+"PDF/"+c1name+".pdf");
	c2->SaveAs(_path+"PDF/"+c2name+".pdf");

	TFile* output = new TFile(_output,"recreate");
	//c1->Write();
	//c2->Write();
	effB->Write("eff_eta<1.2");
	effE->Write("eff_eta>1.2");
	output->Close();

	}

	return 0;

}
void drawDCAcontamination(){
gStyle->SetOptStat(0);
    TFile * file = TFile::Open("/Users/sandrobjelogrlic/Analysis/HFCorrelations/Results/MCCE/83_12022015/10f7a/AnalysisResults.root");
    
    TDirectoryFile * dir = (TDirectoryFile*)file->Get("PWGHF_HFCJ_SE_EffY_DEffY_vsPt_32_bins_SE_RECO_reco_2_348_sigmas");
    TList * list = (TList*)dir->Get("OutputMCSE_RECO");
    
    TH1D * isPhysPrimDCA = (TH1D*)list->FindObject("isPhysPrimDCA");
    TH1D * isSecondaryDCA = (TH1D*)list->FindObject("isSecondaryDCA");
    
    isPhysPrimDCA->GetXaxis()->SetRangeUser(0,2);
    
    isPhysPrimDCA->SetLineColor(2);
    isSecondaryDCA->SetLineColor(4);
     isPhysPrimDCA->SetTitle("; DCA_{XY} (cm); Counts");
    isPhysPrimDCA->GetYaxis()->SetTitleOffset(1.2);
    
    TPaveText * PaveText = new TPaveText(0.5,0.55,0.8,0.7,"NDC");
    PaveText->SetBorderSize(0);
    PaveText->SetFillColor(0);
    PaveText->SetName("pave");
   // PaveText->AddText("THIS THESIS");
   // PaveText->AddText(" ");
    PaveText->AddText("Phytia, pp #sqrt{s} = 7 TeV");
    //PaveText->AddText(" ");
   // PaveText->AddText("Fraction of Primary tracks as funct");
    
    TLine * cut = new TLine(0.25,0,0.25,10000000);
    cut->SetLineStyle(2);
    
    TLegend * legend = new TLegend(0.4,0.7,0.8,0.85);
    //  TLegend * legend = new TLegend(0.1, 1.2*DStarPeak->GetBinContent(DStarPeak->GetMaximumBin()),0.4, 1.6*DStarPeak->GetBinContent(DStarPeak->GetMaximumBin()));
    legend->SetFillColor(0);
    legend->SetTextSize(0.03);
    
    legend->SetBorderSize(0);
    legend->AddEntry(isPhysPrimDCA,"Primary tracks","l");
    legend->AddEntry(isSecondaryDCA,"Secondary tracks","l");
    legend->AddEntry(cut,"Standard cut, DCA_{XY} < 0.25 cm","l");
    //legend->AddEntry(h_Perugia2011,"Pythia, Perugia 2011 tune","lep");
    
    
    
    
    TCanvas * c1 = new TCanvas("c1","c1",0,0,1000,1000);
    c1->cd();
    c1->SetLogy();
    isPhysPrimDCA->Draw();
    isSecondaryDCA->Draw("same");
    legend->Draw("same");
    PaveText->Draw("same");
    cut->Draw("same");
    
    
    
   // cout << "Integral is " << getIntegral(DCA,isPhysPrimDCA) << endl;
    TLegend * legend2 = new TLegend(0.4,0.7,0.8,0.85);
    //  TLegend * legend = new TLegend(0.1, 1.2*DStarPeak->GetBinContent(DStarPeak->GetMaximumBin()),0.4, 1.6*DStarPeak->GetBinContent(DStarPeak->GetMaximumBin()));
    legend2->SetFillColor(0);
    legend2->SetTextSize(0.03);
    
    legend2->SetBorderSize(0);
 
    legend2->AddEntry(cut,"Standard cut, DCA_{XY} < 0.25 cm","l");
    
    TPaveText * PaveText2 = new TPaveText(0.5,0.3,0.8,0.5,"NDC");
    PaveText2->SetBorderSize(0);
    PaveText2->SetFillColor(0);
    PaveText2->SetName("pave2");
    // PaveText->AddText("THIS THESIS");
    // PaveText->AddText(" ");
    PaveText2->AddText("PYTHIA, pp #sqrt{s} = 7 TeV");
    TH1D * contamination = (TH1D*)isPhysPrimDCA->Clone("contamination");
    contamination->Reset();
    contamination->SetTitle("; DCA_{XY} (cm); Purity");
    
    contamination->GetYaxis()->SetRangeUser(0.8,1.05);
    contamination->GetXaxis()->SetRangeUser(0,1);
    contamination->SetLineColor(1);
    contamination->SetLineWidth(2);
    contamination->GetYaxis()->SetTitleOffset(1.4);


    Double_t dcavalue = 0;
    
    for(Int_t k=0; k<2000; k++){
     
        dcavalue += 0.001;
        contamination->SetBinContent(k+1,getPurity(dcavalue,isPhysPrimDCA,isSecondaryDCA));
    }
    
    TLine * cut2 = new TLine(0.25,0.8,0.25,1.05);
    cut2->SetLineStyle(2);
    
    TCanvas * c2 = new TCanvas("c2","c2",0,0,1000,1000); c2->cd();
    contamination->Draw();
    PaveText2->Draw("same");
    cut2->Draw("same");
    legend2->Draw("same");
    
    
     c1->SaveAs("/Users/sandrobjelogrlic/PhD_Thesis/Figures/Chapter_3/DCADistrib.pdf");
     c1->SaveAs("/Users/sandrobjelogrlic/PhD_Thesis/Figures/Chapter_3/DCADistrib.eps");
    c1->SaveAs("/Users/sandrobjelogrlic/PhD_Thesis/Figures/Chapter_3/DCADistrib.png");
     c1->SaveAs("/Users/sandrobjelogrlic/PhD_Thesis/Figures/Chapter_3/DCADistrib.root");
    c2->SaveAs("/Users/sandrobjelogrlic/PhD_Thesis/Figures/Chapter_3/purity.pdf");
     c2->SaveAs("/Users/sandrobjelogrlic/PhD_Thesis/Figures/Chapter_3/purity.png");
     c2->SaveAs("/Users/sandrobjelogrlic/PhD_Thesis/Figures/Chapter_3/purity.eps");
     c2->SaveAs("/Users/sandrobjelogrlic/PhD_Thesis/Figures/Chapter_3/purity.root");
   
}