diff --git a/DDCore/python/dd4hepFactories.py b/DDCore/python/dd4hepFactories.py index 01c23b3f3977b03c06ecec5b54a6babf31c26fc6..c999a6102432fb2f630ea874b9206d155f5650f6 100755 --- a/DDCore/python/dd4hepFactories.py +++ b/DDCore/python/dd4hepFactories.py @@ -13,6 +13,10 @@ from __future__ import absolute_import import os, sys, optparse, logging +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' @@ -22,7 +26,7 @@ class ComponentDumper: ldp = os.environ['LD_LIBRARY_PATH'].split(':') for p in ldp: if len(p): - logging.info('+== Search component directory: '+p) + logger.info('+== Search component directory: '+p) files = os.listdir(p) for f in files: fname = p+os.sep+f @@ -33,7 +37,7 @@ class ComponentDumper: self.dumpDictionaries(fname) def readComponents(self,fname): - logging.info('+== Search component file: '+fname) + logger.info('+== Search component file: '+fname) file = open(fname,"r") lines = file.readlines() dirname = os.path.dirname(fname) @@ -54,18 +58,18 @@ class ComponentDumper: dupl = entries[comp] if dupl[1] == 0: if not summary_only: - logging.info('+'+('==='*40)) - logging.info('| Component entry: '+comp+' in library: '+dupl[0]) + logger.info('+'+('==='*40)) + logger.info('| Component entry: '+comp+' in library: '+dupl[0]) entries[comp][1] = 1 if not summary_only: - logging.info('| --> Duplicate factory declaration in: '+ lib) + logger.info('| --> Duplicate factory declaration in: '+ lib) duplicate_count = duplicate_count + 1 continue entries[comp] = [lib,0] component_count = component_count + 1 - logging.info('+'+('==='*40)) - logging.info('| Found %d dd4hep factory entries and %d DUPLICATES in component files.'%(component_count,duplicate_count,)) - logging.info('+'+('==='*40)) + 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 = {} @@ -83,12 +87,12 @@ class ComponentDumper: if not summary_only: for lib, comp in entries.items(): if dump: - logging.info('+== Component library: '+lib) + logger.info('+== Component library: '+lib) count = 0 for c in comp: count = count + 1 if dump: - logging.info('| %-3d Component: %s'%(count,c,)) + logger.info('| %-3d Component: %s'%(count,c,)) if do_load: ret = 'D' if interactive: @@ -108,15 +112,14 @@ class ComponentDumper: gSystem.Load(lib) elif ret[0].upper() == 'L': do_load = False - logging.info('+'+('==='*40)) - logging.info('| Found %d dd4hep factory libraries with %d components.'%(library_count,component_count,)) - logging.info('+'+('==='*40) ) + 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 -logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) parser = optparse.OptionParser() parser.description = "DD4hep factory checks." parser.formatter.width = 132 @@ -143,7 +146,7 @@ parser.add_option("-n","--no-interactive", (opts, args) = parser.parse_args() if not (opts.check or opts.dump or opts.load): - logging.info(" %s",parser.format_help()) + logger.info(" %s",parser.format_help()) sys.exit(0) try: @@ -152,13 +155,13 @@ try: from ROOT import gSystem gROOT.SetBatch(1) except ImportError,X: - logging.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,X: - logging.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() diff --git a/DDCore/python/dd4hep_base.py b/DDCore/python/dd4hep_base.py index ca3f1a1f7e38821660c4dbd703f83f5ebc32c070..20c8ee077d97ff5167cf010f24744ef4d9c87ee7 100644 --- a/DDCore/python/dd4hep_base.py +++ b/DDCore/python/dd4hep_base.py @@ -11,8 +11,10 @@ from __future__ import absolute_import import imp, logging -logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) -# +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): from ROOT import gInterpreter, gSystem @@ -27,13 +29,10 @@ def compileAClick(dictionary,g4=True): gSystem.AddIncludePath(inc) gSystem.AddLinkedLibs(lib) - #####logging.info("Includes: %s\n","Linked libs:%s",gSystem.GetIncludePath(),gSystem.GetLinkedLibs()) - logging.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 - ###logging.info(str(dic)) gInterpreter.ProcessLine('.L '+dic+'+') - #####gInterpreter.Load('DDG4Dict_C.so') from ROOT import dd4hep as module return module @@ -64,7 +63,6 @@ def import_namespace_item(ns,nam): return attr def import_root(nam): - #logging.info('import ROOT class %s in namespace %s',nam,str(name_space)) setattr(name_space,nam,getattr(ROOT,nam)) #--------------------------------------------------------------------------- @@ -74,10 +72,10 @@ try: import ROOT except Exception as X: import sys - logging.info('+--%-100s--+',100*'-') - logging.info('| %-100s |','Failed to load dd4hep base library:') - logging.info('| %-100s |',str(X)) - logging.info('+--%-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: @@ -293,13 +291,13 @@ try: ] if ns is None: ns = name_space - logging.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) except: - logging.debug('WARNING: No units can be imported.') + logger.warning('No units can be imported.') def import_units(ns=None): return 0 diff --git a/DDCore/python/lcdd.py b/DDCore/python/lcdd.py index 918dbed06611802f342a87063d046c6fd1cd5e60..8a834d18907e8a9dfae02d155982c4d45ef2bc5c 100644 --- a/DDCore/python/lcdd.py +++ b/DDCore/python/lcdd.py @@ -14,8 +14,13 @@ from math import cos, sin, pi, tan from os import path, listdir from functools import partial import SystemOfUnits -import math +import math +import logging from ROOT import SetOwnership, dd4hep, TGeoMixture, TGeoMedium, gGeoManager, TNamed + +logging.basicConfig(format='%(levelname)s: %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) Detector = dd4hep.Geometry.Detector Constant = dd4hep.Geometry.Constant @@ -122,12 +127,12 @@ def load_drivers(*args): for arg in args: if path.exists(arg): if path.isfile(arg): - print "Loading driver file ... %s" % arg + logger.info("Loading driver file ... %s" % arg) execfile(arg, drivers) elif path.isdir(arg): for f in listdir(arg) : if path.splitext(f)[1] == '.py': - print "Loading driver file ... %s" % path.join(arg,f) + logger.info("Loading driver file ... %s" % path.join(arg,f)) execfile(path.join(arg,f), drivers) else: raise "Path '%s' is not a directory or file" % arg else: raise "Path '%s' does not exists" % arg @@ -157,12 +162,12 @@ def process_tag(description, elem): procs = drivers.get('process_%s'% elem.tag, None) if procs : apply(procs,(description, elem)) - else : print 'XML tag %s not processed!!! No function found.' % elem.tag + else : logger.info('XML tag %s not processed!!! No function found.' % elem.tag) #-------------------------------------------------------------------------------- def fromXML(xmlfile): - print 'Converting Compact file: ', xmlfile + logger.info('Converting Compact file: %s', xmlfile) description = Detector.getInstance() #description.create() process_xmlfile(description, xmlfile) @@ -171,17 +176,17 @@ def fromXML(xmlfile): #--------------------------------------------------------------------------------- def process_includes(description, elem): for c in elem.findall('gdmlFile'): - print 'Adding Gdml file ...', c.get('ref') + logger.info('Adding Gdml file ... %s', c.get('ref')) fname = c.get('ref').replace('file:','') if not path.isabs(fname): fname = path.join(path.dirname(current_xmlfile),fname) process_xmlfile(description, fname) for c in elem.findall('pyBuilder'): - print 'Adding PyBuilder ...', c.get('ref') + logger.info('Adding PyBuilder ... %s', c.get('ref')) fname = c.get('ref') if not path.isabs(fname): fname = path.join(path.dirname(current_xmlfile),fname) load_drivers(fname) for c in elem.findall('alignment'): - print 'Adding Alignment file ...', c.get('ref') + logger.info('Adding Alignment file ... %s', c.get('ref')) fname = c.get('ref').replace('file:','') if not path.isabs(fname): fname = path.join(path.dirname(current_xmlfile),fname) process_xmlfile(description, fname) @@ -193,14 +198,12 @@ def process_info(description, elem): #--------------------------------------------------------------------------------- def process_define(description, elem): for c in elem.findall('constant'): - #print 'Adding constant ...', c.get('name') description.addConstant(Constant(c.get('name'),c.get('value'))) _toDictionary(c.get('name'),c.get('value')) #-- Make it known to the evaluator constants[c.get('name')] = c.getF('value') #--------------------------------------------------------------------------------- def process_element(description, elem): - #print 'Adding element ...', elem.get('name') ename = elem.get('name') tab = gGeoManager.GetElementTable() element = tab.FindElement(ename) @@ -229,7 +232,6 @@ def process_materials(description, elem): def process_material(description, m): - #print 'Adding material ...', m.get('name') density = m.find('D') radlen = m.find('RL') intlen = m.find('NIL') @@ -268,7 +270,6 @@ def process_material(description, m): #---------------------------------------------------------------------------------- def process_display(description, elem): for v in elem.findall('vis'): - #print 'Adding vis ...', v.name visattr = VisAttr(v.name) r,g,b = 1.,1.,1. if 'r' in v.keys() : r = v.getF('r') @@ -287,7 +288,6 @@ def process_display(description, elem): if 'drawingStyle' in v.keys() : ds = v.get('drawingStyle') if ds == 'wireframe' : visattr.setDrawingStyle(VisAttr.WIREFRAME) - #print visattr.toString() description.addVisAttribute(visattr) def process_limits(description, elem): @@ -307,7 +307,7 @@ def process_detectors(description, elem): detector = apply(procs,(description, d)) description.addDetector(detector) else : - print 'Detector type %s not found' % d.get('type') + logger.info('Detector type %s not found' % d.get('type')) #----------------------------------------------------------------------------------- def process_alignments(description, elem): @@ -319,7 +319,7 @@ def process_alignment(description, elem): alignment = AlignmentEntry(description, elem.name) pos = getPosition(elem.find('position')) rot = getRotation(elem.find('rotation')) - print pos.isNull(), rot.isNull() + logger.info("%s %s", pos.isNull(), rot.isNull()) alignment.align(pos,rot) return alignment @@ -340,7 +340,7 @@ def process_readout(description, elem): segment = apply(procs,(description, seg)) readout.setSegmentation(segment) else : - print 'Segmentation type %s not found' % seg.get('type') + logger.info('Segmentation type %s not found' % seg.get('type')) id = elem.find('id') if id is not None: idSpec = IDDescriptor(id.text) diff --git a/DDDigi/python/DDDigi.py b/DDDigi/python/DDDigi.py index 02e1a12e497d39e8fe8ed4a23b583b72cdd22b7e..31950d8fd09e3655a1bc3f0c13426eca4d633cf5 100644 --- a/DDDigi/python/DDDigi.py +++ b/DDDigi/python/DDDigi.py @@ -12,7 +12,10 @@ from __future__ import absolute_import import logging from dd4hep_base import * -logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) +logging.basicConfig(format='%(levelname)s: %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + def loadDDDigi(): ## import ROOT ## done in import * above from ROOT import gSystem @@ -47,10 +50,10 @@ def _import_class(ns,nam): try: dd4hep = loadDDDigi() except Exception as X: - logging.info('+--%-100s--+',100*'-') - logging.info('| %-100s |','Failed to load DDDigi library:') - logging.info('| %-100s |',str(X)) - logging.info('+--%-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 @@ -92,15 +95,15 @@ def importConstants(description,namespace=None,debug=False): while len(todo) and cnt<100: cnt = cnt + 1 if cnt == 100: - logging.info('%s %d out of %d %s "%s": [%s]\n+++ %s',\ + 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): - logging.info('+++ FAILED to import: "'+k+'" = "'+str(v)+'"') - logging.info('+++ %s',100*'=') + logger.info('+++ FAILED to import: "'+k+'" = "'+str(v)+'"') + logger.info('+++ %s',100*'=') for k,v in todo.items(): if not hasattr(ns,k): @@ -109,15 +112,14 @@ def importConstants(description,namespace=None,debug=False): if status == 0: evaluator.setVariable(k,val) setattr(ns,k,val) - if debug: logging.info('Imported global value: "'+k+'" = "'+str(val)+'" into namespace'+ns.__name__) + if debug: logger.info('Imported global value: "'+k+'" = "'+str(val)+'" into namespace'+ns.__name__) del todo[k] num = num + 1 if cnt<100: - logging.info('+++ Imported %d global values to namespace:%s',num,ns.__name__,) + logger.info('+++ Imported %d global values to namespace:%s',num,ns.__name__,) #--------------------------------------------------------------------------- def _getKernelProperty(self, name): - #logging.info('_getKernelProperty: %s %s',str(type(self)),name) ret = Interface.getPropertyKernel(self.get(),name) if ret.status > 0: return ret.data @@ -130,7 +132,6 @@ def _getKernelProperty(self, name): #--------------------------------------------------------------------------- def _setKernelProperty(self, name, value): - #logging.info('_setKernelProperty: %s %s',name,str(value)) if Interface.setPropertyKernel(self.get(),name,str(value)): return msg = 'DigiKernel::SetProperty [Unhandled]: Cannot set Kernel.'+name+' = '+str(value) @@ -184,7 +185,6 @@ _import_class('digi','DigiAction') #--------------------------------------------------------------------------- def _get(self, name): import traceback - #logging.info('_get: %s %s',str(type(self)),name) a = Interface.toAction(self) ret = Interface.getProperty(a,name) if ret.status > 0: @@ -268,10 +268,10 @@ class Digitize: return detectors def printDetectors(self): - logging.info('+++ List of sensitive detectors:') + logger.info('+++ List of sensitive detectors:') dets = self.activeDetectors() for d in dets: - logging.info('+++ %-32s ---> type:%-12s', d['name'], d['type']) + logger.info('+++ %-32s ---> type:%-12s', d['name'], d['type']) def setupDetector(self,name,collections=None,modules=None): parameterDict = {} diff --git a/DDG4/examples/CLICSidSimuLCIO.py b/DDG4/examples/CLICSidSimuLCIO.py index bde04bdacb346cd78134eb5ba2612cc9ecd197f4..637598ef374ae4a7ee6527d4f81420108a9ccb57 100644 --- a/DDG4/examples/CLICSidSimuLCIO.py +++ b/DDG4/examples/CLICSidSimuLCIO.py @@ -1,19 +1,21 @@ -# -# +""" + + dd4hep simulation example setup using the python configuration + + @author M.Frank + @version 1.0 + +""" from __future__ import absolute_import import os, time, DDG4 from DDG4 import OutputLevel as Output from SystemOfUnits import * -# -# -""" +import logging - dd4hep simulation example setup using the python configuration +logging.basicConfig(format='%(levelname)s: %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) - @author M.Frank - @version 1.0 - -""" def run(): kernel = DDG4.Kernel() install_dir = os.environ['DD4hepINSTALL'] @@ -30,7 +32,7 @@ def run(): run1.Property_int = 12345 run1.Property_double = -5e15*keV run1.Property_string = 'Startrun: Hello_2' - print run1.Property_string, run1.Property_double, run1.Property_int + logger.info("%s %s %s", run1.Property_string, run1.Property_double, run1.Property_int) run1.enableUI() kernel.registerGlobalAction(run1) kernel.runAction().add(run1) diff --git a/DDG4/examples/CLICSidSimuMarkus.py b/DDG4/examples/CLICSidSimuMarkus.py index 042c91109eacfa6c3c84f9db286d393b5b0d7a13..9d4f0bffba98050eecac7ba37cffac4791d5f11b 100644 --- a/DDG4/examples/CLICSidSimuMarkus.py +++ b/DDG4/examples/CLICSidSimuMarkus.py @@ -5,7 +5,9 @@ import os, time, logging, DDG4 from DDG4 import OutputLevel as Output from SystemOfUnits import * # -logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) +logging.basicConfig(format='%(levelname)s: %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) # """ @@ -171,7 +173,7 @@ def run(): #DDG4.setPrintLevel(Output.DEBUG) kernel.run() - logging.info('End of run. Terminating .......') + logger.info('End of run. Terminating .......') kernel.terminate() if __name__ == "__main__": diff --git a/DDG4/examples/SiDSim.py b/DDG4/examples/SiDSim.py index 74b606c4270827238c73e8a7149d7d047ee17271..fe8aa5edcb481be016f10999c6b6e4d570576ab2 100644 --- a/DDG4/examples/SiDSim.py +++ b/DDG4/examples/SiDSim.py @@ -6,8 +6,9 @@ from DDG4 import OutputLevel as Output from SystemOfUnits import * # # -logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) -logging.info( +logging.basicConfig(format='%(levelname)s: %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) """ dd4hep simulation example setup using the python configuration @@ -15,7 +16,8 @@ logging.info( @author M.Frank @version 1.0 -""") +""" + def run(): kernel = DDG4.Kernel() description = kernel.detectorDescription() @@ -25,35 +27,35 @@ def run(): geant4 = DDG4.Geant4(kernel,tracker='Geant4TrackerCombineAction') geant4.printDetectors() - logging.info("# Configure UI") + logger.info("# Configure UI") geant4.setupCshUI() - logging.info("# Configure G4 magnetic field tracking") + logger.info("# Configure G4 magnetic field tracking") geant4.setupTrackingField() - logging.info("# Setup random generator") + logger.info("# Setup random generator") rndm = DDG4.Action(kernel,'Geant4Random/Random') rndm.Seed = 987654321 rndm.initialize() ##rndm.showStatus() - logging.info("# Configure Run actions") + logger.info("# Configure Run actions") run1 = DDG4.RunAction(kernel,'Geant4TestRunAction/RunInit') run1.Property_int = 12345 run1.Property_double = -5e15*keV run1.Property_string = 'Startrun: Hello_2' - logging.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) - logging.info("# Configure Event actions") + logger.info("# Configure Event actions") prt = DDG4.EventAction(kernel,'Geant4ParticlePrint/ParticlePrint') prt.OutputLevel = Output.INFO prt.OutputType = 3 # Print both: table and tree kernel.eventAction().adopt(prt) - logging.info(""" + logger.info(""" Configure I/O """) #evt_lcio = geant4.setupLCIOOutput('LcioOutput','CLICSiD_'+time.strftime('%Y-%m-%d_%H-%M')) @@ -67,10 +69,10 @@ def run(): kernel.generatorAction().adopt(gen) #VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV - logging.info(""" + logger.info(""" Generation of isotrope tracks of a given multiplicity with overlay: """) - logging.info("# First particle generator: pi+") + logger.info("# First particle generator: pi+") gen = DDG4.GeneratorAction(kernel,"Geant4IsotropeGenerator/IsotropPi+"); gen.Mask = 1 gen.Particle = 'pi+' @@ -78,14 +80,14 @@ def run(): gen.Multiplicity = 2 gen.Distribution = 'cos(theta)' kernel.generatorAction().adopt(gen) - logging.info("# Install vertex smearing for this interaction") + 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) kernel.generatorAction().adopt(gen) - logging.info("# Second particle generator: e-") + logger.info("# Second particle generator: e-") gen = DDG4.GeneratorAction(kernel,"Geant4IsotropeGenerator/IsotropE-"); gen.Mask = 2 gen.Particle = 'e-' @@ -93,7 +95,7 @@ def run(): gen.Multiplicity = 3 gen.Distribution = 'uniform' kernel.generatorAction().adopt(gen) - logging.info(" Install vertex smearing for this interaction") + 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) @@ -101,19 +103,19 @@ def run(): kernel.generatorAction().adopt(gen) #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - logging.info("# Merge all existing interaction records") + logger.info("# Merge all existing interaction records") gen = DDG4.GeneratorAction(kernel,"Geant4InteractionMerger/InteractionMerger") gen.OutputLevel = 4 #generator_output_level gen.enableUI() kernel.generatorAction().adopt(gen) - logging.info("# Finally generate Geant4 primaries") + logger.info("# Finally generate Geant4 primaries") gen = DDG4.GeneratorAction(kernel,"Geant4PrimaryHandler/PrimaryHandler") gen.OutputLevel = 4 #generator_output_level gen.enableUI() kernel.generatorAction().adopt(gen) - logging.info("# ....and handle the simulation particles.") + logger.info("# ....and handle the simulation particles.") part = DDG4.GeneratorAction(kernel,"Geant4ParticleHandler/ParticleHandler") kernel.generatorAction().adopt(part) #part.SaveProcesses = ['conv','Decay'] @@ -127,7 +129,7 @@ def run(): user.enableUI() part.adopt(user) - logging.info("# Setup global filters fur use in sensitive detectors") + logger.info("# Setup global filters fur use in sensitive detectors") f1 = DDG4.Filter(kernel,'GeantinoRejectFilter/GeantinoRejector') f2 = DDG4.Filter(kernel,'ParticleRejectFilter/OpticalPhotonRejector') f2.particle = 'opticalphoton' @@ -141,7 +143,7 @@ def run(): kernel.registerGlobalFilter(f3) kernel.registerGlobalFilter(f4) - logging.info("# First the tracking detectors") + logger.info("# First the tracking detectors") seq,act = geant4.setupTracker('SiVertexBarrel') seq.adopt(f1) #seq.adopt(f4) @@ -154,7 +156,7 @@ def run(): seq,act = geant4.setupTracker('SiTrackerBarrel') seq,act = geant4.setupTracker('SiTrackerEndcap') seq,act = geant4.setupTracker('SiTrackerForward') - logging.info("# Now setup the calorimeters") + logger.info("# Now setup the calorimeters") seq,act = geant4.setupCalorimeter('EcalBarrel') seq,act = geant4.setupCalorimeter('EcalEndcap') seq,act = geant4.setupCalorimeter('HcalBarrel') @@ -165,7 +167,7 @@ def run(): seq,act = geant4.setupCalorimeter('LumiCal') seq,act = geant4.setupCalorimeter('BeamCal') - logging.info("# Now build the physics list:") + logger.info("# Now build the physics list:") phys = geant4.setupPhysics('QGSP_BERT') ph = geant4.addPhysics('Geant4PhysicsList/Myphysics') #ph.addParticleConstructor('G4BosonConstructor') diff --git a/DDG4/examples/SiDSim_MT.py b/DDG4/examples/SiDSim_MT.py index 5b67aa2334809db120f0f125a7310e17987dc003..a6899136f31b39fea86e4f9799cb662804cec54a 100644 --- a/DDG4/examples/SiDSim_MT.py +++ b/DDG4/examples/SiDSim_MT.py @@ -5,9 +5,11 @@ import os, time, logging, DDG4 from DDG4 import OutputLevel as Output from SystemOfUnits import * # -logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) +logging.basicConfig(format='%(levelname)s: %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) # -logging.info(""" +""" dd4hep simulation example setup DDG4 in multi-threaded mode using the python configuration @@ -15,28 +17,28 @@ logging.info(""" @author M.Frank @version 1.0 -""") +""" def setupWorker(geant4): kernel = geant4.kernel() - logging.info('#PYTHON: +++ Creating Geant4 worker thread ....') - logging.info("#PYTHON: Configure Run actions") + 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.Property_string = 'Startrun: Hello_2' - logging.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) - logging.info("#PYTHON: Configure Event actions") + logger.info("#PYTHON: Configure Event actions") prt = DDG4.EventAction(kernel,'Geant4ParticlePrint/ParticlePrint') prt.OutputLevel = Output.INFO prt.OutputType = 3 # Print both: table and tree kernel.eventAction().adopt(prt) - logging.info("\n#PYTHON: Configure I/O\n") + 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 @@ -47,29 +49,29 @@ def setupWorker(geant4): gen = DDG4.GeneratorAction(kernel,"Geant4GeneratorActionInit/GenerationInit") kernel.generatorAction().adopt(gen) #VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV - logging.info("#PYTHON:\n#PYTHON: Generation of isotrope tracks of a given multiplicity with overlay:\n#PYTHON:") - logging.info("#PYTHON: First particle generator: pi+") + 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.Particle = 'pi+' gen.Energy = 20 * GeV gen.Multiplicity = 2 kernel.generatorAction().adopt(gen) - logging.info("#PYTHON: Install vertex smearing for this interaction") + 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) kernel.generatorAction().adopt(gen) - logging.info("#PYTHON: Second particle generator: e-") + logger.info("#PYTHON: Second particle generator: e-") gen = DDG4.GeneratorAction(kernel,"Geant4IsotropeGenerator/IsotropE-"); gen.Mask = 2 gen.Particle = 'e-' gen.Energy = 15 * GeV gen.Multiplicity = 3 kernel.generatorAction().adopt(gen) - logging.info("#PYTHON: Install vertex smearing for this interaction") + 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) @@ -77,19 +79,19 @@ def setupWorker(geant4): kernel.generatorAction().adopt(gen) #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - logging.info("#PYTHON: Merge all existing interaction records") + logger.info("#PYTHON: Merge all existing interaction records") gen = DDG4.GeneratorAction(kernel,"Geant4InteractionMerger/InteractionMerger") gen.OutputLevel = 4 #generator_output_level gen.enableUI() kernel.generatorAction().adopt(gen) - logging.info("#PYTHON: Finally generate Geant4 primaries") + logger.info("#PYTHON: Finally generate Geant4 primaries") gen = DDG4.GeneratorAction(kernel,"Geant4PrimaryHandler/PrimaryHandler") gen.OutputLevel = 4 #generator_output_level gen.enableUI() kernel.generatorAction().adopt(gen) - logging.info("#PYTHON: ....and handle the simulation particles.") + logger.info("#PYTHON: ....and handle the simulation particles.") part = DDG4.GeneratorAction(kernel,"Geant4ParticleHandler/ParticleHandler") kernel.generatorAction().adopt(part) #part.SaveProcesses = ['conv','Decay'] @@ -102,24 +104,24 @@ def setupWorker(geant4): user.TrackingVolume_Rmax = DDG4.EcalBarrel_rmin user.enableUI() part.adopt(user) - logging.info('#PYTHON: +++ Geant4 worker thread configured successfully....') + logger.info('#PYTHON: +++ Geant4 worker thread configured successfully....') return 1 def setupMaster(geant4): kernel = geant4.master() - logging.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): - logging.info("#PYTHON: Setting up all sensitive detectors") + logger.info("#PYTHON: Setting up all sensitive detectors") geant4.printDetectors() - logging.info("#PYTHON: First the tracking detectors") + 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') - logging.info("#PYTHON: Now setup the calorimeters") + logger.info("#PYTHON: Now setup the calorimeters") seq,act = geant4.setupCalorimeter('EcalBarrel') seq,act = geant4.setupCalorimeter('EcalEndcap') seq,act = geant4.setupCalorimeter('HcalBarrel') @@ -142,33 +144,33 @@ def run(): kernel.NumberOfThreads = 3 kernel.RunManagerType = 'G4MTRunManager' geant4 = DDG4.Geant4(kernel,tracker='Geant4TrackerCombineAction') - logging.info("# Configure UI") + logger.info("# Configure UI") geant4.setupCshUI() - logging.info("# Geant4 user initialization action") + logger.info("# Geant4 user initialization action") geant4.addUserInitialization(worker=setupWorker, worker_args=(geant4,), master=setupMaster, master_args=(geant4,)) - logging.info("# Configure G4 geometry setup") + logger.info("# Configure G4 geometry setup") seq,act = geant4.addDetectorConstruction("Geant4DetectorGeometryConstruction/ConstructGeo") - logging.info("# Configure G4 sensitive detectors: python setup callback") + logger.info("# Configure G4 sensitive detectors: python setup callback") seq,act = geant4.addDetectorConstruction("Geant4PythonDetectorConstruction/SetupSD", sensitives=setupSensitives,sensitives_args=(geant4,)) - logging.info("# Configure G4 sensitive detectors: atach'em to the sensitive volumes") + logger.info("# Configure G4 sensitive detectors: atach'em to the sensitive volumes") seq,act = geant4.addDetectorConstruction("Geant4DetectorSensitivesConstruction/ConstructSD") # allow_threads=True) - logging.info("# Configure G4 magnetic field tracking") + logger.info("# Configure G4 magnetic field tracking") geant4.setupTrackingFieldMT() - logging.info("# Setup random generator") + logger.info("# Setup random generator") rndm = DDG4.Action(kernel,'Geant4Random/Random') rndm.Seed = 987654321 rndm.initialize() ##rndm.showStatus() - logging.info("# Now build the physics list:") + logger.info("# Now build the physics list:") phys = geant4.setupPhysics('QGSP_BERT') phys.dump() diff --git a/DDG4/examples/SiD_Markus.py b/DDG4/examples/SiD_Markus.py index 50c5d664c693778b89191c84aeb7e855c17799f5..a85ab58d81bac4368fcef450ee7b2a5e8f6c1789 100644 --- a/DDG4/examples/SiD_Markus.py +++ b/DDG4/examples/SiD_Markus.py @@ -6,7 +6,9 @@ from DDG4 import OutputLevel as Output from SystemOfUnits import * # global geant4 -logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) +logging.basicConfig(format='%(levelname)s: %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) # """ @@ -20,14 +22,14 @@ logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) def setupWorker(): k = DDG4.Kernel() kernel = k.worker() - print 'PYTHON: +++ Creating Geant4 worker thread ....' + 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.Property_string = 'Startrun: Hello_2' - logging.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) @@ -118,11 +120,11 @@ def setupWorker(): user.TrackingVolume_Rmax = DDG4.EcalBarrel_rmin user.enableUI() part.adopt(user) - logging.info('PYTHON: +++ Geant4 worker thread configured successfully....') + logger.info('PYTHON: +++ Geant4 worker thread configured successfully....') return 1 def setupMaster(): - logging.info('PYTHON: +++ Setting up master thread.....') + logger.info('PYTHON: +++ Setting up master thread.....') return 1 def setupSensitives(): @@ -134,15 +136,15 @@ def setupSensitives(): seq,act = geant4.setupTracker('SiVertexEndcap') act.OutputLevel = Output.ERROR act.CollectSingleDeposits = False - logging.info('PYTHON: +++ Setting up Geant4 sensitive detectors for worker thread.....') + logger.info('PYTHON: +++ Setting up Geant4 sensitive detectors for worker thread.....') return 1 def dummy_sd(): - logging.info('PYTHON: +++ Setting up DUMMY Geant4 sensitive detectors for worker thread.....') + logger.info('PYTHON: +++ Setting up DUMMY Geant4 sensitive detectors for worker thread.....') return 1 def dummy_geom(): - logging.info('PYTHON: +++ Setting up DUMMY Geant4 geometry for worker thread.....') + logger.info('PYTHON: +++ Setting up DUMMY Geant4 geometry for worker thread.....') return 1 def run(): @@ -224,5 +226,5 @@ def run(): if __name__ == "__main__": import sys - logging.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 be03ebc456d83d547cc70eb6ae1748f05d683a25..d563fb4b72c63942eb9c0a24797fabdc58f0cd61 100644 --- a/DDG4/examples/readHEPMC.py +++ b/DDG4/examples/readHEPMC.py @@ -8,7 +8,10 @@ dd4hep simulation example setup using the python configuration """ from __future__ import absolute_import import logging -logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) + +logging.basicConfig(format='%(levelname)s: %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) def run(input_file): import DDG4 @@ -29,21 +32,21 @@ def run(input_file): ret = gen.readParticles(evtid,prim_vtx,parts) evtid = evtid + 1 except Exception,X: - logging.info( '\nException: readParticles: %s',str(X)) + logger.error( '\nException: readParticles: %s',str(X)) ret = None if ret: for v in prim_vtx: - logging.info( 'Mask:%04X (X:%8.2g,Y:%8.2g,Z:%8.2g) time:%8.2g Outgoing:%4d particles', + 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: - logging.info( 'Mask:%04X ID:%5d PDG-id:%8d Charge:%1d Mass:%8.3g Momentum:(%8.2g,%8.2g,%8.2g) '\ + 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: - logging.info( '*** End of recordset or read failure.....') - logging.info( 132*'*') + logger.info( '*** End of recordset or read failure.....') + logger.info( 132*'*') return 0 if __name__ == "__main__": @@ -53,5 +56,5 @@ if __name__ == "__main__": input_file = sys.argv[1] sys.exit(run(input_file)) else: - logging.info( '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 c835398eeab7e7e325a6195d03e4dc61d4758798..10216e3c4ad988d991beccc2ad99c3ac1d5dd010 100644 --- a/DDG4/python/DDG4.py +++ b/DDG4/python/DDG4.py @@ -12,7 +12,10 @@ from __future__ import absolute_import import logging from dd4hep_base import * -logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) +logging.basicConfig(format='%(levelname)s: %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + def loadDDG4(): ## import ROOT ## done in import * above from ROOT import gSystem @@ -49,10 +52,10 @@ def _import_class(ns,nam): try: dd4hep = loadDDG4() except Exception as X: - logging.info('+--%-100s--+',100*'-') - logging.info('| %-100s |','Failed to load DDG4 library:') - logging.info('| %-100s |',str(X)) - logging.info('+--%-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 @@ -97,15 +100,15 @@ def importConstants(description,namespace=None,debug=False): while len(todo) and cnt<100: cnt = cnt + 1 if cnt == 100: - logging.info('%s %d out of %d %s "%s": [%s]\n+++ %s',\ + 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): - logging.info('+++ FAILED to import: "'+k+'" = "'+str(v)+'"') - logging.info('+++ %s',100*'=') + logger.error('+++ FAILED to import: "'+k+'" = "'+str(v)+'"') + logger.info('+++ %s',100*'=') for k,v in todo.items(): if not hasattr(ns,k): @@ -114,11 +117,11 @@ def importConstants(description,namespace=None,debug=False): if status == 0: evaluator.setVariable(k,val) setattr(ns,k,val) - if debug: logging.info('Imported global value: "'+k+'" = "'+str(val)+'" into namespace'+ns.__name__) + if debug: logger.info('Imported global value: "'+k+'" = "'+str(val)+'" into namespace'+ns.__name__) del todo[k] num = num + 1 if cnt<100: - logging.info('+++ Imported %d global values to namespace:%s',num,ns.__name__,) + logger.info('+++ Imported %d global values to namespace:%s',num,ns.__name__,) #--------------------------------------------------------------------------- def _registerGlobalAction(self,action): @@ -127,7 +130,6 @@ def _registerGlobalFilter(self,filter): self.get().registerGlobalFilter(Interface.toAction(filter)) #--------------------------------------------------------------------------- def _getKernelProperty(self, name): - #logging.info('_getKernelProperty: %s %s',str(type(self)),name) ret = Interface.getPropertyKernel(self.get(),name) if ret.status > 0: return ret.data @@ -140,7 +142,6 @@ def _getKernelProperty(self, name): #--------------------------------------------------------------------------- def _setKernelProperty(self, name, value): - #logging.info('_setKernelProperty: %s %s',name,str(value)) if Interface.setPropertyKernel(self.get(),name,str(value)): return msg = 'Geant4Kernel::SetProperty [Unhandled]: Cannot set Kernel.'+name+' = '+str(value) @@ -255,7 +256,6 @@ _import_class('CLHEP','HepRandomEngine') #--------------------------------------------------------------------------- def _get(self, name): import traceback - #logging.info('_get: %s %s',str(type(self)),name) a = Interface.toAction(self) ret = Interface.getProperty(a,name) if ret.status > 0: @@ -271,7 +271,6 @@ def _get(self, name): raise KeyError(msg) def _set(self, name, value): - #logging.info('_set: %s %s',name,str(value)) a = Interface.toAction(self) if Interface.setProperty(a,name,str(value)): return @@ -508,9 +507,8 @@ class Geant4: return self def printDetectors(self): - logging.info('+++ List of sensitive detectors:') + logger.info('+++ List of sensitive detectors:') for i in self.description.detectors(): - #logging.info(i.second.ptr().GetName()) o = DetElement(i.second.ptr()) sd = self.description.sensitiveDetector(o.name()) if sd.isValid(): @@ -518,7 +516,7 @@ class Geant4: sdtyp = 'Unknown' if self.sensitive_types.has_key(typ): sdtyp = self.sensitive_types[typ] - logging.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 ): @@ -605,15 +603,15 @@ class Geant4: field.delta_one_step = 0.01*SystemOfUnits.mm field.largest_step = 1000*SystemOfUnits.m if prt: - logging.info('+++++> %s %s %s %s ',field.name,'-> stepper = ',str(field.stepper),'') - logging.info('+++++> %s %s %s %s ',field.name,'-> equation = ',str(field.equation),'') - logging.info('+++++> %s %s %s %s ',field.name,'-> eps_min = ',str(field.eps_min),'[mm]') - logging.info('+++++> %s %s %s %s ',field.name,'-> eps_max = ',str(field.eps_max),'[mm]') - logging.info('+++++> %s %s %s %s ',field.name,'-> delta_chord = ',str(field.delta_chord),'[mm]') - logging.info('+++++> %s %s %s %s ',field.name,'-> min_chord_step = ',str(field.min_chord_step),'[mm]') - logging.info('+++++> %s %s %s %s ',field.name,'-> delta_one_step = ',str(field.delta_one_step),'[mm]') - logging.info('+++++> %s %s %s %s ',field.name,'-> delta_intersection = ',str(field.delta_intersection),'[mm]') - logging.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): diff --git a/DDG4/python/DDSim/DD4hepSimulation.py b/DDG4/python/DDSim/DD4hepSimulation.py index 8960bc3a6db3655b229765c58cd72c73f4c1826f..5c86e9234895be64f2eda1ede23ad9367e05275d 100644 --- a/DDG4/python/DDSim/DD4hepSimulation.py +++ b/DDG4/python/DDSim/DD4hepSimulation.py @@ -9,6 +9,12 @@ Based on M. Frank and F. Gaede runSim.py from __future__ import absolute_import __RCSID__ = "$Id$" from g4units import * +import logging + +logging.basicConfig(format='%(levelname)s: %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + import argparse try: import argcomplete @@ -241,9 +247,9 @@ class DD4hepSimulation(object): if self._dumpParameter: from pprint import pprint - print "="*80 + logger.info("="*80) pprint(vars(self)) - print "="*80 + logger.info("="*80) exit(1) if self._dumpSteeringFile: @@ -254,8 +260,6 @@ class DD4hepSimulation(object): def getDetectorLists( detectorDescription ): ''' get lists of trackers and calorimeters that are defined in detectorDescription (the compact xml file)''' import DDG4 - # if len(detectorList): - # print " subset list of detectors given - will only instantiate these: " , detectorList trackers,calos = [],[] for i in detectorDescription.detectors(): det = DDG4.DetElement(i.second.ptr()) @@ -265,7 +269,7 @@ class DD4hepSimulation(object): detType = sd.type() # if len(detectorList) and not(name in detectorList): # continue - print 'getDetectorLists - found active detctor ' , name , ' type: ' , detType + logger.info('getDetectorLists - found active detctor %s type: %s' , name , detType) if detType == "tracker": trackers.append( det.name() ) if detType == "calorimeter": @@ -310,7 +314,7 @@ class DD4hepSimulation(object): elif self.runType == "batch": simple.setupUI(typ="csh", vis=False, macro=None, ui=False) else: - print "ERROR: unknown runType" + logger.errro("unknown runType") exit(1) #kernel.UI="csh" @@ -349,14 +353,14 @@ class DD4hepSimulation(object): gun.Mask = 1 actionList.append(gun) self.__applyBoostOrSmear(kernel, actionList, 1) - print "++++ Adding DD4hep Particle Gun ++++" + logger.info("++++ Adding DD4hep Particle Gun ++++") if self.enableG4Gun: ## GPS Create something self._g4gun = DDG4.GeneratorAction(kernel,"Geant4GeneratorWrapper/Gun") self._g4gun.Uses = 'G4ParticleGun' self._g4gun.Mask = 2 - print "++++ Adding Geant4 Particle Gun ++++" + logger.info("++++ Adding Geant4 Particle Gun ++++") actionList.append(self._g4gun) if self.enableG4GPS: @@ -364,7 +368,7 @@ class DD4hepSimulation(object): self._g4gps = DDG4.GeneratorAction(kernel,"Geant4GeneratorWrapper/GPS") self._g4gps.Uses = 'G4GeneralParticleSource' self._g4gps.Mask = 3 - print "++++ Adding Geant4 General Particle Source ++++" + logger.info("++++ Adding Geant4 General Particle Source ++++") actionList.append(self._g4gps) for index,inputFile in enumerate(self.inputFiles, start=4): @@ -427,7 +431,7 @@ class DD4hepSimulation(object): try: self.filter.setupFilters( kernel ) except RuntimeError as e: - print "ERROR",str(e) + logger.error("%s", e) exit(1) #================================================================================= @@ -439,14 +443,14 @@ class DD4hepSimulation(object): try: self.__setupSensitiveDetectors( trk, simple.setupTracker, self.filter.tracker) except Exception as e: - print "ERROR setting up sensitive detector", str(e) + logger.error("Setting up sensitive detector %s", e) raise # ---- add the calorimeters: try: self.__setupSensitiveDetectors( cal, simple.setupCalorimeter, self.filter.calo ) except Exception as e: - print "ERROR setting up sensitive detector", str(e) + logger.error("Setting up sensitive detector %s", e) raise #================================================================================= @@ -476,12 +480,12 @@ class DD4hepSimulation(object): totalTimeUser, totalTimeSys, _cuTime, _csTime, _elapsedTime = os.times() if self.printLevel <= 3: - print "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 / float(self.numberOfEvents) - print "DDSim INFO StartUp Time: %3.2f s, Event Processing: %3.2f s (%3.2f s/Event) " \ - % (startUpTime, eventTime, perEventTime) + 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): @@ -562,12 +566,12 @@ class DD4hepSimulation(object): :param setupFunction: function used to register the sensitive detector """ for det in detectors: - print 'Setting up SD for %s' % det + logger.info('Setting up SD for %s' % det) action = None for pattern in self.action.mapActions: if pattern.lower() in det.lower(): action = self.action.mapActions[pattern] - print ' replace default action with : ' , action + logger.info(' replace default action with : %s' , action) break seq,act = setupFuction( det, type=action ) self.filter.applyFilters( seq, det, defaultFilter ) @@ -621,7 +625,7 @@ SIM = DD4hepSimulation() else: steeringFileBase += "SIM.%s = %s" %( parName, str(parameter)) steeringFileBase += "\n" - print steeringFileBase + logger.info("%s", steeringFileBase) def _consistencyChecks( self ): @@ -658,9 +662,9 @@ SIM = DD4hepSimulation() """ enablePrimaryHandler = not (self.enableG4Gun or self.enableG4GPS) if enablePrimaryHandler: - print "Enabling the PrimaryHandler" + logger.info("Enabling the PrimaryHandler") else: - print "Disabling the PrimaryHandler" + logger.info("Disabling the PrimaryHandler") return enablePrimaryHandler diff --git a/DDG4/python/DDSim/Helper/Filter.py b/DDG4/python/DDSim/Helper/Filter.py index 0b87a087a6c8d7a98dbfafd1e9aeb0440396eced..e3c94b2ed1b04644c16d9a5c8593ee1883494699 100644 --- a/DDG4/python/DDSim/Helper/Filter.py +++ b/DDG4/python/DDSim/Helper/Filter.py @@ -8,6 +8,11 @@ The default filters are a GeantinoRejector and a 1keV minimum energy cut from __future__ import absolute_import from DDSim.Helper.ConfigHelper import ConfigHelper from g4units import keV +import logging + +logging.basicConfig(format='%(levelname)s: %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) class Filter( ConfigHelper ): """Configuration for sensitive detector filters @@ -126,7 +131,7 @@ class Filter( ConfigHelper ): for val in self.mapDetFilter.values(): listOfFilters += ConfigHelper.makeList(val) requestedFilter = set(chain( ConfigHelper.makeList(self.tracker), ConfigHelper.makeList(self.calo), listOfFilters)) - print "ReqFilt",requestedFilter + logger.info("ReqFilt %s", requestedFilter) if requestedFilter - setOfFilters: raise RuntimeError(" Filter(s) '%s' are not registered!" % str(requestedFilter - setOfFilters) ) @@ -143,7 +148,7 @@ class Filter( ConfigHelper ): if pattern.lower() in det.lower(): foundFilter = True for filt in filts: - print "Adding filter '%s' matched with '%s' to sensitive detector for '%s' " %( filt, pattern, det ) + 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: diff --git a/DDG4/python/DDSim/Helper/Gun.py b/DDG4/python/DDSim/Helper/Gun.py index ccba67ede1d5d307780c96d5eb319c13822cdfd3..755c3228a43e214beadf013a2e3a3e41ff09618a 100644 --- a/DDG4/python/DDSim/Helper/Gun.py +++ b/DDG4/python/DDSim/Helper/Gun.py @@ -3,6 +3,11 @@ from __future__ import absolute_import from DDSim.Helper.ConfigHelper import ConfigHelper from g4units import GeV +import logging + +logging.basicConfig(format='%(levelname)s: %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) class Gun( ConfigHelper ): """Configuration for the DDG4 ParticleGun""" @@ -121,5 +126,5 @@ class Gun( ConfigHelper ): ddg4Gun.PhiMax = self.phiMax ddg4Gun.isotrop = True except Exception as e: #pylint: disable=W0703 - print "ERROR: parsing gun options:\n%s\nException: %s " % (self, e ) + logger.error("parsing gun options:\n%s\nException: %s " % (self, e )) exit(1) diff --git a/DDG4/python/DDSim/Helper/Meta.py b/DDG4/python/DDSim/Helper/Meta.py index 0e4370659c2aa9f0b8f73402793c17bb9f447aa2..5a8254cbad90e18174ac6dfd0df0c2286df391b5 100644 --- a/DDG4/python/DDSim/Helper/Meta.py +++ b/DDG4/python/DDSim/Helper/Meta.py @@ -3,6 +3,11 @@ from __future__ import absolute_import import datetime import os +import logging + +logging.basicConfig(format='%(levelname)s: %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) from DDSim.Helper.ConfigHelper import ConfigHelper @@ -41,7 +46,7 @@ class Meta( ConfigHelper ): if not pvalue: raise RuntimeError("ERROR: Event parameter '%s' has empty value" %(pname)) allParameters.append(pname) - print "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": diff --git a/DDG4/python/DDSim/Helper/ParticleHandler.py b/DDG4/python/DDSim/Helper/ParticleHandler.py index d9a5278834a8c3fbbaa575bf004e3e014d5d6869..46f201e5759939ea0b1f1998d5c99e9d8802b191 100644 --- a/DDG4/python/DDSim/Helper/ParticleHandler.py +++ b/DDG4/python/DDSim/Helper/ParticleHandler.py @@ -1,6 +1,11 @@ """Configuration Helper for ParticleHandler""" from __future__ import absolute_import from g4units import MeV, mm +import logging + +logging.basicConfig(format='%(levelname)s: %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) from DDSim.Helper.ConfigHelper import ConfigHelper @@ -112,7 +117,7 @@ class ParticleHandler( ConfigHelper ): return if self.userParticleHandler not in ["Geant4TCUserParticleHandler"]: - print "ERROR: unknown UserParticleHandler: %r" % self.userParticleHandler + logger.error("unknown UserParticleHandler: %r" % self.userParticleHandler) exit(1) if self.userParticleHandler == "Geant4TCUserParticleHandler": @@ -120,15 +125,15 @@ class ParticleHandler( ConfigHelper ): try: user.TrackingVolume_Zmax = DDG4.tracker_region_zmax user.TrackingVolume_Rmax = DDG4.tracker_region_rmax - print " *** definition of tracker region *** " - print " tracker_region_zmax = " , user.TrackingVolume_Zmax - print " tracker_region_rmax = " , user.TrackingVolume_Rmax - print " ************************************ " + logger.info(" *** definition of tracker region *** ") + logger.info(" tracker_region_zmax = " , user.TrackingVolume_Zmax) + logger.info(" tracker_region_rmax = " , user.TrackingVolume_Rmax) + logger.info(" ************************************ ") except AttributeError as e: - print "ERROR - attribute of tracker region missing in detector model ", str(e) - print " make sure to specify the global constants tracker_region_zmax and tracker_region_rmax " - print " this is needed for the MC-truth link of created sim-hits ! " - print " Or Disable the User Particle Handler with --part.userParticleHandler=''" + logger.error("Attribute of tracker region missing in detector model %s", e) + logger.error(" make sure to specify the global constants tracker_region_zmax and tracker_region_rmax ") + logger.error(" this is needed for the MC-truth link of created sim-hits ! ") + logger.error(" Or Disable the User Particle Handler with --part.userParticleHandler=''") exit(1) part.adopt(user) diff --git a/DDG4/python/DDSim/Helper/Random.py b/DDG4/python/DDSim/Helper/Random.py index d66d8d618d360691565912660f914bbf9a29f0cc..625b87a00e453cd234b955bf773a90d3291408b7 100644 --- a/DDG4/python/DDSim/Helper/Random.py +++ b/DDG4/python/DDSim/Helper/Random.py @@ -2,6 +2,11 @@ from __future__ import absolute_import import random +import logging + +logging.basicConfig(format='%(levelname)s: %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) from DDSim.Helper.ConfigHelper import ConfigHelper @@ -36,7 +41,7 @@ class Random (ConfigHelper): if self.seed is None: ## System provided random source, truely random according to documentation self.seed = random.SystemRandom().randint(0, 2**31-1) - print "Choosing random seed for you:", self.seed + logger.info("Choosing random seed for you: %s", self.seed) self._random.Seed = self.seed self._random.Luxury = self.luxury diff --git a/DDG4/python/SystemOfUnits.py b/DDG4/python/SystemOfUnits.py index 895234067c08c40615385ab20600e998ce7a1df1..513e3f05ba58d4d29d688055c483c37e16b1c22f 100644 --- a/DDG4/python/SystemOfUnits.py +++ b/DDG4/python/SystemOfUnits.py @@ -13,6 +13,6 @@ # The namespace "DD4hep" is deprecated. Please use "dd4hep" instead. # #========================================================================== -from __future__ import absolute_import +from __future__ import absolute_import, print_function from g4units import * -print 'DEPRECATION WARNING The namespace "SystemOfUnits" is deprecated. Please use "g4units" instead.' +print('DEPRECATION WARNING The namespace "SystemOfUnits" is deprecated. Please use "g4units" instead.') diff --git a/DDG4/python/checkGeometry.py b/DDG4/python/checkGeometry.py index f8d6e8370706ef0561586c384f8c8ca73956e945..83f4f031d66fb950bcf35e432624633e1e13507b 100755 --- a/DDG4/python/checkGeometry.py +++ b/DDG4/python/checkGeometry.py @@ -13,7 +13,10 @@ from __future__ import absolute_import import sys, errno, optparse, logging -logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) +logging.basicConfig(format='%(levelname)s: %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + parser = optparse.OptionParser() parser.description = "TGeo Geometry checking." parser.formatter.width = 132 @@ -53,7 +56,7 @@ parser.add_option("-o", "--option", dest="option", default='ob', (opts, args) = parser.parse_args() if opts.compact is None: - logging.info(" %s",parser.format_help()) + logger.info(" %s",parser.format_help()) sys.exit(1) try: @@ -61,30 +64,30 @@ try: from ROOT import gROOT gROOT.SetBatch(1) except ImportError,X: - logging.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,X: - logging.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) -logging.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) -logging.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: - logging.info('+++ # tracks:%d vertex:(%7.3f, %7.3f, %7.3f) [cm]',opts.num_tracks,opts.vx,opts.vy,opts.vz) + 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() # # -logging.info('+++ Execution finished...') +logger.info('+++ Execution finished...') sys.exit(0) diff --git a/DDG4/python/checkOverlaps.py b/DDG4/python/checkOverlaps.py index f9d105b7de05f54ac4fd3b67081d386636c69dc2..a648951534361b57802a288c91e3968447b99297 100755 --- a/DDG4/python/checkOverlaps.py +++ b/DDG4/python/checkOverlaps.py @@ -13,7 +13,10 @@ from __future__ import absolute_import import sys, errno, optparse, logging -logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) +logging.basicConfig(format='%(levelname)s: %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + parser = optparse.OptionParser() parser.formatter.width = 132 parser.description = "Check TGeo geometries for overlaps." @@ -37,7 +40,7 @@ parser.add_option("-o", "--option", dest="option", default='', (opts, args) = parser.parse_args() if opts.compact is None: - logging.info(" %s",parser.format_help()) + logger.info(" %s",parser.format_help()) sys.exit(1) try: @@ -45,31 +48,31 @@ try: from ROOT import gROOT gROOT.SetBatch(1) except ImportError,X: - logging.error('PyROOT interface not accessible: %s',str(X)) - logging.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,X: - logging.error('dd4hep python interface not accessible: %s',str(X)) - logging.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) -logging.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) -logging.info('+++%s\n+++ Checking overlaps of geometry:%s tolerance:%f option:%s\n+++%s',120*'=',opts.compact,opts.tolerance,opts.option,120*'=') +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: - logging.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() # # -logging.info('+++ Execution finished...') +logger.info('+++ Execution finished...') sys.exit(0) diff --git a/DDG4/python/g4MaterialScan.py b/DDG4/python/g4MaterialScan.py index 85f7c83e428c76bd095c117c6496901a92f9aa0e..acf8742bf877d2859f875b5e677b5aa181a3c458 100644 --- a/DDG4/python/g4MaterialScan.py +++ b/DDG4/python/g4MaterialScan.py @@ -13,12 +13,15 @@ from __future__ import absolute_import import os, sys, errno, optparse, logging -logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) +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(): - logging.info('%s > %-18s %s [%s]',prefix,name+':',str(value),str(value.__class__)) + logger.info('%s > %-18s %s [%s]',prefix,name+':',str(value),str(value.__class__)) def materialScan(opts): kernel = DDG4.Kernel() @@ -37,7 +40,7 @@ def materialScan(opts): geant4.setupDetector(o.name(),geant4.sensitive_types[typ]) sdtyp = geant4.sensitive_types[typ] else: - logging.info('+++ %-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", @@ -93,7 +96,7 @@ parser.add_option('-d', '--direction', (opts, args) = parser.parse_args() if opts.compact is None: - logging.info(" ",parser.format_help()) + logger.info("%s",parser.format_help()) sys.exit(1) opts.position=eval('('+opts.position+')') @@ -105,15 +108,15 @@ try: from ROOT import gROOT gROOT.SetBatch(1) except ImportError,X: - logging.info('PyROOT interface not accessible: %s',str(X)) - logging.info(parser.format_help()) + logger.error('PyROOT interface not accessible: %s', X) + logger.info(parser.format_help()) sys.exit(errno.ENOENT) try: import DDG4, SystemOfUnits except ImportError,X: - logging.info('DDG4 python interface not accessible: %s',str(X)) - logging.info(parser.format_help()) + logger.error('DDG4 python interface not accessible: %s', X) + logger.info(parser.format_help()) sys.exit(errno.ENOENT) # ret = materialScan(opts) diff --git a/DDRec/python/DDRec.py b/DDRec/python/DDRec.py index 9d99e5e2e6208c39d7d45ed28ae4ef84f4c429dc..71ff5d1237ccbb3a19eeb8d010ef89695437eb4c 100644 --- a/DDRec/python/DDRec.py +++ b/DDRec/python/DDRec.py @@ -10,6 +10,11 @@ #========================================================================== from __future__ import absolute_import import logging + +logging.basicConfig(format='%(levelname)s: %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + import dd4hep as core def loadDDRec(): @@ -34,10 +39,10 @@ def import_namespace_item(ns,nam): try: rec = loadDDRec() except Exception as X: - logging.info('+--%-100s--+',100*'-') - logging.info('| %-100s |','Failed to load DDRec library:') - logging.info('| %-100s |',str(X)) - logging.info('+--%-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) diff --git a/DDRec/python/dumpDetectorData.py b/DDRec/python/dumpDetectorData.py index ee10b41f850807ac074013b4103dcd038c392e43..af01788c663b89858b95325293d7089a50072132 100644 --- a/DDRec/python/dumpDetectorData.py +++ b/DDRec/python/dumpDetectorData.py @@ -13,44 +13,43 @@ from __future__ import absolute_import import sys, errno, optparse, logging +logging.basicConfig(format='%(levelname)s: %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) def dumpData( det ): try: dat = DDRec.FixedPadSizeTPCData(det) - print dat.toString() + logger.info(dat.toString()) except: pass try: dat = DDRec.ZPlanarData(det) - print dat.toString() + logger.info(dat.toString()) except: pass try: dat = DDRec.ZDiskPetalsData(det) - print dat.toString() + logger.info(dat.toString()) except: pass try: dat = DDRec.ConicalSupportData(det) - print dat.toString() + logger.info(dat.toString()) except: pass try: dat = DDRec.LayeredCalorimeterData(det) - print dat.toString() + logger.info(dat.toString()) except: pass try: dat = DDRec.NeighbourSurfacesStruct(det) - print dat.toString() + logger.info(dat.toString()) except: pass - - - -logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) parser = optparse.OptionParser() parser.formatter.width = 132 parser.description = "Dump detector data objects from DDRec" @@ -61,7 +60,7 @@ parser.add_option("-c", "--compact", dest="compact", default=None, (opts, args) = parser.parse_args() if opts.compact is None: - logging.info(" %s",parser.format_help()) + logger.info(" %s",parser.format_help()) sys.exit(1) try: @@ -69,27 +68,27 @@ try: from ROOT import gROOT gROOT.SetBatch(1) except ImportError,X: - logging.error('PyROOT interface not accessible: %s',str(X)) - logging.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,X: - logging.error('dd4hep python interface not accessible: %s',str(X)) - logging.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,X: - logging.error('ddrec python interface not accessible: %s',str(X)) - logging.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) -logging.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*'=') @@ -101,9 +100,9 @@ description.fromXML(opts.compact) for n,d in description.detectors(): - print - print " ------------- detector : " , d.name() - print + logger.info("") + logger.info(" ------------- detector : %s" , d.name()) + logger.info("") det = description.detector( n ) @@ -112,5 +111,5 @@ for n,d in description.detectors(): ##----------------------------------------------------------------- -logging.info('+++ Execution finished...') +logger.info('+++ Execution finished...') sys.exit(0) diff --git a/GaudiPluginService/python/GaudiPluginService/cpluginsvc.py b/GaudiPluginService/python/GaudiPluginService/cpluginsvc.py index b8cde1c66246a15dac872e8365d3761e95b7f8f6..bd15fae5bc53cf087069f2e5f5cfc77999b37ba0 100644 --- a/GaudiPluginService/python/GaudiPluginService/cpluginsvc.py +++ b/GaudiPluginService/python/GaudiPluginService/cpluginsvc.py @@ -1,5 +1,5 @@ # cpluginsvc is a ctypes-based wrapper for the C-exposed API of GaudiPluginService -from __future__ import absolute_import +from __future__ import absolute_import, print_function __doc__ = ''' cpluginsvc is a ctypes-based wrapper for the C-API of the GaudiPluginService. @@ -10,11 +10,11 @@ e.g.: ... try: ... f.load() ... except Exception: -... print ("** could not load [%s] for factory [%s]" % (f.library, f.name)) +... print(("** could not load [%s] for factory [%s]" % (f.library, f.name))) ... continue -... print f +... print(f) ... for k,v in f.properties.iteritems(): -... print ("\t%s: %s" % (k,v)) +... print(("\t%s: %s" % (k,v))) ''' import ctypes @@ -217,17 +217,16 @@ for f in _functions_list: pass if __name__ == "__main__": - print("instance: %s" % registry()) - print("factories: %d" % len(factories())) - for _, f in factories().items(): + 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)) + 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(f) + for k,v in f.properties.items(): + print(("\t%s: %s" % (k,v))) # EOF diff --git a/examples/CLICSiD/scripts/CLICRandom.py b/examples/CLICSiD/scripts/CLICRandom.py index d25129e598a2ea6398ef31746c1309372dc2053f..c10af43f47a0f058aa6da75a62ceb8f8548fb171 100644 --- a/examples/CLICSiD/scripts/CLICRandom.py +++ b/examples/CLICSiD/scripts/CLICRandom.py @@ -9,23 +9,28 @@ from __future__ import absolute_import from ROOT import TRandom from ROOT import gRandom +import logging + +logging.basicConfig(format='%(levelname)s: %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + if __name__ == "__main__": - import logging, CLICSid, DDG4 + import CLICSid, DDG4 sid = CLICSid.CLICSid() - logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) - logging.info('DEFAULT Engine: %s', DDG4.CLHEP.HepRandom.getTheEngine().name()) + 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') - logging.info('R1: %s Default instance: %s', rndm1.name, rndm1.instance().name()) - logging.info(' Engine: %s', rndm1.engine().name()) - logging.info(' DEFAULT: %s', DDG4.CLHEP.HepRandom.getTheEngine().name()) + 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') - logging.info('R2: %s Default instance: %s', rndm2.name, rndm2.instance().name()) - logging.info(' Engine: %s', rndm2.engine().name()) - logging.info(' DEFAULT: %s', DDG4.CLHEP.HepRandom.getTheEngine().name()) + 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() DDG4.Geant4Random.setMainInstance(rndm1.get()) @@ -34,29 +39,29 @@ if __name__ == "__main__": # Move main geant random instance from rndm1 to rndm2: # See how gRandom and HepRandom instances move DDG4.Geant4Random.setMainInstance(rndm1.get()) - logging.info('DEFAULT Engine: %s', DDG4.CLHEP.HepRandom.getTheEngine().name()) - logging.info('DDG4 DEFAULT: %s', DDG4.Geant4Random.instance().engine().name()) + logger.info('DEFAULT Engine: %s', DDG4.CLHEP.HepRandom.getTheEngine().name()) + logger.info('DDG4 DEFAULT: %s', DDG4.Geant4Random.instance().engine().name()) rndm = DDG4.Geant4Random.instance() rndm.setSeed(1234) rndm.showStatus() for i in xrange(10): - logging.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 xrange(10): - logging.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 xrange(10): - logging.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 xrange(10): - logging.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 xrange(10): - logging.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 90115d1a325784d13389f2e14c3b3197cf4b4285..e3f487d947ed18a7afa9a0b82f529394f25fb7e9 100644 --- a/examples/CLICSiD/scripts/CLICSiDScan.py +++ b/examples/CLICSiD/scripts/CLICSiDScan.py @@ -7,10 +7,15 @@ """ from __future__ import absolute_import +import logging + +logging.basicConfig(format='%(levelname)s: %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + def run(): - import os, sys, logging, DDG4, CLICSid, g4units + import os, sys, DDG4, CLICSid, g4units - logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) sid = CLICSid.CLICSid() sid.loadGeometry() DDG4.Core.setPrintFormat("%-32s %6s %s") @@ -41,8 +46,8 @@ def run(): sid.kernel.run() sid.kernel.terminate() - logging.info('End of run. Terminating .......') - logging.info('TEST_PASSED') + 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 ff23c8b49c2e91c2345c23dccde59eac8b6f0a70..e66a16711b31bdd7aded7975572fd43a688a48d4 100644 --- a/examples/CLICSiD/scripts/CLICSiD_LoadROOTGeo.py +++ b/examples/CLICSiD/scripts/CLICSiD_LoadROOTGeo.py @@ -8,11 +8,16 @@ """ from __future__ import absolute_import +import logging + +logging.basicConfig(format='%(levelname)s: %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + def run(): - import sys, logging, CLICSid, DDG4 + import sys, CLICSid, DDG4 from DDG4 import OutputLevel as Output - logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) sid = CLICSid.CLICSid() geant4 = sid.geant4 kernel = sid.kernel @@ -33,7 +38,7 @@ def run(): gen = DDG4.GeneratorAction(kernel,"Geant4GeneratorActionInit/GenerationInit") kernel.generatorAction().adopt(gen) - logging.info("# First particle generator: gun") + logger.info("# First particle generator: gun") gun = DDG4.GeneratorAction(kernel,"Geant4GeneratorWrapper/Gun"); gun.Uses = 'G4ParticleGun' gun.Mask = 1 diff --git a/examples/CLICSiD/scripts/CLICSid.py b/examples/CLICSiD/scripts/CLICSid.py index ab900e28db0aab6bc2469bbd37acc602f43cef2b..67686730ae3542db7dc2b6e4022bf1d909ab75b4 100644 --- a/examples/CLICSiD/scripts/CLICSid.py +++ b/examples/CLICSiD/scripts/CLICSid.py @@ -2,6 +2,10 @@ from __future__ import absolute_import import sys, logging, 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'): self.kernel = DDG4.Kernel() @@ -60,13 +64,13 @@ class CLICSid: return self def setupDetectors(self): - logging.info("# First the tracking detectors") + 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') - logging.info("# Now setup the calorimeters") + logger.info("# Now setup the calorimeters") seq,act = self.geant4.setupCalorimeter('EcalBarrel') seq,act = self.geant4.setupCalorimeter('EcalEndcap') seq,act = self.geant4.setupCalorimeter('HcalBarrel') @@ -91,5 +95,5 @@ class CLICSid: self.kernel.NumEvents = 0 self.kernel.run() self.kernel.terminate() - logging.info('+++++ All Done....\n\nTEST_PASSED') + logger.info('+++++ All Done....\n\nTEST_PASSED') sys.exit(0) diff --git a/examples/CLICSiD/scripts/CLIC_G4Gun.py b/examples/CLICSiD/scripts/CLIC_G4Gun.py index bc13b19522ccb4118934c82fcd3e863ca551651b..31bc191be0b8c017a1f009dcb5c7a2673db6c70c 100644 --- a/examples/CLICSiD/scripts/CLIC_G4Gun.py +++ b/examples/CLICSiD/scripts/CLIC_G4Gun.py @@ -8,11 +8,17 @@ """ from __future__ import absolute_import + +import logging + +logging.basicConfig(format='%(levelname)s: %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + def run(): - import logging, CLICSid, DDG4 + import CLICSid, DDG4 from DDG4 import OutputLevel as Output - - logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) + sid = CLICSid.CLICSid() geant4 = sid.geant4 kernel = sid.kernel @@ -30,7 +36,7 @@ def run(): gen = DDG4.GeneratorAction(kernel,"Geant4GeneratorActionInit/GenerationInit") kernel.generatorAction().adopt(gen) - logging.info("# First particle generator: gun") + logger.info("# First particle generator: gun") gun = DDG4.GeneratorAction(kernel,"Geant4GeneratorWrapper/Gun"); gun.Uses = 'G4ParticleGun' gun.Mask = 1 diff --git a/examples/CLICSiD/scripts/CLIC_GDML.py b/examples/CLICSiD/scripts/CLIC_GDML.py index 0f3777d7490ea15eda444ce89c04a5b52100bb0f..e3d4da6830e5822b22a879001222d0445868ee32 100644 --- a/examples/CLICSiD/scripts/CLIC_GDML.py +++ b/examples/CLICSiD/scripts/CLIC_GDML.py @@ -7,12 +7,12 @@ """ from __future__ import absolute_import + def run(): from g4units import * - import logging, CLICSid, DDG4 + import CLICSid, DDG4 from DDG4 import OutputLevel as Output - logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) sid = CLICSid.CLICSid() sid.loadGeometry() sid.geant4.printDetectors() diff --git a/examples/CLICSiD/scripts/testDDPython.py b/examples/CLICSiD/scripts/testDDPython.py index dcd6f273697cb4395bea9775b3a928e0464efe24..b4ed56600488be6289af3e9d4d8708d37f8932b8 100644 --- a/examples/CLICSiD/scripts/testDDPython.py +++ b/examples/CLICSiD/scripts/testDDPython.py @@ -8,7 +8,9 @@ gSystem.Load('libglapi') gSystem.Load('libDDPython') from ROOT import dd4hep as Core -logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) +logging.basicConfig(format='%(levelname)s: %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) name_space = __import__(__name__) def import_namespace_item(ns,nam): @@ -18,58 +20,58 @@ def import_namespace_item(ns,nam): return attr def a_func(): - logging.info('Hello world') + logger.info('Hello world') return 1 class a_class: def __init__(self): pass def fcn(self): - logging.info('Hello world from member function fcn') + logger.info('Hello world from member function fcn') return 1 def fcn_except(self,args,aa): - logging.info('Hello world from member function fcn1 a1=%s a2=%s',str(args),str(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') -logging.info('+++++ Test: Execute statements in python with C++ indirection') +logger.info('+++++ Test: Execute statements in python with C++ indirection') py.instance().execute('import sys, logging') py.instance().execute('logging.info("Arguments: %s", str(sys.argv))') -logging.info('\n') +logger.info('\n') obj=a_class() import sys, traceback -logging.info('+++++ Test: simple function call') +logger.info('+++++ Test: simple function call') ret = py.instance().call(a_func,None) -logging.info('ret: %s',str(ret)) -logging.info('\n') +logger.info('ret: %s',str(ret)) +logger.info('\n') -logging.info('+++++ Test: object method call') +logger.info('+++++ Test: object method call') ret = py.instance().call(obj.fcn,None) -logging.info('ret: %s',str(ret)) -logging.info('\n') +logger.info('ret: %s',str(ret)) +logger.info('\n') -logging.info('+++++ Test: object method call with non callable') +logger.info('+++++ Test: object method call with non callable') try: ret = py.instance().call(1,None) - logging.info('ret: %s',str(ret)) + logger.info('ret: %s',str(ret)) except: traceback.print_exc() -logging.info('\n') +logger.info('\n') -logging.info('+++++ Test: object method call with exception in python callback') +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],)) - logging.info('ret: %s',str(ret)) + logger.info('ret: %s',str(ret)) except: traceback.print_exc() -logging.info('\n') -logging.info('+++++ All Done....\n\n') -logging.info('TEST_PASSED') +logger.info('\n') +logger.info('+++++ All Done....\n\n') +logger.info('TEST_PASSED') #py.instance().prompt() diff --git a/examples/ClientTests/scripts/DDG4TestSetup.py b/examples/ClientTests/scripts/DDG4TestSetup.py index 35a5a3310a2b112a603da58af52cee8c9a238d6d..4243bc5d60cfb878d7c76ec6b0fbdc5b133b4fd6 100644 --- a/examples/ClientTests/scripts/DDG4TestSetup.py +++ b/examples/ClientTests/scripts/DDG4TestSetup.py @@ -3,7 +3,9 @@ import os, sys, time, logging, DDG4 from DDG4 import OutputLevel as Output from SystemOfUnits import * -logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) +logging.basicConfig(format='%(levelname)s: %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) """ @@ -63,7 +65,7 @@ class Setup: # Stop the entire excercise def terminate(self): self.kernel.terminate() - logging.info('+++++ All Done....\n\nTEST_PASSED') + logger.info('+++++ All Done....\n\nTEST_PASSED') sys.exit(0) # Test the configuration diff --git a/examples/ClientTests/scripts/LheD_tracker.py b/examples/ClientTests/scripts/LheD_tracker.py index afe3a1282b0aaed129995fe4b8f55e575a5b0a77..ece390b56ed696991d705a48ecb0b613dc057474 100644 --- a/examples/ClientTests/scripts/LheD_tracker.py +++ b/examples/ClientTests/scripts/LheD_tracker.py @@ -4,6 +4,12 @@ from __future__ import absolute_import import os, sys, time, DDG4 from DDG4 import OutputLevel as Output from SystemOfUnits import * +import logging + +logging.basicConfig(format='%(levelname)s: %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + # # """ @@ -63,7 +69,7 @@ def run(): #DDG4.setPrintLevel(Output.DEBUG) kernel.run() - print 'End of run. Terminating .......' + logger.info('End of run. Terminating .......') kernel.terminate() if __name__ == "__main__": diff --git a/examples/ClientTests/scripts/MiniTelRegions.py b/examples/ClientTests/scripts/MiniTelRegions.py index 5bc15ec85028480f7ba0dedfec8d6ab49c122ab2..f6d05bdd0fc7f8cb7c0173149f1eec58743e426a 100644 --- a/examples/ClientTests/scripts/MiniTelRegions.py +++ b/examples/ClientTests/scripts/MiniTelRegions.py @@ -6,12 +6,17 @@ """ from __future__ import absolute_import +import logging + +logging.basicConfig(format='%(levelname)s: %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + if __name__ == "__main__": from MiniTelSetup import Setup as MiniTel - import logging m = MiniTel() m.configure() - logging.info("# Configure G4 geometry setup") + logger.info("# Configure G4 geometry setup") seq,act = m.geant4.addDetectorConstruction("Geant4DetectorGeometryConstruction/ConstructGeo") act.DebugRegions = True m.test_config(True) diff --git a/examples/DDCMS/scripts/CMSTrackerSim.py b/examples/DDCMS/scripts/CMSTrackerSim.py index 40c03f748cb19b491506b6a6ddc573f6a2e4e0be..cdd17addb603515db5e0b1edc41f46b3374f727c 100644 --- a/examples/DDCMS/scripts/CMSTrackerSim.py +++ b/examples/DDCMS/scripts/CMSTrackerSim.py @@ -2,6 +2,12 @@ from __future__ import absolute_import import os, sys, time, DDG4 from DDG4 import OutputLevel as Output from SystemOfUnits import * +import logging + +logging.basicConfig(format='%(levelname)s: %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + # # """ @@ -53,7 +59,7 @@ def run(): sd = geant4.description.sensitiveDetector(o.name()) if sd.isValid(): type = geant4.sensitive_types[sd.type()] - print 'CMSTracker: Configure subdetector %-24s of type %s'%(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. diff --git a/examples/DDDigi/scripts/TestFramework.py b/examples/DDDigi/scripts/TestFramework.py index b4a6a012bd462e9ce2c292d6d1a439b5ff67d407..411a590d003f8d88b0038c78003ecf583eec4574 100644 --- a/examples/DDDigi/scripts/TestFramework.py +++ b/examples/DDDigi/scripts/TestFramework.py @@ -1,7 +1,7 @@ from __future__ import absolute_import -import os, sys, logging, DDDigi +import os, sys, DDDigi DDDigi.setPrintFormat('%-32s %5s %s') kernel = DDDigi.Kernel() diff --git a/examples/LHeD/scripts/LHeD.py b/examples/LHeD/scripts/LHeD.py index 2c57089b5beb375c8f393bd12ad3899b686026da..69774a7a1d4b6d8331c08268afb93b02eab8e820 100644 --- a/examples/LHeD/scripts/LHeD.py +++ b/examples/LHeD/scripts/LHeD.py @@ -2,6 +2,10 @@ from __future__ import absolute_import import sys, logging, 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'): self.kernel = DDG4.Kernel() @@ -53,12 +57,12 @@ class LHeD: return self def setupDetectors(self): - logging.info("# First the tracking detectors") + 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') - logging.info("# Now setup the calorimeters") + 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') @@ -86,5 +90,5 @@ class LHeD: self.kernel.NumEvents = 0 self.kernel.run() self.kernel.terminate() - logging.info('+++++ All Done....\n\nTEST_PASSED') + logger.info('+++++ All Done....\n\nTEST_PASSED') sys.exit(0) diff --git a/examples/LHeD/scripts/LHeDRandom.py b/examples/LHeD/scripts/LHeDRandom.py index c34e098430179acfab201ceedf04159609eff51f..3def4ca8039d65d3aa01337e4d6a7ba2e25278ef 100644 --- a/examples/LHeD/scripts/LHeDRandom.py +++ b/examples/LHeD/scripts/LHeDRandom.py @@ -8,23 +8,27 @@ from __future__ import absolute_import from ROOT import TRandom from ROOT import gRandom +import logging + +logging.basicConfig(format='%(levelname)s: %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) if __name__ == "__main__": - import LHeD, DDG4, logging + import LHeD, DDG4 lhed = LHeD.LHeD() - logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) - logging.info('DEFAULT Engine: %s', DDG4.CLHEP.HepRandom.getTheEngine().name()) # <<-- See this function to know how it's done.... + 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') - logging.info('R1: %s Default instance: %s', rndm1.name, rndm1.instance().name()) - logging.info(' Engine: %s', rndm1.engine().name()) - logging.info(' DEFAULT: %s', DDG4.CLHEP.HepRandom.getTheEngine().name()) + 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') - logging.info('R2: %s Default instance: %s', rndm2.name, rndm2.instance().name()) - logging.info(' Engine: %s', rndm2.engine().name()) - logging.info(' DEFAULT: %s', DDG4.CLHEP.HepRandom.getTheEngine().name()) + 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() DDG4.Geant4Random.setMainInstance(rndm1.get()) @@ -33,29 +37,29 @@ if __name__ == "__main__": # Move main geant random instance from rndm1 to rndm2: # See how gRandom and HepRandom instances move DDG4.Geant4Random.setMainInstance(rndm1.get()) - logging.info('DEFAULT Engine: %s', DDG4.CLHEP.HepRandom.getTheEngine().name()) - logging.info('DDG4 DEFAULT: %s', DDG4.Geant4Random.instance().engine().name()) + logger.info('DEFAULT Engine: %s', DDG4.CLHEP.HepRandom.getTheEngine().name()) + logger.info('DDG4 DEFAULT: %s', DDG4.Geant4Random.instance().engine().name()) rndm = DDG4.Geant4Random.instance() rndm.setSeed(1234) rndm.showStatus() for i in xrange(10): - logging.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 xrange(10): - logging.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 xrange(10): - logging.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 xrange(10): - logging.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 xrange(10): - logging.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 af90335530333833dfcea0f7a69189867193a492..c5f5d8dba8e1dcab599b49879bf1f8e3d2f9236f 100644 --- a/examples/LHeD/scripts/LHeDScan.py +++ b/examples/LHeD/scripts/LHeDScan.py @@ -7,10 +7,15 @@ """ from __future__ import absolute_import +import logging + +logging.basicConfig(format='%(levelname)s: %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + def run(): - import os, sys, logging, DDG4, SystemOfUnits + import os, sys, DDG4, SystemOfUnits - logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) kernel = DDG4.Kernel() install_dir = os.environ['DD4hepExamplesINSTALL'] kernel.loadGeometry("file:"+install_dir+"/examples/LHeD/compact/compact.xml") @@ -43,8 +48,8 @@ def run(): kernel.run() kernel.terminate() - logging.info('End of run. Terminating .......') - logging.info('TEST_PASSED') + 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 33ca186a44d9b190514420fca5e706285788706f..4c704d9872182d27f8e65951f7a4de75d8cbfc38 100644 --- a/examples/LHeD/scripts/LHeD_G4Gun.py +++ b/examples/LHeD/scripts/LHeD_G4Gun.py @@ -8,11 +8,16 @@ """ from __future__ import absolute_import +import logging + +logging.basicConfig(format='%(levelname)s: %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + def run(): - import logging, LHeD, DDG4 + import LHeD, DDG4 from DDG4 import OutputLevel as Output - logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) lhed = LHeD.LHeD() geant4 = lhed.geant4 kernel = lhed.kernel @@ -30,7 +35,7 @@ def run(): gen = DDG4.GeneratorAction(kernel,"Geant4GeneratorActionInit/GenerationInit") kernel.generatorAction().adopt(gen) - logging.info("# First particle generator: gun") + logger.info("# First particle generator: gun") gun = DDG4.GeneratorAction(kernel,"Geant4GeneratorWrapper/Gun"); gun.Uses = 'G4ParticleGun' gun.Mask = 1 diff --git a/examples/LHeD/scripts/LheSimu.py b/examples/LHeD/scripts/LheSimu.py index 4897482f8f1cea0e65eb9ed7c389e6c0c0e65ba8..5838f0baec4e484caf88993694511dd39e1e54e4 100644 --- a/examples/LHeD/scripts/LheSimu.py +++ b/examples/LHeD/scripts/LheSimu.py @@ -8,6 +8,12 @@ """ from __future__ import absolute_import +import logging + +logging.basicConfig(format='%(levelname)s: %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + def run(): import LHeD, DDG4, os, SystemOfUnits from DDG4 import OutputLevel as Output @@ -38,11 +44,11 @@ def run(): field.delta_chord = 0.25*SystemOfUnits.mm field.delta_intersection = 1e-05*SystemOfUnits.mm field.delta_one_step = 0.001*SystemOfUnits.mm - print '+++++> ',field.name,'-> stepper = ',field.stepper - print '+++++> ',field.name,'-> equation = ',field.equation - print '+++++> ',field.name,'-> eps_min = ',field.eps_min - print '+++++> ',field.name,'-> eps_max = ',field.eps_max - print '+++++> ',field.name,'-> delta_one_step = ',field.delta_one_step + 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) """ @@ -60,7 +66,6 @@ def run(): run1.Property_int = 12345 run1.Property_double = -5e15*keV run1.Property_string = 'Startrun: Hello_LHeD' - print run1.Property_string, run1.Property_double, run1.Property_int """ run1.enableUI() kernel.registerGlobalAction(run1) @@ -324,7 +329,7 @@ def run(): #DDG4.setPrintLevel(Output.DEBUG) kernel.run() - print 'End of run. Terminating .......' + logging.info('End of run. Terminating .......') kernel.terminate() if __name__ == "__main__":