diff --git a/DDCore/python/dd4hep.py b/DDCore/python/dd4hep.py index f476450d18e81b69ddcf149b79dc814c6769b92e..57534f9aa559424e993ef7b802acd86638d34392 100644 --- a/DDCore/python/dd4hep.py +++ b/DDCore/python/dd4hep.py @@ -1,5 +1,5 @@ #========================================================================== -# AIDA Detector description implementation +# AIDA Detector description implementation #-------------------------------------------------------------------------- # Copyright (C) Organisation europeenne pour la Recherche nucleaire (CERN) # All rights reserved. diff --git a/DDCore/python/dd4hepFactories.py b/DDCore/python/dd4hepFactories.py index 7995161a971990a207727f4fdaf84337b3d629c7..6f04056e57846611955f8f24d7896f2ed2f8391b 100755 --- a/DDCore/python/dd4hepFactories.py +++ b/DDCore/python/dd4hepFactories.py @@ -1,6 +1,6 @@ #!/bin/python #========================================================================== -# AIDA Detector description implementation +# AIDA Detector description implementation #-------------------------------------------------------------------------- # Copyright (C) Organisation europeenne pour la Recherche nucleaire (CERN) # All rights reserved. @@ -11,7 +11,10 @@ #========================================================================== from __future__ import absolute_import, unicode_literals -import os, sys, optparse, logging +import os +import sys +import optparse +import logging from six.moves import input from io import open @@ -19,107 +22,109 @@ logging.basicConfig(format='%(levelname)s: %(message)s') logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) + class ComponentDumper: - def __init__(self): - os.environ['DD4HEP_TRACE']='ON' - self.all_components = [] - - def scanPath(self): - ldp = os.environ['LD_LIBRARY_PATH'].split(':') - for p in ldp: - if len(p): - logger.info('+== Search component directory: '+p) - files = os.listdir(p) - for f in files: - fname = p+os.sep+f - ext = os.path.splitext(fname)[-1].lower() - if ext == '.components': - self.readComponents(fname) - elif ext == '.rootmap': - self.dumpDictionaries(fname) - - def readComponents(self,fname): - logger.info('+== Search component file: '+fname) - file = open(fname,"r") - lines = file.readlines() - dirname = os.path.dirname(fname) - for l in lines: - l = l[:-1] - if len(l)>2 and (l[0:2] == '//' or l[0] == '#'): - continue - lib, comp = l.split(':') - self.all_components.append([dirname+os.sep+lib,comp]) - file.close() - - def searchDuplicates(self, summary_only=False): - entries = {} - component_count = 0 - duplicate_count = 0 - for lib, comp in self.all_components: - if comp in entries: - dupl = entries[comp] - if dupl[1] == 0: - if not summary_only: - logger.info('+'+('==='*40)) - logger.info('| Component entry: '+comp+' in library: '+dupl[0]) - entries[comp][1] = 1 - if not summary_only: - logger.info('| --> Duplicate factory declaration in: '+ lib) - duplicate_count = duplicate_count + 1 - continue - entries[comp] = [lib,0] - component_count = component_count + 1 - logger.info('+'+('==='*40)) - logger.info('| Found %d dd4hep factory entries and %d DUPLICATES in component files.'%(component_count,duplicate_count,)) - logger.info('+'+('==='*40)) - - def dumpInventory(self, summary_only=False, dump=True, load=False, interactive=True): - entries = {} - do_load = load - library_count = 0 - component_count = 0 - for lib, comp in self.all_components: - if lib not in entries: - entries[lib] = [comp] - library_count = library_count + 1 - component_count = component_count + 1 - continue - entries[lib].append(comp) - component_count = component_count + 1 + def __init__(self): + os.environ['DD4HEP_TRACE'] = 'ON' + self.all_components = [] + + def scanPath(self): + ldp = os.environ['LD_LIBRARY_PATH'].split(':') + for p in ldp: + if len(p): + logger.info('+== Search component directory: ' + p) + files = os.listdir(p) + for f in files: + fname = p + os.sep + f + ext = os.path.splitext(fname)[-1].lower() + if ext == '.components': + self.readComponents(fname) + elif ext == '.rootmap': + self.dumpDictionaries(fname) + + def readComponents(self, fname): + logger.info('+== Search component file: ' + fname) + file = open(fname, "r") + lines = file.readlines() + dirname = os.path.dirname(fname) + for l in lines: + l = l[:-1] + if len(l) > 2 and (l[0:2] == '//' or l[0] == '#'): + continue + lib, comp = l.split(':') + self.all_components.append([dirname + os.sep + lib, comp]) + file.close() + + def searchDuplicates(self, summary_only=False): + entries = {} + component_count = 0 + duplicate_count = 0 + for lib, comp in self.all_components: + if comp in entries: + dupl = entries[comp] + if dupl[1] == 0: + if not summary_only: + logger.info('+' + ('===' * 40)) + logger.info('| Component entry: ' + comp + ' in library: ' + dupl[0]) + entries[comp][1] = 1 if not summary_only: - for lib, comp in entries.items(): - if dump: - logger.info('+== Component library: '+lib) - count = 0 - for c in comp: - count = count + 1 - if dump: - logger.info('| %-3d Component: %s'%(count,c,)) - if do_load: - ret = 'D' - if interactive: - try: - ret = input("<CR> to DUMP the list of components \n"+ - "<Q> to QUIT \n"+ - "<D> to DUMP the list of components \n"+ - "<S> to SKIP this particular library\n"+ - "<L> to no longer LOAD libraries \n") - except Exception as X: - ret = 'D' - if not len(ret): - ret = 'D' - if ret[0].upper() == 'Q': - sys.exit(0) - elif ret[0].upper() == 'D': - gSystem.Load(lib) - elif ret[0].upper() == 'L': - do_load = False - logger.info('+'+('==='*40)) - logger.info('| Found %d dd4hep factory libraries with %d components.'%(library_count,component_count,)) - logger.info('+'+('==='*40) ) - - def dumpDictionaries(self,fname): - pass + logger.info('| --> Duplicate factory declaration in: ' + lib) + duplicate_count = duplicate_count + 1 + continue + entries[comp] = [lib, 0] + component_count = component_count + 1 + logger.info('+' + ('===' * 40)) + logger.info('| Found %d dd4hep factory entries and %d DUPLICATES in component files.' % + (component_count, duplicate_count,)) + logger.info('+' + ('===' * 40)) + + def dumpInventory(self, summary_only=False, dump=True, load=False, interactive=True): + entries = {} + do_load = load + library_count = 0 + component_count = 0 + for lib, comp in self.all_components: + if lib not in entries: + entries[lib] = [comp] + library_count = library_count + 1 + component_count = component_count + 1 + continue + entries[lib].append(comp) + component_count = component_count + 1 + if not summary_only: + for lib, comp in entries.items(): + if dump: + logger.info('+== Component library: ' + lib) + count = 0 + for c in comp: + count = count + 1 + if dump: + logger.info('| %-3d Component: %s' % (count, c,)) + if do_load: + ret = 'D' + if interactive: + try: + ret = input("<CR> to DUMP the list of components \n" + + "<Q> to QUIT \n" + + "<D> to DUMP the list of components \n" + + "<S> to SKIP this particular library\n" + + "<L> to no longer LOAD libraries \n") + except Exception as X: + ret = 'D' + if not len(ret): + ret = 'D' + if ret[0].upper() == 'Q': + sys.exit(0) + elif ret[0].upper() == 'D': + gSystem.Load(lib) + elif ret[0].upper() == 'L': + do_load = False + logger.info('+' + ('===' * 40)) + logger.info('| Found %d dd4hep factory libraries with %d components.' % (library_count, component_count,)) + logger.info('+' + ('===' * 40)) + + def dumpDictionaries(self, fname): + pass parser = optparse.OptionParser() @@ -128,28 +133,28 @@ parser.formatter.width = 132 parser.add_option("-c", "--check", action="store_true", dest="check", default=False, help="Check the components file in the LD_LIBRARY_PATH for duplicates", - metavar="<boolean>") + metavar="<boolean>") -parser.add_option("-d","--dump", - action="store_true", dest="dump", default=False, +parser.add_option("-d", "--dump", + action="store_true", dest="dump", default=False, help="Dump the content of the components files", - metavar="<boolean>") + metavar="<boolean>") -parser.add_option("-l","--load", - action="store_true", dest="load", default=False, +parser.add_option("-l", "--load", + action="store_true", dest="load", default=False, help="Load all libraries indicated in the component files", - metavar="<boolean>") + metavar="<boolean>") -parser.add_option("-n","--no-interactive", - action="store_false", dest="interactive", default=True, +parser.add_option("-n", "--no-interactive", + action="store_false", dest="interactive", default=True, help="Always load. Do NOT inquire if a library should be loaded or not", - metavar="<boolean>") + metavar="<boolean>") (opts, args) = parser.parse_args() if not (opts.check or opts.dump or opts.load): - logger.info(" %s",parser.format_help()) - sys.exit(0) + logger.info(" %s", parser.format_help()) + sys.exit(0) try: import ROOT @@ -157,19 +162,19 @@ try: from ROOT import gSystem gROOT.SetBatch(1) except ImportError as X: - logger.error('PyROOT interface not accessible: %s',str(X)) + logger.error('PyROOT interface not accessible: %s', str(X)) sys.exit(errno.ENOENT) try: import dd4hep except ImportError as X: - logger.error('dd4hep python interface not accessible: %s',str(X)) + logger.error('dd4hep python interface not accessible: %s', str(X)) sys.exit(errno.ENOENT) dmp = ComponentDumper() dmp.scanPath() if opts.check: - dmp.searchDuplicates() + dmp.searchDuplicates() if opts.dump or opts.load: - dmp.dumpInventory(dump=opts.dump,load=opts.load,interactive=opts.interactive) + dmp.dumpInventory(dump=opts.dump, load=opts.load, interactive=opts.interactive) sys.exit(0) diff --git a/DDCore/python/dd4hep_base.py b/DDCore/python/dd4hep_base.py index 36f81375dee0f9d6cdb30a462d08e2e9fd707a63..869be02b9124a8c6516eef406e50e07f524e2875 100644 --- a/DDCore/python/dd4hep_base.py +++ b/DDCore/python/dd4hep_base.py @@ -1,5 +1,5 @@ #========================================================================== -# AIDA Detector description implementation +# AIDA Detector description implementation #-------------------------------------------------------------------------- # Copyright (C) Organisation europeenne pour la Recherche nucleaire (CERN) # All rights reserved. @@ -9,183 +9,198 @@ # #========================================================================== from __future__ import absolute_import, unicode_literals -import imp, logging +import imp +import logging logging.basicConfig(format='%(levelname)s: %(message)s') logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) # We compile the DDG4 plugin on the fly if it does not exist using the AClick mechanism: -def compileAClick(dictionary,g4=True): + + +def compileAClick(dictionary, g4=True): from ROOT import gInterpreter, gSystem - import sys, os.path + import sys + import os.path dd4hep = os.environ['DD4hepINSTALL'] - inc = ' -I'+os.environ['ROOTSYS']+'/include -I'+dd4hep+'/include ' - lib = ' -L'+dd4hep+'/lib -lDDCore -lDDG4 -lDDSegmentation ' + inc = ' -I' + os.environ['ROOTSYS'] + '/include -I' + dd4hep + '/include ' + lib = ' -L' + dd4hep + '/lib -lDDCore -lDDG4 -lDDSegmentation ' if g4: geant4 = os.environ['G4INSTALL'] - inc = inc + ' -I'+geant4+'/include/Geant4 -Wno-shadow -g -O0 ' - lib = lib + ' -L'+geant4+'/lib -L'+geant4+'/lib64 -lG4event -lG4tracking -lG4particles ' + inc = inc + ' -I' + geant4 + '/include/Geant4 -Wno-shadow -g -O0 ' + lib = lib + ' -L' + geant4 + '/lib -L' + geant4 + '/lib64 -lG4event -lG4tracking -lG4particles ' gSystem.AddIncludePath(inc) gSystem.AddLinkedLibs(lib) - logger.info('Loading AClick %s',dictionary) + logger.info('Loading AClick %s', dictionary) package = imp.find_module('DDG4') - dic = os.path.dirname(package[1])+os.sep+dictionary - gInterpreter.ProcessLine('.L '+dic+'+') + dic = os.path.dirname(package[1]) + os.sep + dictionary + gInterpreter.ProcessLine('.L ' + dic + '+') from ROOT import dd4hep as module return module + def loaddd4hep(): - import os, sys + import os + import sys # Add ROOT to the python path in case it is not yet there.... - sys.path.append(os.environ['ROOTSYS']+os.sep+'lib') + sys.path.append(os.environ['ROOTSYS'] + os.sep + 'lib') import ROOT from ROOT import gSystem import platform - if platform.system()=="Darwin": + if platform.system() == "Darwin": gSystem.SetDynamicPath(os.environ['DD4HEP_LIBRARY_PATH']) os.environ['DYLD_LIBRARY_PATH'] = os.pathsep.join([os.environ['DD4HEP_LIBRARY_PATH'], os.environ.get('DYLD_LIBRARY_PATH', '')]).strip(os.pathsep) result = gSystem.Load("libDDCore") if result < 0: - raise Exception('dd4hep.py: Failed to load the dd4hep library libDDCore: '+gSystem.GetErrorStr()) + raise Exception('dd4hep.py: Failed to load the dd4hep library libDDCore: ' + gSystem.GetErrorStr()) from ROOT import dd4hep as module return module + # We are nearly there .... name_space = __import__(__name__) -def import_namespace_item(ns,nam): - scope = getattr(name_space,ns) - attr = getattr(scope,nam) - setattr(name_space,nam,attr) + + +def import_namespace_item(ns, nam): + scope = getattr(name_space, ns) + attr = getattr(scope, nam) + setattr(name_space, nam, attr) return attr + def import_root(nam): - setattr(name_space,nam,getattr(ROOT,nam)) + setattr(name_space, nam, getattr(ROOT, nam)) + #--------------------------------------------------------------------------- # try: - dd4hep = loaddd4hep() + dd4hep = loaddd4hep() import ROOT except Exception as X: import sys - logger.error('+--%-100s--+',100*'-') - logger.error('| %-100s |','Failed to load dd4hep base library:') - logger.error('| %-100s |',str(X)) - logger.error('+--%-100s--+',100*'-') + logger.error('+--%-100s--+', 100 * '-') + logger.error('| %-100s |', 'Failed to load dd4hep base library:') + logger.error('| %-100s |', str(X)) + logger.error('+--%-100s--+', 100 * '-') sys.exit(1) + class _Levels: def __init__(self): - self.VERBOSE=1 - self.DEBUG=2 - self.INFO=3 - self.WARNING=4 - self.ERROR=5 - self.FATAL=6 - self.ALWAYS=7 + self.VERBOSE = 1 + self.DEBUG = 2 + self.INFO = 3 + self.WARNING = 4 + self.ERROR = 5 + self.FATAL = 6 + self.ALWAYS = 7 + OutputLevel = _Levels() #------------------------Generic STL stuff can be accessed using std: ----- # #-- e.g. Create an instance of std::vector<dd4hep::sim::Geant4Vertex*>: # >>> v=dd4hep.vector('dd4hep::sim::Geant4Vertex*')() -# +# #--------------------------------------------------------------------------- import cppyy std = cppyy.gbl.std std_vector = std.vector -std_list = std.list -std_map = std.map -std_pair = std.pair +std_list = std.list +std_map = std.map +std_pair = std.pair #--------------------------------------------------------------------------- -core = dd4hep -cond = dd4hep.cond -tools = dd4hep.tools -align = dd4hep.align +core = dd4hep +cond = dd4hep.cond +tools = dd4hep.tools +align = dd4hep.align detail = dd4hep.detail -units = imp.new_module('units') +units = imp.new_module('units') #--------------------------------------------------------------------------- -import_namespace_item('tools','Evaluator') +import_namespace_item('tools', 'Evaluator') #--------------------------------------------------------------------------- -import_namespace_item('core','NamedObject') -import_namespace_item('core','run_interpreter') +import_namespace_item('core', 'NamedObject') +import_namespace_item('core', 'run_interpreter') + def import_detail(): - import_namespace_item('detail','DD4hepUI') - + import_namespace_item('detail', 'DD4hepUI') + + def import_geometry(): - import_namespace_item('core','setPrintLevel') - import_namespace_item('core','setPrintFormat') - import_namespace_item('core','printLevel') - import_namespace_item('core','Detector') - import_namespace_item('core','evaluator') - import_namespace_item('core','g4Evaluator') - - import_namespace_item('core','VolumeManager') - import_namespace_item('core','OverlayedField') - import_namespace_item('core','Ref_t') + import_namespace_item('core', 'setPrintLevel') + import_namespace_item('core', 'setPrintFormat') + import_namespace_item('core', 'printLevel') + import_namespace_item('core', 'Detector') + import_namespace_item('core', 'evaluator') + import_namespace_item('core', 'g4Evaluator') + + import_namespace_item('core', 'VolumeManager') + import_namespace_item('core', 'OverlayedField') + import_namespace_item('core', 'Ref_t') #// Objects.h - import_namespace_item('core','Author') - import_namespace_item('core','Header') - import_namespace_item('core','Constant') - import_namespace_item('core','Atom') - import_namespace_item('core','Material') - import_namespace_item('core','VisAttr') - import_namespace_item('core','Limit') - import_namespace_item('core','LimitSet') - import_namespace_item('core','Region') + import_namespace_item('core', 'Author') + import_namespace_item('core', 'Header') + import_namespace_item('core', 'Constant') + import_namespace_item('core', 'Atom') + import_namespace_item('core', 'Material') + import_namespace_item('core', 'VisAttr') + import_namespace_item('core', 'Limit') + import_namespace_item('core', 'LimitSet') + import_namespace_item('core', 'Region') #// Readout.h - import_namespace_item('core','Readout') + import_namespace_item('core', 'Readout') #// Alignments.h - import_namespace_item('core','Alignment') - import_namespace_item('core','AlignmentCondition') + import_namespace_item('core', 'Alignment') + import_namespace_item('core', 'AlignmentCondition') #// Conditions.h - import_namespace_item('core','Condition') - import_namespace_item('core','ConditionKey') + import_namespace_item('core', 'Condition') + import_namespace_item('core', 'ConditionKey') #// DetElement.h - import_namespace_item('core','World') - import_namespace_item('core','DetElement') - import_namespace_item('core','SensitiveDetector') + import_namespace_item('core', 'World') + import_namespace_item('core', 'DetElement') + import_namespace_item('core', 'SensitiveDetector') #// Volume.h - import_namespace_item('core','Volume') - import_namespace_item('core','PlacedVolume') + import_namespace_item('core', 'Volume') + import_namespace_item('core', 'PlacedVolume') #// Shapes.h - import_namespace_item('core','Solid') - import_namespace_item('core','Box') - import_namespace_item('core','HalfSpace') - import_namespace_item('core','Polycone') - import_namespace_item('core','ConeSegment') - import_namespace_item('core','Tube') - import_namespace_item('core','CutTube') - import_namespace_item('core','TruncatedTube') - import_namespace_item('core','EllipticalTube') - import_namespace_item('core','Cone') - import_namespace_item('core','Trap') - import_namespace_item('core','PseudoTrap') - import_namespace_item('core','Trapezoid') - import_namespace_item('core','Torus') - import_namespace_item('core','Sphere') - import_namespace_item('core','Paraboloid') - import_namespace_item('core','Hyperboloid') - import_namespace_item('core','PolyhedraRegular') - import_namespace_item('core','Polyhedra') - import_namespace_item('core','ExtrudedPolygon') - import_namespace_item('core','EightPointSolid') - import_namespace_item('core','BooleanSolid') - import_namespace_item('core','SubtractionSolid') - import_namespace_item('core','UnionSolid') - import_namespace_item('core','IntersectionSolid') + import_namespace_item('core', 'Solid') + import_namespace_item('core', 'Box') + import_namespace_item('core', 'HalfSpace') + import_namespace_item('core', 'Polycone') + import_namespace_item('core', 'ConeSegment') + import_namespace_item('core', 'Tube') + import_namespace_item('core', 'CutTube') + import_namespace_item('core', 'TruncatedTube') + import_namespace_item('core', 'EllipticalTube') + import_namespace_item('core', 'Cone') + import_namespace_item('core', 'Trap') + import_namespace_item('core', 'PseudoTrap') + import_namespace_item('core', 'Trapezoid') + import_namespace_item('core', 'Torus') + import_namespace_item('core', 'Sphere') + import_namespace_item('core', 'Paraboloid') + import_namespace_item('core', 'Hyperboloid') + import_namespace_item('core', 'PolyhedraRegular') + import_namespace_item('core', 'Polyhedra') + import_namespace_item('core', 'ExtrudedPolygon') + import_namespace_item('core', 'EightPointSolid') + import_namespace_item('core', 'BooleanSolid') + import_namespace_item('core', 'SubtractionSolid') + import_namespace_item('core', 'UnionSolid') + import_namespace_item('core', 'IntersectionSolid') def import_tgeo(): @@ -236,6 +251,7 @@ def import_tgeo(): import_root('TGeoTrd2') import_root('TGeoXtru') + import_tgeo() import_geometry() import_detail() @@ -246,58 +262,59 @@ import_detail() try: ###from ROOT import TGeoUnit as TGeoUnits def import_units(ns=None): - def import_unit(ns,nam): - setattr(ns,nam,getattr(core,nam)) + def import_unit(ns, nam): + setattr(ns, nam, getattr(core, nam)) items = [ - # Length - 'nanometer','micrometer','millimeter','centimeter','meter','kilometer','parsec','angstrom','fermi', - 'nm','um','mm','cm','m','km','pc', - # Area - 'millimeter2','centimeter2','meter2','kilometer2','barn','millibarn','microbarn','nanobarn','picobarn', - 'mm2','cm2','m2','km2', - # Volume - 'millimeter3','centimeter3','meter3','kilometer3','mm3','cm3','m3','km3', - # Angle - 'radian','milliradian','degree','steradian','rad','mrad','sr','deg', - # Time & frequency - 'nanosecond','second','millisecond','microsecond','picosecond','hertz','kilohertz','megahertz','ns','s','ms', - # Electric charge - 'eplus','e_SI','coulomb', - # Energy - 'electronvolt','kiloelectronvolt','megaelectronvolt','gigaelectronvolt','teraelectronvolt','petaelectronvolt', - 'joule','eV','keV','MeV','GeV','TeV','PeV', - # Mass - 'milligram','gram','kilogram','mg','g','kg', - # Power, Force, Pressure - 'watt','newton','hep_pascal','bar','atmosphere', - # Electrical current, potential, resistance - 'nanoampere','microampere','milliampere','ampere','volt','kilovolt','megavolt','ohm', - # Electric capacitance - 'picofarad','nanofarad','microfarad','millifarad','farad', - # Magnetic flux, field, Inductance, Temperature, substance - 'weber','tesla','gauss','kilogauss','henry','kelvin','mole', - # Activity, dose intensity - 'becquerel','curie','microgray','milligray','gray','kilogray', - # Luminous intensity, flux, Illuminance - 'candela','lumen','lux', - # Misc - 'perCent','perThousand','perMillion','pi','twopi','halfpi','pi2', - 'Avogadro','c_light','c_squared','h_Planck','hbar_Planck','hbarc','hbarc_squared','electron_charge','e_squared', - 'electron_mass_c2','proton_mass_c2','neutron_mass_c2','amu_c2','amu','mu0','epsilon0', - # - 'elm_coupling','fine_structure_const','classic_electr_radius','electron_Compton_length','Bohr_radius', - 'alpha_rcl2','twopi_mc2_rcl2','k_Boltzmann','STP_Temperature','STP_Pressure', - 'kGasThreshold','universe_mean_density' - ] + # Length + 'nanometer', 'micrometer', 'millimeter', 'centimeter', 'meter', 'kilometer', 'parsec', 'angstrom', 'fermi', + 'nm', 'um', 'mm', 'cm', 'm', 'km', 'pc', + # Area + 'millimeter2', 'centimeter2', 'meter2', 'kilometer2', 'barn', 'millibarn', 'microbarn', 'nanobarn', 'picobarn', + 'mm2', 'cm2', 'm2', 'km2', + # Volume + 'millimeter3', 'centimeter3', 'meter3', 'kilometer3', 'mm3', 'cm3', 'm3', 'km3', + # Angle + 'radian', 'milliradian', 'degree', 'steradian', 'rad', 'mrad', 'sr', 'deg', + # Time & frequency + 'nanosecond', 'second', 'millisecond', 'microsecond', 'picosecond', 'hertz', 'kilohertz', 'megahertz', 'ns', 's', 'ms', + # Electric charge + 'eplus', 'e_SI', 'coulomb', + # Energy + 'electronvolt', 'kiloelectronvolt', 'megaelectronvolt', 'gigaelectronvolt', 'teraelectronvolt', 'petaelectronvolt', + 'joule', 'eV', 'keV', 'MeV', 'GeV', 'TeV', 'PeV', + # Mass + 'milligram', 'gram', 'kilogram', 'mg', 'g', 'kg', + # Power, Force, Pressure + 'watt', 'newton', 'hep_pascal', 'bar', 'atmosphere', + # Electrical current, potential, resistance + 'nanoampere', 'microampere', 'milliampere', 'ampere', 'volt', 'kilovolt', 'megavolt', 'ohm', + # Electric capacitance + 'picofarad', 'nanofarad', 'microfarad', 'millifarad', 'farad', + # Magnetic flux, field, Inductance, Temperature, substance + 'weber', 'tesla', 'gauss', 'kilogauss', 'henry', 'kelvin', 'mole', + # Activity, dose intensity + 'becquerel', 'curie', 'microgray', 'milligray', 'gray', 'kilogray', + # Luminous intensity, flux, Illuminance + 'candela', 'lumen', 'lux', + # Misc + 'perCent', 'perThousand', 'perMillion', 'pi', 'twopi', 'halfpi', 'pi2', + 'Avogadro', 'c_light', 'c_squared', 'h_Planck', 'hbar_Planck', 'hbarc', 'hbarc_squared', 'electron_charge', 'e_squared', + 'electron_mass_c2', 'proton_mass_c2', 'neutron_mass_c2', 'amu_c2', 'amu', 'mu0', 'epsilon0', + # + 'elm_coupling', 'fine_structure_const', 'classic_electr_radius', 'electron_Compton_length', 'Bohr_radius', + 'alpha_rcl2', 'twopi_mc2_rcl2', 'k_Boltzmann', 'STP_Temperature', 'STP_Pressure', + 'kGasThreshold', 'universe_mean_density' + ] if ns is None: ns = name_space - logger.debug('Importing units into namespace '+str(ns.__name__)) + logger.debug('Importing units into namespace ' + str(ns.__name__)) for u in items: if u[0] != '_': import_unit(ns, u) - return len(items) + return len(items) except: logger.warning('No units can be imported.') + def import_units(ns=None): return 0 diff --git a/DDDigi/python/DDDigi.py b/DDDigi/python/DDDigi.py index 73ea412776f831139d22316e5b834edcbb9b97a6..8c2575c05f79e59b7d005492f3b0fb011459b8fa 100644 --- a/DDDigi/python/DDDigi.py +++ b/DDDigi/python/DDDigi.py @@ -1,5 +1,5 @@ #========================================================================== -# AIDA Detector description implementation +# AIDA Detector description implementation #-------------------------------------------------------------------------- # Copyright (C) Organisation europeenne pour la Recherche nucleaire (CERN) # All rights reserved. @@ -16,71 +16,80 @@ logging.basicConfig(format='%(levelname)s: %(message)s') logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) + def loadDDDigi(): - ## import ROOT ## done in import * above + # import ROOT ## done in import * above from ROOT import gSystem - ## Try to load libglapi to avoid issues with TLS Static - ## Turn off all errors from ROOT about the library missing + # Try to load libglapi to avoid issues with TLS Static + # Turn off all errors from ROOT about the library missing orgLevel = ROOT.gErrorIgnoreLevel - ROOT.gErrorIgnoreLevel=6000 + ROOT.gErrorIgnoreLevel = 6000 gSystem.Load("libglapi") - ROOT.gErrorIgnoreLevel=orgLevel + ROOT.gErrorIgnoreLevel = orgLevel import platform import os - if platform.system()=="Darwin": + if platform.system() == "Darwin": gSystem.SetDynamicPath(os.environ['DD4HEP_LIBRARY_PATH']) result = gSystem.Load("libDDDigiPlugins") if result < 0: - raise Exception('DDDigi.py: Failed to load the DDDigi library libDDDigiPlugins: '+gSystem.GetErrorStr()) + raise Exception('DDDigi.py: Failed to load the DDDigi library libDDDigiPlugins: ' + gSystem.GetErrorStr()) from ROOT import dd4hep as module return module # We are nearly there .... current = __import__(__name__) -def _import_class(ns,nam): - scope = getattr(current,ns) - setattr(current,nam,getattr(scope,nam)) + + +def _import_class(ns, nam): + scope = getattr(current, ns) + setattr(current, nam, getattr(scope, nam)) + #--------------------------------------------------------------------------- # try: - dd4hep = loadDDDigi() + dd4hep = loadDDDigi() except Exception as X: - logger.error('+--%-100s--+',100*'-') - logger.error('| %-100s |','Failed to load DDDigi library:') - logger.error('| %-100s |',str(X)) - logger.error('+--%-100s--+',100*'-') + logger.error('+--%-100s--+', 100 * '-') + logger.error('| %-100s |', 'Failed to load DDDigi library:') + logger.error('| %-100s |', str(X)) + logger.error('+--%-100s--+', 100 * '-') exit(1) -core = dd4hep -digi = dd4hep.digi -Kernel = digi.KernelHandle -Interface = digi.DigiActionCreation -Detector = core.Detector +core = dd4hep +digi = dd4hep.digi +Kernel = digi.KernelHandle +Interface = digi.DigiActionCreation +Detector = core.Detector # -from dd4hep_base import std, std_vector, std_list, std_map, std_pair +from dd4hep_base import std, std_vector, std_list, std_map, std_pair # #--------------------------------------------------------------------------- -def _constant(self,name): + + +def _constant(self, name): return self.constantAsString(name) + Detector.globalVal = _constant #--------------------------------------------------------------------------- """ Import the Detector constants into the DDDigi namespace """ -def importConstants(description,namespace=None,debug=False): + + +def importConstants(description, namespace=None, debug=False): scope = current ns = current - if namespace is not None and not hasattr(current,namespace): + if namespace is not None and not hasattr(current, namespace): import imp - m = imp.new_module('DDDigi.'+namespace) - setattr(current,namespace,m) + m = imp.new_module('DDDigi.' + namespace) + setattr(current, namespace, m) ns = m evaluator = dd4hep.g4Evaluator() cnt = 0 @@ -91,127 +100,152 @@ def importConstants(description,namespace=None,debug=False): if c.second.dataType == 'string': strings[c.first] = c.second.GetTitle() else: - todo[c.first] = c.second.GetTitle().replace('(int)','') - while len(todo) and cnt<100: + todo[c.first] = c.second.GetTitle().replace('(int)', '') + while len(todo) and cnt < 100: cnt = cnt + 1 if cnt == 100: - logger.info('%s %d out of %d %s "%s": [%s]\n+++ %s',\ - '+++ FAILED to import', - len(todo),len(todo)+num, - 'global values into namespace', - ns.__name__,'Try to continue anyway',100*'=') - for k,v in todo.items(): - if not hasattr(ns,k): - logger.info('+++ FAILED to import: "'+k+'" = "'+str(v)+'"') - logger.info('+++ %s',100*'=') - - for k,v in todo.items(): - if not hasattr(ns,k): + logger.info('%s %d out of %d %s "%s": [%s]\n+++ %s', + '+++ FAILED to import', + len(todo), len(todo) + num, + 'global values into namespace', + ns.__name__, 'Try to continue anyway', 100 * '=') + for k, v in todo.items(): + if not hasattr(ns, k): + logger.info('+++ FAILED to import: "' + k + '" = "' + str(v) + '"') + logger.info('+++ %s', 100 * '=') + + for k, v in todo.items(): + if not hasattr(ns, k): val = evaluator.evaluate(v) status = evaluator.status() if status == 0: - evaluator.setVariable(k,val) - setattr(ns,k,val) - if debug: logger.info('Imported global value: "'+k+'" = "'+str(val)+'" into namespace'+ns.__name__) + evaluator.setVariable(k, val) + setattr(ns, k, val) + if debug: + logger.info('Imported global value: "' + k + '" = "' + str(val) + '" into namespace' + ns.__name__) del todo[k] num = num + 1 - if cnt<100: - logger.info('+++ Imported %d global values to namespace:%s',num,ns.__name__,) + if cnt < 100: + logger.info('+++ Imported %d global values to namespace:%s', num, ns.__name__,) #--------------------------------------------------------------------------- + + def _getKernelProperty(self, name): - ret = Interface.getPropertyKernel(self.get(),name) + ret = Interface.getPropertyKernel(self.get(), name) if ret.status > 0: return ret.data - elif hasattr(self.get(),name): - return getattr(self.get(),name) - elif hasattr(self,name): - return getattr(self,name) - msg = 'DigiKernel::GetProperty [Unhandled]: Cannot access Kernel.'+name + elif hasattr(self.get(), name): + return getattr(self.get(), name) + elif hasattr(self, name): + return getattr(self, name) + msg = 'DigiKernel::GetProperty [Unhandled]: Cannot access Kernel.' + name raise KeyError(msg) #--------------------------------------------------------------------------- + + def _setKernelProperty(self, name, value): - if Interface.setPropertyKernel(self.get(),str(name),str(value)): + if Interface.setPropertyKernel(self.get(), str(name), str(value)): return - msg = 'DigiKernel::SetProperty [Unhandled]: Cannot set Kernel.'+name+' = '+str(value) + msg = 'DigiKernel::SetProperty [Unhandled]: Cannot set Kernel.' + name + ' = ' + str(value) raise KeyError(msg) #--------------------------------------------------------------------------- -def _kernel_terminate(self): return self.get().terminate() + + +def _kernel_terminate(self): return self.get().terminate() + + #--------------------------------------------------------------------------- Kernel.__getattr__ = _getKernelProperty Kernel.__setattr__ = _setKernelProperty -Kernel.terminate = _kernel_terminate +Kernel.terminate = _kernel_terminate #--------------------------------------------------------------------------- ActionHandle = digi.ActionHandle #--------------------------------------------------------------------------- + + def Action(kernel, nam, parallel=False): - obj = Interface.createAction(kernel,str(nam)) + obj = Interface.createAction(kernel, str(nam)) obj.parallel = parallel return obj #--------------------------------------------------------------------------- + + def TestAction(kernel, nam, sleep=0): - obj = Interface.createAction(kernel,str('DigiTestAction/'+nam)) + obj = Interface.createAction(kernel, str('DigiTestAction/' + nam)) if sleep != 0: obj.sleep = sleep return obj #--------------------------------------------------------------------------- + + def ActionSequence(kernel, nam, parallel=False): - obj = Interface.createSequence(kernel,str(nam)) + obj = Interface.createSequence(kernel, str(nam)) obj.parallel = parallel return obj #--------------------------------------------------------------------------- + + def Synchronize(kernel, nam, parallel=False): - obj = Interface.createSync(kernel,str(nam)) + obj = Interface.createSync(kernel, str(nam)) obj.parallel = parallel return obj #--------------------------------------------------------------------------- + + def _setup(obj): - def _adopt(self,action): self.__adopt(action.get()) - _import_class('digi',obj) - o = getattr(current,obj) - setattr(o,'__adopt',getattr(o,'adopt')) - setattr(o,'adopt',_adopt) - #setattr(o,'add',_adopt) + def _adopt(self, action): self.__adopt(action.get()) + _import_class('digi', obj) + o = getattr(current, obj) + setattr(o, '__adopt', getattr(o, 'adopt')) + setattr(o, 'adopt', _adopt) + # setattr(o,'add',_adopt) + #--------------------------------------------------------------------------- _setup('DigiActionSequence') _setup('DigiSynchronize') -_import_class('digi','DigiKernel') -_import_class('digi','DigiContext') -_import_class('digi','DigiAction') +_import_class('digi', 'DigiKernel') +_import_class('digi', 'DigiContext') +_import_class('digi', 'DigiAction') #--------------------------------------------------------------------------- + + def _get(self, name): import traceback a = Interface.toAction(self) - ret = Interface.getProperty(a,name) + ret = Interface.getProperty(a, name) if ret.status > 0: return ret.data - elif hasattr(self.action,name): - return getattr(self.action,name) - elif hasattr(a,name): - return getattr(a,name) - #elif hasattr(self,name): + elif hasattr(self.action, name): + return getattr(self.action, name) + elif hasattr(a, name): + return getattr(a, name) + # elif hasattr(self,name): # return getattr(self,name) - #traceback.print_stack() - msg = 'DigiAction::GetProperty [Unhandled]: Cannot access property '+a.name()+'.'+name + # traceback.print_stack() + msg = 'DigiAction::GetProperty [Unhandled]: Cannot access property ' + a.name() + '.' + name raise KeyError(msg) + def _set(self, name, value): a = Interface.toAction(self) - if Interface.setProperty(a,name,str(value)): + if Interface.setProperty(a, name, str(value)): return - msg = 'DigiAction::SetProperty [Unhandled]: Cannot set '+a.name()+'.'+name+' = '+str(value) + msg = 'DigiAction::SetProperty [Unhandled]: Cannot set ' + a.name() + '.' + name + ' = ' + str(value) raise KeyError(msg) + def _props(obj): - _import_class('digi',obj) - cl = getattr(current,obj) + _import_class('digi', obj) + cl = getattr(current, obj) cl.__getattr__ = _get cl.__setattr__ = _set + _props('ActionHandle') _props('ActionSequenceHandle') _props('SynchronizeHandle') @@ -229,6 +263,8 @@ _props('SynchronizeHandle') \version 1.0 """ + + class Digitize: def __init__(self, kernel=None): kernel.printProperties() @@ -242,6 +278,7 @@ class Digitize: \author M.Frank """ + def kernel(self): return self._kernel @@ -250,6 +287,7 @@ class Digitize: \author M.Frank """ + def execute(self): self.kernel().configure() self.kernel().initialize() @@ -263,7 +301,7 @@ class Digitize: o = DetElement(i.second.ptr()) sd = self.description.sensitiveDetector(o.name()) if sd.isValid(): - d = { 'name': o.name(), 'type': sd.type(), 'detector': o, 'sensitive': sd } + d = {'name': o.name(), 'type': sd.type(), 'detector': o, 'sensitive': sd} detectors.append(d) return detectors @@ -273,36 +311,37 @@ class Digitize: for d in dets: logger.info('+++ %-32s ---> type:%-12s', d['name'], d['type']) - def setupDetector(self,name,collections=None,modules=None): + def setupDetector(self, name, collections=None, modules=None): parameterDict = {} - seq = ActionSequence(self.kernel(),'DigiActionSequence/'+name) + seq = ActionSequence(self.kernel(), 'DigiActionSequence/' + name) actions = [] - if isinstance(modules,tuple) or isinstance(modules,list): + if isinstance(modules, tuple) or isinstance(modules, list): for m in modules: - if isinstance(m,str): + if isinstance(m, str): a = Action(self.kernel(), m) actions.append(a) - elif isinstance(m,tuple) or isinstance(m,list): + elif isinstance(m, tuple) or isinstance(m, list): a = Action(self.kernel(), m[0]) actions.append(a) if len(m) > 1: params = m[1] - for k,v in params.items(): + for k, v in params.items(): setattr(a, k, v) else: ol = m.OutputLevel # Check if the object is a DigiAction.... actions.append(m) for a in actions: seq.adopt(a) - return (seq,actions) + return (seq, actions) """ Configure ROOT output for the event digitization \author M.Frank """ - def setupROOTOutput(self,name,output,mc_truth=True): - evt_root = EventAction(self.kernel(),'DigiOutput2ROOT/'+name,True) + + def setupROOTOutput(self, name, output, mc_truth=True): + evt_root = EventAction(self.kernel(), 'DigiOutput2ROOT/' + name, True) evt_root.HandleMCTruth = mc_truth evt_root.Control = True if not output.endswith('.root'): @@ -324,10 +363,11 @@ class Digitize: \author M.Frank """ + def buildInputStage(self, generator_input_modules, output_level=None, have_mctruth=True): ga = self.kernel().generatorAction() # Register Generation initialization action - gen = GeneratorAction(self.kernel(),"DigiGeneratorActionInit/GenerationInit") + gen = GeneratorAction(self.kernel(), "DigiGeneratorActionInit/GenerationInit") if output_level is not None: gen.OutputLevel = output_level ga.adopt(gen) @@ -341,7 +381,7 @@ class Digitize: ga.adopt(gen) # Merge all existing interaction records - gen = GeneratorAction(self.kernel(),"DigiInteractionMerger/InteractionMerger") + gen = GeneratorAction(self.kernel(), "DigiInteractionMerger/InteractionMerger") gen.enableUI() if output_level is not None: gen.OutputLevel = output_level @@ -349,8 +389,8 @@ class Digitize: # Finally generate Digi primaries if have_mctruth: - gen = GeneratorAction(self.kernel(),"DigiPrimaryHandler/PrimaryHandler") - gen.RejectPDGs="{1,2,3,4,5,6,21,23,24}" + gen = GeneratorAction(self.kernel(), "DigiPrimaryHandler/PrimaryHandler") + gen.RejectPDGs = "{1,2,3,4,5,6,21,23,24}" gen.enableUI() if output_level is not None: gen.OutputLevel = output_level @@ -362,12 +402,12 @@ class Digitize: Execute the main Digi action \author M.Frank """ + def run(self): - #self.kernel().configure() - #self.kernel().initialize() - #self.kernel().run() - #self.kernel().terminate() + # self.kernel().configure() + # self.kernel().initialize() + # self.kernel().run() + # self.kernel().terminate() from ROOT import PyDDDigi PyDDDigi.run(self.kernel().get()) return self - diff --git a/DDG4/examples/CLICSidSimuLCIO.py b/DDG4/examples/CLICSidSimuLCIO.py index bfed67f00f178091f491d8a32475bf0095f2a1e7..e50f8690a74d323836244549322df03adc208049 100644 --- a/DDG4/examples/CLICSidSimuLCIO.py +++ b/DDG4/examples/CLICSidSimuLCIO.py @@ -7,7 +7,9 @@ """ from __future__ import absolute_import, unicode_literals -import os, time, DDG4 +import os +import time +import DDG4 from DDG4 import OutputLevel as Output from SystemOfUnits import * import logging @@ -16,21 +18,22 @@ logging.basicConfig(format='%(levelname)s: %(message)s') logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) + def run(): kernel = DDG4.Kernel() install_dir = os.environ['DD4hepINSTALL'] - example_dir = install_dir+'/examples/DDG4/examples'; - kernel.loadGeometry(str("file:"+install_dir+"/examples/CLICSiD/compact/compact.xml")) + example_dir = install_dir + '/examples/DDG4/examples' + kernel.loadGeometry(str("file:" + install_dir + "/examples/CLICSiD/compact/compact.xml")) - simple = DDG4.Simple(kernel,tracker='LcioTestTrackerAction') + simple = DDG4.Simple(kernel, tracker='LcioTestTrackerAction') simple.printDetectors() # Configure UI simple.setupCshUI() # Configure Run actions - run1 = DDG4.RunAction(kernel,'Geant4TestRunAction/RunInit') - run1.Property_int = 12345 - run1.Property_double = -5e15*keV + run1 = DDG4.RunAction(kernel, 'Geant4TestRunAction/RunInit') + run1.Property_int = 12345 + run1.Property_double = -5e15 * keV run1.Property_string = 'Startrun: Hello_2' logger.info("%s %s %s", run1.Property_string, run1.Property_double, run1.Property_int) run1.enableUI() @@ -38,17 +41,17 @@ def run(): kernel.runAction().add(run1) # Configure Event actions - evt2 = DDG4.EventAction(kernel,'Geant4TestEventAction/UserEvent_2') - evt2.Property_int = 123454321 - evt2.Property_double = 5e15*GeV + evt2 = DDG4.EventAction(kernel, 'Geant4TestEventAction/UserEvent_2') + evt2.Property_int = 123454321 + evt2.Property_double = 5e15 * GeV evt2.Property_string = 'Hello_2 from the python setup' evt2.enableUI() kernel.registerGlobalAction(evt2) - evt1 = DDG4.EventAction(kernel,'Geant4TestEventAction/UserEvent_1') - evt1.Property_int=0o1234 - evt1.Property_double=1e11 - evt1.Property_string='Hello_1' + evt1 = DDG4.EventAction(kernel, 'Geant4TestEventAction/UserEvent_1') + evt1.Property_int = 0o1234 + evt1.Property_double = 1e11 + evt1.Property_string = 'Hello_1' evt1.enableUI() kernel.eventAction().add(evt1) @@ -62,13 +65,13 @@ def run(): mc.release() """ # Configure I/O - evt_lcio = simple.setupLCIOOutput('LcioOutput','CLICSiD_'+time.strftime('%Y-%m-%d_%H-%M')) + evt_lcio = simple.setupLCIOOutput('LcioOutput', 'CLICSiD_' + time.strftime('%Y-%m-%d_%H-%M')) - gen = DDG4.GeneratorAction(kernel,"Geant4TestGeneratorAction/Generate") + gen = DDG4.GeneratorAction(kernel, "Geant4TestGeneratorAction/Generate") kernel.generatorAction().add(gen) # Setup particle gun - gun = simple.setupGun('Gun','pi-',100*GeV,True) + gun = simple.setupGun('Gun', 'pi-', 100 * GeV, True) """ rdr = DDG4.GeneratorAction(kernel,"LcioGeneratorAction/Reader") @@ -81,52 +84,52 @@ def run(): """ # Setup global filters fur use in sensintive detectors - f1 = DDG4.Filter(kernel,'GeantinoRejectFilter/GeantinoRejector') + f1 = DDG4.Filter(kernel, 'GeantinoRejectFilter/GeantinoRejector') kernel.registerGlobalFilter(f1) - f2 = DDG4.Filter(kernel,'ParticleRejectFilter/OpticalPhotonRejector') + f2 = DDG4.Filter(kernel, 'ParticleRejectFilter/OpticalPhotonRejector') f2.particle = 'opticalphoton' kernel.registerGlobalFilter(f2) - f3 = DDG4.Filter(kernel,'ParticleSelectFilter/OpticalPhotonSelector') + f3 = DDG4.Filter(kernel, 'ParticleSelectFilter/OpticalPhotonSelector') f3.particle = 'opticalphoton' kernel.registerGlobalFilter(f3) - f4 = DDG4.Filter(kernel,'EnergyDepositMinimumCut') - f4.Cut = 10*MeV + f4 = DDG4.Filter(kernel, 'EnergyDepositMinimumCut') + f4.Cut = 10 * MeV f4.enableUI() kernel.registerGlobalFilter(f4) # First the tracking detectors - seq,act = simple.setupTracker('SiVertexBarrel') + seq, act = simple.setupTracker('SiVertexBarrel') seq.add(f1) - #seq.add(f4) + # seq.add(f4) act.add(f1) - seq,act = simple.setupTracker('SiVertexEndcap') + seq, act = simple.setupTracker('SiVertexEndcap') seq.add(f1) - #seq.add(f4) + # seq.add(f4) - seq,act = simple.setupTracker('SiTrackerBarrel') - seq,act = simple.setupTracker('SiTrackerEndcap') - seq,act = simple.setupTracker('SiTrackerForward') + seq, act = simple.setupTracker('SiTrackerBarrel') + seq, act = simple.setupTracker('SiTrackerEndcap') + seq, act = simple.setupTracker('SiTrackerForward') # Now the calorimeters - seq,act = simple.setupCalorimeter('EcalBarrel') - seq,act = simple.setupCalorimeter('EcalEndcap') - seq,act = simple.setupCalorimeter('HcalBarrel') - seq,act = simple.setupCalorimeter('HcalEndcap') - seq,act = simple.setupCalorimeter('HcalPlug') - seq,act = simple.setupCalorimeter('MuonBarrel') - seq,act = simple.setupCalorimeter('MuonEndcap') - seq,act = simple.setupCalorimeter('LumiCal') - seq,act = simple.setupCalorimeter('BeamCal') + seq, act = simple.setupCalorimeter('EcalBarrel') + seq, act = simple.setupCalorimeter('EcalEndcap') + seq, act = simple.setupCalorimeter('HcalBarrel') + seq, act = simple.setupCalorimeter('HcalEndcap') + seq, act = simple.setupCalorimeter('HcalPlug') + seq, act = simple.setupCalorimeter('MuonBarrel') + seq, act = simple.setupCalorimeter('MuonEndcap') + seq, act = simple.setupCalorimeter('LumiCal') + seq, act = simple.setupCalorimeter('BeamCal') # Now build the physics list: phys = simple.setupPhysics('QGSP_BERT') - ph = DDG4.PhysicsList(kernel,'Geant4PhysicsList/Myphysics') + ph = DDG4.PhysicsList(kernel, 'Geant4PhysicsList/Myphysics') ph.addParticleConstructor(str('G4BosonConstructor')) ph.addParticleConstructor(str('G4LeptonConstructor')) - ph.addParticleProcess(str('e[+-]'),str('G4eMultipleScattering'),-1,1,1) + ph.addParticleProcess(str('e[+-]'), str('G4eMultipleScattering'), -1, 1, 1) ph.addPhysicsConstructor(str('G4StepLimiterPhysics')) ph.addPhysicsConstructor(str('G4OpticalPhysics')) ph.enableUI() @@ -137,9 +140,10 @@ def run(): kernel.configure() kernel.initialize() - #DDG4.setPrintLevel(Output.DEBUG) + # DDG4.setPrintLevel(Output.DEBUG) kernel.run() kernel.terminate() + if __name__ == "__main__": run() diff --git a/DDG4/examples/CLICSidSimuMarkus.py b/DDG4/examples/CLICSidSimuMarkus.py index 1fa8486717ac7ea505fa2e2e87eaeebd9d3a39f5..426544fd6a6ba3ccdbd997f722ac1fd08a445b4c 100644 --- a/DDG4/examples/CLICSidSimuMarkus.py +++ b/DDG4/examples/CLICSidSimuMarkus.py @@ -1,7 +1,10 @@ # # from __future__ import absolute_import, unicode_literals -import os, time, logging, DDG4 +import os +import time +import logging +import DDG4 from DDG4 import OutputLevel as Output from SystemOfUnits import * # @@ -39,42 +42,44 @@ kernel.configure() """ + + def run(): kernel = DDG4.Kernel() description = kernel.detectorDescription() install_dir = os.environ['DD4hepINSTALL'] - example_dir = install_dir+'/examples/DDG4/examples'; - kernel.loadGeometry(str("file:"+install_dir+"/DDDetectors/compact/SiD_Markus.xml")) - ##kernel.loadXML("file:"+example_dir+"/DDG4_field.xml") - DDG4.importConstants(description,debug=False) - geant4 = DDG4.Geant4(kernel,tracker='Geant4TrackerCombineAction') + example_dir = install_dir + '/examples/DDG4/examples' + kernel.loadGeometry(str("file:" + install_dir + "/DDDetectors/compact/SiD_Markus.xml")) + # kernel.loadXML("file:"+example_dir+"/DDG4_field.xml") + DDG4.importConstants(description, debug=False) + geant4 = DDG4.Geant4(kernel, tracker='Geant4TrackerCombineAction') geant4.printDetectors() # Configure UI - #geant4.setupCshUI(macro='run.mac',ui=None) + # geant4.setupCshUI(macro='run.mac',ui=None) geant4.setupCshUI() geant4.setupTrackingField() # Configure Run actions - run1 = DDG4.RunAction(kernel,'Geant4TestRunAction/RunInit') + run1 = DDG4.RunAction(kernel, 'Geant4TestRunAction/RunInit') run1.enableUI() kernel.registerGlobalAction(run1) kernel.runAction().adopt(run1) # Configure Event actions - prt = DDG4.EventAction(kernel,'Geant4ParticlePrint/ParticlePrint') + prt = DDG4.EventAction(kernel, 'Geant4ParticlePrint/ParticlePrint') prt.OutputLevel = Output.WARNING - prt.OutputType = 3 # Print both: table and tree + prt.OutputType = 3 # Print both: table and tree kernel.eventAction().adopt(prt) generator_output_level = Output.WARNING # Configure I/O - evt_lcio = geant4.setupLCIOOutput('LcioOutput','CLICSiD_'+time.strftime('%Y-%m-%d_%H-%M')) + evt_lcio = geant4.setupLCIOOutput('LcioOutput', 'CLICSiD_' + time.strftime('%Y-%m-%d_%H-%M')) ##evt_lcio.OutputLevel = generator_output_level #evt_root = geant4.setupROOTOutput('RootOutput','CLICSiD_'+time.strftime('%Y-%m-%d_%H-%M')) - prim = DDG4.GeneratorAction(kernel,"Geant4GeneratorActionInit/GenerationInit") - #VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV + prim = DDG4.GeneratorAction(kernel, "Geant4GeneratorActionInit/GenerationInit") + # VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV """ Generation of primary particles from LCIO input files """ @@ -98,9 +103,9 @@ def run(): geant4.buildInputStage([gen],output_level=generator_output_level) """ #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - gen = geant4.setupGun("Gun",particle='mu+',energy=20*GeV,position=(0*mm,0*mm,0*cm),multiplicity=3) + gen = geant4.setupGun("Gun", particle='mu+', energy=20 * GeV, position=(0 * mm, 0 * mm, 0 * cm), multiplicity=3) gen.isotrop = True - gen.direction = (1,0,0) + gen.direction = (1, 0, 0) gen.OutputLevel = generator_output_level gen.Standalone = False """ @@ -118,7 +123,7 @@ def run(): user.enableUI() part.adopt(user) """ - geant4.buildInputStage([prim,gen],Output.ERROR) + geant4.buildInputStage([prim, gen], Output.ERROR) """ """ @@ -133,11 +138,10 @@ def run(): kernel.generatorAction().adopt(rdr) """ - # First the tracking detectors - seq,act = geant4.setupTracker('SiTrackerBarrel') - seq,act = geant4.setupTracker('SiTrackerEndcap') - seq,act = geant4.setupTracker('SiTrackerForward') + seq, act = geant4.setupTracker('SiTrackerBarrel') + seq, act = geant4.setupTracker('SiTrackerEndcap') + seq, act = geant4.setupTracker('SiTrackerForward') """ # Now the calorimeters seq,act = geant4.setupTracker('SiVertexBarrel') @@ -158,10 +162,9 @@ def run(): kernel.steppingAction().adopt(scan) """ - # Now build the physics list: phys = geant4.setupPhysics('QGSP_BERT') - ph = DDG4.PhysicsList(kernel,'Geant4PhysicsList/Myphysics') + ph = DDG4.PhysicsList(kernel, 'Geant4PhysicsList/Myphysics') ph.addParticleConstructor('G4Geantino') ph.addParticleConstructor('G4BosonConstructor') ph.enableUI() @@ -171,10 +174,11 @@ def run(): kernel.configure() kernel.initialize() - #DDG4.setPrintLevel(Output.DEBUG) + # DDG4.setPrintLevel(Output.DEBUG) kernel.run() logger.info('End of run. Terminating .......') kernel.terminate() + if __name__ == "__main__": run() diff --git a/DDG4/examples/SiDSim.py b/DDG4/examples/SiDSim.py index 269eab120ee6d31a4357cba4db3c173cf7abda1d..f9e697944c00e43a3e5342605fd275269764cd03 100644 --- a/DDG4/examples/SiDSim.py +++ b/DDG4/examples/SiDSim.py @@ -1,7 +1,10 @@ # # from __future__ import absolute_import, unicode_literals -import os, time, logging, DDG4 +import os +import time +import logging +import DDG4 from DDG4 import OutputLevel as Output from SystemOfUnits import * # @@ -18,14 +21,15 @@ logger.setLevel(logging.INFO) """ + def run(): kernel = DDG4.Kernel() description = kernel.detectorDescription() install_dir = os.environ['DD4hepINSTALL'] - kernel.loadGeometry(str("file:"+install_dir+"/DDDetectors/compact/SiD.xml")) + kernel.loadGeometry(str("file:" + install_dir + "/DDDetectors/compact/SiD.xml")) DDG4.importConstants(description) - geant4 = DDG4.Geant4(kernel,tracker='Geant4TrackerCombineAction') + geant4 = DDG4.Geant4(kernel, tracker='Geant4TrackerCombineAction') geant4.printDetectors() logger.info("# Configure UI") geant4.setupCshUI() @@ -34,25 +38,25 @@ def run(): geant4.setupTrackingField() logger.info("# Setup random generator") - rndm = DDG4.Action(kernel,'Geant4Random/Random') + rndm = DDG4.Action(kernel, 'Geant4Random/Random') rndm.Seed = 987654321 rndm.initialize() - ##rndm.showStatus() + # rndm.showStatus() logger.info("# Configure Run actions") - run1 = DDG4.RunAction(kernel,'Geant4TestRunAction/RunInit') - run1.Property_int = 12345 - run1.Property_double = -5e15*keV + run1 = DDG4.RunAction(kernel, 'Geant4TestRunAction/RunInit') + run1.Property_int = 12345 + run1.Property_double = -5e15 * keV run1.Property_string = 'Startrun: Hello_2' - logger.info("%s %s %s",run1.Property_string, str(run1.Property_double), str(run1.Property_int)) + logger.info("%s %s %s", run1.Property_string, str(run1.Property_double), str(run1.Property_int)) run1.enableUI() kernel.registerGlobalAction(run1) kernel.runAction().adopt(run1) logger.info("# Configure Event actions") - prt = DDG4.EventAction(kernel,'Geant4ParticlePrint/ParticlePrint') + prt = DDG4.EventAction(kernel, 'Geant4ParticlePrint/ParticlePrint') prt.OutputLevel = Output.INFO - prt.OutputType = 3 # Print both: table and tree + prt.OutputType = 3 # Print both: table and tree kernel.eventAction().adopt(prt) logger.info(""" @@ -61,82 +65,82 @@ def run(): #evt_lcio = geant4.setupLCIOOutput('LcioOutput','CLICSiD_'+time.strftime('%Y-%m-%d_%H-%M')) #evt_lcio.OutputLevel = Output.ERROR - evt_root = geant4.setupROOTOutput('RootOutput','CLICSiD_'+time.strftime('%Y-%m-%d_%H-%M')) + evt_root = geant4.setupROOTOutput('RootOutput', 'CLICSiD_' + time.strftime('%Y-%m-%d_%H-%M')) generator_output_level = Output.INFO - gen = DDG4.GeneratorAction(kernel,"Geant4GeneratorActionInit/GenerationInit") + gen = DDG4.GeneratorAction(kernel, "Geant4GeneratorActionInit/GenerationInit") kernel.generatorAction().adopt(gen) - #VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV + # VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV logger.info(""" Generation of isotrope tracks of a given multiplicity with overlay: """) logger.info("# First particle generator: pi+") - gen = DDG4.GeneratorAction(kernel,"Geant4IsotropeGenerator/IsotropPi+"); - gen.Mask = 1 + gen = DDG4.GeneratorAction(kernel, "Geant4IsotropeGenerator/IsotropPi+") + gen.Mask = 1 gen.Particle = 'pi+' - gen.Energy = 100 * GeV + gen.Energy = 100 * GeV gen.Multiplicity = 2 gen.Distribution = 'cos(theta)' kernel.generatorAction().adopt(gen) logger.info("# Install vertex smearing for this interaction") - gen = DDG4.GeneratorAction(kernel,"Geant4InteractionVertexSmear/SmearPi+"); - gen.Mask = 1 - gen.Offset = (20*mm, 10*mm, 10*mm, 0*ns) - gen.Sigma = (4*mm, 1*mm, 1*mm, 0*ns) + gen = DDG4.GeneratorAction(kernel, "Geant4InteractionVertexSmear/SmearPi+") + gen.Mask = 1 + gen.Offset = (20 * mm, 10 * mm, 10 * mm, 0 * ns) + gen.Sigma = (4 * mm, 1 * mm, 1 * mm, 0 * ns) kernel.generatorAction().adopt(gen) logger.info("# Second particle generator: e-") - gen = DDG4.GeneratorAction(kernel,"Geant4IsotropeGenerator/IsotropE-"); - gen.Mask = 2 + gen = DDG4.GeneratorAction(kernel, "Geant4IsotropeGenerator/IsotropE-") + gen.Mask = 2 gen.Particle = 'e-' - gen.Energy = 25 * GeV + gen.Energy = 25 * GeV gen.Multiplicity = 3 gen.Distribution = 'uniform' kernel.generatorAction().adopt(gen) logger.info(" Install vertex smearing for this interaction") - gen = DDG4.GeneratorAction(kernel,"Geant4InteractionVertexSmear/SmearE-"); - gen.Mask = 2 - gen.Offset = (-20*mm, -10*mm, -10*mm, 0*ns) - gen.Sigma = (12*mm, 8*mm, 8*mm, 0*ns) + gen = DDG4.GeneratorAction(kernel, "Geant4InteractionVertexSmear/SmearE-") + gen.Mask = 2 + gen.Offset = (-20 * mm, -10 * mm, -10 * mm, 0 * ns) + gen.Sigma = (12 * mm, 8 * mm, 8 * mm, 0 * ns) kernel.generatorAction().adopt(gen) #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ logger.info("# Merge all existing interaction records") - gen = DDG4.GeneratorAction(kernel,"Geant4InteractionMerger/InteractionMerger") - gen.OutputLevel = 4 #generator_output_level + gen = DDG4.GeneratorAction(kernel, "Geant4InteractionMerger/InteractionMerger") + gen.OutputLevel = 4 # generator_output_level gen.enableUI() kernel.generatorAction().adopt(gen) logger.info("# Finally generate Geant4 primaries") - gen = DDG4.GeneratorAction(kernel,"Geant4PrimaryHandler/PrimaryHandler") - gen.OutputLevel = 4 #generator_output_level + gen = DDG4.GeneratorAction(kernel, "Geant4PrimaryHandler/PrimaryHandler") + gen.OutputLevel = 4 # generator_output_level gen.enableUI() kernel.generatorAction().adopt(gen) logger.info("# ....and handle the simulation particles.") - part = DDG4.GeneratorAction(kernel,"Geant4ParticleHandler/ParticleHandler") + part = DDG4.GeneratorAction(kernel, "Geant4ParticleHandler/ParticleHandler") kernel.generatorAction().adopt(part) #part.SaveProcesses = ['conv','Decay'] part.SaveProcesses = ['Decay'] - part.MinimalKineticEnergy = 100*MeV - part.OutputLevel = 5 # generator_output_level + part.MinimalKineticEnergy = 100 * MeV + part.OutputLevel = 5 # generator_output_level part.enableUI() - user = DDG4.Action(kernel,"Geant4TCUserParticleHandler/UserParticleHandler") + user = DDG4.Action(kernel, "Geant4TCUserParticleHandler/UserParticleHandler") user.TrackingVolume_Zmax = DDG4.EcalEndcap_zmin user.TrackingVolume_Rmax = DDG4.EcalBarrel_rmin user.enableUI() part.adopt(user) logger.info("# Setup global filters fur use in sensitive detectors") - f1 = DDG4.Filter(kernel,'GeantinoRejectFilter/GeantinoRejector') - f2 = DDG4.Filter(kernel,'ParticleRejectFilter/OpticalPhotonRejector') + f1 = DDG4.Filter(kernel, 'GeantinoRejectFilter/GeantinoRejector') + f2 = DDG4.Filter(kernel, 'ParticleRejectFilter/OpticalPhotonRejector') f2.particle = 'opticalphoton' - f3 = DDG4.Filter(kernel,'ParticleSelectFilter/OpticalPhotonSelector') + f3 = DDG4.Filter(kernel, 'ParticleSelectFilter/OpticalPhotonSelector') f3.particle = 'opticalphoton' - f4 = DDG4.Filter(kernel,'EnergyDepositMinimumCut') - f4.Cut = 10*MeV + f4 = DDG4.Filter(kernel, 'EnergyDepositMinimumCut') + f4.Cut = 10 * MeV f4.enableUI() kernel.registerGlobalFilter(f1) kernel.registerGlobalFilter(f2) @@ -144,28 +148,28 @@ def run(): kernel.registerGlobalFilter(f4) logger.info("# First the tracking detectors") - seq,act = geant4.setupTracker('SiVertexBarrel') + seq, act = geant4.setupTracker('SiVertexBarrel') seq.adopt(f1) - #seq.adopt(f4) + # seq.adopt(f4) act.adopt(f1) - seq,act = geant4.setupTracker('SiVertexEndcap') + seq, act = geant4.setupTracker('SiVertexEndcap') seq.adopt(f1) - #seq.adopt(f4) + # seq.adopt(f4) - seq,act = geant4.setupTracker('SiTrackerBarrel') - seq,act = geant4.setupTracker('SiTrackerEndcap') - seq,act = geant4.setupTracker('SiTrackerForward') + seq, act = geant4.setupTracker('SiTrackerBarrel') + seq, act = geant4.setupTracker('SiTrackerEndcap') + seq, act = geant4.setupTracker('SiTrackerForward') logger.info("# Now setup the calorimeters") - seq,act = geant4.setupCalorimeter('EcalBarrel') - seq,act = geant4.setupCalorimeter('EcalEndcap') - seq,act = geant4.setupCalorimeter('HcalBarrel') - seq,act = geant4.setupCalorimeter('HcalEndcap') - seq,act = geant4.setupCalorimeter('HcalPlug') - seq,act = geant4.setupCalorimeter('MuonBarrel') - seq,act = geant4.setupCalorimeter('MuonEndcap') - seq,act = geant4.setupCalorimeter('LumiCal') - seq,act = geant4.setupCalorimeter('BeamCal') + seq, act = geant4.setupCalorimeter('EcalBarrel') + seq, act = geant4.setupCalorimeter('EcalEndcap') + seq, act = geant4.setupCalorimeter('HcalBarrel') + seq, act = geant4.setupCalorimeter('HcalEndcap') + seq, act = geant4.setupCalorimeter('HcalPlug') + seq, act = geant4.setupCalorimeter('MuonBarrel') + seq, act = geant4.setupCalorimeter('MuonEndcap') + seq, act = geant4.setupCalorimeter('LumiCal') + seq, act = geant4.setupCalorimeter('BeamCal') logger.info("# Now build the physics list:") phys = geant4.setupPhysics('QGSP_BERT') @@ -177,16 +181,17 @@ def run(): # Add global range cut rg = geant4.addPhysics('Geant4DefaultRangeCut/GlobalRangeCut') - rg.RangeCut = 0.7*mm + rg.RangeCut = 0.7 * mm phys.dump() kernel.configure() kernel.initialize() - #DDG4.setPrintLevel(Output.DEBUG) + # DDG4.setPrintLevel(Output.DEBUG) kernel.run() kernel.terminate() + if __name__ == "__main__": run() diff --git a/DDG4/examples/SiDSim_MT.py b/DDG4/examples/SiDSim_MT.py index 8cd3bc6e8bb3486621bf8791483b1848d37bc8f9..0f82dbaeb9db394536e63a07f924f88e644ae0a8 100644 --- a/DDG4/examples/SiDSim_MT.py +++ b/DDG4/examples/SiDSim_MT.py @@ -1,7 +1,10 @@ # # from __future__ import absolute_import, unicode_literals -import os, time, logging, DDG4 +import os +import time +import logging +import DDG4 from DDG4 import OutputLevel as Output from SystemOfUnits import * # @@ -24,126 +27,129 @@ def setupWorker(geant4): kernel = geant4.kernel() logger.info('#PYTHON: +++ Creating Geant4 worker thread ....') logger.info("#PYTHON: Configure Run actions") - run1 = DDG4.RunAction(kernel,'Geant4TestRunAction/RunInit',shared=True) - run1.Property_int = int(12345) - run1.Property_double = -5e15*keV + run1 = DDG4.RunAction(kernel, 'Geant4TestRunAction/RunInit', shared=True) + run1.Property_int = int(12345) + run1.Property_double = -5e15 * keV run1.Property_string = 'Startrun: Hello_2' - logger.info("%s %s %s",run1.Property_string, str(run1.Property_double), str(run1.Property_int)) + logger.info("%s %s %s", run1.Property_string, str(run1.Property_double), str(run1.Property_int)) run1.enableUI() kernel.runAction().adopt(run1) logger.info("#PYTHON: Configure Event actions") - prt = DDG4.EventAction(kernel,'Geant4ParticlePrint/ParticlePrint') + prt = DDG4.EventAction(kernel, 'Geant4ParticlePrint/ParticlePrint') prt.OutputLevel = Output.INFO - prt.OutputType = 3 # Print both: table and tree + prt.OutputType = 3 # Print both: table and tree kernel.eventAction().adopt(prt) logger.info("\n#PYTHON: Configure I/O\n") #evt_lcio = geant4.setupLCIOOutput('LcioOutput','CLICSiD_'+time.strftime('%Y-%m-%d_%H-%M')) #evt_lcio.OutputLevel = Output.ERROR - evt_root = geant4.setupROOTOutput('RootOutput','CLICSiD_'+time.strftime('%Y-%m-%d_%H-%M')) + evt_root = geant4.setupROOTOutput('RootOutput', 'CLICSiD_' + time.strftime('%Y-%m-%d_%H-%M')) generator_output_level = Output.INFO - gen = DDG4.GeneratorAction(kernel,"Geant4GeneratorActionInit/GenerationInit") + gen = DDG4.GeneratorAction(kernel, "Geant4GeneratorActionInit/GenerationInit") kernel.generatorAction().adopt(gen) - #VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV + # VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV logger.info("#PYTHON:\n#PYTHON: Generation of isotrope tracks of a given multiplicity with overlay:\n#PYTHON:") logger.info("#PYTHON: First particle generator: pi+") - gen = DDG4.GeneratorAction(kernel,"Geant4IsotropeGenerator/IsotropPi+"); - gen.Mask = 1 + gen = DDG4.GeneratorAction(kernel, "Geant4IsotropeGenerator/IsotropPi+") + gen.Mask = 1 gen.Particle = 'pi+' - gen.Energy = 20 * GeV + gen.Energy = 20 * GeV gen.Multiplicity = 2 kernel.generatorAction().adopt(gen) logger.info("#PYTHON: Install vertex smearing for this interaction") - gen = DDG4.GeneratorAction(kernel,"Geant4InteractionVertexSmear/SmearPi+"); - gen.Mask = 1 - gen.Offset = (20*mm, 10*mm, 10*mm, 0*ns) - gen.Sigma = (4*mm, 1*mm, 1*mm, 0*ns) + gen = DDG4.GeneratorAction(kernel, "Geant4InteractionVertexSmear/SmearPi+") + gen.Mask = 1 + gen.Offset = (20 * mm, 10 * mm, 10 * mm, 0 * ns) + gen.Sigma = (4 * mm, 1 * mm, 1 * mm, 0 * ns) kernel.generatorAction().adopt(gen) logger.info("#PYTHON: Second particle generator: e-") - gen = DDG4.GeneratorAction(kernel,"Geant4IsotropeGenerator/IsotropE-"); - gen.Mask = 2 + gen = DDG4.GeneratorAction(kernel, "Geant4IsotropeGenerator/IsotropE-") + gen.Mask = 2 gen.Particle = 'e-' - gen.Energy = 15 * GeV + gen.Energy = 15 * GeV gen.Multiplicity = 3 kernel.generatorAction().adopt(gen) logger.info("#PYTHON: Install vertex smearing for this interaction") - gen = DDG4.GeneratorAction(kernel,"Geant4InteractionVertexSmear/SmearE-"); - gen.Mask = 2 - gen.Offset = (-20*mm, -10*mm, -10*mm, 0*ns) - gen.Sigma = (12*mm, 8*mm, 8*mm, 0*ns) + gen = DDG4.GeneratorAction(kernel, "Geant4InteractionVertexSmear/SmearE-") + gen.Mask = 2 + gen.Offset = (-20 * mm, -10 * mm, -10 * mm, 0 * ns) + gen.Sigma = (12 * mm, 8 * mm, 8 * mm, 0 * ns) kernel.generatorAction().adopt(gen) #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ logger.info("#PYTHON: Merge all existing interaction records") - gen = DDG4.GeneratorAction(kernel,"Geant4InteractionMerger/InteractionMerger") - gen.OutputLevel = 4 #generator_output_level + gen = DDG4.GeneratorAction(kernel, "Geant4InteractionMerger/InteractionMerger") + gen.OutputLevel = 4 # generator_output_level gen.enableUI() kernel.generatorAction().adopt(gen) logger.info("#PYTHON: Finally generate Geant4 primaries") - gen = DDG4.GeneratorAction(kernel,"Geant4PrimaryHandler/PrimaryHandler") - gen.OutputLevel = 4 #generator_output_level + gen = DDG4.GeneratorAction(kernel, "Geant4PrimaryHandler/PrimaryHandler") + gen.OutputLevel = 4 # generator_output_level gen.enableUI() kernel.generatorAction().adopt(gen) logger.info("#PYTHON: ....and handle the simulation particles.") - part = DDG4.GeneratorAction(kernel,"Geant4ParticleHandler/ParticleHandler") + part = DDG4.GeneratorAction(kernel, "Geant4ParticleHandler/ParticleHandler") kernel.generatorAction().adopt(part) #part.SaveProcesses = ['conv','Decay'] part.SaveProcesses = ['Decay'] - part.MinimalKineticEnergy = 100*MeV - part.OutputLevel = 5 # generator_output_level + part.MinimalKineticEnergy = 100 * MeV + part.OutputLevel = 5 # generator_output_level part.enableUI() - user = DDG4.Action(kernel,"Geant4TCUserParticleHandler/UserParticleHandler") + user = DDG4.Action(kernel, "Geant4TCUserParticleHandler/UserParticleHandler") user.TrackingVolume_Zmax = DDG4.EcalEndcap_zmin user.TrackingVolume_Rmax = DDG4.EcalBarrel_rmin user.enableUI() part.adopt(user) logger.info('#PYTHON: +++ Geant4 worker thread configured successfully....') return 1 - + + def setupMaster(geant4): kernel = geant4.master() - logger.info('#PYTHON: +++ Setting up master thread for %d workers',int(kernel.NumberOfThreads)) + logger.info('#PYTHON: +++ Setting up master thread for %d workers', int(kernel.NumberOfThreads)) return 1 + def setupSensitives(geant4): logger.info("#PYTHON: Setting up all sensitive detectors") geant4.printDetectors() logger.info("#PYTHON: First the tracking detectors") - seq,act = geant4.setupTracker('SiVertexBarrel') - seq,act = geant4.setupTracker('SiVertexEndcap') - seq,act = geant4.setupTracker('SiTrackerBarrel') - seq,act = geant4.setupTracker('SiTrackerEndcap') - seq,act = geant4.setupTracker('SiTrackerForward') + seq, act = geant4.setupTracker('SiVertexBarrel') + seq, act = geant4.setupTracker('SiVertexEndcap') + seq, act = geant4.setupTracker('SiTrackerBarrel') + seq, act = geant4.setupTracker('SiTrackerEndcap') + seq, act = geant4.setupTracker('SiTrackerForward') logger.info("#PYTHON: Now setup the calorimeters") - seq,act = geant4.setupCalorimeter('EcalBarrel') - seq,act = geant4.setupCalorimeter('EcalEndcap') - seq,act = geant4.setupCalorimeter('HcalBarrel') - seq,act = geant4.setupCalorimeter('HcalEndcap') - seq,act = geant4.setupCalorimeter('HcalPlug') - seq,act = geant4.setupCalorimeter('MuonBarrel') - seq,act = geant4.setupCalorimeter('MuonEndcap') - seq,act = geant4.setupCalorimeter('LumiCal') - seq,act = geant4.setupCalorimeter('BeamCal') + seq, act = geant4.setupCalorimeter('EcalBarrel') + seq, act = geant4.setupCalorimeter('EcalEndcap') + seq, act = geant4.setupCalorimeter('HcalBarrel') + seq, act = geant4.setupCalorimeter('HcalEndcap') + seq, act = geant4.setupCalorimeter('HcalPlug') + seq, act = geant4.setupCalorimeter('MuonBarrel') + seq, act = geant4.setupCalorimeter('MuonEndcap') + seq, act = geant4.setupCalorimeter('LumiCal') + seq, act = geant4.setupCalorimeter('BeamCal') return 1 + def run(): kernel = DDG4.Kernel() description = kernel.detectorDescription() install_dir = os.environ['DD4hepINSTALL'] DDG4.Core.setPrintFormat(str("%-32s %6s %s")) - kernel.loadGeometry(str("file:"+install_dir+"/DDDetectors/compact/SiD.xml")) + kernel.loadGeometry(str("file:" + install_dir + "/DDDetectors/compact/SiD.xml")) DDG4.importConstants(description) kernel.NumberOfThreads = 3 - kernel.RunManagerType = 'G4MTRunManager' - geant4 = DDG4.Geant4(kernel,tracker='Geant4TrackerCombineAction') + kernel.RunManagerType = 'G4MTRunManager' + geant4 = DDG4.Geant4(kernel, tracker='Geant4TrackerCombineAction') logger.info("# Configure UI") geant4.setupCshUI() @@ -152,23 +158,23 @@ def run(): master=setupMaster, master_args=(geant4,)) logger.info("# Configure G4 geometry setup") - seq,act = geant4.addDetectorConstruction("Geant4DetectorGeometryConstruction/ConstructGeo") + seq, act = geant4.addDetectorConstruction("Geant4DetectorGeometryConstruction/ConstructGeo") logger.info("# Configure G4 sensitive detectors: python setup callback") - seq,act = geant4.addDetectorConstruction("Geant4PythonDetectorConstruction/SetupSD", - sensitives=setupSensitives,sensitives_args=(geant4,)) + seq, act = geant4.addDetectorConstruction("Geant4PythonDetectorConstruction/SetupSD", + sensitives=setupSensitives, sensitives_args=(geant4,)) logger.info("# Configure G4 sensitive detectors: atach'em to the sensitive volumes") - seq,act = geant4.addDetectorConstruction("Geant4DetectorSensitivesConstruction/ConstructSD") + seq, act = geant4.addDetectorConstruction("Geant4DetectorSensitivesConstruction/ConstructSD") # allow_threads=True) logger.info("# Configure G4 magnetic field tracking") geant4.setupTrackingFieldMT() logger.info("# Setup random generator") - rndm = DDG4.Action(kernel,'Geant4Random/Random') + rndm = DDG4.Action(kernel, 'Geant4Random/Random') rndm.Seed = 987654321 rndm.initialize() - ##rndm.showStatus() + # rndm.showStatus() logger.info("# Now build the physics list:") phys = geant4.setupPhysics('QGSP_BERT') @@ -176,5 +182,6 @@ def run(): geant4.run() + if __name__ == "__main__": run() diff --git a/DDG4/examples/SiD_Markus.py b/DDG4/examples/SiD_Markus.py index 4086943c0eddeb67077f3d1d44902caba3790248..ab4c432462566820dac5923f8c636037a1352812 100644 --- a/DDG4/examples/SiD_Markus.py +++ b/DDG4/examples/SiD_Markus.py @@ -1,7 +1,10 @@ # # from __future__ import absolute_import, unicode_literals -import os, time, logging, DDG4 +import os +import time +import logging +import DDG4 from DDG4 import OutputLevel as Output from SystemOfUnits import * # @@ -19,48 +22,49 @@ logger.setLevel(logging.INFO) """ + def setupWorker(): k = DDG4.Kernel() kernel = k.worker() logger.info('PYTHON: +++ Creating Geant4 worker thread ....') - + # Configure Run actions - run1 = DDG4.RunAction(kernel,'Geant4TestRunAction/RunInit') - run1.Property_int = 12345 - run1.Property_double = -5e15*keV + run1 = DDG4.RunAction(kernel, 'Geant4TestRunAction/RunInit') + run1.Property_int = 12345 + run1.Property_double = -5e15 * keV run1.Property_string = 'Startrun: Hello_2' - logger.info("%s %f %d",run1.Property_string, run1.Property_double, run1.Property_int) + logger.info("%s %f %d", run1.Property_string, run1.Property_double, run1.Property_int) run1.enableUI() kernel.registerGlobalAction(run1) kernel.runAction().adopt(run1) # Configure Event actions - prt = DDG4.EventAction(kernel,'Geant4ParticlePrint/ParticlePrint') + prt = DDG4.EventAction(kernel, 'Geant4ParticlePrint/ParticlePrint') prt.OutputLevel = Output.DEBUG - prt.OutputType = 3 # Print both: table and tree + prt.OutputType = 3 # Print both: table and tree kernel.eventAction().adopt(prt) # Configure Event actions - prt = DDG4.EventAction(kernel,'Geant4SurfaceTest/SurfaceTest') + prt = DDG4.EventAction(kernel, 'Geant4SurfaceTest/SurfaceTest') prt.OutputLevel = Output.INFO kernel.eventAction().adopt(prt) # Configure I/O - evt_lcio = geant4.setupLCIOOutput('LcioOutput','CLICSiD_'+time.strftime('%Y-%m-%d_%H-%M')) + evt_lcio = geant4.setupLCIOOutput('LcioOutput', 'CLICSiD_' + time.strftime('%Y-%m-%d_%H-%M')) evt_lcio.OutputLevel = Output.DEBUG #evt_root = geant4.setupROOTOutput('RootOutput','CLICSiD_'+time.strftime('%Y-%m-%d_%H-%M')) #generator_output_level = Output.INFO - - gen = DDG4.GeneratorAction(kernel,"Geant4GeneratorActionInit/GenerationInit") + + gen = DDG4.GeneratorAction(kernel, "Geant4GeneratorActionInit/GenerationInit") kernel.generatorAction().adopt(gen) - #VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV + # VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV """ Generation of isotrope tracks of a given multiplicity with overlay: """ # First particle generator: pi+ - gen = DDG4.GeneratorAction(kernel,"Geant4IsotropeGenerator/IsotropPi+"); + gen = DDG4.GeneratorAction(kernel, "Geant4IsotropeGenerator/IsotropPi+") gen.Particle = 'pi+' gen.Energy = 100 * GeV gen.Multiplicity = 2 @@ -73,10 +77,10 @@ def setupWorker(): kernel.generatorAction().adopt(gen) # Install vertex smearing for this interaction - gen = DDG4.GeneratorAction(kernel,"Geant4InteractionVertexSmear/SmearPi+"); + gen = DDG4.GeneratorAction(kernel, "Geant4InteractionVertexSmear/SmearPi+") gen.Mask = 1 - gen.Offset = (20*mm, 10*mm, 10*mm, 0*ns) - gen.Sigma = (4*mm, 1*mm, 1*mm, 0*ns) + gen.Offset = (20 * mm, 10 * mm, 10 * mm, 0 * ns) + gen.Sigma = (4 * mm, 1 * mm, 1 * mm, 0 * ns) kernel.generatorAction().adopt(gen) """ # Second particle generator: e- @@ -96,69 +100,74 @@ def setupWorker(): #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ """ # Merge all existing interaction records - gen = DDG4.GeneratorAction(kernel,"Geant4InteractionMerger/InteractionMerger") - gen.OutputLevel = 4 #generator_output_level + gen = DDG4.GeneratorAction(kernel, "Geant4InteractionMerger/InteractionMerger") + gen.OutputLevel = 4 # generator_output_level gen.enableUI() kernel.generatorAction().adopt(gen) # Finally generate Geant4 primaries - gen = DDG4.GeneratorAction(kernel,"Geant4PrimaryHandler/PrimaryHandler") - gen.OutputLevel = Output.DEBUG #generator_output_level + gen = DDG4.GeneratorAction(kernel, "Geant4PrimaryHandler/PrimaryHandler") + gen.OutputLevel = Output.DEBUG # generator_output_level gen.enableUI() kernel.generatorAction().adopt(gen) # And handle the simulation particles. - part = DDG4.GeneratorAction(kernel,"Geant4ParticleHandler/ParticleHandler") + part = DDG4.GeneratorAction(kernel, "Geant4ParticleHandler/ParticleHandler") kernel.generatorAction().adopt(part) #part.SaveProcesses = ['conv','Decay'] part.SaveProcesses = ['Decay'] - part.MinimalKineticEnergy = 100*MeV - part.OutputLevel = Output.DEBUG # generator_output_level + part.MinimalKineticEnergy = 100 * MeV + part.OutputLevel = Output.DEBUG # generator_output_level part.enableUI() - user = DDG4.Action(kernel,"Geant4TCUserParticleHandler/UserParticleHandler") + user = DDG4.Action(kernel, "Geant4TCUserParticleHandler/UserParticleHandler") user.TrackingVolume_Zmax = DDG4.EcalEndcap_zmin user.TrackingVolume_Rmax = DDG4.EcalBarrel_rmin user.enableUI() part.adopt(user) logger.info('PYTHON: +++ Geant4 worker thread configured successfully....') return 1 - + + def setupMaster(): logger.info('PYTHON: +++ Setting up master thread.....') return 1 + def setupSensitives(): global geant4 # First the tracking detectors - seq,act = geant4.setupTracker('SiVertexBarrel') + seq, act = geant4.setupTracker('SiVertexBarrel') act.OutputLevel = Output.ERROR act.CollectSingleDeposits = False - seq,act = geant4.setupTracker('SiVertexEndcap') + seq, act = geant4.setupTracker('SiVertexEndcap') act.OutputLevel = Output.ERROR act.CollectSingleDeposits = False logger.info('PYTHON: +++ Setting up Geant4 sensitive detectors for worker thread.....') return 1 + def dummy_sd(): logger.info('PYTHON: +++ Setting up DUMMY Geant4 sensitive detectors for worker thread.....') return 1 - + + def dummy_geom(): logger.info('PYTHON: +++ Setting up DUMMY Geant4 geometry for worker thread.....') return 1 + def run(): global geant4 kernel = DDG4.Kernel() description = kernel.detectorDescription() install_dir = os.environ['DD4hepINSTALL'] - kernel.loadGeometry(str("file:"+install_dir+"/DDDetectors/compact/SiD_Markus.xml")) + kernel.loadGeometry(str("file:" + install_dir + "/DDDetectors/compact/SiD_Markus.xml")) DDG4.importConstants(description) DDG4.Core.setPrintLevel(Output.DEBUG) DDG4.Core.setPrintFormat(str("%-32s %6s %s")) kernel.NumberOfThreads = 1 - geant4 = DDG4.Geant4(kernel,tracker='Geant4TrackerWeightedAction') + geant4 = DDG4.Geant4(kernel, tracker='Geant4TrackerWeightedAction') geant4.printDetectors() # Configure UI geant4.setupCshUI() @@ -167,29 +176,29 @@ def run(): geant4.addUserInitialization(worker=setupWorker, master=setupMaster) # Configure G4 geometry setup - seq,act = geant4.addDetectorConstruction("Geant4DetectorGeometryConstruction/ConstructGeo") + seq, act = geant4.addDetectorConstruction("Geant4DetectorGeometryConstruction/ConstructGeo") # Configure G4 magnetic field tracking self.setupTrackingFieldMT() - seq,act = geant4.addDetectorConstruction("Geant4PythonDetectorConstruction/DummyDet", - geometry=dummy_geom, - sensitives=dummy_sd) + seq, act = geant4.addDetectorConstruction("Geant4PythonDetectorConstruction/DummyDet", + geometry=dummy_geom, + sensitives=dummy_sd) # Configure G4 sensitive detectors - seq,act = geant4.addDetectorConstruction("Geant4PythonDetectorConstruction/SetupSD", - sensitives=setupSensitives) + seq, act = geant4.addDetectorConstruction("Geant4PythonDetectorConstruction/SetupSD", + sensitives=setupSensitives) # Configure G4 sensitive detectors - seq,act = geant4.addDetectorConstruction("Geant4DetectorSensitivesConstruction/ConstructSD", - allow_threads=True) + seq, act = geant4.addDetectorConstruction("Geant4DetectorSensitivesConstruction/ConstructSD", + allow_threads=True) # Setup random generator - rndm = DDG4.Action(kernel,'Geant4Random/Random') + rndm = DDG4.Action(kernel, 'Geant4Random/Random') rndm.Seed = 987654321 rndm.initialize() # Setup global filters fur use in sensntive detectors - f1 = DDG4.Filter(kernel,'GeantinoRejectFilter/GeantinoRejector') + f1 = DDG4.Filter(kernel, 'GeantinoRejectFilter/GeantinoRejector') kernel.registerGlobalFilter(f1) #seq,act = geant4.setupTracker('SiTrackerBarrel') @@ -208,23 +217,24 @@ def run(): # Now build the physics list: seq = geant4.setupPhysics('QGSP_BERT') - phys = DDG4.PhysicsList(geant4.master(),'Geant4PhysicsList/MyPhysics') - part = DDG4.Action(geant4.master(),'Geant4ExtraParticles/extraparts') + phys = DDG4.PhysicsList(geant4.master(), 'Geant4PhysicsList/MyPhysics') + part = DDG4.Action(geant4.master(), 'Geant4ExtraParticles/extraparts') part.pdgfile = 'checkout/DDG4/examples/particle.tbl' phys.adoptPhysicsConstructor(part.get()) seq.add(phys) geant4.run() - #kernel.configure() - #kernel.initialize() + # kernel.configure() + # kernel.initialize() - #DDG4.setPrintLevel(Output.DEBUG) - #kernel.run() - #kernel.terminate() + # DDG4.setPrintLevel(Output.DEBUG) + # kernel.run() + # kernel.terminate() return 1 + if __name__ == "__main__": import sys - logger.info('Arguments: %s',str(sys.argv)) + logger.info('Arguments: %s', str(sys.argv)) run() diff --git a/DDG4/examples/readHEPMC.py b/DDG4/examples/readHEPMC.py index 4e70ce2404dc776e3ff937319bbaef4177ffcd30..9e5c02f263e57dffa7610ee1752572bc3ba0cce5 100644 --- a/DDG4/examples/readHEPMC.py +++ b/DDG4/examples/readHEPMC.py @@ -13,42 +13,44 @@ logging.basicConfig(format='%(levelname)s: %(message)s') logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) + def run(input_file): import DDG4 from DDG4 import OutputLevel as Output kernel = DDG4.Kernel() description = kernel.detectorDescription() - gen = DDG4.GeneratorAction(kernel,"Geant4InputAction/Input") + gen = DDG4.GeneratorAction(kernel, "Geant4InputAction/Input") kernel.generatorAction().adopt(gen) - gen.Input = "Geant4EventReaderHepMC|"+input_file + gen.Input = "Geant4EventReaderHepMC|" + input_file gen.OutputLevel = Output.DEBUG gen.HaveAbort = False prim_vtx = DDG4.std_vector(str('dd4hep::sim::Geant4Vertex*'))() parts = gen.new_particles() ret = 1 - evtid=0 + evtid = 0 while ret: try: - ret = gen.readParticles(evtid,prim_vtx,parts) + ret = gen.readParticles(evtid, prim_vtx, parts) evtid = evtid + 1 except Exception as X: - logger.error( '\nException: readParticles: %s',str(X)) + logger.error('\nException: readParticles: %s', str(X)) ret = None if ret: for v in prim_vtx: - logger.info( 'Mask:%04X (X:%8.2g,Y:%8.2g,Z:%8.2g) time:%8.2g Outgoing:%4d particles', - v.mask,v.x,v.y,v.z,v.time,len(v.out)) + logger.info('Mask:%04X (X:%8.2g,Y:%8.2g,Z:%8.2g) time:%8.2g Outgoing:%4d particles', + v.mask, v.x, v.y, v.z, v.time, len(v.out)) for p in parts: - logger.info( 'Mask:%04X ID:%5d PDG-id:%8d Charge:%1d Mass:%8.3g Momentum:(%8.2g,%8.2g,%8.2g) '\ - 'Vertex:(%8.2g,%8.2g,%8.2g) NDau:%2d Status:%08X', - p.mask,p.id,p.pdgID,int(p.charge3()),p.mass,p.psx,p.psy,p.psz,\ - p.vsx,p.vsy,p.vsz,len(p.daughters),p.status) + logger.info('Mask:%04X ID:%5d PDG-id:%8d Charge:%1d Mass:%8.3g Momentum:(%8.2g,%8.2g,%8.2g) ' + 'Vertex:(%8.2g,%8.2g,%8.2g) NDau:%2d Status:%08X', + p.mask, p.id, p.pdgID, int(p.charge3()), p.mass, p.psx, p.psy, p.psz, + p.vsx, p.vsy, p.vsz, len(p.daughters), p.status) parts.clear() else: - logger.info( '*** End of recordset or read failure.....') - logger.info( 132*'*') + logger.info('*** End of recordset or read failure.....') + logger.info(132 * '*') return 0 - + + if __name__ == "__main__": import sys input_file = None @@ -56,5 +58,5 @@ if __name__ == "__main__": input_file = sys.argv[1] sys.exit(run(input_file)) else: - logger.error( 'No input file given. Try again....') + logger.error('No input file given. Try again....') sys.exit(2) # ENOENT diff --git a/DDG4/python/DDG4.py b/DDG4/python/DDG4.py index 4a6a45122eb943d96472d1985761a68a376fb172..5835e718d1365e3ed66c7239951dfb89c2f3ebac 100644 --- a/DDG4/python/DDG4.py +++ b/DDG4/python/DDG4.py @@ -1,5 +1,5 @@ #========================================================================== -# AIDA Detector description implementation +# AIDA Detector description implementation #-------------------------------------------------------------------------- # Copyright (C) Organisation europeenne pour la Recherche nucleaire (CERN) # All rights reserved. @@ -17,76 +17,85 @@ logging.basicConfig(format='%(levelname)s: %(message)s') logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) + def loadDDG4(): - ## import ROOT ## done in import * above + # import ROOT ## done in import * above from ROOT import gSystem - ## Try to load libglapi to avoid issues with TLS Static - ## Turn off all errors from ROOT about the library missing + # Try to load libglapi to avoid issues with TLS Static + # Turn off all errors from ROOT about the library missing orgLevel = ROOT.gErrorIgnoreLevel - ROOT.gErrorIgnoreLevel=6000 + ROOT.gErrorIgnoreLevel = 6000 gSystem.Load("libglapi") - ROOT.gErrorIgnoreLevel=orgLevel + ROOT.gErrorIgnoreLevel = orgLevel import platform import os - if platform.system()=="Darwin": + if platform.system() == "Darwin": gSystem.SetDynamicPath(os.environ['DD4HEP_LIBRARY_PATH']) os.environ['DYLD_LIBRARY_PATH'] = os.pathsep.join([os.environ['DD4HEP_LIBRARY_PATH'], os.environ.get('DYLD_LIBRARY_PATH', '')]).strip(os.pathsep) result = gSystem.Load("libDDG4Plugins") if result < 0: - raise Exception('DDG4.py: Failed to load the DDG4 library libDDG4Plugins: '+gSystem.GetErrorStr()) + raise Exception('DDG4.py: Failed to load the DDG4 library libDDG4Plugins: ' + gSystem.GetErrorStr()) from ROOT import dd4hep as module return module # We are nearly there .... current = __import__(__name__) -def _import_class(ns,nam): - scope = getattr(current,ns) - setattr(current,nam,getattr(scope,nam)) + + +def _import_class(ns, nam): + scope = getattr(current, ns) + setattr(current, nam, getattr(scope, nam)) + #--------------------------------------------------------------------------- # try: - dd4hep = loadDDG4() + dd4hep = loadDDG4() except Exception as X: - logger.error('+--%-100s--+',100*'-') - logger.error('| %-100s |','Failed to load DDG4 library:') - logger.error('| %-100s |',str(X)) - logger.error('+--%-100s--+',100*'-') + logger.error('+--%-100s--+', 100 * '-') + logger.error('| %-100s |', 'Failed to load DDG4 library:') + logger.error('| %-100s |', str(X)) + logger.error('+--%-100s--+', 100 * '-') exit(1) from ROOT import CLHEP as CLHEP -Core = dd4hep -Sim = dd4hep.sim +Core = dd4hep +Sim = dd4hep.sim Simulation = dd4hep.sim -Kernel = Sim.KernelHandle -Interface = Sim.Geant4ActionCreation -Detector = Core.Detector +Kernel = Sim.KernelHandle +Interface = Sim.Geant4ActionCreation +Detector = Core.Detector # -from dd4hep_base import std, std_vector, std_list, std_map, std_pair -import g4units as G4Units +from dd4hep_base import std, std_vector, std_list, std_map, std_pair +import g4units as G4Units # #--------------------------------------------------------------------------- -def _constant(self,name): + + +def _constant(self, name): return self.constantAsString(name) + Detector.globalVal = _constant #--------------------------------------------------------------------------- """ Import the Detector constants into the DDG4 namespace """ -def importConstants(description,namespace=None,debug=False): + + +def importConstants(description, namespace=None, debug=False): scope = current ns = current - if namespace is not None and not hasattr(current,namespace): + if namespace is not None and not hasattr(current, namespace): import imp - m = imp.new_module('DDG4.'+namespace) - setattr(current,namespace,m) + m = imp.new_module('DDG4.' + namespace) + setattr(current, namespace, m) ns = m evaluator = dd4hep.g4Evaluator() cnt = 0 @@ -97,63 +106,80 @@ def importConstants(description,namespace=None,debug=False): if c.second.dataType == 'string': strings[c.first] = c.second.GetTitle() else: - todo[c.first] = c.second.GetTitle().replace('(int)','') - while len(todo) and cnt<100: + todo[c.first] = c.second.GetTitle().replace('(int)', '') + while len(todo) and cnt < 100: cnt = cnt + 1 if cnt == 100: - logger.error('%s %d out of %d %s "%s": [%s]\n+++ %s',\ - '+++ FAILED to import', - len(todo),len(todo)+num, - 'global values into namespace', - ns.__name__,'Try to continue anyway',100*'=') - for k,v in todo.items(): - if not hasattr(ns,k): - logger.error('+++ FAILED to import: "'+k+'" = "'+str(v)+'"') - logger.info('+++ %s',100*'=') - - for k,v in list(todo.items()): - if not hasattr(ns,k): + logger.error('%s %d out of %d %s "%s": [%s]\n+++ %s', + '+++ FAILED to import', + len(todo), len(todo) + num, + 'global values into namespace', + ns.__name__, 'Try to continue anyway', 100 * '=') + for k, v in todo.items(): + if not hasattr(ns, k): + logger.error('+++ FAILED to import: "' + k + '" = "' + str(v) + '"') + logger.info('+++ %s', 100 * '=') + + for k, v in list(todo.items()): + if not hasattr(ns, k): val = evaluator.evaluate(v) status = evaluator.status() if status == 0: - evaluator.setVariable(k,val) - setattr(ns,k,val) - if debug: logger.info('Imported global value: "'+k+'" = "'+str(val)+'" into namespace'+ns.__name__) + evaluator.setVariable(k, val) + setattr(ns, k, val) + if debug: + logger.info('Imported global value: "' + k + '" = "' + str(val) + '" into namespace' + ns.__name__) del todo[k] num = num + 1 - if cnt<100: - logger.info('+++ Imported %d global values to namespace:%s',num,ns.__name__,) + if cnt < 100: + logger.info('+++ Imported %d global values to namespace:%s', num, ns.__name__,) + +#--------------------------------------------------------------------------- + -#--------------------------------------------------------------------------- -def _registerGlobalAction(self,action): +def _registerGlobalAction(self, action): self.get().registerGlobalAction(Interface.toAction(action)) -def _registerGlobalFilter(self,filter): + + +def _registerGlobalFilter(self, filter): self.get().registerGlobalFilter(Interface.toAction(filter)) #--------------------------------------------------------------------------- + + def _getKernelProperty(self, name): - ret = Interface.getPropertyKernel(self.get(),name) + ret = Interface.getPropertyKernel(self.get(), name) if ret.status > 0: return ret.data - elif hasattr(self.get(),name): - return getattr(self.get(),name) - elif hasattr(self,name): - return getattr(self,name) - msg = 'Geant4Kernel::GetProperty [Unhandled]: Cannot access Kernel.'+name + elif hasattr(self.get(), name): + return getattr(self.get(), name) + elif hasattr(self, name): + return getattr(self, name) + msg = 'Geant4Kernel::GetProperty [Unhandled]: Cannot access Kernel.' + name raise KeyError(msg) #--------------------------------------------------------------------------- + + def _setKernelProperty(self, name, value): - if Interface.setPropertyKernel(self.get(),name,str(value)): + if Interface.setPropertyKernel(self.get(), name, str(value)): return - msg = 'Geant4Kernel::SetProperty [Unhandled]: Cannot set Kernel.'+name+' = '+str(value) + msg = 'Geant4Kernel::SetProperty [Unhandled]: Cannot set Kernel.' + name + ' = ' + str(value) raise KeyError(msg) #--------------------------------------------------------------------------- -def _kernel_phase(self,name): return self.addSimplePhase(str(name),False) + + +def _kernel_phase(self, name): return self.addSimplePhase(str(name), False) #--------------------------------------------------------------------------- -def _kernel_worker(self): return Kernel(self.get().createWorker()) + + +def _kernel_worker(self): return Kernel(self.get().createWorker()) #--------------------------------------------------------------------------- -def _kernel_terminate(self): return self.get().terminate() + + +def _kernel_terminate(self): return self.get().terminate() + + #--------------------------------------------------------------------------- Kernel.phase = _kernel_phase Kernel.registerGlobalAction = _registerGlobalAction @@ -165,62 +191,94 @@ Kernel.terminate = _kernel_terminate #--------------------------------------------------------------------------- ActionHandle = Sim.ActionHandle #--------------------------------------------------------------------------- -def SensitiveAction(kernel,nam,det,shared=False): - return Interface.createSensitive(kernel,str(nam),str(det),shared) + + +def SensitiveAction(kernel, nam, det, shared=False): + return Interface.createSensitive(kernel, str(nam), str(det), shared) #--------------------------------------------------------------------------- -def Action(kernel,nam,shared=False): - return Interface.createAction(kernel,str(nam), shared) + + +def Action(kernel, nam, shared=False): + return Interface.createAction(kernel, str(nam), shared) #--------------------------------------------------------------------------- -def Filter(kernel,nam,shared=False): - return Interface.createFilter(kernel,str(nam), shared) + + +def Filter(kernel, nam, shared=False): + return Interface.createFilter(kernel, str(nam), shared) #--------------------------------------------------------------------------- -def PhaseAction(kernel,nam,shared=False): - return Interface.createPhaseAction(kernel,str(nam), shared) + + +def PhaseAction(kernel, nam, shared=False): + return Interface.createPhaseAction(kernel, str(nam), shared) #--------------------------------------------------------------------------- -def RunAction(kernel,nam,shared=False): - return Interface.createRunAction(kernel,str(nam), shared) + + +def RunAction(kernel, nam, shared=False): + return Interface.createRunAction(kernel, str(nam), shared) #--------------------------------------------------------------------------- -def EventAction(kernel,nam,shared=False): - return Interface.createEventAction(kernel,str(nam), shared) + + +def EventAction(kernel, nam, shared=False): + return Interface.createEventAction(kernel, str(nam), shared) #--------------------------------------------------------------------------- -def GeneratorAction(kernel,nam,shared=False): - return Interface.createGeneratorAction(kernel,str(nam), shared) + + +def GeneratorAction(kernel, nam, shared=False): + return Interface.createGeneratorAction(kernel, str(nam), shared) #--------------------------------------------------------------------------- -def TrackingAction(kernel,nam,shared=False): - return Interface.createTrackingAction(kernel,str(nam), shared) + + +def TrackingAction(kernel, nam, shared=False): + return Interface.createTrackingAction(kernel, str(nam), shared) #--------------------------------------------------------------------------- -def SteppingAction(kernel,nam,shared=False): - return Interface.createSteppingAction(kernel,str(nam), shared) + + +def SteppingAction(kernel, nam, shared=False): + return Interface.createSteppingAction(kernel, str(nam), shared) #--------------------------------------------------------------------------- -def StackingAction(kernel,nam,shared=False): - return Interface.createStackingAction(kernel,str(nam), shared) + + +def StackingAction(kernel, nam, shared=False): + return Interface.createStackingAction(kernel, str(nam), shared) #--------------------------------------------------------------------------- -def DetectorConstruction(kernel,nam): - return Interface.createDetectorConstruction(kernel,str(nam)) + + +def DetectorConstruction(kernel, nam): + return Interface.createDetectorConstruction(kernel, str(nam)) #--------------------------------------------------------------------------- -def PhysicsList(kernel,nam): - return Interface.createPhysicsList(kernel,str(nam)) + + +def PhysicsList(kernel, nam): + return Interface.createPhysicsList(kernel, str(nam)) #--------------------------------------------------------------------------- + + def UserInitialization(kernel, nam): - return Interface.createUserInitialization(kernel,str(nam)) + return Interface.createUserInitialization(kernel, str(nam)) #--------------------------------------------------------------------------- + + def SensitiveSequence(kernel, nam): - return Interface.createSensDetSequence(kernel,str(nam)) + return Interface.createSensDetSequence(kernel, str(nam)) #--------------------------------------------------------------------------- + + def _setup(obj): - def _adopt(self,action): self.__adopt(action.get()) - _import_class('Sim',obj) - o = getattr(current,obj) - setattr(o,'__adopt',getattr(o,'adopt')) - setattr(o,'adopt',_adopt) - setattr(o,'add',_adopt) + def _adopt(self, action): self.__adopt(action.get()) + _import_class('Sim', obj) + o = getattr(current, obj) + setattr(o, '__adopt', getattr(o, 'adopt')) + setattr(o, 'adopt', _adopt) + setattr(o, 'add', _adopt) + def _setup_callback(obj): - def _adopt(self,action): self.__adopt(action.get(),action.callback()) - _import_class('Sim',obj) - o = getattr(current,obj) - setattr(o,'__adopt',getattr(o,'add')) - setattr(o,'add',_adopt) + def _adopt(self, action): self.__adopt(action.get(), action.callback()) + _import_class('Sim', obj) + o = getattr(current, obj) + setattr(o, '__adopt', getattr(o, 'add')) + setattr(o, 'add', _adopt) + #--------------------------------------------------------------------------- _setup_callback('Geant4ActionPhase') @@ -236,56 +294,61 @@ _setup('Geant4DetectorConstructionSequence') _setup('Geant4UserInitializationSequence') _setup('Geant4Sensitive') _setup('Geant4ParticleHandler') -_import_class('Sim','Geant4Vertex') -_import_class('Sim','Geant4Particle') -_import_class('Sim','Geant4VertexVector') -_import_class('Sim','Geant4ParticleVector') -_import_class('Sim','Geant4Action') -_import_class('Sim','Geant4Filter') -_import_class('Sim','Geant4RunAction') -_import_class('Sim','Geant4TrackingAction') -_import_class('Sim','Geant4StackingAction') -_import_class('Sim','Geant4PhaseAction') -_import_class('Sim','Geant4UserParticleHandler') -_import_class('Sim','Geant4UserInitialization') -_import_class('Sim','Geant4DetectorConstruction') -_import_class('Sim','Geant4GeneratorWrapper') -_import_class('Sim','Geant4Random') -_import_class('CLHEP','HepRandom') -_import_class('CLHEP','HepRandomEngine') +_import_class('Sim', 'Geant4Vertex') +_import_class('Sim', 'Geant4Particle') +_import_class('Sim', 'Geant4VertexVector') +_import_class('Sim', 'Geant4ParticleVector') +_import_class('Sim', 'Geant4Action') +_import_class('Sim', 'Geant4Filter') +_import_class('Sim', 'Geant4RunAction') +_import_class('Sim', 'Geant4TrackingAction') +_import_class('Sim', 'Geant4StackingAction') +_import_class('Sim', 'Geant4PhaseAction') +_import_class('Sim', 'Geant4UserParticleHandler') +_import_class('Sim', 'Geant4UserInitialization') +_import_class('Sim', 'Geant4DetectorConstruction') +_import_class('Sim', 'Geant4GeneratorWrapper') +_import_class('Sim', 'Geant4Random') +_import_class('CLHEP', 'HepRandom') +_import_class('CLHEP', 'HepRandomEngine') #--------------------------------------------------------------------------- + + def _get(self, name): import traceback a = Interface.toAction(self) - ret = Interface.getProperty(a,name) + ret = Interface.getProperty(a, name) if ret.status > 0: return ret.data - elif hasattr(self.action,name): - return getattr(self.action,name) - elif hasattr(a,name): - return getattr(a,name) - #elif hasattr(self,name): + elif hasattr(self.action, name): + return getattr(self.action, name) + elif hasattr(a, name): + return getattr(a, name) + # elif hasattr(self,name): # return getattr(self,name) - #traceback.print_stack() - msg = 'Geant4Action::GetProperty [Unhandled]: Cannot access property '+a.name()+'.'+name + # traceback.print_stack() + msg = 'Geant4Action::GetProperty [Unhandled]: Cannot access property ' + a.name() + '.' + name raise KeyError(msg) + def _set(self, name, value): a = Interface.toAction(self) - if isinstance(value,list): + if isinstance(value, list): value = [str(x) for x in value] - if Interface.setProperty(a,name,str(value)): + if Interface.setProperty(a, name, str(value)): return - msg = 'Geant4Action::SetProperty [Unhandled]: Cannot set '+a.name()+'.'+name+' = '+str(value) + msg = 'Geant4Action::SetProperty [Unhandled]: Cannot set ' + a.name() + '.' + name + ' = ' + str(value) raise KeyError(msg) + def _props(obj): - _import_class('Sim',obj) - cl = getattr(current,obj) + _import_class('Sim', obj) + cl = getattr(current, obj) cl.__getattr__ = _get cl.__setattr__ = _set + _props('FilterHandle') _props('ActionHandle') _props('PhaseActionHandle') @@ -328,6 +391,8 @@ _props('Geant4PhysicsListActionSequence') \version 1.0 """ + + class Geant4: def __init__(self, kernel=None, calo='Geant4CalorimeterAction', @@ -343,12 +408,12 @@ class Geant4: self.sensitive_types['calorimeter'] = calo self.sensitive_types['escape_counter'] = 'Geant4EscapeCounter' - """ Access the worker kernel object. \author M.Frank """ + def kernel(self): return self._kernel.worker() @@ -357,6 +422,7 @@ class Geant4: \author M.Frank """ + def master(self): return self._kernel @@ -365,13 +431,18 @@ class Geant4: \author M.Frank """ - def setupUI(self,typ='csh',vis=False,ui=True,macro=None): + + def setupUI(self, typ='csh', vis=False, ui=True, macro=None): # Configure UI - ui_action = Action(self.master(),"Geant4UIManager/UI") - if vis: ui_action.HaveVIS = True - else: ui_action.HaveVIS = False - if ui: ui_action.HaveUI = True - else: ui_action.HaveUI = False + ui_action = Action(self.master(), "Geant4UIManager/UI") + if vis: + ui_action.HaveVIS = True + else: + ui_action.HaveVIS = False + if ui: + ui_action.HaveUI = True + else: + ui_action.HaveUI = False ui_action.SessionType = typ if macro: ui_action.SetupUI = macro @@ -383,18 +454,20 @@ class Geant4: \author M.Frank """ - def setupCshUI(self,typ='csh',vis=False,ui=True,macro=None): - return self.setupUI(typ='csh',vis=vis,ui=ui,macro=macro) + + def setupCshUI(self, typ='csh', vis=False, ui=True, macro=None): + return self.setupUI(typ='csh', vis=vis, ui=ui, macro=macro) """ Configure Geant4 user initialization for optionasl multi-threading mode \author M.Frank """ + def addUserInitialization(self, worker, worker_args=None, master=None, master_args=None): import sys init_seq = self.master().userInitialization(True) - init_action = UserInitialization(self.master(),'Geant4PythonInitialization/PyG4Init') + init_action = UserInitialization(self.master(), 'Geant4PythonInitialization/PyG4Init') # if worker: init_action.setWorkerSetup(worker, worker_args) @@ -402,55 +475,58 @@ class Geant4: raise RuntimeError('Invalid argument for Geant4 worker initialization') # if master: - init_action.setMasterSetup(master,master_args) + init_action.setMasterSetup(master, master_args) # init_seq.adopt(init_action) - return init_seq,init_action + return init_seq, init_action def detectorConstruction(self): seq = self.master().detectorConstruction(True) return seq - + """ Configure Geant4 user initialization for optionasl multi-threading mode \author M.Frank """ - def addDetectorConstruction(self, name_type, - field=None, field_args=None, - geometry=None, geometry_args=None, + + def addDetectorConstruction(self, name_type, + field=None, field_args=None, + geometry=None, geometry_args=None, sensitives=None, sensitives_args=None, allow_threads=False): init_seq = self.master().detectorConstruction(True) - init_action = DetectorConstruction(self.master(),name_type) + init_action = DetectorConstruction(self.master(), name_type) # if geometry: - init_action.setConstructGeo(geometry,geometry_args) + init_action.setConstructGeo(geometry, geometry_args) # if field: - init_action.setConstructField(field,field_args) + init_action.setConstructField(field, field_args) # if sensitives: - init_action.setConstructSensitives(sensitives,sensitives_args) + init_action.setConstructSensitives(sensitives, sensitives_args) # init_seq.adopt(init_action) if allow_threads: - last_action = DetectorConstruction(self.master(),"Geant4PythonDetectorConstructionLast/LastDetectorAction") + last_action = DetectorConstruction(self.master(), "Geant4PythonDetectorConstructionLast/LastDetectorAction") init_seq.adopt(last_action) - return init_seq,init_action + return init_seq, init_action """ Add a new phase action to an arbitrary step. \author M.Frank """ - def addPhaseAction(self,phase_name,factory_specification,ui=True,instance=None): + + def addPhaseAction(self, phase_name, factory_specification, ui=True, instance=None): if instance is None: instance = self.kernel() - action = PhaseAction(instance,factory_specification) + action = PhaseAction(instance, factory_specification) instance.phase(phase_name).add(action) - if ui: action.enableUI() + if ui: + action.enableUI() return action """ @@ -461,8 +537,9 @@ class Geant4: \author M.Frank """ + def addConfig(self, factory_specification): - return self.addPhaseAction('configure',factory_specification,instance=self.master()) + return self.addPhaseAction('configure', factory_specification, instance=self.master()) """ Add a new phase action to the 'initialize' step. @@ -472,8 +549,9 @@ class Geant4: \author M.Frank """ + def addInit(self, factory_specification): - return self.addPhaseAction('initialize',factory_specification) + return self.addPhaseAction('initialize', factory_specification) """ Add a new phase action to the 'start' step. @@ -483,8 +561,9 @@ class Geant4: \author M.Frank """ + def addStart(self, factory_specification): - return self.addPhaseAction('start',factory_specification) + return self.addPhaseAction('start', factory_specification) """ Add a new phase action to the 'stop' step. @@ -494,14 +573,16 @@ class Geant4: \author M.Frank """ + def addStop(self, factory_specification): - return self.addPhaseAction('stop',factory_specification) + return self.addPhaseAction('stop', factory_specification) """ Execute the Geant 4 program with all steps. \author M.Frank """ + def execute(self): self.kernel().configure() self.kernel().initialize() @@ -519,138 +600,140 @@ class Geant4: sdtyp = 'Unknown' if typ in self.sensitive_types: sdtyp = self.sensitive_types[typ] - logger.info('+++ %-32s type:%-12s --> Sensitive type: %s',o.name(), typ, sdtyp) + logger.info('+++ %-32s type:%-12s --> Sensitive type: %s', o.name(), typ, sdtyp) def setupSensitiveSequencer(self, name, action): - if isinstance( action, tuple ): + if isinstance(action, tuple): sensitive_type = action[0] else: sensitive_type = action - seq = SensitiveSequence(self.kernel(),'Geant4SensDetActionSequence/'+name) + seq = SensitiveSequence(self.kernel(), 'Geant4SensDetActionSequence/' + name) seq.enableUI() return seq - - def setupDetector(self,name,action,collections=None): - #fg: allow the action to be a tuple with parameter dictionary + + def setupDetector(self, name, action, collections=None): + # fg: allow the action to be a tuple with parameter dictionary sensitive_type = "" parameterDict = {} - if isinstance(action,tuple) or isinstance(action,list): + if isinstance(action, tuple) or isinstance(action, list): sensitive_type = action[0] parameterDict = action[1] else: sensitive_type = action - seq = SensitiveSequence(self.kernel(),'Geant4SensDetActionSequence/'+name) + seq = SensitiveSequence(self.kernel(), 'Geant4SensDetActionSequence/' + name) seq.enableUI() acts = [] if collections is None: sd = self.description.sensitiveDetector(str(name)) ro = sd.readout() collections = ro.collectionNames() - if len(collections)==0: - act = SensitiveAction(self.kernel(),sensitive_type+'/'+name+'Handler',name) + if len(collections) == 0: + act = SensitiveAction(self.kernel(), sensitive_type + '/' + name + 'Handler', name) for parameter, value in six.iteritems(parameterDict): - setattr( act, parameter, value) + setattr(act, parameter, value) acts.append(act) # Work down the collections if present if collections is not None: for coll in collections: params = {} - if isinstance(coll,tuple) or isinstance(coll,list): - if len(coll)>2: + if isinstance(coll, tuple) or isinstance(coll, list): + if len(coll) > 2: coll_nam = coll[0] sensitive_type = coll[1] params = coll[2] - elif len(coll)>1: + elif len(coll) > 1: coll_nam = coll[0] sensitive_type = coll[1] else: coll_nam = coll[0] else: coll_nam = coll - act = SensitiveAction(self.kernel(),sensitive_type+'/'+coll_nam+'Handler',name) + act = SensitiveAction(self.kernel(), sensitive_type + '/' + coll_nam + 'Handler', name) act.CollectionName = coll_nam for parameter, value in six.iteritems(params): - setattr( act, parameter, value) + setattr(act, parameter, value) acts.append(act) for act in acts: act.enableUI() seq.add(act) - if len(acts)>1: - return (seq,acts) - return (seq,acts[0]) + if len(acts) > 1: + return (seq, acts) + return (seq, acts[0]) - def setupCalorimeter(self,name,type=None,collections=None): + def setupCalorimeter(self, name, type=None, collections=None): sd = self.description.sensitiveDetector(str(name)) - ### sd.setType('calorimeter') - if type is None: type = self.sensitive_types['calorimeter'] - return self.setupDetector(name,type,collections) + # sd.setType('calorimeter') + if type is None: + type = self.sensitive_types['calorimeter'] + return self.setupDetector(name, type, collections) - def setupTracker(self,name,type=None,collections=None): + def setupTracker(self, name, type=None, collections=None): sd = self.description.sensitiveDetector(str(name)) - ### sd.setType('tracker') - if type is None: type = self.sensitive_types['tracker'] - return self.setupDetector(name,type,collections) + # sd.setType('tracker') + if type is None: + type = self.sensitive_types['tracker'] + return self.setupDetector(name, type, collections) def _private_setupField(self, field, stepper, equation, prt): import SystemOfUnits - field.stepper = stepper - field.equation = equation - field.eps_min = 5e-05*SystemOfUnits.mm - field.eps_max = 0.001*SystemOfUnits.mm - field.min_chord_step = 0.01*SystemOfUnits.mm - field.delta_chord = 0.25*SystemOfUnits.mm - field.delta_intersection = 0.001*SystemOfUnits.mm - field.delta_one_step = 0.01*SystemOfUnits.mm - field.largest_step = 1000*SystemOfUnits.m + field.stepper = stepper + field.equation = equation + field.eps_min = 5e-05 * SystemOfUnits.mm + field.eps_max = 0.001 * SystemOfUnits.mm + field.min_chord_step = 0.01 * SystemOfUnits.mm + field.delta_chord = 0.25 * SystemOfUnits.mm + field.delta_intersection = 0.001 * SystemOfUnits.mm + field.delta_one_step = 0.01 * SystemOfUnits.mm + field.largest_step = 1000 * SystemOfUnits.m if prt: - logger.info('+++++> %s %s %s %s ',field.name,'-> stepper = ',str(field.stepper),'') - logger.info('+++++> %s %s %s %s ',field.name,'-> equation = ',str(field.equation),'') - logger.info('+++++> %s %s %s %s ',field.name,'-> eps_min = ',str(field.eps_min),'[mm]') - logger.info('+++++> %s %s %s %s ',field.name,'-> eps_max = ',str(field.eps_max),'[mm]') - logger.info('+++++> %s %s %s %s ',field.name,'-> delta_chord = ',str(field.delta_chord),'[mm]') - logger.info('+++++> %s %s %s %s ',field.name,'-> min_chord_step = ',str(field.min_chord_step),'[mm]') - logger.info('+++++> %s %s %s %s ',field.name,'-> delta_one_step = ',str(field.delta_one_step),'[mm]') - logger.info('+++++> %s %s %s %s ',field.name,'-> delta_intersection = ',str(field.delta_intersection),'[mm]') - logger.info('+++++> %s %s %s %s ',field.name,'-> largest_step = ',str(field.largest_step),'[mm]') + logger.info('+++++> %s %s %s %s ', field.name, '-> stepper = ', str(field.stepper), '') + logger.info('+++++> %s %s %s %s ', field.name, '-> equation = ', str(field.equation), '') + logger.info('+++++> %s %s %s %s ', field.name, '-> eps_min = ', str(field.eps_min), '[mm]') + logger.info('+++++> %s %s %s %s ', field.name, '-> eps_max = ', str(field.eps_max), '[mm]') + logger.info('+++++> %s %s %s %s ', field.name, '-> delta_chord = ', str(field.delta_chord), '[mm]') + logger.info('+++++> %s %s %s %s ', field.name, '-> min_chord_step = ', str(field.min_chord_step), '[mm]') + logger.info('+++++> %s %s %s %s ', field.name, '-> delta_one_step = ', str(field.delta_one_step), '[mm]') + logger.info('+++++> %s %s %s %s ', field.name, '-> delta_intersection = ', str(field.delta_intersection), '[mm]') + logger.info('+++++> %s %s %s %s ', field.name, '-> largest_step = ', str(field.largest_step), '[mm]') return field - - def setupTrackingFieldMT(self, name='MagFieldTrackingSetup', stepper='ClassicalRK4', equation='Mag_UsualEqRhs',prt=False): - seq,fld = self.addDetectorConstruction("Geant4FieldTrackingConstruction/"+name) + + def setupTrackingFieldMT(self, name='MagFieldTrackingSetup', stepper='ClassicalRK4', equation='Mag_UsualEqRhs', prt=False): + seq, fld = self.addDetectorConstruction("Geant4FieldTrackingConstruction/" + name) self._private_setupField(fld, stepper, equation, prt) - return (seq,fld) + return (seq, fld) - def setupTrackingField(self, name='MagFieldTrackingSetup', stepper='ClassicalRK4', equation='Mag_UsualEqRhs',prt=False): - field = self.addConfig('Geant4FieldTrackingSetupAction/'+name) + def setupTrackingField(self, name='MagFieldTrackingSetup', stepper='ClassicalRK4', equation='Mag_UsualEqRhs', prt=False): + field = self.addConfig('Geant4FieldTrackingSetupAction/' + name) self._private_setupField(field, stepper, equation, prt) return field - + def setupPhysics(self, name): phys = self.master().physicsList() phys.extends = name - phys.decays = True + phys.decays = True phys.enableUI() phys.dump() return phys def addPhysics(self, name): phys = self.master().physicsList() - opt = PhysicsList(self.master(), name) + opt = PhysicsList(self.master(), name) opt.enableUI() phys.adopt(opt) return opt - - def setupGun(self, name, particle, energy, isotrop=True, multiplicity=1, position=(0.0,0.0,0.0),register=True, **args): - gun = GeneratorAction(self.kernel(),"Geant4ParticleGun/"+name,True) + + def setupGun(self, name, particle, energy, isotrop=True, multiplicity=1, position=(0.0, 0.0, 0.0), register=True, **args): + gun = GeneratorAction(self.kernel(), "Geant4ParticleGun/" + name, True) for i in args.items(): - setattr(gun,i[0],i[1]) - gun.energy = energy - gun.particle = particle + setattr(gun, i[0], i[1]) + gun.energy = energy + gun.particle = particle gun.multiplicity = multiplicity - gun.position = position - gun.isotrop = isotrop + gun.position = position + gun.isotrop = isotrop gun.enableUI() if register: self.kernel().generatorAction().add(gun) @@ -661,8 +744,9 @@ class Geant4: \author M.Frank """ - def setupROOTOutput(self,name,output,mc_truth=True): - evt_root = EventAction(self.kernel(),'Geant4Output2ROOT/'+name,True) + + def setupROOTOutput(self, name, output, mc_truth=True): + evt_root = EventAction(self.kernel(), 'Geant4Output2ROOT/' + name, True) evt_root.HandleMCTruth = mc_truth evt_root.Control = True if not output.endswith('.root'): @@ -677,10 +761,11 @@ class Geant4: \author M.Frank """ - def setupLCIOOutput(self,name,output): - evt_lcio = EventAction(self.kernel(),'Geant4Output2LCIO/'+name,True) + + def setupLCIOOutput(self, name, output): + evt_lcio = EventAction(self.kernel(), 'Geant4Output2LCIO/' + name, True) evt_lcio.Control = True - evt_lcio.Output = output + evt_lcio.Output = output evt_lcio.enableUI() self.kernel().eventAction().add(evt_lcio) return evt_lcio @@ -697,10 +782,11 @@ class Geant4: \author M.Frank """ + def buildInputStage(self, generator_input_modules, output_level=None, have_mctruth=True): ga = self.kernel().generatorAction() # Register Generation initialization action - gen = GeneratorAction(self.kernel(),"Geant4GeneratorActionInit/GenerationInit") + gen = GeneratorAction(self.kernel(), "Geant4GeneratorActionInit/GenerationInit") if output_level is not None: gen.OutputLevel = output_level ga.adopt(gen) @@ -714,7 +800,7 @@ class Geant4: ga.adopt(gen) # Merge all existing interaction records - gen = GeneratorAction(self.kernel(),"Geant4InteractionMerger/InteractionMerger") + gen = GeneratorAction(self.kernel(), "Geant4InteractionMerger/InteractionMerger") gen.enableUI() if output_level is not None: gen.OutputLevel = output_level @@ -722,8 +808,8 @@ class Geant4: # Finally generate Geant4 primaries if have_mctruth: - gen = GeneratorAction(self.kernel(),"Geant4PrimaryHandler/PrimaryHandler") - gen.RejectPDGs="{1,2,3,4,5,6,21,23,24}" + gen = GeneratorAction(self.kernel(), "Geant4PrimaryHandler/PrimaryHandler") + gen.RejectPDGs = "{1,2,3,4,5,6,21,23,24}" gen.enableUI() if output_level is not None: gen.OutputLevel = output_level @@ -735,13 +821,15 @@ class Geant4: Execute the main Geant4 action \author M.Frank """ + def run(self): - #self.master().configure() - #self.master().initialize() - #self.master().run() - #self.master().terminate() + # self.master().configure() + # self.master().initialize() + # self.master().run() + # self.master().terminate() from ROOT import PyDDG4 PyDDG4.run(self.master().get()) return self + Simple = Geant4 diff --git a/DDG4/python/DDSim/DD4hepSimulation.py b/DDG4/python/DDSim/DD4hepSimulation.py index f9e15e3db4328cb88088395109ae1891a4231395..520600dfe5db877e2e1ed999a115837d286f494f 100644 --- a/DDG4/python/DDSim/DD4hepSimulation.py +++ b/DDG4/python/DDSim/DD4hepSimulation.py @@ -20,25 +20,26 @@ logger.setLevel(logging.INFO) import argparse try: import argcomplete - ARGCOMPLETEENABLED=True + ARGCOMPLETEENABLED = True except ImportError: - ARGCOMPLETEENABLED=False + ARGCOMPLETEENABLED = False POSSIBLEINPUTFILES = (".stdhep", ".slcio", ".HEPEvt", ".hepevt", ".hepmc", ".pairs") -def outputLevel( level ): + +def outputLevel(level): """return INT for outputlevel""" if isinstance(level, int): if level < 1 or 7 < level: raise KeyError return level - outputlevels = { "VERBOSE": 1, - "DEBUG": 2, - "INFO": 3, - "WARNING": 4, - "ERROR": 5, - "FATAL": 6, - "ALWAYS": 7 } + outputlevels = {"VERBOSE": 1, + "DEBUG": 2, + "INFO": 3, + "WARNING": 4, + "ERROR": 5, + "FATAL": 6, + "ALWAYS": 7} return outputlevels[level.upper()] @@ -59,6 +60,7 @@ import os import sys import datetime + class DD4hepSimulation(object): """Class to hold all the parameters and functions to run simulation""" @@ -72,7 +74,7 @@ class DD4hepSimulation(object): self.numberOfEvents = 0 self.skipNEvents = 0 - self.physicsList = None ## deprecated use physics.list + self.physicsList = None # deprecated use physics.list self.crossingAngleBoost = 0.0 self.macroFile = '' self.enableGun = False @@ -88,7 +90,7 @@ class DD4hepSimulation(object): self._dumpParameter = False self._dumpSteeringFile = False - ## objects for extended configuration option + # objects for extended configuration option self.output = Output() self.random = Random() self.gun = Gun() @@ -104,16 +106,15 @@ class DD4hepSimulation(object): self._argv = None - ### use TCSH geant UI instead of QT + # use TCSH geant UI instead of QT os.environ['G4UI_USE_TCSH'] = "1" - def readSteeringFile(self): """Reads a steering file and sets the parameters to that of the DD4hepSimulation object present in the steering file. """ globs = {} - locs = {} + locs = {} if not self.steeringFile: return sFileTemp = self.steeringFile @@ -135,35 +136,35 @@ class DD4hepSimulation(object): parser.add_argument("--steeringFile", "-S", action="store", default=self.steeringFile, help="Steering file to change default behaviour") - #first we parse just the steering file, but only if we don't want to see the help message - if not any( opt in self._argv for opt in ('-h','--help')): + # first we parse just the steering file, but only if we don't want to see the help message + if not any(opt in self._argv for opt in ('-h', '--help')): parsed, _unknown = parser.parse_known_args() self.steeringFile = parsed.steeringFile self.readSteeringFile() - ## readSteeringFile will set self._argv to None if there is a steering file + # readSteeringFile will set self._argv to None if there is a steering file if self._argv is None: self._argv = list(argv) if argv else list(sys.argv) - parser.add_argument("--compactFile", action="store", default=self.compactFile, help="The compact XML file") - parser.add_argument("--runType", action="store", choices=("batch","vis","run","shell"), default=self.runType, - help="The type of action to do in this invocation"##Note: implicit string concatenation + parser.add_argument("--runType", action="store", choices=("batch", "vis", "run", "shell"), default=self.runType, + help="The type of action to do in this invocation" # Note: implicit string concatenation "\nbatch: just simulate some events, needs numberOfEvents, and input file or gun" "\nvis: enable visualisation, run the macroFile if it is set" "\nrun: run the macroFile and exit" "\nshell: enable interactive session") parser.add_argument("--inputFiles", "-I", nargs='+', action="store", default=self.inputFiles, - help="InputFiles for simulation %s files are supported" % ", ".join(POSSIBLEINPUTFILES) ) + help="InputFiles for simulation %s files are supported" % ", ".join(POSSIBLEINPUTFILES)) - parser.add_argument("--outputFile","-O", action="store", default=self.outputFile, + parser.add_argument("--outputFile", "-O", action="store", default=self.outputFile, help="Outputfile from the simulation,only lcio output is supported") parser.add_argument("-v", "--printLevel", action="store", default=self.printLevel, dest="printLevel", - choices=(1,2,3,4,5,6,7,'VERBOSE','DEBUG', 'INFO', 'WARNING', 'ERROR', 'FATAL', 'ALWAYS'), + choices=(1, 2, 3, 4, 5, 6, 7, 'VERBOSE', 'DEBUG', + 'INFO', 'WARNING', 'ERROR', 'FATAL', 'ALWAYS'), help="Verbosity use integers from 1(most) to 7(least) verbose" "\nor strings: VERBOSE, DEBUG, INFO, WARNING, ERROR, FATAL, ALWAYS") @@ -179,10 +180,10 @@ class DD4hepSimulation(object): parser.add_argument("--crossingAngleBoost", action="store", dest="crossingAngleBoost", default=self.crossingAngleBoost, type=float, help="Lorentz boost for the crossing angle, in radian!") - parser.add_argument("--vertexSigma", nargs=4, action="store", dest="vertexSigma", default=self.vertexSigma, metavar = ('X','Y','Z','T'), + parser.add_argument("--vertexSigma", nargs=4, action="store", dest="vertexSigma", default=self.vertexSigma, metavar=('X', 'Y', 'Z', 'T'), type=float, help="FourVector of the Sigma for the Smearing of the Vertex position: x y z t") - parser.add_argument("--vertexOffset", nargs=4, action="store", dest="vertexOffset", default=self.vertexOffset, metavar = ('X','Y','Z','T'), + parser.add_argument("--vertexOffset", nargs=4, action="store", dest="vertexOffset", default=self.vertexOffset, metavar=('X', 'Y', 'Z', 'T'), type=float, help="FourVector of translation for the Smearing of the Vertex position: x y z t") parser.add_argument("--macroFile", "-M", action="store", dest="macroFile", default=self.macroFile, @@ -206,11 +207,11 @@ class DD4hepSimulation(object): parser.add_argument("--dumpSteeringFile", action="store_true", dest="dumpSteeringFile", default=self._dumpSteeringFile, help="print an example steering file to stdout") - #output, or do something smarter with fullHelp only for example + # output, or do something smarter with fullHelp only for example ConfigHelper.addAllHelper(self, parser) - ## now parse everything. The default values are now taken from the - ## steeringFile if they were set so that the steering file parameters can be - ## overwritten from the command line + # now parse everything. The default values are now taken from the + # steeringFile if they were set so that the steering file parameters can be + # overwritten from the command line if ARGCOMPLETEENABLED: argcomplete.autocomplete(parser) parsed = parser.parse_args() @@ -220,9 +221,9 @@ class DD4hepSimulation(object): self.compactFile = parsed.compactFile self.inputFiles = parsed.inputFiles - self.inputFiles = self.__checkFileFormat( self.inputFiles, POSSIBLEINPUTFILES) + self.inputFiles = self.__checkFileFormat(self.inputFiles, POSSIBLEINPUTFILES) self.outputFile = parsed.outputFile - self.__checkFileFormat( self.outputFile, ('.root', '.slcio')) + self.__checkFileFormat(self.outputFile, ('.root', '.slcio')) self.runType = parsed.runType self.printLevel = self.__checkOutputLevel(parsed.printLevel) @@ -241,7 +242,7 @@ class DD4hepSimulation(object): self._consistencyChecks() #self.__treatUnknownArgs( parsed, unknown ) - self.__parseAllHelper( parsed ) + self.__parseAllHelper(parsed) if self._errorMessages and not (self._dumpParameter or self._dumpSteeringFile): parser.epilog = "\n".join(self._errorMessages) parser.print_help() @@ -249,35 +250,35 @@ class DD4hepSimulation(object): if self._dumpParameter: from pprint import pprint - logger.info("="*80) + logger.info("=" * 80) pprint(vars(self)) - logger.info("="*80) + logger.info("=" * 80) exit(1) if self._dumpSteeringFile: - self.__printSteeringFile( parser ) + self.__printSteeringFile(parser) exit(1) @staticmethod - def getDetectorLists( detectorDescription ): + def getDetectorLists(detectorDescription): ''' get lists of trackers and calorimeters that are defined in detectorDescription (the compact xml file)''' import DDG4 - trackers,calos = [],[] + trackers, calos = [], [] for i in detectorDescription.detectors(): det = DDG4.DetElement(i.second.ptr()) name = det.name() - sd = detectorDescription.sensitiveDetector( name ) + sd = detectorDescription.sensitiveDetector(name) if sd.isValid(): detType = sd.type() # if len(detectorList) and not(name in detectorList): # continue - logger.info('getDetectorLists - found active detctor %s type: %s' , name , detType) + logger.info('getDetectorLists - found active detctor %s type: %s', name, detType) if detType == "tracker": - trackers.append( det.name() ) + trackers.append(det.name()) if detType == "calorimeter": - calos.append( det.name() ) + calos.append(det.name()) - return trackers,calos + return trackers, calos #================================================================================== @@ -286,31 +287,32 @@ class DD4hepSimulation(object): import ROOT ROOT.PyConfig.IgnoreCommandLineOptions = True - import DDG4, dd4hep + import DDG4 + import dd4hep self.printLevel = getOutputLevel(self.printLevel) kernel = DDG4.Kernel() dd4hep.setPrintLevel(self.printLevel) - kernel.loadGeometry(str("file:"+ self.compactFile )) + kernel.loadGeometry(str("file:" + self.compactFile)) detectorDescription = kernel.detectorDescription() - DDG4.importConstants( detectorDescription ) + DDG4.importConstants(detectorDescription) #---------------------------------------------------------------------------------- #simple = DDG4.Geant4( kernel, tracker='Geant4TrackerAction',calo='Geant4CalorimeterAction') #simple = DDG4.Geant4( kernel, tracker='Geant4TrackerCombineAction',calo='Geant4ScintillatorCalorimeterAction') - simple = DDG4.Geant4( kernel, tracker=self.action.tracker, calo=self.action.calo ) + simple = DDG4.Geant4(kernel, tracker=self.action.tracker, calo=self.action.calo) simple.printDetectors() - if self.runType =="vis": + if self.runType == "vis": simple.setupUI(typ="csh", vis=True, macro=self.macroFile) - elif self.runType =="run": + elif self.runType == "run": simple.setupUI(typ="csh", vis=False, macro=self.macroFile, ui=False) - elif self.runType =="shell": + elif self.runType == "shell": simple.setupUI(typ="csh", vis=False, macro=None, ui=True) elif self.runType == "batch": simple.setupUI(typ="csh", vis=False, macro=None, ui=False) @@ -318,8 +320,8 @@ class DD4hepSimulation(object): logger.errro("unknown runType") exit(1) - #kernel.UI="csh" - kernel.NumEvents=self.numberOfEvents + # kernel.UI="csh" + kernel.NumEvents = self.numberOfEvents #----------------------------------------------------------------------------------- # setup the magnetic field: @@ -328,12 +330,12 @@ class DD4hepSimulation(object): #---------------------------------------------------------------------------------- # Configure Run actions - run1 = DDG4.RunAction(kernel,'Geant4TestRunAction/RunInit') + run1 = DDG4.RunAction(kernel, 'Geant4TestRunAction/RunInit') kernel.registerGlobalAction(run1) kernel.runAction().add(run1) # Configure the random seed, do it before the I/O because we might change the seed! - _rndm = self.random.initialize( DDG4, kernel, self.output.random ) + _rndm = self.random.initialize(DDG4, kernel, self.output.random) # Configure I/O if self.outputFile.endswith(".slcio"): @@ -348,8 +350,8 @@ class DD4hepSimulation(object): actionList = [] if self.enableGun: - gun = DDG4.GeneratorAction(kernel,"Geant4ParticleGun/"+"Gun") - self.gun.setOptions( gun ) + gun = DDG4.GeneratorAction(kernel, "Geant4ParticleGun/" + "Gun") + self.gun.setOptions(gun) gun.Standalone = False gun.Mask = 1 actionList.append(gun) @@ -357,45 +359,45 @@ class DD4hepSimulation(object): logger.info("++++ Adding DD4hep Particle Gun ++++") if self.enableG4Gun: - ## GPS Create something - self._g4gun = DDG4.GeneratorAction(kernel,"Geant4GeneratorWrapper/Gun") + # GPS Create something + self._g4gun = DDG4.GeneratorAction(kernel, "Geant4GeneratorWrapper/Gun") self._g4gun.Uses = 'G4ParticleGun' self._g4gun.Mask = 2 logger.info("++++ Adding Geant4 Particle Gun ++++") actionList.append(self._g4gun) if self.enableG4GPS: - ## GPS Create something - self._g4gps = DDG4.GeneratorAction(kernel,"Geant4GeneratorWrapper/GPS") + # GPS Create something + self._g4gps = DDG4.GeneratorAction(kernel, "Geant4GeneratorWrapper/GPS") self._g4gps.Uses = 'G4GeneralParticleSource' self._g4gps.Mask = 3 logger.info("++++ Adding Geant4 General Particle Source ++++") actionList.append(self._g4gps) - for index,inputFile in enumerate(self.inputFiles, start=4): + for index, inputFile in enumerate(self.inputFiles, start=4): if inputFile.endswith(".slcio"): - gen = DDG4.GeneratorAction(kernel,"LCIOInputAction/LCIO%d" % index) + gen = DDG4.GeneratorAction(kernel, "LCIOInputAction/LCIO%d" % index) gen.Parameters = self.lcio.getParameters() - gen.Input="LCIOFileReader|"+inputFile + gen.Input = "LCIOFileReader|" + inputFile elif inputFile.endswith(".stdhep"): - gen = DDG4.GeneratorAction(kernel,"LCIOInputAction/STDHEP%d" % index) - gen.Input="LCIOStdHepReader|"+inputFile + gen = DDG4.GeneratorAction(kernel, "LCIOInputAction/STDHEP%d" % index) + gen.Input = "LCIOStdHepReader|" + inputFile elif inputFile.endswith(".HEPEvt"): - gen = DDG4.GeneratorAction(kernel,"Geant4InputAction/HEPEvt%d" % index) - gen.Input="Geant4EventReaderHepEvtShort|"+inputFile + gen = DDG4.GeneratorAction(kernel, "Geant4InputAction/HEPEvt%d" % index) + gen.Input = "Geant4EventReaderHepEvtShort|" + inputFile elif inputFile.endswith(".hepevt"): - gen = DDG4.GeneratorAction(kernel,"Geant4InputAction/hepevt%d" % index) - gen.Input="Geant4EventReaderHepEvtLong|"+inputFile + gen = DDG4.GeneratorAction(kernel, "Geant4InputAction/hepevt%d" % index) + gen.Input = "Geant4EventReaderHepEvtLong|" + inputFile elif inputFile.endswith(".hepmc"): - gen = DDG4.GeneratorAction(kernel,"Geant4InputAction/hepmc%d" % index) - gen.Input="Geant4EventReaderHepMC|"+inputFile + gen = DDG4.GeneratorAction(kernel, "Geant4InputAction/hepmc%d" % index) + gen.Input = "Geant4EventReaderHepMC|" + inputFile elif inputFile.endswith(".pairs"): - gen = DDG4.GeneratorAction(kernel,"Geant4InputAction/GuineaPig%d" % index) - gen.Input="Geant4EventReaderGuineaPig|"+inputFile + gen = DDG4.GeneratorAction(kernel, "Geant4InputAction/GuineaPig%d" % index) + gen.Input = "Geant4EventReaderGuineaPig|" + inputFile gen.Parameters = self.guineapig.getParameters() else: - ##this should never happen because we already check at the top, but in case of some LogicError... - raise RuntimeError( "Unknown input file type: %s" % inputFile ) + # this should never happen because we already check at the top, but in case of some LogicError... + raise RuntimeError("Unknown input file type: %s" % inputFile) gen.Sync = self.skipNEvents gen.Mask = index actionList.append(gen) @@ -403,26 +405,25 @@ class DD4hepSimulation(object): if actionList: self._buildInputStage(simple, actionList, output_level=self.output.inputStage, - have_mctruth=self._enablePrimaryHandler() ) + have_mctruth=self._enablePrimaryHandler()) #================================================================================================ # And handle the simulation particles. - part = DDG4.GeneratorAction(kernel,"Geant4ParticleHandler/ParticleHandler") + part = DDG4.GeneratorAction(kernel, "Geant4ParticleHandler/ParticleHandler") kernel.generatorAction().adopt(part) #part.SaveProcesses = ['conv','Decay'] - part.SaveProcesses = self.part.saveProcesses + part.SaveProcesses = self.part.saveProcesses part.MinimalKineticEnergy = self.part.minimalKineticEnergy - part.KeepAllParticles = self.part.keepAllParticles - part.PrintEndTracking = self.part.printEndTracking - part.PrintStartTracking = self.part.printStartTracking - part.MinDistToParentVertex= self.part.minDistToParentVertex + part.KeepAllParticles = self.part.keepAllParticles + part.PrintEndTracking = self.part.printEndTracking + part.PrintStartTracking = self.part.printStartTracking + part.MinDistToParentVertex = self.part.minDistToParentVertex part.OutputLevel = self.output.part part.enableUI() - if self.part.enableDetailedHitsAndParticleInfo: - self.part.setDumpDetailedParticleInfo( kernel, DDG4 ) + self.part.setDumpDetailedParticleInfo(kernel, DDG4) self.part.setupUserParticleHandler(part, kernel, DDG4) @@ -430,7 +431,7 @@ class DD4hepSimulation(object): # Setup global filters for use in sensitive detectors try: - self.filter.setupFilters( kernel ) + self.filter.setupFilters(kernel) except RuntimeError as e: logger.error("%s", e) exit(1) @@ -438,28 +439,28 @@ class DD4hepSimulation(object): #================================================================================= # get lists of trackers and calorimeters in detectorDescription - trk,cal = self.getDetectorLists( detectorDescription ) + trk, cal = self.getDetectorLists(detectorDescription) # ---- add the trackers: try: - self.__setupSensitiveDetectors( trk, simple.setupTracker, self.filter.tracker) + self.__setupSensitiveDetectors(trk, simple.setupTracker, self.filter.tracker) except Exception as e: logger.error("Setting up sensitive detector %s", e) raise # ---- add the calorimeters: try: - self.__setupSensitiveDetectors( cal, simple.setupCalorimeter, self.filter.calo ) + self.__setupSensitiveDetectors(cal, simple.setupCalorimeter, self.filter.calo) except Exception as e: logger.error("Setting up sensitive detector %s", e) raise #================================================================================= # Now build the physics list: - _phys = self.physics.setupPhysics( kernel, name=self.physicsList ) + _phys = self.physics.setupPhysics(kernel, name=self.physicsList) - ## add the G4StepLimiterPhysics to activate the max step limits in volumes - ph = DDG4.PhysicsList(kernel,'Geant4PhysicsList/Myphysics') + # add the G4StepLimiterPhysics to activate the max step limits in volumes + ph = DDG4.PhysicsList(kernel, 'Geant4PhysicsList/Myphysics') ph.addPhysicsConstructor(str('G4StepLimiterPhysics')) _phys.add(ph) @@ -468,7 +469,7 @@ class DD4hepSimulation(object): kernel.configure() kernel.initialize() - ## GPS + # GPS if self._g4gun is not None: self._g4gun.generator() if self._g4gps is not None: @@ -481,38 +482,38 @@ class DD4hepSimulation(object): totalTimeUser, totalTimeSys, _cuTime, _csTime, _elapsedTime = os.times() if self.printLevel <= 3: - logger.info("DDSim INFO Total Time: %3.2f s (User), %3.2f s (System)"% (totalTimeUser, totalTimeSys)) + logger.info("DDSim INFO Total Time: %3.2f s (User), %3.2f s (System)" % + (totalTimeUser, totalTimeSys)) if self.numberOfEvents != 0: eventTime = totalTimeUser - startUpTime - perEventTime = eventTime / self.numberOfEvents - logger.info("DDSim INFO StartUp Time: %3.2f s, Event Processing: %3.2f s (%3.2f s/Event) " \ - % (startUpTime, eventTime, perEventTime)) - + perEventTime = eventTime / self.numberOfEvents + logger.info("DDSim INFO StartUp Time: %3.2f s, Event Processing: %3.2f s (%3.2f s/Event) " + % (startUpTime, eventTime, perEventTime)) def __setMagneticFieldOptions(self, simple): """ create and configure the magnetic tracking setup """ field = simple.addConfig('Geant4FieldTrackingSetupAction/MagFieldTrackingSetup') - field.stepper = self.field.stepper - field.equation = self.field.equation - field.eps_min = self.field.eps_min - field.eps_max = self.field.eps_max - field.min_chord_step = self.field.min_chord_step - field.delta_chord = self.field.delta_chord + field.stepper = self.field.stepper + field.equation = self.field.equation + field.eps_min = self.field.eps_min + field.eps_max = self.field.eps_max + field.min_chord_step = self.field.min_chord_step + field.delta_chord = self.field.delta_chord field.delta_intersection = self.field.delta_intersection - field.delta_one_step = self.field.delta_one_step - field.largest_step = self.field.largest_step + field.delta_one_step = self.field.delta_one_step + field.largest_step = self.field.largest_step def __checkFileFormat(self, fileNames, extensions): """check if the fileName is allowed, note that the filenames are case sensitive, and in case of hepevt we depend on this to identify short and long versions of the content """ - if isinstance( fileNames, six.string_types ): + if isinstance(fileNames, six.string_types): fileNames = [fileNames] - if not all( fileName.endswith( extensions ) for fileName in fileNames ): + if not all(fileName.endswith(extensions) for fileName in fileNames): self._errorMessages.append("ERROR: Unknown fileformat for file: %s" % fileNames) return fileNames - def __applyBoostOrSmear( self, kernel, actionList, mask ): + def __applyBoostOrSmear(self, kernel, actionList, mask): """apply boost or smearing for given mask index""" import DDG4 if self.crossingAngleBoost: @@ -528,19 +529,18 @@ class DD4hepSimulation(object): vSmear.Mask = mask actionList.append(vSmear) - - def __parseAllHelper( self, parsed ): + def __parseAllHelper(self, parsed): """ parse all the options for the helper """ parsedDict = vars(parsed) for name, obj in six.iteritems(vars(self)): - if isinstance( obj, ConfigHelper ): + if isinstance(obj, ConfigHelper): for var in obj.getOptions(): - key = "%s.%s" %( name,var ) + key = "%s.%s" % (name, var) if key in parsedDict: try: - obj.setOption( var, parsedDict[key] ) + obj.setOption(var, parsedDict[key]) except RuntimeError as e: - self._errorMessages.append( "ERROR: %s " % e ) + self._errorMessages.append("ERROR: %s " % e) def __checkOutputLevel(self, level): """return outputlevel as int so we don't have to import anything for faster startup""" @@ -553,10 +553,10 @@ class DD4hepSimulation(object): try: return outputLevel(level.upper()) except ValueError: - self._errorMessages.append( "ERROR: printLevel is neither integer nor string" ) + self._errorMessages.append("ERROR: printLevel is neither integer nor string") return -1 except KeyError: - self._errorMessages.append( "ERROR: printLevel '%s' unknown" % level ) + self._errorMessages.append("ERROR: printLevel '%s' unknown" % level) return -1 def __setupSensitiveDetectors(self, detectors, setupFuction, defaultFilter=None): @@ -572,12 +572,12 @@ class DD4hepSimulation(object): for pattern in self.action.mapActions: if pattern.lower() in det.lower(): action = self.action.mapActions[pattern] - logger.info(' replace default action with : %s' , action) + logger.info(' replace default action with : %s', action) break - seq,act = setupFuction( det, type=action ) - self.filter.applyFilters( seq, det, defaultFilter ) + seq, act = setupFuction(det, type=action) + self.filter.applyFilters(seq, det, defaultFilter) - ##set detailed hit creation mode for this + # set detailed hit creation mode for this if self.enableDetailedShowerMode: if isinstance(act, list): for a in act: @@ -585,51 +585,50 @@ class DD4hepSimulation(object): else: act.HitCreationMode = 2 - def __printSteeringFile( self, parser): + def __printSteeringFile(self, parser): """print the parameters formated as a steering file""" - steeringFileBase="""from DDSim.DD4hepSimulation import DD4hepSimulation + steeringFileBase = """from DDSim.DD4hepSimulation import DD4hepSimulation from g4units import mm, GeV, MeV SIM = DD4hepSimulation() """ optionDict = parser._option_string_actions parameters = vars(self) - for parName, parameter in sorted(list(parameters.items()), sortParameters ): + for parName, parameter in sorted(list(parameters.items()), sortParameters): if parName.startswith("_"): continue - if isinstance( parameter, ConfigHelper ): + if isinstance(parameter, ConfigHelper): steeringFileBase += "\n\n" steeringFileBase += "################################################################################\n" - steeringFileBase += "## %s \n" % "\n## ".join( parameter.__doc__.splitlines() ) + steeringFileBase += "## %s \n" % "\n## ".join(parameter.__doc__.splitlines()) steeringFileBase += "################################################################################\n" options = parameter.getOptions() - for opt, optionsDict in sorted( six.iteritems(options), sortParameters ): + for opt, optionsDict in sorted(six.iteritems(options), sortParameters): if opt.startswith("_"): continue parValue = optionsDict['default'] if isinstance(optionsDict.get('help'), six.string_types): steeringFileBase += "\n## %s\n" % "\n## ".join(optionsDict.get('help').splitlines()) - ## add quotes if it is a string - if isinstance( parValue, six.string_types ): - steeringFileBase += "SIM.%s.%s = \"%s\"\n" %(parName, opt, parValue) + # add quotes if it is a string + if isinstance(parValue, six.string_types): + steeringFileBase += "SIM.%s.%s = \"%s\"\n" % (parName, opt, parValue) else: - steeringFileBase += "SIM.%s.%s = %s\n" %(parName, opt, parValue) + steeringFileBase += "SIM.%s.%s = %s\n" % (parName, opt, parValue) else: - ## get the docstring from the command line parameter - optionObj = optionDict.get("--"+parName, None) - if isinstance(optionObj, argparse._StoreAction ): + # get the docstring from the command line parameter + optionObj = optionDict.get("--" + parName, None) + if isinstance(optionObj, argparse._StoreAction): steeringFileBase += "## %s\n" % "\n## ".join(optionObj.help.splitlines()) - ## add quotes if it is a string + # add quotes if it is a string if isinstance(parameter, six.string_types): - steeringFileBase += "SIM.%s = \"%s\"" %( parName, str(parameter)) + steeringFileBase += "SIM.%s = \"%s\"" % (parName, str(parameter)) else: - steeringFileBase += "SIM.%s = %s" %( parName, str(parameter)) + steeringFileBase += "SIM.%s = %s" % (parName, str(parameter)) steeringFileBase += "\n" logger.info("%s", steeringFileBase) - - def _consistencyChecks( self ): + def _consistencyChecks(self): """Check if the requested setup makes sense, or if there is something preventing it from working correctly Appends error messages to self._errorMessages @@ -646,16 +645,16 @@ SIM = DD4hepSimulation() if not self.inputFiles and not self.enableGun: self._errorMessages.append("ERROR: Batch mode requested, but did not set inputFile(s) or gun") - if self.inputFiles and ( self.enableG4Gun or self.enableG4GPS ): + if self.inputFiles and (self.enableG4Gun or self.enableG4GPS): self._errorMessages.append("ERROR: Cannot use both inputFiles and Geant4Gun or GeneralParticleSource") - if self.enableGun and ( self.enableG4Gun or self.enableG4GPS ): + if self.enableGun and (self.enableG4Gun or self.enableG4GPS): self._errorMessages.append("ERROR: Cannot use both DD4hepGun and Geant4 Gun or GeneralParticleSource") if self.numberOfEvents < 0 and not self.inputFiles: self._errorMessages.append("ERROR: Negative number of events only sensible for inputFiles") - def _enablePrimaryHandler( self ): + def _enablePrimaryHandler(self): """ the geant4 Gun or GeneralParticleSource cannot be used together with the PrimaryHandler. Particles would be simulated multiple times @@ -668,7 +667,6 @@ SIM = DD4hepSimulation() logger.info("Disabling the PrimaryHandler") return enablePrimaryHandler - def _buildInputStage(self, simple, generator_input_modules, output_level=None, have_mctruth=True): """ Generic build of the input stage with multiple input modules. @@ -683,7 +681,7 @@ SIM = DD4hepSimulation() ga = simple.kernel().generatorAction() # Register Generation initialization action - gen = GeneratorAction(simple.kernel(),"Geant4GeneratorActionInit/GenerationInit") + gen = GeneratorAction(simple.kernel(), "Geant4GeneratorActionInit/GenerationInit") if output_level is not None: gen.OutputLevel = output_level ga.adopt(gen) @@ -697,7 +695,7 @@ SIM = DD4hepSimulation() ga.adopt(gen) # Merge all existing interaction records - gen = GeneratorAction(simple.kernel(),"Geant4InteractionMerger/InteractionMerger") + gen = GeneratorAction(simple.kernel(), "Geant4InteractionMerger/InteractionMerger") gen.enableUI() if output_level is not None: gen.OutputLevel = output_level @@ -705,8 +703,8 @@ SIM = DD4hepSimulation() # Finally generate Geant4 primaries if have_mctruth: - gen = GeneratorAction(simple.kernel(),"Geant4PrimaryHandler/PrimaryHandler") - gen.RejectPDGs=ConfigHelper.makeString(self.physics.rejectPDGs) + gen = GeneratorAction(simple.kernel(), "Geant4PrimaryHandler/PrimaryHandler") + gen.RejectPDGs = ConfigHelper.makeString(self.physics.rejectPDGs) gen.enableUI() if output_level is not None: gen.OutputLevel = output_level @@ -716,10 +714,10 @@ SIM = DD4hepSimulation() ################################################################################ -### MODULE FUNCTIONS GO HERE +# MODULE FUNCTIONS GO HERE ################################################################################ -def sortParameters( parA, parB ): +def sortParameters(parA, parB): """sort the parameters by name: first normal parameters, then set of parameters based on ConfigHelper objects """ @@ -734,15 +732,15 @@ def sortParameters( parA, parB ): else: return 1 if str(parA[0]) > str(parB[0]) else -1 + def getOutputLevel(level): """return output.LEVEL""" from DDG4 import OutputLevel - levels = { 1: OutputLevel.VERBOSE, - 2: OutputLevel.DEBUG, - 3: OutputLevel.INFO, - 4: OutputLevel.WARNING, - 5: OutputLevel.ERROR, - 6: OutputLevel.FATAL, - 7: OutputLevel.ALWAYS } + levels = {1: OutputLevel.VERBOSE, + 2: OutputLevel.DEBUG, + 3: OutputLevel.INFO, + 4: OutputLevel.WARNING, + 5: OutputLevel.ERROR, + 6: OutputLevel.FATAL, + 7: OutputLevel.ALWAYS} return levels[level] - diff --git a/DDG4/python/DDSim/Helper/Action.py b/DDG4/python/DDSim/Helper/Action.py index c2ffa45e1b7d79f7e34ec973327d2516c84491f2..5418770cc5fe2dee37da40adf570dd33a46402be 100644 --- a/DDG4/python/DDSim/Helper/Action.py +++ b/DDG4/python/DDSim/Helper/Action.py @@ -6,7 +6,8 @@ from DDSim.Helper.ConfigHelper import ConfigHelper from six.moves import range import six -class Action( ConfigHelper ): + +class Action(ConfigHelper): """Action holding sensitive detector actions The default tracker and calorimeter actions can be set with @@ -25,37 +26,39 @@ class Action( ConfigHelper ): >>> SIM.action.mapActions['ecal'] =( "CaloPreShowerSDAction", {"FirstLayerNumber": 1} ) """ - def __init__( self ): + + def __init__(self): super(Action, self).__init__() self._tracker = ('Geant4TrackerWeightedAction', {'HitPositionCombination': 2, 'CollectSingleDeposits': False}) self._calo = 'Geant4ScintillatorCalorimeterAction' self._mapActions = dict() @property - def tracker( self ): + def tracker(self): """ set the default tracker action """ return self._tracker + @tracker.setter - def tracker( self, val ): + def tracker(self, val): self._tracker = val @property - def calo( self ): + def calo(self): """ set the default calorimeter action """ return self._calo + @calo.setter - def calo( self, val ): + def calo(self, val): self._calo = val - @property - def mapActions( self ): + def mapActions(self): """ create a map of patterns and actions to be applied to sensitive detectors example: SIM.action.mapActions['tpc'] = "TPCSDAction" """ return self._mapActions @mapActions.setter - def mapActions( self, val ): + def mapActions(self, val): """check if the argument is a dict, then we just update mapActions if it is a string or list, we use pairs as patterns --> Action """ @@ -65,13 +68,13 @@ class Action( ConfigHelper ): if isinstance(val, six.string_types): vals = val.split(" ") - elif isinstance( val, list ): + elif isinstance(val, list): vals = val - if len(vals)%2 != 0: + if len(vals) % 2 != 0: raise RuntimeError("Not enough parameters for mapActions") - for index in range(0,len(vals),2): - self._mapActions[vals[index]] = vals[index+1] + for index in range(0, len(vals), 2): + self._mapActions[vals[index]] = vals[index + 1] - def clearMapActions( self ): + def clearMapActions(self): """empty the mapActions dictionary""" self._mapActions = dict() diff --git a/DDG4/python/DDSim/Helper/ConfigHelper.py b/DDG4/python/DDSim/Helper/ConfigHelper.py index f7a458a963b55041ff597ffad21c5db195445f52..253fba6c0292288ede499716ac4277ad63442b38 100644 --- a/DDG4/python/DDSim/Helper/ConfigHelper.py +++ b/DDG4/python/DDSim/Helper/ConfigHelper.py @@ -16,9 +16,11 @@ from __future__ import absolute_import, unicode_literals from pprint import pprint import six -class ConfigHelper( object ): + +class ConfigHelper(object): """Base class for configuration helper""" - def __init__( self ): + + def __init__(self): pass def getOptions(self): @@ -26,7 +28,7 @@ class ConfigHelper( object ): # get all direct members not starting with underscore allVars = vars(self) - for var,val in six.iteritems(allVars): + for var, val in six.iteritems(allVars): if not var.startswith('_'): extraArgumentsName = "_%s_EXTRA" % var options = getattr(self, extraArgumentsName) if hasattr(self, extraArgumentsName) else None @@ -35,9 +37,9 @@ class ConfigHelper( object ): finalVars[var].update(options) # now get things defined with @property - props = [(p, getattr(type(self),p)) for p in dir(type(self)) if isinstance(getattr(type(self),p),property)] + props = [(p, getattr(type(self), p)) for p in dir(type(self)) if isinstance(getattr(type(self), p), property)] for propName, prop in props: - optName = "_%s_EXTRA" % propName + optName = "_%s_EXTRA" % propName doc = prop.__doc__ options = getattr(self, optName) if hasattr(self, optName) else None finalVars[propName] = {'default': getattr(self, propName)} @@ -51,23 +53,23 @@ class ConfigHelper( object ): def __repr__(self): return self.printOptions() - def printOptions( self ): + def printOptions(self): """print all paramters""" options = [] - for opt,val in six.iteritems(self.getOptions()): + for opt, val in six.iteritems(self.getOptions()): options.append("\n\t'%s': '%s'" % (opt, val[0])) return "".join(options) - def setOption( self, name, val ): + def setOption(self, name, val): """ set the attribute name to val """ setattr(self, name, val) @staticmethod - def makeList( stringVal, sep=" "): + def makeList(stringVal, sep=" "): """returns a list from a string separated by sep""" if not stringVal: return [] - if isinstance( stringVal, list ): + if isinstance(stringVal, list): return stringVal else: return stringVal.split(sep) @@ -82,7 +84,6 @@ class ConfigHelper( object ): else: return set(stringVal.split(sep)) - @staticmethod def makeString(container): """Return a string that can be parsed by dd4hep into a vector.""" @@ -92,22 +93,22 @@ class ConfigHelper( object ): return '{%s}' % ','.join([str(s) for s in container]) @staticmethod - def makeTuple( val ): + def makeTuple(val): """ returns a tuple of the string, separators are space or comma """ myTuple = None - if isinstance( val, tuple ): + if isinstance(val, tuple): myTuple = val - if isinstance( val, list ): + if isinstance(val, list): myTuple = tuple(val) - if isinstance( val, six.string_types ): + if isinstance(val, six.string_types): sep = ',' if ',' in val else ' ' - myTuple = tuple([ _.strip("(), ") for _ in val.split(sep) ]) + myTuple = tuple([_.strip("(), ") for _ in val.split(sep)]) if myTuple is None: - raise RuntimeError( "Cannot parse input value %s" % val ) + raise RuntimeError("Cannot parse input value %s" % val) return myTuple @staticmethod - def makeBool( val ): + def makeBool(val): """check if val is a bool or a string of true/false, otherwise raise exception""" if isinstance(val, bool): return val @@ -116,17 +117,16 @@ class ConfigHelper( object ): return True elif val.lower() == 'false': return False - raise RuntimeError( val ) - + raise RuntimeError(val) @staticmethod def addAllHelper(ddsim, parser): """all configHelper objects to commandline args""" for name, obj in six.iteritems(vars(ddsim)): if isinstance(obj, ConfigHelper): - for var,optionsDict in six.iteritems(obj.getOptions()): - optionsDict['action']='store_true' if var.startswith("enable") else 'store' + for var, optionsDict in six.iteritems(obj.getOptions()): + optionsDict['action'] = 'store_true' if var.startswith("enable") else 'store' parser.add_argument("--%s.%s" % (name, var), dest="%s.%s" % (name, var), **optionsDict - ) + ) diff --git a/DDG4/python/DDSim/Helper/Filter.py b/DDG4/python/DDSim/Helper/Filter.py index 333cc17dbc51e4ca7955b7cefd7f9478acf42050..0c027f620351c6e191e68949d46a1dee2579be5e 100644 --- a/DDG4/python/DDSim/Helper/Filter.py +++ b/DDG4/python/DDSim/Helper/Filter.py @@ -16,7 +16,8 @@ logging.basicConfig(format='%(levelname)s: %(message)s') logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) -class Filter( ConfigHelper ): + +class Filter(ConfigHelper): """Configuration for sensitive detector filters Set the default filter for tracker or caliromter @@ -36,95 +37,96 @@ class Filter( ConfigHelper ): >>> SIM.filter.filters['edep3kev'] = dict(name="EnergyDepositMinimumCut/3keV", parameter={"Cut": 3.0*keV} ) """ - def __init__( self ): + + def __init__(self): super(Filter, self).__init__() self._mapDetFilter = {} self._tracker = "edep1kev" - self._calo = "edep0" + self._calo = "edep0" self._filters = {} self._createDefaultFilters() @property - def tracker( self ): + def tracker(self): """ default filter for tracking sensitive detectors; this is applied if no other filter is used for a tracker""" return self._tracker + @tracker.setter - def tracker( self, val ): + def tracker(self, val): self._tracker = val @property - def calo( self ): + def calo(self): """ default filter for calorimeter sensitive detectors; this is applied if no other filter is used for a calorimeter """ return self._calo + @calo.setter - def calo( self, val ): + def calo(self, val): self._calo = val - @property - def filters( self ): + def filters(self): """ list of filter objects: map between name and parameter dictionary """ return self._filters + @filters.setter - def filters( self, val ): + def filters(self, val): if isinstance(val, dict): self._filters.update(val) return ## - raise RuntimeError("Commandline setting of filters is not supported, use a steeringFile: %s " % val ) - + raise RuntimeError("Commandline setting of filters is not supported, use a steeringFile: %s " % val) @property - def mapDetFilter( self ): + def mapDetFilter(self): """ a map between patterns and filter objects, using patterns to attach filters to sensitive detector """ return self._mapDetFilter + @mapDetFilter.setter - def mapDetFilter( self, val ): + def mapDetFilter(self, val): if isinstance(val, dict): self._mapDetFilter.update(val) return if isinstance(val, six.string_types): vals = val.split(" ") - elif isinstance( val, list ): + elif isinstance(val, list): vals = val - if len(vals)%2 != 0: + if len(vals) % 2 != 0: raise RuntimeError("Not enough parameters for mapDetFilter") - for index in range(0,len(vals),2): - self._mapDetFilter[vals[index]] = vals[index+1] + for index in range(0, len(vals), 2): + self._mapDetFilter[vals[index]] = vals[index + 1] - def resetFilter( self ): + def resetFilter(self): """ remove all filters """ self._filters = {} - def _createDefaultFilters( self ): + def _createDefaultFilters(self): """ create the map with the default filters """ - self.filters["geantino"]= dict( name="GeantinoRejectFilter/GeantinoRejector", - parameter={} ) + self.filters["geantino"] = dict(name="GeantinoRejectFilter/GeantinoRejector", + parameter={}) - self.filters["edep1kev"] = dict( name="EnergyDepositMinimumCut", - parameter={"Cut": 1.0*keV} ) + self.filters["edep1kev"] = dict(name="EnergyDepositMinimumCut", + parameter={"Cut": 1.0 * keV}) - self.filters["edep0"] = dict( name="EnergyDepositMinimumCut/Cut0", - parameter={"Cut": 0.0} ) + self.filters["edep0"] = dict(name="EnergyDepositMinimumCut/Cut0", + parameter={"Cut": 0.0}) - - def __makeMapDetList( self ): + def __makeMapDetList(self): """ create the values of the mapDetFilters a list of filters """ for pattern, filters in six.iteritems(self._mapDetFilter): self._mapDetFilter[pattern] = ConfigHelper.makeList(filters) - - def setupFilters( self, kernel): + def setupFilters(self, kernel): """ attach all filters to the kernel """ import DDG4 setOfFilters = set() for name, filt in six.iteritems(self.filters): setOfFilters.add(name) - ddFilt = DDG4.Filter(kernel,filt['name']) + ddFilt = DDG4.Filter(kernel, filt['name']) for para, value in six.iteritems(filt['parameter']): - setattr( ddFilt, para, value ) + setattr(ddFilt, para, value) kernel.registerGlobalFilter(ddFilt) filt['filter'] = ddFilt @@ -132,12 +134,12 @@ class Filter( ConfigHelper ): listOfFilters = [] for val in self.mapDetFilter.values(): listOfFilters += ConfigHelper.makeList(val) - requestedFilter = set(chain( ConfigHelper.makeList(self.tracker), ConfigHelper.makeList(self.calo), listOfFilters)) + requestedFilter = set(chain(ConfigHelper.makeList(self.tracker), ConfigHelper.makeList(self.calo), listOfFilters)) logger.info("ReqFilt %s", requestedFilter) if requestedFilter - setOfFilters: - raise RuntimeError(" Filter(s) '%s' are not registered!" % str(requestedFilter - setOfFilters) ) + raise RuntimeError(" Filter(s) '%s' are not registered!" % str(requestedFilter - setOfFilters)) - def applyFilters( self, seq, det, defaultFilter=None): + def applyFilters(self, seq, det, defaultFilter=None): """apply the filters to to the sensitive detector :param seq: sequence object returned when creating sensitive detector @@ -145,13 +147,13 @@ class Filter( ConfigHelper ): :returns: None """ self.__makeMapDetList() - foundFilter=False + foundFilter = False for pattern, filts in six.iteritems(self.mapDetFilter): if pattern.lower() in det.lower(): foundFilter = True for filt in filts: - logger.info("Adding filter '%s' matched with '%s' to sensitive detector for '%s' " %( filt, pattern, det )) - seq.add( self.filters[filt]['filter'] ) + logger.info("Adding filter '%s' matched with '%s' to sensitive detector for '%s' " % (filt, pattern, det)) + seq.add(self.filters[filt]['filter']) if not foundFilter and defaultFilter: - seq.add( self.filters[defaultFilter]['filter'] ) + seq.add(self.filters[defaultFilter]['filter']) diff --git a/DDG4/python/DDSim/Helper/GuineaPig.py b/DDG4/python/DDSim/Helper/GuineaPig.py index e4d2ded06661d59bf4acb897cd2456ff26a6d0cd..6a2f37372c5a1aa5b8abeb065c28fb0557f8929e 100644 --- a/DDG4/python/DDSim/Helper/GuineaPig.py +++ b/DDG4/python/DDSim/Helper/GuineaPig.py @@ -3,19 +3,22 @@ from __future__ import absolute_import, unicode_literals from DDSim.Helper.Input import Input -class GuineaPig( Input ): + +class GuineaPig(Input): """Configuration for the GuineaPig InputFiles""" - def __init__( self ): + + def __init__(self): super(GuineaPig, self).__init__() self._parameters["ParticlesPerEvent"] = -1 @property - def particlesPerEvent( self ): + def particlesPerEvent(self): """Set the number of pair particles to simulate per event. Only used if inputFile ends with ".pairs" If "-1" all particles will be simulated in a single event """ return self._parameters["ParticlesPerEvent"] + @particlesPerEvent.setter - def particlesPerEvent( self, val ): + def particlesPerEvent(self, val): self._parameters["ParticlesPerEvent"] = str(val) diff --git a/DDG4/python/DDSim/Helper/Gun.py b/DDG4/python/DDSim/Helper/Gun.py index fc334f69fa16e276aae402d3df65e42ce1179d94..ff3baf5b1571f6c53704c32da02c33627f5cabae 100644 --- a/DDG4/python/DDSim/Helper/Gun.py +++ b/DDG4/python/DDSim/Helper/Gun.py @@ -10,16 +10,18 @@ logging.basicConfig(format='%(levelname)s: %(message)s') logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) -class Gun( ConfigHelper ): + +class Gun(ConfigHelper): """Configuration for the DDG4 ParticleGun""" - def __init__( self ): + + def __init__(self): super(Gun, self).__init__() - self.energy = 10*GeV + self.energy = 10 * GeV self.particle = "mu-" self.multiplicity = 1 - self._position = (0.0,0.0,0.0) + self._position = (0.0, 0.0, 0.0) self._isotrop = False - self._direction = (0,0,1) + self._direction = (0, 0, 1) self._phiMin_EXTRA = {'help': "Minimal azimuthal angle for random distribution"} self.phiMin = None @@ -29,12 +31,11 @@ class Gun( ConfigHelper ): self._distribution_EXTRA = {'choices': ['uniform', 'cos(theta)', 'eta', 'pseudorapidity', - 'ffbar']} ## (1+cos^2 theta) + 'ffbar']} # (1+cos^2 theta) self._distribution = None - @property - def distribution( self ): + def distribution(self): """choose the distribution of the random direction for theta Options for random distributions: @@ -47,72 +48,76 @@ class Gun( ConfigHelper ): Setting a distribution will set isotrop = True """ return self._distribution + @distribution.setter - def distribution( self, val ): + def distribution(self, val): if val is None: return - possibleDistributions = ['uniform', 'cos(theta)', 'eta', 'pseudorapidity', 'ffbar'] ## (1+cos^2 theta) - if not isinstance( val, six.string_types): - raise RuntimeError( "malformed input '%s' for gun.distribution. Need a string : %s " % (val, ",".join(possibleDistributions)) ) + possibleDistributions = ['uniform', 'cos(theta)', 'eta', 'pseudorapidity', 'ffbar'] # (1+cos^2 theta) + if not isinstance(val, six.string_types): + raise RuntimeError("malformed input '%s' for gun.distribution. Need a string : %s " % + (val, ",".join(possibleDistributions))) if val not in possibleDistributions: - ## surround options by quots to be explicit - stringified = [ "'%s'" % _ for _ in possibleDistributions ] - raise RuntimeError( "Unknown distribution '%s', Use one of: %s " % (val, - ", ".join(stringified)) ) + # surround options by quots to be explicit + stringified = ["'%s'" % _ for _ in possibleDistributions] + raise RuntimeError("Unknown distribution '%s', Use one of: %s " % (val, + ", ".join(stringified))) self._distribution = val self._isotrop = True @property - def isotrop( self ): + def isotrop(self): """ isotropic distribution for the particle gun use the options phiMin, phiMax, thetaMin, and thetaMax to limit the range of randomly distributed directions if one of these options is not None the random distribution will be set to True and cannot be turned off! """ return self._isotrop + @isotrop.setter - def isotrop( self, val ): + def isotrop(self, val): """check that value is equivalent to bool""" try: - self._isotrop = ConfigHelper.makeBool( val ) + self._isotrop = ConfigHelper.makeBool(val) except RuntimeError: - raise RuntimeError( "malformed input '%s' for gun.isotrop " % val) + raise RuntimeError("malformed input '%s' for gun.isotrop " % val) if val and self.distribution is None: self.distribution = 'uniform' @property - def direction( self ): + def direction(self): """ direction of the particle gun, 3 vector """ return self._direction + @direction.setter - def direction( self, val ): + def direction(self, val): """ make sure the direction is parseable by boost, i.e. (1.0, 1.0, 1.0) """ - self._direction = ConfigHelper.makeTuple( val ) + self._direction = ConfigHelper.makeTuple(val) if len(self._direction) != 3: - raise RuntimeError(" gun.direction: malformed input '%s', needs to be a string representing a three vector " % val ) - + raise RuntimeError( + " gun.direction: malformed input '%s', needs to be a string representing a three vector " % val) @property - def position( self ): + def position(self): """ position of the particle gun, 3 vector """ return self._position + @position.setter - def position( self, val ): + def position(self, val): """check that the position is a three vector and can be parsed by ddg4""" - self._position = ConfigHelper.makeTuple( val ) + self._position = ConfigHelper.makeTuple(val) if len(self._position) != 3: - raise RuntimeError(" gun.position: malformed input '%s', needs to be a string representing a three vector " % val ) - + raise RuntimeError(" gun.position: malformed input '%s', needs to be a string representing a three vector " % val) - def setOptions( self, ddg4Gun ): + def setOptions(self, ddg4Gun): """set the starting properties of the DDG4 particle gun""" try: - ddg4Gun.energy = self.energy - ddg4Gun.particle = self.particle + ddg4Gun.energy = self.energy + ddg4Gun.particle = self.particle ddg4Gun.multiplicity = self.multiplicity - ddg4Gun.position = self.position - ddg4Gun.isotrop = self.isotrop - ddg4Gun.direction = self.direction + ddg4Gun.position = self.position + ddg4Gun.isotrop = self.isotrop + ddg4Gun.direction = self.direction ddg4Gun.Distribution = self.distribution if self.thetaMin is not None: ddg4Gun.ThetaMin = self.thetaMin @@ -126,6 +131,6 @@ class Gun( ConfigHelper ): if self.phiMax is not None: ddg4Gun.PhiMax = self.phiMax ddg4Gun.isotrop = True - except Exception as e: #pylint: disable=W0703 - logger.error("parsing gun options:\n%s\nException: %s " % (self, e )) + except Exception as e: # pylint: disable=W0703 + logger.error("parsing gun options:\n%s\nException: %s " % (self, e)) exit(1) diff --git a/DDG4/python/DDSim/Helper/Input.py b/DDG4/python/DDSim/Helper/Input.py index 917e358898fee2bbd24b20b747ba325ce1ddd4e8..89294546df7e0a8f067c845064dc78f49ace50b9 100644 --- a/DDG4/python/DDSim/Helper/Input.py +++ b/DDG4/python/DDSim/Helper/Input.py @@ -4,9 +4,11 @@ from __future__ import absolute_import, unicode_literals from DDSim.Helper.ConfigHelper import ConfigHelper import six -class Input( ConfigHelper ): + +class Input(ConfigHelper): """Configuration for the InputFiles""" - def __init__( self ): + + def __init__(self): super(Input, self).__init__() self.__parameters = {} @@ -15,15 +17,15 @@ class Input( ConfigHelper ): return self.__parameters @property - def _parameters( self ): + def _parameters(self): return self.__parameters @_parameters.setter - def _parameters( self, newParameters ): - if isinstance( newParameters, dict ): + def _parameters(self, newParameters): + if isinstance(newParameters, dict): for par, val in six.iteritems(newParameters): self.__parameters[par] = str(val) else: raise RuntimeError("Commandline setting of InputFileParameters is not supported, use a steeringFile: %s " - % newParameters ) + % newParameters) diff --git a/DDG4/python/DDSim/Helper/LCIO.py b/DDG4/python/DDSim/Helper/LCIO.py index 2f793eae73182ebdf135a082c6ef378726dbdbcd..95ea8f2454e713c2a857a49fa8c63f57f3908b95 100644 --- a/DDG4/python/DDSim/Helper/LCIO.py +++ b/DDG4/python/DDSim/Helper/LCIO.py @@ -3,20 +3,21 @@ from __future__ import absolute_import, unicode_literals from DDSim.Helper.Input import Input -class LCIO( Input ): + +class LCIO(Input): """Configuration for the generator-level InputFiles""" - def __init__( self ): + + def __init__(self): super(LCIO, self).__init__() self._parameters["MCParticleCollectionName"] = "MCParticle" @property - def mcParticleCollectionName( self ): + def mcParticleCollectionName(self): """Set the name of the collection containing the MCParticle input. Default is "MCParticle". """ return self._parameters["MCParticleCollectionName"] - + @mcParticleCollectionName.setter - def mcParticleCollectionName( self, val ): + def mcParticleCollectionName(self, val): self._parameters["MCParticleCollectionName"] = val - diff --git a/DDG4/python/DDSim/Helper/MagneticField.py b/DDG4/python/DDSim/Helper/MagneticField.py index 36263d2581f7223bd4b031352aa45ff344b52969..1597542e58bfa6149c51aabbf03a51a02db4e0aa 100644 --- a/DDG4/python/DDSim/Helper/MagneticField.py +++ b/DDG4/python/DDSim/Helper/MagneticField.py @@ -3,16 +3,18 @@ from __future__ import absolute_import, unicode_literals from g4units import mm, m from DDSim.Helper.ConfigHelper import ConfigHelper -class MagneticField( ConfigHelper ): + +class MagneticField(ConfigHelper): """Configuration for the magnetic field (stepper)""" - def __init__( self ): + + def __init__(self): super(MagneticField, self).__init__() self.stepper = "ClassicalRK4" self.equation = "Mag_UsualEqRhs" - self.eps_min = 5e-05*mm - self.eps_max = 0.001*mm - self.min_chord_step = 0.01*mm - self.delta_chord = 0.25*mm - self.delta_intersection = 0.001*mm - self.delta_one_step = 0.01*mm - self.largest_step = 10*m + self.eps_min = 5e-05 * mm + self.eps_max = 0.001 * mm + self.min_chord_step = 0.01 * mm + self.delta_chord = 0.25 * mm + self.delta_intersection = 0.001 * mm + self.delta_one_step = 0.01 * mm + self.largest_step = 10 * m diff --git a/DDG4/python/DDSim/Helper/Meta.py b/DDG4/python/DDSim/Helper/Meta.py index 0e26a2480c192feb9bc5e87e5f77406217a683ec..56a875edaba5018d4cd33be0cb67cf0649fdbc47 100644 --- a/DDG4/python/DDSim/Helper/Meta.py +++ b/DDG4/python/DDSim/Helper/Meta.py @@ -13,18 +13,20 @@ logger.setLevel(logging.INFO) from DDSim.Helper.ConfigHelper import ConfigHelper -class Meta( ConfigHelper ): + +class Meta(ConfigHelper): """Configuration for the LCIO output file settings""" - def __init__( self ): + + def __init__(self): super(Meta, self).__init__() - self._eventParameters_EXTRA = {'help': "Event parameters to write in every event. " \ + self._eventParameters_EXTRA = {'help': "Event parameters to write in every event. " "Use C/F/I ids to specify parameter type. E.g parameterName/F=0.42 to set a float parameter", 'nargs': '+'} self.eventParameters = [] - self._runNumberOffset_EXTRA = {'help': "The run number offset to write in slcio output file. "\ + self._runNumberOffset_EXTRA = {'help': "The run number offset to write in slcio output file. " "E.g setting it to 42 will start counting runs from 42 instead of 0"} self.runNumberOffset = 0 - self._eventNumberOffset_EXTRA = {'help': "The event number offset to write in slcio output file."\ + self._eventNumberOffset_EXTRA = {'help': "The event number offset to write in slcio output file." " E.g setting it to 42 will start counting events from 42 instead of 0"} self.eventNumberOffset = 0 @@ -32,23 +34,23 @@ class Meta( ConfigHelper ): """Parse the event parameters and return 3 event parameter dictionnaries, respectively for string, int and float parameters""" stringParameters, intParameters, floatParameters, allParameters = {}, {}, {}, [] for p in self.eventParameters: - parameterAndValue = p.split( "=", 1 ) + parameterAndValue = p.split("=", 1) if len(parameterAndValue) != 2: - raise SyntaxError("ERROR: Couldn't decode event parameter '%s'" %(p)) - parameterAndType = parameterAndValue[0].split( "/", 1 ) + raise SyntaxError("ERROR: Couldn't decode event parameter '%s'" % (p)) + parameterAndType = parameterAndValue[0].split("/", 1) if len(parameterAndType) != 2: - raise SyntaxError("ERROR: Couldn't decode event parameter '%s'" %(p)) + raise SyntaxError("ERROR: Couldn't decode event parameter '%s'" % (p)) pname = parameterAndType[0] ptype = parameterAndType[1] pvalue = parameterAndValue[1] if ptype.lower() not in ["c", "f", "i"]: - raise ValueError("ERROR: Event parameter '%s' with invalid type '%s'" %(pname, ptype)) + raise ValueError("ERROR: Event parameter '%s' with invalid type '%s'" % (pname, ptype)) if pname in allParameters: - raise RuntimeError("ERROR: Event parameter '%s' specified twice" %(pname)) + raise RuntimeError("ERROR: Event parameter '%s' specified twice" % (pname)) if not pvalue: - raise RuntimeError("ERROR: Event parameter '%s' has empty value" %(pname)) + raise RuntimeError("ERROR: Event parameter '%s' has empty value" % (pname)) allParameters.append(pname) - logger.info("Event parameter '%s', type '%s', value='%s'"%(pname, ptype, pvalue)) + logger.info("Event parameter '%s', type '%s', value='%s'" % (pname, ptype, pvalue)) if ptype.lower() == "c": stringParameters[pname] = pvalue elif ptype.lower() == "f": @@ -63,38 +65,38 @@ class Meta( ConfigHelper ): runHeader = {} parameters = vars(sim) for parName, parameter in six.iteritems(parameters): - if isinstance( parameter, ConfigHelper ): + if isinstance(parameter, ConfigHelper): options = parameter.getOptions() - for opt,optionsDict in six.iteritems(options): - runHeader["%s.%s"%(parName, opt)] = str(optionsDict['default']) + for opt, optionsDict in six.iteritems(options): + runHeader["%s.%s" % (parName, opt)] = str(optionsDict['default']) else: runHeader[parName] = str(parameter) - ### steeringFile content + # steeringFile content if sim.steeringFile and os.path.exists(sim.steeringFile) and os.path.isfile(sim.steeringFile): with open(sim.steeringFile) as sFile: runHeader["SteeringFileContent"] = sFile.read() - ### macroFile content + # macroFile content if sim.macroFile and os.path.exists(sim.macroFile) and os.path.isfile(sim.macroFile): with open(sim.macroFile) as mFile: runHeader["MacroFileContent"] = mFile.read() - ### add command line + # add command line if sim._argv: runHeader["CommandLine"] = " ".join(sim._argv) - ### add current working directory (where we call from) + # add current working directory (where we call from) runHeader["WorkingDirectory"] = os.getcwd() - ### ILCSoft, LCGEo location from environment variables, names from init_ilcsoft.sh + # ILCSoft, LCGEo location from environment variables, names from init_ilcsoft.sh runHeader["ILCSoft_location"] = os.environ.get("ILCSOFT", "Unknown") runHeader["lcgeo_location"] = os.environ.get("lcgeo_DIR", "Unknown") - ### add date - runHeader["DateUTC"] = str(datetime.datetime.utcnow())+" UTC" + # add date + runHeader["DateUTC"] = str(datetime.datetime.utcnow()) + " UTC" - ### add User + # add User import getpass runHeader["User"] = getpass.getuser() diff --git a/DDG4/python/DDSim/Helper/Output.py b/DDG4/python/DDSim/Helper/Output.py index 09e4c6afd3e130ae06136657282663c080b76dfb..d6a8b23d3921606de1be0a01b9258de314f800b2 100644 --- a/DDG4/python/DDSim/Helper/Output.py +++ b/DDG4/python/DDSim/Helper/Output.py @@ -4,50 +4,60 @@ from __future__ import absolute_import, unicode_literals from DDSim.Helper.ConfigHelper import ConfigHelper from DDSim.DD4hepSimulation import outputLevel -class Output( ConfigHelper ): + +class Output(ConfigHelper): """Configuration for the output levels of DDG4 components""" - def __init__( self ): + + def __init__(self): super(Output, self).__init__() - self._kernel_EXTRA = {'choices': (1,2,3,4,5,6,7,'VERBOSE','DEBUG', 'INFO', 'WARNING', 'ERROR', 'FATAL', 'ALWAYS')} + self._kernel_EXTRA = {'choices': (1, 2, 3, 4, 5, 6, 7, 'VERBOSE', 'DEBUG', + 'INFO', 'WARNING', 'ERROR', 'FATAL', 'ALWAYS')} self._kernel = outputLevel('INFO') - self._part_EXTRA = {'choices': (1,2,3,4,5,6,7,'VERBOSE','DEBUG', 'INFO', 'WARNING', 'ERROR', 'FATAL', 'ALWAYS')} + self._part_EXTRA = {'choices': (1, 2, 3, 4, 5, 6, 7, 'VERBOSE', 'DEBUG', + 'INFO', 'WARNING', 'ERROR', 'FATAL', 'ALWAYS')} self._part = outputLevel('INFO') - self._inputStage_EXTRA = {'choices': (1,2,3,4,5,6,7,'VERBOSE','DEBUG', 'INFO', 'WARNING', 'ERROR', 'FATAL', 'ALWAYS')} + self._inputStage_EXTRA = {'choices': (1, 2, 3, 4, 5, 6, 7, 'VERBOSE', 'DEBUG', + 'INFO', 'WARNING', 'ERROR', 'FATAL', 'ALWAYS')} self._inputStage = outputLevel('INFO') - self._random_EXTRA = {'choices': (1,2,3,4,5,6,7,'VERBOSE','DEBUG', 'INFO', 'WARNING', 'ERROR', 'FATAL', 'ALWAYS')} + self._random_EXTRA = {'choices': (1, 2, 3, 4, 5, 6, 7, 'VERBOSE', 'DEBUG', + 'INFO', 'WARNING', 'ERROR', 'FATAL', 'ALWAYS')} self._random = outputLevel('FATAL') @property - def inputStage( self ): + def inputStage(self): """Output level for input sources""" return self._inputStage + @inputStage.setter def inputStage(self, level): self._inputStage = outputLevel(level) @property - def kernel( self ): + def kernel(self): """Output level for Geant4 kernel""" return self._kernel + @kernel.setter def kernel(self, level): self._kernel = outputLevel(level) @property - def part( self ): + def part(self): """Output level for ParticleHandler""" return self._part + @part.setter def part(self, level): self._part = outputLevel(level) @property - def random( self ): + def random(self): """Output level for Random Number Generator setup""" return self._random + @random.setter def random(self, level): self._random = outputLevel(level) diff --git a/DDG4/python/DDSim/Helper/ParticleHandler.py b/DDG4/python/DDSim/Helper/ParticleHandler.py index 80bb7926c23a781aed08d643410eb5407a4346e9..f86fdcf7f3553a32eb2275bb9c2e43463490fa2b 100644 --- a/DDG4/python/DDSim/Helper/ParticleHandler.py +++ b/DDG4/python/DDSim/Helper/ParticleHandler.py @@ -9,16 +9,18 @@ logger.setLevel(logging.INFO) from DDSim.Helper.ConfigHelper import ConfigHelper -class ParticleHandler( ConfigHelper ): + +class ParticleHandler(ConfigHelper): """Configuration for the Particle Handler/ MCTruth treatment""" - def __init__( self ): + + def __init__(self): super(ParticleHandler, self).__init__() self._saveProcesses = ['Decay'] - self._minimalKineticEnergy = 1*MeV + self._minimalKineticEnergy = 1 * MeV self._keepAllParticles = False self._printEndTracking = False self._printStartTracking = False - self._minDistToParentVertex = 2.2e-14*mm + self._minDistToParentVertex = 2.2e-14 * mm self._enableDetailedHitsAndParticleInfo = False self._userParticleHandler = "Geant4TCUserParticleHandler" @@ -28,83 +30,90 @@ class ParticleHandler( ConfigHelper ): return self._enableDetailedHitsAndParticleInfo @enableDetailedHitsAndParticleInfo.setter - def enableDetailedHitsAndParticleInfo( self, val ): + def enableDetailedHitsAndParticleInfo(self, val): self._enableDetailedHitsAndParticleInfo = val @property - def userParticleHandler( self ): + def userParticleHandler(self): """Optionally enable an extended Particle Handler""" return self._userParticleHandler + @userParticleHandler.setter - def userParticleHandler( self, val ): + def userParticleHandler(self, val): self._userParticleHandler = val @property - def minDistToParentVertex( self ): + def minDistToParentVertex(self): """Minimal distance between particle vertex and endpoint of parent after which the vertexIsNotEndpointOfParent flag is set """ return self._minDistToParentVertex + @minDistToParentVertex.setter - def minDistToParentVertex( self, val ): + def minDistToParentVertex(self, val): self._minDistToParentVertex = val @property def saveProcesses(self): """List of processes to save, on command line give as whitespace separated string in quotation marks""" return self._saveProcesses + @saveProcesses.setter def saveProcesses(self, stringVal): - self._saveProcesses = ConfigHelper.makeList( stringVal ) + self._saveProcesses = ConfigHelper.makeList(stringVal) @property def minimalKineticEnergy(self): """MinimalKineticEnergy to store particles created in the tracking region""" return self._minimalKineticEnergy + @minimalKineticEnergy.setter - def minimalKineticEnergy( self, val ): + def minimalKineticEnergy(self, val): self._minimalKineticEnergy = val @property - def keepAllParticles( self ): + def keepAllParticles(self): """ Keep all created particles """ return self._keepAllParticles + @keepAllParticles.setter - def keepAllParticles( self, val ): + def keepAllParticles(self, val): self._keepAllParticles = val @property - def printStartTracking( self ): + def printStartTracking(self): """ Printout at Start of Tracking """ return self._printStartTracking + @printStartTracking.setter - def printStartTracking( self, val ): + def printStartTracking(self, val): self._printEndTracking = val @property - def printEndTracking( self ): + def printEndTracking(self): """ Printout at End of Tracking """ return self._printEndTracking + @printEndTracking.setter - def printEndTracking( self, val ): + def printEndTracking(self, val): self._printEndTracking = val - def setDumpDetailedParticleInfo( self, kernel, DDG4 ): + def setDumpDetailedParticleInfo(self, kernel, DDG4): #---- debug code from Markus for detailed dumps of hits and MC-truth assignement ------ # Add the particle dumper to associate the MC truth - evt = DDG4.EventAction(kernel,"Geant4ParticleDumpAction/ParticleDump") + evt = DDG4.EventAction(kernel, "Geant4ParticleDumpAction/ParticleDump") kernel.eventAction().adopt(evt) evt.enableUI() # Add the hit dumper BEFORE any hit truth is fixed - evt = DDG4.EventAction(kernel,"Geant4HitDumpAction/RawDump") + evt = DDG4.EventAction(kernel, "Geant4HitDumpAction/RawDump") kernel.eventAction().adopt(evt) evt.enableUI() # Add the hit dumper to the event action sequence - evt = DDG4.EventAction(kernel,"Geant4HitTruthHandler/HitTruth") + evt = DDG4.EventAction(kernel, "Geant4HitTruthHandler/HitTruth") kernel.eventAction().adopt(evt) evt.enableUI() # Add the hit dumper AFTER any hit truth is fixed. We should see the reduced track references - evt = DDG4.EventAction(kernel,"Geant4HitDumpAction/HitDump") + evt = DDG4.EventAction(kernel, "Geant4HitDumpAction/HitDump") kernel.eventAction().adopt(evt) evt.enableUI() @@ -121,13 +130,13 @@ class ParticleHandler( ConfigHelper ): exit(1) if self.userParticleHandler == "Geant4TCUserParticleHandler": - user = DDG4.Action(kernel,"%s/UserParticleHandler" % self.userParticleHandler) + user = DDG4.Action(kernel, "%s/UserParticleHandler" % self.userParticleHandler) try: user.TrackingVolume_Zmax = DDG4.tracker_region_zmax user.TrackingVolume_Rmax = DDG4.tracker_region_rmax logger.info(" *** definition of tracker region *** ") - logger.info(" tracker_region_zmax = " , user.TrackingVolume_Zmax) - logger.info(" tracker_region_rmax = " , user.TrackingVolume_Rmax) + logger.info(" tracker_region_zmax = ", user.TrackingVolume_Zmax) + logger.info(" tracker_region_rmax = ", user.TrackingVolume_Rmax) logger.info(" ************************************ ") except AttributeError as e: logger.error("Attribute of tracker region missing in detector model %s", e) diff --git a/DDG4/python/DDSim/Helper/Physics.py b/DDG4/python/DDSim/Helper/Physics.py index fe6d61a2331b38bb322c5de8fa82a0a186ca669b..a7eb4589daed94d1e8ff093a02fffe6f31885a59 100644 --- a/DDG4/python/DDSim/Helper/Physics.py +++ b/DDG4/python/DDSim/Helper/Physics.py @@ -7,26 +7,29 @@ from DDSim.Helper.ConfigHelper import ConfigHelper from g4units import mm import six -class Physics( ConfigHelper ): + +class Physics(ConfigHelper): """Configuration for the PhysicsList""" - def __init__( self ): + + def __init__(self): super(Physics, self).__init__() - self._rangecut = 0.7*mm + self._rangecut = 0.7 * mm self._list = "FTFP_BERT" self._decays = False self._pdgfile = None - self._rejectPDGs = {1,2,3,4,5,6,21,23,24,25} + self._rejectPDGs = {1, 2, 3, 4, 5, 6, 21, 23, 24, 25} self._zeroTimePDGs = {11, 13, 15, 17} @property - def rejectPDGs( self ): + def rejectPDGs(self): """Set of PDG IDs that will not be passed from the input record to Geant4. Quarks, gluons and W's Z's etc should not be treated by Geant4 """ return self._rejectPDGs + @rejectPDGs.setter - def rejectPDGs( self, val ): + def rejectPDGs(self, val): self._rejectPDGs = self.makeSet(val) @property @@ -36,12 +39,13 @@ class Physics( ConfigHelper ): The properTime of 0 indicates a documentation to add FSR to a lepton for example. """ return self._zeroTimePDGs + @zeroTimePDGs.setter def zeroTimePDGs(self, val): self._zeroTimePDGs = self.makeSet(val) @property - def rangecut( self ): + def rangecut(self): """ The global geant4 rangecut for secondary production Default is 0.7 mm as is the case in geant4 10 @@ -52,32 +56,34 @@ class Physics( ConfigHelper ): but this only works if range cut is not "None" """ return self._rangecut + @rangecut.setter - def rangecut( self, val ): + def rangecut(self, val): if val is None: self._rangecut = None return - if isinstance( val, six.string_types): + if isinstance(val, six.string_types): if val == "None": self._rangecut = None return self._rangecut = val @property - def pdgfile( self ): + def pdgfile(self): """ location of particle.tbl file containing extra particles and their lifetime information For example in $DD4HEP/examples/DDG4/examples/particle.tbl """ return self._pdgfile + @pdgfile.setter - def pdgfile( self, val ): + def pdgfile(self, val): if not val: self._pdgfile = None return - if not os.path.exists( val ): - raise RuntimeError( "PDGFile: %s not found" % os.path.abspath( val ) ) - self._pdgfile = os.path.abspath( val ) + if not os.path.exists(val): + raise RuntimeError("PDGFile: %s not found" % os.path.abspath(val)) + self._pdgfile = os.path.abspath(val) @property def decays(self): @@ -86,6 +92,7 @@ class Physics( ConfigHelper ): Only enable when creating a physics list not based on an existing Geant4 list! """ return self._decays + @decays.setter def decays(self, val): self._decays = val @@ -94,14 +101,15 @@ class Physics( ConfigHelper ): def list(self): """The name of the Geant4 Physics list.""" return self._list + @list.setter def list(self, val): self._list = val - def setupPhysics( self, kernel, name=None): + def setupPhysics(self, kernel, name=None): seq = kernel.physicsList() - seq.extends = name if name is not None else self.list - seq.decays = self.decays + seq.extends = name if name is not None else self.list + seq.decays = self.decays seq.enableUI() seq.dump() @@ -118,7 +126,7 @@ class Physics( ConfigHelper ): # Add global range cut if self.rangecut is not None: seq = kernel.physicsList() - rg = PhysicsList(kernel,'Geant4DefaultRangeCut/GlobalRangeCut') + rg = PhysicsList(kernel, 'Geant4DefaultRangeCut/GlobalRangeCut') rg.enableUI() seq.adopt(rg) rg.RangeCut = self.rangecut diff --git a/DDG4/python/DDSim/Helper/Random.py b/DDG4/python/DDSim/Helper/Random.py index af69edf8ae6fc5345c935c8db3d7dd31c9d9f4c8..46ac5322766d9789c58463e19d0e31b20efcb862 100644 --- a/DDG4/python/DDSim/Helper/Random.py +++ b/DDG4/python/DDSim/Helper/Random.py @@ -10,9 +10,11 @@ logger.setLevel(logging.INFO) from DDSim.Helper.ConfigHelper import ConfigHelper + class Random (ConfigHelper): """Properties for the random number generator""" - def __init__ (self): + + def __init__(self): super(Random, self).__init__() self.seed = None self.type = None @@ -21,8 +23,8 @@ class Random (ConfigHelper): self.file = None self._random = None - self._enableEventSeed_EXTRA = {'help': "If True, calculate random seed for each event based" \ - "on eventID and runID\nAllows reproducibility even when" \ + self._enableEventSeed_EXTRA = {'help': "If True, calculate random seed for each event based" + "on eventID and runID\nAllows reproducibility even when" "SkippingEvents"} self.enableEventSeed = False @@ -36,11 +38,11 @@ class Random (ConfigHelper): """ if self._random: return self._random - self._random = DDG4.Action(kernel,'Geant4Random/R1') + self._random = DDG4.Action(kernel, 'Geant4Random/R1') if self.seed is None: - ## System provided random source, truely random according to documentation - self.seed = random.SystemRandom().randint(0, 2**31-1) + # System provided random source, truely random according to documentation + self.seed = random.SystemRandom().randint(0, 2**31 - 1) logger.info("Choosing random seed for you: %s", self.seed) self._random.Seed = self.seed @@ -52,9 +54,9 @@ class Random (ConfigHelper): self._random.initialize() if self.seed is not None and self.enableEventSeed: - self._eventseed = DDG4.RunAction(kernel,'Geant4EventSeed/EventSeeder1') + self._eventseed = DDG4.RunAction(kernel, 'Geant4EventSeed/EventSeeder1') - ## Needs to be called after initilisation + # Needs to be called after initilisation if output <= 3: self._random.showStatus() return self._random diff --git a/DDG4/python/SystemOfUnits.py b/DDG4/python/SystemOfUnits.py index d7a049a71eceecd96a1626e901bf19d195543693..7c5e40de541ea22417edb8d04ac9df7c134ac5b3 100644 --- a/DDG4/python/SystemOfUnits.py +++ b/DDG4/python/SystemOfUnits.py @@ -1,5 +1,5 @@ #========================================================================== -# AIDA Detector description implementation +# AIDA Detector description implementation #-------------------------------------------------------------------------- # Copyright (C) Organisation europeenne pour la Recherche nucleaire (CERN) # All rights reserved. diff --git a/DDG4/python/checkGeometry.py b/DDG4/python/checkGeometry.py index b5e6dcec122847b414991431cc7495ec0098c62d..de6252671bde927596289715b25044ef1eed0ff2 100755 --- a/DDG4/python/checkGeometry.py +++ b/DDG4/python/checkGeometry.py @@ -1,6 +1,6 @@ #!/bin/python #========================================================================== -# AIDA Detector description implementation +# AIDA Detector description implementation #-------------------------------------------------------------------------- # Copyright (C) Organisation europeenne pour la Recherche nucleaire (CERN) # All rights reserved. @@ -11,7 +11,10 @@ #========================================================================== from __future__ import absolute_import, unicode_literals -import sys, errno, optparse, logging +import sys +import errno +import optparse +import logging logging.basicConfig(format='%(levelname)s: %(message)s') logger = logging.getLogger(__name__) @@ -22,41 +25,41 @@ parser.description = "TGeo Geometry checking." parser.formatter.width = 132 parser.add_option("-c", "--compact", dest="compact", default=None, help="Define LCCDD style compact xml input", - metavar="<FILE>") + metavar="<FILE>") -parser.add_option("-f","--full", - dest="full", default=False, +parser.add_option("-f", "--full", + dest="full", default=False, help="Full geometry checking", - metavar="<boolean>") + metavar="<boolean>") parser.add_option("-n", "--ntracks", - dest="num_tracks", default=1000000, + dest="num_tracks", default=1000000, help="Number of tracks [requires '--full']", - metavar="<integer>") + metavar="<integer>") parser.add_option("-x", "--vx", - dest="vx", default=0.0, + dest="vx", default=0.0, help="X-position of track origine vertex [requires '--full']", - metavar="<double>") + metavar="<double>") parser.add_option("-y", "--vy", - dest="vy", default=0.0, + dest="vy", default=0.0, help="Y-position of track origine vertex [requires '--full']", - metavar="<double>") + metavar="<double>") parser.add_option("-z", "--vz", - dest="vz", default=0.0, + dest="vz", default=0.0, help="Z-position of track origine vertex [requires '--full']", - metavar="<double>") + metavar="<double>") parser.add_option("-o", "--option", dest="option", default='ob', help="TGeoManager geometry check option default:ob", - metavar="<string>") + metavar="<string>") (opts, args) = parser.parse_args() if opts.compact is None: - logger.info(" %s",parser.format_help()) + logger.info(" %s", parser.format_help()) sys.exit(1) try: @@ -64,27 +67,27 @@ try: from ROOT import gROOT gROOT.SetBatch(1) except ImportError as X: - logger.error('PyROOT interface not accessible: %s',str(X)) + logger.error('PyROOT interface not accessible: %s', str(X)) sys.exit(errno.ENOENT) try: import dd4hep except ImportError as X: - logger.error('dd4hep python interface not accessible: %s',str(X)) + logger.error('dd4hep python interface not accessible: %s', str(X)) sys.exit(errno.ENOENT) dd4hep.setPrintLevel(dd4hep.OutputLevel.ERROR) -logger.info('+++%s\n+++ Loading compact geometry:%s\n+++%s',120*'=',opts.compact,120*'=') +logger.info('+++%s\n+++ Loading compact geometry:%s\n+++%s', 120 * '=', opts.compact, 120 * '=') description = dd4hep.Detector.getInstance() description.fromXML(opts.compact) opts.num_tracks = int(opts.num_tracks) opts.vx = float(opts.vx) opts.vy = float(opts.vy) opts.vz = float(opts.vz) -logger.info('+++%s\n+++ Checking geometry:%s full-check:%s\n+++%s',120*'=',opts.compact,opts.full,120*'=') +logger.info('+++%s\n+++ Checking geometry:%s full-check:%s\n+++%s', 120 * '=', opts.compact, opts.full, 120 * '=') if opts.full: - logger.info('+++ # tracks:%d vertex:(%7.3f, %7.3f, %7.3f) [cm]',opts.num_tracks,opts.vx,opts.vy,opts.vz) - description.manager().CheckGeometryFull(opts.num_tracks,opts.vx,opts.vy,opts.vz,opts.option) + logger.info('+++ # tracks:%d vertex:(%7.3f, %7.3f, %7.3f) [cm]', opts.num_tracks, opts.vx, opts.vy, opts.vz) + description.manager().CheckGeometryFull(opts.num_tracks, opts.vx, opts.vy, opts.vz, opts.option) else: description.manager().CheckGeometry() # diff --git a/DDG4/python/checkOverlaps.py b/DDG4/python/checkOverlaps.py index b687439b898571d2dca0b9bf1099ec5725426e50..d1aea73d0dfb93aedb1c05ad58b10f6f068f0348 100755 --- a/DDG4/python/checkOverlaps.py +++ b/DDG4/python/checkOverlaps.py @@ -1,6 +1,6 @@ #!/bin/python #========================================================================== -# AIDA Detector description implementation +# AIDA Detector description implementation #-------------------------------------------------------------------------- # Copyright (C) Organisation europeenne pour la Recherche nucleaire (CERN) # All rights reserved. @@ -11,7 +11,10 @@ #========================================================================== from __future__ import absolute_import, unicode_literals -import sys, errno, optparse, logging +import sys +import errno +import optparse +import logging logging.basicConfig(format='%(levelname)s: %(message)s') logger = logging.getLogger(__name__) @@ -22,25 +25,25 @@ parser.formatter.width = 132 parser.description = "Check TGeo geometries for overlaps." parser.add_option("-c", "--compact", dest="compact", default=None, help="Define LCCDD style compact xml input", - metavar="<FILE>") + metavar="<FILE>") parser.add_option("-p", "--print", - dest="print_overlaps", default=True, + dest="print_overlaps", default=True, help="Print overlap information to standard output (default:True)", - metavar="<boolean>") -parser.add_option("-q", "--quiet", + metavar="<boolean>") +parser.add_option("-q", "--quiet", action="store_false", dest="print_overlaps", help="Do not print (disable --print)") parser.add_option("-t", "--tolerance", dest="tolerance", default=0.1, help="Overlap checking tolerance. Unit is in [mm]. (default:0.1 mm)", - metavar="<double number>") + metavar="<double number>") parser.add_option("-o", "--option", dest="option", default='', help="Overlap checking option ('' or 's')", - metavar="<string>") + metavar="<string>") (opts, args) = parser.parse_args() if opts.compact is None: - logger.info(" %s",parser.format_help()) + logger.info(" %s", parser.format_help()) sys.exit(1) try: @@ -48,29 +51,30 @@ try: from ROOT import gROOT gROOT.SetBatch(1) except ImportError as X: - logger.error('PyROOT interface not accessible: %s',str(X)) - logger.error("%s",parser.format_help()) + logger.error('PyROOT interface not accessible: %s', str(X)) + logger.error("%s", parser.format_help()) sys.exit(errno.ENOENT) try: import dd4hep except ImportError as X: - logger.error('dd4hep python interface not accessible: %s',str(X)) - logger.error("%s",parser.format_help()) + logger.error('dd4hep python interface not accessible: %s', str(X)) + logger.error("%s", parser.format_help()) sys.exit(errno.ENOENT) # # opts.tolerance = float(opts.tolerance) dd4hep.setPrintLevel(dd4hep.OutputLevel.ERROR) -logger.info('+++%s\n+++ Loading compact geometry:%s\n+++%s',120*'=',opts.compact,120*'=') +logger.info('+++%s\n+++ Loading compact geometry:%s\n+++%s', 120 * '=', opts.compact, 120 * '=') description = dd4hep.Detector.getInstance() description.fromXML(opts.compact) -logger.info('+++%s\n+++ Checking overlaps of geometry:%s tolerance:%f option:%s\n+++%s',120*'=',opts.compact,opts.tolerance,opts.option,120*'=') -description.manager().CheckOverlaps(opts.tolerance,opts.option) +logger.info('+++%s\n+++ Checking overlaps of geometry:%s tolerance:%f option:%s\n+++%s', + 120 * '=', opts.compact, opts.tolerance, opts.option, 120 * '=') +description.manager().CheckOverlaps(opts.tolerance, opts.option) # # if opts.print_overlaps: - logger.info('+++%s\n+++ Printing overlaps of geometry:%s\n+++%s',120*'=',opts.compact,120*'=') + logger.info('+++%s\n+++ Printing overlaps of geometry:%s\n+++%s', 120 * '=', opts.compact, 120 * '=') description.manager().PrintOverlaps() # # diff --git a/DDG4/python/g4MaterialScan.py b/DDG4/python/g4MaterialScan.py index 8d58d8dbd93ce0b8eb81b4133c341627cacf7761..6ac45b2c19ec63c343cfa97cace083909b3d370f 100644 --- a/DDG4/python/g4MaterialScan.py +++ b/DDG4/python/g4MaterialScan.py @@ -1,6 +1,6 @@ #!/bin/python #========================================================================== -# AIDA Detector description implementation +# AIDA Detector description implementation #-------------------------------------------------------------------------- # Copyright (C) Organisation europeenne pour la Recherche nucleaire (CERN) # All rights reserved. @@ -11,17 +11,23 @@ #========================================================================== from __future__ import absolute_import, unicode_literals -import os, sys, errno, optparse, logging +import os +import sys +import errno +import optparse +import logging logging.basicConfig(format='%(levelname)s: %(message)s') logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) + def printOpts(opts): o = eval(str(opts)) prefix = sys.argv[0].split(os.sep)[-1] - for name,value in o.items(): - logger.info('%s > %-18s %s [%s]',prefix,name+':',str(value),str(value.__class__)) + for name, value in o.items(): + logger.info('%s > %-18s %s [%s]', prefix, name + ':', str(value), str(value.__class__)) + def materialScan(opts): kernel = DDG4.Kernel() @@ -37,21 +43,21 @@ def materialScan(opts): if sd.isValid(): typ = sd.type() if typ in geant4.sensitive_types: - geant4.setupDetector(o.name(),geant4.sensitive_types[typ]) + geant4.setupDetector(o.name(), geant4.sensitive_types[typ]) sdtyp = geant4.sensitive_types[typ] else: - logger.error('+++ %-32s type:%-12s --> Unknown Sensitive type: %s',o.name(), typ, sdtyp) + logger.error('+++ %-32s type:%-12s --> Unknown Sensitive type: %s', o.name(), typ, sdtyp) sys.exit(errno.EINVAL) gun = geant4.setupGun("Gun", Standalone=True, particle='geantino', - energy=20*SystemOfUnits.GeV, + energy=20 * SystemOfUnits.GeV, position=opts.position, direction=opts.direction, multiplicity=1, - isotrop=False ) - scan = DDG4.SteppingAction(kernel,'Geant4MaterialScanner/MaterialScan') + isotrop=False) + scan = DDG4.SteppingAction(kernel, 'Geant4MaterialScanner/MaterialScan') kernel.steppingAction().adopt(scan) # Now build the physics list: @@ -73,34 +79,35 @@ def materialScan(opts): kernel.run() kernel.terminate() return 0 - + + parser = optparse.OptionParser() parser.formatter.width = 132 parser.description = 'Material scan using Geant4.' parser.add_option('-c', '--compact', dest='compact', default=None, help='Define LCCDD style compact xml input', - metavar='<FILE>') + metavar='<FILE>') parser.add_option('-P', '--print', - dest='print_level', default=2, + dest='print_level', default=2, help='Set dd4hep print level.', - metavar='<int>') + metavar='<int>') parser.add_option('-p', '--position', - dest='position', default='0.0,0.0,0.0', + dest='position', default='0.0,0.0,0.0', help='Start position of the material scan. [give tuple "x,y,z" as string]', - metavar='<tuple>') + metavar='<tuple>') parser.add_option('-d', '--direction', - dest='direction', default='0.0,1.0,0.0', + dest='direction', default='0.0,1.0,0.0', help='Direction of the material scan. [give tuple "x,y,z" as string]', - metavar='<tuple>') + metavar='<tuple>') (opts, args) = parser.parse_args() if opts.compact is None: - logger.info("%s",parser.format_help()) + logger.info("%s", parser.format_help()) sys.exit(1) -opts.position=eval('('+opts.position+')') -opts.direction=eval('('+opts.direction+')') +opts.position = eval('(' + opts.position + ')') +opts.direction = eval('(' + opts.direction + ')') printOpts(opts) try: @@ -113,11 +120,12 @@ except ImportError as X: sys.exit(errno.ENOENT) try: - import DDG4, SystemOfUnits + import DDG4 + import SystemOfUnits except ImportError as X: logger.error('DDG4 python interface not accessible: %s', X) logger.info(parser.format_help()) sys.exit(errno.ENOENT) # ret = materialScan(opts) -sys.exit(ret); +sys.exit(ret) diff --git a/DDG4/python/g4units.py b/DDG4/python/g4units.py index 2d348d46b8c41023e21439051864fdd14155e200..b687973f1d5b63419203a5bb04194b0b1d82c63d 100644 --- a/DDG4/python/g4units.py +++ b/DDG4/python/g4units.py @@ -50,49 +50,49 @@ # from __future__ import absolute_import, unicode_literals, division -millimeter = 1. -millimeter2 = millimeter*millimeter -millimeter3 = millimeter*millimeter*millimeter +millimeter = 1. +millimeter2 = millimeter * millimeter +millimeter3 = millimeter * millimeter * millimeter -centimeter = 10.*millimeter -centimeter2 = centimeter*centimeter -centimeter3 = centimeter*centimeter*centimeter +centimeter = 10. * millimeter +centimeter2 = centimeter * centimeter +centimeter3 = centimeter * centimeter * centimeter -meter = 1000.*millimeter -meter2 = meter*meter -meter3 = meter*meter*meter +meter = 1000. * millimeter +meter2 = meter * meter +meter3 = meter * meter * meter -kilometer = 1000.*meter -kilometer2 = kilometer*kilometer -kilometer3 = kilometer*kilometer*kilometer +kilometer = 1000. * meter +kilometer2 = kilometer * kilometer +kilometer3 = kilometer * kilometer * kilometer -parsec = 3.0856775807e+16*meter +parsec = 3.0856775807e+16 * meter -micrometer = 1.e-6 *meter -nanometer = 1.e-9 *meter -angstrom = 1.e-10*meter -fermi = 1.e-15*meter +micrometer = 1.e-6 * meter +nanometer = 1.e-9 * meter +angstrom = 1.e-10 * meter +fermi = 1.e-15 * meter -barn = 1.e-28*meter2 -millibarn = 1.e-3 *barn -microbarn = 1.e-6 *barn -nanobarn = 1.e-9 *barn -picobarn = 1.e-12*barn +barn = 1.e-28 * meter2 +millibarn = 1.e-3 * barn +microbarn = 1.e-6 * barn +nanobarn = 1.e-9 * barn +picobarn = 1.e-12 * barn # symbols -mm = millimeter +mm = millimeter mm2 = millimeter2 mm3 = millimeter3 -cm = centimeter +cm = centimeter cm2 = centimeter2 cm3 = centimeter3 -m = meter +m = meter m2 = meter2 m3 = meter3 -km = kilometer +km = kilometer km2 = kilometer2 km3 = kilometer3 @@ -101,59 +101,59 @@ pc = parsec # # Angle # -radian = 1. -milliradian = 1.e-3*radian -degree = (3.14159265358979323846/180.0)*radian +radian = 1. +milliradian = 1.e-3 * radian +degree = (3.14159265358979323846 / 180.0) * radian -steradian = 1. +steradian = 1. # symbols -rad = radian +rad = radian mrad = milliradian -sr = steradian -deg = degree +sr = steradian +deg = degree # # Time [T] # -nanosecond = 1. -second = 1.e+9 *nanosecond -millisecond = 1.e-3 *second -microsecond = 1.e-6 *second -picosecond = 1.e-12*second -femtosecond = 1.e-15*second +nanosecond = 1. +second = 1.e+9 * nanosecond +millisecond = 1.e-3 * second +microsecond = 1.e-6 * second +picosecond = 1.e-12 * second +femtosecond = 1.e-15 * second -hertz = 1./second -kilohertz = 1.e+3*hertz -megahertz = 1.e+6*hertz +hertz = 1. / second +kilohertz = 1.e+3 * hertz +megahertz = 1.e+6 * hertz # symbols ns = nanosecond -s = second +s = second ms = millisecond # # Electric charge [Q] # eplus = 1. # positron charge -e_SI = 1.60217733e-19 # positron charge in coulomb -coulomb = eplus/e_SI # coulomb = 6.24150 e+18 * eplus +e_SI = 1.60217733e-19 # positron charge in coulomb +coulomb = eplus / e_SI # coulomb = 6.24150 e+18 * eplus # # Energy [E] # megaelectronvolt = 1. -electronvolt = 1.e-6*megaelectronvolt -kiloelectronvolt = 1.e-3*megaelectronvolt -gigaelectronvolt = 1.e+3*megaelectronvolt -teraelectronvolt = 1.e+6*megaelectronvolt -petaelectronvolt = 1.e+9*megaelectronvolt +electronvolt = 1.e-6 * megaelectronvolt +kiloelectronvolt = 1.e-3 * megaelectronvolt +gigaelectronvolt = 1.e+3 * megaelectronvolt +teraelectronvolt = 1.e+6 * megaelectronvolt +petaelectronvolt = 1.e+9 * megaelectronvolt -joule = electronvolt/e_SI # joule = 6.24150 e+12 * MeV +joule = electronvolt / e_SI # joule = 6.24150 e+12 * MeV # symbols MeV = megaelectronvolt -eV = electronvolt +eV = electronvolt keV = kiloelectronvolt GeV = gigaelectronvolt TeV = teraelectronvolt @@ -162,79 +162,79 @@ PeV = petaelectronvolt # # Mass [E][T^2][L^-2] # -kilogram = joule*second*second/(meter*meter) -gram = 1.e-3*kilogram -milligram = 1.e-3*gram +kilogram = joule * second * second / (meter * meter) +gram = 1.e-3 * kilogram +milligram = 1.e-3 * gram # symbols kg = kilogram -g = gram +g = gram mg = milligram # # Power [E][T^-1] # -watt = joule/second # watt = 6.24150 e+3 * MeV/ns +watt = joule / second # watt = 6.24150 e+3 * MeV/ns # # Force [E][L^-1] # -newton = joule/meter # newton = 6.24150 e+9 * MeV/mm +newton = joule / meter # newton = 6.24150 e+9 * MeV/mm # # Pressure [E][L^-3] # -hep_pascal = newton/m2 # pascal = 6.24150 e+3 * MeV/mm3 -pascal = hep_pascal # a trick to avoid warnings -bar = 100000*pascal # bar = 6.24150 e+8 * MeV/mm3 -atmosphere = 101325*pascal # atm = 6.32420 e+8 * MeV/mm3 +hep_pascal = newton / m2 # pascal = 6.24150 e+3 * MeV/mm3 +pascal = hep_pascal # a trick to avoid warnings +bar = 100000 * pascal # bar = 6.24150 e+8 * MeV/mm3 +atmosphere = 101325 * pascal # atm = 6.32420 e+8 * MeV/mm3 # # Electric current [Q][T^-1] # -ampere = coulomb/second # ampere = 6.24150 e+9 * eplus/ns -milliampere = 1.e-3*ampere -microampere = 1.e-6*ampere -nanoampere = 1.e-9*ampere +ampere = coulomb / second # ampere = 6.24150 e+9 * eplus/ns +milliampere = 1.e-3 * ampere +microampere = 1.e-6 * ampere +nanoampere = 1.e-9 * ampere # # Electric potential [E][Q^-1] # -megavolt = megaelectronvolt/eplus -kilovolt = 1.e-3*megavolt -volt = 1.e-6*megavolt +megavolt = megaelectronvolt / eplus +kilovolt = 1.e-3 * megavolt +volt = 1.e-6 * megavolt # # Electric resistance [E][T][Q^-2] # -ohm = volt/ampere # ohm = 1.60217e-16*(MeV/eplus)/(eplus/ns) +ohm = volt / ampere # ohm = 1.60217e-16*(MeV/eplus)/(eplus/ns) # # Electric capacitance [Q^2][E^-1] # -farad = coulomb/volt # farad = 6.24150e+24 * eplus/Megavolt -millifarad = 1.e-3*farad -microfarad = 1.e-6*farad -nanofarad = 1.e-9*farad -picofarad = 1.e-12*farad +farad = coulomb / volt # farad = 6.24150e+24 * eplus/Megavolt +millifarad = 1.e-3 * farad +microfarad = 1.e-6 * farad +nanofarad = 1.e-9 * farad +picofarad = 1.e-12 * farad # # Magnetic Flux [T][E][Q^-1] # -weber = volt*second # weber = 1000*megavolt*ns +weber = volt * second # weber = 1000*megavolt*ns # # Magnetic Field [T][E][Q^-1][L^-2] # -tesla = volt*second/meter2 # tesla =0.001*megavolt*ns/mm2 +tesla = volt * second / meter2 # tesla =0.001*megavolt*ns/mm2 -gauss = 1.e-4*tesla -kilogauss = 1.e-1*tesla +gauss = 1.e-4 * tesla +kilogauss = 1.e-1 * tesla # # Inductance [T^2][E][Q^-2] # -henry = weber/ampere # henry = 1.60217e-7*MeV*(ns/eplus)**2 +henry = weber / ampere # henry = 1.60217e-7*MeV*(ns/eplus)**2 # # Temperature @@ -249,13 +249,13 @@ mole = 1. # # Activity [T^-1] # -becquerel = 1./second +becquerel = 1. / second curie = 3.7e+10 * becquerel # # Absorbed dose [L^2][T^-2] # -gray = joule/kilogram +gray = joule / kilogram # # Luminous intensity [I] @@ -265,16 +265,16 @@ candela = 1. # # Luminous flux [I] # -lumen = candela*steradian +lumen = candela * steradian # # Illuminance [I][L^-2] # -lux = lumen/meter2 +lux = lumen / meter2 # # Miscellaneous # -perCent = 0.01 +perCent = 0.01 perThousand = 0.001 -perMillion = 0.000001 +perMillion = 0.000001 diff --git a/DDRec/python/DDRec.py b/DDRec/python/DDRec.py index b6521971e339aec5eb3cf36d5449c15fae16c33d..a8e4f584a18937183657352ef90ee0869f8241d8 100644 --- a/DDRec/python/DDRec.py +++ b/DDRec/python/DDRec.py @@ -1,5 +1,5 @@ #========================================================================== -# AIDA Detector description implementation +# AIDA Detector description implementation #-------------------------------------------------------------------------- # Copyright (C) Organisation europeenne pour la Recherche nucleaire (CERN) # All rights reserved. @@ -17,83 +17,89 @@ logger.setLevel(logging.INFO) import dd4hep as core + def loadDDRec(): from ROOT import gSystem result = gSystem.Load("libDDRec") if result < 0: - raise Exception('DDG4.py: Failed to load the DDG4 library libDDRec: '+gSystem.GetErrorStr()) + raise Exception('DDG4.py: Failed to load the DDG4 library libDDRec: ' + gSystem.GetErrorStr()) from ROOT import dd4hep as module core.rec = module.rec return module.rec + # We are nearly there .... name_space = __import__(__name__) -def import_namespace_item(ns,nam): - scope = getattr(name_space,ns) - attr = getattr(scope,nam) - setattr(name_space,nam,attr) + + +def import_namespace_item(ns, nam): + scope = getattr(name_space, ns) + attr = getattr(scope, nam) + setattr(name_space, nam, attr) return attr + #--------------------------------------------------------------------------- # try: rec = loadDDRec() except Exception as X: - logger.error('+--%-100s--+',100*'-') - logger.error('| %-100s |','Failed to load DDRec library:') - logger.error('| %-100s |',str(X)) - logger.error('+--%-100s--+',100*'-') + logger.error('+--%-100s--+', 100 * '-') + logger.error('| %-100s |', 'Failed to load DDRec library:') + logger.error('| %-100s |', str(X)) + logger.error('+--%-100s--+', 100 * '-') exit(1) def import_rec(): - import_namespace_item('rec','CellIDPositionConverter') - - import_namespace_item('rec','FixedPadSizeTPCStruct') - - import_namespace_item('rec','ZPlanarStruct') - import_namespace_item('rec','ZPlanarStruct::LayerLayout') - - import_namespace_item('rec','ZDiskPetalsStruct') - import_namespace_item('rec','ZDiskPetalsStruct::LayerLayout') - - import_namespace_item('rec','ConicalSupportStruct') - - import_namespace_item('rec','LayeredCalorimeterStruct') - import_namespace_item('rec','LayeredCalorimeterStruct::Layer') - - import_namespace_item('rec','NeighbourSurfacesStruct') - import_namespace_item('rec','DetectorSurfaces') - - import_namespace_item('rec','IMaterial') - import_namespace_item('rec','ISurface') - import_namespace_item('rec','ICylinder') - import_namespace_item('rec','ICone') - import_namespace_item('rec','SurfaceType') - import_namespace_item('rec','MaterialData') - import_namespace_item('rec','MaterialManager') - import_namespace_item('rec','VolSurfaceBase') - import_namespace_item('rec','VolSurface') - import_namespace_item('rec','VolSurfaceList') - import_namespace_item('rec','VolPlaneImpl') - import_namespace_item('rec','VolCylinderImpl') - import_namespace_item('rec','VolConeImpl') - import_namespace_item('rec','Surface') - import_namespace_item('rec','CylinderSurface') - import_namespace_item('rec','ConeSurface') - import_namespace_item('rec','SurfaceList') - import_namespace_item('rec','Vector2D') - import_namespace_item('rec','Vector3D') - import_namespace_item('rec','SurfaceManager') - - import_namespace_item('rec','FixedPadSizeTPCData') - import_namespace_item('rec','ZPlanarData') - import_namespace_item('rec','ZDiskPetalsData') - import_namespace_item('rec','ConicalSupportData') - import_namespace_item('rec','LayeredCalorimeterData') - import_namespace_item('rec','NeighbourSurfacesData') + import_namespace_item('rec', 'CellIDPositionConverter') + + import_namespace_item('rec', 'FixedPadSizeTPCStruct') + + import_namespace_item('rec', 'ZPlanarStruct') + import_namespace_item('rec', 'ZPlanarStruct::LayerLayout') + + import_namespace_item('rec', 'ZDiskPetalsStruct') + import_namespace_item('rec', 'ZDiskPetalsStruct::LayerLayout') + + import_namespace_item('rec', 'ConicalSupportStruct') + + import_namespace_item('rec', 'LayeredCalorimeterStruct') + import_namespace_item('rec', 'LayeredCalorimeterStruct::Layer') + + import_namespace_item('rec', 'NeighbourSurfacesStruct') + import_namespace_item('rec', 'DetectorSurfaces') + + import_namespace_item('rec', 'IMaterial') + import_namespace_item('rec', 'ISurface') + import_namespace_item('rec', 'ICylinder') + import_namespace_item('rec', 'ICone') + import_namespace_item('rec', 'SurfaceType') + import_namespace_item('rec', 'MaterialData') + import_namespace_item('rec', 'MaterialManager') + import_namespace_item('rec', 'VolSurfaceBase') + import_namespace_item('rec', 'VolSurface') + import_namespace_item('rec', 'VolSurfaceList') + import_namespace_item('rec', 'VolPlaneImpl') + import_namespace_item('rec', 'VolCylinderImpl') + import_namespace_item('rec', 'VolConeImpl') + import_namespace_item('rec', 'Surface') + import_namespace_item('rec', 'CylinderSurface') + import_namespace_item('rec', 'ConeSurface') + import_namespace_item('rec', 'SurfaceList') + import_namespace_item('rec', 'Vector2D') + import_namespace_item('rec', 'Vector3D') + import_namespace_item('rec', 'SurfaceManager') + + import_namespace_item('rec', 'FixedPadSizeTPCData') + import_namespace_item('rec', 'ZPlanarData') + import_namespace_item('rec', 'ZDiskPetalsData') + import_namespace_item('rec', 'ConicalSupportData') + import_namespace_item('rec', 'LayeredCalorimeterData') + import_namespace_item('rec', 'NeighbourSurfacesData') + # Now instantiate the entire thing import_rec() -std_list_ISurface = core.std_list('ISurface*') +std_list_ISurface = core.std_list('ISurface*') std_list_VolSurface = core.std_list('VolSurface') diff --git a/DDRec/python/dumpDetectorData.py b/DDRec/python/dumpDetectorData.py index e8af8ded259d819227e2c4bfcb43082ec506ff4f..3ee246b96f5674bb33a6dd2e29584919596829d1 100644 --- a/DDRec/python/dumpDetectorData.py +++ b/DDRec/python/dumpDetectorData.py @@ -1,6 +1,6 @@ #!/bin/python #========================================================================== -# AIDA Detector description implementation +# AIDA Detector description implementation #-------------------------------------------------------------------------- # Copyright (C) Organisation europeenne pour la Recherche nucleaire (CERN) # All rights reserved. @@ -11,13 +11,17 @@ #========================================================================== from __future__ import absolute_import, unicode_literals -import sys, errno, optparse, logging +import sys +import errno +import optparse +import logging logging.basicConfig(format='%(levelname)s: %(message)s') logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) -def dumpData( det ): + +def dumpData(det): try: dat = DDRec.FixedPadSizeTPCData(det) logger.info(dat.toString()) @@ -55,12 +59,12 @@ parser.formatter.width = 132 parser.description = "Dump detector data objects from DDRec" parser.add_option("-c", "--compact", dest="compact", default=None, help="Define LCCDD style compact xml input", - metavar="<FILE>") + metavar="<FILE>") (opts, args) = parser.parse_args() if opts.compact is None: - logger.info(" %s",parser.format_help()) + logger.info(" %s", parser.format_help()) sys.exit(1) try: @@ -68,47 +72,46 @@ try: from ROOT import gROOT gROOT.SetBatch(1) except ImportError as X: - logger.error('PyROOT interface not accessible: %s',str(X)) - logger.error("%s",parser.format_help()) + logger.error('PyROOT interface not accessible: %s', str(X)) + logger.error("%s", parser.format_help()) sys.exit(errno.ENOENT) try: import dd4hep except ImportError as X: - logger.error('dd4hep python interface not accessible: %s',str(X)) - logger.error("%s",parser.format_help()) + logger.error('dd4hep python interface not accessible: %s', str(X)) + logger.error("%s", parser.format_help()) sys.exit(errno.ENOENT) # try: import DDRec except ImportError as X: - logger.error('ddrec python interface not accessible: %s',str(X)) - logger.error("%s",parser.format_help()) + logger.error('ddrec python interface not accessible: %s', str(X)) + logger.error("%s", parser.format_help()) sys.exit(errno.ENOENT) # dd4hep.setPrintLevel(dd4hep.OutputLevel.ERROR) -logger.info('+++%s\n+++ Loading compact geometry:%s\n+++%s',120*'=',opts.compact,120*'=') - +logger.info('+++%s\n+++ Loading compact geometry:%s\n+++%s', 120 * '=', opts.compact, 120 * '=') description = dd4hep.Detector.getInstance() description.fromXML(opts.compact) -## ------ loop over detectors and print their detector data objects +# ------ loop over detectors and print their detector data objects -for n,d in description.detectors(): +for n, d in description.detectors(): - logger.info("") - logger.info(" ------------- detector : %s" , d.name()) - logger.info("") + logger.info("") + logger.info(" ------------- detector : %s", d.name()) + logger.info("") - det = description.detector( n ) + det = description.detector(n) - dumpData(det) + dumpData(det) -##----------------------------------------------------------------- +# ----------------------------------------------------------------- logger.info('+++ Execution finished...') diff --git a/GaudiPluginService/python/GaudiPluginService/cpluginsvc.py b/GaudiPluginService/python/GaudiPluginService/cpluginsvc.py index 451ffee156e0da4ef8037bf06ab91d08fb6e6073..d62b9af14ab44b499bd8167c8addb29a6ce6b09f 100644 --- a/GaudiPluginService/python/GaudiPluginService/cpluginsvc.py +++ b/GaudiPluginService/python/GaudiPluginService/cpluginsvc.py @@ -33,17 +33,17 @@ _libname = None def _get_filename(): - if _libname: - return _libname - import platform - name = platform.system() + if _libname: + return _libname + import platform + name = platform.system() - fname = { - 'Darwin': "libGaudiPluginService.dylib", - 'Windows': "libGaudiPluginService.dll", - 'Linux': "libGaudiPluginService.so", - }[name] - return fname + fname = { + 'Darwin': "libGaudiPluginService.dylib", + 'Windows': "libGaudiPluginService.dll", + 'Linux': "libGaudiPluginService.so", + }[name] + return fname _libname = _get_filename() @@ -51,119 +51,119 @@ _lib = ctypes.CDLL(_libname, ctypes.RTLD_GLOBAL) class Registry(ctypes.Structure): - '''Registry holds the list of factories known by the gaudi PluginService. - ''' - _fields_ = [("_registry", ctypes.c_void_p)] + '''Registry holds the list of factories known by the gaudi PluginService. + ''' + _fields_ = [("_registry", ctypes.c_void_p)] - @property - def factories(self): - facts = {} - n = _lib.cgaudi_pluginsvc_get_factory_size(self) - for i in range(n): - f = _lib.cgaudi_pluginsvc_get_factory_at(self, i) - facts[f.name] = f - return facts + @property + def factories(self): + facts = {} + n = _lib.cgaudi_pluginsvc_get_factory_size(self) + for i in range(n): + f = _lib.cgaudi_pluginsvc_get_factory_at(self, i) + facts[f.name] = f + return facts - pass + pass _instance = None def registry(): - '''registry returns the singleton-like instance of the plugin service.''' + '''registry returns the singleton-like instance of the plugin service.''' - global _instance - if _instance: - return _instance - _instance = _lib.cgaudi_pluginsvc_instance() + global _instance + if _instance: return _instance + _instance = _lib.cgaudi_pluginsvc_instance() + return _instance def factories(): - ''' - factories returns the list of components factory informations known to the plugin service - ''' - return registry().factories + ''' + factories returns the list of components factory informations known to the plugin service + ''' + return registry().factories class Factory(ctypes.Structure): - """ - Factory holds informations about a component's factory: - - its name - - the library hosting that component - - the type of component (algorithm, service, tool, ...) - - the return type of this factory - - the C++ class name of that component - - the properties which may decorate that component. - """ - _fields_ = [ - ("_registry", Registry), - ("_id", ctypes.c_char_p), - ] - - @property - def name(self): - return self._id - - @property - def library(self): - return _lib.cgaudi_factory_get_library(self) - - @property - def type(self): - return _lib.cgaudi_factory_get_type(self) - - @property - def classname(self): - return _lib.cgaudi_factory_get_classname(self) - - @property - def properties(self): - props = {} - nprops = _lib.cgaudi_factory_get_property_size(self) - for i in range(nprops): - prop = _lib.cgaudi_factory_get_property_at(self, i) - props[prop.key] = prop.value - return props - - def load(self): - '''load the C++ library hosting this factory - ''' - return ctypes.CDLL(self.library, ctypes.RTLD_GLOBAL) - - def __repr__(self): - return "<Factory id=%s library=%s type=%s class=%s props=%d>" % ( - self._id, - self.library, - self.type, - self.classname, - len(self.properties), - ) - - pass + """ + Factory holds informations about a component's factory: + - its name + - the library hosting that component + - the type of component (algorithm, service, tool, ...) + - the return type of this factory + - the C++ class name of that component + - the properties which may decorate that component. + """ + _fields_ = [ + ("_registry", Registry), + ("_id", ctypes.c_char_p), + ] + + @property + def name(self): + return self._id + + @property + def library(self): + return _lib.cgaudi_factory_get_library(self) + + @property + def type(self): + return _lib.cgaudi_factory_get_type(self) + + @property + def classname(self): + return _lib.cgaudi_factory_get_classname(self) + + @property + def properties(self): + props = {} + nprops = _lib.cgaudi_factory_get_property_size(self) + for i in range(nprops): + prop = _lib.cgaudi_factory_get_property_at(self, i) + props[prop.key] = prop.value + return props + + def load(self): + '''load the C++ library hosting this factory + ''' + return ctypes.CDLL(self.library, ctypes.RTLD_GLOBAL) + + def __repr__(self): + return "<Factory id=%s library=%s type=%s class=%s props=%d>" % ( + self._id, + self.library, + self.type, + self.classname, + len(self.properties), + ) + + pass class Property(ctypes.Structure): - ''' - Property is a pair (key, value) optionally decorating a factory. - It is used to attach additional informations about a factory. - ''' - _fields_ = [ - ("_registry", Registry), - ("_id", ctypes.c_char_p), - ("_key", ctypes.c_char_p), - ] + ''' + Property is a pair (key, value) optionally decorating a factory. + It is used to attach additional informations about a factory. + ''' + _fields_ = [ + ("_registry", Registry), + ("_id", ctypes.c_char_p), + ("_key", ctypes.c_char_p), + ] - @property - def key(self): - return _lib.cgaudi_property_get_key(self) + @property + def key(self): + return _lib.cgaudi_property_get_key(self) - @property - def value(self): - return _lib.cgaudi_property_get_value(self) + @property + def value(self): + return _lib.cgaudi_property_get_value(self) - pass + pass _functions_list = [( @@ -209,25 +209,25 @@ _functions_list = [( )] for f in _functions_list: - n = f[0] - func = getattr(_lib, n) - func.argtypes = f[1] - func.restype = f[2] - if len(f) == 4: - func.errcheck = f[3] - pass + n = f[0] + func = getattr(_lib, n) + func.argtypes = f[1] + func.restype = f[2] + if len(f) == 4: + func.errcheck = f[3] + pass if __name__ == "__main__": - print(("instance: %s" % registry())) - print(("factories: %d" % len(factories()))) - for _,f in factories().items(): - try: - f.load() - except Exception: - print(("** could not load [%s] for factory [%s]" % (f.library, f.name))) - continue - print(f) - for k,v in f.properties.items(): - print(("\t%s: %s" % (k,v))) + print(("instance: %s" % registry())) + print(("factories: %d" % len(factories()))) + for _, f in factories().items(): + try: + f.load() + except Exception: + print(("** could not load [%s] for factory [%s]" % (f.library, f.name))) + continue + print(f) + for k, v in f.properties.items(): + print(("\t%s: %s" % (k, v))) # EOF diff --git a/etc/CreateParsers.py b/etc/CreateParsers.py index 8387fa9ffed00ee5b437248c0dc384ea0aed3d72..00c75d53ae084e704ded42926f36383d5d863403 100644 --- a/etc/CreateParsers.py +++ b/etc/CreateParsers.py @@ -14,7 +14,7 @@ from __future__ import absolute_import, unicode_literals import os from io import open -LICENSE ="""// $Id$ +LICENSE = """// $Id$ //========================================================================== // AIDA Detector description implementation //-------------------------------------------------------------------------- @@ -27,6 +27,7 @@ LICENSE ="""// $Id$ //========================================================================== """ + def createParsers(): """ make files for all parsers""" @@ -46,65 +47,65 @@ def createParsers(): 'unsigned long long', 'std::string', 'signed char', - ] - listOfContainers = ['std::vector','std::list','std::set','std::deque'] - listOfMaps = ['int','unsigned long','std::string',] - + ] + listOfContainers = ['std::vector', 'std::list', 'std::set', 'std::deque'] + listOfMaps = ['int', 'unsigned long', 'std::string', ] for typ in listOfTypes: for cont in listOfContainers: - createContainerFile( typ, cont) + createContainerFile(typ, cont) for mtype in listOfMaps: - createMapFile( typ, mtype ) + createMapFile(typ, mtype) + + createMappedFile(typ) - createMappedFile( typ ) -def createMappedFile( typ ): +def createMappedFile(typ): """ create file for mapped parsers """ tName = typ[5:] if typ.startswith("std::") else typ - filename="ParserStandardList_Mapped_%s.cpp" % ( tName.replace(" ", "") ) - fileContent= """ + filename = "ParserStandardList_Mapped_%s.cpp" % (tName.replace(" ", "")) + fileContent = """ #include "ParsersStandardListCommon.h" namespace dd4hep{ namespace Parsers{ IMPLEMENT_MAPPED_PARSERS(pair,%(type)s) }} -""" % { "type":typ } - fileContent = LICENSE+fileContent +""" % {"type": typ} + fileContent = LICENSE + fileContent if os.path.exists(filename): os.remove(filename) with open(filename, "w") as parseFile: parseFile.write(fileContent) -def createContainerFile( typ, cont ): +def createContainerFile(typ, cont): """create file to make container parser""" tName = typ[5:] if typ.startswith("std::") else typ - filename="ParserStandardList_%s_%s.cpp" % ( cont[5:], tName.replace(" ", "")) - fileContent= """ + filename = "ParserStandardList_%s_%s.cpp" % (cont[5:], tName.replace(" ", "")) + fileContent = """ #include "ParsersStandardListCommon.h" namespace dd4hep{ namespace Parsers{ IMPLEMENT_STL_PARSER(%(cont)s,%(type)s) }} -""" % { "cont": cont, "type":typ } - fileContent = LICENSE+fileContent +""" % {"cont": cont, "type": typ} + fileContent = LICENSE + fileContent if os.path.exists(filename): os.remove(filename) with open(filename, "w") as parseFile: parseFile.write(fileContent) -def createMapFile( typ, mtype ): +def createMapFile(typ, mtype): """ create file to make map parser""" mName = mtype[5:] if mtype.startswith("std::") else mtype tName = typ[5:] if typ.startswith("std::") else typ - filename="ParserStandardList_Map%s_%s.cpp" % ( mName.replace(" ", "") , tName.replace(" ", "")) - fileContent= """ + filename = "ParserStandardList_Map%s_%s.cpp" % (mName.replace(" ", ""), tName.replace(" ", "")) + fileContent = """ #include "ParsersStandardListCommon.h" namespace dd4hep{ namespace Parsers{ IMPLEMENT_STL_MAP_PARSER(std::map,%(mtype)s,%(type)s) }} -""" % { "mtype": mtype, "type":typ } - fileContent = LICENSE+fileContent +""" % {"mtype": mtype, "type": typ} + fileContent = LICENSE + fileContent if os.path.exists(filename): os.remove(filename) with open(filename, "w") as parseFile: diff --git a/examples/AlignDet/drivers/BoxSegment.py b/examples/AlignDet/drivers/BoxSegment.py index eb8f016cca64c5872f66829f3d7ea16f57c18d8e..e63e7324f2a904aef149681f01ed3570fcce6db4 100644 --- a/examples/AlignDet/drivers/BoxSegment.py +++ b/examples/AlignDet/drivers/BoxSegment.py @@ -1,17 +1,18 @@ from __future__ import absolute_import, unicode_literals + def detector_BoxSegment(description, det): - box = det.find('box') - mat = det.find('material') - pos = det.find('position') - rot = det.find('rotation') + box = det.find('box') + mat = det.find('material') + pos = det.find('position') + rot = det.find('rotation') mother = description.worldVolume() - de = DetElement(description, det.name, det.type, det.id) - sha = Box(description, det.name+'_envelope', box.x, box.y, box.z) - vol = Volume(description, det.name+'_envelope_volume', sha, description.material(mat.name)) - phv = mother.placeVolume(vol, Position(pos.x, pos.y, pos.z), - Rotation(rot.x, rot.y, rot.z)) + de = DetElement(description, det.name, det.type, det.id) + sha = Box(description, det.name + '_envelope', box.x, box.y, box.z) + vol = Volume(description, det.name + '_envelope_volume', sha, description.material(mat.name)) + phv = mother.placeVolume(vol, Position(pos.x, pos.y, pos.z), + Rotation(rot.x, rot.y, rot.z)) vol.setVisAttributes(description, det.vis) - phv.addPhysVolID('id',det.id) + phv.addPhysVolID('id', det.id) de.addPlacement(phv) return de diff --git a/examples/AlignDet/drivers/Shelf.py b/examples/AlignDet/drivers/Shelf.py index 849d80f3e85802ad9d20d10751f92dab4cd7bf8c..2cee9e4e2694993e5102d61a7e9c3fd1bc921896 100644 --- a/examples/AlignDet/drivers/Shelf.py +++ b/examples/AlignDet/drivers/Shelf.py @@ -1,42 +1,45 @@ from __future__ import absolute_import, unicode_literals from six.moves import range + def detector_Shelf(description, det): - plane = det.find('planes') - mat = det.find('material') + plane = det.find('planes') + mat = det.find('material') #pos = det.find('position') #rot = det.find('rotation') - book = det.find('books') - + book = det.find('books') + #---Construct the ensamble plane+books volume------------------------------------------------------------- - e_vol = Volume(description, 'ensemble', Box(description,'box', plane.x, plane.y+book.y, plane.z), description.material('Air')) - e_vol.setVisAttributes(description,'InvisibleWithDaughters') - + e_vol = Volume(description, 'ensemble', Box(description, 'box', plane.x, + plane.y + book.y, plane.z), description.material('Air')) + e_vol.setVisAttributes(description, 'InvisibleWithDaughters') + #---Construct the plane and place it---------------------------------------------------------------------- - p_vol = Volume(description, 'plane', Box(description, 'plane', plane.x, plane.y, plane.z), description.material(mat.name)) + p_vol = Volume(description, 'plane', Box(description, 'plane', plane.x, + plane.y, plane.z), description.material(mat.name)) p_vol.setVisAttributes(description, plane.vis) - e_vol.placeVolume(p_vol, Position(0,-book.y,0)) - + e_vol.placeVolume(p_vol, Position(0, -book.y, 0)) + #---Construct a book and place it number of times--------------------------------------------------------- - b_vol = Volume(description, 'book',Box(description, 'book', book.x, book.y, book.z), description.material('Carbon')) + b_vol = Volume(description, 'book', Box(description, 'book', book.x, book.y, book.z), description.material('Carbon')) b_vol.setVisAttributes(description, book.vis) - x,y,z = plane.x-book.x, plane.y, -plane.z+book.z + x, y, z = plane.x - book.x, plane.y, -plane.z + book.z for n in range(book.number): - e_vol.placeVolume(b_vol, Position(x,y,z)) - z += 2*book.z + book.getF('dz') - + e_vol.placeVolume(b_vol, Position(x, y, z)) + z += 2 * book.z + book.getF('dz') + #--Construct the overal envelope and Detector element----------------------------------------------------- - g_x, g_y, g_z = plane.x, plane.number*plane.getF('dy'), plane.z - g_vol = Volume(description, det.name, Box(description,'box', g_x, g_y, g_z), description.material('Air')) - g_vol.setVisAttributes(description,'InvisibleWithDaughters') - de = DetElement(description, det.name, det.type, det.id) - phv = description.worldVolume().placeVolume(g_vol, Position(g_x,g_y,g_z)) - phv.addPhysVolID('id',det.id) + g_x, g_y, g_z = plane.x, plane.number * plane.getF('dy'), plane.z + g_vol = Volume(description, det.name, Box(description, 'box', g_x, g_y, g_z), description.material('Air')) + g_vol.setVisAttributes(description, 'InvisibleWithDaughters') + de = DetElement(description, det.name, det.type, det.id) + phv = description.worldVolume().placeVolume(g_vol, Position(g_x, g_y, g_z)) + phv.addPhysVolID('id', det.id) de.addPlacement(phv) - x,y,z = 0,book.y+plane.y-2*plane.getF('dy'),0 + x, y, z = 0, book.y + plane.y - 2 * plane.getF('dy'), 0 for n in range(plane.number): - g_vol.placeVolume(e_vol, Position(x,y,z)) + g_vol.placeVolume(e_vol, Position(x, y, z)) y += plane.getF('dy') #---Return detector element--------------------------------------------------------------------------------- return de diff --git a/examples/CLICSiD/scripts/CLICRandom.py b/examples/CLICSiD/scripts/CLICRandom.py index dfa6b15e5bc76d8f84048443f4757e8f195d8d74..95a69865eb4a0237e67ba48a49f4a7b14850d00c 100644 --- a/examples/CLICSiD/scripts/CLICRandom.py +++ b/examples/CLICSiD/scripts/CLICRandom.py @@ -17,22 +17,23 @@ logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) if __name__ == "__main__": - import CLICSid, DDG4 + import CLICSid + import DDG4 sid = CLICSid.CLICSid() - + logger.info('DEFAULT Engine: %s', DDG4.CLHEP.HepRandom.getTheEngine().name()) # <<-- See this function to know how it's done.... - rndm1 = sid.setupRandom('R1',seed=987654321,type='RunluxEngine') + rndm1 = sid.setupRandom('R1', seed=987654321, type='RunluxEngine') logger.info('R1: %s Default instance: %s', rndm1.name, rndm1.instance().name()) logger.info(' Engine: %s', rndm1.engine().name()) logger.info(' DEFAULT: %s', DDG4.CLHEP.HepRandom.getTheEngine().name()) rndm1.showStatus() - rndm2 = sid.setupRandom('R2',seed=1234321,type='MTwistEngine') + rndm2 = sid.setupRandom('R2', seed=1234321, type='MTwistEngine') logger.info('R2: %s Default instance: %s', rndm2.name, rndm2.instance().name()) logger.info(' Engine: %s', rndm2.engine().name()) logger.info(' DEFAULT: %s', DDG4.CLHEP.HepRandom.getTheEngine().name()) - #rndm2.showStatus() + # rndm2.showStatus() DDG4.Geant4Random.setMainInstance(rndm1.get()) rndm1.showStatus() @@ -47,22 +48,22 @@ if __name__ == "__main__": rndm.setSeed(1234) rndm.showStatus() for i in range(10): - logger.info("%s -- 0 gRandome.Rndm() -- Shoot random[[%d]= %f",rndm.name(),i,gRandom.Rndm()) - + logger.info("%s -- 0 gRandome.Rndm() -- Shoot random[[%d]= %f", rndm.name(), i, gRandom.Rndm()) + rndm.setSeed(1234) for i in range(10): - logger.info("%s -- 1 gRandome.Rndm() -- Shoot random[[%d]= %f",rndm.name(),i,gRandom.Rndm()) - + logger.info("%s -- 1 gRandome.Rndm() -- Shoot random[[%d]= %f", rndm.name(), i, gRandom.Rndm()) + rndm.setSeed(1234) for i in range(10): - logger.info("%s -- 2 Geant4Random(CLHEP) -- Shoot random[[%d]= %f",rndm.name(),i,rndm.rndm_clhep()) - + logger.info("%s -- 2 Geant4Random(CLHEP) -- Shoot random[[%d]= %f", rndm.name(), i, rndm.rndm_clhep()) + rndm.setSeed(1234) for i in range(10): - logger.info("%s -- 3 Geant4Random(CLHEP) -- Shoot random[[%d]= %f",rndm.name(),i,rndm.rndm_clhep()) + logger.info("%s -- 3 Geant4Random(CLHEP) -- Shoot random[[%d]= %f", rndm.name(), i, rndm.rndm_clhep()) rndm.setSeed(1234) for i in range(10): - logger.info("%s -- 4 HepRandomEngine(CLHEP) -- Shoot random[%d]= %f",rndm.name(),i,rndm.engine().flat()) - + logger.info("%s -- 4 HepRandomEngine(CLHEP) -- Shoot random[%d]= %f", rndm.name(), i, rndm.engine().flat()) + sid.test_run(have_geo=False) diff --git a/examples/CLICSiD/scripts/CLICSiDScan.py b/examples/CLICSiD/scripts/CLICSiDScan.py index de4cdb8f78da1dc6683d9e665bf9c7a0eba6f383..213955b848cdf7cf506c59da00bf05363509b650 100644 --- a/examples/CLICSiD/scripts/CLICSiDScan.py +++ b/examples/CLICSiD/scripts/CLICSiDScan.py @@ -13,8 +13,13 @@ logging.basicConfig(format='%(levelname)s: %(message)s') logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) + def run(): - import os, sys, DDG4, CLICSid, g4units + import os + import sys + import DDG4 + import CLICSid + import g4units sid = CLICSid.CLICSid() sid.loadGeometry() @@ -23,13 +28,13 @@ def run(): # Configure UI sid.geant4.setupCshUI(ui=None) gun = sid.geant4.setupGun("Gun", - Standalone=True, - particle='geantino', - energy=20*g4units.GeV, - position=(0,0,0), - multiplicity=1, - isotrop=False ) - scan = DDG4.SteppingAction(sid.kernel,'Geant4MaterialScanner/MaterialScan') + Standalone=True, + particle='geantino', + energy=20 * g4units.GeV, + position=(0, 0, 0), + multiplicity=1, + isotrop=False) + scan = DDG4.SteppingAction(sid.kernel, 'Geant4MaterialScanner/MaterialScan') sid.kernel.steppingAction().adopt(scan) # Now build the physics list: @@ -38,16 +43,17 @@ def run(): sid.kernel.NumEvents = 1 # 3 shots in different directions: - gun.direction = (0,1,0) + gun.direction = (0, 1, 0) sid.kernel.run() - gun.direction = (1,0,0) + gun.direction = (1, 0, 0) sid.kernel.run() - gun.direction = (1,1,1) + gun.direction = (1, 1, 1) sid.kernel.run() sid.kernel.terminate() logger.info('End of run. Terminating .......') logger.info('TEST_PASSED') + if __name__ == "__main__": run() diff --git a/examples/CLICSiD/scripts/CLICSiD_LoadROOTGeo.py b/examples/CLICSiD/scripts/CLICSiD_LoadROOTGeo.py index f32401fc28c6c1722152a53e1dc05f14d2256912..cb50db81e07b421bf1b31e5c5235725bd1eaa6d4 100644 --- a/examples/CLICSiD/scripts/CLICSiD_LoadROOTGeo.py +++ b/examples/CLICSiD/scripts/CLICSiD_LoadROOTGeo.py @@ -14,48 +14,50 @@ logging.basicConfig(format='%(levelname)s: %(message)s') logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) + def run(): - import sys, CLICSid, DDG4 + import sys + import CLICSid + import DDG4 from DDG4 import OutputLevel as Output - + sid = CLICSid.CLICSid() geant4 = sid.geant4 kernel = sid.kernel sid.loadGeometry(str('CLICSiD_geometry.root')) geant4.printDetectors() - if len(sys.argv) >= 2 and sys.argv[1] =="batch": + if len(sys.argv) >= 2 and sys.argv[1] == "batch": kernel.UI = '' geant4.setupCshUI() sid.setupField(quiet=False) - DDG4.importConstants(kernel.detectorDescription(),debug=False) + DDG4.importConstants(kernel.detectorDescription(), debug=False) - prt = DDG4.EventAction(kernel,'Geant4ParticlePrint/ParticlePrint') + prt = DDG4.EventAction(kernel, 'Geant4ParticlePrint/ParticlePrint') prt.OutputLevel = Output.INFO - prt.OutputType = 3 # Print both: table and tree + prt.OutputType = 3 # Print both: table and tree kernel.eventAction().adopt(prt) - gen = DDG4.GeneratorAction(kernel,"Geant4GeneratorActionInit/GenerationInit") + gen = DDG4.GeneratorAction(kernel, "Geant4GeneratorActionInit/GenerationInit") kernel.generatorAction().adopt(gen) logger.info("# First particle generator: gun") - gun = DDG4.GeneratorAction(kernel,"Geant4GeneratorWrapper/Gun"); - gun.Uses = 'G4ParticleGun' - gun.Mask = 1 + gun = DDG4.GeneratorAction(kernel, "Geant4GeneratorWrapper/Gun") + gun.Uses = 'G4ParticleGun' + gun.Mask = 1 kernel.generatorAction().adopt(gun) # Merge all existing interaction records - merger = DDG4.GeneratorAction(kernel,"Geant4InteractionMerger/InteractionMerger") + merger = DDG4.GeneratorAction(kernel, "Geant4InteractionMerger/InteractionMerger") merger.enableUI() kernel.generatorAction().adopt(merger) - # And handle the simulation particles. - part = DDG4.GeneratorAction(kernel,"Geant4ParticleHandler/ParticleHandler") + part = DDG4.GeneratorAction(kernel, "Geant4ParticleHandler/ParticleHandler") kernel.generatorAction().adopt(part) part.OutputLevel = Output.INFO part.enableUI() - user = DDG4.Action(kernel,"Geant4TCUserParticleHandler/UserParticleHandler") + user = DDG4.Action(kernel, "Geant4TCUserParticleHandler/UserParticleHandler") user.TrackingVolume_Zmax = DDG4.EcalEndcap_zmin user.TrackingVolume_Rmax = DDG4.EcalBarrel_rmin user.enableUI() @@ -68,5 +70,6 @@ def run(): kernel.run() kernel.terminate() + if __name__ == "__main__": run() diff --git a/examples/CLICSiD/scripts/CLICSid.py b/examples/CLICSiD/scripts/CLICSid.py index 6e677885a8523b44f946ad3365cab0893af9bae1..aedc8fb3ba93305fc46f63589b2305adf17496ba 100644 --- a/examples/CLICSiD/scripts/CLICSid.py +++ b/examples/CLICSiD/scripts/CLICSid.py @@ -1,26 +1,29 @@ from __future__ import absolute_import, unicode_literals -import sys, logging, DDG4 +import sys +import logging +import DDG4 from g4units import * logging.basicConfig(format='%(levelname)s: %(message)s') logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) + class CLICSid: - def __init__(self,tracker='Geant4TrackerCombineAction'): + def __init__(self, tracker='Geant4TrackerCombineAction'): self.kernel = DDG4.Kernel() self.description = self.kernel.detectorDescription() - self.geant4 = DDG4.Geant4(self.kernel,tracker=tracker) + self.geant4 = DDG4.Geant4(self.kernel, tracker=tracker) self.kernel.UI = "" self.noPhysics() - + def loadGeometry(self, file=None): import os if file is None: install_dir = os.environ['DD4hepINSTALL'] level = DDG4.printLevel() DDG4.setPrintLevel(DDG4.OutputLevel.WARNING) - self.kernel.loadGeometry(str("file:"+install_dir+"/DDDetectors/compact/SiD.xml")) + self.kernel.loadGeometry(str("file:" + install_dir + "/DDDetectors/compact/SiD.xml")) DDG4.setPrintLevel(level) else: ui = DDG4.DD4hepUI(self.description) @@ -33,23 +36,26 @@ class CLICSid: # Example to show how to setup random generator def setupRandom(self, name, type=None, seed=None, quiet=True): - rndm = DDG4.Action(self.kernel,'Geant4Random/'+name) - if seed: rndm.Seed = seed - if type: rndm.Type = type + rndm = DDG4.Action(self.kernel, 'Geant4Random/' + name) + if seed: + rndm.Seed = seed + if type: + rndm.Type = type rndm.initialize() - if not quiet: rndm.showStatus() + if not quiet: + rndm.showStatus() return rndm # Example to show how to configure the Geant4 physics list def setupPhysics(self, model): phys = self.geant4.setupPhysics(model) - ph = DDG4.PhysicsList(self.kernel,str('Geant4PhysicsList/Myphysics')) + ph = DDG4.PhysicsList(self.kernel, str('Geant4PhysicsList/Myphysics')) # Add bosons to the model (redundant if already implemented by the model) ph.addParticleGroup(str('G4BosonConstructor')) # Add leptons to the model (redundant if already implemented by the model) ph.addParticleGroup(str('G4LeptonConstructor')) # Add multiple scattering in the material - ph.addParticleProcess(str('e[+-]'),str('G4eMultipleScattering'),-1,1,1) + ph.addParticleProcess(str('e[+-]'), str('G4eMultipleScattering'), -1, 1, 1) # Add optical physics (RICH dets etc) ph.addPhysicsConstructor(str('G4OpticalPhysics')) # Interactivity @@ -65,21 +71,21 @@ class CLICSid: def setupDetectors(self): logger.info("# First the tracking detectors") - seq,act = self.geant4.setupTracker('SiVertexBarrel') - seq,act = self.geant4.setupTracker('SiVertexEndcap') - seq,act = self.geant4.setupTracker('SiTrackerBarrel') - seq,act = self.geant4.setupTracker('SiTrackerEndcap') - seq,act = self.geant4.setupTracker('SiTrackerForward') + seq, act = self.geant4.setupTracker('SiVertexBarrel') + seq, act = self.geant4.setupTracker('SiVertexEndcap') + seq, act = self.geant4.setupTracker('SiTrackerBarrel') + seq, act = self.geant4.setupTracker('SiTrackerEndcap') + seq, act = self.geant4.setupTracker('SiTrackerForward') logger.info("# Now setup the calorimeters") - seq,act = self.geant4.setupCalorimeter('EcalBarrel') - seq,act = self.geant4.setupCalorimeter('EcalEndcap') - seq,act = self.geant4.setupCalorimeter('HcalBarrel') - seq,act = self.geant4.setupCalorimeter('HcalEndcap') - seq,act = self.geant4.setupCalorimeter('HcalPlug') - seq,act = self.geant4.setupCalorimeter('MuonBarrel') - seq,act = self.geant4.setupCalorimeter('MuonEndcap') - seq,act = self.geant4.setupCalorimeter('LumiCal') - seq,act = self.geant4.setupCalorimeter('BeamCal') + seq, act = self.geant4.setupCalorimeter('EcalBarrel') + seq, act = self.geant4.setupCalorimeter('EcalEndcap') + seq, act = self.geant4.setupCalorimeter('HcalBarrel') + seq, act = self.geant4.setupCalorimeter('HcalEndcap') + seq, act = self.geant4.setupCalorimeter('HcalPlug') + seq, act = self.geant4.setupCalorimeter('MuonBarrel') + seq, act = self.geant4.setupCalorimeter('MuonEndcap') + seq, act = self.geant4.setupCalorimeter('LumiCal') + seq, act = self.geant4.setupCalorimeter('BeamCal') return self # Test the configuration diff --git a/examples/CLICSiD/scripts/CLIC_G4Gun.py b/examples/CLICSiD/scripts/CLIC_G4Gun.py index 9c2fe24de72e3f04c2b747a67963f1e911f9188d..93ffad4ab530b3aea368363e074e8e56249ff4f8 100644 --- a/examples/CLICSiD/scripts/CLIC_G4Gun.py +++ b/examples/CLICSiD/scripts/CLIC_G4Gun.py @@ -15,8 +15,10 @@ logging.basicConfig(format='%(levelname)s: %(message)s') logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) + def run(): - import CLICSid, DDG4 + import CLICSid + import DDG4 from DDG4 import OutputLevel as Output sid = CLICSid.CLICSid() @@ -27,32 +29,32 @@ def run(): kernel.UI = "UI" geant4.setupCshUI() sid.setupField(quiet=False) - DDG4.importConstants(kernel.detectorDescription(),debug=False) + DDG4.importConstants(kernel.detectorDescription(), debug=False) - prt = DDG4.EventAction(kernel,'Geant4ParticlePrint/ParticlePrint') + prt = DDG4.EventAction(kernel, 'Geant4ParticlePrint/ParticlePrint') prt.OutputLevel = Output.INFO - prt.OutputType = 3 # Print both: table and tree + prt.OutputType = 3 # Print both: table and tree kernel.eventAction().adopt(prt) - gen = DDG4.GeneratorAction(kernel,"Geant4GeneratorActionInit/GenerationInit") + gen = DDG4.GeneratorAction(kernel, "Geant4GeneratorActionInit/GenerationInit") kernel.generatorAction().adopt(gen) logger.info("# First particle generator: gun") - gun = DDG4.GeneratorAction(kernel,"Geant4GeneratorWrapper/Gun"); - gun.Uses = 'G4ParticleGun' - gun.Mask = 1 + gun = DDG4.GeneratorAction(kernel, "Geant4GeneratorWrapper/Gun") + gun.Uses = 'G4ParticleGun' + gun.Mask = 1 kernel.generatorAction().adopt(gun) # Merge all existing interaction records - merger = DDG4.GeneratorAction(kernel,"Geant4InteractionMerger/InteractionMerger") + merger = DDG4.GeneratorAction(kernel, "Geant4InteractionMerger/InteractionMerger") merger.enableUI() kernel.generatorAction().adopt(merger) # And handle the simulation particles. - part = DDG4.GeneratorAction(kernel,"Geant4ParticleHandler/ParticleHandler") + part = DDG4.GeneratorAction(kernel, "Geant4ParticleHandler/ParticleHandler") kernel.generatorAction().adopt(part) part.OutputLevel = Output.INFO part.enableUI() - user = DDG4.Action(kernel,"Geant4TCUserParticleHandler/UserParticleHandler") + user = DDG4.Action(kernel, "Geant4TCUserParticleHandler/UserParticleHandler") user.TrackingVolume_Zmax = DDG4.EcalEndcap_zmin user.TrackingVolume_Rmax = DDG4.EcalBarrel_rmin user.enableUI() @@ -65,5 +67,6 @@ def run(): kernel.run() kernel.terminate() + if __name__ == "__main__": run() diff --git a/examples/CLICSiD/scripts/CLIC_GDML.py b/examples/CLICSiD/scripts/CLIC_GDML.py index ceefc6546eec72daad6a4fa0422493e5272c0034..4fa3f5014242d65ee961ab4d2370f4354e66d71d 100644 --- a/examples/CLICSiD/scripts/CLIC_GDML.py +++ b/examples/CLICSiD/scripts/CLIC_GDML.py @@ -9,10 +9,12 @@ from __future__ import absolute_import, unicode_literals from g4units import * + def run(): - import CLICSid, DDG4 + import CLICSid + import DDG4 from DDG4 import OutputLevel as Output - + sid = CLICSid.CLICSid() sid.loadGeometry() sid.geant4.printDetectors() @@ -21,12 +23,12 @@ def run(): ui = sid.geant4.setupCshUI(ui=None) # # Setup the GDML writer action - writer = DDG4.Action(kernel,'Geant4GDMLWriteAction/Writer') + writer = DDG4.Action(kernel, 'Geant4GDMLWriteAction/Writer') writer.enableUI() kernel.registerGlobalAction(writer) sid.setupPhysics('QGSP_BERT') # - gen = sid.geant4.setupGun('Gun','pi-',10*GeV,Standalone=True) + gen = sid.geant4.setupGun('Gun', 'pi-', 10 * GeV, Standalone=True) # Now initialize. At the Geant4 command prompt we can write the geometry: # Idle> /ddg4/Writer/write # or by configuring the UI using ui.Commands @@ -41,16 +43,17 @@ def run(): # sid.geant4.setupGun('Gun','pi-',10*GeV,Standalone=True) # ui.Commands = [ - '/run/beamOn 0', - '/ddg4/Writer/Output CLICSiD.gdml', - '/ddg4/Writer/OverWrite 1', - '/ddg4/Writer/write' - ] + '/run/beamOn 0', + '/ddg4/Writer/Output CLICSiD.gdml', + '/ddg4/Writer/OverWrite 1', + '/ddg4/Writer/write' + ] kernel.NumEvents = 0 kernel.configure() kernel.initialize() kernel.run() kernel.terminate() + if __name__ == "__main__": run() diff --git a/examples/CLICSiD/scripts/testDDPython.py b/examples/CLICSiD/scripts/testDDPython.py index ed62dd3abbe94bc4b9bb31b3cdd8157df3d1987a..38b2d6e396f69ebff52be4d5292becac95a06524 100644 --- a/examples/CLICSiD/scripts/testDDPython.py +++ b/examples/CLICSiD/scripts/testDDPython.py @@ -1,8 +1,10 @@ from __future__ import absolute_import, unicode_literals from ROOT import gSystem -import os, logging, platform -if platform.system()=="Darwin": +import os +import logging +import platform +if platform.system() == "Darwin": gSystem.SetDynamicPath(os.environ['DD4HEP_LIBRARY_PATH']) gSystem.Load('libglapi') gSystem.Load('libDDPython') @@ -13,67 +15,73 @@ logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) name_space = __import__(__name__) -def import_namespace_item(ns,nam): - scope = getattr(name_space,ns) - attr = getattr(scope,nam) - setattr(name_space,nam,attr) + + +def import_namespace_item(ns, nam): + scope = getattr(name_space, ns) + attr = getattr(scope, nam) + setattr(name_space, nam, attr) return attr + def a_func(): logger.info('Hello world') return 1 + class a_class: def __init__(self): pass + def fcn(self): logger.info('Hello world from member function fcn') return 1 - def fcn_except(self,args,aa): - logger.info('Hello world from member function fcn1 a1=%s a2=%s',str(args),str(aa)) + + def fcn_except(self, args, aa): + logger.info('Hello world from member function fcn1 a1=%s a2=%s', str(args), str(aa)) raise RuntimeError('Except from python test object a_class') return 6 - -py = import_namespace_item('Core','DDPython') + +py = import_namespace_item('Core', 'DDPython') logger.info('+++++ Test: Execute statements in python with C++ indirection') py.instance().execute(str('import sys, logging')) py.instance().execute(str('logging.info("Arguments: %s", str(sys.argv))')) logger.info('\n') -obj=a_class() -import sys, traceback +obj = a_class() +import sys +import traceback logger.info('+++++ Test: simple function call') -ret = py.instance().call(a_func,None) -logger.info('ret: %s',str(ret)) +ret = py.instance().call(a_func, None) +logger.info('ret: %s', str(ret)) logger.info('\n') logger.info('+++++ Test: object method call') -ret = py.instance().call(obj.fcn,None) -logger.info('ret: %s',str(ret)) +ret = py.instance().call(obj.fcn, None) +logger.info('ret: %s', str(ret)) logger.info('\n') logger.info('+++++ Test: object method call with non callable') -try: - ret = py.instance().call(1,None) - logger.info('ret: %s',str(ret)) +try: + ret = py.instance().call(1, None) + logger.info('ret: %s', str(ret)) except: traceback.print_exc() logger.info('\n') logger.info('+++++ Test: object method call with exception in python callback') -try: - ret = py.instance().call(obj.fcn_except,(1,[1,2,3,4,5,6],)) - logger.info('ret: %s',str(ret)) +try: + ret = py.instance().call(obj.fcn_except, (1, [1, 2, 3, 4, 5, 6],)) + logger.info('ret: %s', str(ret)) except: traceback.print_exc() logger.info('\n') logger.info('+++++ All Done....\n\n') logger.info('TEST_PASSED') -#py.instance().prompt() +# py.instance().prompt() sys.exit(0) - diff --git a/examples/ClientTests/scripts/Assemblies.py b/examples/ClientTests/scripts/Assemblies.py index 31be521039a0c90996a7eeb6e787bd6253b3f96d..72d60ab0c29ce348a131fcff683a60a3b26d0cf5 100644 --- a/examples/ClientTests/scripts/Assemblies.py +++ b/examples/ClientTests/scripts/Assemblies.py @@ -1,5 +1,8 @@ from __future__ import absolute_import, unicode_literals -import os, sys, time, DDG4 +import os +import sys +import time +import DDG4 from SystemOfUnits import * # """ @@ -9,26 +12,28 @@ from SystemOfUnits import * \version 1.0 """ + + def run(): kernel = DDG4.Kernel() install_dir = os.environ['DD4hepExamplesINSTALL'] - kernel.loadGeometry(str("file:"+install_dir+"/examples/ClientTests/compact/Assemblies.xml")) + kernel.loadGeometry(str("file:" + install_dir + "/examples/ClientTests/compact/Assemblies.xml")) # - geant4 = DDG4.Geant4(kernel,tracker='Geant4TrackerCombineAction') + geant4 = DDG4.Geant4(kernel, tracker='Geant4TrackerCombineAction') geant4.printDetectors() # Configure UI geant4.setupCshUI() - if len(sys.argv) >= 2 and sys.argv[1] =="batch": + if len(sys.argv) >= 2 and sys.argv[1] == "batch": kernel.UI = '' # Configure field field = geant4.setupTrackingField(prt=True) # Configure I/O - geant4.setupROOTOutput('RootOutput','Assemblies_'+time.strftime('%Y-%m-%d_%H-%M'),mc_truth=False) + geant4.setupROOTOutput('RootOutput', 'Assemblies_' + time.strftime('%Y-%m-%d_%H-%M'), mc_truth=False) # Setup particle gun - geant4.setupGun("Gun",particle='e-',energy=2*GeV,position=(0.15*mm,0.12*mm,0.1*cm),multiplicity=1) + geant4.setupGun("Gun", particle='e-', energy=2 * GeV, position=(0.15 * mm, 0.12 * mm, 0.1 * cm), multiplicity=1) # First the tracking detectors - seq,act = geant4.setupTracker('VXD') + seq, act = geant4.setupTracker('VXD') # Now build the physics list: phys = kernel.physicsList() phys.extends = 'QGSP_BERT' @@ -38,5 +43,6 @@ def run(): DDG4.setPrintLevel(DDG4.OutputLevel.DEBUG) geant4.execute() + if __name__ == "__main__": run() diff --git a/examples/ClientTests/scripts/DDG4TestSetup.py b/examples/ClientTests/scripts/DDG4TestSetup.py index a4d820664bb01e1f733cd338d21f42d95b2c9d87..a84d5da277768e39ed2e507c8d389f45f32a1d8b 100644 --- a/examples/ClientTests/scripts/DDG4TestSetup.py +++ b/examples/ClientTests/scripts/DDG4TestSetup.py @@ -1,5 +1,9 @@ from __future__ import absolute_import, unicode_literals -import os, sys, time, logging, DDG4 +import os +import sys +import time +import logging +import DDG4 from DDG4 import OutputLevel as Output from SystemOfUnits import * @@ -15,11 +19,13 @@ logger.setLevel(logging.INFO) \version 1.0 """ + + class Setup: def __init__(self, geometry_file): self.kernel = DDG4.Kernel() - self.kernel.setOutputLevel(str('Geant4Converter'),Output.DEBUG) - self.kernel.setOutputLevel(str('Gun'),Output.INFO) + self.kernel.setOutputLevel(str('Geant4Converter'), Output.DEBUG) + self.kernel.setOutputLevel(str('Gun'), Output.INFO) self.kernel.loadGeometry(str(geometry_file)) self.geant4 = DDG4.Geant4(self.kernel) @@ -31,22 +37,22 @@ class Setup: self.field = self.geant4.setupTrackingField(prt=True) return self - def defineOutput(self,output): + def defineOutput(self, output): # Configure I/O - evt_root = self.geant4.setupROOTOutput('RootOutput',output,mc_truth=True) + evt_root = self.geant4.setupROOTOutput('RootOutput', output, mc_truth=True) return evt_root - def setupGun(self, name="Gun",particle='pi-',energy=100*GeV,multiplicity=1): + def setupGun(self, name="Gun", particle='pi-', energy=100 * GeV, multiplicity=1): # Setup particle gun - return self.geant4.setupGun(name,particle=particle,energy=energy,multiplicity=multiplicity) + return self.geant4.setupGun(name, particle=particle, energy=energy, multiplicity=multiplicity) def setupGenerator(self): # And handle the simulation particles. - part = DDG4.GeneratorAction(self.kernel,"Geant4ParticleHandler/ParticleHandler") + part = DDG4.GeneratorAction(self.kernel, "Geant4ParticleHandler/ParticleHandler") self.kernel.generatorAction().adopt(part) - part.SaveProcesses = ['conv','Decay'] - part.MinimalKineticEnergy = 1*MeV - part.OutputLevel = 5 # generator_output_level + part.SaveProcesses = ['conv', 'Decay'] + part.MinimalKineticEnergy = 1 * MeV + part.OutputLevel = 5 # generator_output_level part.enableUI() return part @@ -82,4 +88,3 @@ class Setup: self.kernel.NumEvents = 0 self.kernel.run() self.terminate() - diff --git a/examples/ClientTests/scripts/FCC_Hcal.py b/examples/ClientTests/scripts/FCC_Hcal.py index 6195858595fe0659b3a1aa81b352271dec65dcf1..57b421b23e2a9b8e859eb387ad5ede269b4dc349 100644 --- a/examples/ClientTests/scripts/FCC_Hcal.py +++ b/examples/ClientTests/scripts/FCC_Hcal.py @@ -1,5 +1,7 @@ from __future__ import absolute_import, unicode_literals -import os, time, DDG4 +import os +import time +import DDG4 from DDG4 import OutputLevel as Output from SystemOfUnits import * # @@ -12,15 +14,17 @@ from SystemOfUnits import * \version 1.0 """ + + def run(): kernel = DDG4.Kernel() install_dir = os.environ['DD4hepINSTALL'] - example_dir = install_dir+'/examples/DDG4/examples'; - kernel.setOutputLevel(str('Geant4Converter'),Output.DEBUG) - kernel.setOutputLevel(str('RootOutput'),Output.INFO) - kernel.setOutputLevel(str('ShellHandler'),Output.DEBUG) - kernel.setOutputLevel(str('Gun'),Output.INFO) - kernel.loadGeometry(str("file:"+install_dir+"/examples/ClientTests/compact/FCC_HcalBarrel.xml")) + example_dir = install_dir + '/examples/DDG4/examples' + kernel.setOutputLevel(str('Geant4Converter'), Output.DEBUG) + kernel.setOutputLevel(str('RootOutput'), Output.INFO) + kernel.setOutputLevel(str('ShellHandler'), Output.DEBUG) + kernel.setOutputLevel(str('Gun'), Output.INFO) + kernel.loadGeometry(str("file:" + install_dir + "/examples/ClientTests/compact/FCC_HcalBarrel.xml")) geant4 = DDG4.Geant4(kernel) geant4.printDetectors() @@ -29,12 +33,12 @@ def run(): # Configure field field = geant4.setupTrackingField(prt=True) # Configure I/O - evt_root = geant4.setupROOTOutput('RootOutput','FCC_'+time.strftime('%Y-%m-%d_%H-%M'),mc_truth=False) + evt_root = geant4.setupROOTOutput('RootOutput', 'FCC_' + time.strftime('%Y-%m-%d_%H-%M'), mc_truth=False) # Setup particle gun - geant4.setupGun("Gun",particle='pi-',energy=100*GeV,multiplicity=1) + geant4.setupGun("Gun", particle='pi-', energy=100 * GeV, multiplicity=1) # Now the calorimeters - seq,act = geant4.setupTracker('HcalBarrel') - seq,act = geant4.setupDetector('ContainmentShell','Geant4EscapeCounter') + seq, act = geant4.setupTracker('HcalBarrel') + seq, act = geant4.setupDetector('ContainmentShell', 'Geant4EscapeCounter') # Now build the physics list: phys = kernel.physicsList() phys.extends = 'QGSP_BERT' @@ -43,5 +47,6 @@ def run(): # and run geant4.execute() + if __name__ == "__main__": run() diff --git a/examples/ClientTests/scripts/LheD_tracker.py b/examples/ClientTests/scripts/LheD_tracker.py index 465b21271b9c55a780554b262e2607b07ca2ba8f..67ac5f3c91c3a5d0dab8f0ff4f916ad4ea5b1a14 100644 --- a/examples/ClientTests/scripts/LheD_tracker.py +++ b/examples/ClientTests/scripts/LheD_tracker.py @@ -1,7 +1,10 @@ # # from __future__ import absolute_import, unicode_literals -import os, sys, time, DDG4 +import os +import sys +import time +import DDG4 from DDG4 import OutputLevel as Output from SystemOfUnits import * import logging @@ -20,44 +23,46 @@ logger.setLevel(logging.INFO) @version 1.0 """ + + def run(): kernel = DDG4.Kernel() description = kernel.detectorDescription() - + install_dir = os.environ['DD4hepExamplesINSTALL'] - kernel.loadGeometry(str("file:"+install_dir+"/examples/ClientTests/compact/LheD_tracker.xml")) + kernel.loadGeometry(str("file:" + install_dir + "/examples/ClientTests/compact/LheD_tracker.xml")) - DDG4.importConstants(description,debug=False) - geant4 = DDG4.Geant4(kernel,tracker='Geant4TrackerCombineAction') + DDG4.importConstants(description, debug=False) + geant4 = DDG4.Geant4(kernel, tracker='Geant4TrackerCombineAction') geant4.printDetectors() # Configure UI geant4.setupCshUI() - ##geant4.setupCshUI('csh',True,True) - ##geant4.setupCshUI('csh',True,True,'vis.mac') - if len(sys.argv) >= 2 and sys.argv[1] =="batch": + # geant4.setupCshUI('csh',True,True) + # geant4.setupCshUI('csh',True,True,'vis.mac') + if len(sys.argv) >= 2 and sys.argv[1] == "batch": kernel.UI = '' - + # Configure field field = geant4.setupTrackingField(prt=True) # Configure Event actions - prt = DDG4.EventAction(kernel,'Geant4ParticlePrint/ParticlePrint') - prt.OutputLevel = Output.WARNING # Output.WARNING - prt.OutputType = 3 # Print both: table and tree + prt = DDG4.EventAction(kernel, 'Geant4ParticlePrint/ParticlePrint') + prt.OutputLevel = Output.WARNING # Output.WARNING + prt.OutputType = 3 # Print both: table and tree kernel.eventAction().adopt(prt) # Configure I/O - evt_root = geant4.setupROOTOutput('RootOutput','LHeD_tracker_'+time.strftime('%Y-%m-%d_%H-%M')) - gen = geant4.setupGun("Gun",particle='geantino',energy=20*GeV,position=(0*mm,0*mm,0*cm),multiplicity=3) + evt_root = geant4.setupROOTOutput('RootOutput', 'LHeD_tracker_' + time.strftime('%Y-%m-%d_%H-%M')) + gen = geant4.setupGun("Gun", particle='geantino', energy=20 * GeV, position=(0 * mm, 0 * mm, 0 * cm), multiplicity=3) gen.isotrop = False - gen.direction = (1,0,0) + gen.direction = (1, 0, 0) gen.OutputLevel = Output.WARNING #seq,act = geant4.setupTracker('SiVertexBarrel') # Now build the physics list: phys = geant4.setupPhysics('QGSP_BERT') - ph = DDG4.PhysicsList(kernel,'Geant4PhysicsList/Myphysics') + ph = DDG4.PhysicsList(kernel, 'Geant4PhysicsList/Myphysics') ph.addParticleConstructor(str('G4Geantino')) ph.addParticleConstructor(str('G4BosonConstructor')) ph.enableUI() @@ -67,10 +72,11 @@ def run(): kernel.configure() kernel.initialize() - #DDG4.setPrintLevel(Output.DEBUG) + # DDG4.setPrintLevel(Output.DEBUG) kernel.run() logger.info('End of run. Terminating .......') kernel.terminate() + if __name__ == "__main__": run() diff --git a/examples/ClientTests/scripts/MiniTel.py b/examples/ClientTests/scripts/MiniTel.py index 6137ac1fdfb9b050f3d18c68c1005a6151d67305..6a5b2fdec93e87fc7516e72a4084a2678986f036 100644 --- a/examples/ClientTests/scripts/MiniTel.py +++ b/examples/ClientTests/scripts/MiniTel.py @@ -1,5 +1,7 @@ from __future__ import absolute_import, unicode_literals -import os, sys, DDG4 +import os +import sys +import DDG4 # """ @@ -9,10 +11,12 @@ import os, sys, DDG4 \version 1.0 """ + + def run(): from MiniTelSetup import Setup m = Setup() - if len(sys.argv) >= 2 and sys.argv[1] =="batch": + if len(sys.argv) >= 2 and sys.argv[1] == "batch": DDG4.setPrintLevel(DDG4.OutputLevel.WARNING) m.kernel.UI = '' m.configure() @@ -22,5 +26,6 @@ def run(): m.setupPhysics() m.run() + if __name__ == "__main__": run() diff --git a/examples/ClientTests/scripts/MiniTelEnergyDeposits.py b/examples/ClientTests/scripts/MiniTelEnergyDeposits.py index 00025d0ecb71f44e6570447c7306b54802da4911..27b77d1eba3da6d751a30fb74d7c9e2cdcac3223 100644 --- a/examples/ClientTests/scripts/MiniTelEnergyDeposits.py +++ b/examples/ClientTests/scripts/MiniTelEnergyDeposits.py @@ -1,5 +1,8 @@ from __future__ import absolute_import, unicode_literals -import sys, time, DDG4, MiniTelSetup +import sys +import time +import DDG4 +import MiniTelSetup from DDG4 import OutputLevel as Output # # @@ -11,9 +14,11 @@ from DDG4 import OutputLevel as Output \version 1.0 """ + + def run(): m = MiniTelSetup.Setup() - if len(sys.argv) >= 2 and sys.argv[1] =="batch": + if len(sys.argv) >= 2 and sys.argv[1] == "batch": m.kernel.NumEvents = 200 m.kernel.UI = '' DDG4.setPrintLevel(Output.WARNING) @@ -23,8 +28,8 @@ def run(): part = m.setupGenerator() part.OutputLevel = Output.DEBUG # This is the actual test: - hit_tuple = DDG4.EventAction(m.kernel,'HitTupleAction/MiniTelTuple',True) - hit_tuple.OutputFile = 'MiniTel_EnergyDeposits_'+time.strftime('%Y-%m-%d_%H-%M')+'.root' + hit_tuple = DDG4.EventAction(m.kernel, 'HitTupleAction/MiniTelTuple', True) + hit_tuple.OutputFile = 'MiniTel_EnergyDeposits_' + time.strftime('%Y-%m-%d_%H-%M') + '.root' hit_tuple.Collections = ['*'] m.kernel.eventAction().add(hit_tuple) # Setup physics @@ -32,5 +37,6 @@ def run(): # ... and run m.geant4.execute() + if __name__ == "__main__": run() diff --git a/examples/ClientTests/scripts/MiniTelRegions.py b/examples/ClientTests/scripts/MiniTelRegions.py index c66fd28c0611f5c01beb8b275ea72f07952571fc..294ab49e52ad5a121e4be40e9332bb388275c2c5 100644 --- a/examples/ClientTests/scripts/MiniTelRegions.py +++ b/examples/ClientTests/scripts/MiniTelRegions.py @@ -17,7 +17,7 @@ if __name__ == "__main__": m = MiniTel() m.configure() logger.info("# Configure G4 geometry setup") - seq,act = m.geant4.addDetectorConstruction("Geant4DetectorGeometryConstruction/ConstructGeo") + seq, act = m.geant4.addDetectorConstruction("Geant4DetectorGeometryConstruction/ConstructGeo") act.DebugRegions = True m.test_config(True) m.terminate() diff --git a/examples/ClientTests/scripts/MiniTelSetup.py b/examples/ClientTests/scripts/MiniTelSetup.py index 066f0f975a0445fa365fdf4a2ace16ae992bb93f..74ddd51d59a8e2386b0926b532cc7977fb43b754 100644 --- a/examples/ClientTests/scripts/MiniTelSetup.py +++ b/examples/ClientTests/scripts/MiniTelSetup.py @@ -1,5 +1,7 @@ from __future__ import absolute_import, unicode_literals -import os, time, DDG4TestSetup +import os +import time +import DDG4TestSetup """ dd4hep example setup using the python configuration @@ -8,36 +10,48 @@ import os, time, DDG4TestSetup \version 1.0 """ + + class Setup(DDG4TestSetup.Setup): def __init__(self): install_dir = os.environ['DD4hepExamplesINSTALL'] - DDG4TestSetup.Setup.__init__(self, "file:"+install_dir+"/examples/ClientTests/compact/MiniTel.xml") + DDG4TestSetup.Setup.__init__(self, "file:" + install_dir + "/examples/ClientTests/compact/MiniTel.xml") - def configure(self,output_level=None): + def configure(self, output_level=None): DDG4TestSetup.Setup.configure(self) # Now the calorimeters - seq,act = self.geant4.setupTracker('MyLHCBdetector1') - if output_level: act.OutputLevel = output_level - seq,act = self.geant4.setupTracker('MyLHCBdetector2') - if output_level: act.OutputLevel = output_level - seq,act = self.geant4.setupTracker('MyLHCBdetector3') - if output_level: act.OutputLevel = output_level - seq,act = self.geant4.setupTracker('MyLHCBdetector4') - if output_level: act.OutputLevel = output_level + seq, act = self.geant4.setupTracker('MyLHCBdetector1') + if output_level: + act.OutputLevel = output_level + seq, act = self.geant4.setupTracker('MyLHCBdetector2') + if output_level: + act.OutputLevel = output_level + seq, act = self.geant4.setupTracker('MyLHCBdetector3') + if output_level: + act.OutputLevel = output_level + seq, act = self.geant4.setupTracker('MyLHCBdetector4') + if output_level: + act.OutputLevel = output_level #act.OutputLevel = 4 - seq,act = self.geant4.setupTracker('MyLHCBdetector5') - if output_level: act.OutputLevel = output_level - seq,act = self.geant4.setupTracker('MyLHCBdetector6') - if output_level: act.OutputLevel = output_level - seq,act = self.geant4.setupTracker('MyLHCBdetector7') - if output_level: act.OutputLevel = output_level - seq,act = self.geant4.setupTracker('MyLHCBdetector8') - if output_level: act.OutputLevel = output_level - seq,act = self.geant4.setupTracker('MyLHCBdetector9') - if output_level: act.OutputLevel = output_level - seq,act = self.geant4.setupTracker('MyLHCBdetector10') - if output_level: act.OutputLevel = output_level + seq, act = self.geant4.setupTracker('MyLHCBdetector5') + if output_level: + act.OutputLevel = output_level + seq, act = self.geant4.setupTracker('MyLHCBdetector6') + if output_level: + act.OutputLevel = output_level + seq, act = self.geant4.setupTracker('MyLHCBdetector7') + if output_level: + act.OutputLevel = output_level + seq, act = self.geant4.setupTracker('MyLHCBdetector8') + if output_level: + act.OutputLevel = output_level + seq, act = self.geant4.setupTracker('MyLHCBdetector9') + if output_level: + act.OutputLevel = output_level + seq, act = self.geant4.setupTracker('MyLHCBdetector10') + if output_level: + act.OutputLevel = output_level return self - def defineOutput(self,output='MiniTel_'+time.strftime('%Y-%m-%d_%H-%M')): - return DDG4TestSetup.Setup.defineOutput(self,output) + def defineOutput(self, output='MiniTel_' + time.strftime('%Y-%m-%d_%H-%M')): + return DDG4TestSetup.Setup.defineOutput(self, output) diff --git a/examples/ClientTests/scripts/MultiCollections.py b/examples/ClientTests/scripts/MultiCollections.py index 07a0e735180541b3518fae5dff16679b447c6f9b..8134391112a419cf132a940fd7729f77bd2e80a5 100644 --- a/examples/ClientTests/scripts/MultiCollections.py +++ b/examples/ClientTests/scripts/MultiCollections.py @@ -1,5 +1,8 @@ from __future__ import absolute_import, unicode_literals -import os, sys, time, DDG4 +import os +import sys +import time +import DDG4 from DDG4 import OutputLevel as Output from SystemOfUnits import * from six.moves import range @@ -13,43 +16,46 @@ from six.moves import range \version 1.0 """ + + def run(): batch = False kernel = DDG4.Kernel() install_dir = os.environ['DD4hepExamplesINSTALL'] - geometry = "file:"+install_dir+"/examples/ClientTests/compact/MultiCollections.xml" - kernel.setOutputLevel(str('Geant4Converter'),Output.DEBUG) - kernel.setOutputLevel(str('Gun'),Output.INFO) + geometry = "file:" + install_dir + "/examples/ClientTests/compact/MultiCollections.xml" + kernel.setOutputLevel(str('Geant4Converter'), Output.DEBUG) + kernel.setOutputLevel(str('Gun'), Output.INFO) for i in range(len(sys.argv)): - if sys.argv[i]=='-compact': - geometry = sys.argv[i+1] - elif sys.argv[i]=='-input': - geometry = sys.argv[i+1] - elif sys.argv[i]=='-batch': + if sys.argv[i] == '-compact': + geometry = sys.argv[i + 1] + elif sys.argv[i] == '-input': + geometry = sys.argv[i + 1] + elif sys.argv[i] == '-batch': batch = True - elif sys.argv[i]=='batch': + elif sys.argv[i] == 'batch': batch = True kernel.loadGeometry(str(geometry)) geant4 = DDG4.Geant4(kernel) geant4.printDetectors() geant4.setupCshUI() - if batch: kernel.UI = '' + if batch: + kernel.UI = '' # Configure field field = geant4.setupTrackingField(prt=True) # Configure I/O - evt_root = geant4.setupROOTOutput('RootOutput','Multi_coll_'+time.strftime('%Y-%m-%d_%H-%M'),mc_truth=True) + evt_root = geant4.setupROOTOutput('RootOutput', 'Multi_coll_' + time.strftime('%Y-%m-%d_%H-%M'), mc_truth=True) # Setup particle gun - geant4.setupGun("Gun",particle='pi-',energy=10*GeV,multiplicity=1) + geant4.setupGun("Gun", particle='pi-', energy=10 * GeV, multiplicity=1) # Now the test calorimeter with multiple collections - seq,act = geant4.setupCalorimeter('TestCal') + seq, act = geant4.setupCalorimeter('TestCal') # And handle the simulation particles. - part = DDG4.GeneratorAction(kernel,"Geant4ParticleHandler/ParticleHandler") + part = DDG4.GeneratorAction(kernel, "Geant4ParticleHandler/ParticleHandler") kernel.generatorAction().adopt(part) - part.MinimalKineticEnergy = 1*MeV + part.MinimalKineticEnergy = 1 * MeV part.enableUI() # Now build the physics list: @@ -60,5 +66,6 @@ def run(): # and run geant4.execute() + if __name__ == "__main__": run() diff --git a/examples/ClientTests/scripts/MultiSegmentCollections.py b/examples/ClientTests/scripts/MultiSegmentCollections.py index eec0718d162dbd5d314a4d0f5202a21f64b867b5..7af8380d4e3496e4322af6a64a21dafbd3bbd824 100644 --- a/examples/ClientTests/scripts/MultiSegmentCollections.py +++ b/examples/ClientTests/scripts/MultiSegmentCollections.py @@ -1,5 +1,8 @@ from __future__ import absolute_import, unicode_literals -import os, sys, time, DDG4 +import os +import sys +import time +import DDG4 from DDG4 import OutputLevel as Output from SystemOfUnits import * from six.moves import range @@ -13,65 +16,68 @@ from six.moves import range \version 1.0 """ + + def run(): batch = False kernel = DDG4.Kernel() install_dir = os.environ['DD4hepExamplesINSTALL'] - geometry = "file:"+install_dir+"/examples/ClientTests/compact/MultiSegmentCollections.xml" - kernel.setOutputLevel(str('Geant4Converter'),Output.DEBUG) - kernel.setOutputLevel(str('Gun'),Output.INFO) + geometry = "file:" + install_dir + "/examples/ClientTests/compact/MultiSegmentCollections.xml" + kernel.setOutputLevel(str('Geant4Converter'), Output.DEBUG) + kernel.setOutputLevel(str('Gun'), Output.INFO) for i in range(len(sys.argv)): - if sys.argv[i]=='-compact': - geometry = sys.argv[i+1] - elif sys.argv[i]=='-input': - geometry = sys.argv[i+1] - elif sys.argv[i]=='-batch': + if sys.argv[i] == '-compact': + geometry = sys.argv[i + 1] + elif sys.argv[i] == '-input': + geometry = sys.argv[i + 1] + elif sys.argv[i] == '-batch': batch = True - elif sys.argv[i]=='batch': + elif sys.argv[i] == 'batch': batch = True kernel.loadGeometry(str(geometry)) geant4 = DDG4.Geant4(kernel) geant4.printDetectors() geant4.setupCshUI() - if batch: kernel.UI = '' + if batch: + kernel.UI = '' # Configure field field = geant4.setupTrackingField(prt=True) # Setup particle gun - geant4.setupGun("Gun",particle='pi-',energy=50*GeV,multiplicity=1) + geant4.setupGun("Gun", particle='pi-', energy=50 * GeV, multiplicity=1) # Now the test calorimeter with multiple collections - seq,act = geant4.setupCalorimeter('TestCal') + seq, act = geant4.setupCalorimeter('TestCal') # And handle the simulation particles. - part = DDG4.GeneratorAction(kernel,"Geant4ParticleHandler/ParticleHandler") + part = DDG4.GeneratorAction(kernel, "Geant4ParticleHandler/ParticleHandler") kernel.generatorAction().adopt(part) - part.MinimalKineticEnergy = 1*MeV + part.MinimalKineticEnergy = 1 * MeV part.enableUI() # Add the particle dumper to associate the MC truth - evt = DDG4.EventAction(kernel,"Geant4ParticleDumpAction/ParticleDump") + evt = DDG4.EventAction(kernel, "Geant4ParticleDumpAction/ParticleDump") kernel.eventAction().adopt(evt) evt.enableUI() # Add the hit dumper BEFORE any hit truth is fixed - evt = DDG4.EventAction(kernel,"Geant4HitDumpAction/RawDump") + evt = DDG4.EventAction(kernel, "Geant4HitDumpAction/RawDump") kernel.eventAction().adopt(evt) evt.enableUI() # Add the hit dumper to the event action sequence - evt = DDG4.EventAction(kernel,"Geant4HitTruthHandler/HitTruth") + evt = DDG4.EventAction(kernel, "Geant4HitTruthHandler/HitTruth") kernel.eventAction().adopt(evt) evt.enableUI() # Add the hit dumper AFTER any hit truth is fixed. We should see the reduced track references - evt = DDG4.EventAction(kernel,"Geant4HitDumpAction/HitDump") + evt = DDG4.EventAction(kernel, "Geant4HitDumpAction/HitDump") kernel.eventAction().adopt(evt) evt.enableUI() # Configure I/O - evt_root = geant4.setupROOTOutput('RootOutput','Multi_coll_'+time.strftime('%Y-%m-%d_%H-%M'),mc_truth=True) + evt_root = geant4.setupROOTOutput('RootOutput', 'Multi_coll_' + time.strftime('%Y-%m-%d_%H-%M'), mc_truth=True) evt_root.HandleMCTruth = False # Now build the physics list: @@ -82,5 +88,6 @@ def run(): # and run geant4.execute() + if __name__ == "__main__": run() diff --git a/examples/ClientTests/scripts/NestedDetectors.py b/examples/ClientTests/scripts/NestedDetectors.py index 69647c5dc8198aa47a0ee89805293cb73b22ba9a..0424846730014b63a5279608ad7779975bfd6ec9 100644 --- a/examples/ClientTests/scripts/NestedDetectors.py +++ b/examples/ClientTests/scripts/NestedDetectors.py @@ -1,5 +1,8 @@ from __future__ import absolute_import, unicode_literals -import os, sys, time, DDG4 +import os +import sys +import time +import DDG4 from DDG4 import OutputLevel as Output from SystemOfUnits import * # @@ -12,33 +15,35 @@ from SystemOfUnits import * \version 1.0 """ + + def run(): kernel = DDG4.Kernel() install_dir = os.environ['DD4hepExamplesINSTALL'] - kernel.setOutputLevel(str('Geant4Converter'),Output.DEBUG) - kernel.setOutputLevel(str('Gun'),Output.INFO) - kernel.loadGeometry(str("file:"+install_dir+"/examples/ClientTests/compact/NestedDetectors.xml")) + kernel.setOutputLevel(str('Geant4Converter'), Output.DEBUG) + kernel.setOutputLevel(str('Gun'), Output.INFO) + kernel.loadGeometry(str("file:" + install_dir + "/examples/ClientTests/compact/NestedDetectors.xml")) geant4 = DDG4.Geant4(kernel) geant4.printDetectors() geant4.setupCshUI() - if len(sys.argv) >= 2 and sys.argv[1] =="batch": + if len(sys.argv) >= 2 and sys.argv[1] == "batch": kernel.UI = '' # Configure field field = geant4.setupTrackingField(prt=True) # Configure I/O - evt_root = geant4.setupROOTOutput('RootOutput','Nested_'+time.strftime('%Y-%m-%d_%H-%M'),mc_truth=True) + evt_root = geant4.setupROOTOutput('RootOutput', 'Nested_' + time.strftime('%Y-%m-%d_%H-%M'), mc_truth=True) # Setup particle gun - geant4.setupGun("Gun",particle='pi-',energy=100*GeV,multiplicity=1) + geant4.setupGun("Gun", particle='pi-', energy=100 * GeV, multiplicity=1) # Now the calorimeters - seq,act = geant4.setupTracker('SiTrackerBarrel') - seq,act = geant4.setupTracker('SiVertexBarrel') + seq, act = geant4.setupTracker('SiTrackerBarrel') + seq, act = geant4.setupTracker('SiVertexBarrel') # And handle the simulation particles. - part = DDG4.GeneratorAction(kernel,"Geant4ParticleHandler/ParticleHandler") + part = DDG4.GeneratorAction(kernel, "Geant4ParticleHandler/ParticleHandler") kernel.generatorAction().adopt(part) - part.SaveProcesses = ['conv','Decay'] - part.MinimalKineticEnergy = 1*MeV + part.SaveProcesses = ['conv', 'Decay'] + part.MinimalKineticEnergy = 1 * MeV part.enableUI() # Now build the physics list: @@ -49,5 +54,6 @@ def run(): # and run geant4.execute() + if __name__ == "__main__": run() diff --git a/examples/ClientTests/scripts/SiliconBlock.py b/examples/ClientTests/scripts/SiliconBlock.py index 5fd14a5bc8d2322223f54d4b05819f8f3adcf5bf..b0e30273317fd50f935ffe981c62df3dc2b5f922 100644 --- a/examples/ClientTests/scripts/SiliconBlock.py +++ b/examples/ClientTests/scripts/SiliconBlock.py @@ -1,7 +1,10 @@ # # from __future__ import absolute_import, unicode_literals -import os, sys, time, DDG4 +import os +import sys +import time +import DDG4 from DDG4 import OutputLevel as Output from SystemOfUnits import * # @@ -14,16 +17,18 @@ from SystemOfUnits import * @version 1.0 """ + + def run(): kernel = DDG4.Kernel() install_dir = os.environ['DD4hepExamplesINSTALL'] - kernel.loadGeometry(str("file:"+install_dir+"/examples/ClientTests/compact/SiliconBlock.xml")) + kernel.loadGeometry(str("file:" + install_dir + "/examples/ClientTests/compact/SiliconBlock.xml")) - DDG4.importConstants(kernel.detectorDescription(),debug=False) - geant4 = DDG4.Geant4(kernel,tracker='Geant4TrackerCombineAction') + DDG4.importConstants(kernel.detectorDescription(), debug=False) + geant4 = DDG4.Geant4(kernel, tracker='Geant4TrackerCombineAction') geant4.printDetectors() # Configure UI - if len(sys.argv)>1: + if len(sys.argv) > 1: geant4.setupCshUI(macro=sys.argv[1]) else: geant4.setupCshUI() @@ -31,37 +36,37 @@ def run(): # Configure field field = geant4.setupTrackingField(prt=True) # Configure Event actions - prt = DDG4.EventAction(kernel,'Geant4ParticlePrint/ParticlePrint') + prt = DDG4.EventAction(kernel, 'Geant4ParticlePrint/ParticlePrint') prt.OutputLevel = Output.DEBUG - prt.OutputType = 3 # Print both: table and tree + prt.OutputType = 3 # Print both: table and tree kernel.eventAction().adopt(prt) generator_output_level = Output.INFO # Configure G4 geometry setup - seq,act = geant4.addDetectorConstruction("Geant4DetectorGeometryConstruction/ConstructGeo") + seq, act = geant4.addDetectorConstruction("Geant4DetectorGeometryConstruction/ConstructGeo") act.DebugMaterials = True - act.DebugElements = False - act.DebugVolumes = True - act.DebugShapes = True + act.DebugElements = False + act.DebugVolumes = True + act.DebugShapes = True # Configure I/O - evt_root = geant4.setupROOTOutput('RootOutput','SiliconBlock_'+time.strftime('%Y-%m-%d_%H-%M')) + evt_root = geant4.setupROOTOutput('RootOutput', 'SiliconBlock_' + time.strftime('%Y-%m-%d_%H-%M')) # Setup particle gun - gun = geant4.setupGun("Gun",particle='mu-',energy=20*GeV,multiplicity=1) + gun = geant4.setupGun("Gun", particle='mu-', energy=20 * GeV, multiplicity=1) gun.OutputLevel = generator_output_level # And handle the simulation particles. - part = DDG4.GeneratorAction(kernel,"Geant4ParticleHandler/ParticleHandler") + part = DDG4.GeneratorAction(kernel, "Geant4ParticleHandler/ParticleHandler") kernel.generatorAction().adopt(part) part.SaveProcesses = ['Decay'] - part.MinimalKineticEnergy = 100*MeV - part.OutputLevel = Output.INFO #generator_output_level + part.MinimalKineticEnergy = 100 * MeV + part.OutputLevel = Output.INFO # generator_output_level part.enableUI() - user = DDG4.Action(kernel,"Geant4TCUserParticleHandler/UserParticleHandler") - user.TrackingVolume_Zmax = 3.0*m - user.TrackingVolume_Rmax = 3.0*m + user = DDG4.Action(kernel, "Geant4TCUserParticleHandler/UserParticleHandler") + user.TrackingVolume_Zmax = 3.0 * m + user.TrackingVolume_Rmax = 3.0 * m user.enableUI() part.adopt(user) @@ -70,7 +75,7 @@ def run(): # Now build the physics list: phys = geant4.setupPhysics('QGSP_BERT') - ph = DDG4.PhysicsList(kernel,'Geant4PhysicsList/Myphysics') + ph = DDG4.PhysicsList(kernel, 'Geant4PhysicsList/Myphysics') ph.addParticleConstructor('G4Geantino') ph.addParticleConstructor('G4BosonConstructor') ph.enableUI() @@ -79,5 +84,6 @@ def run(): geant4.execute() + if __name__ == "__main__": run() diff --git a/examples/ClientTests/scripts/TrackingRegion.py b/examples/ClientTests/scripts/TrackingRegion.py index f89ba5e2c1a7a48690b8b48c8c5b2446de82f8de..ae5b25e9de3446543d2416df700612018c77acfd 100644 --- a/examples/ClientTests/scripts/TrackingRegion.py +++ b/examples/ClientTests/scripts/TrackingRegion.py @@ -1,7 +1,10 @@ # # from __future__ import absolute_import, unicode_literals -import os, sys, time, DDG4 +import os +import sys +import time +import DDG4 # """ @@ -11,16 +14,18 @@ import os, sys, time, DDG4 @version 1.0 """ + + def run(): kernel = DDG4.Kernel() install_dir = os.environ['DD4hepExamplesINSTALL'] - kernel.loadGeometry(str("file:"+install_dir+"/examples/ClientTests/compact/TrackingRegion.xml")) - geant4 = DDG4.Geant4(kernel,tracker='Geant4TrackerCombineAction') + kernel.loadGeometry(str("file:" + install_dir + "/examples/ClientTests/compact/TrackingRegion.xml")) + geant4 = DDG4.Geant4(kernel, tracker='Geant4TrackerCombineAction') # Configure field ##field = geant4.setupTrackingField(prt=True) # Configure G4 geometry setup - seq,act = geant4.addDetectorConstruction("Geant4DetectorGeometryConstruction/ConstructGeo") - act.DebugVolumes = True + seq, act = geant4.addDetectorConstruction("Geant4DetectorGeometryConstruction/ConstructGeo") + act.DebugVolumes = True act.DebugPlacements = True geant4.setupTracker('SiliconBlock') kernel.configure() @@ -28,5 +33,6 @@ def run(): kernel.terminate() sys.exit(0) + if __name__ == "__main__": run() diff --git a/examples/DDCMS/scripts/CMSTrackerSim.py b/examples/DDCMS/scripts/CMSTrackerSim.py index ff0d50e5d20d247c6966fa692b85bfc91cdd5d33..1d09395be6aa42330b18738c819c3621fa1406ab 100644 --- a/examples/DDCMS/scripts/CMSTrackerSim.py +++ b/examples/DDCMS/scripts/CMSTrackerSim.py @@ -1,5 +1,8 @@ from __future__ import absolute_import, unicode_literals -import os, sys, time, DDG4 +import os +import sys +import time +import DDG4 from DDG4 import OutputLevel as Output from SystemOfUnits import * import logging @@ -19,40 +22,46 @@ logger.setLevel(logging.INFO) \version 1.0 """ + + def run(): kernel = DDG4.Kernel() install_dir = os.environ['DD4hepINSTALL'] - kernel.setOutputLevel(str('Geant4Converter'),Output.DEBUG) - kernel.setOutputLevel(str('Gun'),Output.INFO) - kernel.detectorDescription().fromXML(str("file:"+install_dir+"/examples/DDCMS/data/dd4hep-config.xml")); + kernel.setOutputLevel(str('Geant4Converter'), Output.DEBUG) + kernel.setOutputLevel(str('Gun'), Output.INFO) + kernel.detectorDescription().fromXML(str("file:" + install_dir + "/examples/DDCMS/data/dd4hep-config.xml")) kernel.NumEvents = 5 - geant4 = DDG4.Geant4(kernel,tracker='Geant4TrackerCombineAction') + geant4 = DDG4.Geant4(kernel, tracker='Geant4TrackerCombineAction') geant4.printDetectors() geant4.setupCshUI() batch = False - test = False + test = False for i in range(len(sys.argv)): arg = sys.argv[i].lower() if arg == 'batch': batch = True elif arg == 'test': - test = True + test = True elif arg == 'numevents': - kernel.NumEvents = int(sys.argv[i+1]) + kernel.NumEvents = int(sys.argv[i + 1]) if batch or test: kernel.UI = '' # Configure field field = geant4.setupTrackingField(prt=True) # Configure I/O - evt_root = geant4.setupROOTOutput('RootOutput','CMSTracker_'+time.strftime('%Y-%m-%d_%H-%M'),mc_truth=True) + evt_root = geant4.setupROOTOutput('RootOutput', 'CMSTracker_' + time.strftime('%Y-%m-%d_%H-%M'), mc_truth=True) # Setup particle gun generators = [] - generators.append(geant4.setupGun("GunPi-",particle='pi-',energy=300*GeV,multiplicity=1,Standalone=False,register=False, Mask=1)) + generators.append(geant4.setupGun("GunPi-", particle='pi-', energy=300 * GeV, + multiplicity=1, Standalone=False, register=False, Mask=1)) if not test: - generators.append(geant4.setupGun("GunPi+",particle='pi+',energy=300*GeV,multiplicity=1,Standalone=False,register=False, Mask=2)) - generators.append(geant4.setupGun("GunE-",particle='e-',energy=100*GeV,multiplicity=1,Standalone=False,register=False, Mask=4)) - generators.append(geant4.setupGun("GunE+",particle='e+',energy=100*GeV,multiplicity=1,Standalone=False,register=False, Mask=8)) + generators.append(geant4.setupGun("GunPi+", particle='pi+', energy=300 * GeV, + multiplicity=1, Standalone=False, register=False, Mask=2)) + generators.append(geant4.setupGun("GunE-", particle='e-', energy=100 * GeV, + multiplicity=1, Standalone=False, register=False, Mask=4)) + generators.append(geant4.setupGun("GunE+", particle='e+', energy=100 * GeV, + multiplicity=1, Standalone=False, register=False, Mask=8)) geant4.buildInputStage(generators) # Now setup all tracking detectors for i in geant4.description.detectors(): @@ -60,15 +69,15 @@ def run(): sd = geant4.description.sensitiveDetector(o.name()) if sd.isValid(): type = geant4.sensitive_types[sd.type()] - logger.info('CMSTracker: Configure subdetector %-24s of type %s'%(o.name(),type,)) - geant4.setupDetector(o.name(),type) + logger.info('CMSTracker: Configure subdetector %-24s of type %s' % (o.name(), type,)) + geant4.setupDetector(o.name(), type) # And handle the simulation particles. - part = DDG4.GeneratorAction(kernel,"Geant4ParticleHandler/ParticleHandler") + part = DDG4.GeneratorAction(kernel, "Geant4ParticleHandler/ParticleHandler") kernel.generatorAction().adopt(part) - part.SaveProcesses = ['conv','Decay'] - part.MinimalKineticEnergy = 1*MeV - part.OutputLevel = 5 # generator_output_level + part.SaveProcesses = ['conv', 'Decay'] + part.MinimalKineticEnergy = 1 * MeV + part.OutputLevel = 5 # generator_output_level part.enableUI() # Now build the physics list: @@ -78,5 +87,6 @@ def run(): # and run geant4.execute() + if __name__ == "__main__": run() diff --git a/examples/DDCodex/python/CODEX-b-alone.py b/examples/DDCodex/python/CODEX-b-alone.py index 64915c6369b9f6e08fb2d106ecf9fab05cd9684a..e6192b9cf1a36f66e4d2f6f6e1985d81c7e0beb0 100755 --- a/examples/DDCodex/python/CODEX-b-alone.py +++ b/examples/DDCodex/python/CODEX-b-alone.py @@ -1,7 +1,10 @@ # # from __future__ import absolute_import, unicode_literals -import os, sys, time, DDG4 +import os +import sys +import time +import DDG4 from DDG4 import OutputLevel as Output from SystemOfUnits import * # @@ -14,16 +17,18 @@ from SystemOfUnits import * @version 1.0 """ + + def run(): kernel = DDG4.Kernel() install_dir = os.environ['DD4hepExamplesINSTALL'] - kernel.loadGeometry(str("file:"+install_dir+"/examples/DDCodex/compact/CODEX-b-alone.xml")) + kernel.loadGeometry(str("file:" + install_dir + "/examples/DDCodex/compact/CODEX-b-alone.xml")) - DDG4.importConstants(kernel.detectorDescription(),debug=False) - geant4 = DDG4.Geant4(kernel,tracker='Geant4TrackerCombineAction') + DDG4.importConstants(kernel.detectorDescription(), debug=False) + geant4 = DDG4.Geant4(kernel, tracker='Geant4TrackerCombineAction') geant4.printDetectors() # Configure UI - if len(sys.argv)>1: + if len(sys.argv) > 1: geant4.setupCshUI(macro=sys.argv[1]) else: geant4.setupCshUI() @@ -31,26 +36,26 @@ def run(): # Configure field field = geant4.setupTrackingField(prt=True) # Configure Event actions - prt = DDG4.EventAction(kernel,'Geant4ParticlePrint/ParticlePrint') + prt = DDG4.EventAction(kernel, 'Geant4ParticlePrint/ParticlePrint') prt.OutputLevel = Output.WARNING - prt.OutputType = 3 # Print both: table and tree + prt.OutputType = 3 # Print both: table and tree kernel.eventAction().adopt(prt) # Configure I/O - evt_root = geant4.setupROOTOutput('RootOutput','CodexB_'+time.strftime('%Y-%m-%d_%H-%M')) + evt_root = geant4.setupROOTOutput('RootOutput', 'CodexB_' + time.strftime('%Y-%m-%d_%H-%M')) # Setup particle gun - - #gun = geant4.setupGun("Gun",particle='pi+', - gun = geant4.setupGun("Gun",particle='mu-', - energy=1000*GeV, + + # gun = geant4.setupGun("Gun",particle='pi+', + gun = geant4.setupGun("Gun", particle='mu-', + energy=1000 * GeV, multiplicity=1, - isotrop=False,Standalone=True, - direction=(1,0,0), - #direction=(0.866025,0,0.5), + isotrop=False, Standalone=True, + direction=(1, 0, 0), + # direction=(0.866025,0,0.5), position='(0,0,12650)') - #position='(0,0,0)') - setattr(gun,'print',True) + # position='(0,0,0)') + setattr(gun, 'print', True) """ gen = DDG4.GeneratorAction(kernel,"Geant4InputAction/Input") ##gen.Input = "Geant4EventReaderHepMC|"+ "/afs/cern.ch/work/j/jongho/Project_DD4hep/Test/DD4hep/examples/DDG4/data/hepmc_geant4.dat" @@ -60,27 +65,26 @@ def run(): geant4.buildInputStage([gen],output_level=Output.DEBUG) """ - seq,action = geant4.setupTracker('CODEXb') + seq, action = geant4.setupTracker('CODEXb') #action.OutputLevel = Output.ERROR #seq,action = geant4.setupTracker('Shield') #action.OutputLevel = Output.ERROR # And handle the simulation particles. - part = DDG4.GeneratorAction(kernel,"Geant4ParticleHandler/ParticleHandler") + part = DDG4.GeneratorAction(kernel, "Geant4ParticleHandler/ParticleHandler") kernel.generatorAction().adopt(part) part.OutputLevel = Output.INFO part.enableUI() - user = DDG4.Action(kernel,"Geant4TCUserParticleHandler/UserParticleHandler") - user.TrackingVolume_Zmax = 999999.*m # Something big. All is a tracker - user.TrackingVolume_Rmax = 999999.*m + user = DDG4.Action(kernel, "Geant4TCUserParticleHandler/UserParticleHandler") + user.TrackingVolume_Zmax = 999999. * m # Something big. All is a tracker + user.TrackingVolume_Rmax = 999999. * m user.enableUI() part.adopt(user) - # Now build the physics list: ##phys = kernel.physicsList() phys = geant4.setupPhysics('QGSP_BERT') - ph = DDG4.PhysicsList(kernel,'Geant4PhysicsList/Myphysics') + ph = DDG4.PhysicsList(kernel, 'Geant4PhysicsList/Myphysics') ph.addParticleConstructor('G4LeptonConstructor') ph.addParticleConstructor('G4BaryonConstructor') ph.addParticleConstructor('G4MesonConstructor') @@ -95,5 +99,6 @@ def run(): kernel.run() kernel.terminate() + if __name__ == "__main__": run() diff --git a/examples/DDCodex/python/GeoExtract.py b/examples/DDCodex/python/GeoExtract.py index d4885d9865461750aa6532ea473dccbeca50f119..cf4dbf1747ca44088e72556ace50cdbdf4c072da 100755 --- a/examples/DDCodex/python/GeoExtract.py +++ b/examples/DDCodex/python/GeoExtract.py @@ -5,7 +5,7 @@ # gaudirun.py Brunel-Default.py <someDataFiles>.py ############################################################################### from __future__ import absolute_import, unicode_literals -from Gaudi.Configuration import * +from Gaudi.Configuration import * from Configurables import LHCbConfigurableUser, LHCbApp, CondDB, ToolSvc, EventSelector from Configurables import LoadDD4hepDet, LbDD4hepExample import GaudiKernel.ProcessJobOptions @@ -15,71 +15,61 @@ import GaudiKernel.ProcessJobOptions class MyTest(LHCbConfigurableUser): - # Steering options - __slots__ = { - "DDDBtag" : "" - ,"CondDBtag" : "" - ,"UseDBSnapshot" : False - ,"PartitionName" : "LHCb" - ,"DBSnapshotDirectory" : "/group/online/hlt/conditions" - } + # Steering options + __slots__ = { + "DDDBtag": "", "CondDBtag": "", "UseDBSnapshot": False, "PartitionName": "LHCb", "DBSnapshotDirectory": "/group/online/hlt/conditions" + } - _propertyDocDct = { - 'DDDBtag' : """ Tag for DDDB """ - ,'CondDBtag' : """ Tag for CondDB """ - ,"UseDBSnapshot" : """Use a snapshot for velo position and rich pressure""" - ,"PartitionName" : """Name of the partition when running (needed to find DB: '', 'FEST', or 'LHCb'""" - ,"DBSnapshotDirectory" : """Local Directory where the snapshot is""" - } + _propertyDocDct = { + 'DDDBtag': """ Tag for DDDB """, 'CondDBtag': """ Tag for CondDB """, "UseDBSnapshot": """Use a snapshot for velo position and rich pressure""", "PartitionName": """Name of the partition when running (needed to find DB: '', 'FEST', or 'LHCb'""", "DBSnapshotDirectory": """Local Directory where the snapshot is""" + } - ## Apply the configuration - def __apply_configuration__(self): - actor = LoadDD4hepDet() - actor.OutputLevel = DEBUG - #actor.SetupPlugins = ['DDCondDetElementMapping','DDDB_AssignConditions','DDDB_DetectorConditionKeysDump'] - actor.SetupPlugins = ['DDDB_DetectorDump','DD4hep_InteractiveUI','DD4hep_Rint'] - actor.DumpDetElements = 0 - actor.DumpDetVolumes = 0 - actor.DumpConditions = "" - #actor.DumpConditions = "DDDB_DetElementConditionDump" - #actor.DumpAlignments = "DDDB_AlignmentDump" - #actor.DumpAlignments = "DDDB_DerivedCondTest" - actor.ScanConditions = 0 - pxml = None - try: - pxml = os.path.join(os.path.dirname(os.path.realpath(__file__)), "Parameters.xml") - except: - pxml = os.path.join(os.getcwd(), "Parameters.xml") - actor.Parameters = "file://" + pxml - actor.VisAttrs = os.path.join(os.getcwd(), "Visattrs.xml") - #actor.Config = [os.path.join(os.getcwd(), "apps/DD4hep/examples/DDDB/data/VPOnly.xml")] + # Apply the configuration + def __apply_configuration__(self): + actor = LoadDD4hepDet() + actor.OutputLevel = DEBUG + #actor.SetupPlugins = ['DDCondDetElementMapping','DDDB_AssignConditions','DDDB_DetectorConditionKeysDump'] + actor.SetupPlugins = ['DDDB_DetectorDump', 'DD4hep_InteractiveUI', 'DD4hep_Rint'] + actor.DumpDetElements = 0 + actor.DumpDetVolumes = 0 + actor.DumpConditions = "" + #actor.DumpConditions = "DDDB_DetElementConditionDump" + #actor.DumpAlignments = "DDDB_AlignmentDump" + #actor.DumpAlignments = "DDDB_DerivedCondTest" + actor.ScanConditions = 0 + pxml = None + try: + pxml = os.path.join(os.path.dirname(os.path.realpath(__file__)), "Parameters.xml") + except: + pxml = os.path.join(os.getcwd(), "Parameters.xml") + actor.Parameters = "file://" + pxml + actor.VisAttrs = os.path.join(os.getcwd(), "Visattrs.xml") + #actor.Config = [os.path.join(os.getcwd(), "apps/DD4hep/examples/DDDB/data/VPOnly.xml")] + + example_alg = LbDD4hepExample() + ApplicationMgr().TopAlg = [actor, example_alg] - example_alg = LbDD4hepExample() - ApplicationMgr().TopAlg = [actor, example_alg] # Just instantiate the configurable... theApp = MyTest() -ToolSvc.LogLevel=DEBUG +ToolSvc.LogLevel = DEBUG cdb = CondDB() -tag = { "DDDB": '' - , "LHCBCOND": 'default' - #, "SIMCOND" : 'upgrade/dd4hep' - , "SIMCOND" : '' - , "ONLINE" : 'fake' - } +tag = {"DDDB": '', "LHCBCOND": 'default' # , "SIMCOND" : 'upgrade/dd4hep' + , "SIMCOND": '', "ONLINE": 'fake' + } cdb.Tags = tag cdb.setProp('IgnoreHeartBeat', True) cdb.setProp('EnableRunChangeHandler', True) #cdb.LogFile = "/tmp/cdb.log" cdb.Upgrade = True -theApp.setOtherProps( cdb, [ 'UseDBSnapshot', - 'DBSnapshotDirectory', - 'PartitionName' ]) +theApp.setOtherProps(cdb, ['UseDBSnapshot', + 'DBSnapshotDirectory', + 'PartitionName']) #-- Use latest database tags for real data #LHCbApp().DDDBtag = "" #LHCbApp().CondDBtag = "default" -LHCbApp().EvtMax = 5 +LHCbApp().EvtMax = 5 LHCbApp().DataType = "Upgrade" LHCbApp().Simulation = True EventSelector().PrintFreq = 1 diff --git a/examples/DDDigi/scripts/TestFramework.py b/examples/DDDigi/scripts/TestFramework.py index 7975af40cc06b70afaeef82c996883f16d72b6ad..90a58202ded925948a8a464f5ad954b3ec62b9bc 100644 --- a/examples/DDDigi/scripts/TestFramework.py +++ b/examples/DDDigi/scripts/TestFramework.py @@ -1,12 +1,14 @@ from __future__ import absolute_import, unicode_literals -import os, sys, DDDigi +import os +import sys +import DDDigi DDDigi.setPrintFormat(str('%-32s %5s %s')) kernel = DDDigi.Kernel() install_dir = os.environ['DD4hepINSTALL'] -fname = "file:"+install_dir+"/examples/ClientTests/compact/MiniTel.xml" +fname = "file:" + install_dir + "/examples/ClientTests/compact/MiniTel.xml" kernel.loadGeometry(str(fname)) kernel.printProperties() digi = DDDigi.Digitize(kernel) @@ -14,24 +16,25 @@ digi.printDetectors() def make_input(): - input_1 = DDDigi.TestAction(kernel,'input_01', 100) - input_2 = DDDigi.TestAction(kernel,'input_02', 200) - input_3 = DDDigi.TestAction(kernel,'input_03', 150) - input_4 = DDDigi.TestAction(kernel,'input_04', 60) - seq = kernel.inputAction() + input_1 = DDDigi.TestAction(kernel, 'input_01', 100) + input_2 = DDDigi.TestAction(kernel, 'input_02', 200) + input_3 = DDDigi.TestAction(kernel, 'input_03', 150) + input_4 = DDDigi.TestAction(kernel, 'input_04', 60) + seq = kernel.inputAction() seq.adopt(input_1) seq.adopt(input_2) seq.adopt(input_3) seq.adopt(input_4) return seq + def make_subdetector(name): - action_1 = DDDigi.TestAction(kernel,name+'_deposits', 150) - action_2 = DDDigi.TestAction(kernel,name+'_rndmNoise', 100) - action_3 = DDDigi.TestAction(kernel,name+'_deadChan', 100) - action_4 = DDDigi.TestAction(kernel,name+'_noiseChan', 50) - action_5 = DDDigi.TestAction(kernel,name+'_merge', 200) - seq = DDDigi.ActionSequence(kernel,'DigiActionSequence/'+name+'_sequence',True) + action_1 = DDDigi.TestAction(kernel, name + '_deposits', 150) + action_2 = DDDigi.TestAction(kernel, name + '_rndmNoise', 100) + action_3 = DDDigi.TestAction(kernel, name + '_deadChan', 100) + action_4 = DDDigi.TestAction(kernel, name + '_noiseChan', 50) + action_5 = DDDigi.TestAction(kernel, name + '_merge', 200) + seq = DDDigi.ActionSequence(kernel, 'DigiActionSequence/' + name + '_sequence', True) seq.adopt(action_1) seq.adopt(action_2) seq.adopt(action_3) @@ -39,7 +42,8 @@ def make_subdetector(name): seq.adopt(action_5) return seq -event_processor = DDDigi.Synchronize(kernel,'DigiSynchronize/MainDigitizer',True) + +event_processor = DDDigi.Synchronize(kernel, 'DigiSynchronize/MainDigitizer', True) event_processor.parallel = True detectors = DDDigi # input @@ -51,13 +55,13 @@ for d in dets: event_processor.adopt(seq) kernel.eventAction().adopt(event_processor) # Output -output = DDDigi.TestAction(kernel,'output_01', 200) +output = DDDigi.TestAction(kernel, 'output_01', 200) kernel.outputAction().adopt(output) DDDigi.setPrintLevel(DDDigi.OutputLevel.DEBUG) -kernel.numThreads = 0 # = number of concurrent threads -kernel.numEvents = 10 +kernel.numThreads = 0 # = number of concurrent threads +kernel.numEvents = 10 kernel.maxEventsParallel = 3 kernel.run() DDDigi.setPrintLevel(DDDigi.OutputLevel.INFO) diff --git a/examples/DDG4_MySensDet/scripts/MyTrackerSD_sim.py b/examples/DDG4_MySensDet/scripts/MyTrackerSD_sim.py index 2c4e5f28f4b0e1b9e4f44e977bf5c9a822de02f3..9ca80432bba6a60717a5da35da3aa56d30a095c1 100644 --- a/examples/DDG4_MySensDet/scripts/MyTrackerSD_sim.py +++ b/examples/DDG4_MySensDet/scripts/MyTrackerSD_sim.py @@ -1,7 +1,11 @@ # # from __future__ import absolute_import, unicode_literals -import os, sys, time, DDG4, dd4hep +import os +import sys +import time +import DDG4 +import dd4hep from DDG4 import OutputLevel as Output from SystemOfUnits import * # @@ -14,15 +18,17 @@ from SystemOfUnits import * @version 1.0 """ + + def run(): kernel = DDG4.Kernel() install_dir = os.environ['DD4hepExamplesINSTALL'] - kernel.loadGeometry(str("file:"+install_dir+"/examples/ClientTests/compact/SiliconBlock.xml")) - DDG4.importConstants(kernel.detectorDescription(),debug=False) + kernel.loadGeometry(str("file:" + install_dir + "/examples/ClientTests/compact/SiliconBlock.xml")) + DDG4.importConstants(kernel.detectorDescription(), debug=False) # ======================================================================================= # ===> This is actually the ONLY difference to ClientTests/scripts/SiliconBlock.py # ======================================================================================= - geant4 = DDG4.Geant4(kernel,tracker='MyTrackerSDAction') + geant4 = DDG4.Geant4(kernel, tracker='MyTrackerSDAction') geant4.printDetectors() kernel.NumEvents = 5 @@ -31,18 +37,18 @@ def run(): # Configure field field = geant4.setupTrackingField(prt=True) # Configure Event actions - prt = DDG4.EventAction(kernel,'Geant4ParticlePrint/ParticlePrint') + prt = DDG4.EventAction(kernel, 'Geant4ParticlePrint/ParticlePrint') prt.OutputLevel = Output.WARNING - prt.OutputType = 3 # Print both: table and tree + prt.OutputType = 3 # Print both: table and tree kernel.eventAction().adopt(prt) # Configure I/O - evt_root = geant4.setupROOTOutput('RootOutput','MySD_'+time.strftime('%Y-%m-%d_%H-%M'),mc_truth=False) + evt_root = geant4.setupROOTOutput('RootOutput', 'MySD_' + time.strftime('%Y-%m-%d_%H-%M'), mc_truth=False) # Setup particle gun - gun = geant4.setupGun("Gun",particle='mu-',energy=5*GeV,multiplicity=1,Standalone=True,position=(0,0,0)) - seq,act = geant4.setupTracker('SiliconBlockUpper') + gun = geant4.setupGun("Gun", particle='mu-', energy=5 * GeV, multiplicity=1, Standalone=True, position=(0, 0, 0)) + seq, act = geant4.setupTracker('SiliconBlockUpper') act.OutputLevel = Output.INFO - seq,act = geant4.setupTracker('SiliconBlockDown') + seq, act = geant4.setupTracker('SiliconBlockDown') act.OutputLevel = Output.INFO # Now build the physics list: phys = kernel.physicsList() @@ -55,5 +61,6 @@ def run(): kernel.run() kernel.terminate() + if __name__ == "__main__": run() diff --git a/examples/LHeD/scripts/LHeD.py b/examples/LHeD/scripts/LHeD.py index 596fef71a6d0effebdc87910064e6bf0f96eef46..e636a35c90557fbb5726cd5f790cbaf729331dbb 100644 --- a/examples/LHeD/scripts/LHeD.py +++ b/examples/LHeD/scripts/LHeD.py @@ -1,23 +1,26 @@ from __future__ import absolute_import, unicode_literals -import sys, logging, DDG4 +import sys +import logging +import DDG4 from SystemOfUnits import * logging.basicConfig(format='%(levelname)s: %(message)s') logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) + class LHeD: - def __init__(self,tracker='Geant4TrackerCombineAction'): + def __init__(self, tracker='Geant4TrackerCombineAction'): self.kernel = DDG4.Kernel() - self.description = self.kernel.detectorDescription() - self.geant4 = DDG4.Geant4(self.kernel,tracker=tracker) + self.description = self.kernel.detectorDescription() + self.geant4 = DDG4.Geant4(self.kernel, tracker=tracker) self.kernel.UI = "" self.noPhysics() - + def loadGeometry(self): import os install_dir = os.environ['DD4hepExamplesINSTALL'] - self.kernel.loadGeometry(str("file:"+install_dir+"/examples/LHeD/compact/compact_Lhe_dip_sol_ell.xml")) + self.kernel.loadGeometry(str("file:" + install_dir + "/examples/LHeD/compact/compact_Lhe_dip_sol_ell.xml")) return self # Example to show how to configure G4 magnetic field tracking @@ -26,23 +29,26 @@ class LHeD: # Example to show how to setup random generator def setupRandom(self, name, type=None, seed=None, quiet=True): - rndm = DDG4.Action(self.kernel,'Geant4Random/'+name) - if seed: rndm.Seed = seed - if type: rndm.Type = type + rndm = DDG4.Action(self.kernel, 'Geant4Random/' + name) + if seed: + rndm.Seed = seed + if type: + rndm.Type = type rndm.initialize() - if not quiet: rndm.showStatus() + if not quiet: + rndm.showStatus() return rndm # Example to show how to configure the Geant4 physics list def setupPhysics(self, model): phys = self.geant4.setupPhysics(model) - ph = DDG4.PhysicsList(self.kernel,'Geant4PhysicsList/Myphysics') + ph = DDG4.PhysicsList(self.kernel, 'Geant4PhysicsList/Myphysics') # Add bosons to the model (redundant if already implemented by the model) ph.addParticleGroup(str('G4BosonConstructor')) # Add leptons to the model (redundant if already implemented by the model) ph.addParticleGroup(str('G4LeptonConstructor')) # Add multiple scattering in the material - ph.addParticleProcess(str('e[+-]'),str('G4eMultipleScattering'),-1,1,1) + ph.addParticleProcess(str('e[+-]'), str('G4eMultipleScattering'), -1, 1, 1) # Add optical physics (RICH dets etc) ph.addPhysicsConstructor(str('G4OpticalPhysics')) # Interactivity @@ -58,26 +64,26 @@ class LHeD: def setupDetectors(self): logger.info("# First the tracking detectors") - seq,act = self.geant4.setupTracker('SiVertexBarrel') - seq,act = self.geant4.setupTracker('SiTrackerForward') - seq,act = self.geant4.setupTracker('SiTrackerBarrel') - seq,act = self.geant4.setupTracker('SiTrackerBackward') + seq, act = self.geant4.setupTracker('SiVertexBarrel') + seq, act = self.geant4.setupTracker('SiTrackerForward') + seq, act = self.geant4.setupTracker('SiTrackerBarrel') + seq, act = self.geant4.setupTracker('SiTrackerBackward') logger.info("# Now setup the calorimeters") - seq,act = self.geant4.setupCalorimeter('EcalBarrel') - seq,act = self.geant4.setupCalorimeter('EcalEndcap_fwd') - seq,act = self.geant4.setupCalorimeter('EcalEndcap_bwd') - seq,act = self.geant4.setupCalorimeter('HcalBarrel') - seq,act = self.geant4.setupCalorimeter('HcalEndcap_fwd') - seq,act = self.geant4.setupCalorimeter('HcalEndcap_bwd') - seq,act = self.geant4.setupCalorimeter('HcalPlug_fwd') - seq,act = self.geant4.setupCalorimeter('HcalPlug_bwd') - seq,act = self.geant4.setupCalorimeter('MuonBarrel') - seq,act = self.geant4.setupCalorimeter('MuonEndcap_fwd1') - seq,act = self.geant4.setupCalorimeter('MuonEndcap_fwd2') - seq,act = self.geant4.setupCalorimeter('MuonEndcap_bwd1') - seq,act = self.geant4.setupCalorimeter('MuonEndcap_bwd2') + seq, act = self.geant4.setupCalorimeter('EcalBarrel') + seq, act = self.geant4.setupCalorimeter('EcalEndcap_fwd') + seq, act = self.geant4.setupCalorimeter('EcalEndcap_bwd') + seq, act = self.geant4.setupCalorimeter('HcalBarrel') + seq, act = self.geant4.setupCalorimeter('HcalEndcap_fwd') + seq, act = self.geant4.setupCalorimeter('HcalEndcap_bwd') + seq, act = self.geant4.setupCalorimeter('HcalPlug_fwd') + seq, act = self.geant4.setupCalorimeter('HcalPlug_bwd') + seq, act = self.geant4.setupCalorimeter('MuonBarrel') + seq, act = self.geant4.setupCalorimeter('MuonEndcap_fwd1') + seq, act = self.geant4.setupCalorimeter('MuonEndcap_fwd2') + seq, act = self.geant4.setupCalorimeter('MuonEndcap_bwd1') + seq, act = self.geant4.setupCalorimeter('MuonEndcap_bwd2') return self - + def test_config(self, have_geo=True): self.kernel.configure() if have_geo: diff --git a/examples/LHeD/scripts/LHeDRandom.py b/examples/LHeD/scripts/LHeDRandom.py index 8b5a44bb9732b5474666ab167b5db64bb0c586e3..1b949397cee087cf4a1ff3af381c1be0a3a941d2 100644 --- a/examples/LHeD/scripts/LHeDRandom.py +++ b/examples/LHeD/scripts/LHeDRandom.py @@ -16,21 +16,23 @@ logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) if __name__ == "__main__": - import LHeD, DDG4 + import LHeD + import DDG4 lhed = LHeD.LHeD() - - logger.info('DEFAULT Engine: %s', DDG4.CLHEP.HepRandom.getTheEngine().name()) # <<-- See this function to know how it's done.... - rndm1 = lhed.setupRandom('R1',seed=987654321,type='RunluxEngine') + + # <<-- See this function to know how it's done.... + logger.info('DEFAULT Engine: %s', DDG4.CLHEP.HepRandom.getTheEngine().name()) + rndm1 = lhed.setupRandom('R1', seed=987654321, type='RunluxEngine') logger.info('R1: %s Default instance: %s', rndm1.name, rndm1.instance().name()) logger.info(' Engine: %s', rndm1.engine().name()) logger.info(' DEFAULT: %s', DDG4.CLHEP.HepRandom.getTheEngine().name()) rndm1.showStatus() - rndm2 = lhed.setupRandom('R2',seed=1234321,type='MTwistEngine') + rndm2 = lhed.setupRandom('R2', seed=1234321, type='MTwistEngine') logger.info('R2: %s Default instance: %s', rndm2.name, rndm2.instance().name()) logger.info(' Engine: %s', rndm2.engine().name()) logger.info(' DEFAULT: %s', DDG4.CLHEP.HepRandom.getTheEngine().name()) - #rndm2.showStatus() + # rndm2.showStatus() DDG4.Geant4Random.setMainInstance(rndm1.get()) rndm1.showStatus() @@ -45,22 +47,22 @@ if __name__ == "__main__": rndm.setSeed(1234) rndm.showStatus() for i in range(10): - logger.info("%s -- 0 gRandome.Rndm() -- Shoot random[[%d]= %f",rndm.name(),i,gRandom.Rndm()) - + logger.info("%s -- 0 gRandome.Rndm() -- Shoot random[[%d]= %f", rndm.name(), i, gRandom.Rndm()) + rndm.setSeed(1234) for i in range(10): - logger.info("%s -- 1 gRandome.Rndm() -- Shoot random[[%d]= %f",rndm.name(),i,gRandom.Rndm()) - + logger.info("%s -- 1 gRandome.Rndm() -- Shoot random[[%d]= %f", rndm.name(), i, gRandom.Rndm()) + rndm.setSeed(1234) for i in range(10): - logger.info("%s -- 2 Geant4Random(CLHEP) -- Shoot random[[%d]= %f",rndm.name(),i,rndm.rndm_clhep()) - + logger.info("%s -- 2 Geant4Random(CLHEP) -- Shoot random[[%d]= %f", rndm.name(), i, rndm.rndm_clhep()) + rndm.setSeed(1234) for i in range(10): - logger.info("%s -- 3 Geant4Random(CLHEP) -- Shoot random[[%d]= %f",rndm.name(),i,rndm.rndm_clhep()) + logger.info("%s -- 3 Geant4Random(CLHEP) -- Shoot random[[%d]= %f", rndm.name(), i, rndm.rndm_clhep()) rndm.setSeed(1234) for i in range(10): - logger.info("%s -- 4 HepRandomEngine(CLHEP) -- Shoot random[%d]= %f",rndm.name(),i,rndm.engine().flat()) - + logger.info("%s -- 4 HepRandomEngine(CLHEP) -- Shoot random[%d]= %f", rndm.name(), i, rndm.engine().flat()) + lhed.test_run(have_geo=False) diff --git a/examples/LHeD/scripts/LHeDScan.py b/examples/LHeD/scripts/LHeDScan.py index 413d4d6775930486c14bdb472858476c04789b60..20d3f00ca92b7a78fa13a1a05c2c0b1e1ea0c3b7 100644 --- a/examples/LHeD/scripts/LHeDScan.py +++ b/examples/LHeD/scripts/LHeDScan.py @@ -13,12 +13,16 @@ logging.basicConfig(format='%(levelname)s: %(message)s') logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) + def run(): - import os, sys, DDG4, SystemOfUnits + import os + import sys + import DDG4 + import SystemOfUnits kernel = DDG4.Kernel() install_dir = os.environ['DD4hepExamplesINSTALL'] - kernel.loadGeometry(str("file:"+install_dir+"/examples/LHeD/compact/compact.xml")) + kernel.loadGeometry(str("file:" + install_dir + "/examples/LHeD/compact/compact.xml")) DDG4.Core.setPrintFormat(str("%-32s %6s %s")) geant4 = DDG4.Geant4(kernel) # Configure UI @@ -26,11 +30,11 @@ def run(): gun = geant4.setupGun("Gun", Standalone=True, particle='geantino', - energy=20*SystemOfUnits.GeV, - position=(0,0,0), + energy=20 * SystemOfUnits.GeV, + position=(0, 0, 0), multiplicity=1, - isotrop=False ) - scan = DDG4.SteppingAction(kernel,'Geant4MaterialScanner/MaterialScan') + isotrop=False) + scan = DDG4.SteppingAction(kernel, 'Geant4MaterialScanner/MaterialScan') kernel.steppingAction().adopt(scan) # Now build the physics list: @@ -40,16 +44,17 @@ def run(): kernel.NumEvents = 1 # 3 shots in different directions: - gun.direction = (0,1,0) + gun.direction = (0, 1, 0) kernel.run() - gun.direction = (1,0,0) + gun.direction = (1, 0, 0) kernel.run() - gun.direction = (1,1,1) + gun.direction = (1, 1, 1) kernel.run() kernel.terminate() logger.info('End of run. Terminating .......') logger.info('TEST_PASSED') + if __name__ == "__main__": run() diff --git a/examples/LHeD/scripts/LHeD_G4Gun.py b/examples/LHeD/scripts/LHeD_G4Gun.py index 8b769d2b88ff5212e42cebbaf14886ca396a57ba..8907f45c4ed831fdc4d3b551973b12fc70482197 100644 --- a/examples/LHeD/scripts/LHeD_G4Gun.py +++ b/examples/LHeD/scripts/LHeD_G4Gun.py @@ -14,10 +14,12 @@ logging.basicConfig(format='%(levelname)s: %(message)s') logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) + def run(): - import LHeD, DDG4 + import LHeD + import DDG4 from DDG4 import OutputLevel as Output - + lhed = LHeD.LHeD() geant4 = lhed.geant4 kernel = lhed.kernel @@ -26,33 +28,32 @@ def run(): kernel.UI = "UI" geant4.setupCshUI() lhed.setupField(quiet=False) - DDG4.importConstants(kernel.detectorDescription(),debug=False) + DDG4.importConstants(kernel.detectorDescription(), debug=False) - prt = DDG4.EventAction(kernel,'Geant4ParticlePrint/ParticlePrint') + prt = DDG4.EventAction(kernel, 'Geant4ParticlePrint/ParticlePrint') prt.OutputLevel = Output.INFO - prt.OutputType = 3 # Print both: table and tree + prt.OutputType = 3 # Print both: table and tree kernel.eventAction().adopt(prt) - gen = DDG4.GeneratorAction(kernel,"Geant4GeneratorActionInit/GenerationInit") + gen = DDG4.GeneratorAction(kernel, "Geant4GeneratorActionInit/GenerationInit") kernel.generatorAction().adopt(gen) logger.info("# First particle generator: gun") - gun = DDG4.GeneratorAction(kernel,"Geant4GeneratorWrapper/Gun"); - gun.Uses = 'G4ParticleGun' - gun.Mask = 1 + gun = DDG4.GeneratorAction(kernel, "Geant4GeneratorWrapper/Gun") + gun.Uses = 'G4ParticleGun' + gun.Mask = 1 kernel.generatorAction().adopt(gun) # Merge all existing interaction records - merger = DDG4.GeneratorAction(kernel,"Geant4InteractionMerger/InteractionMerger") + merger = DDG4.GeneratorAction(kernel, "Geant4InteractionMerger/InteractionMerger") merger.enableUI() kernel.generatorAction().adopt(merger) - # And handle the simulation particles. - part = DDG4.GeneratorAction(kernel,"Geant4ParticleHandler/ParticleHandler") + part = DDG4.GeneratorAction(kernel, "Geant4ParticleHandler/ParticleHandler") kernel.generatorAction().adopt(part) part.OutputLevel = Output.INFO part.enableUI() - user = DDG4.Action(kernel,"Geant4TCUserParticleHandler/UserParticleHandler") + user = DDG4.Action(kernel, "Geant4TCUserParticleHandler/UserParticleHandler") user.TrackingVolume_Zmax = DDG4.EcalEndcap_zmin user.TrackingVolume_Rmax = DDG4.EcalBarrel_rmin user.enableUI() @@ -65,5 +66,6 @@ def run(): kernel.run() kernel.terminate() + if __name__ == "__main__": run() diff --git a/examples/LHeD/scripts/LheSimu.py b/examples/LHeD/scripts/LheSimu.py index 77ada7df9fbd180c202d9d7050badf8546403777..235958d16f579a78df6a4c80cd8711a99661b3db 100644 --- a/examples/LHeD/scripts/LheSimu.py +++ b/examples/LHeD/scripts/LheSimu.py @@ -14,10 +14,14 @@ logging.basicConfig(format='%(levelname)s: %(message)s') logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) + def run(): - import LHeD, DDG4, os, SystemOfUnits + import LHeD + import DDG4 + import os + import SystemOfUnits from DDG4 import OutputLevel as Output - + lhed = LHeD.LHeD() geant4 = lhed.geant4 kernel = lhed.kernel @@ -26,31 +30,30 @@ def run(): kernel.UI = "UI" geant4.setupCshUI() lhed.setupField(quiet=False) - DDG4.importConstants(kernel.detectorDescription(),debug=False) + DDG4.importConstants(kernel.detectorDescription(), debug=False) dd4hep_dir = os.environ['DD4hep'] - kernel.loadXML("file:"+dd4hep_dir+"/examples/LHeD/scripts/DDG4_field.xml") + kernel.loadXML("file:" + dd4hep_dir + "/examples/LHeD/scripts/DDG4_field.xml") - geant4 = DDG4.Geant4(kernel,tracker='Geant4TrackerCombineAction') + geant4 = DDG4.Geant4(kernel, tracker='Geant4TrackerCombineAction') geant4.printDetectors() # Configure G4 magnetic field tracking field = geant4.addConfig('Geant4FieldTrackingSetupAction/MagFieldTrackingSetup') - field.stepper = "HelixGeant4Runge" - field.equation = "Mag_UsualEqRhs" - field.eps_min = 5e-0520*SystemOfUnits.mm - field.eps_max = 0.001*SystemOfUnits.mm - field.min_chord_step = 0.01*SystemOfUnits.mm - field.delta_chord = 0.25*SystemOfUnits.mm - field.delta_intersection = 1e-05*SystemOfUnits.mm - field.delta_one_step = 0.001*SystemOfUnits.mm + field.stepper = "HelixGeant4Runge" + field.equation = "Mag_UsualEqRhs" + field.eps_min = 5e-0520 * SystemOfUnits.mm + field.eps_max = 0.001 * SystemOfUnits.mm + field.min_chord_step = 0.01 * SystemOfUnits.mm + field.delta_chord = 0.25 * SystemOfUnits.mm + field.delta_intersection = 1e-05 * SystemOfUnits.mm + field.delta_one_step = 0.001 * SystemOfUnits.mm logger.info('+++++> %s -> stepper = %s', field.name, field.stepper) logger.info('+++++> %s -> equation = %s', field.name, field.equation) logger.info('+++++> %s -> eps_min = %s', field.name, field.eps_min) logger.info('+++++> %s -> eps_max = %s', field.name, field.eps_max) logger.info('+++++> %s -> delta_one_step = %s', field.name, field.delta_one_step) - """ # Setup random generator rndm = DDG4.Action(kernel,'Geant4Random/Random') @@ -61,7 +64,7 @@ def run(): """ # Configure Run actions - run1 = DDG4.RunAction(kernel,'Geant4TestRunAction/RunInit') + run1 = DDG4.RunAction(kernel, 'Geant4TestRunAction/RunInit') """ run1.Property_int = 12345 run1.Property_double = -5e15*keV @@ -72,19 +75,19 @@ def run(): kernel.runAction().adopt(run1) # Configure Event actions - prt = DDG4.EventAction(kernel,'Geant4ParticlePrint/ParticlePrint') + prt = DDG4.EventAction(kernel, 'Geant4ParticlePrint/ParticlePrint') prt.OutputLevel = Output.INFO - prt.OutputType = 3 # Print both: table and tree + prt.OutputType = 3 # Print both: table and tree kernel.eventAction().adopt(prt) # Configure I/O #evt_lcio = geant4.setupLCIOOutput('LcioOutput','Lhe_dip_sol_circ-higgs-bb') #evt_lcio.OutputLevel = Output.ERROR - - evt_root = geant4.setupROOTOutput('RootOutput','Lhe_dip_sol_circ-higgs-bb') + + evt_root = geant4.setupROOTOutput('RootOutput', 'Lhe_dip_sol_circ-higgs-bb') evt_root.OutputLevel = Output.INFO - gen = DDG4.GeneratorAction(kernel,"Geant4GeneratorActionInit/GenerationInit") + gen = DDG4.GeneratorAction(kernel, "Geant4GeneratorActionInit/GenerationInit") kernel.generatorAction().adopt(gen) """ @@ -105,11 +108,11 @@ def run(): kernel.generatorAction().adopt(gen) """ - #VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV + # VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV """ Generation of isotrope tracks of a given multiplicity with overlay: """ - #VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV + # VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV """ # First particle generator: pi+ gen = DDG4.GeneratorAction(kernel,"Geant4IsotropeGenerator/IsotropPi+"); @@ -140,71 +143,68 @@ def run(): kernel.generatorAction().adopt(gen) """ #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - - - #VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV + # VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV """ Generation of primary particles from LCIO input files """ - #VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV - + # VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV + # First particle file reader - gen = DDG4.GeneratorAction(kernel,"LCIOInputAction/LCIO1"); + gen = DDG4.GeneratorAction(kernel, "LCIOInputAction/LCIO1") # gen.Input = "LCIOStdHepReader|/afs/.cern.ch/project/lhec/software/aidasoft/DD4hep/DD4hep/files/NC_bb_tag_2_pythia_events.hep" #gen.Input = "LCIOStdHepReader|/opt/DD4hep/files/NC_bb_tag_2_pythia_events.hep" gen.Input = "LCIOStdHepReader|/opt/DD4hep/files/lhec_for_peter/tag_2_pythia_events.hep" # gen.Input = "LCIOStdHepReader|/opt/DD4hep/files/single-top-tag_1_pythia_events.hep" - + # gen.Input = "Geant4EventReaderHepMC|/opt/DD4hep/files/ePb-q2-0-i.mc2" # gen.Input = "LCIOStdHepReader|/opt/DD4hep/files/single-top-tag_1_pythia_events.hep" # gen.Input = "LCIOStdHepReader|/opt/DD4hep/files/root.hep" - gen.OutputLevel = 2 # generator_output_level + gen.OutputLevel = 2 # generator_output_level gen.MomentumScale = 1.0 gen.Mask = 1 gen.enableUI() kernel.generatorAction().adopt(gen) # Install vertex smearing for this interaction - gen = DDG4.GeneratorAction(kernel,"Geant4InteractionVertexSmear/Smear1"); - gen.OutputLevel = 4 #generator_output_level + gen = DDG4.GeneratorAction(kernel, "Geant4InteractionVertexSmear/Smear1") + gen.OutputLevel = 4 # generator_output_level gen.Mask = 1 - gen.Offset = (-20*SystemOfUnits.mm, -10*SystemOfUnits.mm, -10*SystemOfUnits.mm, 0*SystemOfUnits.ns) - gen.Sigma = (12*SystemOfUnits.mm, 8*SystemOfUnits.mm, 8*SystemOfUnits.mm, 0*SystemOfUnits.ns) + gen.Offset = (-20 * SystemOfUnits.mm, -10 * SystemOfUnits.mm, -10 * SystemOfUnits.mm, 0 * SystemOfUnits.ns) + gen.Sigma = (12 * SystemOfUnits.mm, 8 * SystemOfUnits.mm, 8 * SystemOfUnits.mm, 0 * SystemOfUnits.ns) gen.enableUI() kernel.generatorAction().adopt(gen) #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - + # Merge all existing interaction records - gen = DDG4.GeneratorAction(kernel,"Geant4InteractionMerger/InteractionMerger") - gen.OutputLevel = 4 #generator_output_level + gen = DDG4.GeneratorAction(kernel, "Geant4InteractionMerger/InteractionMerger") + gen.OutputLevel = 4 # generator_output_level gen.enableUI() kernel.generatorAction().adopt(gen) # Finally generate Geant4 primaries - gen = DDG4.GeneratorAction(kernel,"Geant4PrimaryHandler/PrimaryHandler") - gen.OutputLevel = 4 #generator_output_level + gen = DDG4.GeneratorAction(kernel, "Geant4PrimaryHandler/PrimaryHandler") + gen.OutputLevel = 4 # generator_output_level gen.enableUI() kernel.generatorAction().adopt(gen) # And handle the simulation particles. - part = DDG4.GeneratorAction(kernel,"Geant4ParticleHandler/ParticleHandler") + part = DDG4.GeneratorAction(kernel, "Geant4ParticleHandler/ParticleHandler") kernel.generatorAction().adopt(part) #part.SaveProcesses = ['conv','Decay'] part.SaveProcesses = ['Decay'] - part.MinimalKineticEnergy = 10*SystemOfUnits.MeV - part.OutputLevel = 5 # generator_output_level + part.MinimalKineticEnergy = 10 * SystemOfUnits.MeV + part.OutputLevel = 5 # generator_output_level part.enableUI() - user = DDG4.Action(kernel,"Geant4TCUserParticleHandler/UserParticleHandler") + user = DDG4.Action(kernel, "Geant4TCUserParticleHandler/UserParticleHandler") user.TrackingVolume_Zmax = DDG4.EcalEndcap_zmin_fwd user.TrackingVolume_Rmax = DDG4.EcalBarrel_rmin user.enableUI() part.adopt(user) - """ rdr = DDG4.GeneratorAction(kernel,"LcioGeneratorAction/Reader") rdr.zSpread = 0.0 @@ -216,97 +216,96 @@ def run(): """ # Setup global filters fur use in sensntive detectors - f1 = DDG4.Filter(kernel,'GeantinoRejectFilter/GeantinoRejector') + f1 = DDG4.Filter(kernel, 'GeantinoRejectFilter/GeantinoRejector') kernel.registerGlobalFilter(f1) - f2 = DDG4.Filter(kernel,'ParticleRejectFilter/OpticalPhotonRejector') + f2 = DDG4.Filter(kernel, 'ParticleRejectFilter/OpticalPhotonRejector') f2.particle = 'opticalphoton' kernel.registerGlobalFilter(f2) - f3 = DDG4.Filter(kernel,'ParticleSelectFilter/OpticalPhotonSelector') + f3 = DDG4.Filter(kernel, 'ParticleSelectFilter/OpticalPhotonSelector') f3.particle = 'opticalphoton' kernel.registerGlobalFilter(f3) - f4 = DDG4.Filter(kernel,'EnergyDepositMinimumCut') - f4.Cut = 0.5*SystemOfUnits.MeV + f4 = DDG4.Filter(kernel, 'EnergyDepositMinimumCut') + f4.Cut = 0.5 * SystemOfUnits.MeV f4.enableUI() kernel.registerGlobalFilter(f4) # First the tracking detectors - seq,act = geant4.setupTracker('SiVertexBarrel') + seq, act = geant4.setupTracker('SiVertexBarrel') seq.adopt(f1) act.adopt(f1) - - seq,act = geant4.setupTracker('SiTrackerBarrel') + + seq, act = geant4.setupTracker('SiTrackerBarrel') seq.adopt(f1) act.adopt(f1) - seq,act = geant4.setupTracker('SiTrackerForward') + seq, act = geant4.setupTracker('SiTrackerForward') seq.adopt(f1) act.adopt(f1) - seq,act = geant4.setupTracker('SiTrackerBackward') + seq, act = geant4.setupTracker('SiTrackerBackward') seq.adopt(f1) act.adopt(f1) # Now the calorimeters - seq,act = geant4.setupCalorimeter('EcalBarrel') + seq, act = geant4.setupCalorimeter('EcalBarrel') seq.adopt(f3) act.adopt(f3) seq.adopt(f4) act.adopt(f4) - seq,act = geant4.setupCalorimeter('EcalEndcap_fwd') + seq, act = geant4.setupCalorimeter('EcalEndcap_fwd') seq.adopt(f3) act.adopt(f3) seq.adopt(f4) act.adopt(f4) - seq,act = geant4.setupCalorimeter('EcalEndcap_bwd') + seq, act = geant4.setupCalorimeter('EcalEndcap_bwd') seq.adopt(f3) act.adopt(f3) seq.adopt(f4) act.adopt(f4) - - seq,act = geant4.setupCalorimeter('HcalBarrel') + + seq, act = geant4.setupCalorimeter('HcalBarrel') seq.adopt(f3) act.adopt(f3) seq.adopt(f4) act.adopt(f4) - seq,act = geant4.setupCalorimeter('HcalEndcap_fwd') + seq, act = geant4.setupCalorimeter('HcalEndcap_fwd') seq.adopt(f3) act.adopt(f3) seq.adopt(f4) act.adopt(f4) - seq,act = geant4.setupCalorimeter('HcalEndcap_bwd') + seq, act = geant4.setupCalorimeter('HcalEndcap_bwd') seq.adopt(f3) act.adopt(f3) seq.adopt(f4) act.adopt(f4) - seq,act = geant4.setupCalorimeter('HcalPlug_fwd') + seq, act = geant4.setupCalorimeter('HcalPlug_fwd') seq.adopt(f3) act.adopt(f3) seq.adopt(f4) act.adopt(f4) - seq,act = geant4.setupCalorimeter('HcalPlug_bwd') + seq, act = geant4.setupCalorimeter('HcalPlug_bwd') seq.adopt(f3) act.adopt(f3) seq.adopt(f4) act.adopt(f4) - - seq,act = geant4.setupCalorimeter('MuonBarrel') + + seq, act = geant4.setupCalorimeter('MuonBarrel') seq.adopt(f2) act.adopt(f2) - seq,act = geant4.setupCalorimeter('MuonEndcap_fwd1') + seq, act = geant4.setupCalorimeter('MuonEndcap_fwd1') seq.adopt(f2) act.adopt(f2) - seq,act = geant4.setupCalorimeter('MuonEndcap_fwd2') + seq, act = geant4.setupCalorimeter('MuonEndcap_fwd2') seq.adopt(f2) act.adopt(f2) - seq,act = geant4.setupCalorimeter('MuonEndcap_bwd1') + seq, act = geant4.setupCalorimeter('MuonEndcap_bwd1') seq.adopt(f2) act.adopt(f2) - seq,act = geant4.setupCalorimeter('MuonEndcap_bwd2') + seq, act = geant4.setupCalorimeter('MuonEndcap_bwd2') seq.adopt(f2) act.adopt(f2) - """ scan = DDG4.SteppingAction(kernel,'Geant4MaterialScanner/MaterialScan') kernel.steppingAction().adopt(scan) @@ -314,11 +313,11 @@ def run(): # Now build the physics list: phys = geant4.setupPhysics('QGSP_BERT') - ph = DDG4.PhysicsList(kernel,'Geant4PhysicsList/Myphysics') + ph = DDG4.PhysicsList(kernel, 'Geant4PhysicsList/Myphysics') ph.addParticleConstructor(str('G4Geantino')) ph.addParticleConstructor(str('G4BosonConstructor')) ph.addParticleConstructor(str('G4LeptonConstructor')) - ph.addParticleProcess(str('e[+-]'),str('G4eMultipleScattering'),-1,1,1) + ph.addParticleProcess(str('e[+-]'), str('G4eMultipleScattering'), -1, 1, 1) ph.addPhysicsConstructor(str('G4OpticalPhysics')) ph.enableUI() phys.adopt(ph) @@ -327,10 +326,11 @@ def run(): kernel.configure() kernel.initialize() - #DDG4.setPrintLevel(Output.DEBUG) + # DDG4.setPrintLevel(Output.DEBUG) kernel.run() logging.info('End of run. Terminating .......') kernel.terminate() + if __name__ == "__main__": run() diff --git a/examples/OpticalSurfaces/scripts/OpNovice.py b/examples/OpticalSurfaces/scripts/OpNovice.py index 6fc2bb27e410b441b19a8dae616881cf7ab1758a..fb75d3361846080e3a4fa46ff46a2f9f74449e65 100644 --- a/examples/OpticalSurfaces/scripts/OpNovice.py +++ b/examples/OpticalSurfaces/scripts/OpNovice.py @@ -1,7 +1,10 @@ # # from __future__ import absolute_import, unicode_literals -import os, sys, time, DDG4 +import os +import sys +import time +import DDG4 from DDG4 import OutputLevel as Output from SystemOfUnits import * # @@ -14,16 +17,18 @@ from SystemOfUnits import * @version 1.0 """ + + def run(): kernel = DDG4.Kernel() install_dir = os.environ['DD4hepExamplesINSTALL'] - kernel.loadGeometry(str("file:"+install_dir+"/examples/OpticalSurfaces/compact/OpNovice.xml")) + kernel.loadGeometry(str("file:" + install_dir + "/examples/OpticalSurfaces/compact/OpNovice.xml")) - DDG4.importConstants(kernel.detectorDescription(),debug=False) - geant4 = DDG4.Geant4(kernel,tracker='Geant4TrackerCombineAction') + DDG4.importConstants(kernel.detectorDescription(), debug=False) + geant4 = DDG4.Geant4(kernel, tracker='Geant4TrackerCombineAction') geant4.printDetectors() # Configure UI - if len(sys.argv)>1: + if len(sys.argv) > 1: geant4.setupCshUI(macro=sys.argv[1]) else: geant4.setupCshUI() @@ -31,26 +36,26 @@ def run(): # Configure field field = geant4.setupTrackingField(prt=True) # Configure Event actions - prt = DDG4.EventAction(kernel,'Geant4ParticlePrint/ParticlePrint') + prt = DDG4.EventAction(kernel, 'Geant4ParticlePrint/ParticlePrint') prt.OutputLevel = Output.DEBUG - prt.OutputType = 3 # Print both: table and tree + prt.OutputType = 3 # Print both: table and tree kernel.eventAction().adopt(prt) generator_output_level = Output.INFO # Configure G4 geometry setup - seq,act = geant4.addDetectorConstruction("Geant4DetectorGeometryConstruction/ConstructGeo") + seq, act = geant4.addDetectorConstruction("Geant4DetectorGeometryConstruction/ConstructGeo") act.DebugMaterials = True - act.DebugElements = False - act.DebugVolumes = True - act.DebugShapes = True - act.DebugSurfaces = True + act.DebugElements = False + act.DebugVolumes = True + act.DebugShapes = True + act.DebugSurfaces = True # Configure I/O ###evt_root = geant4.setupROOTOutput('RootOutput','OpNovice_'+time.strftime('%Y-%m-%d_%H-%M')) # Setup particle gun - gun = geant4.setupGun("Gun",particle='gamma',energy=5*keV,multiplicity=1) + gun = geant4.setupGun("Gun", particle='gamma', energy=5 * keV, multiplicity=1) gun.OutputLevel = generator_output_level # And handle the simulation particles. @@ -71,7 +76,7 @@ def run(): # Now build the physics list: phys = geant4.setupPhysics('') - ph = DDG4.PhysicsList(kernel,'Geant4OpticalPhotonPhysics/OpticalGammaPhys') + ph = DDG4.PhysicsList(kernel, 'Geant4OpticalPhotonPhysics/OpticalGammaPhys') ph.VerboseLevel = 2 ph.addParticleGroup('G4BosonConstructor') ph.addParticleGroup('G4LeptonConstructor') @@ -80,39 +85,40 @@ def run(): ph.addParticleGroup('G4IonConstructor') ph.addParticleConstructor('G4OpticalPhoton') - ph.addDiscreteParticleProcess('gamma', 'G4GammaConversion') - ph.addDiscreteParticleProcess('gamma', 'G4ComptonScattering') - ph.addDiscreteParticleProcess('gamma', 'G4PhotoElectricEffect') - ph.addParticleProcess(str('e[+-]'), str('G4eMultipleScattering'), -1, 1, 1) - ph.addParticleProcess(str('e[+-]'), str('G4eIonisation'), -1, 2, 2) - ph.addParticleProcess(str('e[+-]'), str('G4eBremsstrahlung'), -1, 3, 3) - ph.addParticleProcess(str('e+'), str('G4eplusAnnihilation'), 0,-1, 4) - ph.addParticleProcess(str('mu[+-]'), str('G4MuMultipleScattering'),-1, 1, 1) - ph.addParticleProcess(str('mu[+-]'), str('G4MuIonisation'), -1, 2, 2) - ph.addParticleProcess(str('mu[+-]'), str('G4MuBremsstrahlung'), -1, 3, 3) - ph.addParticleProcess(str('mu[+-]'), str('G4MuPairProduction'), -1, 4, 4) + ph.addDiscreteParticleProcess('gamma', 'G4GammaConversion') + ph.addDiscreteParticleProcess('gamma', 'G4ComptonScattering') + ph.addDiscreteParticleProcess('gamma', 'G4PhotoElectricEffect') + ph.addParticleProcess(str('e[+-]'), str('G4eMultipleScattering'), -1, 1, 1) + ph.addParticleProcess(str('e[+-]'), str('G4eIonisation'), -1, 2, 2) + ph.addParticleProcess(str('e[+-]'), str('G4eBremsstrahlung'), -1, 3, 3) + ph.addParticleProcess(str('e+'), str('G4eplusAnnihilation'), 0, -1, 4) + ph.addParticleProcess(str('mu[+-]'), str('G4MuMultipleScattering'), -1, 1, 1) + ph.addParticleProcess(str('mu[+-]'), str('G4MuIonisation'), -1, 2, 2) + ph.addParticleProcess(str('mu[+-]'), str('G4MuBremsstrahlung'), -1, 3, 3) + ph.addParticleProcess(str('mu[+-]'), str('G4MuPairProduction'), -1, 4, 4) ph.enableUI() phys.adopt(ph) - ph = DDG4.PhysicsList(kernel,'Geant4ScintillationPhysics/ScintillatorPhys') - ph.ScintillationYieldFactor = 1.0 + ph = DDG4.PhysicsList(kernel, 'Geant4ScintillationPhysics/ScintillatorPhys') + ph.ScintillationYieldFactor = 1.0 ph.ScintillationExcitationRatio = 1.0 - ph.TrackSecondariesFirst = False - ph.VerboseLevel = 2 + ph.TrackSecondariesFirst = False + ph.VerboseLevel = 2 ph.enableUI() phys.adopt(ph) - ph = DDG4.PhysicsList(kernel,'Geant4CerenkovPhysics/CerenkovPhys') - ph.MaxNumPhotonsPerStep = 10 - ph.MaxBetaChangePerStep = 10.0 + ph = DDG4.PhysicsList(kernel, 'Geant4CerenkovPhysics/CerenkovPhys') + ph.MaxNumPhotonsPerStep = 10 + ph.MaxBetaChangePerStep = 10.0 ph.TrackSecondariesFirst = True - ph.VerboseLevel = 2 + ph.VerboseLevel = 2 ph.enableUI() phys.adopt(ph) - + phys.dump() geant4.execute() + if __name__ == "__main__": run() diff --git a/examples/OpticalSurfaces/scripts/OpNovice_GDML.py b/examples/OpticalSurfaces/scripts/OpNovice_GDML.py index 113388c989b0ccd32dad70f014496a898382aa85..fd1cb0b725d1680b93022b4f835498e691d22817 100644 --- a/examples/OpticalSurfaces/scripts/OpNovice_GDML.py +++ b/examples/OpticalSurfaces/scripts/OpNovice_GDML.py @@ -7,17 +7,23 @@ """ from __future__ import absolute_import, unicode_literals -import os, sys, time, logging, DDG4 +import os +import sys +import time +import logging +import DDG4 from DDG4 import OutputLevel as Output + def run(): kernel = DDG4.Kernel() install_dir = os.environ['DD4hepExamplesINSTALL'] - kernel.loadGeometry("file:"+install_dir+"/examples/OpticalSurfaces/compact/OpNovice.xml") + kernel.loadGeometry("file:" + install_dir + "/examples/OpticalSurfaces/compact/OpNovice.xml") logging.basicConfig(format='%(levelname)s: %(message)s') logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) + if __name__ == "__main__": run()