FairShip
Loading...
Searching...
No Matches
rootUtils Namespace Reference

Functions

None readHists (h, fname, wanted=None)
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)
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="")
None writeHists (h, fname, bool plusCanvas=False)
None bookCanvas (h, key=None, str title="", int nx=900, int ny=600, int cx=1, int cy=1)
None assignClonesArrayItem (arr, index, obj)
None reportError (s)
None errorSummary ()
str checkFileExists (x)
bool checkForBranch (inFile, branchName)
tuple[list[str], list[str]] stage1AbsorberFieldOff (inFile)
bool is_known_particle (int|str code)
ROOT.TParticlePDG get_particle (int|str code)

Variables

Counter _error_log = Counter()

Function Documentation

◆ assignClonesArrayItem()

None rootUtils.assignClonesArrayItem ( arr,
index,
obj )
Copy obj into slot `index` of a TClonesArray, expanding it as needed.

Item assignment (arr[i] = obj) raises in ROOT >= 6.32; construct the slot
and copy-assign into it instead. TVectorD slots are resized to match obj
first (TVectorD::operator= requires matching sizes).

Definition at line 136 of file rootUtils.py.

136def assignClonesArrayItem(arr, index, obj) -> None:
137 """Copy obj into slot `index` of a TClonesArray, expanding it as needed.
138
139 Item assignment (arr[i] = obj) raises in ROOT >= 6.32; construct the slot
140 and copy-assign into it instead. TVectorD slots are resized to match obj
141 first (TVectorD::operator= requires matching sizes).
142 """
143 if arr.GetSize() <= index:
144 arr.Expand(index + 10)
145 slot = arr.ConstructedAt(index)
146 if hasattr(slot, "ResizeTo"):
147 slot.ResizeTo(obj)
148 slot.__assign__(obj)
149
150

◆ bookCanvas()

None rootUtils.bookCanvas ( h,
key = None,
str title = "",
int nx = 900,
int ny = 600,
int cx = 1,
int cy = 1 )

Definition at line 127 of file rootUtils.py.

127def bookCanvas(h, key=None, title: str = "", nx: int = 900, ny: int = 600, cx: int = 1, cy: int = 1) -> None:
128 if key is None:
129 print("missing key")
130 return
131 if key not in h:
132 h[key] = ROOT.TCanvas(key, title, nx, ny)
133 h[key].Divide(cx, cy)
134
135

◆ bookHist()

None rootUtils.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 at line 61 of file rootUtils.py.

74) -> None:
75 if key is None:
76 print("missing key")
77 return
78 rkey = str(key) # in case somebody wants to use integers, or floats as keys
79 if key in h:
80 h[key].Reset()
81 elif nbinsz > 0:
82 h[key] = ROOT.TH3D(rkey, title, nbinsx, xmin, xmax, nbinsy, ymin, ymax, nbinsz, zmin, zmax)
83 elif nbinsy > 0:
84 h[key] = ROOT.TH2D(rkey, title, nbinsx, xmin, xmax, nbinsy, ymin, ymax)
85 else:
86 h[key] = ROOT.TH1D(rkey, title, nbinsx, xmin, xmax)
87 h[key].SetDirectory(ROOT.gROOT)
88
89

◆ bookProf()

None rootUtils.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 at line 90 of file rootUtils.py.

100) -> None:
101 if key is None:
102 print("missing key")
103 return
104 rkey = str(key) # in case somebody wants to use integers, or floats as keys
105 if key in h:
106 h[key].Reset()
107 elif ymin is None or ymax is None:
108 h[key] = ROOT.TProfile(rkey, title, nbinsx, xmin, xmax, option)
109 else:
110 h[key] = ROOT.TProfile(rkey, title, nbinsx, xmin, xmax, ymin, ymax, option)
111 h[key].SetDirectory(ROOT.gROOT)
112
113

◆ checkFileExists()

str rootUtils.checkFileExists ( x)

Definition at line 162 of file rootUtils.py.

162def checkFileExists(x) -> str:
163 if isinstance(x, str):
164 tx = [x]
165 else:
166 tx = x
167 if isinstance(tx, (list, tuple)):
168 # See what we are looking at and make sure all the files are of the same type
169 fileType = ""
170 for _f in tx:
171 if _f[0:4] == "/eos":
172 f = ROOT.gSystem.Getenv("EOSSHIP") + _f
173 else:
174 f = _f
175 test = ROOT.TFile.Open(f)
176 if not test:
177 print("ERROR FileCheck: input file", f, " does not exist. Missing authentication?")
178 sys.exit(1)
179 thisType = "tree" if test.FindObjectAny("cbmsim") else "ntuple"
180 test.Close()
181 if fileType == "":
182 fileType = thisType
183 elif fileType != thisType:
184 print("ERROR FileCheck: Supplied list of files not all of tree or ntuple type")
185 sys.exit(1)
186 return fileType
187 else:
188 print("ERROR FileCheck: File must be either a string or list of files")
189 os._exit(1)
190
191

◆ checkForBranch()

bool rootUtils.checkForBranch ( inFile,
branchName )

Definition at line 192 of file rootUtils.py.

192def checkForBranch(inFile, branchName) -> bool:
193 if isinstance(inFile, str):
194 fileList = [inFile]
195 else:
196 fileList = inFile
197 if isinstance(fileList, (list, tuple)):
198 hasIt = None
199 for _f in fileList:
200 with ROOT.TFile.Open(_f) as test:
201 if not test:
202 raise FileNotFoundError(f"ERROR FileCheck: input file {_f} does not exist. Missing authentication?")
203 current_has_branch = bool(test.FindObjectAny("cbmsim") and test["cbmsim"].FindBranch(branchName))
204 if hasIt is None:
205 hasIt = current_has_branch
206 elif current_has_branch != hasIt:
207 raise ValueError(
208 f"ERROR CheckForBranch: Mixed input files (some have branch {branchName} and some do not)."
209 )
210 return bool(hasIt)
211 else:
212 print("ERROR CheckForBranch: File must be either a string or list of files")
213 os._exit(1)
214
215

◆ errorSummary()

None rootUtils.errorSummary ( )

Definition at line 155 of file rootUtils.py.

155def errorSummary() -> None:
156 if _error_log:
157 print("Summary of recorded incidents:")
158 for e in _error_log:
159 print(e, ":", _error_log[e])
160
161

◆ get_particle()

ROOT.TParticlePDG rootUtils.get_particle ( int | str code)
Return the TDatabasePDG entry for a PDG code or particle name; raise ValueError if it is unknown.

Definition at line 243 of file rootUtils.py.

243def get_particle(code: int | str) -> ROOT.TParticlePDG:
244 """Return the TDatabasePDG entry for a PDG code or particle name; raise ValueError if it is unknown."""
245 particle = ROOT.TDatabasePDG.Instance().GetParticle(code)
246 if not particle:
247 raise ValueError(f"Unknown particle: {code}")
248 return particle

◆ is_known_particle()

bool rootUtils.is_known_particle ( int | str code)
Return True if TDatabasePDG knows this PDG code or particle name.

Definition at line 237 of file rootUtils.py.

237def is_known_particle(code: int | str) -> bool:
238 """Return True if TDatabasePDG knows this PDG code or particle name."""
239 # GetParticle returns a null pointer for an unknown code: it is falsy, but it is not None.
240 return bool(ROOT.TDatabasePDG.Instance().GetParticle(code))
241
242

◆ readHists()

None rootUtils.readHists ( h,
fname,
wanted = None )

Definition at line 14 of file rootUtils.py.

14def readHists(h, fname, wanted=None) -> None:
15 if wanted is None:
16 wanted = []
17 if fname[0:4] == "/eos":
18 eospath = ROOT.gSystem.Getenv("EOSSHIP") + fname
19 f = ROOT.TFile.Open(eospath)
20 else:
21 f = ROOT.TFile(fname)
22 for akey in f.GetListOfKeys():
23 name = akey.GetName()
24 try:
25 hname = int(name)
26 except ValueError:
27 hname = name
28 if len(wanted) > 0 and hname not in wanted:
29 continue
30 obj = akey.ReadObj()
31 cln = obj.Class().GetName()
32 if "TCanv" in cln:
33 h[hname] = obj.Clone()
34 if "TH" not in cln:
35 continue
36 if hname in h:
37 rc = h[hname].Add(obj)
38 if not rc:
39 print("Error when adding histogram ", hname)
40 else:
41 h[hname] = obj.Clone()
42 if h[hname].GetSumw2N() == 0:
43 h[hname].Sumw2()
44 h[hname].SetDirectory(ROOT.gROOT)
45 if cln in {"TH2D", "TH2F"}:
46 for p in ["_projx", "_projy"]:
47 if isinstance(hname, str):
48 projname = hname + p
49 else:
50 projname = str(hname) + p
51 if "x" in p:
52 h[projname] = h[hname].ProjectionX()
53 else:
54 h[projname] = h[hname].ProjectionY()
55 h[projname].SetName(name + p)
56 h[projname].SetDirectory(ROOT.gROOT)
57 f.Close()
58 return
59
60

◆ reportError()

None rootUtils.reportError ( s)

Definition at line 151 of file rootUtils.py.

151def reportError(s) -> None:
152 _error_log[s] += 1
153
154

◆ stage1AbsorberFieldOff()

tuple[list[str], list[str]] rootUtils.stage1AbsorberFieldOff ( inFile)
Check the FileSummary that run_fixedTarget.py writes for the hadron absorber field.

Returns the files without a FileSummary, and the files simulated with a hadron
absorber but without its field.

Definition at line 216 of file rootUtils.py.

216def stage1AbsorberFieldOff(inFile) -> tuple[list[str], list[str]]:
217 """Check the FileSummary that run_fixedTarget.py writes for the hadron absorber field.
218
219 Returns the files without a FileSummary, and the files simulated with a hadron
220 absorber but without its field.
221 """
222 fileList = [inFile] if isinstance(inFile, str) else list(inFile)
223 noSummary, noField = [], []
224 for _f in fileList:
225 with ROOT.TFile.Open(_f) as f:
226 summary = f.Get("FileSummary")
227 if not summary:
228 noSummary.append(_f)
229 continue
230 fsr = json.loads(str(summary))
231 hasAbsorber = fsr.get("AddMuonShield") or fsr.get("AddHadronAbsorberOnly")
232 if hasAbsorber and not fsr.get("AddMuonShieldField"):
233 noField.append(_f)
234 return noSummary, noField
235
236

◆ writeHists()

None rootUtils.writeHists ( h,
fname,
bool plusCanvas = False )

Definition at line 114 of file rootUtils.py.

114def writeHists(h, fname, plusCanvas: bool = False) -> None:
115 f = ROOT.TFile(fname, "RECREATE")
116 for akey in h:
117 if not hasattr(h[akey], "Class"):
118 continue
119 cln = h[akey].Class().GetName()
120 if "TH" in cln or "TP" in cln:
121 h[akey].Write()
122 if plusCanvas and "TC" in cln:
123 h[akey].Write()
124 f.Close()
125
126

Variable Documentation

◆ _error_log

Counter rootUtils._error_log = Counter()
protected

Definition at line 11 of file rootUtils.py.