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 json
5import os
6import sys
7from collections import Counter
8
9import ROOT
10
11_error_log: Counter[str] = Counter()
12
13
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
62 h,
63 key=None,
64 title: str = "",
65 nbinsx: int = 100,
66 xmin: float = 0,
67 xmax: float = 1,
68 nbinsy: int = 0,
69 ymin: float = 0,
70 ymax: float = 1,
71 nbinsz: int = 0,
72 zmin: float = 0,
73 zmax: float = 1,
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
91 h,
92 key=None,
93 title: str = "",
94 nbinsx: int = 100,
95 xmin: float = 0,
96 xmax: float = 1,
97 ymin: float | None = None,
98 ymax: float | None = None,
99 option: str = "",
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
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
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
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
151def reportError(s) -> None:
152 _error_log[s] += 1
153
154
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
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
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
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
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
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
bool is_known_particle(int|str code)
Definition rootUtils.py:237
None writeHists(h, fname, bool plusCanvas=False)
Definition rootUtils.py:114
tuple[list[str], list[str]] stage1AbsorberFieldOff(inFile)
Definition rootUtils.py:216
str checkFileExists(x)
Definition rootUtils.py:162
None readHists(h, fname, wanted=None)
Definition rootUtils.py:14
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:74
ROOT.TParticlePDG get_particle(int|str code)
Definition rootUtils.py:243
bool checkForBranch(inFile, branchName)
Definition rootUtils.py:192
None errorSummary()
Definition rootUtils.py:155
None reportError(s)
Definition rootUtils.py:151
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:100
None assignClonesArrayItem(arr, index, obj)
Definition rootUtils.py:136
None bookCanvas(h, key=None, str title="", int nx=900, int ny=600, int cx=1, int cy=1)
Definition rootUtils.py:127