11from ROOT
import Belle2, kIsPublic, kIsStatic, TVector3, TLorentzVector
12from ROOT.Belle2
import Const
14from basf2
import Module, B2FATAL
17def get_public_members(classname):
19 Return a list of public, non-static member functions for a given classname.
20 The
class must exist in the
Belle2 namespace and have a ROOT dictionary
"""
21 if not hasattr(Belle2, classname):
23 tclass = getattr(Belle2, classname).Class()
24 members = {e.GetName()
for e
in tclass.GetListOfMethods()
25 if (e.Property() & kIsPublic)
and not (e.Property() & kIsStatic)}
30 "CheckTObjectHashConsistency",
"Class",
"Class_Name",
"Class_Version",
31 "DeclFileLine",
"DeclFileName",
"Dictionary",
"ImplFileLine",
32 "ImplFileName",
"IsA",
"ShowMembers",
"Streamer",
"StreamerNVirtual",
33 "operator!=",
"operator=",
"operator==",
35 classname, f
"~{classname}",
38 return list(sorted(members))
41class DataStorePrinter:
43 Class to print contents of a StoreObjPtr
or StoreArray.
45 This
class is inteded to
print the contents of dataobjects to the standard
46 output to monitor changes to the contents among versions.
50 >>> printer =
DataStorePrinter(
"MCParticle", [
"getVertex"], {
"hasStatus": [1, 2, 4]})
53 will loop over all MCParticle instances
in the MCParticles StoreArray
and
54 print someting like ::
65 def __init__(self, name, simple, withArgument=None, array=True):
70 name (str): class name of the DataStore object
71 simple (list): list of member names to
print which do
not need any additional
73 withArgument (dict
or None): dictionary of member names
and a list of
74 all argument combinations to call them.
75 array (bool):
if True we
print a StoreArray, otherwise a single StoreObjPtr
91 for member, arguments
in withArgument.items():
92 for args
in arguments:
94 if not isinstance(args, list)
or isinstance(args, tuple):
104 def add_member(self, name, arguments=None, print_callback=None, display=None):
106 Add an additional member to be printed.
109 name (str): name of the member
110 arguments (list or callable): arguments to
pass to the member when calling it
111 If this
is a callable object then the function
is called
with
112 the object
as first argument
and the member name to be tested
as
113 second argument. The function
is supposed to
return the list of
114 arguments to
pass to the member when calling. Possible
return
115 valus
for the callable are:
117 * a `list` of arguments to be passed to the member. An empty
118 `list` means to call the member
with no arguments.
119 * a `tuple` of `lists <list>` to call the member once
for each
120 list of arguments
in the tuple
121 * `
None`
or an empty tuple to
not call the member at all
122 print_callback (function
or None):
if not None a function to
print
123 the result of the member call. The function will be called
with
124 the arguments (name, arguments, result)
and should
print the
125 result on stdout without any additional information.
126 display (str
or None): display string to use when printing member call
127 info instead of function name + arguments. If it
is not given
128 the default output will be ``{membername}({arguments}):``
129 followed by the result.
131 if arguments
is None:
133 self.
object_members.append((name, arguments, print_callback, display))
138 """Print all the objects currently existing"""
141 if not data.isValid():
142 print(f
"No data for {self.name}")
144 for i, obj
in enumerate(data):
148 if not obj.isValid():
149 print(f
"No data for {self.name}")
155 """Print all the public member functions we will not test"""
156 members = get_public_members(self.
name)
158 for member
in members:
161 print(f
"Untested method {self.name}::{member}")
164 """Print all defined members for each object with given index.
165 If we print a StoreObjPtr then index
is None and this function
is called
166 once. If we
print StoreArrays this function
is called once
for each
167 entry
in the array
with index set to the position
in the array
170 if index
is not None:
171 index = f
"#{int(index)}"
175 print(f
"{self.name}{index}:")
182 if callable(arguments):
183 all_args = arguments(obj, name)
190 if isinstance(all_args, list):
191 all_args = (all_args,)
195 all_args = (arguments,)
197 for args
in all_args:
198 result = getattr(obj, name)(*args)
201 if display
is not None:
202 print(
" " + display +
": ", end=
"")
205 print(f
" {name}({','.join(map(str, args))}): ", end=
"")
207 if callback
is not None:
208 print(
"", end=
"", flush=
True)
209 callback(name, args, result)
215 """ Print the result of calling a certain member.
216 As we want the test to be independent of memory we have to be a bit careful
217 how to not just
print() but check whether the object
is maybe a pointer to another
218 DataStore object
or if it
is a TObject
with implements Print().
219 Also, call recursively std::pair
222 result: object to
print
223 depth (int): depth
for recursive printing, controls the level of indent
224 weight (float
or None): weight to
print in addition to object, only used
for
229 print(
" " * (depth + 1), end=
"")
231 if weight
is not None:
232 weight = f
" (weight: {weight:.6g})"
237 if hasattr(result,
"getArrayName")
and hasattr(result,
"getArrayIndex"):
239 print(f
"-> NULL{weight}")
241 print(f
"-> {result.getArrayName()}#{int(result.getArrayIndex())}{weight}")
243 elif hasattr(result,
"GetNrows")
and hasattr(result,
"GetNcols"):
244 print(weight, end=
"")
245 for row
in range(result.GetNrows()):
246 print(
"\n" +
" " * (depth + 2), end=
"")
247 for col
in range(result.GetNcols()):
248 print(f
"{result(row, col):13.6e} ", end=
"")
252 elif isinstance(result, TVector3):
253 print(
"(" +
",".join(f
"{result[i]:.6g}" for i
in range(3)) +
")")
254 elif isinstance(result, XYZVector):
255 print(
"(" +
",".join(f
"{Belle2.B2Vector3D(result)[i]:.6g}" for i
in range(3)) +
")")
257 elif isinstance(result, TLorentzVector):
258 print(
"(" +
",".join(f
"{result[i]:.6g}" for i
in range(4)) +
")")
260 elif hasattr(result,
"first")
and hasattr(result,
"second"):
261 print(f
"pair{weight}")
265 elif (hasattr(result,
"size")
and hasattr(result,
"begin")
266 and hasattr(result,
"end"))
and not hasattr(result,
"npos") \
267 and not isinstance(result, Const.DetectorSet):
268 print(f
"size({int(result.size())}){weight}")
271 weight_getter = getattr(result,
"weight",
None)
275 for i, e
in enumerate(result):
276 if weight_getter
is not None:
277 weight = weight_getter(i)
280 elif isinstance(result, float):
281 print(f
"{result:.6g}{weight}")
283 elif isinstance(result, str)
and len(result) == 1:
284 print(ord(result), weight, sep=
"")
287 print(result, weight, sep=
"")
294 """Call all DataStorePrinter objects in for each event"""
296 def __init__(self, objects_to_print, print_untested=False):
301 objects_to_print (list): list of object to print
310 """Print all untested members if requested"""
315 printer.print_untested()
318 """print the contents of the mdst mdst_dataobjects"""
322 except Exception
as e:
323 B2FATAL(
"Error in datastore printer: ", e)
A (simplified) python wrapper for StoreArray.
a (simplified) python wrapper for StoreObjPtr.
def __init__(self, name, simple, withArgument=None, array=True)
def _printObj(self, obj, index=None)
array
if True we print a StoreArray, otherwise a single StoreObjPtr
def add_member(self, name, arguments=None, print_callback=None, display=None)
def _printResult(self, result, depth=0, weight=None)
object_members
list of object members to call and print their results
name
class name of the datastore object
objects_to_print
list of object to print
def __init__(self, objects_to_print, print_untested=False)
print_untested
print untested members?
Abstract base class for different kinds of events.