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