TH1 * YieldMean_HighExtrapolationHisto(TH1 *h, TF1 *f, Double_t max, Double_t binwidth) { /* find highest edge in histo */ Int_t binhi; Double_t hi; for (Int_t ibin = h->GetNbinsX(); ibin > 0; ibin--) { if (h->GetBinContent(ibin) != 0.) { binhi = ibin + 1; hi = h->GetBinLowEdge(ibin + 1); break; } } if(max<hi) { Printf("Warning! You should probably set a higher max value (Max = %f, hi = %f)", max, hi); return 0x0; } Int_t nbins = (max - hi) / binwidth; if(nbins<1) return 0x0; TH1 *hhi = new TH1F("hhi", "", nbins, hi, max); /* integrate function in histogram bins */ Double_t cont, err, width; for (Int_t ibin = 0; ibin < hhi->GetNbinsX(); ibin++) { width = hhi->GetBinWidth(ibin + 1); cont = f->Integral(hhi->GetBinLowEdge(ibin + 1), hhi->GetBinLowEdge(ibin + 2), (Double_t *)0, 1.e-6); err = f->IntegralError(hhi->GetBinLowEdge(ibin + 1), hhi->GetBinLowEdge(ibin + 2), (Double_t *)0, (Double_t *)0, 1.e-6); hhi->SetBinContent(ibin + 1, cont / width); hhi->SetBinError(ibin + 1, err / width); } return hhi; }
TH1 * YieldMean_LowExtrapolationHisto(TH1 *h, TF1 *f, Double_t min, Double_t binwidth) { /* find lowest edge in histo */ Int_t binlo; Double_t lo; for (Int_t ibin = 1; ibin < h->GetNbinsX() + 1; ibin++) { if (h->GetBinContent(ibin) != 0.) { binlo = ibin; lo = h->GetBinLowEdge(ibin); break; } } Int_t nbins = (lo - min) / binwidth; if(nbins<1) return 0x0; TH1 *hlo = new TH1F("hlo", "", nbins, min, lo); /* integrate function in histogram bins */ Double_t cont, err, width; for (Int_t ibin = 0; ibin < hlo->GetNbinsX(); ibin++) { width = hlo->GetBinWidth(ibin + 1); cont = f->Integral(hlo->GetBinLowEdge(ibin + 1), hlo->GetBinLowEdge(ibin + 2), (Double_t *)0, 1.e-6); err = f->IntegralError(hlo->GetBinLowEdge(ibin + 1), hlo->GetBinLowEdge(ibin + 2), (Double_t *)0, (Double_t *)0, 1.e-6); hlo->SetBinContent(ibin + 1, cont / width); hlo->SetBinError(ibin + 1, err / width); } return hlo; }
Double_t fitfulllang( char* hs ) { TH1 *h = (TH1*)gDirectory->Get(hs); if( h == NULL ){ cout << hs << " does not exist\n"; return 0; } double aa = h->GetEntries();//normalization // find peak: int ipk = h->GetMaximumBin(); double xpk = h->GetBinCenter(ipk); double sm = xpk / 9; // sigma double ns = sm; // noise // fit range: int ib0 = ipk/2; int ib9 = h->GetNbinsX() - 1; double x0 = h->GetBinLowEdge(ib0); double x9 = h->GetBinLowEdge(ib9) + h->GetBinWidth(ib9); // create a TF1 with the range from x0 to x9 and 4 parameters TF1 *fitFcn = new TF1( "fitFcn", fitLandauGauss, x0, x9, 4 ); fitFcn->SetParName( 0, "peak" ); fitFcn->SetParName( 1, "sigma" ); fitFcn->SetParName( 2, "area" ); fitFcn->SetParName( 3, "smear" ); fitFcn->SetNpx(500); fitFcn->SetLineWidth(4); fitFcn->SetLineColor(kMagenta); // set start values: fitFcn->SetParameter( 0, xpk ); // peak position, defined above fitFcn->SetParameter( 1, sm ); // width fitFcn->SetParameter( 2, aa ); // area fitFcn->SetParameter( 3, ns ); // noise h->Fit("fitFcn", "NQR", "ep" );// R = range from fitFcn return fitFcn->GetParameter(0); }
TH1 * UnfoldMe_MB2(const Char_t *data, const Char_t *mc, const Char_t *anatag, Int_t bin, Bool_t useMBcorr , Bool_t usecorrfit , Bool_t ismc , Float_t smooth , Int_t iter , Int_t regul , Float_t weight , Bool_t bayesian , Int_t nloop ) { // MF comments: // usedMBcorr: changes the matrix used for unfonding, from effMatrix to bin matrix (I think this is just to use mult dependent v s mb correction_) // usecorrfit: if I understand correctly, fits the response matrix and uses fit to extrapolate it TFile *fdt =0; if (ismc) fdt = TFile::Open(data); else fdt = TFile::Open(data); TFile *fmc = TFile::Open(mc); TList *ldt = (TList *)fdt->Get(Form("%s", anatag)); TList *lmc = (TList *)fmc->Get(Form("%s", anatag)); TH2 *hmatdt = (TH2 *)ldt->FindObject(Form(responseMatrix, bin)); TH2 *hmatmc = 0; if (useMBcorr){ hmatmc = (TH2 *)lmc->FindObject("effMatrix"); std::cout << "USING MB" << std::endl; } else { hmatmc = (TH2 *)lmc->FindObject(Form(responseMatrix, bin)); } TH1 *hdata = hmatdt->ProjectionY("hdata"); // TH1 *hdata = hmatdt->ProjectionY("htrue"); // For truth Only Calculations hdata->Sumw2(); hdata->SetBinContent(1, 0.); hdata->SetBinError(1, 0.); // hdata->Scale(1. / hdata->Integral()); hdata->SetMarkerStyle(25); TH1 *htrue = hmatdt->ProjectionX("htrue"); htrue->Sumw2(); // htrue->Scale(1. / htrue->Integral()); htrue->SetMarkerStyle(7); htrue->SetMarkerColor(2); htrue->SetBinContent(1, 0.); htrue->SetBinError(1, 0.); TH2 *hcorr = (TH2 *)hmatmc->Clone("hcorr"); TH1 *hinit = (TH1 *)hdata->Clone("hinit"); TH1 *hresu = (TH1 *)hdata->Clone("hresu"); TH1 *hbias = (TH1 *)hdata->Clone("hbias"); hresu->SetMarkerStyle(20); hresu->SetMarkerColor(4); hresu->Reset(); TH1 *hnum = hcorr->ProjectionY("hnum"); TH1 *hden = hcorr->ProjectionY("hden"); TH1 *heff = hcorr->ProjectionY("heff"); hnum->Reset(); hnum->Sumw2(); hden->Reset(); hden->Sumw2(); heff->Reset(); for (Int_t i = 0; i < heff->GetNbinsX(); i++) { Float_t int1 = hcorr->Integral(i + 1, i + 1, 0, -1); if (int1 <= 0.) continue; Float_t int2 = hcorr->Integral(i + 1, i + 1, 2, -1); hnum->SetBinContent(i + 1, int2); hnum->SetBinError(i + 1, TMath::Sqrt(int2)); hden->SetBinContent(i + 1, int1); hden->SetBinError(i + 1, TMath::Sqrt(int1)); } TCanvas *cEfficiency = new TCanvas("cEfficiency", "cEfficiency"); cEfficiency->SetLogx(); cEfficiency->SetLogy(); heff->Divide(hnum, hden, 1., 1., "B"); heff->Draw(); #if 0 for (Int_t ii = 0; ii < heff->GetNbinsX(); ii++) { heff->SetBinContent(ii + 1, 1.); heff->SetBinError(ii + 1, 0.); } #endif for (Int_t i = 0; i < hcorr->GetNbinsX(); i++) { hcorr->SetBinContent(i + 1, 1, 0.); hcorr->SetBinError(i + 1, 1, 0.); } for (Int_t i = 0; i < hcorr->GetNbinsY(); i++) { hcorr->SetBinContent(1, i + 1, 0.); hcorr->SetBinError(1, i + 1, 0.); } TH2 *hcorrfit = ReturnCorrFromFit(hcorr); // Docs from AliUnfolding //Int_t AliUnfolding::Unfold(TH2* correlation, TH1* efficiency, TH1* measured, TH1* initialConditions, TH1* result, Bool_t check) // unfolds with unfolding method fgMethodType // // parameters: // correlation: response matrix as measured vs. generated // efficiency: (optional) efficiency that is applied on the unfolded spectrum, i.e. it has to be in unfolded variables. If 0 no efficiency is applied. // measured: the measured spectrum // initialConditions: (optional) initial conditions for the unfolding. if 0 the measured spectrum is used as initial conditions. // result: target for the unfolded result // check: depends on the unfolding method, see comments in specific functions for (Int_t iloop = 0; iloop < nloop; iloop++) { if (bayesian) { AliUnfolding::SetUnfoldingMethod(AliUnfolding::kBayesian); AliUnfolding::SetBayesianParameters(smooth, iter); } else { AliUnfolding::SetUnfoldingMethod(AliUnfolding::kChi2Minimization); AliUnfolding::SetChi2Regularization(AliUnfolding::RegularizationType(regul), weight); } AliUnfolding::SetSkip0BinInChi2(kTRUE); AliUnfolding::SetSkipBinsBegin(1); AliUnfolding::SetNbins(150, 150); AliUnfolding::Unfold(usecorrfit ? hcorrfit : hcorr, heff, hdata, hinit, hresu); hinit = (TH1 *)hresu->Clone(Form("hinit_%d", iloop)); } printf("hdata->Integral(2, -1) = %f\n", hdata->Integral(2, -1)); printf("hresu->Integral(2, -1) = %f\n", hresu->Integral(2, -1)); TCanvas *cUnfolded = new TCanvas ("cUnfolded", "cUnfolded", 400, 800); cUnfolded->Divide(1, 2); cUnfolded->cd(1)->SetLogx(); cUnfolded->cd(1)->SetLogy(); hdata->Draw(); hresu->Draw("same"); htrue->Draw("same"); cUnfolded->cd(2)->SetLogx(); cUnfolded->cd(2)->DrawFrame(1., 0, 300., 10); TH1 *hrat = (TH1 *)hresu->Clone("hrat"); hrat->Divide(htrue); hrat->Draw("same"); TH1 *htrig = (TH1 *)hresu->Clone("htrig"); htrig->Multiply(heff); Float_t dndeta_resu = 0.; Float_t integr_resu = 0.; Float_t dndeta_trig = 0.; Float_t integr_trig = 0.; for (Int_t i = 1; i < hresu->GetNbinsX(); i++) { dndeta_resu += hresu->GetBinContent(i + 1) * hresu->GetBinLowEdge(i + 1); integr_resu += hresu->GetBinContent(i + 1); dndeta_trig += htrig->GetBinContent(i + 1) * htrig->GetBinLowEdge(i + 1); integr_trig += htrig->GetBinContent(i + 1); } cUnfolded->SaveAs("unfold_efficiency.pdf"); integr_eff = integr_trig / integr_resu; integr_eff_err = TMath::Sqrt(integr_eff * (1. - integr_eff) / integr_resu); dndeta_eff = dndeta_trig / dndeta_resu; dndeta_eff_err = TMath::Sqrt(dndeta_eff * (1. - dndeta_eff) / dndeta_resu); printf("INEL > 0 efficiency: %.3f +- %.3f\n", integr_eff, integr_eff_err); printf("dN/dEta correction: %.3f +- %.3f\n", dndeta_eff, dndeta_eff_err); return hresu; }
TH1 * UnfoldMe(Char_t *data, Char_t *mc, Char_t *anatag, Int_t bin, Bool_t useMBcorr = kTRUE, Bool_t usecorrfit = kFALSE, Bool_t ismc = kFALSE, Float_t smooth = 0.001, Int_t iter = 50, Int_t regul = AliUnfolding::kPowerLaw, Float_t weight = 100., Bool_t bayesian = kTRUE, Int_t nloop = 1) { if (ismc) TFile *fdt = TFile::Open(data); else TFile *fdt = TFile::Open(data); TFile *fmc = TFile::Open(mc); TList *ldt = (TList *)fdt->Get(Form("clist_%s", anatag)); TList *lmc = (TList *)fmc->Get(Form("clist_%s", anatag)); TH2 *hmatdt = (TH2 *)ldt->FindObject(Form("b%d_corrMatrix", bin)); if (useMBcorr) TH2 *hmatmc = (TH2 *)lmc->FindObject("effMatrix"); else TH2 *hmatmc = (TH2 *)lmc->FindObject(Form("b%d_corrMatrix", bin)); TH1 *hdata = hmatdt->ProjectionY("hdata"); hdata->Sumw2(); hdata->SetBinContent(1, 0.); hdata->SetBinError(1, 0.); // hdata->Scale(1. / hdata->Integral()); hdata->SetMarkerStyle(25); TH1 *htrue = hmatdt->ProjectionX("htrue"); htrue->Sumw2(); // htrue->Scale(1. / htrue->Integral()); htrue->SetMarkerStyle(7); htrue->SetMarkerColor(2); htrue->SetBinContent(1, 0.); htrue->SetBinError(1, 0.); TH2 *hcorr = (TH2 *)hmatmc->Clone("hcorr"); TH1 *hinit = (TH1 *)hdata->Clone("hinit"); TH1 *hresu = (TH1 *)hdata->Clone("hresu"); TH1 *hbias = (TH1 *)hdata->Clone("hbias"); hresu->SetMarkerStyle(20); hresu->SetMarkerColor(4); hresu->Reset(); TH1 *hnum = hcorr->ProjectionY("hnum"); TH1 *hden = hcorr->ProjectionY("hden"); TH1 *heff = hcorr->ProjectionY("heff"); hnum->Reset(); hnum->Sumw2(); hden->Reset(); hden->Sumw2(); heff->Reset(); for (Int_t i = 0; i < heff->GetNbinsX(); i++) { Float_t int1 = hcorr->Integral(i + 1, i + 1, 0, -1); if (int1 <= 0.) continue; Float_t int2 = hcorr->Integral(i + 1, i + 1, 2, -1); hnum->SetBinContent(i + 1, int2); hnum->SetBinError(i + 1, TMath::Sqrt(int2)); hden->SetBinContent(i + 1, int1); hden->SetBinError(i + 1, TMath::Sqrt(int1)); } new TCanvas("cEfficiency"); heff->Divide(hnum, hden, 1., 1., "B"); heff->Draw(); #if 0 for (Int_t ii = 0; ii < heff->GetNbinsX(); ii++) { heff->SetBinContent(ii + 1, 1.); heff->SetBinError(ii + 1, 0.); } #endif for (Int_t i = 0; i < hcorr->GetNbinsX(); i++) { hcorr->SetBinContent(i + 1, 1, 0.); hcorr->SetBinError(i + 1, 1, 0.); } for (Int_t i = 0; i < hcorr->GetNbinsY(); i++) { hcorr->SetBinContent(1, i + 1, 0.); hcorr->SetBinError(1, i + 1, 0.); } TH2 *hcorrfit = ReturnCorrFromFit(hcorr); for (Int_t iloop = 0; iloop < nloop; iloop++) { if (bayesian) { AliUnfolding::SetUnfoldingMethod(AliUnfolding::kBayesian); AliUnfolding::SetBayesianParameters(smooth, iter); } else { AliUnfolding::SetUnfoldingMethod(AliUnfolding::kChi2Minimization); AliUnfolding::SetChi2Regularization(regul, weight); } AliUnfolding::SetSkip0BinInChi2(kTRUE); AliUnfolding::SetSkipBinsBegin(1); AliUnfolding::SetNbins(150, 150); AliUnfolding::Unfold(usecorrfit ? hcorrfit : hcorr, heff, hdata, hinit, hresu); hinit = (TH1 *)hresu->Clone(Form("hinit_%d", iloop)); } printf("hdata->Integral(2, -1) = %f\n", hdata->Integral(2, -1)); printf("hresu->Integral(2, -1) = %f\n", hresu->Integral(2, -1)); TCanvas *cUnfolded = new TCanvas ("cUnfolded", "", 400, 800); cUnfolded->Divide(1, 2); cUnfolded->cd(1)->SetLogx(); cUnfolded->cd(1)->SetLogy(); hdata->Draw(); hresu->Draw("same"); htrue->Draw("same"); cUnfolded->cd(2)->SetLogx(); cUnfolded->cd(2)->DrawFrame(1., 0.75, 300., 1.25); TH1 *hrat = (TH1 *)hresu->Clone("hrat"); hrat->Divide(htrue); hrat->Draw("same"); TH1 *htrig = (TH1 *)hresu->Clone("htrig"); htrig->Multiply(heff); Float_t dndeta_resu = 0.; Float_t integr_resu = 0.; Float_t dndeta_trig = 0.; Float_t integr_trig = 0.; for (Int_t i = 1; i < hresu->GetNbinsX(); i++) { dndeta_resu += hresu->GetBinContent(i + 1) * hresu->GetBinLowEdge(i + 1); integr_resu += hresu->GetBinContent(i + 1); dndeta_trig += htrig->GetBinContent(i + 1) * htrig->GetBinLowEdge(i + 1); integr_trig += htrig->GetBinContent(i + 1); } // dndeta_resu /= integr_resu; // dndeta_trig /= integr_trig; integr_eff = integr_trig / integr_resu; integr_eff_err = TMath::Sqrt(integr_eff * (1. - integr_eff) / integr_resu); dndeta_eff = dndeta_trig / dndeta_resu; dndeta_eff_err = TMath::Sqrt(dndeta_eff * (1. - dndeta_eff) / dndeta_resu); printf("INEL > 0 efficiency: %.3f +- %.3f\n", integr_eff, integr_eff_err); printf("dN/dEta correction: %.3f +- %.3f\n", dndeta_eff, dndeta_eff_err); return hresu; }
void Fit(TString SIGNAL,TString HISTO,double scaleSGN) { gROOT->ForceStyle(); TFile *fDat = TFile::Open("Histo_flatTree_data_tmva"+SIGNAL+".root"); TFile *fBkg = TFile::Open("Histo_flatTree_qcd_weights_tmva"+SIGNAL+".root"); TFile *fSgn = TFile::Open("Histo_flatTree_"+SIGNAL+"_weights_tmva"+SIGNAL+".root"); TH1 *hDat = (TH1*)fDat->Get(HISTO); TH1 *hBkgRaw = (TH1*)fBkg->Get(HISTO); TH1 *hSgn = (TH1*)fSgn->Get(HISTO); TH1 *hDat_JESlo = (TH1*)fDat->Get(HISTO+"_JESlo"); TH1 *hBkgRaw_JESlo = (TH1*)fBkg->Get(HISTO+"_JESlo"); TH1 *hSgn_JESlo = (TH1*)fSgn->Get(HISTO+"_JESlo"); TH1 *hDat_JESup = (TH1*)fDat->Get(HISTO+"_JESup"); TH1 *hBkgRaw_JESup = (TH1*)fBkg->Get(HISTO+"_JESup"); TH1 *hSgn_JESup = (TH1*)fSgn->Get(HISTO+"_JESup"); TH1F *hBkg = (TH1F*)hBkgRaw->Clone("Bkg"); TH1F *hBkg_JESlo = (TH1F*)hBkgRaw_JESlo->Clone("Bkg_JESlo"); TH1F *hBkg_JESup = (TH1F*)hBkgRaw_JESup->Clone("Bkg_JESup"); hBkg->Smooth(2); hBkg_JESlo->Smooth(2); hBkg_JESup->Smooth(2); hSgn->Smooth(2); hSgn_JESlo->Smooth(2); hSgn_JESup->Smooth(2); double lumi = 4967; hBkg->Scale(lumi); hBkg_JESlo->Scale(lumi); hBkg_JESup->Scale(lumi); double k_factor = hDat->Integral()/hBkg->Integral(); double k_factor_JESlo = hDat->Integral()/hBkg_JESlo->Integral(); double k_factor_JESup = hDat->Integral()/hBkg_JESup->Integral(); hBkg->Scale(k_factor); cout<<"Signal entries = "<<hSgn->GetEntries()<<endl; hSgn->Scale(lumi/scaleSGN); hBkg_JESlo->Scale(k_factor_JESlo); hSgn_JESlo->Scale(lumi/scaleSGN); hBkg_JESup->Scale(k_factor_JESup); hSgn_JESup->Scale(lumi/scaleSGN); hSgn_JESlo->Scale(hSgn->Integral()/hSgn_JESlo->Integral()); hSgn_JESup->Scale(hSgn->Integral()/hSgn_JESup->Integral()); TH1 *hBkg_STATlo = (TH1*)hBkg->Clone(HISTO+"_STATlo"); TH1 *hSgn_STATlo = (TH1*)hSgn->Clone(HISTO+"_STATlo"); TH1 *hBkg_STATup = (TH1*)hBkg->Clone(HISTO+"_STATup"); TH1 *hSgn_STATup = (TH1*)hSgn->Clone(HISTO+"_STATup"); float y1,e1; for(int i=0;i<hBkg->GetNbinsX();i++) { y1 = hBkg->GetBinContent(i+1); e1 = hBkg->GetBinError(i+1); hBkg_STATlo->SetBinContent(i+1,y1-e1); hBkg_STATup->SetBinContent(i+1,y1+e1); y1 = hSgn->GetBinContent(i+1); e1 = hSgn->GetBinError(i+1); hSgn_STATlo->SetBinContent(i+1,y1-e1); hSgn_STATup->SetBinContent(i+1,y1+e1); } hBkg_STATlo->Scale(hBkg->Integral()/hBkg_STATlo->Integral()); hBkg_STATup->Scale(hBkg->Integral()/hBkg_STATup->Integral()); hSgn_STATlo->Scale(hSgn->Integral()/hSgn_STATlo->Integral()); hSgn_STATup->Scale(hSgn->Integral()/hSgn_STATup->Integral()); double xMIN = hBkg->GetBinLowEdge(1); double xMAX = hBkg->GetBinLowEdge(hBkg->GetNbinsX()+1); double xMIN2 = hDat->GetBinLowEdge(hDat->FindFirstBinAbove(0.5)); double xMAX2 = hDat->GetBinLowEdge(hDat->FindLastBinAbove(0.5)+1); RooRealVar x("x","x",xMIN2,xMAX2); RooDataHist data("data","dataset with x",x,hDat); RooDataHist bkg("qcd","bkg with x",x,hBkg); RooDataHist sgn("signal","sgn with x",x,hSgn); RooHistPdf bkgPDF("bkgPDF","bkgPDF",x,bkg,0); RooHistPdf sgnPDF("sgnPDF","sgnPDF",x,sgn,0); RooRealVar f("f","f",0,0.,1.); RooAddPdf model("model","model",RooArgList(sgnPDF,bkgPDF),RooArgList(f)); RooFitResult* r = model.fitTo(data,Save()); r->Print("v"); double N = hDat->Integral(); double B = hBkg->Integral(); double S = hSgn->Integral(); double m = f.getVal(); double e = f.getError(); cout<<"k-factor = "<<k_factor<<endl; cout<<N<<" "<<B<<" "<<S<<endl; cout<<"Total cross section = "<<N/lumi<<" pb"<<endl; cout<<"Model cross section = "<<S/lumi<<" pb"<<endl; cout<<"Fitted signal strength = "<<m*N/S<<endl; cout<<"Fitted signal error = "<<e*N/S<<endl; double p = 0.95; double xup = (N/S)*(m+sqrt(2.)*e*TMath::ErfInverse((1-p)*TMath::Erf(m/e)+p)); cout<<"Bayesian Upper limit = "<<xup<<endl; RooPlot* frame1 = x.frame(); data.plotOn(frame1); model.plotOn(frame1,Components("sgnPDF*"),LineStyle(1),LineWidth(2),LineColor(kGreen+1)); model.plotOn(frame1,Components("bkgPDF*"),LineStyle(1),LineWidth(2),LineColor(kRed)); model.plotOn(frame1,LineStyle(1),LineWidth(2),LineColor(kBlue)); //cout<<frame1->chiSquare()<<endl; RooHist* hresid = frame1->residHist(); RooHist* hpull = frame1->pullHist(); RooPlot* frame2 = x.frame(Title("Residual Distribution")); frame2->addPlotable(hresid,"P") ; // Create a new frame to draw the pull distribution and add the distribution to the frame RooPlot* frame3 = x.frame(Title("Pull Distribution")); frame3->addPlotable(hpull,"P"); TCanvas* cFit = new TCanvas("fitANN_"+SIGNAL,"fitANN_"+SIGNAL,900,600); gPad->SetLogy(); frame1->SetMaximum(1e+4); frame1->SetMinimum(0.5); frame1->GetXaxis()->SetTitle("ANN Output"); frame1->GetYaxis()->SetTitle("Events"); frame1->Draw(); cout<<frame1->nameOf(3)<<endl; TLegend *leg = new TLegend(0.7,0.65,0.9,0.9); leg->SetHeader(SIGNAL); leg->AddEntry(frame1->findObject("h_data"),"data","P"); leg->AddEntry(frame1->findObject("model_Norm[x]"),"QCD+Signal","L"); leg->AddEntry(frame1->findObject("model_Norm[x]_Comp[bkgPDF*]"),"QCD","L"); leg->AddEntry(frame1->findObject("model_Norm[x]_Comp[sgnPDF*]"),"Signal","L"); leg->SetFillColor(0); leg->SetBorderSize(0); leg->SetTextFont(42); leg->SetTextSize(0.04); leg->Draw(); TCanvas* cPull = new TCanvas("pullANN_"+SIGNAL,"pullANN_"+SIGNAL,900,400); frame3->GetXaxis()->SetTitle("ANN Output"); frame3->GetYaxis()->SetTitle("Pull"); frame3->Draw(); cout<<"Creating datacard"<<endl; ofstream datacard; datacard.open("datacard_"+SIGNAL+"_"+HISTO+".txt"); datacard.setf(ios::right); datacard<<"imax 1"<<"\n"; datacard<<"jmax 1"<<"\n"; datacard<<"kmax *"<<"\n"; datacard<<"----------------"<<"\n"; datacard<<"shapes * * "<<SIGNAL+"_"+HISTO+"_input.root $PROCESS $PROCESS_$SYSTEMATIC"<<"\n"; datacard<<"----------------"<<"\n"; datacard<<"bin 1"<<"\n"; datacard<<"observation "<<N<<"\n"; datacard<<"----------------"<<"\n"; datacard<<"bin 1 1"<<"\n"; datacard<<"process signal background "<<"\n"; datacard<<"process 0 1"<<"\n"; datacard<<"rate "<<S<<" "<<B<<"\n"; datacard<<"----------------"<<"\n"; datacard<<"lumi lnN 1.022 1.022"<<"\n"; datacard<<"jes shape 1 1"<<"\n"; datacard<<"mcstat shape 1 1"<<"\n"; datacard<<"jer shape 0 0"<<"\n"; datacard.close(); TFile *out = new TFile(SIGNAL+"_"+HISTO+"_input.root","RECREATE"); out->cd(); hDat->Write("data_obs"); hBkg->Write("background"); hSgn->Write("signal"); hDat_JESlo->Write("data_obs_jesDown"); hBkg_JESlo->Write("background_jesDown"); hBkg_STATlo->Write("background_mcstatDown"); hSgn_STATlo->Write("signal_mcstatDown"); hSgn_JESlo->Write("signal_jesDown"); hDat_JESup->Write("data_obs_jesUp"); hBkg_JESup->Write("background_jesUp"); hBkg_STATup->Write("background_mcstatUp"); hSgn_JESup->Write("signal_jesUp"); hSgn_STATup->Write("signal_mcstatUp"); //----- JER placeholder ---------------- hBkg_JESlo->Write("background_jerDown"); hSgn_JESlo->Write("signal_jerDown"); hBkg_JESup->Write("background_jerUp"); hSgn_JESup->Write("signal_jerUp"); }
void correlation_plots2(bool rwt = true, TString catName = "e3je2t"){ int numhists = 0; // jet and tag cut for each category TString jettagcut = ""; if (catName == "ge4je2t"){ jettagcut = "numJets>3 && numTaggedJets==2"; numhists = 7; } else if(catName == "e3je2t"){ jettagcut = "numJets==3 && numTaggedJets==2"; numhists = 5; } else std::cout << "Error, wrong category name" << std::endl; //IN GLOBAL SCOPE // const int numhists = 5; // 5; const int numprofiles = pow(numhists,2); TProfile** profiles_Data = new TProfile * [numprofiles]; TProfile** profiles_MC = new TProfile * [numprofiles]; //IN MAIN FUNCTION char** histnames = new char * [numhists]; char** histXaxis = new char * [numhists]; int* histbins = new int[numhists]; double* histmin = new double[numhists]; double* histmax = new double[numhists]; if(catName == "e3je2t"){ histnames[0] = (char*) "sum_pt"; histXaxis[0] = (char*) "p_{T}(l, jets)"; histbins[0] = 13; histmin[0] = 150; histmax[0] = 930; histnames[1] = (char*) "min_dr_jets"; histXaxis[1] = (char*) "minimum #DeltaR(j, j)"; histbins[1] = 12; histmin[1] = 0.5; histmax[1] = 3.5; histnames[2] = (char*) "avg_btag_disc_non_btags"; histXaxis[2] = (char*) "#mu^{CSV}(non b-tags)"; histbins[2] = 10; histmin[2] = 0.0; histmax[2] = 0.68; histnames[3] = (char*) "avg_btag_disc_btags"; histXaxis[3] = (char*) "#mu^{CSV}"; histbins[3] = 10; histmin[3] = 0.7; histmax[3] = 1; histnames[4] = (char*) "BDTG_e3je2t"; histXaxis[4] = (char*) "BDT output"; histbins[4] = 10; histmin[4] = -1.; histmax[4] = 1.; } else if(catName == "ge4je2t"){ histnames[0] = (char*) "sum_pt"; histXaxis[0] = (char*) "p_{T}(l, jets)"; histbins[0] = 15; histmin[0] = 200; histmax[0] = 1400; histnames[1] = (char*) "min_dr_jets"; histXaxis[1] = (char*) "minimum #DeltaR(j, j)"; histbins[1] = 11; histmin[1] = 0.5; histmax[1] = 2.7; histnames[2] = (char*) "avg_btag_disc_non_btags"; histXaxis[2] = (char*) "#mu^{CSV}(non b-tags)"; histbins[2] = 11; histmin[2] = 0.0; histmax[2] = 0.605; histnames[3] = (char*) "higgsLike_dijet_mass"; histXaxis[3] = (char*) "higgsLike dijet mass"; histbins[3] = 17; histmin[3] = 34; histmax[3] = 255; histnames[4] = (char*) "higgsLike_dijet_mass2"; histXaxis[4] = (char*) "higgsLike dijet mass2"; histbins[4] = 17; histmin[4] = 30; histmax[4] = 370; histnames[5] = (char*) "numJets"; histXaxis[5] = (char*) "N_{jets}"; histbins[5] = 5; histmin[5] = 4; histmax[5] = 9; histnames[6] = (char*) "BDTG_ge4je2t"; histXaxis[6] = (char*) "BDT output"; histbins[6] = 12; histmin[6] = -0.95; histmax[6] = 0.85; } else std::cout << "Error2, wrong category name" << std::endl; //// TString cuts = "(oppositeLepCharge == 1) && (dR_leplep > 0.2) && (mass_leplep > 12) && isCleanEvent && PassZmask==1 && "; cuts += jettagcut; //// sample info TString htitle[21] = {"_singlet_s","_singlet_tW","_singlet_t","_singletbar_s","_singletbar_tW","_singletbar_t","_ttbarW","_ttbarZ","_ttbar_cc","_ttbar_bb","_ttbar_b","_ttbar","_wjets","_zjets","_zjets_lowmass","_ww","_wz","_zz","_MuEG","_DoubleElectron","_DoubleMu",}; // Float_t lumi = 19450; //////// //SKIPPING HISTOGRAM INITIALIZATION FOR OTHER 49 VARIABLES (USE ABOVE THREE EXAMPLES FOR YOUR USE) //////// TDirectory *currentDir = gDirectory; for (int i = 0; i < numhists; i++){ std::cout << "-->Figuring out binning for " << histnames[i] << std::endl; //Set the binning on the x-axis by looking at the data and combining bins (if necessary) to make sure there are no poorly populated bins //Define poorly populated arbitrarily as N < 100 currentDir->cd(); //This is because the "Draw" command only finds TString histName = Form("tempData_%s",histnames[i]); TH1 * tempHist = new TH1D(histName,"",histbins[i],histmin[i],histmax[i]); //Only look at data for (int isam=18; isam<21; isam++){ TString sample = htitle[isam]; TString fileName = "/afs/crc.nd.edu/user/w/wluo1/LHCP_2013/CMSSW_5_3_8_patch1/src/BEAN/DrawPlots/bin/treeFiles/dilSummaryTrees" +sample + "_2012_53x_July5th_all.root"; std::cout << " -->Including " << fileName << std::endl; TFile * tmpfile = new TFile(fileName); TTree * tmpTree = (TTree*)tmpfile->Get("summaryTree"); currentDir->cd(); //This is because the "Draw" command only finds TString selection = "(" + cuts + "&&"; if (isam == 18) selection+= "MuonEle && isMuEGTriggerPass"; else if (isam == 19) selection += "TwoEle && isDoubleElectronTriggerPass"; else if (isam == 20) selection += "TwoMuon && isDoubleMuTriggerPass"; selection += ")"; TString var = string(histnames[i])+">>+"+histName ; tmpTree->Draw(var, selection, "goff"); tmpfile->Close(); delete tmpfile; } std::cout << "tempHist name = " << tempHist->GetName() << std::endl; std::cout << "tempHist: Entries = " << tempHist->GetEntries() << ", Integral = " << tempHist->Integral() << std::endl; double threshold = (tempHist->Integral())/20; //Now, look through the bins of the histograms, combining when necessary int nBinsUsed = 0; double *xBins = new double[histbins[i]+1]; xBins[0] = histmin[i]; //First bin always starts at minimum double binSum = 0; for (int iBin = 1; iBin <= histbins[i]; ++iBin) { binSum += tempHist->GetBinContent(iBin); std::cout << "binSum = " << binSum << ", iBin = " << iBin << std::endl; if (binSum >= threshold) { std::cout << "Setting bin edge!" << std::endl; ++nBinsUsed; xBins[nBinsUsed] = tempHist->GetBinLowEdge(iBin+1); binSum = 0.; } } //Now check: if binSum > 0, that means the last bin was too small to be a bin //by itself. If so, we need to make sure it's combined with the bin on it's left by setting the bin edge to the histogram max if (binSum > 0) { xBins[nBinsUsed] = tempHist->GetBinLowEdge(histbins[i]+1); } std::cout << " -->Proposed binning: " << histbins[i] << ", " << histmin[i] << ", " << histmax[i] << std::endl; std::cout << " -->Using " << nBinsUsed << " bins: "; for (int iBin = 0; iBin < nBinsUsed; ++iBin) std::cout << xBins[iBin] << ", "; std::cout << xBins[nBinsUsed] << std::endl; for (int j = 0; j < numhists; j++) { currentDir->cd(); //This is because the "Draw" command only finds profiles_Data[numhists*i+j] = new TProfile(Form("profiles_Data_%s_%s",histnames[i],histnames[j]),"",nBinsUsed,xBins); profiles_Data[numhists*i+j]->Sumw2(); profiles_Data[numhists*i+j]->SetLineWidth(2); profiles_MC[numhists*i+j] = new TProfile(Form("profiles_MC_%s_%s",histnames[i],histnames[j]),"",nBinsUsed,xBins); profiles_MC[numhists*i+j]->Sumw2(); profiles_MC[numhists*i+j]->SetLineWidth(2); } delete[] xBins; } // loop over samples for (int isam=0; isam<21; isam++){ /// get the tree file for each sample TString sample = htitle[isam]; TString fileName = "/afs/crc.nd.edu/user/w/wluo1/LHCP_2013/CMSSW_5_3_8_patch1/src/BEAN/DrawPlots/bin/treeFiles/dilSummaryTrees" +sample + "_2012_53x_July5th_all.root"; std::cout << "-->start processing sample " << fileName << std::endl; TFile * tmpfile = new TFile(fileName); TTree * tmpTree = (TTree*)tmpfile->Get("summaryTree"); TString weight = "(19450*Xsec/nGen)*weight*topPtWgt*lepTotalSF*triggerSF*csvWgtlf*csvWgthf*"; ///// before rwt if (rwt) weight = "(19450*Xsec/nGen)*weight*topPtWgt*lepTotalSF*triggerSF*csvWgtlf*csvWgthf*"; ///// after rwt TString lepCut = "((MuonEle && isMuEGTriggerPass) || (TwoEle && isDoubleElectronTriggerPass) || (TwoMuon && isDoubleMuTriggerPass))"; if (isam==18) lepCut = "(MuonEle && isMuEGTriggerPass)"; if (isam==19) lepCut = "(TwoEle && isDoubleElectronTriggerPass)"; if (isam==20) lepCut = "(TwoMuon && isDoubleMuTriggerPass)"; /// selection cut TString selection = weight; // selection += Form("%f*",lumi); //Adjust for sample normalization; selection += ("(" + cuts + "&&" + lepCut + ")"); if (isam>17) selection = ("(" + cuts + "&&" + lepCut + ")"); // no weights for data // std::cout << " -->selection is: " << selection << std::endl; ///// loop through variables for (int i = 0; i < numhists; i++){ for (int j = 0; j < numhists; j++){ TString proName = profiles_MC[numhists*i+j]->GetName(); if (isam >= 18) proName = profiles_Data[numhists*i+j]->GetName(); TString var = string(histnames[j]) + ":" + string(histnames[i])+">>+"+proName ; currentDir->cd(); //This is because the "Draw" command only finds tmpTree->Draw(var, selection, "goff"); } } tmpfile->Close(); delete tmpfile; } // end sample loop //Format the plots the way Robin does for (int i = 0; i < numhists; i++) { for (int j = 0; j < numhists; j++) { profiles_MC[numhists*i+j]->SetFillColor(2); profiles_MC[numhists*i+j]->SetLineColor(0); profiles_MC[numhists*i+j]->SetMarkerSize(0); profiles_MC[numhists*i+j]->SetFillStyle(3013); profiles_MC[numhists*i+j]->GetXaxis()->SetTitle(histXaxis[i]); profiles_MC[numhists*i+j]->GetYaxis()->SetTitle(histXaxis[j]); profiles_MC[numhists*i+j]->GetYaxis()->SetTitleOffset(1.3); double minval = 9999999.0; double maxval = -9999999.0; for(int ibin = 0; ibin < profiles_Data[numhists*i+j]->GetNbinsX(); ibin++){ if(profiles_Data[numhists*i+j]->GetBinContent(ibin+1) != 0.0){ if(profiles_Data[numhists*i+j]->GetBinContent(ibin+1)-profiles_Data[numhists*i+j]->GetBinError(ibin+1) < minval) minval = profiles_Data[numhists*i+j]->GetBinContent(ibin+1)-profiles_Data[numhists*i+j]->GetBinError(ibin+1); if(profiles_Data[numhists*i+j]->GetBinContent(ibin+1)+profiles_Data[numhists*i+j]->GetBinError(ibin+1) > maxval) maxval = profiles_Data[numhists*i+j]->GetBinContent(ibin+1)+profiles_Data[numhists*i+j]->GetBinError(ibin+1); } if(profiles_MC[numhists*i+j]->GetBinContent(ibin+1) != 0.0){ if(profiles_MC[numhists*i+j]->GetBinContent(ibin+1)-profiles_MC[numhists*i+j]->GetBinError(ibin+1) < minval) minval = profiles_MC[numhists*i+j]->GetBinContent(ibin+1)-profiles_MC[numhists*i+j]->GetBinError(ibin+1); if(profiles_MC[numhists*i+j]->GetBinContent(ibin+1)+profiles_MC[numhists*i+j]->GetBinError(ibin+1) > maxval) maxval = profiles_MC[numhists*i+j]->GetBinContent(ibin+1)+profiles_MC[numhists*i+j]->GetBinError(ibin+1); } } if(minval < 0) { profiles_MC[numhists*i+j]->SetMaximum(maxval + 0.4*fabs(maxval-1.1*minval)); profiles_MC[numhists*i+j]->SetMinimum(1.1*minval); } else { profiles_MC[numhists*i+j]->SetMaximum(maxval + 0.4*fabs(maxval-0.9*minval)); profiles_MC[numhists*i+j]->SetMinimum(0.9*minval); } } //end loop j } //end loop i //Save plots in output file TString outFileName = "corrPlots"; if (rwt) outFileName += "_rwt_"; outFileName += catName; outFileName += ".root"; TFile *outputFile = TFile::Open(outFileName,"RECREATE"); outputFile->cd(); for (int i = 0; i < numhists*numhists; ++i) { profiles_MC[i]->Write(); profiles_Data[i]->Write(); } outputFile->Close(); }
float PurityFit::fit_specific( const TH1* h_, const TH1* sig_, const TH1* bkg_, string name, // unique name of the result string outname , // output file name, where to save results map<string,float> *pars // to gather additional params ) { // 1) perform preliminary checks if ( h_ == NULL ) { cout<<"[PurityFit]::[fit_specific]::[ERROR] no target histogram"<<endl; return -1;} if ( sig_ == NULL ) { cout<<"[PurityFit]::[fit_specific]::[ERROR] no sig histogram"<<endl; return -1;} if ( bkg_ == NULL ) { cout<<"[PurityFit]::[fit_specific]::[ERROR] no bkg histogram"<<endl; return -1;} if (sig_ -> Integral() == 0 ) { cout<<"[PurityFit]::[fit_specific]::[ERROR] sig integrall is NULL"<<endl; return -2;} if (bkg_ -> Integral() == 0 ) { cout<<"[PurityFit]::[fit_specific]::[ERROR] bkg integrall is NULL"<<endl; return -2;} if (verbose_ >0) cout <<"[PurityFit]::[fit_specific]::[INFO] fitting "<<h_->GetName() << " " << sig_->GetName()<<" "<<bkg_->GetName()<<endl; // 1.5) Clone TH1 * sig = (TH1*)sig_ -> Clone(Form("%s_fitspecific_clone",sig_->GetName())); TH1 * bkg = (TH1*)bkg_ -> Clone(Form("%s_fitspecific_clone",bkg_->GetName())); TH1 * h = (TH1*)h_ -> Clone(Form("%s_fitspecific_clone",h_->GetName())); // 1.6) check no negative entries otherwise 0 for(int i=1;i<=sig->GetNbinsX();++i) if(sig->GetBinContent(i) <0) sig->SetBinContent(i,0); for(int i=1;i<=bkg->GetNbinsX();++i) if(bkg->GetBinContent(i) <0) bkg->SetBinContent(i,0); // 2) scale templates: template normalization is meaningless sig->Sumw2(); bkg->Sumw2(); if (bkg->Integral() <=0) { for(int i=1;i<=bkg->GetNbinsX();++i) bkg->SetBinContent(i,1.0); } // 2.5) fit background with exponential int nbins = h->GetNbinsX(); float xmin = h->GetBinLowEdge(1); float xmax = h->GetBinLowEdge(nbins+1); double prevChi2=-1; vector<TCanvas*> cbkgs; vector<TF1> expos; double cached_pars[50]; //cache for(int i=0;i< sizeof(cached_pars)/sizeof(double); ++i) cached_pars[i]=0; int poln=0; for( poln=0;poln<5; ++poln) { string formula = "TMath::Exp(-[0]*x) * ( "; for(int i=0;i<=poln;++i) { if (i>0 ) formula += " + "; formula += Form("[%d]",i+1); if (i>0) formula += Form("*TMath::Power(x,%d)",i); } formula += ")"; cout <<"Considering Formula"<<formula<<endl; TF1 expo(Form("expo%d",poln),formula.c_str(),xmin,xmax); expo.SetParameter(0,0.01); expo.SetParameter(1,0.05); expo.SetParLimits(0,TMath::Min(bkg->Integral()*.1,0.001), bkg->Integral()*10); expo.SetParLimits(1,1e-9, 1.); if (poln>0)for(int k=0;k < poln+1;++k) expo.SetParameter(k, cached_pars[k]); bkg->Fit( &expo ,"QN") ; bkg->Fit( &expo ,"QNM") ; expos.push_back(expo); //cache parameters for(int k=0;k < poln+1;++k) cached_pars[k]=expo.GetParameter(k); double chi2=expo.GetChisquare(); double prob = 0 ; if (poln > 0) { int n = 0; for(int i=1;i<=bkg->GetNbinsX();++i) if ( bkg->GetBinContent(i)> 0 ) ++n; int dof = n - (poln+2) + 1; double f = (prevChi2 - chi2) / ( chi2 /dof) ; prob= 1.- TMath::FDistI (f , 1, dof ) ; } prevChi2 = chi2; cout<<"----------- BKG PARAMETERS ARE -------"<<endl; cout << "Prob = "<<prob<<endl; cout << "chi2 = "<<chi2<<endl; cout<<" 0 : "<< expo.GetParameter(0) <<endl; for(int i=0; i<=poln;++i) cout<<" "<< i+1 <<" : "<< expo.GetParameter(i+1) <<endl; cout<<"--------------------------------------"<<endl; TCanvas *cbkg=new TCanvas( (string(name)+"_bkgfit"+ Form("pol%d",poln)).c_str(),"Canvas"); cbkgs.push_back(cbkg); bkg->Clone("bkgForDraw")->Draw("P E"); // FIXME, memory leak expo.DrawClone("L SAME"); if (prob >0.05 and poln> 0) break; // ---------------------- EXIT BEFORE UPDATING } poln -= 1; // the last has a negligible improvement for(int i=1;i<=bkg->GetNbinsX() ;++i) bkg->SetBinContent(i,expos[poln].Integral( bkg->GetBinLowEdge(i),bkg->GetBinLowEdge(i+1) ) ) ; if (sig->Integral() >0) sig -> Scale( 1./sig->Integral() ); if (bkg->Integral() >0) bkg -> Scale( 1./bkg->Integral() ); // 3) estimate paramaters // float fracEstimator=0.5; // { // // 3.1) compute frac as around the max of sig // float sigMax= sig->GetMaximum(); // int sigBinMax= sig->GetMaximumBin(); // float sigInt= sig->Integral(); // float bkgUnderMax=bkg->GetBinContent(sigBinMax); // float targetMax = h->GetMaximum(); // float targetInt = h->Integral(); // float frac1=(targetMax/targetInt)/( (sigMax-bkgUnderMax)/sigInt); // // 3.2) compute frac as tail // float bkgInt= bkg->Integral(); // int bkgN=bkg->GetNbinsX(); // int nTailSum= bkgN/10; // float bkgTail=0;for(int i=0;i<nTailSum;i++) bkgTail+= bkg->GetBinContent(bkgN-i); // int targetN=h->GetNbinsX(); // float targetTail=0;for(int i=0;i<nTailSum;i++) targetTail+= h->GetBinContent(targetN-i); // float frac2=1.- (targetTail/targetInt)/(bkgTail/bkgInt); // // 3.3) set estimator // fracEstimator = frac1; // if(fracEstimator<0.05 or fracEstimator>0.95) fracEstimator=frac2; // if(fracEstimator<0.05 or fracEstimator>0.95) fracEstimator=0.8; // } // 4) create roofit variables RooRealVar f("f","fraction",0.95,0.3,1.0); //if ( TMath::IsNaN( fracEstimator ) ) // f.setVal(0.05); //else // f.setVal(fracEstimator); f.setRange(0.3,1.0); f.setConstant(false); RooRealVar x("x","EtMiss",xmin,xmax); // 5) create roo data hist RooDataHist HistSig("sig","hist sig",x,sig); RooDataHist HistBkg("bkg","hist bkg",x,bkg); RooDataHist HistToFit("target","hist target",x,h); // 6) create roo hist pdf RooHistPdf PdfSig("pdfsig","pdfsig",x,HistSig,0); RooHistPdf PdfBkg("pdfbkg","pdfbkg",x,HistBkg,10); //last number is interpolation // 7) create model RooAddPdf PdfModel("model","model",RooArgList(PdfSig,PdfBkg),f); // 8) fit RooFitResult *r; RooPlot *frame=x.frame(); RooMsgService::instance().setSilentMode(true); PdfModel.fitTo(HistToFit, SumW2Error(kTRUE), Save(), PrintEvalErrors(-1), PrintLevel(-1), //Minos(kTRUE), Warnings(0) ); r = PdfModel.fitTo(HistToFit, SumW2Error(kTRUE), Save(), PrintEvalErrors(-1), PrintLevel(-1), Minos(kTRUE), Warnings(0) ); cout <<" -------------- FLOATING -------------"<<endl; r-> floatParsInit() . Print("V"); cout <<" -------------- FINAL ----------------"<<endl; r-> floatParsFinal() . Print("V"); cout <<" -------------------------------------"<<endl; // 8.5) save additional results if (pars != NULL ) { (*pars)["fracErrorHigh"] = f.getAsymErrorHi(); (*pars)["fracErrorLow" ] = f.getAsymErrorLo(); } // 9) plot HistToFit.plotOn(frame,DataError(RooAbsData::SumW2)); PdfModel.plotOn(frame, LineColor(kBlack)); PdfModel.plotOn(frame, Components(PdfBkg),LineColor(kRed)); PdfModel.plotOn(frame, Components(PdfSig),LineColor(kBlue),LineStyle(kDashed)); TCanvas *c=new TCanvas((string(name)+"_canvas").c_str(),"Canvas"); c->cd(); c->Draw(); frame->Draw(); TLatex* txt = new TLatex();//Form("Fraction=%.1f\%",f.getVal()*100) ; txt->SetTextSize(0.03) ; txt->SetTextColor(kBlack) ; txt->SetNDC(); txt->SetTextAlign(22); //txt->AddText(Form("Fraction=%.1f\%",f.getVal()*100) ); txt->DrawLatex(.3,.85,Form("Fraction=%.1f%%",float(f.getVal()*100))); // get pt from name { size_t n = name.find("pt"); float ptmin = -1; float ptmax = -1; if (n != string::npos) { string pts = ""; //name[n+0] == 'p' //name[n+1] =='t' n +=2; //all string are null terminated in C/C++ while ( name[n] != '_' and name[n] != '\0' ) { pts+=name[n]; ++n;} ptmin = atof( pts.c_str() ) ; pts=""; ++n; while ( name[n] != '_' and name[n] != '\0' ) { pts+=name[n]; ++n;} ptmax = atof( pts.c_str() ) ; txt->DrawLatex(.3,.82,Form("%.1f<P_{T}<%.1f",ptmin,ptmax)); } } // end get pt from name if ( outname != "") { TFile *fOut=TFile::Open(outname.c_str(),"UPDATE"); fOut->cd(); c->Write(); for( auto c : cbkgs ) c->Write(); r->Write(Form("%s_roofit",name.c_str() ) ); fOut->Close(); } // delete the clone for( auto c : cbkgs ) c->Delete(); cbkgs.clear(); sig -> Delete(); bkg -> Delete(); h -> Delete(); return f.getVal(); }
Bool_t fitsHere(TLegend *l,Double_t x1, Double_t y1, Double_t x2, Double_t y2) { Bool_t fits = true; TList *list = l->GetListOfPrimitives(); for (Int_t k = 0; list->At(k) != 0 && fits; k++) { TObject *obj = ((TLegendEntry*)(list->At(k)))->GetObject(); if (obj == 0) continue; TClass *cl = obj->IsA(); //Histogram, drawn as a histogram if (cl->InheritsFrom("TH1") && !cl->InheritsFrom("TH2") && !cl->InheritsFrom("TH3") && cl != TProfile::Class() && ((TH1*)obj)->GetMarkerColor() == kWhite) { Int_t where = 0; TH1 *h = (TH1*)obj; for (Int_t i = 1; i <= h->GetNbinsX() && fits; i++) { if (h->GetBinLowEdge(i) + h->GetBinWidth(i) < x1) continue; //to the left of the legend if (h->GetBinLowEdge(i) > x2) continue; //to the right of the legend if (h->GetBinContent(i) > y1 && h->GetBinContent(i) < y2) fits = false; //inside the legend if (h->GetBinContent(i) < y1) { if (where == 0) where = -1; //below the legend if (where == 1) fits = false; //a previous bin was above it so there's a vertical line through it } if (h->GetBinContent(i) > y2) { if (where == 0) where = 1; //above the legend if (where == -1) fits = false; //a previous bin was below it so there's a vertical line through it } } continue; } //Histogram, drawn with Draw("P") else if (cl->InheritsFrom("TH1") && !cl->InheritsFrom("TH2") && !cl->InheritsFrom("TH3") && cl != TProfile::Class()) //Probably TProfile would be the same but I haven't tested it { TH1 *h = (TH1*)obj; for (Int_t i = 1; i <= h->GetNbinsX() && fits; i++) { if (h->GetBinLowEdge(i) + h->GetBinWidth(i)/2 < x1) continue; if (h->GetBinLowEdge(i) > x2) continue; if (h->GetBinContent(i) > y1 && h->GetBinContent(i) < y2) fits = false; if (h->GetBinContent(i) + h->GetBinError(i) > y2 && h->GetBinContent(i) - h->GetBinError(i) < y2) fits = false; if (h->GetBinContent(i) + h->GetBinError(i) > y1 && h->GetBinContent(i) - h->GetBinError(i) < y1) fits = false; } } else if (cl->InheritsFrom("TF1") && !cl->InheritsFrom("TF2")) { //TF1 *f = (TF1*)obj; //Double_t max = f->GetMaximum(x1,x2); //Double_t min = f->GetMinimum(x1,x2); //if (min < y2 && max > y1) fits = false; } // else if (cl->InheritsFrom(...... add more objects here else { cout << "Don't know how to place the legend around objects of type " << obj->ClassName() << "." << endl << "Add this class into placeLegend.C if you want it to work properly." << endl << "The legend will still be placed around any other objects." << endl; } } return fits; }