The Gaudi Framework  master (bb95dfce)
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
145# ---Globals--------------------------------------------------------------------
146if not hasattr(gbl.StatusCode, "SUCCESS"):
147 # emulate enums
148 gbl.StatusCode.SUCCESS = 1
149 gbl.StatusCode.FAILURE = 0
150
151# - string key, equality
152if hasattr(gbl.Gaudi.StringKey, "__cpp_eq__"):
153 _eq = gbl.Gaudi.StringKey.__cpp_eq__
154 setattr(gbl.Gaudi.StringKey, "__eq__", _eq)
155
156# - string key, non-equality
157if hasattr(gbl.Gaudi.StringKey, "__cpp_ne__"):
158 _ne = gbl.Gaudi.StringKey.__cpp_ne__
159 setattr(gbl.Gaudi.StringKey, "__ne__", _ne)
160
161# =============================================================================
162# decorate some map-like objects
163# =============================================================================
164# The iterator for MapBase class
165#
166# @code
167#
168# >>> m = ... ## the map
169# >>> for key in m : print(key , m[key])
170#
171# @endcode
172# @see Gaudi::Utils::MapBase
173# @see GaudiUtils::Map
174# @see GaudiUtils::HashMap
175# @see GaudiUtils::VectorMap
176# @see GaudiUtils::Map::key_at
177# @see GaudiUtils::HashMap::key_at
178# @see GaudiUtils::VectorMap::key_at
179# @author Vanya BELYAEV Ivan.Belyaev@itep.ru
180# @date 2010-02-20
181
182
184 """
185 The iterator for MapBase-based containers
186
187 >>> m = ... ## the map
188 >>> for key in m : print(key , m[key])
189
190 """
191 _size = len(self)
192 _index = 0
193 while _index < _size:
194 yield self.key_at(_index)
195 _index += 1
196
197
198# =============================================================================
199# The iterator for MapBase class
200#
201# @code
202#
203# >>> m = ... ## the map
204# >>> for key,value in m.iteritems() : print(key , value)
205#
206# @endcode
207# @see Gaudi::Utils::MapBase
208# @see GaudiUtils::Map
209# @see GaudiUtils::HashMap
210# @see GaudiUtils::VectorMap
211# @see GaudiUtils::Map::key_at
212# @see GaudiUtils::HashMap::key_at
213# @see GaudiUtils::VectorMap::key_at
214# @see GaudiUtils::Map::value_at
215# @see GaudiUtils::HashMap::value_at
216# @see GaudiUtils::VectorMap::value_at
217# @author Vanya BELYAEV Ivan.Belyaev@itep.ru
218# @date 2010-02-20
219
220
222 """
223 The iterator for MapBase-based containers
224
225 >>> m = ... ## the map
226 >>> for key,value in m.iteritems() : print(key, value)
227
228 """
229 _size = len(self)
230 _index = 0
231 while _index < _size:
232 _key = self.key_at(_index)
233 yield (_key, self.at(_key))
234 _index += 1
235
236
237# ============================================
238# Get the list of keys for the map
239#
240# @code
241#
242# >>> m = ... ## the map
243# >>> keys = m.keys() ## get the list of keys
244#
245# @endcode
246# @see Gaudi::Utils::MapBase
247# @see GaudiUtils::Map
248# @see GaudiUtils::HashMap
249# @see GaudiUtils::VectorMap
250# @see GaudiUtils::Map::key_at
251# @see GaudiUtils::HashMap::key_at
252# @ see GaudiUtils::VectorMap::key_at
253# @author Vanya BELYAEV Ivan.BElyaev@itep.ru
254# @date 2010-02-20
255
256
258 """
259 Get the list of keys
260
261 >>> m = ... ## the map
262 >>> keys = m.keys() ## get the list of keys
263
264 """
265 _size = len(self)
266 _keys = []
267 for i in range(0, _size):
268 _keys.append(self.key_at(i))
269 return _keys
270
271
272# ============================================
273# Get the list of items for the map
274#
275# @code
276#
277# >>> m = ... ## the map
278# >>> items = m.items() ## get the list of items
279#
280# @endcode
281# @see Gaudi::Utils::MapBase
282# @see GaudiUtils::Map
283# @see GaudiUtils::HashMap
284# @see GaudiUtils::VectorMap
285# @see GaudiUtils::Map::key_at
286# @see GaudiUtils::HashMap::key_at
287# @ see GaudiUtils::VectorMap::key_at
288# @author Vanya BELYAEV Ivan.BElyaev@itep.ru
289# @date 2010-02-20
290
291
293 """
294 Get the list of items
295
296 >>> m = ... ## the map
297 >>> items = m.keys() ## get the list of items
298
299 """
300 _size = len(self)
301 _items = []
302 for i in range(0, _size):
303 _key = self.key_at(i)
304 _value = self.at(_key)
305 _items.append((_key, _value))
306 return _items
307
308
309# ============================================
310# Get the list of values for the map
311#
312# @code
313#
314# >>> m = ... ## the map
315# >>> values = m.values () ## get the list of values
316#
317# @endcode
318# @see Gaudi::Utils::MapBase
319# @see GaudiUtils::Map
320# @see GaudiUtils::HashMap
321# @see GaudiUtils::VectorMap
322# @see GaudiUtils::Map::value_at
323# @see GaudiUtils::HashMap::value_at
324# @ see GaudiUtils::VectorMap::value_at
325# @author Vanya BELYAEV Ivan.Belyaev@itep.ru
326# @date 2010-02-20
327
328
330 """
331 Get the list of values
332
333 >>> m = ... ## the map
334 >>> values = m.values() ## get the list of values
335
336 """
337 _size = len(self)
338 _values = []
339 for i in range(0, _size):
340 _value = self.value_at(i)
341 _values.append(_value)
342 return _values
343
344
345# ============================================
346# Check if the certain key is in the map
347#
348# @code
349#
350# >>> m = ... ## the map
351# >>> if 'a' in m : print('key is in the map!')
352#
353# @endcode
354# @see Gaudi::Utils::MapBase
355# @see GaudiUtils::Map
356# @see GaudiUtils::HashMap
357# @see GaudiUtils::VectorMap
358# @see GaudiUtils::Map::count
359# @see GaudiUtils::HashMap::count
360# @ see GaudiUtils::VectorMap::count
361# @author Vanya BELYAEV Ivan.BElyaev@itep.ru
362# @date 2010-02-20
363
364
365def __mapbase_contains__(self, key):
366 """
367 Check if the certainkey is in the map
368
369 >>> m = ... ## the map
370 >>> if 'a' in m : ... ## chekc the presence of the key in the map
371
372 """
373 _num = self.count(key)
374 return False if 0 == _num else True
375
376
377# ============================================
378# Get the value for certain key,
379# return predefined value otherwise
380#
381# @code
382#
383# >>> m = ... ## the map
384# >>> v = m.get( key , 15 ) ## return the value[key] for existing key, else 15
385#
386# @endcode
387# @see Gaudi::Utils::MapBase
388# @see GaudiUtils::Map
389# @see GaudiUtils::HashMap
390# @see GaudiUtils::VectorMap
391# @see GaudiUtils::Map::count
392# @see GaudiUtils::HashMap::count
393# @ see GaudiUtils::VectorMap::count
394# @author Vanya BELYAEV Ivan.BElyaev@itep.ru
395# @date 2010-02-20
396
397
398def __mapbase_get__(self, key, value=None):
399 """
400 Get the value for the certain key, or 'value' otherwise
401
402 >>> m = ... ## the map
403 >>> v = m.get ( key , 15 )
404
405 """
406 if key in self:
407 return self.at(key)
408 return value
409
410
411# ============================================
412# Representation of MapBase-based maps
413#
414# @code
415#
416# >>> m = ... ## the map
417# >>> print(m)
418#
419# @endcode
420# @see Gaudi::Utils::MapBase
421# @see GaudiUtils::Map
422# @see GaudiUtils::HashMap
423# @see GaudiUtils::VectorMap
424# @author Vanya BELYAEV Ivan.BElyaev@itep.ru
425# @date 2010-02-20
426
427
429 """
430 Representation of MapBase-based maps:
431
432 >>> m = ... ## the map
433 >>> print(map)
434
435 """
436 _result = " { "
437 _size = len(self)
438 for i in range(0, _size):
439 _key = self.key_at(i)
440 _val = self.at(_key)
441 if 0 != i:
442 _result += " , "
443 _result += " %s : %s " % (str(_key), str(_val))
444 _result += " } "
445 return _result
446
447
448# ============================================
449# "Setitem" for MapBase-based maps:
450#
451# @code
452#
453# >>> m = ... ## the map
454# >>> m [ key] = value ## set the item
455#
456# @endcode
457# @see Gaudi::Utils::MapBase
458# @see GaudiUtils::Map
459# @see GaudiUtils::HashMap
460# @see GaudiUtils::VectorMap
461# @see GaudiUtils::Map::update
462# @see GaudiUtils::HashMap::update
463# @see GaudiUtils::VectorMap::update
464# @author Vanya BELYAEV Ivan.BElyaev@itep.ru
465# @date 2010-02-20
466
467
468def __mapbase_setitem__(self, key, value):
469 """
470 'Set-item' for MapBase-based maps:
471
472 >>> m = ... ## the map
473 >>> m[key] = value ## set the item
474
475 """
476 _replaced = True if key in self else False
477 self.update(key, value)
478 return _replaced
479
480
481# ============================================
482# "Del-item" for MapBase-based maps:
483#
484# @code
485#
486# >>> m = ... ## the map
487# >>> del m [ key] ## del th eitem
488#
489# @endcode
490#
491# @see Gaudi::Utils::MapBase
492# @see GaudiUtils::Map
493# @see GaudiUtils::HashMap
494# @see GaudiUtils::VectorMap
495# @see GaudiUtils::Map::erase
496# @see GaudiUtils::HashMap::erase
497# @see GaudiUtils::VectorMap::erase
498# @author Vanya BELYAEV Ivan.BElyaev@itep.ru
499# @date 2010-02-20
500
501
502def __mapbase_delitem__(self, key):
503 """
504 'Del-item' for MapBase-based maps:
505
506 >>> m = ... ## the map
507 >>> del m[key]
508
509 """
510 _erased = True if key in self else False
511 self.erase(key)
512 return _erased
513
514
515gbl.Gaudi.Utils.MapBase.__len__ = lambda s: s.size()
516gbl.Gaudi.Utils.MapBase.__iter__ = __mapbase_iter__
517gbl.Gaudi.Utils.MapBase.keys = __mapbase_keys__
518gbl.Gaudi.Utils.MapBase.__iteritems__ = __mapbase_iteritems__
519gbl.Gaudi.Utils.MapBase.values = __mapbase_values__
520gbl.Gaudi.Utils.MapBase.__contains__ = __mapbase_contains__
521gbl.Gaudi.Utils.MapBase.get = __mapbase_get__
522gbl.Gaudi.Utils.MapBase.__str__ = __mapbase_str__
523gbl.Gaudi.Utils.MapBase.__repr__ = __mapbase_str__
524gbl.Gaudi.Utils.MapBase.__setitem__ = __mapbase_setitem__
525gbl.Gaudi.Utils.MapBase.__delitem__ = __mapbase_delitem__
526gbl.Gaudi.Utils.MapBase.__getitem__ = lambda s, key: s.at(key)
527gbl.Gaudi.Utils.MapBase.items = __mapbase_iteritems__
528
529
535gbl.gInterpreter.Declare(
536 """
537#ifndef REENTINTERFACES_PYTHON_HELPERS
538#define REENTINTERFACES_PYTHON_HELPERS
539#include <GaudiKernel/IAlgorithm.h>
540#include <GaudiKernel/IEventProcessor.h>
541#include <GaudiKernel/ThreadLocalContext.h>
542
543namespace GaudiPython::Helpers {
544 StatusCode executeEvent( IEventProcessor* self ) {
545 return self->executeEvent( self->createEventContext() );
546 }
547 bool isExecuted( IAlgorithm* self ) {
548 return self->execState( Gaudi::Hive::currentContext() ).state() == AlgExecState::Done;
549 }
550 bool filterPassed( IAlgorithm* self ) {
551 return self->execState( Gaudi::Hive::currentContext() ).filterPassed();
552 }
553 StatusCode ialg_execute( IAlgorithm* self ) {
554 return self->execute( Gaudi::Hive::currentContext() );
555 }
556}
557
558#endif
559"""
560)
561gbl.IEventProcessor.executeEvent = gbl.GaudiPython.Helpers.executeEvent
562gbl.IAlgorithm.isExecuted = gbl.GaudiPython.Helpers.isExecuted
563gbl.IAlgorithm.filterPassed = gbl.GaudiPython.Helpers.filterPassed
564gbl.IAlgorithm._execute_orig = gbl.IAlgorithm.execute
565gbl.IAlgorithm.execute = lambda self, ctx=None: (
566 gbl.GaudiPython.Helpers.ialg_execute(self)
567 if ctx is None
568 else self._execute_orig(ctx)
569)
__mapbase_get__(self, key, value=None)
__mapbase_setitem__(self, key, value)