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