Double_t fitgp0( char* hs ) { TH1 *h = (TH1*)gDirectory->Get(hs); if( h == NULL ){ cout << hs << " does not exist\n"; return 0; } h->SetMarkerStyle(21); h->SetMarkerSize(0.8); h->SetStats(1); gStyle->SetOptFit(101); gROOT->ForceStyle(); double dx = h->GetBinWidth(1); double nmax = h->GetBinContent(h->GetMaximumBin()); double xmax = h->GetBinCenter(h->GetMaximumBin()); double nn = 7*nmax; int nb = h->GetNbinsX(); double n1 = h->GetBinContent(1); double n9 = h->GetBinContent(nb); double bg = 0.5*(n1+n9); double x1 = h->GetBinCenter(1); double x9 = h->GetBinCenter(nb); // create a TF1 with the range from x1 to x9 and 4 parameters TF1 *gp0Fcn = new TF1( "gp0Fcn", gp0Fit, x1, x9, 4 ); gp0Fcn->SetParName( 0, "mean" ); gp0Fcn->SetParName( 1, "sigma" ); gp0Fcn->SetParName( 2, "area" ); gp0Fcn->SetParName( 3, "BG" ); gp0Fcn->SetNpx(500); gp0Fcn->SetLineWidth(4); gp0Fcn->SetLineColor(kMagenta); gp0Fcn->SetLineColor(kGreen); // set start values for some parameters: gp0Fcn->SetParameter( 0, xmax ); // peak position gp0Fcn->SetParameter( 1, 4*dx ); // width gp0Fcn->SetParameter( 2, nn ); // N gp0Fcn->SetParameter( 3, bg ); // N: not drawing // Q: quiet // R: use specified range h->Fit( "gp0Fcn", "NQR", "ep" ); return gp0Fcn->GetParameter(1); }
void KVCanvas::ProjectionX(TH2* hh) { TString pname = Form("%s_px", hh->GetName()); Int_t ip = 1; while (gROOT->FindObject(pname.Data())) { pname = Form("%s_px%d", hh->GetName(), ip); ip++; } TH1* px = hh->ProjectionX(pname.Data()); if (!px) return; Double_t minY = (hh->GetYaxis()->GetXmin()); Double_t maxY = (hh->GetYaxis()->GetXmax()); Double_t dY = (maxY - minY) * 0.8; Double_t maxH = px->GetBinContent(px->GetMaximumBin()); TGraph* gg = 0; if ((gg = (TGraph*)gROOT->FindObject(Form("%s_gjx", hh->GetName())))) gg->Delete(); gg = new TGraph; for (int i = 0; i < px->GetNbinsX(); i++) { gg->SetPoint(i, px->GetBinCenter(i), minY + px->GetBinContent(i)*dY / maxH); } gg->SetName(Form("%s_gjx", hh->GetName())); gg->SetTitle(Form("%s_gjx", hh->GetName())); gg->SetLineColor(kBlack); gg->SetMarkerColor(kBlack); gg->SetMarkerStyle(8); gg->Draw("PL"); Modified(); Update(); }
void setRange(RooWorkspace& myws, RooPlot* frame, string dsName, bool setLogScale, double dMuonYmin) { // Find maximum and minimum points of Plot to rescale Y axis TH1* h = myws.data(dsName.c_str())->createHistogram("hist", *myws.var("ctau"), Binning(frame->GetNbinsX(),frame->GetXaxis()->GetXmin(),frame->GetXaxis()->GetXmax())); Double_t YMax = h->GetBinContent(h->GetMaximumBin()); cout << YMax << endl; // Double_t YMin = min( h->GetBinContent(h->FindFirstBinAbove(0.0)), h->GetBinContent(h->FindLastBinAbove(0.0)) ); Double_t YMin = 1e99; for (int i=1; i<=h->GetNbinsX(); i++) if (h->GetBinContent(i)>0) YMin = min(YMin, h->GetBinContent(i)); bool isMC = false; if (dsName.find("MC")!=std::string::npos) isMC = true; Double_t Yup(0.),Ydown(0.); if(setLogScale) { if (isMC) Ydown = YMin*0.3; else Ydown = YMin/(TMath::Power((YMax/YMin), (0.1/(1.0-0.1-0.4)))); Yup = YMax*TMath::Power((YMax/YMin), (0.4/(1.0-0.1-0.4))); } else { Ydown = max(YMin-(YMax-YMin)*(0.1/(1.0-0.1-0.4)),0.0); Yup = YMax+(YMax-YMin)*(0.4/(1.0-0.1-0.4)); } cout << Ydown << " " << Yup << endl; frame->GetYaxis()->SetRangeUser(Ydown,Yup); delete h; // Create line to indicate upper fitting range for MC if (isMC) { if (dsName.find("JPSIP")!=std::string::npos) { TLine* line(0x0); if (dMuonYmin >= 1.6) line = new TLine(3.32,Ydown,3.32,Yup); else line = new TLine(3.26,Ydown,3.26,Yup); line->SetLineStyle(2); line->SetLineColor(1); line->SetLineWidth(3); frame->addObject(line); } else if (dsName.find("PSI2S")!=std::string::npos) { TLine* line(0x0); if (dMuonYmin >= 1.6) line = new TLine(3.95,Ydown,3.95,Yup); else line = new TLine(3.85,Ydown,3.85,Yup); line->SetLineStyle(2); line->SetLineColor(1); line->SetLineWidth(3); frame->addObject(line); } } }
Double_t fitep0sigma( char* hs, int binlow=-999, int binhigh=999) { TH1 *h = (TH1*)gDirectory->Get(hs); if( h == NULL ){ cout << hs << " does not exist\n"; return 0; } double dx = h->GetBinWidth(1); double nmax = h->GetBinContent(h->GetMaximumBin()); double xmax = h->GetBinCenter(h->GetMaximumBin()); double nn = 7*nmax; int nb = h->GetNbinsX(); double n1 = h->GetBinContent(1); double n9 = h->GetBinContent(nb); double bg = 0.5*(n1+n9); double x1, x9; if(binlow < -900 && binhigh > 900) { x1 = h->GetBinCenter(1); x9 = h->GetBinCenter(nb); } else { x1 = binlow; x9 = binhigh; } // create a TF1 with the range from x1 to x9 and 5 parameters TF1 *ep0Fcn = new TF1( "ep0Fcn", ep0Fit, x1, x9, 5 ); ep0Fcn->SetParName( 0, "mean" ); ep0Fcn->SetParName( 1, "sigma" ); ep0Fcn->SetParName( 2, "pow" ); ep0Fcn->SetParName( 3, "area" ); ep0Fcn->SetParName( 4, "BG" ); // Start values for some parameters: ep0Fcn->SetParameter( 0, xmax ); // peak position ep0Fcn->SetParameter( 1, 4*dx ); // width ep0Fcn->SetParameter( 2, 3.3 ); // pow ep0Fcn->SetParameter( 3, nn ); // N ep0Fcn->SetParameter( 4, bg ); h->Fit("ep0Fcn", "Q R", "ep" ); TF1 *fit = h->GetFunction("ep0Fcn"); return fit->GetParameter(1); }
double fittp0sigma( char* hs ) { TH1 *h = (TH1*)gDirectory->Get(hs); if( h == NULL ){ cout << hs << " does not exist\n"; return 0; } double dx = h->GetBinWidth(1); double nmax = h->GetBinContent(h->GetMaximumBin()); double xmax = h->GetBinCenter(h->GetMaximumBin()); double nn = 7*nmax; int nb = h->GetNbinsX(); double n1 = h->GetBinContent(1); double n9 = h->GetBinContent(nb); double bg = 0.5*(n1+n9); double x1 = h->GetBinCenter(1); double x9 = h->GetBinCenter(nb); // create a TF1 with the range from x1 to x9 and 5 parameters TF1 *tp0Fcn = new TF1( "tp0Fcn", tp0Fit, x1, x9, 5 ); tp0Fcn->SetParName( 0, "mean" ); tp0Fcn->SetParName( 1, "sigma" ); tp0Fcn->SetParName( 2, "nu" ); tp0Fcn->SetParName( 3, "area" ); tp0Fcn->SetParName( 4, "BG" ); // set start values for some parameters: tp0Fcn->SetParameter( 0, xmax ); // peak position tp0Fcn->SetParameter( 1, 4*dx ); // width tp0Fcn->SetParameter( 2, 2.2 ); // nu tp0Fcn->SetParameter( 3, nn ); // N tp0Fcn->SetParameter( 4, bg ); h->Fit( "tp0Fcn", "Q R", "ep" ); // h->Fit("tp0Fcn","V+","ep"); TF1 *fit = h->GetFunction("tp0Fcn"); return fit->GetParameter(1); }
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); }
// Returns the RMS including 96% of the histogram entries, cutting the tails: Double_t getRMS96(char* hs, double truncation=96.) { bool debug = false; TH1 *h = (TH1*)gDirectory->Get(hs); if( h == NULL ){ cout << hs << " does not exist\n"; return 0; } // Total entries: double integral = h->GetEntries(); int maxbin = h->GetMaximumBin(); if(debug) cout << "entries=" << integral << " maxbin=" << maxbin << endl; double subrange_integral = h->GetBinContent(maxbin); int bin = 0; while(subrange_integral < truncation/100*integral) { bin++; // Add one bin to the left: subrange_integral += h->GetBinContent(maxbin-bin); // Add one bin to the right: subrange_integral += h->GetBinContent(maxbin+bin); if(debug) cout << "subrange " << (maxbin-bin) << "-" << (maxbin+bin) << ": entries=" << subrange_integral << endl; } if(debug) cout << "subrange " << (maxbin-bin) << "-" << (maxbin+bin) << " now has " << subrange_integral << " entries, this is " << (100.0*subrange_integral)/integral << "%" << endl; // Correct by overshoot bin: subrange_integral -= h->GetBinContent(maxbin+bin); subrange_integral -= h->GetBinContent(maxbin-bin); bin--; int binlow = maxbin-bin; int binhigh = maxbin+bin; if(debug) cout << "subrange " << (maxbin-bin) << "-" << (maxbin+bin) << " now has " << subrange_integral << " entries, this is " << (100.0*subrange_integral)/integral << "%" << endl; h->GetXaxis()->SetRange(binlow,binhigh); //to restrict range to bins binlow to binhigh double rms96 = h->GetRMS(); //will return the RMS within the axis range return rms96; }
void setMassFrom2DRange(RooWorkspace& myws, RooPlot* frame, string dsName, bool setLogScale) { // Find maximum and minimum points of Plot to rescale Y axis TH1* h = myws.data(dsName.c_str())->createHistogram("hist", *myws.var("invMass"), Binning(frame->GetNbinsX(),frame->GetXaxis()->GetXmin(),frame->GetXaxis()->GetXmax())); Double_t YMax = h->GetBinContent(h->GetMaximumBin()); // Double_t YMin = min( h->GetBinContent(h->FindFirstBinAbove(0.0)), h->GetBinContent(h->FindLastBinAbove(0.0)) ); Double_t YMin = 1e99; for (int i=1; i<=h->GetNbinsX(); i++) if (h->GetBinContent(i)>0) YMin = min(YMin, h->GetBinContent(i)); Double_t Yup(0.),Ydown(0.); if(setLogScale) { Ydown = YMin/(TMath::Power((YMax/YMin), (0.1/(1.0-0.1-0.4)))); Yup = YMax*TMath::Power((YMax/YMin), (0.4/(1.0-0.1-0.4))); } else { Ydown = max(YMin-(YMax-YMin)*(0.1/(1.0-0.1-0.4)),0.0); Yup = YMax+(YMax-YMin)*(0.4/(1.0-0.1-0.4)); } frame->GetYaxis()->SetRangeUser(Ydown,Yup); delete h; };
void setCtauFrom2DRange(RooWorkspace& myws, RooPlot* frame, string dsName, bool setLogScale, vector<double> rangeErr, double excEvts) { // Find maximum and minimum points of Plot to rescale Y axis TH1* h = myws.data(dsName.c_str())->createHistogram("hist", *myws.var("ctau"), Binning(frame->GetNbinsX(),frame->GetXaxis()->GetXmin(),frame->GetXaxis()->GetXmax())); Double_t YMax = h->GetBinContent(h->GetMaximumBin()); Double_t YMin = 1e99; for (int i=1; i<=h->GetNbinsX(); i++) if (h->GetBinContent(i)>0) YMin = min(YMin, h->GetBinContent(i)); Double_t Yup(0.),Ydown(0.); if(setLogScale) { Yup = YMax*TMath::Power((YMax/0.1), 0.5); Ydown = 0.1; } else { Yup = YMax+(YMax-0.0)*0.5; Ydown = 0.0; } frame->GetYaxis()->SetRangeUser(Ydown,Yup); delete h; if (excEvts>0.0) { TLine *minline = new TLine(rangeErr[0], 0.0, rangeErr[0], (setLogScale?(Ydown*TMath::Power((Yup/Ydown),0.4)):(Ydown + (Yup-Ydown)*0.4))); minline->SetLineStyle(2); minline->SetLineColor(1); minline->SetLineWidth(3); frame->addObject(minline); TLine *maxline = new TLine(rangeErr[1], 0.0, rangeErr[1], (setLogScale?(Ydown*TMath::Power((Yup/Ydown),0.4)):(Ydown + (Yup-Ydown)*0.4))); maxline->SetLineStyle(2); maxline->SetLineColor(1); maxline->SetLineWidth(3); frame->addObject(maxline); } };
// //---------------------------------------------------------------------- // int fittp0( char* hs ) { TH1 *h = (TH1*)gDirectory->Get(hs); if( h == NULL ){ cout << hs << " does not exist\n"; } else{ h->SetMarkerStyle(21); h->SetMarkerSize(0.8); h->SetStats(1); gStyle->SetOptFit(101); gROOT->ForceStyle(); double dx = h->GetBinWidth(1); double nmax = h->GetBinContent(h->GetMaximumBin()); double xmax = h->GetBinCenter(h->GetMaximumBin()); double nn = 7*nmax; int nb = h->GetNbinsX(); double n1 = h->GetBinContent(1); double n9 = h->GetBinContent(nb); double bg = 0.5*(n1+n9); double x1 = h->GetBinCenter(1); double x9 = h->GetBinCenter(nb); cout << hs << ": " << x1 << " - " << x9 << endl; // create a TF1 with the range from x1 to x9 and 5 parameters TF1 *tp0Fcn = new TF1( "tp0Fcn", tp0Fit, x1, x9, 5 ); tp0Fcn->SetParName( 0, "mean" ); tp0Fcn->SetParName( 1, "sigma" ); tp0Fcn->SetParName( 2, "nu" ); tp0Fcn->SetParName( 3, "area" ); tp0Fcn->SetParName( 4, "BG" ); tp0Fcn->SetNpx(500); tp0Fcn->SetLineWidth(4); tp0Fcn->SetLineColor(kMagenta); tp0Fcn->SetLineColor(kGreen); // set start values for some parameters: cout << hs << " " << dx << ", " << nn << ", " << xmax << endl; tp0Fcn->SetParameter( 0, xmax ); // peak position tp0Fcn->SetParameter( 1, 4*dx ); // width tp0Fcn->SetParameter( 2, 2.2 ); // nu tp0Fcn->SetParameter( 3, nn ); // N tp0Fcn->SetParameter( 4, bg ); h->Fit( "tp0Fcn", "R", "ep" ); // h->Fit("tp0Fcn","V+","ep"); h->Draw("histepsame"); // data again on top } }
//void makeHist(const int sample, const int dataset=1) void makeHist(const string title="") { vector<Hist> hist2print; TPaveText *tx = new TPaveText(.05,.1,.95,.8); // tx->AddText("Using Deafult JERs for all jets"); // tx->AddText("Using b-Jet JERs"); /* string title("QCD MG:"); //if (sample==1) title += "NJet(70/50/30>=2/4/5), #slash{E}_{T}>175, Triplet>1, 80<TopMass<270, TOP+0.5*BJET>500, MT2>300, #Delta#Phi(.5,.5,.3), BJets>=1"; if (sample==1) title += "All Stop cuts applied (use default JERs for all jets)"; else if (sample==2) title += "All Stop cuts applied + Inverted #Delta#Phi (use default JERs for all jets)"; else if (sample==3) title += "All Stop cuts applied (use b-Jet JERs)"; else if (sample==4) title += "All Stop cuts applied + Inverted #Delta#Phi (use b-Jet JERs)"; else if (sample==5) title += "No cuts applied"; */ unsigned bitMaskArray[] = {0,1,2,3,129,130,131,195,257,258,269,323}; vector<unsigned> vBitMaskArray(bitMaskArray, bitMaskArray + sizeof(bitMaskArray) / sizeof(unsigned)); stringstream unclmet_title; unclmet_title << title << "Unclutered MET"; hist2print.push_back(Hist("met",title,2,0.0, 400.0,1)); hist2print.push_back(Hist("unclmet",unclmet_title.str().c_str(),2,0.0, 100.0,1)); hist2print.push_back(Hist("mht",title,2,0.0, 400.0,1)); hist2print.push_back(Hist("ht",title,2,0,2000,1)); hist2print.push_back(Hist("njet30eta5p0",title,1,0,15,1)); hist2print.push_back(Hist("nbjets",title,1,0,10,1)); // hist2print.push_back(Hist("bjetPt",title,2)); hist2print.push_back(Hist("M123",title,2)); // hist2print.push_back(Hist("M23overM123",title)); hist2print.push_back(Hist("MT2",title,2)); hist2print.push_back(Hist("MTb",title,4)); hist2print.push_back(Hist("MTt",title,4)); hist2print.push_back(Hist("MTb_p_MTt",title,2,400,1000,1)); //hist2print.push_back(Hist("jet1_pt",title,2)); //hist2print.push_back("bjetPt"); // hist2print.push_back(Hist("bjetMass",title,2,0,200)); // hist2print.push_back(Hist("dphimin",title,4)); TFile *outRootFile = new TFile("Merged.root"); /*TPad *c1=0, *c2=0; TCanvas *c = GetCanvas(c1, c2); if (c ==NULL|| c1 == 0 ||c2 == 0) { cout << " A drawing pad is null !"<< endl; cout << "c = " << c << endl; cout << "c1 = " << c1 << endl; cout << "c2 = " << c2 << endl; assert(false); }*/ TCanvas *c = new TCanvas("c1"); c->Range(0,0,1,1); c->SetBorderSize(2); c->SetFrameFillColor(0); // ------------>Primitives in pad: c1_1 TPad *c1_1 = new TPad("c1_1", "c1_1",0.01,0.30,0.99,0.99); c1_1->Draw(); c1_1->cd(); c1_1->SetBorderSize(2); c1_1->SetTickx(1); c1_1->SetTicky(1); c1_1->SetTopMargin(0.1); c1_1->SetBottomMargin(0.0); //c1_1->SetFrameFillColor(3); //c1_1->SetLogy(); c->cd(); // ------------>Primitives in pad: c1_2 TPad *c1_2 = new TPad("c1_2", "c1_2",0.01,0.01,0.99,0.30); c1_2->Draw(); c1_2->cd(); c1_2->SetBorderSize(2); c1_2->SetTickx(1); c1_2->SetTicky(1); c1_2->SetTopMargin(0.0); c1_2->SetBottomMargin(0.24); c1_2->SetFrameFillColor(0); c1_2->SetGridx(); c1_2->SetGridy(); c->cd(); gStyle->SetOptStat(0); gPad->Print("samples.eps["); for (unsigned i=0;i<vBitMaskArray.size(); ++i) { unsigned mask = vBitMaskArray.at(i); for (unsigned ihist=0; ihist < hist2print.size(); ++ihist) { stringstream path, reco_hist_name, gen_hist_name, smear_hist_name; stringstream reco_hist, gen_hist, smear_hist; stringstream folder; folder << "Hist/Mask"<< mask << "HT0to8000MHT0to8000/"; //cout << "folder = " << folder.str() << endl; /* if ((hist2print.at(ihist).Name()).find("Jet")) { reco_hist_name << folder.str() << "reco" << hist2print.at(ihist).Name() << "_copy"; reco_hist << folder.str() << "reco" << hist2print.at(ihist).Name(); smear_hist_name << folder.str() << "smeared" << hist2print.at(ihist).Name() << "_copy"; smear_hist << folder.str() << "smeared" << hist2print.at(ihist).Name(); gen_hist_name << folder.str() << "gen" << hist2print.at(ihist).Name() << "_copy"; gen_hist << folder.str() << "gen" << hist2print.at(ihist).Name(); } else */ { reco_hist_name << folder.str() << "reco_" << hist2print.at(ihist).Name() << "_copy"; reco_hist << folder.str() << "reco_" << hist2print.at(ihist).Name(); smear_hist_name << folder.str() << "smeared_" << hist2print.at(ihist).Name() << "_copy"; smear_hist << folder.str() << "smeared_" << hist2print.at(ihist).Name(); gen_hist_name << folder.str() << "gen_" << hist2print.at(ihist).Name() << "_copy"; gen_hist << folder.str() << "gen_" << hist2print.at(ihist).Name(); } TH1* hreco = (TH1*) (outRootFile->Get(reco_hist.str().c_str())); if (hreco == NULL) { cout << "hreco = " << reco_hist.str() << " was not found!" << endl; assert(false); } hreco->SetDirectory(0); TH1* hsmear = (TH1*) (outRootFile->Get(smear_hist.str().c_str())); if (hsmear == NULL) { cout << "hsmear = " << smear_hist.str() << " was not found!" << endl; assert(false); } hsmear->SetDirectory(0); TH1* hgen = (TH1*) (outRootFile->Get(gen_hist.str().c_str())); //->Clone(gen_hist_name.str().c_str())); if (hgen == NULL) { cout << "hgen = " << gen_hist.str() << " was not found!" << endl; assert(false); } hgen->SetDirectory(0); hreco->Sumw2(); hsmear->Sumw2(); hgen->Sumw2(); const int rebin = hist2print.at(ihist).Rebin(); const string title = hist2print.at(ihist).Title(); const double xmin = hist2print.at(ihist).Xmin(); const double xmax = hist2print.at(ihist).Xmax(); if (rebin>1) { hreco->Rebin(rebin); hsmear->Rebin(rebin); hgen->Rebin(rebin); } if (title.length()>0) { hreco->SetTitle(title.c_str()); hsmear->SetTitle(title.c_str()); hgen->SetTitle(title.c_str()); } if (xmin != LargeNegNum || xmax != LargeNegNum) { hreco->GetXaxis()->SetRangeUser(xmin,xmax); hsmear->GetXaxis()->SetRangeUser(xmin,xmax); hgen->GetXaxis()->SetRangeUser(xmin,xmax); } const double reco_max_y = hreco->GetBinContent(hreco->GetMaximumBin()); const double smear_max_y = hsmear->GetBinContent(hsmear->GetMaximumBin()); const double y_max = max(reco_max_y, smear_max_y); double y_min = 9999.0; for (unsigned bin=1; bin<hreco->GetNbinsX(); ++bin) { const double v1 = hreco->GetBinContent(bin); const double v2 = hsmear->GetBinContent(bin); const double minv = min(v1,v2); if (minv != 0 && minv < y_min) y_min = minv; } cout << hreco->GetName() << "->ymin/max = " << y_min << "(" << y_min/2.0 << ")/" << y_max << "(" << y_max*2.0 << ")" << endl; hreco->GetYaxis()->SetRangeUser(y_min/2.0, y_max*2.0); hsmear->GetYaxis()->SetRangeUser(y_min/2.0, y_max*2.0); hgen->SetLineColor(kBlue); hgen->SetMarkerColor(kBlue); hgen->SetMarkerStyle(24); hgen->SetLineWidth(2); hsmear->SetLineColor(kRed); hsmear->SetMarkerColor(kRed); hsmear->SetMarkerStyle(24); hsmear->SetLineWidth(2); hreco->SetLineWidth(2); hreco->SetMarkerStyle(kDot); hreco->SetLineColor(kBlack); hreco->SetMarkerColor(kBlack); //hreco->GetXaxis()->SetRangeUser(0,300); //hsmear->GetXaxis()->SetRangeUser(0,300); hreco->GetYaxis()->CenterTitle(1); hreco->SetLabelFont(42,"XYZ"); hreco->SetTitleFont(42,"XYZ"); hreco->GetYaxis()->SetTitleOffset(0.8); hreco->SetLabelSize(0.05,"XYZ"); hreco->SetTitleSize(0.06,"XYZ"); TH1 *hsmeartoreco_ratio = (TH1*) (hsmear->Clone("hsmear_copy")); hsmeartoreco_ratio->Divide(hreco); hsmeartoreco_ratio->SetTitle(""); hsmeartoreco_ratio->GetYaxis()->SetTitle("Smear/Reco"); hsmeartoreco_ratio->GetYaxis()->SetRangeUser(0,2.); hsmeartoreco_ratio->GetYaxis()->SetTitleOffset(0.4); hsmeartoreco_ratio->GetXaxis()->SetTitleOffset(0.9); hsmeartoreco_ratio->GetYaxis()->CenterTitle(1); hsmeartoreco_ratio->GetXaxis()->CenterTitle(1); hsmeartoreco_ratio->SetLabelSize(0.125,"XYZ"); hsmeartoreco_ratio->SetTitleSize(0.125,"XYZ"); // hsmeartoreco_ratio->SetLabelFont(labelfont,"XYZ"); // hsmeartoreco_ratio->SetTitleFont(titlefont,"XYZ"); hsmeartoreco_ratio->GetXaxis()->SetTickLength(0.07); stringstream recoleg,smearleg, genleg; const double sum_reco = hreco->Integral(1, hreco->GetNbinsX()+1); const double sum_smear = hsmear->Integral(1, hsmear->GetNbinsX()+1); const double sum_gen = hgen->Integral(1, hgen->GetNbinsX()+1); const double err_reco = StatErr(hreco); const double err_smear = StatErr(hsmear); cout << setprecision(1) << fixed; recoleg << "Reco (" << sum_reco << "#pm" << err_reco << ")"; smearleg << "Smear (" << sum_smear << "#pm" << err_smear << ")"; genleg << "Gen (" << sum_gen << ")"; cout << smear_hist_name.str() << "::reco/smear = " << sum_reco << "/" << sum_smear << endl; TLegend *l2 = new TLegend(0.6,0.6,0.9,0.9); l2->AddEntry(hreco, recoleg.str().c_str()); //l2->AddEntry(hgen, genleg.str().c_str()); l2->AddEntry(hsmear, smearleg.str().c_str()); c1_1->cd(); gPad->SetLogy(hist2print.at(ihist).LogY()); hreco->DrawCopy(); //hgen->DrawCopy("same"); hsmear->DrawCopy("same"); l2->Draw(); //tx->Draw(); c1_2->cd(); hsmeartoreco_ratio->DrawCopy(); c->cd(); gPad->Print("samples.eps"); } } gPad->Print("samples.eps]"); }
//______________________________________________________________________________ void CheckTime(const Char_t* loc) { // Check time. Char_t t[256]; // number of runs Int_t nRuns = gFiles->GetSize(); // create arrays const Int_t nCh = 352; Double_t** pedPos = new Double_t*[nCh]; Double_t* runNumbersD = new Double_t[nRuns]; for (Int_t i = 0; i < nCh; i++) pedPos[i] = new Double_t[nRuns]; // open the output files TFile* fROOTout = new TFile("/tmp/tagger_time.root", "RECREATE"); // create directories for (Int_t i = 0; i < nCh; i++) { sprintf(t, "%03d", i); fROOTout->mkdir(t); } TF1* func = new TF1("func", "gaus(0)+pol1(3)", -1000 , 1000); // loop over runs for (Int_t i = 0; i < nRuns; i++) { // get the file TFile* f = (TFile*) gFiles->At(i); // extract run number Int_t runNumber; sprintf(t, "%s/ARHistograms_CB_%%d.root", loc); sscanf(f->GetName(), t, &runNumber); runNumbersD[i] = (Double_t)runNumber; printf("Processing run %d (%d/%d)\n", runNumber, i+1, nRuns); fROOTout->cd(); TH2* h2 = (TH2*) f->Get("CaLib_Tagger_Time"); // loop over channels for (Int_t j = 0; j < nCh; j++) { // load histogram sprintf(t, "%03d", j); fROOTout->cd(t); sprintf(t, "%d_%d", i, j); TH1* h = h2->ProjectionX(t, j+1, j+1); h->Rebin(2); sprintf(t, "Run_%d", runNumber); TCanvas* c = new TCanvas(t, t); TLine* tline = 0; // check entries if (h->GetEntries()) { // fit gaussian to peak Double_t maxPos = h->GetXaxis()->GetBinCenter(h->GetMaximumBin()); func->SetParameters(1, maxPos, 0.5, 1, 0.1); func->SetRange(maxPos - 2, maxPos + 2); func->SetParLimits(0, 0, 1000); for (Int_t k = 0; k < 10; k++) if (!h->Fit(func, "RBQ")) break; // save position in file and memory maxPos = func->GetParameter(1); pedPos[j][i] = maxPos; h->GetXaxis()->SetRangeUser(maxPos - 10, maxPos + 10); h->Draw(); tline = new TLine(maxPos, 0, maxPos, 10000); tline->SetLineColor(kRed); tline->SetLineWidth(2); tline->Draw(); } else { h->Draw(); } c->Write(c->GetName(), TObject::kOverwrite); delete h; delete c; if (tline) delete tline; } delete h2; } // create pedestal evolution graphs fROOTout->cd(); // loop over channels for (Int_t j = 0; j < nCh; j++) { printf("Creating time graph for channel %d\n", j); TGraph* g = new TGraph(nRuns, runNumbersD, pedPos[j]); sprintf(t, "Overview_%03d", j); g->SetName(t); g->SetTitle(t); //g->GetYaxis()->SetRangeUser(1200, 1300); g->Write(g->GetName(), TObject::kOverwrite); delete g; } printf("Saving output file\n"); delete fROOTout; // cleanup for (Int_t i = 0; i < nCh; i++) delete [] pedPos[i]; delete [] pedPos; delete [] runNumbersD; }
//________________________________________________________________ void KVZALineFinder::FindALine(Int_t zz, Int_t width) { fLinearHisto->SetAxisRange(zz-0.5,zz+0.5,"Y"); KVIDLine* line = (KVIDLine*)fGrid->GetIdentifier(zz,2*zz+1); // A=2*zz+1 : dummy, A is ignored in this case if(!line) { int i=1; while(!(line = (KVIDLine*)fGrid->GetIdentifier(zz+i,2*zz+1))) i++; } if(!line) return; Double_t lX, lY; line->GetStartPoint(lX,lY); Int_t xbmin = 0;//fLinearHisto->GetYaxis()->FindBin(lX); line->GetEndPoint(lX,lY); Int_t xbmax = fLinearHisto->GetXaxis()->FindBin(lX); // create lines TList Lines; KVSpiderLine* tmp = 0; fLinearHisto->SetAxisRange(fLinearHisto->GetXaxis()->GetBinCenter(50),lX,"X");//fLinearHisto->GetXaxis()->GetXmax(),"X"); TH1* tmph = fLinearHisto->ProjectionX(Form("tmph%d",zz)); Int_t startBin = (Int_t)(tmph->GetMaximumBin()*0.95); delete tmph; TH1* projey = 0; if(startBin) { projey = fLinearHisto->ProjectionY("ProjectionAfterLin",startBin-width*3,startBin+width*3); int nfound = fSpectrum.Search(projey,0.05,"goff",0.0001); Info("FindALine","%d peack found...",nfound); #if ROOT_VERSION_CODE > ROOT_VERSION(5,99,01) Double_t* xpeaks = fSpectrum.GetPositionX(); Double_t* ypeaks = fSpectrum.GetPositionY(); #else Float_t* xpeaks = fSpectrum.GetPositionX(); Float_t* ypeaks = fSpectrum.GetPositionY(); #endif for(int p=0;p<nfound;p++) { if(p>8) break; if(ypeaks[p]<10) continue; Double_t xline = fLinearHisto->GetXaxis()->GetBinCenter(startBin); Double_t yline = xpeaks[p]; KVSpiderLine* tmp = 0; TIter next(&Lines); while((tmp=(KVSpiderLine*)next())) { Info("FindALine","line found but I don't know why..."); if(TMath::Abs(tmp->GetY()-yline)<0.05) continue; } tmp = new KVSpiderLine(zz,-1); Lines.AddLast(tmp); tmp->AddPoint(xline,yline); fPoints->SetPoint(fNPoints,xline,yline); fNPoints++; } if(projey) delete projey; } else Error("FindALine","not starting bin indicated..."); SortLines(&Lines); Int_t nLines = Lines.GetSize(); tmp = 0; for(int xx=startBin-width; xx>xbmin; xx-=width) { projey = fLinearHisto->ProjectionY("ProjectionAfterLin",xx-width/2,xx+width/2); int nfound = fSpectrum.Search(projey,0.05,"goff",0.02); #if ROOT_VERSION_CODE > ROOT_VERSION(5,99,01) Double_t* xpeaks = fSpectrum.GetPositionX(); Double_t* ypeaks = fSpectrum.GetPositionY(); #else Float_t* xpeaks = fSpectrum.GetPositionX(); Float_t* ypeaks = fSpectrum.GetPositionY(); #endif for(int p=0;p<nfound;p++) { if(p>=nLines+1) continue; if(ypeaks[p]<5) continue; Double_t xline = fLinearHisto->GetXaxis()->GetBinCenter(xx); Double_t yline = xpeaks[p]; KVSpiderLine* tmp = 0; TIter next(&Lines); while((tmp=(KVSpiderLine*)next())) { if((TMath::Abs(tmp->GetY()-yline)<0.05)) break; } if(tmp) { if((TMath::Abs(tmp->GetX()-xline)<10*width)) tmp->AddPoint(xline,yline); } } if(projey) delete projey; } TIter nextli(&Lines); while((tmp=(KVSpiderLine*)nextli()))tmp->Sort(true); tmp = 0; for(int xx=startBin+width; xx<=xbmax-width/2; xx+=width) { projey = fLinearHisto->ProjectionY("ProjectionAfterLin",xx-width/2,xx+width/2); int nfound = fSpectrum.Search(projey,0.05,"goff",0.02); #if ROOT_VERSION_CODE > ROOT_VERSION(5,99,01) Double_t* xpeaks = fSpectrum.GetPositionX(); Double_t* ypeaks = fSpectrum.GetPositionY(); #else Float_t* xpeaks = fSpectrum.GetPositionX(); Float_t* ypeaks = fSpectrum.GetPositionY(); #endif for(int p=0;p<nfound;p++) { if(p>=nLines+1) continue; if(ypeaks[p]<5) continue; Double_t xline = fLinearHisto->GetXaxis()->GetBinCenter(xx); Double_t yline = xpeaks[p]; KVSpiderLine* tmp = 0; TIter next(&Lines); while((tmp=(KVSpiderLine*)next())) { if(TMath::Abs(tmp->GetY()-yline)<0.05) break; } if(tmp) { if((TMath::Abs(tmp->GetX()-xline)<10*width)) tmp->AddPoint(xline,yline); } } if(projey) delete projey; } fLines->AddAll(&Lines); }
void printCalibStat(Int_t run, const char * fname, TTreeSRedirector * pcstream){ // // Dump the statistical information about all histograms in the calibration files // into the statistical tree, print on the screen (log files) as well // // // 1. Default dump for all histograms // Information to dump: // stat =Entries, Mean, MeanError, RMS, MaxBin // Branch naming convention: // <detName>_<hisName><statName> // // 2. Detector statistical information - to be implemented by expert // - First version implemented by MI // // TFile *fin = TFile::Open(fname); if (!fin) return; const Double_t kMaxHis=10000; TList * keyList = fin->GetListOfKeys(); Int_t nkeys=keyList->GetEntries(); Double_t *hisEntries = new Double_t[kMaxHis]; Double_t *hisMean = new Double_t[kMaxHis]; Double_t *hisMeanError = new Double_t[kMaxHis]; Double_t *hisRMS = new Double_t[kMaxHis]; Double_t *hisMaxBin = new Double_t[kMaxHis]; Int_t counter=0; if (pcstream) (*pcstream)<<"calibStatAll"<<"run="<<run; for (Int_t ikey=0; ikey<nkeys; ikey++){ TObject * object = fin->Get(keyList->At(ikey)->GetName()); if (!object) continue; if (object->InheritsFrom("TCollection")==0) continue; TSeqCollection *collection = (TSeqCollection*)object; Int_t nentries= collection->GetEntries(); for (Int_t ihis=0; ihis<nentries; ihis++){ TObject * ohis = collection->At(ihis); if (!ohis) continue; if (ohis->InheritsFrom("TH1")==0) continue; TH1* phis = (TH1*)ohis; hisEntries[counter]=phis->GetEntries(); Int_t idim=1; if (ohis->InheritsFrom("TH2")) idim=2; if (ohis->InheritsFrom("TH3")) idim=3; hisMean[counter]=phis->GetMean(idim); hisMeanError[counter]=phis->GetMeanError(idim); hisRMS[counter]=phis->GetRMS(idim); hisMaxBin[counter]=phis->GetBinCenter(phis->GetMaximumBin()); if (pcstream) (*pcstream)<<"calibStatAll"<< Form("%s_%sEntries=",keyList->At(ikey)->GetName(), phis->GetName())<<hisEntries[counter]<< Form("%s_%sMean=",keyList->At(ikey)->GetName(), phis->GetName())<<hisMean[counter]<< Form("%s_%sMeanError=",keyList->At(ikey)->GetName(), phis->GetName())<<hisMeanError[counter]<< Form("%s_%sRMS=",keyList->At(ikey)->GetName(), phis->GetName())<<hisRMS[counter]<< Form("%s_%sMaxBin=",keyList->At(ikey)->GetName(), phis->GetName())<<hisMaxBin[counter]; //printf("Histo:\t%s_%s\t%f\t%d\n",keyList->At(ikey)->GetName(), phis->GetName(), hisEntries[counter],idim); counter++; } delete object; } // // Expert dump example (MI first iteration): // // 0.) TOF dump // Int_t tofEvents=0; Int_t tofTracks=0; TList * TOFCalib = (TList*)fin->Get("TOFHistos"); if (TOFCalib) { TH1 *histoEvents = (TH1*)TOFCalib->FindObject("hHistoVertexTimestamp"); TH1 *histoTracks = (TH1*)TOFCalib->FindObject("hHistoDeltatTimestamp"); if (histoEvents && histoTracks){ tofEvents = TMath::Nint(histoEvents->GetEntries()); tofTracks = TMath::Nint(histoTracks->GetEntries()); } delete TOFCalib; } printf("Monalisa TOFevents\t%d\n",tofEvents); if (pcstream) (*pcstream)<<"calibStatAll"<<"TOFevents="<<tofEvents; printf("Monalisa TOFtracks\t%d\n",tofTracks); if (pcstream) (*pcstream)<<"calibStatAll"<<"TOFtracks="<<tofTracks; // // 1.) TPC dump - usefull events/tracks for the calibration // Int_t tpcEvents=0; Int_t tpcTracks=0; TObject* obj = dynamic_cast<TObject*>(fin->Get("TPCCalib")); TObjArray* array = dynamic_cast<TObjArray*>(obj); TDirectory* dir = dynamic_cast<TDirectory*>(obj); AliTPCcalibTime * calibTime = NULL; if (dir) { calibTime = dynamic_cast<AliTPCcalibTime*>(dir->Get("calibTime")); } else if (array){ calibTime = (AliTPCcalibTime *)array->FindObject("calibTime"); } if (calibTime) { tpcEvents = TMath::Nint(calibTime->GetTPCVertexHisto(0)->GetEntries()); tpcTracks = TMath::Nint(calibTime->GetResHistoTPCITS(0)->GetEntries()); } printf("Monalisa TPCevents\t%d\n",tpcEvents); if (pcstream) (*pcstream)<<"calibStatAll"<<"TPCevents="<<tpcEvents; printf("Monalisa TPCtracks\t%d\n",tpcTracks); if (pcstream) (*pcstream)<<"calibStatAll"<<"TPCtracks="<<tpcTracks; // // 2. TRD dump // Int_t trdEvents=0; Int_t trdTracks=0; TList * TRDCalib = (TList*)fin->Get("TRDCalib"); if (TRDCalib) { TH1 *histoEvents = (TH1*)TRDCalib->FindObject("NEventsInput_AliTRDCalibTask"); TH1 *histoTracks = (TH1*)TRDCalib->FindObject("AbsoluteGain_AliTRDCalibTask"); if (histoEvents && histoTracks){ trdEvents= TMath::Nint(histoEvents->GetEntries()); trdTracks= TMath::Nint(histoTracks->GetEntries()); } delete TRDCalib; } printf("Monalisa TRDevents\t%d\n",trdEvents); if (pcstream) (*pcstream)<<"calibStatAll"<<"TRDevents="<<trdEvents; printf("Monalisa TRDtracks\t%d\n",trdTracks); if (pcstream) (*pcstream)<<"calibStatAll"<<"TRDtracks="<<trdTracks; // // 3. T0 dump // Int_t T0Events=0; TList * T0Calib = (TList*)fin->Get("T0Calib"); if (T0Calib) { TH1 *histoEvents = (TH1*) T0Calib->FindObject("fTzeroORAplusORC"); if (histoEvents){ T0Events= TMath::Nint(histoEvents->GetEntries()); } delete T0Calib; } printf("Monalisa T0events\t%d\n",T0Events); if (pcstream) (*pcstream)<<"calibStatAll"<<"T0events="<<T0Events; // // 4. Mean vertex - dump // Not present in CPass1 /* Int_t meanVertexEvents=0; TList * meanVertexCalib = (TList*)fin->Get("MeanVertex"); if (meanVertexCalib) { TH1 *histoEvents = (TH1*) meanVertexCalib->FindObject("hTRKVertexX"); if (histoEvents){ meanVertexEvents = TMath::Nint(histoEvents->GetEntries()); } delete meanVertexCalib; } printf("Monalisa MeanVertexevents\t%d\n",meanVertexEvents); if (pcstream) (*pcstream)<<"calibStatAll"<<"MeanVertexevents="<<meanVertexEvents; */ // // 5. SDD dump // Int_t sddEvents=0; Int_t sddTracks=0; TList * SDDCalib = (TList*)fin->Get("clistSDDCalib"); if (SDDCalib) { TH1 *histoEvents = (TH1*) SDDCalib->FindObject("hNEvents"); if (histoEvents ){ sddEvents = TMath::Nint(histoEvents->GetBinContent(4)); sddTracks = TMath::Nint(histoEvents->GetBinContent(5)); } delete SDDCalib; } printf("Monalisa SDDevents\t%d\n",sddEvents); if (pcstream) (*pcstream)<<"calibStatAll"<<"SDDevents="<<sddEvents; printf("Monalisa SDDtracks\t%d\n",sddTracks); if (pcstream) (*pcstream)<<"calibStatAll"<<"SDDtracks="<<sddTracks; // // 6. AD dump // Int_t adEvents=0; TDirectory *adDir = (TDirectory*)fin->Get("ADCalib"); if (adDir) { TList *adList = (TList*) adDir->Get("ADCalibListHist"); if (adList) { TH2* adHistInt0 = (TH2*) adList->FindObject("hCh00_bc10_int0"); if (adHistInt0) adEvents += TMath::Nint(adHistInt0->GetEntries()); TH2* adHistInt1 = (TH2*) adList->FindObject("hCh00_bc10_int1"); if (adHistInt1) adEvents += TMath::Nint(adHistInt1->GetEntries()); delete adList; } } printf("Monalisa ADevents\t%d\n",adEvents); if (pcstream) (*pcstream)<<"calibStatAll"<<"ADevents="<<adEvents; // if (pcstream) (*pcstream)<<"calibStatAll"<<"\n"; delete fin; }
double leptonic_fitter_algebraic::likeliest_scale( const TH1& ITF ) { Int_t ibin = ITF.GetMaximumBin(); return ITF.GetBinCenter( ibin ); }
void ptBestFit(float BIN_SIZE=5.0,bool BLIND=false,TString MASS,TString NAME) { gROOT->ProcessLine(".x ../../common/styleCMSTDR.C"); gSystem->Load("libHiggsAnalysisCombinedLimit.so"); gROOT->ForceStyle(); gStyle->SetOptStat(0); gStyle->SetOptTitle(0); gROOT->SetBatch(1); gStyle->SetPadRightMargin(0.04); gStyle->SetPadLeftMargin(0.16); gStyle->SetPadTopMargin(0.06); gStyle->SetPadBottomMargin(0.10); gStyle->SetTitleFont(42,"XY"); gStyle->SetTitleSize(0.0475,"XY"); gStyle->SetTitleOffset(0.9,"X"); gStyle->SetTitleOffset(1.5,"Y"); gStyle->SetLabelSize(0.0375,"XY"); RooMsgService::instance().setSilentMode(kTRUE); for(int i=0;i<2;i++) { RooMsgService::instance().setStreamStatus(i,kFALSE); } float XMIN = 80; float XMAX = 200; TFile *f1 = TFile::Open("datacards/datacard_m"+MASS+"_"+NAME+".root"); TFile *f2 = TFile::Open("combine/mlfit.vbfHbb_"+NAME+"_mH"+MASS+".root"); TFile *f3 = TFile::Open("root/sig_shapes_workspace_B80-200.root"); TFile *f4 = TFile::Open("root/data_shapes_workspace_"+NAME+".root"); RooWorkspace *w = (RooWorkspace*)f1->Get("w"); //w->Print(); RooAbsPdf *bkg_model = (RooAbsPdf*)w->pdf("model_s"); RooFitResult *res_s = (RooFitResult*)f2->Get("fit_s"); RooFitResult *res_b = (RooFitResult*)f2->Get("fit_b"); RooRealVar *rFit = dynamic_cast<RooRealVar *>(res_s->floatParsFinal()).find("r"); RooDataSet *data = (RooDataSet*)w->data("data_obs"); int nparS=0,nparB=0; cout << res_s->floatParsFinal().getSize() << endl; cout << res_b->floatParsFinal().getSize() << endl; nparS = res_s->floatParsFinal().getSize(); nparB = res_b->floatParsFinal().getSize(); float chi2sumS = 0.; float chi2sumB = 0.; int nparsum = 0; // if (BLIND) { // res_b->Print(); // } // else { // res_s->Print(); // } w->allVars().assignValueOnly(res_s->floatParsFinal()); // w->Print(); // w->allVars()->Print(); RooWorkspace *wSig = (RooWorkspace*)f3->Get("w"); RooWorkspace *wDat = (RooWorkspace*)f4->Get("w"); const RooSimultaneous *sim = dynamic_cast<const RooSimultaneous *> (bkg_model); const RooAbsCategoryLValue &cat = (RooAbsCategoryLValue &) sim->indexCat(); TList *datasets = data->split(cat,true); TIter next(datasets); //int count = 0; for(RooAbsData *ds = (RooAbsData*)next();ds != 0; ds = (RooAbsData*)next()) { //if (count > 0) return 0; //count++; RooAbsPdf *pdfi = sim->getPdf(ds->GetName()); RooArgSet *obs = (RooArgSet*)pdfi->getObservables(ds); RooRealVar *x = dynamic_cast<RooRealVar *>(obs->first()); RooRealVar *yield_vbf = (RooRealVar*)wSig->var("yield_signalVBF_mass"+MASS+"_"+TString(ds->GetName())); RooRealVar *yield_gf = (RooRealVar*)wSig->var("yield_signalGF_mass"+MASS+"_"+TString(ds->GetName())); TString ds_name(ds->GetName()); //----- get the QCD normalization ----------- RooRealVar *qcd_norm_final = dynamic_cast<RooRealVar *>(res_s->floatParsFinal()).find("CMS_vbfbb_qcd_norm_"+ds_name); RooRealVar *qcd_yield = (RooRealVar*)wDat->var("yield_data_"+ds_name); float Nqcd = exp(log(1.5)*qcd_norm_final->getVal())*qcd_yield->getVal(); float eNqcd = log(1.5)*qcd_norm_final->getError()*Nqcd; cout<<"QCD normalization = "<<Nqcd<<" +/- "<<eNqcd<<endl; TH1 *hCoarse = (TH1*)ds->createHistogram("coarseHisto_"+ds_name,*x); float norm = hCoarse->Integral(); int rebin = BIN_SIZE/hCoarse->GetBinWidth(1); hCoarse->Rebin(rebin); float MIN_VAL = TMath::Max(0.9*hCoarse->GetBinContent(hCoarse->GetMinimumBin()),1.0); float MAX_VAL = 1.3*hCoarse->GetBinContent(hCoarse->GetMaximumBin()); RooDataHist ds_coarse("ds_coarse_"+ds_name,"ds_coarse_"+ds_name,*x,hCoarse); TH1F *hBlind = (TH1F*)hCoarse->Clone("blindHisto_"+ds_name); for(int i=0;i<hBlind->GetNbinsX();i++) { double x0 = hBlind->GetBinCenter(i+1); if (x0 > 100 && x0 < 150) { hBlind->SetBinContent(i+1,0); hBlind->SetBinError(i+1,0); } } RooDataHist ds_blind("ds_blind_"+ds_name,"ds_blind_"+ds_name,*x,hBlind); RooHist *hresid,*hresid0; RooPlot *frame1 = x->frame(); RooPlot *frame2 = x->frame(); if (BLIND) { //cout << "Blind case: " << ds_coarse.GetName() << endl; ds_coarse.plotOn(frame1,LineColor(0),MarkerColor(0)); pdfi->plotOn(frame1,Components("shapeBkg_qcd_"+ds_name+",shapeBkg_top_"+ds_name+",shapeBkg_zjets_"+ds_name),VisualizeError(*res_s,1,kTRUE),FillColor(0),MoveToBack()); pdfi->plotOn(frame1,Components("shapeBkg_qcd_"+ds_name+",shapeBkg_top_"+ds_name+",shapeBkg_zjets_"+ds_name),LineWidth(2),LineStyle(3)); ds_blind.plotOn(frame1); hresid = frame1->residHist(); frame2->addPlotable(hresid,"pE1"); } else { //cout << "Non-blind case: " << ds_coarse.GetName() << endl; ds_coarse.plotOn(frame1); pdfi->plotOn(frame1); //cout << pdfi->getParameters(ds_coarse)->selectByAttrib("Constant",kFALSE)->getSize() << endl; cout<<"chi2/ndof (bkg+sig) = "<<frame1->chiSquare()<<endl; cout << ds_coarse.numEntries() << endl; chi2sumS += frame1->chiSquare()*ds_coarse.numEntries(); nparsum += ds_coarse.numEntries(); //hresid0 = frame1->residHist(); //pdfi->plotOn(frame1,VisualizeError(*res_s,1,kTRUE),FillColor(0),MoveToBack()); pdfi->plotOn(frame1,Components("shapeBkg_qcd_"+ds_name),LineWidth(2),LineStyle(5),LineColor(kGreen+2)); pdfi->plotOn(frame1,Components("shapeBkg_qcd_"+ds_name+",shapeBkg_top_"+ds_name+",shapeBkg_zjets_"+ds_name),LineWidth(2),LineStyle(2),LineColor(kBlack)); cout<<"chi2/ndof (bkg) = "<<frame1->chiSquare()<<endl; chi2sumB += frame1->chiSquare()*ds_coarse.numEntries(); pdfi->plotOn(frame1,Components("shapeBkg_qcd_"+ds_name+",shapeBkg_top_"+ds_name+",shapeBkg_zjets_"+ds_name),LineWidth(2),LineStyle(2),LineColor(kBlack),VisualizeError(*res_s,1,kTRUE),FillColor(0),MoveToBack()); hresid = frame1->residHist(); frame2->addPlotable(hresid,"pE1"); float yield_sig = rFit->getValV()*(yield_vbf->getValV()+yield_gf->getValV()); RooAbsPdf *signal_pdf = (RooAbsPdf*)w->pdf("shapeSig_qqH_"+ds_name); signal_pdf->plotOn(frame2,LineWidth(2),LineColor(kRed),Normalization(yield_sig,RooAbsReal::NumEvent),MoveToBack()); } // hresid0->Print(); // hresid->Print(); // double x2,y2; // for (int i=0; i<3; ++i) { // hresid0->GetPoint(i,x2,y2); // cout << "BKG+SIG\t" << x2 << "\t" << y2 << endl; // hresid->GetPoint(i,x2,y2); // cout << "BKG\t" << x2 << "\t" << y2 << endl; // ds_coarse.get(i); // cout << ds_coarse.weightError(RooAbsData::SumW2) << endl; // cout << endl; // } TCanvas* canFit = new TCanvas("Higgs_fit_"+ds_name,"Higgs_fit_"+ds_name,900,750); canFit->cd(1)->SetBottomMargin(0.4); frame1->SetMinimum(MIN_VAL); frame1->SetMaximum(MAX_VAL); frame1->GetYaxis()->SetNdivisions(510); frame1->GetXaxis()->SetTitleSize(0); frame1->GetXaxis()->SetLabelSize(0); frame1->GetYaxis()->SetTitle(TString::Format("Events / %1.1f GeV",BIN_SIZE)); frame1->Draw(); gPad->Update(); TList *list = (TList*)gPad->GetListOfPrimitives(); //list->Print(); TH1F *hUncH = new TH1F("hUncH"+ds_name,"hUncH"+ds_name,(XMAX-XMIN)/BIN_SIZE,XMIN,XMAX); TH1F *hUncL = new TH1F("hUncL"+ds_name,"hUncL"+ds_name,(XMAX-XMIN)/BIN_SIZE,XMIN,XMAX); TH1F *hUnc2H = new TH1F("hUnc2H"+ds_name,"hUnc2H"+ds_name,(XMAX-XMIN)/BIN_SIZE,XMIN,XMAX); TH1F *hUnc2L = new TH1F("hUnc2L"+ds_name,"hUnc2L"+ds_name,(XMAX-XMIN)/BIN_SIZE,XMIN,XMAX); TH1F *hUncC = new TH1F("hUncC"+ds_name,"hUncC"+ds_name,(XMAX-XMIN)/BIN_SIZE,XMIN,XMAX); RooCurve *errorBand,*gFit,*gQCDFit,*gBkgFit; //list->Print(); if (BLIND) { errorBand = (RooCurve*)list->FindObject("pdf_bin"+ds_name+"_Norm[mbbReg_"+ds_name+"]_errorband_Comp[shapeBkg_qcd_"+ds_name+",shapeBkg_top_"+ds_name+",shapeBkg_zjets_"+ds_name+"]"); gFit = (RooCurve*)list->FindObject("pdf_bin"+ds_name+"_Norm[mbbReg_"+ds_name+"]"+"_Comp[shapeBkg_qcd_"+ds_name+",shapeBkg_top_"+ds_name+",shapeBkg_zjets_"+ds_name+"]"); } else { //errorBand = (RooCurve*)list->FindObject("pdf_bin"+ds_name+"_Norm[mbbReg_"+ds_name+"]_errorband"); errorBand = (RooCurve*)list->FindObject("pdf_bin"+ds_name+"_Norm[mbbReg_"+ds_name+"]_errorband_Comp[shapeBkg_qcd_"+ds_name+",shapeBkg_top_"+ds_name+",shapeBkg_zjets_"+ds_name+"]"); gFit = (RooCurve*)list->FindObject("pdf_bin"+ds_name+"_Norm[mbbReg_"+ds_name+"]"); } gQCDFit = (RooCurve*)list->FindObject("pdf_bin"+ds_name+"_Norm[mbbReg_"+ds_name+"]"+"_Comp[shapeBkg_qcd_"+ds_name+"]"); gBkgFit = (RooCurve*)list->FindObject("pdf_bin"+ds_name+"_Norm[mbbReg_"+ds_name+"]"+"_Comp[shapeBkg_qcd_"+ds_name+",shapeBkg_top_"+ds_name+",shapeBkg_zjets_"+ds_name+"]"); for(int i=0;i<hUncH->GetNbinsX();i++) { double x0 = hUncH->GetBinCenter(i+1); double e1 = fabs(errorBand->Eval(x0)-gBkgFit->Eval(x0)); //double e1 = fabs(errorBand->Eval(x0)-gFit->Eval(x0)); double e2 = eNqcd/hUncH->GetNbinsX(); hUncH->SetBinContent(i+1,sqrt(pow(e2,2)+pow(e1,2))); hUnc2H->SetBinContent(i+1,2*sqrt(pow(e2,2)+pow(e1,2))); hUncL->SetBinContent(i+1,-sqrt(pow(e2,2)+pow(e1,2))); hUnc2L->SetBinContent(i+1,-2*sqrt(pow(e2,2)+pow(e1,2))); hUncC->SetBinContent(i+1,0.); } TPad* pad = new TPad("pad", "pad", 0., 0., 1., 1.); pad->SetTopMargin(0.63); pad->SetFillColor(0); pad->SetFillStyle(0); pad->Draw(); pad->cd(0); hUnc2H->GetXaxis()->SetTitle("m_{bb} (GeV)"); hUnc2H->GetYaxis()->SetTitle("Data - Bkg"); //hUnc2H->GetYaxis()->SetTitle("Data - Fit"); double YMAX = 1.1*frame2->GetMaximum(); double YMIN = -1.1*frame2->GetMaximum(); hUnc2H->GetYaxis()->SetRangeUser(YMIN,YMAX); hUnc2H->GetYaxis()->SetNdivisions(507); // hUnc2H->GetXaxis()->SetTitleOffset(0.9); // hUnc2H->GetYaxis()->SetTitleOffset(1.0); hUnc2H->GetYaxis()->SetTickLength(0.0); // hUnc2H->GetYaxis()->SetTitleSize(0.05); // hUnc2H->GetYaxis()->SetLabelSize(0.04); hUnc2H->GetYaxis()->CenterTitle(kTRUE); hUnc2H->SetFillColor(kGreen); hUnc2L->SetFillColor(kGreen); hUncH->SetFillColor(kYellow); hUncL->SetFillColor(kYellow); hUncC->SetLineColor(kBlack); hUncC->SetLineStyle(7); hUnc2H->Draw("HIST"); hUnc2L->Draw("same HIST"); hUncH->Draw("same HIST"); hUncL->Draw("same HIST"); hUncC->Draw("same HIST"); frame2->GetYaxis()->SetTickLength(0.03/0.4); frame2->Draw("same"); TList *list1 = (TList*)gPad->GetListOfPrimitives(); //list1->Print(); RooCurve *gSigFit = (RooCurve*)list1->FindObject("shapeSig_qqH_"+ds_name+"_Norm[mbbReg_"+ds_name+"]"); TLegend *leg = new TLegend(0.70,0.61,0.94,1.-gStyle->GetPadTopMargin()-0.01); leg->SetTextFont(42); leg->SetFillStyle(-1); //leg->SetHeader(ds_name+" (m_{H}="+MASS+")"); leg->SetHeader(TString::Format("Category %d",atoi(ds_name(3,1).Data())+1)); leg->AddEntry(hBlind,"Data","P"); if (!BLIND) { leg->AddEntry(gSigFit,"Fitted signal","L"); } TLine *gEmpty = new TLine(0.0,0.0,0.0,0.0); gEmpty->SetLineWidth(0); TLegendEntry *l1 = leg->AddEntry(gEmpty,"(m_{H} = "+MASS+" GeV)",""); l1->SetTextSize(0.038*0.97*0.85); leg->AddEntry(gFit,"Bkg. + signal","L"); leg->AddEntry(gBkgFit,"Bkg.","L"); leg->AddEntry(gQCDFit,"QCD","L"); leg->AddEntry(hUnc2H,"2#sigma bkg. unc.","F"); leg->AddEntry(hUncH,"1#sigma bkg. unc.","F"); leg->SetFillColor(0); leg->SetBorderSize(0); leg->SetTextFont(42); leg->SetTextSize(0.038*0.98); leg->Draw(); leg->SetY1(leg->GetY2()-leg->GetNRows()*0.045*0.96); TPaveText *paveCMS = new TPaveText(gStyle->GetPadLeftMargin()+0.02,0.7,gStyle->GetPadLeftMargin()+0.15,1.-gStyle->GetPadTopMargin()-0.01,"NDC"); paveCMS->SetTextFont(62); paveCMS->SetTextSize(gStyle->GetPadTopMargin()*3./4.); paveCMS->SetBorderSize(0); paveCMS->SetFillStyle(-1); paveCMS->SetTextAlign(12); paveCMS->AddText("CMS"); paveCMS->Draw(); gPad->Update(); paveCMS->SetY1NDC(paveCMS->GetY2NDC()-paveCMS->GetListOfLines()->GetSize()*gStyle->GetPadTopMargin()); TPaveText *paveLumi = new TPaveText(0.5,1.-gStyle->GetPadTopMargin(),0.98,1.00,"NDC"); paveLumi->SetTextFont(42); paveLumi->SetTextSize(gStyle->GetPadTopMargin()*3./4.); paveLumi->SetBorderSize(0); paveLumi->SetFillStyle(-1); paveLumi->SetTextAlign(32); paveLumi->AddText(TString::Format("%.1f fb^{-1} (8TeV)",(atoi(ds_name(3,1).Data())<4 ? 19.8 : 18.3)).Data());//+ 18.2 ; paveLumi->Draw(); TString path="."; //TString path="BiasV10_limit_BRN5p4_dX0p1_B80-200_CAT0-6/output/"; system(TString::Format("[ ! -d %s/plot ] && mkdir %s/plot",path.Data(),path.Data()).Data()); system(TString::Format("[ ! -d %s/plot/fits ] && mkdir %s/plot/fits",path.Data(),path.Data()).Data()); canFit->SaveAs(TString::Format("%s/plot/fits/Fit_mH%s_%s.pdf",path.Data(),MASS.Data(),ds_name.Data()).Data()); canFit->SaveAs(TString::Format("%s/plot/fits/Fit_mH%s_%s.png",path.Data(),MASS.Data(),ds_name.Data()).Data()); canFit->SaveAs(TString::Format("%s/plot/fits/Fit_mH%s_%s.eps",path.Data(),MASS.Data(),ds_name.Data()).Data()); TText *l = (TText*)paveCMS->AddText("Preliminary"); l->SetTextFont(52); paveCMS->Draw(); gPad->Update(); paveCMS->SetY1NDC(paveCMS->GetY2NDC()-paveCMS->GetListOfLines()->GetSize()*gStyle->GetPadTopMargin()); canFit->SaveAs(TString::Format("%s/plot/fits/Fit_mH%s_%s_prelim.pdf",path.Data(),MASS.Data(),ds_name.Data()).Data()); canFit->SaveAs(TString::Format("%s/plot/fits/Fit_mH%s_%s_prelim.png",path.Data(),MASS.Data(),ds_name.Data()).Data()); canFit->SaveAs(TString::Format("%s/plot/fits/Fit_mH%s_%s_prelim.eps",path.Data(),MASS.Data(),ds_name.Data()).Data()); delete ds; } cout << "chi2sumS: " << chi2sumS << endl; cout << "chi2sumB: " << chi2sumB << endl; cout << "nparS: " << nparS << endl; cout << "nparB: " << nparB << endl; cout << "nbinsum: " << nparsum << endl; cout << "chi2sumS/(nbinsum - nparS): " << chi2sumS / (float)(nparsum - nparS) << endl; cout << "chi2sumB/(nbinsum - nparB): " << chi2sumB / (float)(nparsum - nparB) << endl; delete datasets; }
void makeStack(TString myVar, TString myCut, TString myName, TString myAxisNameX, TString myAxisNameY, vector<const Sample*>& listOfSignals, vector<const Sample*>& listOfSamples, vector<const Sample*> listOfDatasets, TString inFileName, bool isBlind, bool isLog, bool drawSignal, bool drawLegend, int nBins, float xLow, float xHigh, float* xlowVec) { // prepare the input file TFile* infile = new TFile(inFileName, "READ"); infile -> cd(); // prepare the stack THStack *hs = new THStack("hs",""); // prepare the histos pointers TH1F* hist[20]; // prepare the tree pointers TTree* tree[20]; // prepare the legend TLegend* leg = new TLegend(.7485,.7225,.9597,.9604); leg->SetFillColor(0); // prepare the colors Int_t col[20] = {46,2,12,5,3,4,9,7,47,49,49,50,51,52,53,54,55,56,57,58}; // prepare the cut if (isBlind) myCut += "*(phoMetDeltaPhi < 2.9)"; // prepare the Y axis lable if (xlowVec != 0) myAxisNameY = "Events/" + myAxisNameY; else { float binWidth = (xHigh-xLow)/nBins; TString tempString; tempString.Form("%.2f ",binWidth); myAxisNameY = "Events/" + tempString + myAxisNameY; } // prepare the legend strings vector<TString> theLegends; // loop through the datasets and produce the plots TH1F* hdata; TH1F* hsignal; //prepare data and signal histos if (xlowVec != 0) hdata = new TH1F("hdata","",nBins,xlowVec); else hdata = new TH1F("hdata","",nBins,xLow,xHigh); if (xlowVec != 0) hsignal = new TH1F("hsignal","",nBins,xlowVec); else hsignal = new TH1F("hsignal","",nBins,xLow,xHigh); TTree* treedata[20]; for (UInt_t iDatas=0; iDatas < listOfDatasets.size(); iDatas++) { //get the tree treedata[iDatas] = (TTree*) infile -> Get(listOfDatasets.at(iDatas)->Name()->Data()); //fill the histogram if ( iDatas == 0 ) treedata[iDatas] -> Draw(myVar + " >> hdata","evt_weight*kf_weight*pu_weight" + myCut); else treedata[iDatas] -> Draw(myVar + " >>+ hdata","evt_weight*kf_weight*pu_weight" + myCut); if ( isBlind && iDatas == 0 ) leg -> AddEntry(hdata, "DATA (19.8 fb^{-1})", "pl"); }//end loop on datasets if (xlowVec != 0) { for (int iBin = 1; iBin <= nBins; iBin++) hdata->SetBinError (iBin,hdata->GetBinError(iBin)/hdata->GetBinWidth(iBin)); for (int iBin = 1; iBin <= nBins; iBin++) hdata->SetBinContent(iBin,hdata->GetBinContent(iBin)/hdata->GetBinWidth(iBin)); } TTree* treesignal[20]; for (UInt_t iSignal=0; iSignal < listOfSignals.size(); iSignal++) { //get the tree treesignal[iSignal] = (TTree*) infile -> Get(listOfSignals.at(iSignal)->Name()->Data()); //fill the histogram TString thisScale = Form("%f *", *(listOfSignals.at(iSignal)->Scale())); if ( iSignal == 0 ) treesignal[iSignal] -> Draw(myVar + " >> hsignal",thisScale + "evt_weight*kf_weight*pu_weight" + myCut); else treesignal[iSignal] -> Draw(myVar + " >>+ hsignal",thisScale + "evt_weight*kf_weight*pu_weight" + myCut); if ( drawSignal && iSignal == 0 ) leg -> AddEntry(hsignal, "Signal", "l"); }//end loop on signals if (xlowVec != 0) { for (int iBin = 1; iBin <= nBins; iBin++) hsignal->SetBinError (iBin,hsignal->GetBinError(iBin)/hsignal->GetBinWidth(iBin)); for (int iBin = 1; iBin <= nBins; iBin++) hsignal->SetBinContent(iBin,hsignal->GetBinContent(iBin)/hsignal->GetBinWidth(iBin)); } hsignal -> SetLineColor(49); hsignal -> SetLineWidth(4.0); int theHistCounter = 0; // loop through the samples and produce the plots for (UInt_t iSample=0; iSample < listOfSamples.size(); iSample++) { //determine if the histo is first of the series bool isFirstOfSerie = (*listOfSamples.at(iSample)->Legend()).CompareTo(" "); bool isLastOfSerie = false; if (iSample == listOfSamples.size() - 1) isLastOfSerie = true; if (iSample < listOfSamples.size() - 1 && (*listOfSamples.at(iSample+1)->Legend()).CompareTo(" ") != 0) isLastOfSerie = true; //get the tree tree[iSample] = (TTree*) infile -> Get(listOfSamples.at(iSample)->Name()->Data()); //if sample first of the list create a new histogram if (isFirstOfSerie) { TString thisHistName = "h_" + *(listOfSamples.at(iSample)->Name()); //variable bin histo if (xlowVec != 0) hist[theHistCounter] = new TH1F(thisHistName,thisHistName,nBins,xlowVec); //fixed bin histo else hist[theHistCounter] = new TH1F(thisHistName,thisHistName,nBins,xLow,xHigh); hist[theHistCounter] -> Sumw2(); hist[theHistCounter] -> SetFillColor(col[theHistCounter]); hist[theHistCounter] -> SetFillStyle(1001); theLegends.push_back(*listOfSamples.at(iSample)->Legend()); } //fill the histogram TString thisScale = Form("%f *", *(listOfSamples.at(iSample)->Scale())); if (isFirstOfSerie) tree[iSample] -> Draw(myVar + " >> " + TString(hist[theHistCounter] -> GetName()),thisScale + "evt_weight*kf_weight*pu_weight" + myCut); else tree[iSample] -> Draw(myVar + " >>+ " + TString(hist[theHistCounter] -> GetName()),thisScale + "evt_weight*kf_weight*pu_weight" + myCut); //add the histogram to the stack if the last of the series: //either last sample or ~ sample followed by non ~ sample if (isLastOfSerie) { if (xlowVec != 0) { for (int iBin = 1; iBin <= nBins; iBin++) hist[theHistCounter]->SetBinError (iBin,hist[theHistCounter]->GetBinError(iBin)/hist[theHistCounter]->GetBinWidth(iBin)); for (int iBin = 1; iBin <= nBins; iBin++) hist[theHistCounter]->SetBinContent(iBin,hist[theHistCounter]->GetBinContent(iBin)/hist[theHistCounter]->GetBinWidth(iBin)); } hs -> Add(hist[theHistCounter]); theHistCounter++; } }//end loop on samples //Fix the legend for (int iHisto = theHistCounter-1; iHisto >= 0; iHisto--) { leg -> AddEntry(hist[iHisto], theLegends[iHisto], "f"); } //get the maximum to properly set the frame float theMax = hdata -> GetBinContent(hdata -> GetMaximumBin()) + hdata -> GetBinError(hdata -> GetMaximumBin()); TH1* theMCSum = (TH1*) hs->GetStack()->Last(); float theMaxMC = theMCSum->GetBinContent(theMCSum->GetMaximumBin()) + theMCSum->GetBinError(theMCSum->GetMaximumBin()); if (theMaxMC > theMax) theMax = theMaxMC; //prepare the ratio band and plot TH1* theMCRatioBand = makeRatioBand(theMCSum); TH1* theRatioPlot = makeRatioPlot(hdata,theMCSum); TCanvas* can = new TCanvas(); can -> SetLogy(isLog); TPad *pad1 = new TPad("pad1","top pad",0,0.30,1,1); pad1->SetBottomMargin(0.02); pad1->SetLeftMargin(0.13); pad1->Draw(); TPad *pad2 = new TPad("pad2","bottom pad",0,0.0,1,0.30); pad2->SetTopMargin(0.02); pad2->SetLeftMargin(0.13); pad2->SetBottomMargin(0.4); pad2->SetGridy(); pad2->Draw(); pad1->cd(); hs->Draw("hist"); hdata->Draw("same,pe"); if (drawSignal) hsignal->Draw("same,hist"); if (drawLegend) leg->Draw("same"); //hs->GetXaxis()->SetTitle(myAxisNameX); hs->GetYaxis()->SetTitle(myAxisNameY); hs->GetXaxis()->SetLabelSize(0.04); hs->GetYaxis()->SetLabelSize(0.04); hs->GetXaxis()->SetLabelOffset(0.025); hs->GetYaxis()->SetLabelOffset(0.035); //hs->GetXaxis()->SetTitleOffset(1.1); hs->GetYaxis()->SetTitleOffset(1.1); hs->SetMaximum(theMax); if (isLog) hs->SetMinimum(0.01); pad2->cd(); theMCRatioBand->GetXaxis()->SetTitle(myAxisNameX); theMCRatioBand->GetXaxis()->SetTitleSize(0.16); theMCRatioBand->GetXaxis()->SetTitleOffset(1.1); theMCRatioBand->GetXaxis()->SetLabelSize(0.12); theMCRatioBand->GetXaxis()->SetLabelOffset(0.07); theMCRatioBand->GetYaxis()->SetTitle("Data/MC"); theMCRatioBand->GetYaxis()->SetTitleSize(0.10); theMCRatioBand->GetYaxis()->SetTitleOffset(0.6); theMCRatioBand->GetYaxis()->SetLabelSize(0.06); theMCRatioBand->GetYaxis()->SetLabelOffset(0.03); theMCRatioBand->SetFillStyle(3001); theMCRatioBand->SetFillColor(kBlue); theMCRatioBand->SetLineWidth(1); theMCRatioBand->SetLineColor(kBlack); theMCRatioBand->SetMarkerSize(0.1); theMCRatioBand->SetMaximum(4.); theMCRatioBand->SetMinimum(0.); theMCRatioBand->Draw("E2"); TLine *line = new TLine(xLow,1,xHigh,1); line->SetLineColor(kBlack); line->Draw("same"); theRatioPlot->Draw("same,pe"); can->cd(); can->Modified(); can -> SaveAs(myName + ".pdf","pdf"); //cleanup the memory allocation delete theMCSum; delete hs; delete leg; delete hdata; delete pad1; delete pad2; delete can; delete theMCRatioBand; delete theRatioPlot; infile -> Close(); delete infile; return; }
//______________________________________________________________________________ void CalibrateFit(Int_t nPar, Double_t time_limit, Double_t bad_frac) { // Calibrate using iterative fitting. const Double_t convergence_factor = 0.05; // iterate calibrations for (Int_t i = 0; i >= 0; i++) { // create new histogram TH2* h = CreateHisto("fit_histo", nPar, gOff); // user info printf("Calibration iteration %d\n", i+1); // loop over elements Int_t n = 0; Int_t outside_n = 0; for (Int_t j = 0; j < nPar; j++) { // create projection TH1* hProj = (TH1*) h->ProjectionX(TString::Format("Proj_%d", j).Data(), j+1, j+1, "e"); // check for filled histograms if (hProj->GetEntries()) { // create fitting function TF1* func = new TF1(TString::Format("Func_%d", j).Data(), "gaus", -5, 5); func->SetParameter(0, 1); func->SetParameter(1, hProj->GetXaxis()->GetBinCenter(hProj->GetMaximumBin())); func->SetParameter(2, 0.1); // fit histogram hProj->GetXaxis()->SetRangeUser(-5, 5); hProj->Fit(func, "0Q"); Double_t mean = func->GetParameter(1); // update offset gOff[j] = gOff[j] + convergence_factor * mean / gGain[j]; n++; if (TMath::Abs(mean) > time_limit) outside_n++; // clean-up delete func; } // clean-up delete hProj; } // clean-up delete h; // user info Double_t outside_frac = (Double_t)outside_n/(Double_t)n; printf("Element outside limits: %.1f%%\n", outside_frac*100.); if (outside_frac < bad_frac) break; } }
void makeTable(TString myVar, TString myCut, TString myName, TString myAxisNameX, TString myAxisNameY, vector<const Sample*>& listOfSamples, vector<const Sample*> listOfDatasets, TString inFileName, bool isBlind, bool isLog, int nBins, float xLow, float xHigh, float* xlowVec) { // prepare the input file TFile* infile = new TFile(inFileName, "READ"); infile -> cd(); // prepare the necessary for the scale factor estimation float defScaleFactor = 1.3; float newScaleFactor = 1.; float varScaleFactor = 1.; float nBkg = 0; float nBkgErrSq = 0; float nSig = 0; float nSigErrSq = 0; // prepare the stack THStack *hs = new THStack("hs",""); // prepare the histos pointers TH1F* hist[20]; // prepare the tree pointers TTree* tree[20]; // prepare the legend TLegend* leg = new TLegend(.7485,.7225,.9597,.9604); leg->SetFillColor(0); // prepare the colors Int_t col[20] = {46,2,12,5,3,4,9,7,47,49,49,50,51,52,53,54,55,56,57,58}; // prepare the Y axis lable if (xlowVec != 0) myAxisNameY = "Events/" + myAxisNameY; else { float binWidth = (xHigh-xLow)/nBins; TString tempString; tempString.Form("%.2f ",binWidth); myAxisNameY = "Events/" + tempString + myAxisNameY; } // prepare the legend strings vector<TString> theLegends; // loop through the datasets and produce the plots TH1F* hdata; //variable bin histo if (xlowVec != 0) hdata = new TH1F("hdata","",nBins,xlowVec); //fixed bin histo else hdata = new TH1F("hdata","",nBins,xLow,xHigh); TTree* treedata[20]; for (UInt_t iDatas=0; iDatas < listOfDatasets.size(); iDatas++) { //get the tree treedata[iDatas] = (TTree*) infile -> Get(listOfDatasets.at(iDatas)->Name()->Data()); //fill the histogram if ( iDatas == 0 ) treedata[iDatas] -> Draw(myVar + " >> hdata","hlt_weight*evt_weight*kf_weight*pu_weight" + myCut,"goff"); else treedata[iDatas] -> Draw(myVar + " >>+ hdata","hlt_weight*evt_weight*kf_weight*pu_weight" + myCut,"goff"); if ( iDatas == 0 ) leg -> AddEntry(hdata, "DATA (19.8 fb^{-1})", "pl"); }//end loop on datasets if (xlowVec != 0) { for (int iBin = 1; iBin <= nBins; iBin++) hdata->SetBinError (iBin,hdata->GetBinError(iBin)/hdata->GetBinWidth(iBin)); for (int iBin = 1; iBin <= nBins; iBin++) hdata->SetBinContent(iBin,hdata->GetBinContent(iBin)/hdata->GetBinWidth(iBin)); } int theHistCounter = 0; // loop through the samples and produce the plots for (UInt_t iSample=0; iSample < listOfSamples.size(); iSample++) { //determine if the histo is first of the series bool isFirstOfSerie = (*listOfSamples.at(iSample)->Legend()).CompareTo(" "); bool isLastOfSerie = false; if (iSample == listOfSamples.size() - 1) isLastOfSerie = true; if (iSample < listOfSamples.size() - 1 && (*listOfSamples.at(iSample+1)->Legend()).CompareTo(" ") != 0) isLastOfSerie = true; //get the tree tree[iSample] = (TTree*) infile -> Get(listOfSamples.at(iSample)->Name()->Data()); //if sample first of the list create a new histogram if (isFirstOfSerie) { TString thisHistName = "h_" + *(listOfSamples.at(iSample)->Name()); //variable bin histo if (xlowVec != 0) hist[theHistCounter] = new TH1F(thisHistName,thisHistName,nBins,xlowVec); //fixed bin histo else hist[theHistCounter] = new TH1F(thisHistName,thisHistName,nBins,xLow,xHigh); hist[theHistCounter] -> Sumw2(); hist[theHistCounter] -> SetFillColor(col[theHistCounter]); hist[theHistCounter] -> SetFillStyle(1001); theLegends.push_back(*listOfSamples.at(iSample)->Legend()); cout << *listOfSamples.at(iSample)->Legend() << " "; } //fill the histogram TString thisScale = Form("%f *", *(listOfSamples.at(iSample)->Scale())); if (isFirstOfSerie) tree[iSample] -> Draw(myVar + " >> " + TString(hist[theHistCounter] -> GetName()),thisScale + "hlt_weight*evt_weight*kf_weight*pu_weight" + myCut,"goff"); else tree[iSample] -> Draw(myVar + " >>+ " + TString(hist[theHistCounter] -> GetName()),thisScale + "hlt_weight*evt_weight*kf_weight*pu_weight" + myCut,"goff"); //add the histogram to the stack if the last of the series: //either last sample or ~ sample followed by non ~ sample if (isLastOfSerie) { if (xlowVec != 0) { for (int iBin = 1; iBin <= nBins; iBin++) hist[theHistCounter]->SetBinError (iBin,hist[theHistCounter]->GetBinError(iBin)/hist[theHistCounter]->GetBinWidth(iBin)); for (int iBin = 1; iBin <= nBins; iBin++) hist[theHistCounter]->SetBinContent(iBin,hist[theHistCounter]->GetBinContent(iBin)/hist[theHistCounter]->GetBinWidth(iBin)); } hs -> Add(hist[theHistCounter]); cout << hist[theHistCounter] -> GetBinContent(1) << " +/- " << hist[theHistCounter] -> GetBinError(1) << endl; if ( listOfSamples.at(iSample)->Name()->Contains("wgptg130") ) { nSig += hist[theHistCounter] -> GetBinContent(1) ; nSigErrSq += pow(hist[theHistCounter] -> GetBinError(1),2) ; } else { nBkg += hist[theHistCounter] -> GetBinContent(1) ; nBkgErrSq += pow(hist[theHistCounter] -> GetBinError(1),2) ; } theHistCounter++; } }//end loop on samples //Fix the legend for (int iHisto = theHistCounter-1; iHisto >= 0; iHisto--) { leg -> AddEntry(hist[iHisto], theLegends[iHisto], "f"); } //get the maximum to properly set the frame float theMax = hdata -> GetBinContent(hdata -> GetMaximumBin()) + hdata -> GetBinError(hdata -> GetMaximumBin()); TH1* theMCSum = (TH1*) hs->GetStack()->Last(); cout << "total MC " << theMCSum -> GetBinContent(1) << " +/- " << theMCSum -> GetBinError(1) << endl; float theMaxMC = theMCSum->GetBinContent(theMCSum->GetMaximumBin()) + theMCSum->GetBinError(theMCSum->GetMaximumBin()); if (theMaxMC > theMax) theMax = theMaxMC; if (isBlind) cout << "total DATA " << hdata -> GetBinContent(1) << " +/- " << hdata -> GetBinError(1) << endl; //compute the scale factor float nData = hdata -> GetBinContent(1); float nDataErr = hdata -> GetBinError(1); newScaleFactor = (nData - nBkg)/(nSig/defScaleFactor); float newScaleFactorErr = sqrt( (pow(nDataErr,2) + nBkgErrSq)/(nData - nBkg)/(nData - nBkg) + nSigErrSq/nSig/nSig ) * newScaleFactor; cout << "\n The scale factor is " << newScaleFactor << " +/- " << newScaleFactorErr << endl; //cleanup the memory allocation delete theMCSum; delete hs; delete leg; delete hdata; infile -> Close(); delete infile; return; }
void FDC_Timing(bool save = 0){ TDirectory *dir = (TDirectory*)gDirectory->FindObjectAny("FDC_Efficiency"); if(!dir) return; dir->cd(); gDirectory->cd("Residuals"); TCanvas *cWireTiming = new TCanvas("cWireTiming", "WireTiming", 1000, 800); cWireTiming->Divide(6,4); double cell[24]; double cell_err[24]; double wire[24]; double wire_err[24]; double cath[24]; double cath_err[24]; double delta[24]; double delta_err[24]; double pull[24]; double pull_err[24]; for(unsigned int icell=1; icell<=24; icell++){ cWireTiming->cd(icell); cell[icell-1] = icell; cell_err[icell-1] = 0; char hname[256]; sprintf(hname, "hWireTime_cell[%d]", icell); TH1 *hWire = (TH1*)(gDirectory->Get(hname)); hWire->GetXaxis()->SetTitle("Wire Time (ns)"); //hWire->Draw(); int tzero_bin = hWire->GetMaximumBin(); double tzero = hWire->GetXaxis()->GetBinCenter(tzero_bin); TF1 *fwire = new TF1("fwire", "gaus(0)", tzero - 10, tzero + 10); fwire->SetLineColor(2); fwire->SetNpx(600); fwire->SetParameter(1,tzero); hWire->Fit("fwire","q0r"); wire[icell-1] = fwire->GetParameter(1); wire_err[icell-1] = fwire->GetParError(1); sprintf(hname, "hCathodeTime_cell[%d]", icell); TH1 *hCathode = (TH1*)(gDirectory->Get(hname)); hCathode->GetXaxis()->SetTitle("Cathode Time (ns)"); //hCathode->Draw(); tzero_bin = hCathode->GetMaximumBin(); tzero = hCathode->GetXaxis()->GetBinCenter(tzero_bin); hCathode->GetXaxis()->SetRangeUser(tzero-40,tzero+40); TF1 *fcath = new TF1("fcath", "gaus(0)", tzero - 20, tzero + 20); fcath->SetLineColor(2); fcath->SetNpx(600); fcath->SetParameter(1,tzero); hCathode->Fit("fcath","qr"); cath[icell-1] = fcath->GetParameter(1); cath_err[icell-1] = fcath->GetParError(1); sprintf(hname, "hDeltaTime_cell[%d]", icell); TH1 *hDelta = (TH1*)(gDirectory->Get(hname)); hDelta->GetXaxis()->SetTitle("Wire Time - Cathode Time (ns)"); hDelta->Draw(); tzero_bin = hDelta->GetMaximumBin(); tzero = hDelta->GetXaxis()->GetBinCenter(tzero_bin); TF1 *fdelta = new TF1("fdelta", "gaus(0)", tzero - 5, tzero + 5); fdelta->SetLineColor(2); fdelta->SetNpx(600); fdelta->SetParameter(1,tzero); hDelta->Fit("fdelta","qr"); delta[icell-1] = fdelta->GetParameter(1); delta_err[icell-1] = fdelta->GetParError(1); sprintf(hname, "hPullTime_cell[%d]", icell); TH1 *hPull = (TH1*)(gDirectory->Get(hname)); hPull->GetXaxis()->SetTitle("Pseudo Time (from pull) (ns)"); //hPull->Draw(); tzero_bin = hPull->GetMaximumBin(); tzero = hPull->GetXaxis()->GetBinCenter(tzero_bin); hPull->GetXaxis()->SetRangeUser(tzero-10,tzero+10); TF1 *fpull = new TF1("fpull", "gaus(0)", tzero - 5, tzero + 3); fpull->SetLineColor(2); fpull->SetNpx(600); fpull->SetParameter(1,tzero); hPull->Fit("fpull","q0r"); pull[icell-1] = fpull->GetParameter(1); pull_err[icell-1] = fpull->GetParError(1); } TCanvas *cTiming = new TCanvas("cTiming", "Timing", 1400, 1000); cTiming->Divide(2,2); cTiming->cd(1); TGraphErrors *gWireTiming = new TGraphErrors(24, cell, wire, cell_err, wire_err); gWireTiming->SetTitle("; Cell # ; Wire Timing (ns)"); gWireTiming->SetMarkerColor(1); gWireTiming->SetMarkerStyle(8); gWireTiming->Draw("AP"); cTiming->cd(2); TGraphErrors *gCathTiming = new TGraphErrors(24, cell, cath, cell_err, cath_err); gCathTiming->SetTitle("; Cell # ; Cathode Timing (ns)"); gCathTiming->SetMarkerColor(2); gCathTiming->SetMarkerStyle(8); gCathTiming->Draw("AP"); cTiming->cd(3); TGraphErrors *gDelta = new TGraphErrors(24, cell, delta, cell_err, delta_err); gDelta->SetTitle("; Cell # ; Wire - Cathode Timing (ns)"); gDelta->SetMarkerColor(4); gDelta->SetMarkerStyle(8); gDelta->Draw("AP"); cTiming->cd(4); TGraphErrors *gPull = new TGraphErrors(24, cell, pull, cell_err, pull_err); gPull->SetTitle("; Cell # ; Pseudo Time from Pull (ns)"); gPull->SetMarkerColor(6); gPull->SetMarkerStyle(8); gPull->Draw("AP"); }