// === FUNCTION ============================================================ // Name: TPlot::GetEffHist // Description: // =========================================================================== TH1* TPlot::GetEffHist(std::string Eff, std::string det, std::string algo) { TH1* hNum = GetHist1D(listEff[Eff].first, det, algo); TH1* hDem = GetHist1D(listEff[Eff].second, det, algo); TH1* temp = (TH1*)hNum->Clone(Eff.c_str()); assert(hNum->GetNbinsX() == hDem->GetNbinsX()); for (int i = 0; i < hNum->GetNbinsX(); ++i) { double val = hNum->GetBinContent(i) / hDem->GetBinContent(i); double valerr = val * sqrt( pow(hNum->GetBinError(i)/hNum->GetBinContent(i), 2) + pow(hDem->GetBinError(i)/hDem->GetBinContent(i), 2) ); if (isnan(val)) { val = 0; valerr = 0; } temp->SetBinContent(i, val); temp->SetBinError(i, valerr); std::cout << " bin " <<i <<" val " << val << std::endl; } //temp->Divide(hDem); temp->GetYaxis()->SetTitle("Efficiency"); return temp; } // ----- end of function TPlot::GetEffHist -----
//____________________________________________________________________ void Run(const char* newName, const char* oldName, const char* newTitle="New", const char* oldTitle="Old") { TFile* newFile = TFile::Open(newName,"READ"); TFile* oldFile = TFile::Open(oldName,"READ"); if (!newFile || !oldFile) return; TH1* newCent = GetH1(newFile, "realCent"); TH1* oldCent = GetH1(oldFile, "realCent"); if (!newCent || !oldCent) return; TString t; t.Form("#it{R}=#frac{%s}{%s}", newTitle, oldTitle); TCanvas* c = new TCanvas("c", t, 1200, 800); c->SetTopMargin(0.01); c->SetRightMargin(0.20); fLegend = new TLegend(1-c->GetRightMargin(), c->GetBottomMargin(), 1, 1-c->GetTopMargin(), t); fLegend->SetFillStyle(0); fLegend->SetBorderSize(0); THStack* stack = new THStack("ratios",""); fMin = +1e6; fMax = -1e6; TH1* one = 0; for (Int_t i = newCent->GetNbinsX(); i--;) { Double_t c1 = newCent->GetXaxis()->GetBinLowEdge(i+1); Double_t c2 = newCent->GetXaxis()->GetBinUpEdge(i+1); Info("", "c1=%f c2=%f", c1, c2); TH1* r = One(newFile, oldFile, c1, c2); if (!r) continue; if (!one) { one = static_cast<TH1*>(r->Clone("one")); one->SetDirectory(0); one->Reset(); for (Int_t j = 1; j <= one->GetNbinsX(); j++) { one->SetBinContent(j,1); one->SetBinError (j,0); } } // r->Add(one, i-1); // r->Scale(TMath::Power(10,i)); stack->Add(r); } stack->Draw("nostack"); stack->SetMinimum(0.95*fMin); stack->SetMaximum(1.05*fMax); stack->GetHistogram()->SetXTitle("#eta"); stack->GetHistogram()->SetYTitle("#it{R}"); fLegend->Draw(); c->Modified(); c->Update(); c->cd(); c->SaveAs(Form("%sover%s.png", newTitle, oldTitle)); }
void cutFlow(bool eff = false) { using namespace std; double integral, preInt = 1.0; vector<pair<string,TFile*> > fnames; vector<pair<string,string> > hnames; hnames.push_back(pair<string,string>("none","hNu/cut0_none/mWR")); hnames.push_back(pair<string,string>("LLJJ Pt","hNu/cut1_LLJJpt/mWR")); hnames.push_back(pair<string,string>("trig","hNu/cut2_TrigMatches/mWR")); hnames.push_back(pair<string,string>("vertex","hNu/cut3_Vertex/mWR")); hnames.push_back(pair<string,string>("mu1 pt","hNu/cut4_Mu1HighPt/mWR")); hnames.push_back(pair<string,string>("Mll","hNu/cut5_diLmass/mWR")); hnames.push_back(pair<string,string>("MWR","hNu/cut6_mWRmass/mWR")); fnames.push_back(pair<string,TFile*>("ttbar powheg", new TFile("/local/cms/user/pastika/heavynu/heavynu_2011Bg_summer11_TTTo2L2Nu2B_7TeV-powheg-pythia6.root"))); fnames.push_back(pair<string,TFile*>("ttbar madgraph", new TFile("/local/cms/user/dahmes/wr2011/bgMC/Summer11/aug30/ttbar-PFJets.root"))); fnames.push_back(pair<string,TFile*>("Z+Jets sherpa", new TFile("/local/cms/user/pastika/heavynu/heavynu_2011Bg_summer11_DYToLL_M-50_7TeV-sherpa.root"))); fnames.push_back(pair<string,TFile*>("W+Jets sherpa", new TFile("/local/cms/user/pastika/heavynu/heavynu_2011Bg_summer11_WToLNu_7TeV-sherpa.root"))); fnames.push_back(pair<string,TFile*>("ZZ", new TFile("/local/cms/user/pastika/heavynu/heavynu_2011Bg_summer11_ZZ_TuneZ2_7TeV_pythia6_tauola.root"))); fnames.push_back(pair<string,TFile*>("WZ", new TFile("/local/cms/user/pastika/heavynu/heavynu_2011Bg_summer11_WZ_TuneZ2_7TeV_pythia6_tauola.root"))); fnames.push_back(pair<string,TFile*>("WW", new TFile("/local/cms/user/pastika/heavynu/heavynu_2011Bg_summer11_WW_TuneZ2_7TeV_pythia6_tauola.root"))); fnames.push_back(pair<string,TFile*>("tW", new TFile("/local/cms/user/pastika/heavynu/heavynu_2011Bg_summer11_T_TuneZ2_tW-channel-DR_7TeV-powheg-tauola.root"))); fnames.push_back(pair<string,TFile*>("tbarW", new TFile("/local/cms/user/pastika/heavynu/heavynu_2011Bg_summer11_Tbar_TuneZ2_tW-channel-DR_7TeV-powheg-tauola.root"))); printf("%8s", "cut"); for(vector<pair<string,TFile*> >::const_iterator i = fnames.begin(); i != fnames.end(); i++) { printf(eff?" & %15s ":" & %15s", i->first.c_str()); } printf(" \\\\ \\hline\n"); for(vector<pair<string,string> >::const_iterator j = hnames.begin(); j != hnames.end(); j++) { printf("%8s", j->first.c_str()); for(vector<pair<string,TFile*> >::const_iterator i = fnames.begin(); i != fnames.end(); i++) { TH1* h = (TH1*)i->second->Get(j->second.c_str()); integral = h->Integral(0, h->GetNbinsX()+1); printf((j == hnames.begin() && eff)?" & %15.0f ":" & %15.0f", integral); if(j != hnames.begin() && eff) { TH1* hpre = (TH1*)i->second->Get((j-1)->second.c_str()); preInt = hpre->Integral(0, h->GetNbinsX()+1); printf(" (%4.2f)", integral/preInt); } } printf(" \\\\ \\hline\n"); } }
void TH2CB::FillElements(const TH1 &h) { if( h.GetNbinsX() != GetNumberOfElements() ) { cerr << "WARNING: Number of bis don't match" << endl; } const Int_t n = min((Int_t)GetNumberOfElements(), h.GetNbinsX()); for(Int_t i=1;i<=n; ++i) { SetElement(i-1, GetElement(i-1) + h.GetBinContent(i)); } SetBinContentChanged(kTRUE); }
void TH2Crystals::SetElements(const TH1 &h) { if( h.GetNbinsX() != GetNumberOfElements() ) { cerr << "WARNING: Number of bis don't match" << endl; } TIter next(fBins); TObject *obj; TH2PolyBin *bin; Int_t hbin=1; while ( (obj = next()) && (hbin <= h.GetNbinsX()) ) { bin = (TH2PolyBin*) obj; bin->SetContent(h.GetBinContent(hbin++)); } }
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; }
void getPlotData() { TH1 * h = (TH1*) m_file->Get(m_direc.c_str()); for (int i=0; i<h->GetXaxis()->GetNbins(); i++) { m_xs.push_back(h->GetXaxis()->GetBinCenter(i)); m_ys.push_back(h->GetBinContent(i)); } m_plot->m_xAxisTitle = std::string(h->GetXaxis()->GetTitle()); m_plot->m_yAxisTitle = std::string(h->GetYaxis()->GetTitle()); m_plot->m_title = std::string(h->GetTitle()); std::stringstream ssN, ssMu, ssSig, ssUF, ssOF; ssN << std::setprecision(4) << h->GetEntries(); ssMu << std::setprecision(4) << h->GetMean(); ssSig << std::setprecision(4) << h->GetRMS(); ssUF << std::setprecision(4) << h->GetBinContent(0); ssOF << std::setprecision(4) << h->GetBinContent(h->GetNbinsX() + 1); m_statsTitles.push_back("N:"); m_statsTitles.push_back("mu:"); m_statsTitles.push_back("sig:"); m_statsTitles.push_back("UF:"); m_statsTitles.push_back("OF:"); m_statsValues.push_back(ssN.str()); m_statsValues.push_back(ssMu.str()); m_statsValues.push_back(ssSig.str()); m_statsValues.push_back(ssUF.str()); m_statsValues.push_back(ssOF.str()); }
//------------------------------------------------------------------------------ std::pair<double,double> fitskwlin( char* hs, double xl=-0.1, double xr=0.1 ) { TH1 *h = (TH1*)gDirectory->Get(hs); if( h == NULL ) { cout << hs << " does not exist\n"; return std::make_pair(0.,0.); } int nb = h->GetNbinsX(); double x1 = h->GetBinCenter(1); // first double x9 = h->GetBinCenter(nb); // last if( xl > x1 && xl < x9 ) x1 = xl; // left if( xr > x1 && xr < x9 ) x9 = xr; // right // create a TF1 with the range from x1 to x9 and 3 parameters TF1 *tanhFcn = new TF1( "tanhFcn", fitSkw, x1, x9, 2 ); tanhFcn->SetParName( 0, "dyoff" ); tanhFcn->SetParName( 1, "dyslp" ); // set start values: tanhFcn->SetParameter( 0, 0 ); // dy off [um] tanhFcn->SetParameter( 1, 99 ); // dy slope [um/skw] h->Fit( "tanhFcn", "R Q", "p" );// R = range from tanhFcn return std::make_pair(tanhFcn->GetParameter(0),tanhFcn->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(); }
TH1* subtractHistograms(const std::string& newHistogramName, const TH1* histogram_central, const TH1* histogram_shift, int mode) { const TH1* histogramMinuend = 0; const TH1* histogramSubtrahend = 0; if ( compIntegral(histogram_central) >= compIntegral(histogram_shift) ) { histogramMinuend = histogram_central; histogramSubtrahend = histogram_shift; } else { histogramMinuend = histogram_shift; histogramSubtrahend = histogram_central; } if ( !(histogramMinuend && histogramSubtrahend) ) return 0; TH1* newHistogram = (TH1*)histogramMinuend->Clone(newHistogramName.data()); newHistogram->Reset(); if ( !newHistogram->GetSumw2N() ) newHistogram->Sumw2(); int numBins = newHistogram->GetNbinsX(); for ( int iBin = 0; iBin <= (numBins + 1); ++iBin ) { double newBinContent = histogramMinuend->GetBinContent(iBin) - histogramSubtrahend->GetBinContent(iBin); double newBinError2 = square(histogramMinuend->GetBinError(iBin)) + square(histogramSubtrahend->GetBinError(iBin)); if ( mode == kRelative ) { if ( histogram_central->GetBinContent(iBin) > 0. ) { newBinContent /= histogram_central->GetBinContent(iBin); newBinError2 /= square(histogram_central->GetBinContent(iBin)); } else { newBinContent = 0.; newBinError2 = 0.; } } newHistogram->SetBinContent(iBin, newBinContent); assert(newBinError2 >= 0.); newHistogram->SetBinError(iBin, TMath::Sqrt(newBinError2)); } return newHistogram; }
TH1* GenerateConsistentHist(TH1* hbg, TH1* hprod) { TH1* hpprod = 0; if (hbg!=NULL && hprod!=NULL) { hpprod = dynamic_cast<TH1*>(hbg->Clone(hprod->GetName())); if (hpprod!=NULL) { Reset(hpprod); Double_t binctr=0, x=0, ex=0; // cout << hpprod->GetName() << endl; for(Int_t i=1; i<=hpprod->GetNbinsX(); i++) { binctr = hbg->GetBinCenter(i); x = hprod->GetBinContent(hprod->GetXaxis()->FindBin(binctr)); ex = hprod->GetBinError(hprod->GetXaxis()->FindBin(binctr)); if (x!=0 && ex/x > 1.0001) cout << "bin:" << i << "\tcontent:" << x << "\terr:" << ex << " \terr/content:" << ex/x << endl; hpprod->SetBinContent(i,x); hpprod->SetBinError(i,ex); } } } return hpprod; }
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 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); }
RooHistN::RooHistN(const TH1 &data1, const TH1 &data2, Double_t nominalBinWidth, Double_t nSigma, Double_t xErrorFrac) : TGraphAsymmErrors(), _nominalBinWidth(nominalBinWidth), _nSigma(nSigma), _rawEntries(-1) { // Create a histogram from the asymmetry between the specified TH1 objects // which may have fixed or variable bin widths, but which must both have // the same binning. The asymmetry is calculated as (1-2)/(1+2). Error bars are // calculated using Binomial statistics. Prints a warning and rounds // any bins with non-integer contents. Use the optional parameter to // specify the confidence level in units of sigma to use for // calculating error bars. The nominal bin width specifies the // default used by addAsymmetryBin(), and is used to set the relative // normalization of bins with different widths. If not set, the // nominal bin width is calculated as range/nbins. initialize(); // copy the first input histogram's name and title SetName(data1.GetName()); SetTitle(data1.GetTitle()); // calculate our nominal bin width if necessary if(_nominalBinWidth == 0) { const TAxis *axis= ((TH1&)data1).GetXaxis(); if(axis->GetNbins() > 0) _nominalBinWidth= (axis->GetXmax() - axis->GetXmin())/axis->GetNbins(); } setYAxisLabel(Form("Asymmetry (%s - %s)/(%s + %s)", data1.GetName(),data2.GetName(),data1.GetName(),data2.GetName())); // initialize our contents from the input histogram contents Int_t nbin= data1.GetNbinsX(); if(data2.GetNbinsX() != nbin) { coutE(InputArguments) << "RooHistN::RooHistN: histograms have different number of bins" << endl; return; } for(Int_t bin= 1; bin <= nbin; bin++) { Axis_t x= data1.GetBinCenter(bin); if(fabs(data2.GetBinCenter(bin)-x)>1e-10) { coutW(InputArguments) << "RooHistN::RooHistN: histograms have different centers for bin " << bin << endl; } Stat_t y1= data1.GetBinContent(bin); Stat_t y2= data2.GetBinContent(bin); addAsymmetryBin(x,roundBin(y1),roundBin(y2),data1.GetBinWidth(bin),xErrorFrac); } // we do not have a meaningful number of entries _entries= -1; }
/** * Create ratios to other data * * @param ib Bin number * @param res Result * @param alice ALICE result if any * @param cms CMS result if any * @param all Stack to add ratio to */ void Ratio2Stack(Int_t ib, TH1* res, TGraph* alice, TGraph* cms, THStack* all) { if (!all || !res || !(alice || cms)) return; Int_t off = 5*ib; TGraph* gs[] = { (alice ? alice : cms), (alice ? cms : 0), 0 }; TGraph** pg = gs; while (*pg) { TGraph* g = *pg; const char* n = (g == alice ? "ALICE" : "CMS"); TH1* r = static_cast<TH1*>(res->Clone(Form("ratio%s", n))); TString tit(r->GetTitle()); tit.ReplaceAll("Corrected", Form("Ratio to %s", n)); r->SetTitle(tit); r->SetMarkerColor(g->GetMarkerColor()); r->SetLineColor(g->GetLineColor()); TObject* tst = r->FindObject("legend"); if (tst) r->GetListOfFunctions()->Remove(tst); for (Int_t i = 1; i <= r->GetNbinsX(); i++) { Double_t c = r->GetBinContent(i); Double_t e = r->GetBinError(i); Double_t o = g->Eval(r->GetBinCenter(i)); if (o < 1e-12) { r->SetBinContent(i, 0); r->SetBinError(i, 0); continue; } r->SetBinContent(i, (c - o) / o + off); r->SetBinError(i, e / o); } all->Add(r); pg++; } TLegend* leg = StackLegend(all); if (!leg) return; TString txt = res->GetTitle(); txt.ReplaceAll("Corrected P(#it{N}_{ch}) in ", ""); if (ib == 0) txt.Append(" "); // (#times1)"); // else if (ib == 1) txt.Append(" (#times10)"); else txt.Append(Form(" (+%d)", off)); TObject* dummy = 0; TLegendEntry* e = leg->AddEntry(dummy, txt, "p"); e->SetMarkerStyle(res->GetMarkerStyle()); e->SetMarkerSize(res->GetMarkerSize()); e->SetMarkerColor(kBlack); e->SetFillColor(0); e->SetFillStyle(0); e->SetLineColor(kBlack); }
void ScaleTo10pb( TH1& hist) { int bins = hist.GetNbinsX(); double error = 0; for(int i=1; i<= bins; i++) { error = 8.0 * hist.GetBinError(i); // if( error > 1.0 ) error = 1.0; hist.SetBinError(i, error); } }
TEST_F(EvalHistMethods, CreateHistogram1D) { evaluator->SetNormalizationBuffer(norm); evaluator->SetParameterBuffer(params); TH1* hist = evaluator->CreateHistogram(); EXPECT_EQ(2, hist->GetNbinsX()); ASSERT_FLOAT_EQ(1.0, hist->Integral("width")); ASSERT_FLOAT_EQ(1.6, hist->GetBinContent(hist->FindBin(0.25))); ASSERT_FLOAT_EQ(0.4, hist->GetBinContent(hist->FindBin(0.75))); delete hist; }
void writeFile(const char* inRootFile) { TFile inRoot(inRootFile); if(!inRoot.IsOpen()){ cout << "Cannot open " << inRootFile << endl; return; } TIterator* iterator = inRoot.GetListOfKeys()->MakeIterator(); TKey* key; TString outText = inRootFile; outText.Replace(0,outText.Last('/')+1,""); ofstream os(outText.Data()); char buf[500]; int count(0); while( (key=dynamic_cast<TKey*>(iterator->Next())) != 0){ cout << key->GetName() << endl; TH1* h = (TH1*)inRoot.Get(key->GetName()); if(h->GetDimension()!=1) continue; if(++count>1) break; int nBin = h->GetNbinsX(); os << "name: " << h->GetName() << endl << "title: " << h->GetTitle() << endl << "bins: " << h->GetNbinsX() << endl << "min: " << h->GetXaxis()->GetBinLowEdge(1) << ", max: " << h->GetXaxis()->GetBinUpEdge(h->GetNbinsX()) << endl; for(int i=1; i<=nBin; i++){ os << "bin: " << i << " value: " << (float)h->GetBinContent(i) << " error: " << (float)h->GetBinError(i) << endl; } } }
//______________________________________________________________________________ int SizeOfH(TObject *to) { TClass *kl = to->IsA(); if (!kl) return 0; if (!kl->InheritsFrom(TH1::Class())) return 0; int s0 = kl->Size(); TH1 *h = (TH1 *)to; int nbins = h->GetNbinsX()*h->GetNbinsY()*h->GetNbinsZ(); int szw = 0; if (kl->InheritsFrom("TArrayC")) szw=1; else if (kl->InheritsFrom("TArrayS")) szw=2; else if (kl->InheritsFrom("TArrayI")) szw=4; else if (kl->InheritsFrom("TArrayF")) szw=4; else if (kl->InheritsFrom("TArrayD")) szw=8; return s0 + nbins*szw; }
TH1 *computeEffVsCut(TH1 *discrShape, double total) { TH1 *h = discrShape->Clone(Form("%s_effVsCut", discrShape->GetName())); h->Sumw2(); h->SetMaximum(1.5); h->SetMinimum(1e-3); unsigned int n = h->GetNbinsX(); for(unsigned int bin = 1; bin <= n; bin++) { double efficiency = h->Integral(bin, n + 1) / total; double error = sqrt(efficiency * (1 - efficiency) / total); h->SetBinContent(bin, efficiency); h->SetBinError(bin, error); } return h; }
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); }
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); }
void makefinal(TFile* fp, TFile *fm, TFile* of=0) { setTDRStyle(); TH1 *hp = (TH1*) fp->Get("MYHA"); TH1 *hm = (TH1*) fm->Get("MYHA"); TH1 *h = hp->Clone("MYNA"); for (int k=1; k<=h->GetNbinsX(); k++) { std::cout << hp->GetBinContent(k) << " " << hm->GetBinContent(k) << std::endl; h->SetBinContent(k,hp->GetBinContent(k)*.5 +hm->GetBinContent(k)*.5); std::cout << " NEW " << h->GetBinContent(k) << std::endl; //h->SetBinEntries(k,1); } if (of!=0) { of->cd(); h->Write();} }
// A function that get histogram and sets contents to 0 // if entries are too small TH1 * getHisto(TFile * file, const char * name, unsigned int rebin) { TObject * h = file->Get(name); if(h == 0) throw edm::Exception(edm::errors::Configuration) << "Can't find object " << name << "\n"; TH1 * histo = dynamic_cast<TH1*>(h); if(histo == 0) throw edm::Exception(edm::errors::Configuration) << "Object " << name << " is of type " << h->ClassName() << ", not TH1\n"; histo->Rebin(rebin); for(int i = 1; i <= histo->GetNbinsX(); ++i) { if(histo->GetBinContent(i) < 0.1) { histo->SetBinContent(i, 0.0); histo->SetBinError(i, 0.0); } } return histo; }
//====================================================================== // takes the ID of a graph to fill into a pre-booked histo // void fill1DHistoFromGraph(std::string& gid, wTH1 *&wth1) { map<string, wGraph_t *>::const_iterator it=glmap_id2graph.find(gid); if (it==glmap_id2graph.end()) { cerr<<"Couldn't find graph with id "<<gid<<", define first"<<endl; exit(-1); } if (gl_verbose) cout << "Loading histo from graph " << gid << endl; TH1 *h = wth1->histo(); for (int ibin=1; ibin <= h->GetNbinsX(); ibin++) h->SetBinContent(ibin,it->second->gr->Eval(h->GetBinCenter(ibin))); } // fill1DHistoFromGraph
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); }
RooHistN::RooHistN(const TH1 &data, Double_t nominalBinWidth, Double_t nSigma, RooAbsData::ErrorType etype, Double_t xErrorFrac) : TGraphAsymmErrors(), _nominalBinWidth(nominalBinWidth), _nSigma(nSigma), _rawEntries(-1) { // Create a histogram from the contents of the specified TH1 object // which may have fixed or variable bin widths. Error bars are // calculated using Poisson statistics. Prints a warning and rounds // any bins with non-integer contents. Use the optional parameter to // specify the confidence level in units of sigma to use for // calculating error bars. The nominal bin width specifies the // default used by addBin(), and is used to set the relative // normalization of bins with different widths. If not set, the // nominal bin width is calculated as range/nbins. initialize(); // copy the input histogram's name and title SetName(data.GetName()); SetTitle(data.GetTitle()); // calculate our nominal bin width if necessary if(_nominalBinWidth == 0) { const TAxis *axis= ((TH1&)data).GetXaxis(); if(axis->GetNbins() > 0) _nominalBinWidth= (axis->GetXmax() - axis->GetXmin())/axis->GetNbins(); } // TH1::GetYaxis() is not const (why!?) setYAxisLabel(const_cast<TH1&>(data).GetYaxis()->GetTitle()); // initialize our contents from the input histogram's contents Int_t nbin= data.GetNbinsX(); for(Int_t bin= 1; bin <= nbin; bin++) { Axis_t x= data.GetBinCenter(bin); Stat_t y= data.GetBinContent(bin); Stat_t dy = data.GetBinError(bin) ; if (etype==RooAbsData::Poisson) { addBin(x,roundBin(y),data.GetBinWidth(bin),xErrorFrac); } else { addBinWithError(x,y,dy,dy,data.GetBinWidth(bin),xErrorFrac); } } // add over/underflow bins to our event count _entries+= data.GetBinContent(0) + data.GetBinContent(nbin+1); }
TCanvas* cumulative() { TH1* h = new TH1D("h", "h", 100, -5., 5.); gRandom->SetSeed(); h->FillRandom("gaus", 1u << 16); // get the cumulative of h TH1* hc = h->GetCumulative(); // check that c has the "right" contents Double_t* integral = h->GetIntegral(); for (Int_t i = 1; i <= hc->GetNbinsX(); ++i) { assert(std::abs(integral[i] * h->GetEntries() - hc->GetBinContent(i)) < 1e-7); } // draw histogram together with its cumulative distribution TCanvas* c = new TCanvas; c->Divide(1,2); c->cd(1); h->Draw(); c->cd(2); hc->Draw(); c->Update(); return c; }
/** * Steering * * @param input Input file */ void ExtractGSE(const char* input) { if (!gROOT->GetClass("GraphSysErr")) gROOT->LoadMacro("$HOME/GraphSysErr/GraphSysErr.C+g"); TString base = gSystem->BaseName(input); base.ReplaceAll(".root",""); TFile* file = TFile::Open(input, "READ"); if (!file) return; TH1* cent = GetH1(file, "realCent"); Bool_t first = true; TList* stack = new TList; for (Int_t i = 1; i <= cent->GetNbinsX(); i++) { Double_t c1 = cent->GetXaxis()->GetBinLowEdge(i); Double_t c2 = cent->GetXaxis()->GetBinUpEdge(i); TObject* g = MakeGSE(file, c1, c2); if (!g) continue; stack->Add(g); if (first) g->Draw("quad stat combine axis"); else g->Draw("quad stat combine"); first = false; } TString obase(base); obase.Prepend("GSE_"); std::ofstream out(Form("%s.input", obase.Data())); GraphSysErr::Export(stack, out, "HFC", 2); out << "*E" << std::endl; out.close(); TFile* rout = TFile::Open(Form("%s.root", obase.Data()), "RECREATE"); stack->Write("container", TObject::kSingleKey); rout->Write(); }