FairShip
Loading...
Searching...
No Matches
rootUtils.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2# SPDX-FileCopyrightText: Copyright CERN for the benefit of the SHiP Collaboration
3
4import os
5import sys
6from collections import Counter
7
8import ROOT
9
10_error_log: Counter[str] = Counter()
11
12
13def readHists(h, fname, wanted=None) -> None:
14 if wanted is None:
15 wanted = []
16 if fname[0:4] == "/eos":
17 eospath = ROOT.gSystem.Getenv("EOSSHIP") + fname
18 f = ROOT.TFile.Open(eospath)
19 else:
20 f = ROOT.TFile(fname)
21 for akey in f.GetListOfKeys():
22 name = akey.GetName()
23 try:
24 hname = int(name)
25 except ValueError:
26 hname = name
27 if len(wanted) > 0 and hname not in wanted:
28 continue
29 obj = akey.ReadObj()
30 cln = obj.Class().GetName()
31 if "TCanv" in cln:
32 h[hname] = obj.Clone()
33 if "TH" not in cln:
34 continue
35 if hname in h:
36 rc = h[hname].Add(obj)
37 if not rc:
38 print("Error when adding histogram ", hname)
39 else:
40 h[hname] = obj.Clone()
41 if h[hname].GetSumw2N() == 0:
42 h[hname].Sumw2()
43 h[hname].SetDirectory(ROOT.gROOT)
44 if cln in {"TH2D", "TH2F"}:
45 for p in ["_projx", "_projy"]:
46 if isinstance(hname, str):
47 projname = hname + p
48 else:
49 projname = str(hname) + p
50 if "x" in p:
51 h[projname] = h[hname].ProjectionX()
52 else:
53 h[projname] = h[hname].ProjectionY()
54 h[projname].SetName(name + p)
55 h[projname].SetDirectory(ROOT.gROOT)
56 return
57
58
60 h,
61 key=None,
62 title: str = "",
63 nbinsx: int = 100,
64 xmin: float = 0,
65 xmax: float = 1,
66 nbinsy: int = 0,
67 ymin: float = 0,
68 ymax: float = 1,
69 nbinsz: int = 0,
70 zmin: float = 0,
71 zmax: float = 1,
72) -> None:
73 if key is None:
74 print("missing key")
75 return
76 rkey = str(key) # in case somebody wants to use integers, or floats as keys
77 if key in h:
78 h[key].Reset()
79 elif nbinsz > 0:
80 h[key] = ROOT.TH3D(rkey, title, nbinsx, xmin, xmax, nbinsy, ymin, ymax, nbinsz, zmin, zmax)
81 elif nbinsy > 0:
82 h[key] = ROOT.TH2D(rkey, title, nbinsx, xmin, xmax, nbinsy, ymin, ymax)
83 else:
84 h[key] = ROOT.TH1D(rkey, title, nbinsx, xmin, xmax)
85 h[key].SetDirectory(ROOT.gROOT)
86
87
89 h,
90 key=None,
91 title: str = "",
92 nbinsx: int = 100,
93 xmin: float = 0,
94 xmax: float = 1,
95 ymin: float | None = None,
96 ymax: float | None = None,
97 option: str = "",
98) -> None:
99 if key is None:
100 print("missing key")
101 return
102 rkey = str(key) # in case somebody wants to use integers, or floats as keys
103 if key in h:
104 h[key].Reset()
105 if ymin is None or ymax is None:
106 h[key] = ROOT.TProfile(rkey, title, nbinsx, xmin, xmax, option)
107 else:
108 h[key] = ROOT.TProfile(rkey, title, nbinsx, xmin, xmax, ymin, ymax, option)
109 h[key].SetDirectory(ROOT.gROOT)
110
111
112def writeHists(h, fname, plusCanvas: bool = False) -> None:
113 f = ROOT.TFile(fname, "RECREATE")
114 for akey in h:
115 if not hasattr(h[akey], "Class"):
116 continue
117 cln = h[akey].Class().GetName()
118 if "TH" in cln or "TP" in cln:
119 h[akey].Write()
120 if plusCanvas and "TC" in cln:
121 h[akey].Write()
122 f.Close()
123
124
125def bookCanvas(h, key=None, title: str = "", nx: int = 900, ny: int = 600, cx: int = 1, cy: int = 1) -> None:
126 if key is None:
127 print("missing key")
128 return
129 if key not in h:
130 h[key] = ROOT.TCanvas(key, title, nx, ny)
131 h[key].Divide(cx, cy)
132
133
134def reportError(s) -> None:
135 _error_log[s] += 1
136
137
138def errorSummary() -> None:
139 if _error_log:
140 print("Summary of recorded incidents:")
141 for e in _error_log:
142 print(e, ":", _error_log[e])
143
144
145def checkFileExists(x) -> str:
146 if isinstance(x, str):
147 tx = [x]
148 else:
149 tx = x
150 if isinstance(tx, (list, tuple)):
151 # See what we are looking at and make sure all the files are of the same type
152 fileType = ""
153 for _f in tx:
154 if _f[0:4] == "/eos":
155 f = ROOT.gSystem.Getenv("EOSSHIP") + _f
156 else:
157 f = _f
158 test = ROOT.TFile.Open(f)
159 if not test:
160 print("ERROR FileCheck: input file", f, " does not exist. Missing authentication?")
161 sys.exit(1)
162 if test.FindObjectAny("cbmsim") and fileType in ["tree", ""]:
163 fileType = "tree"
164 elif fileType in ["ntuple", ""]:
165 fileType = "ntuple"
166 else:
167 print("ERROR FileCheck: Supplied list of files not all of tree or ntuple type")
168 return fileType
169 else:
170 print("ERROR FileCheck: File must be either a string or list of files")
171 os._exit(1)
None writeHists(h, fname, bool plusCanvas=False)
Definition: rootUtils.py:112
str checkFileExists(x)
Definition: rootUtils.py:145
None readHists(h, fname, wanted=None)
Definition: rootUtils.py:13
None bookHist(h, key=None, str title="", int nbinsx=100, float xmin=0, float xmax=1, int nbinsy=0, float ymin=0, float ymax=1, int nbinsz=0, float zmin=0, float zmax=1)
Definition: rootUtils.py:72
None errorSummary()
Definition: rootUtils.py:138
None reportError(s)
Definition: rootUtils.py:134
None bookProf(h, key=None, str title="", int nbinsx=100, float xmin=0, float xmax=1, float|None ymin=None, float|None ymax=None, str option="")
Definition: rootUtils.py:98
None bookCanvas(h, key=None, str title="", int nx=900, int ny=600, int cx=1, int cy=1)
Definition: rootUtils.py:125