double Getmean(TString sys1, TString sys2, float cent1, float cent2){ gROOT->SetStyle("Plain"); TFile *infile = TFile::Open(Form("glau_%s%s_ntuple_1M.root",sys1.Data(),sys2.Data())); infile->cd(); TH2F *pEcc2B = new TH2F("pEcc2B","#epsilon_{2} vs impact paramter in 200 GeV Collisions from Glauber MC;B;#epsilon_{n}",25200,-0.5,251.5,100,0,1); if(sys2.Contains("smeared")){ TNtuple *nt = (TNtuple*)infile->Get("nt"); nt->Project("pEcc2B","Ecc3G:B"); } else{ TNtuple *nt = (TNtuple*)infile->Get(Form("nt_%s_%s",sys1.Data(),sys2.Data())); nt->Project("pEcc2B","Ecc2:B"); } TH1D* hB = (TH1D*)pEcc2B->ProjectionX("hB",0,-1); for(int ibin=0;ibin<hB->GetNbinsX();ibin++){ if(hB->Integral(0,ibin) >= cent1 /100. * hB->Integral()){ int bin1 = ibin; break;} } for(int ibin=0;ibin<hB->GetNbinsX();ibin++){ if(hB->Integral(0,ibin) >= cent2 /100. * hB->Integral()){ int bin2 = ibin; break;} } cout<< bin1 << "\t" << bin2 << endl; TH1D* hEcc2 = (TH1D*)pEcc2B->ProjectionY("hEcc2",bin1,bin2); // hEcc2->Draw(); cout << hEcc2 -> GetEntries() << endl; double mean = hEcc2->GetMean(); return mean; }
void createSysStatErrorHist(TH1D *hist_pre){ TH1D *histErr = (TH1D*) hist_pre->Clone("histErr"); hsyserr = (TH1D*) hist_pre->Clone("hsyserr"), hsyserr->Reset(); hsyserr->Sumw2(); cout<<""<<endl; for(int i=0;i<histErr->GetNbinsX();i++){ // last bin is meaningless double pt = histErr->GetBinCenter(i+1); double statferr = histErr->GetBinError(i+1)/histErr->GetBinContent(i+1); if(i==(histErr->GetNbinsX()-1)) statferr = 0.9; //double sysferr = fsyserr->Eval(pt); double sysferr = returnCombinedSysError(pt); double sumferr = sqrt(statferr*statferr + sysferr*sysferr); //double sumerr = 1.*(sumferr/100); double sumerr = 1.*sumferr; hsyserr->SetBinContent(i+1,1); hsyserr->SetBinError(i+1,sumerr); //hsyserr->SetBinError(i+1,0.5); cout<<"[setSysStatError] stat err (frac): "<<statferr<<" syst err (fac): "<<sysferr<<" combined (frac): "<<sumferr<<endl; } //tsyserr = (TGraphErrors*) TgraphIt(hsyserr); }
void loglikdistrib(Int_t ntrials = 10000, Bool_t print = kFALSE) { // compute distribution of log likelihood value TH1D * hmc = gStack[gPadNr][gOrder[gPadNr][0]]; TH1D * hdata = gStack[gPadNr][gMaxProcess-1]; Int_t nbins = hmc->GetNbinsX(); Double_t loglik = loglikelihood(hmc, hdata, 1, nbins); TH1D * htest = new TH1D(*hdata); TH1D * lldistrib = new TH1D("lldistrib", "log(Likelihood) distribution", 1000, loglik-200, loglik+200); setopt(lldistrib); for (Int_t n = 0; n < ntrials; n++) { // generate poisson around theorie for (Int_t i = 1; i <= nbins; i++) { htest->SetBinContent(i, gRandom->Poisson(hmc->GetBinContent(i))); } lldistrib->Fill(loglikelihood(hmc, htest, 1, nbins)); } TCanvas * llcanvas = new TCanvas("llcanvas", "Log(Likelihood) distribution", 40, 40, 800, 600); setopt(llcanvas); lldistrib->SetFillColor(kYellow); lldistrib->Draw(); lldistrib->GetYaxis()->SetTitle("Anzahl Ereignisse"); lldistrib->GetXaxis()->SetTitle("-ln L"); // autozoom Int_t lowbin = 1; while (lldistrib->GetBinContent(lowbin) == 0) lowbin++; Int_t highbin = lldistrib->GetNbinsX(); while (lldistrib->GetBinContent(highbin) == 0) highbin--; lldistrib->SetAxisRange(lldistrib->GetBinLowEdge(lowbin), lldistrib->GetBinLowEdge(highbin)); TH1D * hworse = (TH1D *) lldistrib->Clone(); for (Int_t nbin = 1; nbin < 501; nbin++) { hworse->SetBinContent(nbin, 0); } hworse->SetFillColor(95); hworse->Draw("same"); Double_t pvalue = lldistrib->Integral(501,1000) / lldistrib->Integral(); TLatex * tex = new TLatex(0.18, 0.96, Form("-ln L_{obs} = %5.2f", loglik)); tex->SetNDC(); tex->SetTextAlign(13); tex->Draw(); tex = new TLatex(0.18, 0.86, Form("CL_{obs} = %.3f", pvalue)); tex->SetNDC(); tex->SetTextAlign(13); tex->Draw(); TLine * l = new TLine(loglik, 0, loglik, lldistrib->GetMaximum()); l->SetLineWidth(3); l->SetLineColor(kBlue); l->Draw(); llcanvas->Modified(); llcanvas->Update(); if (print) llcanvas->Print("lldistrib.pdf"); cd(gPadNr+1); }
void takeDirectlyFromMC(TFile* fin, TFile* fout, TString gentype) { TList* listOfDirs = fin->GetListOfKeys(); for (auto k : *listOfDirs) { TString srname = k->GetName(); if (!srname.Contains("sr")) continue; if (srname.Contains("base") || srname.Contains("incl") || srname.Contains("sb")) continue; if (gentype == "_1lepW" && !srname.EndsWith("2") && !srname.EndsWith("3")) continue; auto indir = (TDirectoryFile*) fin->Get(srname); auto outdir = (TDirectory*) fout->mkdir(srname); auto hlist = indir->GetListOfKeys(); for (auto h : *hlist) { TString hname = h->GetName(); if (!hname.BeginsWith("h_metbins" + gentype)) continue; TH1D* hin = (TH1D*) indir->Get(hname); outdir->cd(); TH1D* hout = (TH1D*) hin->Clone(TString(hname).ReplaceAll(gentype, "")); for (int i = 1; i <= hout->GetNbinsX(); ++i) { // zero out negative yields if (hout->GetBinContent(i) < 0) { hout->SetBinContent(i, 0); hout->SetBinError(i, 0); } } hout->Write(); if (yearSeparateSyst && (hname.EndsWith("Up") || hname.EndsWith("Dn"))) { for (int i = 1; i < 4; ++i) { TH1D* hcen_yi = (TH1D*) fbkgs[i]->Get(srname+"/h_metbins"+gentype); TH1D* hsys_yi = (TH1D*) fbkgs[i]->Get(srname+"/"+hname); if (hsys_yi && !hcen_yi) { cout << "Find " << srname+"/"+hname << " from " << fbkgs[i]->GetName() << " but not hcen " << srname+"/h_metbins"+gentype << " Should not happen?" << endl; } TH1D* hout_yi = (TH1D*) fin->Get(srname+"/h_metbins"+gentype)->Clone(TString(hname).Insert(hname.Length()-2, Form("%d", 15+i)).ReplaceAll(gentype, "")); if (hcen_yi) hout_yi->Add(hcen_yi, -1); if (hsys_yi) hout_yi->Add(hsys_yi); hout_yi->Write(); } } } if (!outdir->Get("h_metbins")) { cout << "Didn't find yield hist for " << gentype << " in " << fin->GetName() << ":" << srname << "/. Faking a 0 one!" << endl; outdir->cd(); // Get the MET binning from h_metbins, which shall always exist, and then set all bins to 0 TH1D* hout = (TH1D*) fin->Get(srname + "/h_metbins")->Clone("h_metbins"); for (int i = 1; i <= hout->GetNbinsX(); ++i) { hout->SetBinContent(i, 0); hout->SetBinError(i, 0); } hout->Write(); } } }
TH1D GetSOverSqrtB(TH1D sig, TH1D back){ if(sig.GetNbinsX()!=back.GetNbinsX()) return sig; sig.GetYaxis()->SetTitle("S/#sqrt{B}"); for(int i(1); i<=sig.GetNbinsX(); ++i){ if(back.GetBinContent(i)>0.0 && sig.GetBinContent(i)>0.0){ sig.SetBinContent(i,sig.GetBinContent(i)/sqrt(back.GetBinContent(i))); }else{ sig.SetBinContent(i,0.0); } } return sig; }
TH1D* getQCD(int rebinFact){ TString dir = "rootFiles/"; TFile* file = new TFile(dir +"qcdest.root"); TH1D* plot = (TH1D*) file->Get("muon_AbsEta_0btag"); // for(int i = 1; i <= plot->GetNbinsX(); i++){ // plot->SetBinError(i, 0.0); // } plot->SetFillColor(kYellow); plot->SetLineColor(kYellow); plot->SetMarkerStyle(1); TH1D* copyplot = new TH1D("qcd plot", "qcd plot", 30, 0.0, 3.0); for(int i = 1; i <= plot->GetNbinsX(); i++){ copyplot->SetBinContent(i, plot->GetBinContent(i)); //copyplot->SetBinError(i, plot->GetBinError(i)); } copyplot->SetFillColor(kYellow); copyplot->SetLineColor(kYellow); copyplot->SetMarkerStyle(1); copyplot->Scale(1./copyplot->Integral()); copyplot->Rebin(rebinFact); //file->Close("R"); return copyplot; //file->Close(); }
void QinvKstar (const char* filename, const char* histname) { TFile* fileIn = new TFile(filename,"update"); TH1D* hist = (TH1D*)fileIn->Get(histname); TH1D* histnew = new TH1D(Form("kstar_%s",histname),"",hist->GetNbinsX(),0,0.25);//(TH1D*)fileIn->Get(histname); // for (int ibins = 1; ibins <= hist->GetNbinsX()*2; ibins++ ) { // hist->SetBinContent(ibins, hist->GetBinContent(ibins)); // // hist->SetBinContent(ibins, hist->GetBinContent(ibins)); // } int bin=2;//1 for (double kstar = 0.00375; kstar <= 0.25; kstar += 0.0025 ) { // for (double kstar = 0.00375; kstar <= 0.25; kstar += 0.0025 ) { // for (double kstar = 0.005; kstar <= 0.25; kstar += 0.01 ) { // hist->Fill(kstar,hist->GetBinContent(hist->FindBin(kstar*2))); histnew->SetBinContent(bin,hist->GetBinContent(hist->FindFixBin(kstar*2))); histnew->SetBinError(bin++,hist->GetBinError(hist->FindFixBin(kstar*2))); // hist->SetBinContent(ibins, hist->GetBinContent(ibins)); // hist->SetBinContent(ibins, hist->GetBinContent(ibins)); } TFile* fileOut = new TFile(Form("kstar_%s",filename), "update"); hist->Write(); histnew->Write(); }
// Merge same modes int dmMerge(TObject *a1, TObject *b1,TList *keys) { TDecayMode *a=(TDecayMode*)a1; TDecayMode *b=(TDecayMode*)b1; TIter nexthist(keys); TKey *key_hist=0; while(key_hist=(TKey*)nexthist()) { int cycle=-10; if(strcmp(key_hist->GetClassName(),"TH1D")==0) { TH1D *h=0; int cycleh=key_hist->GetCycle(); if(cycleh<cycle) { cout<<"Skipping..."<<endl; continue; } if(cycle<cycleh) cycle=cycleh; h=(TH1D*)key_hist->ReadObj(); if(!h) { cout<<"Cannot read: "<<key_hist->GetName()<<endl; exit(-2); } TH1D *eh = (TH1D*) a->histograms->FindObject(h->GetName()); if(!eh) continue; if(eh->GetNbinsX()!=h->GetNbinsX() || eh->GetXaxis()->GetXmax()!=h->GetXaxis()->GetXmax()) return -1; eh->Add(h); } } a->SetNEntries(a->GetNEntries()+b->GetNEntries()); a->SetSumw(a->GetSumw()+b->GetSumw()); a->SetSumw2(a->GetSumw2()+b->GetSumw2()); return 0; }
std::pair<float,float> getFitRange(TH1D& hist) { int maxBin = hist.GetMaximumBin(); float targetVal = hist.GetBinContent( maxBin ) /2.; int nBins = hist.GetNbinsX(); std::pair<float,float> results = {hist.GetBinLowEdge(1),hist.GetBinLowEdge(nBins+1)}; int diff=0; while( maxBin-(++diff) >0) { if( hist.GetBinContent(maxBin-diff) < targetVal ){ results.first = hist.GetBinCenter(maxBin-diff); break; } } diff=0; while( maxBin+(++diff) <=nBins) { if( hist.GetBinContent(maxBin+diff) < targetVal ){ results.second = hist.GetBinCenter(maxBin+diff); break; } } return results; }
void getStatPowerLoss() { TFile* mc = TFile::Open("MyMCPileupHistogram.root"); TH1D* hmc = (TH1D*) mc->Get("pileup"); TFile* wgt = TFile::Open("MyRatioPileupHistogram.root"); TH1D* hwgt = (TH1D*) wgt->Get("pileup"); double old_sumx = 0; double old_sumx2 = 0; double new_sumx = 0; double new_sumx2 = 0; for (int i=0; i<=hmc->GetNbinsX()+1; i++) { double val = hmc->GetBinContent(i); double factor = hwgt->GetBinContent(i); old_sumx += val; old_sumx2 += val*val; new_sumx += val*factor; new_sumx2 += val*factor*val*factor; } double old_stat = old_sumx*old_sumx/old_sumx2; double new_stat = new_sumx*new_sumx/new_sumx2; double loss = 1-new_stat/old_stat; cout << "The fractional loss in statistical power is " << std::setprecision(4) << loss*100 << "%" << endl; mc->Close(); wgt->Close(); }
Double_t fTH1toTF1(Double_t *x, Double_t *par) { Double_t g4 = x[0]; // -> g^4 value Int_t mll = (Int_t)par[0]; // -> dilepton invariant mass bin number TH2D* h2 = (TH2D*)h2Template->Clone(); TH1D* hTmp = (TH1D*)TH2toTH1(h2,mll); // TH1 histogram of g^4 in the dilepton mass bin number mll Int_t nbinsx = hTmp->GetNbinsX(); Double_t xval = -999.; if(doInterpolation) { Int_t bin = hTmp->FindBin(g4); if(bin==0 || bin==1) xval = hTmp->GetBinContent(1); // cannot interpolate on the first bin or the underflow else if(bin==nbinsx+1) xval = hTmp->GetBinContent(bin-1); // cannot interpolate on the last bin or the overflow else if(bin==nbinsx) xval = hTmp->GetBinContent(bin); // cannot interpolate on the last bin or the overflow else xval = hTmp->Interpolate(g4); // interpolated dN/dg^4 at g^4, between the 2 adjacent bin centers } else { Int_t bin = hTmp->FindBin(g4); if(bin==nbinsx+1) xval = hTmp->GetBinContent(bin-1); // overflow else if(bin==0) xval = hTmp->GetBinContent(1); // underflow else xval = hTmp->GetBinContent(bin); // normal } delete h2; delete hTmp; return xval; }
/** Personalized build a TGraphError starting from a TH1F */ TGraphErrors buildGEfromH_Personalized (const TH1D & histo) { TVectorF xV(histo.GetNbinsX()); TVectorF yV(histo.GetNbinsX()); TVectorF errxV(histo.GetNbinsX()); TVectorF erryV(histo.GetNbinsX()); for (int iBin = 0; iBin<histo.GetNbinsX(); iBin++){ xV[iBin] = histo.GetBinCenter(iBin); yV[iBin] = histo.GetBinContent(iBin); errxV[iBin] = 0; // histo.GetBinWidth(iBin); erryV[iBin] = histo.GetBinError(iBin); } TGraphErrors g (xV, yV, errxV, erryV) ; return g ; }
void makeGaussianSignals(SigData_t& m_sigdata) { //std::vector<TH1D *> vgsh(NUMCHAN); std::vector<TH1D *> vcdfh(NUMCHAN); if( m_sigdata.find("gs") == m_sigdata.end() ) { cerr << "Gaussian signal data not found, not making CDF signal!" << endl; return; } for (int ichan=0; ichan<NUMCHAN; ichan++) { TH1D *cdfh; TString channame(channames[ichan]); TString name; TH1D * gsh = m_sigdata["gs"].at(ichan); assert(gsh) ; #if 0 name = "Signalgs_"+channame; gsh = (TH1D *)tch->Clone(name.Data()); assert(gsh); gsh->SetTitle("Gaussian signal"); gsh->Reset(); TF1 *g = (TF1 *)gROOT->GetFunction("gaus"); g->SetParameters(1,gaussian_mean_mass_gev,gaussian_mass_sigma_gev); gsh->FillRandom("gaus",100000); // norm to 1pb signal with 1/fb integrated luminosity double norm = 1000 * gseffxacc[ichan]/gsh->Integral(0,gsh->GetNbinsX()+1,"width"); //gsh->Scale(norm/eff_fudgefactor); // kludge: pre-undo the fudge in the next module gsh->Scale(norm); vgsh[ichan] = gsh; #endif // New CDF bump, same as Gauss but set to CDF (obs/theor)*(LHC theor) = 3.43pb cdfh = (TH1D *)gsh->Clone("CDFbump"); cdfh->Scale(3.43); vcdfh[ichan] = cdfh; cdfh->Draw(); gsh->Draw("same"); } // channel loop //m_sigdata["gs"] = vgsh; m_sigdata["cdf"] = vcdfh; } // makeGaussianSignals
void Normalize(TH1D &h, double normalization, bool norm_per_avg_width) { int nbins = h.GetNbinsX(); double low = h.GetBinLowEdge(1); double high = h.GetBinLowEdge(nbins+1); double width = (high-low)/nbins; if(norm_per_avg_width) normalization *= width; double integral = h.Integral("width"); h.Scale(normalization/integral); }
// Draw 1D histos TH1D *plot1Dhisto(double intLumi,TFile *fileName,TString folderName,TString histoName,int color,int rebin,float xMin,float xMax,TString xName, TString yName,TString sampleName,bool mc) { TH1D *hTemp = (TH1D*)fileName->Get(folderName+"/"+histoName); hTemp->SetName(histoName+"_"+sampleName); if (mc){ hTemp->Scale(intLumi/100.); } hTemp->Rebin(rebin); hTemp->SetLineColor(color); hTemp->SetLineWidth(5); hTemp->GetXaxis()->SetRangeUser(xMin,xMax); hTemp->GetXaxis()->SetTitle(xName); hTemp->GetXaxis()->SetTitleSize(0.06); hTemp->GetXaxis()->SetLabelSize(0.06); hTemp->GetYaxis()->SetTitle(yName); hTemp->GetYaxis()->SetTitleSize(0.06); hTemp->GetYaxis()->SetLabelSize(0.06); hTemp->SetTitleOffset(1.5, "Y"); // last/first bin: put over/underflow hTemp->SetBinContent(hTemp->FindBin(xMax),hTemp->Integral(hTemp->FindBin(xMax),hTemp->GetNbinsX()+1)); hTemp->SetBinContent(hTemp->FindBin(xMin),hTemp->Integral(-1,hTemp->FindBin(xMin))); hTemp->SetBinError(hTemp->FindBin(xMax),sqrt(hTemp->Integral(hTemp->FindBin(xMax),hTemp->GetNbinsX()+1))); hTemp->SetBinError(hTemp->FindBin(xMin),sqrt(hTemp->Integral(-1,hTemp->FindBin(xMin)))); //fileName->Close(); /* if (histoName != "LP_tot") { if (histoName != "SumLepPt_tot") { if ((folderName == "ANplots150_NOLP")) { hTemp->GetXaxis()->SetRangeUser(0.,300.); } if ((folderName == "ANplots250_NOLP")) { hTemp->GetXaxis()->SetRangeUser(0.,400.); } if ((folderName == "ANplots350_NOLP")) { hTemp->GetXaxis()->SetRangeUser(0.,500.); } if ((folderName == "ANplots450_NOLP")) { hTemp->GetXaxis()->SetRangeUser(0.,1000.); } } else { if ((folderName == "ANplots150_NOLP")) { hTemp->GetXaxis()->SetRangeUser(100.,300.); } if ((folderName == "ANplots250_NOLP")) { hTemp->GetXaxis()->SetRangeUser(200.,400.); } if ((folderName == "ANplots350_NOLP")) { hTemp->GetXaxis()->SetRangeUser(300.,500.); } if ((folderName == "ANplots450_NOLP")) { hTemp->GetXaxis()->SetRangeUser(400.,1000.); } } } */ return hTemp; } // ~ end of plot1Dhisto function
TH1D* Prediction::GetScaledHisto(TH1D* histo, float scale_fact, float scale_fact_err){ // takes histo, scale factor and uncertainty on scale factor // and returns scaled and rebinned histo with 1 bin with uncertainty on scale factor propagated. TH1D *h = (TH1D*) histo->Clone(histo->GetName()); h->Rebin(h->GetNbinsX()); h->SetBinError(1, sqrt(h->GetBinError(1)* h->GetBinError(1) *scale_fact *scale_fact + h->GetBinContent(1)*h->GetBinContent(1) *scale_fact_err*scale_fact_err)); h->SetBinContent(1, h->GetBinContent(1)*scale_fact); return h; }
// Called just after the main event loop // Can be used to write things out, dump a summary etc // Return non-zero to indicate a problem int TemplateCreator::AfterLastEntry(TGlobalData* gData, const TSetupData* setup){ // Print extra info if we're debugging this module: if(Debug()){ cout<<"-----I'm debugging TemplateCreator::AfterLastEntry()"<<endl; } // Print to stdout the percentage of successful fit for each channel StringPulseIslandMap::const_iterator it; for(it = gData->fPulseIslandToChannelMap.begin(); it != gData->fPulseIslandToChannelMap.end(); ++it){ std::string bankname = it->first; std::string detname = setup->GetDetectorName(bankname); TH1D* hTemplate = fTemplates[detname]; if (!hTemplate) { // if there's no template been created for this channel continue; } int& n_fit_attempts = fNFitAttempts[detname]; // number of pulses we try to fit to int& n_successful_fits = fNSuccessfulFits[detname]; std::cout << "TemplateCreator: " << detname << ": " << n_fit_attempts << " fits attempted with " << n_successful_fits << " successful (" << ((double)n_successful_fits/(double)n_fit_attempts)*100 << "%)" << std::endl; // Normalise the template so that it has pedestal=0 and amplitude=1 // Work out the pedestal of the template from the first 5 bins int n_bins_for_template_pedestal = 5; double total = 0; for (int iBin = 1; iBin <= n_bins_for_template_pedestal; ++iBin) { total += hTemplate->GetBinContent(iBin); } double template_pedestal = total / n_bins_for_template_pedestal; // std::cout << detname << ": Template Pedestal = " << template_pedestal << std::endl; // Subtract off the pedesal for (int iBin = 1; iBin <= hTemplate->GetNbinsX(); ++iBin) { double old_value = hTemplate->GetBinContent(iBin); double new_value = old_value - template_pedestal; hTemplate->SetBinContent(iBin, new_value); } // Integrate over the histogram and scale to give an area of 1 double integral = std::fabs(hTemplate->Integral()); // want the absolute value for the integral because of the negative polarity pulses hTemplate->Scale(1.0/integral); integral = std::fabs(hTemplate->Integral()); // Save the template to the file fTemplateArchive->SaveTemplate(hTemplate); } // Clean up the template archive delete fTemplateArchive; return 0; }
void testIntegration(){ TFile* infile = new TFile("/Users/keithlandry/Desktop/testPtHist.root"); TH1D * h = infile->Get("Pt"); int bmin = 751; int bmax = bmin+1; double binval = 0; int numberOfPairs = 0; cout << "starting at bmin = " << bmin << " bmax = " << bmax << endl; cout << (double)h->GetEntries()/9.0 << endl; for (int i=0; i < h->GetNbinsX()-bmin; i++) { bmax++; cout << " i = " << i << " bmax = " << bmax << endl; int integ = h->Integral(bmin,bmax); cout << bmax << " " << integ << endl; binval += h->GetBinContent(bmax)*h->GetBinCenter(bmax); numberOfPairs += h->GetBinContent(bmax); if (integ > (double)h->GetEntries()/9.0) { cout << bmax << " " << integ << endl; lastI = i; break; } if (bmax == 1000) { break; } } cout << "avg val of bin " << (double)binval/numberOfPairs << endl; cout << " Pt = " << h->GetBinCenter(bmax) << endl; }
void FindMCToDataScaleFactor() { std::string data_filename = "~/data/out/v92/total.root"; TFile* data_file = new TFile(data_filename.c_str(), "READ"); std::string data_plotname = "TME_Al50_EvdE/all_particles/SiL_EvdE"; TH2F* hEvdE_data = (TH2F*) data_file->Get(data_plotname.c_str()); hEvdE_data->SetDirectory(0); data_file->Close(); std::string MC_filename = "plots.root"; TFile* MC_file = new TFile(MC_filename.c_str(), "READ"); std::string MC_plotname = "hAll_EvdE_SiL"; TH2F* hEvdE_MC = (TH2F*) MC_file->Get(MC_plotname.c_str()); hEvdE_MC->SetDirectory(0); MC_file->Close(); double energy_slice = 3000; int energy_slice_bin = hEvdE_data->GetXaxis()->FindBin(energy_slice); TH1D* hDataProjection = hEvdE_data->ProjectionY("_py", energy_slice_bin, energy_slice_bin); energy_slice_bin = hEvdE_MC->GetXaxis()->FindBin(energy_slice); TH1D* hMCProjection = hEvdE_MC->ProjectionY("_py", energy_slice_bin, energy_slice_bin); TFitResultPtr data_fit_result = hDataProjection->Fit("gaus", "S"); TFitResultPtr MC_fit_result = hMCProjection->Fit("gaus", "S"); hDataProjection->SetLineColor(kBlack); hDataProjection->GetXaxis()->SetRangeUser(0, energy_slice); hDataProjection->Draw(); hMCProjection->SetLineColor(kRed); hMCProjection->GetXaxis()->SetRangeUser(0, energy_slice); hMCProjection->Draw("SAME"); //EvdE_data->Draw("COLZ"); double data_mean = data_fit_result->Parameter(1); double MC_mean = MC_fit_result->Parameter(1); double scale_factor = data_mean / MC_mean; std::cout << "data / MC = " << data_mean << " / " << MC_mean << " = " << scale_factor << std::endl; // Go through the MC projection and scale each bin by the scale factor int n_bins = hMCProjection->GetNbinsX(); double min_x = hMCProjection->GetXaxis()->GetXmin(); double max_x = hMCProjection->GetXaxis()->GetXmax(); TH1F* hMCProjection_scaled = new TH1F("hMCProjection_scaled", "", n_bins,min_x,max_x); for (int i_bin = 1; i_bin <= n_bins; ++i_bin) { double old_energy = hMCProjection->GetBinLowEdge(i_bin); double new_energy = old_energy * scale_factor; double old_bin_content = hMCProjection->GetBinContent(i_bin); hMCProjection_scaled->Fill(new_energy, old_bin_content); } hMCProjection_scaled->Draw(); hDataProjection->Draw("SAME"); }
//################################################################################################################################ // Get the 68% confindence interval of mu1/mu2 void getPoissonIntervalls(double mu1, double mu2){ double result = mu1/mu2; TH1D *expHist = new TH1D("mu1/mu2","mu1/mu2",1000,0,1); TRandom3 rand1(0); TRandom3 rand2(0); cout<<"mu1 = "<<mu1<<endl; cout<<"mu2 = "<<mu2<<endl; cout<<"ratio = "<<result<<endl; for(int i=0; i<10000000; i++){ expHist->Fill(1.*rand1.Poisson(mu1)/rand2.Poisson(mu2)); } // Get now the 68% upper and lower interval double errUp = 0; double errLow = 0; for(int i=1; i<=expHist->GetNbinsX();i++){ double upperIntegral = expHist->Integral(i,expHist->GetNbinsX()); double lowerIntegral = expHist->Integral(1,i); if(abs(upperIntegral/expHist->Integral()-0.32)<0.02){ cout<<"upper bound = "<<expHist->GetBinCenter(i)<<endl; errUp = expHist->GetBinCenter(i)-result; } if(abs(lowerIntegral/expHist->Integral()-0.32)<0.02){ cout<<"lower bound = "<<expHist->GetBinCenter(i)<<endl; errLow = result - expHist->GetBinCenter(i); } } cout<<"error Up = "<<errUp<<endl; cout<<"error Low = "<<errLow<<endl; TCanvas *c = new TCanvas("cExp","cExp",0,0,500,500); c->cd(); expHist->Draw(); }
TH1D* Prediction::GetScaledHisto(TH1D* histo, float scale_fact, float scale_fact_err, int ngroup){ // takes histo, scale factor and uncertainty on scale factor // and returns scaled and rebinned histo with ngroup bins merged into 1 with uncertainty on scale factor propagated. if(ngroup>=histo->GetNbinsX()) ngroup=histo->GetNbinsX(); TH1D *h = (TH1D*) histo->Clone(histo->GetName()); h->Rebin(ngroup); for(int i=1; i<=h->GetNbinsX(); ++i){ h->SetBinError(i, sqrt(h->GetBinError(i)* h->GetBinError(i) *scale_fact *scale_fact + h->GetBinContent(i)*h->GetBinContent(i) *scale_fact_err*scale_fact_err)); h->SetBinContent(i, h->GetBinContent(i)*scale_fact); } return h; }
TH1D * GetITSTPCSpectrum(TFile *file, Int_t part, Int_t charge, Int_t cent) { TList *list = (TList *)file->Get("output"); TH1D *hin = (TH1D *)list->FindObject(Form("h_%s_%s_cen_%d", ITSTPCPartName[part], ITSTPCChargeName[charge], cent + 1)); if (!hin) return NULL; TH1D *h = new TH1D(Form("hITSTPC_cent%d_%s_%s", cent, AliPID::ParticleName(part), chargeName[charge]), "ITSTPC", NptBins, ptBin); Double_t pt, width, value, error; Int_t bin; for (Int_t ipt = 0; ipt < NptBins; ipt++) { /* get input bin */ pt = h->GetBinCenter(ipt + 1); width = h->GetBinWidth(ipt + 1); bin = hin->FindBin(pt); /* sanity check */ if (TMath::Abs(hin->GetBinCenter(bin) - pt) > 0.001 || TMath::Abs(hin->GetBinWidth(bin) - width) > 0.001) continue; /* copy bin */ value = hin->GetBinContent(bin); error = hin->GetBinError(bin); h->SetBinContent(ipt + 1, value); h->SetBinError(ipt + 1, error); } #if 0 /* add systematic error */ Double_t sys; if (part == 2) sys = 0.5; else sys = 0.1; Double_t cont, conte; for (Int_t ipt = 0; ipt < h->GetNbinsX(); ipt++) { cont = h->GetBinContent(ipt + 1); conte = h->GetBinError(ipt + 1); conte = TMath::Sqrt(conte * conte + sys * sys * cont * cont); h->SetBinError(ipt + 1, conte); } #endif h->SetTitle("ITSTPC"); h->SetLineWidth(1); h->SetLineColor(1); h->SetMarkerStyle(21); h->SetMarkerColor(2); h->SetFillStyle(0); h->SetFillColor(0); return h; }
void Yield1S_1D(){ TFile *f = new TFile("SigmaDATA_RapInt_3SBin.root"); TH1D *H; H = (TH1D*)gFile->Get("hYield1S"); double tot(0.); double totE(0.); ofstream OUT("Yield_1S_1D.tex"); OUT << "% ----------------------------------------------------------------------" << endl; OUT << "% -- Yields" << endl; for ( int x = 1; x <= H->GetNbinsX(); ++x ){ OUT << Form("\\vdef{%iS_bin%iLowEdge} {\\ensuremath{ {%.2f } } }",1, x, H->GetXaxis()->GetBinLowEdge(x) ) << endl; if ( x == H->GetNbinsX() ) OUT << Form("\\vdef{%iS_bin%iHighEdge} {\\ensuremath{ {%.2f } } }",1 , x, H->GetXaxis()->GetBinUpEdge(x) ) << endl; OUT << Form("\\vdef{%iS_bin%iContent} {\\ensuremath{ {%.0f } } }",1, x, H->GetBinContent(x) ) << endl; OUT << Form("\\vdef{%iS_bin%iError} {\\ensuremath{ {%.0f } } }",1, x, H->GetBinError(x) ) << endl; tot += H->GetBinContent(x); totE += (H->GetBinError(x)*H->GetBinError(x)); } OUT << Form("\\vdef{sum%iS} {\\ensuremath{ {%.0f } } }",1, tot) << endl; OUT << Form("\\vdef{sum%iSError} {\\ensuremath{ {%.0f } } }",1 , TMath::Sqrt(totE) ) << endl; OUT.close(); }
void fitpapvar(const char* infilename, const char* histname) { TFile* infile = new TFile(Form("%s",infilename),"read"); TH1D* hcf = (TH1D*)infile->Get(histname); hcf->GetXaxis()->SetRangeUser(0,2); TF1 *fc2 = new TF1("fc2","[3]+[2]*TMath::Gaus(x,[0],[1])",0.4,1); fc2->SetParameters(1.5,0.3,-0.2,1); // TF1 *fc2 = new TF1("fc2","[1]+[0]*x*x",0,1); // fc2->SetParameters(-0.01,1.0); // TF1 *fc2 = new TF1("fc2","[2]+[1]*x*x*x*x*x",0,1); // fc2->SetParameters(-0.01,0.01,1.0); // TF1 *fc2 = new TF1("fc2","[3]+[2]*x*x+[1]*x*x*x+[0]*x*x*x*x",0.,1); // fc2->SetParameters(-0.01,0.01,1.0,1.0); hcf->Fit("fc2","r","",0.3,1); TH1D* hnew = new TH1D("hnew","hnew",hcf->GetNbinsX(),0,1); for(int i=1;i<=hcf->GetNbinsX();++i){ // cout << i << endl; // cout << hcf->GetBinContent(i)/fc2->Eval(2.*i/hcf->GetNbinsX()) << endl; // cout << hcf->GetBinContent(i) << endl; // cout << fc2->Eval(2.*i/hcf->GetNbinsX()) << endl << endl; hnew->SetBinContent(i, hcf->GetBinContent(i)/fc2->Eval(1.*i/hcf->GetNbinsX())); hnew->SetBinError(i, hcf->GetBinError(i)); } hnew->Draw("same"); fc2->Draw("same"); hnew->SetName(Form("divp4%s",histname)); TFile* ofile = new TFile(Form("divp4%s",infilename),"update"); hnew->Write(); hcf->Write(); ofile->Close(); }
void MergeOverflow(TH1D &h, bool merge_underflow, bool merge_overflow) { if(merge_underflow) { h.SetBinContent(1, h.GetBinContent(0)+h.GetBinContent(1)); h.SetBinContent(0, 0.); h.SetBinError(1, hypot(h.GetBinError(0), h.GetBinError(1))); h.SetBinError(0, 0.); } int nbins = h.GetNbinsX(); if(merge_overflow) { h.SetBinContent(nbins, h.GetBinContent(nbins)+h.GetBinContent(nbins+1)); h.SetBinContent(nbins+1, 0.); h.SetBinError(nbins, hypot(h.GetBinError(nbins), h.GetBinError(nbins+1))); h.SetBinError(nbins+1, 0.); } }
TH1D *getpuweights(TFile *file, TH1D *target) { TDirectory *dirmcpv = (TDirectory*)file->FindObjectAny("AnaFwkMod"); TH1D *hnpu = (TH1D*)dirmcpv->Get("hNPU"); TH1D *hpumc = (TH1D*)hnpu->Clone(); hpumc->Sumw2(); hpumc->Scale(1.0/hpumc->Integral(0,hpumc->GetNbinsX()+1)); TH1D *htargettmp = new TH1D("htargettmp","", hpumc->GetNbinsX(), hpumc->GetXaxis()->GetXmin(), hpumc->GetXaxis()->GetXmax()); htargettmp->Sumw2(); for (int ibin = 0; ibin<=(htargettmp->GetNbinsX()+1); ++ibin) { htargettmp->Fill(htargettmp->GetBinCenter(ibin),target->GetBinContent(target->FindFixBin(htargettmp->GetBinCenter(ibin)))); } htargettmp->Scale(1.0/htargettmp->Integral(0,htargettmp->GetNbinsX()+1)); TH1D *puweights = new TH1D((*htargettmp)/(*hpumc)); delete htargettmp; return puweights; }
double countDataError(TChain* chain, TCut cut) { // Create temporary histogram TH1D* tmp = new TH1D("tmp", "tmp", 30, 0, 1000); double DataError = 0; tmp->Sumw2(); chain->Draw("Njet>>tmp", cut, "goff"); for(int i=0; i<=(tmp->GetNbinsX()+1); i++) DataError += tmp->GetBinError(i); delete tmp; return DataError; }
void AdjustDensityForBinWidth(TH1D &h) { double entries = h.GetEntries(); int nbins = h.GetNbinsX(); double low = h.GetBinLowEdge(1); double high = h.GetBinLowEdge(nbins+1); double width = (high-low)/nbins; for(int bin = 1; bin <= nbins; ++bin) { double content = h.GetBinContent(bin); double error = h.GetBinError(bin); double this_width = h.GetBinWidth(bin); double scale = width/this_width; h.SetBinContent(bin, content*scale); h.SetBinError(bin, error*scale); } h.SetEntries(entries); }
//=== FUNCTION DEFINITIONS ====================================================================================== TTree* toyHist(int iNToys, bool iDoMu,std::string iName,TH1D *iData,TH1D *iW,TH1D *iEWK,TH1D *iAntiData,TH1D *iAntiW,TH1D *iAntiEWK,double *iOriginalResults) { TCanvas *c = 0; TTree *tree = new TTree(("Toys"+iName).c_str(),("Toys"+iName).c_str()); float *vals = new float[16]; for(int i0 = 0; i0 < 16; i0++) vals[i0] = 0.; tree->Branch("nsig" ,&vals[0] ,"Val0/F"); tree->Branch("newk" ,&vals[1] ,"Val1/F"); tree->Branch("nqcd" ,&vals[2] ,"Val2/F"); tree->Branch("nantisig" ,&vals[3] ,"Val3/F"); tree->Branch("nantiewk" ,&vals[4] ,"Val4/F"); tree->Branch("nantiqcd" ,&vals[5] ,"Val5/F"); tree->Branch("sigma" ,&vals[6] ,"Val6/F"); tree->Branch("a1" ,&vals[7] ,"Val7/F"); tree->Branch("nsig_e" ,&vals[8] ,"Val8/F"); tree->Branch("newk_e" ,&vals[9] ,"Val9/F"); tree->Branch("nqcd_e" ,&vals[10],"Val10/F"); tree->Branch("nantisig_e",&vals[11],"Val11/F"); tree->Branch("nantiewk_e",&vals[12],"Val12/F"); tree->Branch("nantiqcd_e",&vals[13],"Val13/F"); tree->Branch("sigma_e" ,&vals[14],"Val14/F"); tree->Branch("a1_e" ,&vals[15],"Val15/F"); //Set The first entry of the tree to be the default values for(int i1 = 0; i1 < 16; i1++) vals[i1] = float(iOriginalResults[i1]); tree->Fill(); TH1D *pData = 0; TH1D *pAntiData = 0; for(int i0 = 0; i0 < iNToys; i0++) { std::stringstream pSS; pSS << "Hist" << i0; pData = (TH1D*) iData ->Clone((pSS.str()+"A").c_str()); pAntiData = (TH1D*) iAntiData->Clone((pSS.str()+"B").c_str()); for(int i1 = 0; i1 < pData ->GetNbinsX()+1; i1++) pData ->SetBinContent(i1,0); for(int i1 = 0; i1 < pAntiData->GetNbinsX()+1; i1++) pAntiData->SetBinContent(i1,0); pData ->FillRandom(iData, iData ->Integral()); pAntiData->FillRandom(iAntiData,iAntiData->Integral()); cout <<"==> " << pData->Integral() << " -- " << iData->Integral() << endl; double* pVals = fitHist(c,iDoMu,0,pSS.str(),pData,iW,iEWK,pAntiData,iAntiW,iAntiEWK,100,100,100,100); for(int i1 = 0; i1 < 16; i1++) vals[i1] = float(pVals[i1]); tree->Fill(); delete pData; delete pAntiData; } return tree; }
TH1D *HistoRatio (TH1D *hisNum, TH1D *hisDen){ //Graph Ratio Clone TH1D *Ratio; Ratio = (TH1D*)hisNum->Clone(); Ratio->Divide(hisDen); for(int ibin=1;ibin<=Ratio->GetNbinsX();ibin++) { if (Ratio->GetBinContent(ibin) == 0.0 ) { Ratio->SetBinContent(ibin, 1.0); Ratio->SetBinError(ibin, 0.0); } } Ratio->SetFillColor(0); Ratio->SetLineColor(kGray+2); // Ratio->SetLineColor(kMagenta-5); Ratio->SetLineWidth(1); Ratio->SetTitle(""); Ratio->GetYaxis()->SetTitle("Obs/Exp"); Ratio->GetYaxis()->CenterTitle(); Ratio->GetYaxis()->SetTitleFont(42); Ratio->GetYaxis()->SetTitleSize(0.135); Ratio->GetYaxis()->SetTitleOffset(0.28); Ratio->GetYaxis()->SetLabelFont(42); Ratio->GetYaxis()->SetLabelSize(0.115); Ratio->GetYaxis()->SetNdivisions(402); Ratio->GetXaxis()->SetTitle("CSVv2 bin"); Ratio->GetXaxis()->SetNdivisions(509); //(402) Ratio->GetXaxis()->SetTitleOffset(1.1); Ratio->GetXaxis()->SetTitleFont(42); Ratio->GetXaxis()->SetTitleSize(0.16); Ratio->GetXaxis()->SetTitleFont(42); Ratio->GetXaxis()->SetLabelSize(0.14); Ratio->SetMinimum(0.4); Ratio->SetMaximum(1.6); return Ratio; }