Back to home page

EIC code displayed by LXR

 
 

    


Warning, file /DD4hep/DDDigi/python/dddigi.py was not indexed or was modified since last indexation (in which case cross-reference links may be missing, inaccurate or erroneous).

0001 # ==========================================================================
0002 #  AIDA Detector description implementation
0003 # --------------------------------------------------------------------------
0004 # Copyright (C) Organisation europeenne pour la Recherche nucleaire (CERN)
0005 # All rights reserved.
0006 #
0007 # For the licensing terms see $DD4hepINSTALL/LICENSE.
0008 # For the list of contributors see $DD4hepINSTALL/doc/CREDITS.
0009 #
0010 # ==========================================================================
0011 import cppyy
0012 from dd4hep_base import *  # noqa: F401, F403
0013 
0014 logger = None
0015 
0016 
0017 def loadDDDigi():
0018   global logger
0019   import ROOT
0020   import dd4hep_base
0021   from ROOT import gSystem
0022 
0023   logger = dd4hep_base.dd4hep_logger('dddigi')
0024 
0025   # Try to load libglapi to avoid issues with TLS Static
0026   # Turn off all errors from ROOT about the library missing
0027   if 'libglapi' not in gSystem.GetLibraries():
0028     orgLevel = ROOT.gErrorIgnoreLevel
0029     ROOT.gErrorIgnoreLevel = 6000
0030     gSystem.Load("libglapi")
0031     ROOT.gErrorIgnoreLevel = orgLevel
0032 
0033   import os
0034   import platform
0035   if platform.system() == "Darwin":
0036     gSystem.SetDynamicPath(os.environ['DD4HEP_LIBRARY_PATH'])
0037   #
0038   # load with ROOT the DDDigi plugin library, which in turn loads the DDigi module
0039   result = gSystem.Load("libDDDigiPlugins")
0040   if result < 0:
0041     raise Exception('DDDigi.py: Failed to load the DDDigi library libDDDigiPlugins: ' + gSystem.GetErrorStr())
0042   logger.info('DDDigi.py: Successfully loaded DDDigi plugin library libDDDigiPlugins!')
0043   #
0044   # import with ROOT the I/O module to read DDG4 output
0045   result = gSystem.Load("libDDDigi_IO")
0046   if result < 0:
0047     raise Exception('DDDigi.py: Failed to load the DDDigi IO library libDDDigi_IO: ' + gSystem.GetErrorStr())
0048   logger.info('DDDigi.py: Successfully loaded DDDigi IO plugin library libDDDigi_IO!')
0049   #
0050   # import the main dd4hep module from ROOT
0051   from ROOT import dd4hep as module
0052   return module
0053 
0054 
0055 # We are nearly there ....
0056 current = __import__(__name__)
0057 
0058 
0059 def _import_class(ns, nam):
0060   scope = getattr(current, ns)
0061   setattr(current, nam, getattr(scope, nam))
0062 
0063 
0064 # ---------------------------------------------------------------------------
0065 #
0066 try:
0067   dd4hep = loadDDDigi()
0068 except Exception as X:
0069   logger.error('+--%-100s--+' % (100 * '-',))
0070   logger.error('|  %-100s  |' % ('Failed to load DDDigi library:',))
0071   logger.error('|  %-100s  |' % (str(X),))
0072   logger.error('+--%-100s--+' % (100 * '-',))
0073   exit(1)
0074 
0075 core = dd4hep
0076 digi = dd4hep.digi
0077 Kernel = digi.KernelHandle
0078 Interface = digi.DigiActionCreation
0079 Detector = core.Detector
0080 
0081 
0082 # ---------------------------------------------------------------------------
0083 def _constant(self, name):
0084   return self.constantAsString(name)
0085 
0086 
0087 Detector.globalVal = _constant
0088 # ---------------------------------------------------------------------------
0089 
0090 
0091 def importConstants(description, namespace=None, debug=False):
0092   """
0093   Import the Detector constants into the dddigi namespace
0094   """
0095   ns = current
0096   if namespace is not None and not hasattr(current, namespace):
0097     import types
0098     m = types.ModuleType('dddigi.' + namespace)
0099     setattr(current, namespace, m)
0100     ns = m
0101   evaluator = dd4hep.g4Evaluator()
0102   cnt = 0
0103   num = 0
0104   todo = {}
0105   strings = {}
0106   for c in description.constants():
0107     if c.second.dataType == 'string':
0108       strings[str(c.first)] = c.second.GetTitle()
0109     else:
0110       todo[str(c.first)] = c.second.GetTitle().replace('(int)', '')
0111   while len(todo) and cnt < 100:
0112     cnt = cnt + 1
0113     if cnt == 100:
0114       logger.info('%s %d out of %d %s "%s": [%s]\n+++ %s' %
0115                   ('+++ FAILED to import',
0116                    len(todo), len(todo) + num,
0117                    'global values into namespace',
0118                    ns.__name__, 'Try to continue anyway', 100 * '=',))
0119       for k, v in todo.items():
0120         if not hasattr(ns, k):
0121           logger.info('+++ FAILED to import: "' + k + '" = "' + str(v) + '"')
0122       logger.info('+++ %s' % (100 * '=',))
0123 
0124     for k, v in list(todo.items()):
0125       if not hasattr(ns, k):
0126         val = evaluator.evaluate(v)
0127         status = evaluator.status()
0128         if status == 0:
0129           evaluator.setVariable(k, val)
0130           setattr(ns, k, val)
0131           if debug:
0132             logger.info('Imported global value: "' + k + '" = "' + str(val) + '" into namespace' + ns.__name__)
0133           del todo[k]
0134           num = num + 1
0135   if cnt < 100:
0136     logger.info('+++ Imported %d global values to namespace:%s' % (num, ns.__name__),)
0137 
0138 
0139 def TestAction(kernel, nam, sleep=0):
0140   obj = Interface.createAction(kernel, str('DigiTestAction/' + nam))
0141   if sleep != 0:
0142     obj.sleep = sleep
0143   return obj
0144 # ---------------------------------------------------------------------------
0145 
0146 
0147 def Action(kernel, nam, **options):
0148   action = Interface.createAction(kernel, str(nam))
0149   for option in options.items():
0150     setattr(action, option[0], option[1])
0151   return action
0152 # ---------------------------------------------------------------------------
0153 
0154 
0155 def _get_action(self):
0156   " Convert handles to action references to access underlying properties provided a dictionary exists. "
0157   return Interface.toAction(self)
0158 
0159 
0160 # ---------------------------------------------------------------------------
0161 def _adopt_property(self, action, foreign_name, local_name=None):
0162   proc = _get_action(action)
0163   if not local_name:
0164     local_name = foreign_name
0165   _get_action(self).adopt_property(proc, str(foreign_name), str(local_name))
0166 
0167 
0168 # ---------------------------------------------------------------------------
0169 def _add_new_property(self, name, value):
0170   Interface.addProperty(_get_action(self), str(name), value)
0171 
0172 
0173 # ---------------------------------------------------------------------------
0174 def _add_new_position_property(self, name, value):
0175   Interface.addPositionProperty(_get_action(self), str(name), str(value))
0176 
0177 
0178 # ---------------------------------------------------------------------------
0179 def _add_new_set_property(self, name, value):
0180   Interface.addSetProperty(_get_action(self), str(name), value)
0181 
0182 
0183 # ---------------------------------------------------------------------------
0184 def _add_new_list_property(self, name, value):
0185   Interface.addListProperty(_get_action(self), str(name), value)
0186 
0187 
0188 # ---------------------------------------------------------------------------
0189 def _add_new_vector_property(self, name, value):
0190   Interface.addVectorProperty(_get_action(self), str(name), value)
0191 
0192 
0193 # ---------------------------------------------------------------------------
0194 def _add_new_mapped_property(self, name, value):
0195   Interface.addMappedProperty(_get_action(self), str(name), value)
0196 # ---------------------------------------------------------------------------
0197 
0198 
0199 def _kernel_terminate(self):
0200   return self.get().terminate()
0201 # ---------------------------------------------------------------------------
0202 
0203 
0204 def _default_adopt(self, action):
0205   self.__adopt(action.get())
0206 # ---------------------------------------------------------------------------
0207 
0208 
0209 def _adopt_event_action(self, action):
0210   " Helper to convert DigiActions objects to DigiEventAction "
0211   proc = Interface.toEventAction(_get_action(action))
0212   attr = self.__adopt
0213   attr(proc)
0214 # ---------------------------------------------------------------------------
0215 
0216 
0217 def _adopt_container_processor(self, action, processor_argument):
0218   " Helper to convert DigiActions objects to DigiEventAction "
0219   parent = Interface.toContainerSequenceAction(_get_action(self))
0220   attr = parent.adopt_processor
0221   proc = Interface.toContainerProcessor(_get_action(action))
0222   attr(proc, processor_argument)
0223 # ---------------------------------------------------------------------------
0224 
0225 
0226 def _adopt_segment_processor(self, action, processor_argument):
0227   " Helper to convert DigiActions objects to DigiEventAction "
0228   attr = _get_action(self).__adopt_segment_processor
0229   proc = Interface.toContainerProcessor(_get_action(action))
0230   attr(proc, processor_argument)
0231 # ---------------------------------------------------------------------------
0232 
0233 
0234 def _adopt_sequence_action(self, name, **options):
0235   " Helper to adopt DigiAction objects for DigiSynchronize "
0236   kernel = Interface.createKernel(_get_action(self))
0237   action = Action(kernel, name)
0238   for option in options.items():
0239     setattr(action, option[0], option[1])
0240   self.adopt(action)
0241   return action
0242 # ---------------------------------------------------------------------------
0243 
0244 
0245 def _adopt_processor(self, action, containers):
0246   proc = Interface.toContainerProcessor(_get_action(action))
0247   attr = _get_action(self).__adopt_processor
0248   attr(proc, containers)
0249 # ---------------------------------------------------------------------------
0250 
0251 
0252 def _get(self, name):
0253   a = Interface.toAction(self)
0254   ret = Interface.getProperty(a, name)
0255   if ret.status > 0:
0256     # print('Property: %s = %s [%s]' % (name, str(ret.data), str(ret.data.__class__),))
0257     v = ret.data
0258     try:
0259       v = eval(v)
0260     except TypeError:
0261       pass
0262     finally:
0263       pass
0264     return v
0265   elif hasattr(a, name):
0266     return getattr(a, name)
0267   # elif a.__class__ != self.__class__ and hasattr(a, name):
0268   #   return getattr(a, name)
0269   msg = 'DigiAction::GetProperty [Unhandled]: Cannot access property ' + a.name() + '.' + str(name)
0270   raise KeyError(msg)
0271 # ---------------------------------------------------------------------------
0272 
0273 
0274 def _set(self, name, value):
0275   """This function is called when properties are passed to the c++ objects."""
0276   import dd4hep as dd4hep
0277   act = _get_action(self)
0278   nam = dd4hep.unicode_2_string(name)
0279   if isinstance(value, (list,)):  # cppyy.gbl.string showing up for some reason
0280     value = [x.decode('utf-8') if isinstance(x, cppyy.gbl.std.string) else x for x in value]
0281   if isinstance(value, str):
0282     val = dd4hep.unicode_2_string(value)
0283   else:
0284     val = str(value)
0285   if Interface.setProperty(act, nam, val):
0286     return
0287   msg = 'DigiAction::SetProperty [Unhandled]: Cannot set ' + act.name() + '.' + str(name) + ' = ' + str(value)
0288   raise KeyError(msg)
0289 # ---------------------------------------------------------------------------
0290 
0291 
0292 def _props(obj, **extensions):
0293   from dd4hep_base import debug as dd4hep_debug
0294   _import_class('digi', obj)
0295   cls = getattr(current, obj)
0296   for extension in extensions.items():
0297     call = extension[0]
0298     # print('TRY: Overloading: ' + str(cls) + ' ' + call + ' to __' + call + ' ' + str(hasattr(cls, call)))
0299     if hasattr(cls, call):
0300       # print('Overloading: ' + str(cls) + ' ' + call + ' to __' + call)
0301       setattr(cls, '__' + call, getattr(cls, call))
0302     else:
0303       dd4hep_debug('FAILED', 'Overloading: ' + str(cls) + ' ' + call + ' to __' + call + ' ' + str(hasattr(cls, call)))
0304     setattr(cls, call, extension[1])
0305   cls.__getattr__ = _get
0306   cls.__setattr__ = _set
0307   return cls
0308 # ---------------------------------------------------------------------------
0309 
0310 
0311 #
0312 # Import unmodified classes from C++
0313 _import_class('digi', 'DigiContext')
0314 
0315 
0316 # ---------------------------------------------------------------------------
0317 Kernel = _props('KernelHandle')
0318 _props('DigiKernel')
0319 _props('DigiAction')
0320 _import_class('digi', 'DigiEventAction')
0321 _import_class('digi', 'DigiInputAction')
0322 #
0323 # Import classes with specialized python extensions
0324 _props('ActionHandle',
0325        adopt_property=_adopt_property,
0326        add_property=_add_new_property,
0327        add_position_property=_add_new_position_property,
0328        add_set_property=_add_new_set_property,
0329        add_list_property=_add_new_list_property,
0330        add_vector_property=_add_new_vector_property,
0331        add_mapped_property=_add_new_mapped_property,
0332        adopt_container_processor=_adopt_container_processor)
0333 _props('DigiSynchronize', adopt=_adopt_event_action, adopt_action=_adopt_sequence_action)
0334 _props('DigiActionSequence', adopt=_adopt_event_action, adopt_action=_adopt_sequence_action)
0335 _props('DigiParallelActionSequence', adopt_action=_adopt_sequence_action)
0336 _props('DigiSequentialActionSequence', adopt_action=_adopt_sequence_action)
0337 _props('DigiContainerSequenceAction', adopt_container_processor=_adopt_container_processor)
0338 _props('DigiMultiContainerProcessor', adopt_processor=_adopt_processor)
0339 _props('DigiSegmentSplitter', adopt_segment_processor=_adopt_segment_processor)
0340 # ---------------------------------------------------------------------------
0341 
0342 
0343 # ---------------------------------------------------------------------------
0344 #
0345 # Need to import digitize late, since it cross includes dddigi
0346 # ---------------------------------------------------------------------------
0347 Digitize = None
0348 try:
0349   import digitize
0350   Digitize = digitize.Digitize
0351 except Exception as X:
0352   logger.error('Failed to import digitize application: ' + str(X))
0353 # ---------------------------------------------------------------------------