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