Back to home page

sPhenix code displayed by LXR

 
 

    


File indexing completed on 2025-08-05 08:11:19

0001 // get histogram from TFile. use template to get the histogram type
0002 template <typename T>
0003 T *getHist(std::string filename, std::string histname)
0004 {
0005     TFile *f = new TFile(filename.c_str(), "READ");
0006     if (!f->IsOpen())
0007     {
0008         std::cout << "Cannot open file " << filename << std::endl;
0009         return nullptr;
0010     }
0011 
0012     T *h = dynamic_cast<T *>(f->Get(histname.c_str()));
0013     if (!h)
0014     {
0015         std::cout << "Cannot find histogram " << histname << " in file " << filename << std::endl;
0016         return nullptr;
0017     }
0018     h->SetDirectory(0);
0019     f->Close();
0020     return h;
0021 }
0022 
0023 void print_with_significant_digits(double value, int sig_digits = 4)
0024 {
0025     // Determine the order of magnitude
0026     int magnitude = (value == 0.0) ? 0 : std::floor(std::log10(std::abs(value)));
0027 
0028     // Adjust precision to ensure exactly `sig_digits`
0029     int decimal_places = sig_digits - magnitude - 1;
0030 
0031     // Print using either fixed or scientific notation based on the magnitude
0032     if (magnitude >= -3 && magnitude <= 6)
0033     {
0034         // Use fixed notation for numbers in a reasonable range
0035         std::cout << std::fixed << std::setprecision(decimal_places) << value;
0036     }
0037     else
0038     {
0039         // Use scientific notation for very small or very large numbers
0040         std::cout << std::scientific << std::setprecision(sig_digits - 1) << value;
0041     }
0042 
0043     // Restore default formatting
0044     std::cout << std::defaultfloat;
0045 }
0046 
0047 void draw2Dhist(TH2 *hM, const char *xtitle, const char *ytitle, bool logz, vector<const char *> plotinfo, const char *plotopt, const char *plotname)
0048 {
0049     float ytitleoffset = 1.6;
0050 
0051     TCanvas *c = new TCanvas("c", "c", 800, 700);
0052     gPad->SetRightMargin(0.15);
0053     gPad->SetTopMargin(0.07);
0054     c->cd();
0055     if (logz)
0056         c->SetLogz();
0057     hM->GetXaxis()->SetTitle(xtitle);
0058     hM->GetYaxis()->SetTitle(ytitle);
0059     hM->GetYaxis()->SetTitleOffset(ytitleoffset);
0060     // only maximal 3 digits for the axis labels
0061     TGaxis::SetMaxDigits(3);
0062     hM->Draw(plotopt);
0063     TLatex *t = new TLatex();
0064     t->SetTextSize(0.035);
0065     for (size_t i = 0; i < plotinfo.size(); ++i)
0066     {
0067         t->DrawLatexNDC(0.25, 0.85 - i * 0.045, plotinfo[i]);
0068     }
0069     c->SaveAs(Form("%s.pdf", plotname));
0070     c->SaveAs(Form("%s.png", plotname));
0071 }