The Gaudi Framework  master (bdbe7744)
Loading...
Searching...
No Matches
Pythonizations.py
Go to the documentation of this file.
13"""This Pythonizations module provides a number of useful pythonizations
14of adaptation of some classes.
15"""
16
17__all__ = []
18
19try:
20 from cppyy import gbl
21except ImportError:
22 # FIXME: backward compatibility
23 print("# WARNING: using PyCintex as cppyy implementation")
24 from PyCintex import gbl
25
26if not hasattr(gbl, "ostream"):
27 gbl.gROOT.ProcessLine("#include <ostream>")
28if not hasattr(gbl, "stringstream"):
29 gbl.gROOT.ProcessLine("#include <sstream>")
30
31# --- Adding extra functionality to C++ raw classes------------------------------------
32
33
35 x = h.axis()
36 return (
37 f'Histogram 1D "{h.title()}" {x.bins()} bins [{x.lowerEdge()},{x.upperEdge()}]'
38 )
39
40
42 x = h.axis()
43 return map(h.binEntries, range(x.bins()))
44
45
47 x, y = h.xAxis(), h.yAxis()
48 return f'Histogram 2D "{h.title()}" {x.bins()} xbins [{x.lowerEdge()},{x.upperEdge()}], {y.bins()} ybins [{y.lowerEdge()},{y.upperEdge()}]'
49
50
52 if s.isSuccess():
53 return "SUCCESS"
54 else:
55 return "FAILURE"
56
57
59 return str(1 == b.bool())
60
61
63 if o:
64 s = gbl.stringstream()
65 o.fillStream(s)
66 out = str(s.str())
67 if out == "":
68 out = o.__class__.__name__ + " object"
69 if hasattr(o, "hasKey") and o.hasKey():
70 out += " key = " + str(o.key())
71 else:
72 out = o.__class__.__name__ + " NULL object"
73 return out
74
75
77 return self.containedObject(k)
78
79
81 return self.numberOfObjects()
82
83
85 if hasattr(self, "containedObjects"):
86 sequential = self.containedObjects()
87 else:
88 sequential = self
89 count = 0
90 limit = self.__len__()
91 while count < limit:
92 yield sequential.__getitem__(count)
93 count += 1
94
95
96def _draw_aida_(self, *args):
97 """
98 Draw AIDA histogram (through access to internal ROOT histogram
99
100 >>> aida = ... # get the historgam
101 >>> aida.Draw()
102
103 """
104 _fun = gbl.Gaudi.Utils.Aida2ROOT.aida2root
105 _root = _fun(self)
106 return _root.Draw(*args)
107
108
109gbl.AIDA.IHistogram1D.__str__ = _printHisto1D
110gbl.AIDA.IHistogram1D.contents = _contentsHisto1D
111gbl.AIDA.IHistogram2D.__str__ = _printHisto2D
112for h in (
113 gbl.AIDA.IHistogram,
114 gbl.AIDA.IHistogram1D,
115 gbl.AIDA.IHistogram2D,
116 gbl.AIDA.IHistogram3D,
117 gbl.AIDA.IProfile1D,
118 gbl.AIDA.IProfile2D,
119):
120 h.Draw = _draw_aida_
121 h.plot = _draw_aida_
122
123gbl.StatusCode.__repr__ = _printStatusCode
124try:
125 gbl._Bit_reference.__repr__ = _printBitReference
126except Exception:
127 pass
128gbl.ContainedObject.__repr__ = _printFillStream
129gbl.DataObject.__repr__ = _printFillStream
130gbl.ObjectContainerBase.__getitem__ = _container__getitem__
131gbl.ObjectContainerBase.__len__ = _container__len__
132gbl.ObjectContainerBase.__iter__ = _container__iter__
133
134# ---Globals--------------------------------------------------------------------
135if not hasattr(gbl.StatusCode, "SUCCESS"):
136 # emulate enums
137 gbl.StatusCode.SUCCESS = 1
138 gbl.StatusCode.FAILURE = 0
139
140# - string key, equality
141if hasattr(gbl.Gaudi.StringKey, "__cpp_eq__"):
142 _eq = gbl.Gaudi.StringKey.__cpp_eq__
143 setattr(gbl.Gaudi.StringKey, "__eq__", _eq)
144
145# - string key, non-equality
146if hasattr(gbl.Gaudi.StringKey, "__cpp_ne__"):
147 _ne = gbl.Gaudi.StringKey.__cpp_ne__
148 setattr(gbl.Gaudi.StringKey, "__ne__", _ne)
149
150# =============================================================================
151# decorate some map-like objects
152# =============================================================================
153# The iterator for MapBase class
154#
155# @code
156#
157# >>> m = ... ## the map
158# >>> for key in m : print(key , m[key])
159#
160# @endcode
161# @see Gaudi::Utils::MapBase
162# @see GaudiUtils::Map
163# @see GaudiUtils::HashMap
164# @see GaudiUtils::VectorMap
165# @see GaudiUtils::Map::key_at
166# @see GaudiUtils::HashMap::key_at
167# @see GaudiUtils::VectorMap::key_at
168# @author Vanya BELYAEV Ivan.Belyaev@itep.ru
169# @date 2010-02-20
170
171
173 """
174 The iterator for MapBase-based containers
175
176 >>> m = ... ## the map
177 >>> for key in m : print(key , m[key])
178
179 """
180 _size = len(self)
181 _index = 0
182 while _index < _size:
183 yield self.key_at(_index)
184 _index += 1
185
186
187# =============================================================================
188# The iterator for MapBase class
189#
190# @code
191#
192# >>> m = ... ## the map
193# >>> for key,value in m.iteritems() : print(key , value)
194#
195# @endcode
196# @see Gaudi::Utils::MapBase
197# @see GaudiUtils::Map
198# @see GaudiUtils::HashMap
199# @see GaudiUtils::VectorMap
200# @see GaudiUtils::Map::key_at
201# @see GaudiUtils::HashMap::key_at
202# @see GaudiUtils::VectorMap::key_at
203# @see GaudiUtils::Map::value_at
204# @see GaudiUtils::HashMap::value_at
205# @see GaudiUtils::VectorMap::value_at
206# @author Vanya BELYAEV Ivan.Belyaev@itep.ru
207# @date 2010-02-20
208
209
211 """
212 The iterator for MapBase-based containers
213
214 >>> m = ... ## the map
215 >>> for key,value in m.iteritems() : print(key, value)
216
217 """
218 _size = len(self)
219 _index = 0
220 while _index < _size:
221 _key = self.key_at(_index)
222 yield (_key, self.at(_key))
223 _index += 1
224
225
226# ============================================
227# Get the list of keys for the map
228#
229# @code
230#
231# >>> m = ... ## the map
232# >>> keys = m.keys() ## get the list of keys
233#
234# @endcode
235# @see Gaudi::Utils::MapBase
236# @see GaudiUtils::Map
237# @see GaudiUtils::HashMap
238# @see GaudiUtils::VectorMap
239# @see GaudiUtils::Map::key_at
240# @see GaudiUtils::HashMap::key_at
241# @ see GaudiUtils::VectorMap::key_at
242# @author Vanya BELYAEV Ivan.BElyaev@itep.ru
243# @date 2010-02-20
244
245
247 """
248 Get the list of keys
249
250 >>> m = ... ## the map
251 >>> keys = m.keys() ## get the list of keys
252
253 """
254 _size = len(self)
255 _keys = []
256 for i in range(0, _size):
257 _keys.append(self.key_at(i))
258 return _keys
259
260
261# ============================================
262# Get the list of items for the map
263#
264# @code
265#
266# >>> m = ... ## the map
267# >>> items = m.items() ## get the list of items
268#
269# @endcode
270# @see Gaudi::Utils::MapBase
271# @see GaudiUtils::Map
272# @see GaudiUtils::HashMap
273# @see GaudiUtils::VectorMap
274# @see GaudiUtils::Map::key_at
275# @see GaudiUtils::HashMap::key_at
276# @ see GaudiUtils::VectorMap::key_at
277# @author Vanya BELYAEV Ivan.BElyaev@itep.ru
278# @date 2010-02-20
279
280
282 """
283 Get the list of items
284
285 >>> m = ... ## the map
286 >>> items = m.keys() ## get the list of items
287
288 """
289 _size = len(self)
290 _items = []
291 for i in range(0, _size):
292 _key = self.key_at(i)
293 _value = self.at(_key)
294 _items.append((_key, _value))
295 return _items
296
297
298# ============================================
299# Get the list of values for the map
300#
301# @code
302#
303# >>> m = ... ## the map
304# >>> values = m.values () ## get the list of values
305#
306# @endcode
307# @see Gaudi::Utils::MapBase
308# @see GaudiUtils::Map
309# @see GaudiUtils::HashMap
310# @see GaudiUtils::VectorMap
311# @see GaudiUtils::Map::value_at
312# @see GaudiUtils::HashMap::value_at
313# @ see GaudiUtils::VectorMap::value_at
314# @author Vanya BELYAEV Ivan.Belyaev@itep.ru
315# @date 2010-02-20
316
317
319 """
320 Get the list of values
321
322 >>> m = ... ## the map
323 >>> values = m.values() ## get the list of values
324
325 """
326 _size = len(self)
327 _values = []
328 for i in range(0, _size):
329 _value = self.value_at(i)
330 _values.append(_value)
331 return _values
332
333
334# ============================================
335# Check if the certain key is in the map
336#
337# @code
338#
339# >>> m = ... ## the map
340# >>> if 'a' in m : print('key is in the map!')
341#
342# @endcode
343# @see Gaudi::Utils::MapBase
344# @see GaudiUtils::Map
345# @see GaudiUtils::HashMap
346# @see GaudiUtils::VectorMap
347# @see GaudiUtils::Map::count
348# @see GaudiUtils::HashMap::count
349# @ see GaudiUtils::VectorMap::count
350# @author Vanya BELYAEV Ivan.BElyaev@itep.ru
351# @date 2010-02-20
352
353
354def __mapbase_contains__(self, key):
355 """
356 Check if the certainkey is in the map
357
358 >>> m = ... ## the map
359 >>> if 'a' in m : ... ## chekc the presence of the key in the map
360
361 """
362 _num = self.count(key)
363 return False if 0 == _num else True
364
365
366# ============================================
367# Get the value for certain key,
368# return predefined value otherwise
369#
370# @code
371#
372# >>> m = ... ## the map
373# >>> v = m.get( key , 15 ) ## return the value[key] for existing key, else 15
374#
375# @endcode
376# @see Gaudi::Utils::MapBase
377# @see GaudiUtils::Map
378# @see GaudiUtils::HashMap
379# @see GaudiUtils::VectorMap
380# @see GaudiUtils::Map::count
381# @see GaudiUtils::HashMap::count
382# @ see GaudiUtils::VectorMap::count
383# @author Vanya BELYAEV Ivan.BElyaev@itep.ru
384# @date 2010-02-20
385
386
387def __mapbase_get__(self, key, value=None):
388 """
389 Get the value for the certain key, or 'value' otherwise
390
391 >>> m = ... ## the map
392 >>> v = m.get ( key , 15 )
393
394 """
395 if key in self:
396 return self.at(key)
397 return value
398
399
400# ============================================
401# Representation of MapBase-based maps
402#
403# @code
404#
405# >>> m = ... ## the map
406# >>> print(m)
407#
408# @endcode
409# @see Gaudi::Utils::MapBase
410# @see GaudiUtils::Map
411# @see GaudiUtils::HashMap
412# @see GaudiUtils::VectorMap
413# @author Vanya BELYAEV Ivan.BElyaev@itep.ru
414# @date 2010-02-20
415
416
418 """
419 Representation of MapBase-based maps:
420
421 >>> m = ... ## the map
422 >>> print(map)
423
424 """
425 _result = " { "
426 _size = len(self)
427 for i in range(0, _size):
428 _key = self.key_at(i)
429 _val = self.at(_key)
430 if 0 != i:
431 _result += " , "
432 _result += f" {_key} : {_val} "
433 _result += " } "
434 return _result
435
436
437# ============================================
438# "Setitem" for MapBase-based maps:
439#
440# @code
441#
442# >>> m = ... ## the map
443# >>> m [ key] = value ## set the item
444#
445# @endcode
446# @see Gaudi::Utils::MapBase
447# @see GaudiUtils::Map
448# @see GaudiUtils::HashMap
449# @see GaudiUtils::VectorMap
450# @see GaudiUtils::Map::update
451# @see GaudiUtils::HashMap::update
452# @see GaudiUtils::VectorMap::update
453# @author Vanya BELYAEV Ivan.BElyaev@itep.ru
454# @date 2010-02-20
455
456
457def __mapbase_setitem__(self, key, value):
458 """
459 'Set-item' for MapBase-based maps:
460
461 >>> m = ... ## the map
462 >>> m[key] = value ## set the item
463
464 """
465 _replaced = True if key in self else False
466 self.update(key, value)
467 return _replaced
468
469
470# ============================================
471# "Del-item" for MapBase-based maps:
472#
473# @code
474#
475# >>> m = ... ## the map
476# >>> del m [ key] ## del th eitem
477#
478# @endcode
479#
480# @see Gaudi::Utils::MapBase
481# @see GaudiUtils::Map
482# @see GaudiUtils::HashMap
483# @see GaudiUtils::VectorMap
484# @see GaudiUtils::Map::erase
485# @see GaudiUtils::HashMap::erase
486# @see GaudiUtils::VectorMap::erase
487# @author Vanya BELYAEV Ivan.BElyaev@itep.ru
488# @date 2010-02-20
489
490
491def __mapbase_delitem__(self, key):
492 """
493 'Del-item' for MapBase-based maps:
494
495 >>> m = ... ## the map
496 >>> del m[key]
497
498 """
499 _erased = True if key in self else False
500 self.erase(key)
501 return _erased
502
503
504gbl.Gaudi.Utils.MapBase.__len__ = lambda s: s.size()
505gbl.Gaudi.Utils.MapBase.__iter__ = __mapbase_iter__
506gbl.Gaudi.Utils.MapBase.keys = __mapbase_keys__
507gbl.Gaudi.Utils.MapBase.__iteritems__ = __mapbase_iteritems__
508gbl.Gaudi.Utils.MapBase.values = __mapbase_values__
509gbl.Gaudi.Utils.MapBase.__contains__ = __mapbase_contains__
510gbl.Gaudi.Utils.MapBase.get = __mapbase_get__
511gbl.Gaudi.Utils.MapBase.__str__ = __mapbase_str__
512gbl.Gaudi.Utils.MapBase.__repr__ = __mapbase_str__
513gbl.Gaudi.Utils.MapBase.__setitem__ = __mapbase_setitem__
514gbl.Gaudi.Utils.MapBase.__delitem__ = __mapbase_delitem__
515gbl.Gaudi.Utils.MapBase.__getitem__ = lambda s, key: s.at(key)
516gbl.Gaudi.Utils.MapBase.items = __mapbase_iteritems__
517
518
524gbl.gInterpreter.Declare(
525 """
526#ifndef REENTINTERFACES_PYTHON_HELPERS
527#define REENTINTERFACES_PYTHON_HELPERS
528#include <GaudiKernel/IAlgorithm.h>
529#include <GaudiKernel/IEventProcessor.h>
530#include <GaudiKernel/ThreadLocalContext.h>
531
532namespace GaudiPython::Helpers {
533 StatusCode executeEvent( IEventProcessor* self ) {
534 return self->executeEvent( self->createEventContext() );
535 }
536 bool isExecuted( IAlgorithm* self ) {
537 return self->execState( Gaudi::Hive::currentContext() ).state() == AlgExecState::Done;
538 }
539 bool filterPassed( IAlgorithm* self ) {
540 return self->execState( Gaudi::Hive::currentContext() ).filterPassed();
541 }
542 StatusCode ialg_execute( IAlgorithm* self ) {
543 return self->execute( Gaudi::Hive::currentContext() );
544 }
545}
546
547#endif
548"""
549)
550gbl.IEventProcessor.executeEvent = gbl.GaudiPython.Helpers.executeEvent
551gbl.IAlgorithm.isExecuted = gbl.GaudiPython.Helpers.isExecuted
552gbl.IAlgorithm.filterPassed = gbl.GaudiPython.Helpers.filterPassed
553gbl.IAlgorithm._execute_orig = gbl.IAlgorithm.execute
554gbl.IAlgorithm.execute = lambda self, ctx=None: (
555 gbl.GaudiPython.Helpers.ialg_execute(self)
556 if ctx is None
557 else self._execute_orig(ctx)
558)
__mapbase_get__(self, key, value=None)
__mapbase_setitem__(self, key, value)