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