The Gaudi Framework  master (37c0b60a)
Pythonizations.py
Go to the documentation of this file.
1 
13 """This Pythonizations module provides a number of useful pythonizations
14 of adaptation of some classes.
15 """
16 
17 __all__ = []
18 
19 try:
20  from cppyy import gbl
21 except ImportError:
22  # FIXME: backward compatibility
23  print("# WARNING: using PyCintex as cppyy implementation")
24  from PyCintex import gbl
25 
26 if not hasattr(gbl, "ostream"):
27  gbl.gROOT.ProcessLine("#include <ostream>")
28 if 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 
87 def _container__getitem__(self, k):
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 
107 def _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 
120 gbl.AIDA.IHistogram1D.__str__ = _printHisto1D
121 gbl.AIDA.IHistogram1D.contents = _contentsHisto1D
122 gbl.AIDA.IHistogram2D.__str__ = _printHisto2D
123 for 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 
134 gbl.StatusCode.__repr__ = _printStatusCode
135 try:
136  gbl._Bit_reference.__repr__ = _printBitReference
137 except Exception:
138  pass
139 gbl.ContainedObject.__repr__ = _printFillStream
140 gbl.DataObject.__repr__ = _printFillStream
141 gbl.ObjectContainerBase.__getitem__ = _container__getitem__
142 gbl.ObjectContainerBase.__len__ = _container__len__
143 gbl.ObjectContainerBase.__iter__ = _container__iter__
144 
145 gbl.IUpdateManagerSvc.update = (
146  lambda self, obj: gbl.IUpdateManagerSvc.PythonHelper.update(self, obj)
147 )
148 gbl.IUpdateManagerSvc.invalidate = (
149  lambda self, obj: gbl.IUpdateManagerSvc.PythonHelper.invalidate(self, obj)
150 )
151 
152 # ---Globals--------------------------------------------------------------------
153 if not hasattr(gbl.StatusCode, "SUCCESS"):
154  # emulate enums
155  gbl.StatusCode.SUCCESS = 1
156  gbl.StatusCode.FAILURE = 0
157 
158 # - string key, equality
159 if 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
164 if hasattr(gbl.Gaudi.StringKey, "__cpp_ne__"):
165  _ne = gbl.Gaudi.StringKey.__cpp_ne__
166  setattr(gbl.Gaudi.StringKey, "__ne__", _ne)
167 
168 # ---Enabling Pickle support----------------------------------------------------
169 if gbl.gROOT.GetVersionInt() <= 51800:
170  import libPyROOT
171 
172  gbl.GaudiPython.PyROOTPickle.Initialize(libPyROOT, libPyROOT.ObjectProxy)
173 
174 # =============================================================================
175 # decorate some map-like objects
176 # =============================================================================
177 # The iterator for MapBase class
178 #
179 # @code
180 #
181 # >>> m = ... ## the map
182 # >>> for key in m : print(key , m[key])
183 #
184 # @endcode
185 # @see Gaudi::Utils::MapBase
186 # @see GaudiUtils::Map
187 # @see GaudiUtils::HashMap
188 # @see GaudiUtils::VectorMap
189 # @see GaudiUtils::Map::key_at
190 # @see GaudiUtils::HashMap::key_at
191 # @see GaudiUtils::VectorMap::key_at
192 # @author Vanya BELYAEV Ivan.Belyaev@itep.ru
193 # @date 2010-02-20
194 
195 
197  """
198  The iterator for MapBase-based containers
199 
200  >>> m = ... ## the map
201  >>> for key in m : print(key , m[key])
202 
203  """
204  _size = len(self)
205  _index = 0
206  while _index < _size:
207  yield self.key_at(_index)
208  _index += 1
209 
210 
211 # =============================================================================
212 # The iterator for MapBase class
213 #
214 # @code
215 #
216 # >>> m = ... ## the map
217 # >>> for key,value in m.iteritems() : print(key , value)
218 #
219 # @endcode
220 # @see Gaudi::Utils::MapBase
221 # @see GaudiUtils::Map
222 # @see GaudiUtils::HashMap
223 # @see GaudiUtils::VectorMap
224 # @see GaudiUtils::Map::key_at
225 # @see GaudiUtils::HashMap::key_at
226 # @see GaudiUtils::VectorMap::key_at
227 # @see GaudiUtils::Map::value_at
228 # @see GaudiUtils::HashMap::value_at
229 # @see GaudiUtils::VectorMap::value_at
230 # @author Vanya BELYAEV Ivan.Belyaev@itep.ru
231 # @date 2010-02-20
232 
233 
235  """
236  The iterator for MapBase-based containers
237 
238  >>> m = ... ## the map
239  >>> for key,value in m.iteritems() : print(key, value)
240 
241  """
242  _size = len(self)
243  _index = 0
244  while _index < _size:
245  _key = self.key_at(_index)
246  yield (_key, self.at(_key))
247  _index += 1
248 
249 
250 # ============================================
251 # Get the list of keys for the map
252 #
253 # @code
254 #
255 # >>> m = ... ## the map
256 # >>> keys = m.keys() ## get the list of keys
257 #
258 # @endcode
259 # @see Gaudi::Utils::MapBase
260 # @see GaudiUtils::Map
261 # @see GaudiUtils::HashMap
262 # @see GaudiUtils::VectorMap
263 # @see GaudiUtils::Map::key_at
264 # @see GaudiUtils::HashMap::key_at
265 # @ see GaudiUtils::VectorMap::key_at
266 # @author Vanya BELYAEV Ivan.BElyaev@itep.ru
267 # @date 2010-02-20
268 
269 
271  """
272  Get the list of keys
273 
274  >>> m = ... ## the map
275  >>> keys = m.keys() ## get the list of keys
276 
277  """
278  _size = len(self)
279  _keys = []
280  for i in range(0, _size):
281  _keys.append(self.key_at(i))
282  return _keys
283 
284 
285 # ============================================
286 # Get the list of items for the map
287 #
288 # @code
289 #
290 # >>> m = ... ## the map
291 # >>> items = m.items() ## get the list of items
292 #
293 # @endcode
294 # @see Gaudi::Utils::MapBase
295 # @see GaudiUtils::Map
296 # @see GaudiUtils::HashMap
297 # @see GaudiUtils::VectorMap
298 # @see GaudiUtils::Map::key_at
299 # @see GaudiUtils::HashMap::key_at
300 # @ see GaudiUtils::VectorMap::key_at
301 # @author Vanya BELYAEV Ivan.BElyaev@itep.ru
302 # @date 2010-02-20
303 
304 
306  """
307  Get the list of items
308 
309  >>> m = ... ## the map
310  >>> items = m.keys() ## get the list of items
311 
312  """
313  _size = len(self)
314  _items = []
315  for i in range(0, _size):
316  _key = self.key_at(i)
317  _value = self.at(_key)
318  _items.append((_key, _value))
319  return _items
320 
321 
322 # ============================================
323 # Get the list of values for the map
324 #
325 # @code
326 #
327 # >>> m = ... ## the map
328 # >>> values = m.values () ## get the list of values
329 #
330 # @endcode
331 # @see Gaudi::Utils::MapBase
332 # @see GaudiUtils::Map
333 # @see GaudiUtils::HashMap
334 # @see GaudiUtils::VectorMap
335 # @see GaudiUtils::Map::value_at
336 # @see GaudiUtils::HashMap::value_at
337 # @ see GaudiUtils::VectorMap::value_at
338 # @author Vanya BELYAEV Ivan.Belyaev@itep.ru
339 # @date 2010-02-20
340 
341 
343  """
344  Get the list of values
345 
346  >>> m = ... ## the map
347  >>> values = m.values() ## get the list of values
348 
349  """
350  _size = len(self)
351  _values = []
352  for i in range(0, _size):
353  _value = self.value_at(i)
354  _values.append(_value)
355  return _values
356 
357 
358 # ============================================
359 # Check if the certain key is in the map
360 #
361 # @code
362 #
363 # >>> m = ... ## the map
364 # >>> if 'a' in m : print('key is in the map!')
365 #
366 # @endcode
367 # @see Gaudi::Utils::MapBase
368 # @see GaudiUtils::Map
369 # @see GaudiUtils::HashMap
370 # @see GaudiUtils::VectorMap
371 # @see GaudiUtils::Map::count
372 # @see GaudiUtils::HashMap::count
373 # @ see GaudiUtils::VectorMap::count
374 # @author Vanya BELYAEV Ivan.BElyaev@itep.ru
375 # @date 2010-02-20
376 
377 
378 def __mapbase_contains__(self, key):
379  """
380  Check if the certainkey is in the map
381 
382  >>> m = ... ## the map
383  >>> if 'a' in m : ... ## chekc the presence of the key in the map
384 
385  """
386  _num = self.count(key)
387  return False if 0 == _num else True
388 
389 
390 # ============================================
391 # Get the value for certain key,
392 # return predefined value otherwise
393 #
394 # @code
395 #
396 # >>> m = ... ## the map
397 # >>> v = m.get( key , 15 ) ## return the value[key] for existing key, else 15
398 #
399 # @endcode
400 # @see Gaudi::Utils::MapBase
401 # @see GaudiUtils::Map
402 # @see GaudiUtils::HashMap
403 # @see GaudiUtils::VectorMap
404 # @see GaudiUtils::Map::count
405 # @see GaudiUtils::HashMap::count
406 # @ see GaudiUtils::VectorMap::count
407 # @author Vanya BELYAEV Ivan.BElyaev@itep.ru
408 # @date 2010-02-20
409 
410 
411 def __mapbase_get__(self, key, value=None):
412  """
413  Get the value for the certain key, or 'value' otherwise
414 
415  >>> m = ... ## the map
416  >>> v = m.get ( key , 15 )
417 
418  """
419  if key in self:
420  return self.at(key)
421  return value
422 
423 
424 # ============================================
425 # Representation of MapBase-based maps
426 #
427 # @code
428 #
429 # >>> m = ... ## the map
430 # >>> print(m)
431 #
432 # @endcode
433 # @see Gaudi::Utils::MapBase
434 # @see GaudiUtils::Map
435 # @see GaudiUtils::HashMap
436 # @see GaudiUtils::VectorMap
437 # @author Vanya BELYAEV Ivan.BElyaev@itep.ru
438 # @date 2010-02-20
439 
440 
441 def __mapbase_str__(self):
442  """
443  Representation of MapBase-based maps:
444 
445  >>> m = ... ## the map
446  >>> print(map)
447 
448  """
449  _result = " { "
450  _size = len(self)
451  for i in range(0, _size):
452  _key = self.key_at(i)
453  _val = self.at(_key)
454  if 0 != i:
455  _result += " , "
456  _result += " %s : %s " % (str(_key), str(_val))
457  _result += " } "
458  return _result
459 
460 
461 # ============================================
462 # "Setitem" for MapBase-based maps:
463 #
464 # @code
465 #
466 # >>> m = ... ## the map
467 # >>> m [ key] = value ## set the item
468 #
469 # @endcode
470 # @see Gaudi::Utils::MapBase
471 # @see GaudiUtils::Map
472 # @see GaudiUtils::HashMap
473 # @see GaudiUtils::VectorMap
474 # @see GaudiUtils::Map::update
475 # @see GaudiUtils::HashMap::update
476 # @see GaudiUtils::VectorMap::update
477 # @author Vanya BELYAEV Ivan.BElyaev@itep.ru
478 # @date 2010-02-20
479 
480 
481 def __mapbase_setitem__(self, key, value):
482  """
483  'Set-item' for MapBase-based maps:
484 
485  >>> m = ... ## the map
486  >>> m[key] = value ## set the item
487 
488  """
489  _replaced = True if key in self else False
490  self.update(key, value)
491  return _replaced
492 
493 
494 # ============================================
495 # "Del-item" for MapBase-based maps:
496 #
497 # @code
498 #
499 # >>> m = ... ## the map
500 # >>> del m [ key] ## del th eitem
501 #
502 # @endcode
503 #
504 # @see Gaudi::Utils::MapBase
505 # @see GaudiUtils::Map
506 # @see GaudiUtils::HashMap
507 # @see GaudiUtils::VectorMap
508 # @see GaudiUtils::Map::erase
509 # @see GaudiUtils::HashMap::erase
510 # @see GaudiUtils::VectorMap::erase
511 # @author Vanya BELYAEV Ivan.BElyaev@itep.ru
512 # @date 2010-02-20
513 
514 
515 def __mapbase_delitem__(self, key):
516  """
517  'Del-item' for MapBase-based maps:
518 
519  >>> m = ... ## the map
520  >>> del m[key]
521 
522  """
523  _erased = True if key in self else False
524  self.erase(key)
525  return _erased
526 
527 
528 gbl.Gaudi.Utils.MapBase.__len__ = lambda s: s.size()
529 gbl.Gaudi.Utils.MapBase.__iter__ = __mapbase_iter__
530 gbl.Gaudi.Utils.MapBase.keys = __mapbase_keys__
531 gbl.Gaudi.Utils.MapBase.__iteritems__ = __mapbase_iteritems__
532 gbl.Gaudi.Utils.MapBase.values = __mapbase_values__
533 gbl.Gaudi.Utils.MapBase.__contains__ = __mapbase_contains__
534 gbl.Gaudi.Utils.MapBase.get = __mapbase_get__
535 gbl.Gaudi.Utils.MapBase.__str__ = __mapbase_str__
536 gbl.Gaudi.Utils.MapBase.__repr__ = __mapbase_str__
537 gbl.Gaudi.Utils.MapBase.__setitem__ = __mapbase_setitem__
538 gbl.Gaudi.Utils.MapBase.__delitem__ = __mapbase_delitem__
539 gbl.Gaudi.Utils.MapBase.__getitem__ = lambda s, key: s.at(key)
540 gbl.Gaudi.Utils.MapBase.items = __mapbase_iteritems__
541 
542 
548 gbl.gInterpreter.Declare(
549  """
550 #ifndef REENTINTERFACES_PYTHON_HELPERS
551 #define REENTINTERFACES_PYTHON_HELPERS
552 #include <GaudiKernel/IAlgorithm.h>
553 #include <GaudiKernel/IEventProcessor.h>
554 #include <GaudiKernel/ThreadLocalContext.h>
555 
556 namespace GaudiPython::Helpers {
557  StatusCode executeEvent( IEventProcessor* self ) {
558  return self->executeEvent( self->createEventContext() );
559  }
560  bool isExecuted( IAlgorithm* self ) {
561  return self->execState( Gaudi::Hive::currentContext() ).state() == AlgExecState::State::Done;
562  }
563  bool filterPassed( IAlgorithm* self ) {
564  return self->execState( Gaudi::Hive::currentContext() ).filterPassed();
565  }
566  StatusCode ialg_execute( IAlgorithm* self ) {
567  return self->execute( Gaudi::Hive::currentContext() );
568  }
569 }
570 
571 #endif
572 """
573 )
574 gbl.IEventProcessor.executeEvent = gbl.GaudiPython.Helpers.executeEvent
575 gbl.IAlgorithm.isExecuted = gbl.GaudiPython.Helpers.isExecuted
576 gbl.IAlgorithm.filterPassed = gbl.GaudiPython.Helpers.filterPassed
577 gbl.IAlgorithm._execute_orig = gbl.IAlgorithm.execute
578 gbl.IAlgorithm.execute = lambda self, ctx=None: (
579  gbl.GaudiPython.Helpers.ialg_execute(self)
580  if ctx is None
581  else self._execute_orig(ctx)
582 )
GaudiPython.Pythonizations.__mapbase_keys__
def __mapbase_keys__(self)
Definition: Pythonizations.py:270
GaudiPython.Pythonizations._printHisto2D
def _printHisto2D(h)
Definition: Pythonizations.py:49
GaudiPython.Pythonizations._printBitReference
def _printBitReference(b)
Definition: Pythonizations.py:69
GaudiPython.Pythonizations._printFillStream
def _printFillStream(o)
Definition: Pythonizations.py:73
Containers::map
struct GAUDI_API map
Parametrisation class for map-like implementation.
Definition: KeyedObjectManager.h:35
GaudiPython.Pythonizations._draw_aida_
def _draw_aida_(self, *args)
Definition: Pythonizations.py:107
GaudiPython.Pythonizations.__mapbase_iter__
def __mapbase_iter__(self)
Definition: Pythonizations.py:196
GaudiPython.Pythonizations._contentsHisto1D
def _contentsHisto1D(h)
Definition: Pythonizations.py:44
GaudiPython.Pythonizations.__mapbase_items__
def __mapbase_items__(self)
Definition: Pythonizations.py:305
GaudiPython.Pythonizations._container__getitem__
def _container__getitem__(self, k)
Definition: Pythonizations.py:87
GaudiPython.Pythonizations._printStatusCode
def _printStatusCode(s)
Definition: Pythonizations.py:62
GaudiPython.Pythonizations.__mapbase_str__
def __mapbase_str__(self)
Definition: Pythonizations.py:441
GaudiPython.Pythonizations.__mapbase_values__
def __mapbase_values__(self)
Definition: Pythonizations.py:342
GaudiPython.Pythonizations.__mapbase_setitem__
def __mapbase_setitem__(self, key, value)
Definition: Pythonizations.py:481
GaudiPython.Pythonizations._printHisto1D
def _printHisto1D(h)
Definition: Pythonizations.py:34
GaudiPython.Pythonizations.__mapbase_delitem__
def __mapbase_delitem__(self, key)
Definition: Pythonizations.py:515
GaudiPython.Pythonizations.__mapbase_iteritems__
def __mapbase_iteritems__(self)
Definition: Pythonizations.py:234
GaudiPython.Pythonizations.__mapbase_get__
def __mapbase_get__(self, key, value=None)
Definition: Pythonizations.py:411
GaudiPython.Pythonizations.__mapbase_contains__
def __mapbase_contains__(self, key)
Definition: Pythonizations.py:378
GaudiPython.Pythonizations._container__len__
def _container__len__(self)
Definition: Pythonizations.py:91
Gaudi::Functional::details::zip::range
decltype(auto) range(Args &&... args)
Zips multiple containers together to form a single range.
Definition: details.h:97
GaudiPython.Pythonizations._container__iter__
def _container__iter__(self)
Definition: Pythonizations.py:95