diff --git a/CaloTB/CaloTB_EPT_AHCAL/TBModel2015_steering.py b/CaloTB/CaloTB_EPT_AHCAL/TBModel2015_steering.py index b547c31e3..a90bfc930 100644 --- a/CaloTB/CaloTB_EPT_AHCAL/TBModel2015_steering.py +++ b/CaloTB/CaloTB_EPT_AHCAL/TBModel2015_steering.py @@ -6,33 +6,38 @@ SIM.compactFile = "../../DD4HEP/compact/TBModel2015.xml" SIM.runType = "batch" SIM.macroFile = "vis.mac" -#SIM.inputFiles = "mcparticles.slcio" +# SIM.inputFiles = "mcparticles.slcio" SIM.outputFile = "DD4hep_mu-_8GeV_QGSP_BERT_10k.slcio" SIM.numberOfEvents = 10000 SIM.skipNEvents = 0 SIM.physicsList = "QGSP_BERT" SIM.dumpSteeringFile = "TBModel2015_dump.xml" -SIM.enableDetailedShowerMode=True +SIM.enableDetailedShowerMode = True SIM.random.seed = "0123456789" -SIM.field.eps_min = 1*mm -SIM.part.minimalKineticEnergy = 1*MeV +SIM.field.eps_min = 1 * mm +SIM.part.minimalKineticEnergy = 1 * MeV SIM.action.calo = "Geant4ScintillatorCalorimeterAction" ## set the particle.tbl file to add extra particles to DDsim (B-Baryons) ## use the power of python to get the file from DD4hep wherever it is import os -if os.path.exists( os.path.join( os.environ.get("DD4hepINSTALL"), "examples/DDG4/examples/particle.tbl") ): - SIM.physics.pdgfile = os.path.join( os.environ.get("DD4hepINSTALL"), "examples/DDG4/examples/particle.tbl") + +if os.path.exists( + os.path.join(os.environ.get("DD4hepINSTALL"), "examples/DDG4/examples/particle.tbl") +): + SIM.physics.pdgfile = os.path.join( + os.environ.get("DD4hepINSTALL"), "examples/DDG4/examples/particle.tbl" + ) SIM.enableGun = True SIM.gun.particle = "mu-" -SIM.gun.energy = 8*GeV +SIM.gun.energy = 8 * GeV SIM.gun.position = "0, 0, -1000" SIM.gun.direction = "0,0,1" -#SIM.gun.isotrop +# SIM.gun.isotrop SIM.gun.multiplicity = 1 diff --git a/CaloTB/run_sim/ddsim_steering_00.py b/CaloTB/run_sim/ddsim_steering_00.py index 4d02f47d6..0a93d03e2 100644 --- a/CaloTB/run_sim/ddsim_steering_00.py +++ b/CaloTB/run_sim/ddsim_steering_00.py @@ -12,19 +12,19 @@ SIM.compactFile = "../compact/MainTestBeamSetup.xml" SIM.dumpSteeringFile = "dumpSteering00.xml" -SIM.field.eps_min = 1*mm +SIM.field.eps_min = 1 * mm -SIM.part.minimalKineticEnergy = 1*MeV +SIM.part.minimalKineticEnergy = 1 * MeV SIM.physicsList = "QGSP_BERT" - -SIM.enableDetailedShowerMode=True + +SIM.enableDetailedShowerMode = True SIM.enableGun = True -SIM.gun.energy = 10*GeV +SIM.gun.energy = 10 * GeV SIM.gun.particle = "pi+" -#SIM.gun.multiplicity +# SIM.gun.multiplicity SIM.gun.position = "0,0,-1000" -#SIM.gun.isotrop +# SIM.gun.isotrop SIM.gun.direction = "0,0,1" diff --git a/ILD/compact/ILD_common_v02/writeAllILDCompactDescriptions.py b/ILD/compact/ILD_common_v02/writeAllILDCompactDescriptions.py index ed170a418..3df122626 100644 --- a/ILD/compact/ILD_common_v02/writeAllILDCompactDescriptions.py +++ b/ILD/compact/ILD_common_v02/writeAllILDCompactDescriptions.py @@ -1,44 +1,55 @@ -def writeTopCompactXml( outfile, version, name, Large, Option, SolenoidMap, AntiDID, FwdFields ): - +def writeTopCompactXml( + outfile, version, name, Large, Option, SolenoidMap, AntiDID, FwdFields +): # defaults for option 0, 1 # si ecal - ecal_sl1=4 - ecal_sl2=10 + ecal_sl1 = 4 + ecal_sl2 = 10 # ahcal - hcal_sl=3 - if Option==2 or Option==4: # SDHCAL - hcal_sl=1 - elif Option==3 or Option==4: # ScECAL - ecal_sl1=3 - ecal_sl2=11 - elif Option>1: - print( 'ERROR: do not know about Option', Option) + hcal_sl = 3 + if Option == 2 or Option == 4: # SDHCAL + hcal_sl = 1 + elif Option == 3 or Option == 4: # ScECAL + ecal_sl1 = 3 + ecal_sl2 = 11 + elif Option > 1: + print("ERROR: do not know about Option", Option) return - if FwdFields!=250 and FwdFields!=500 and FwdFields!=1000 and FwdFields!=0: - print( 'ERROR: do not know about FwdFields at energy', FwdFields) + if FwdFields != 250 and FwdFields != 500 and FwdFields != 1000 and FwdFields != 0: + print("ERROR: do not know about FwdFields at energy", FwdFields) return outfile.write('\n') - outfile.write(' \n' + ) + outfile.write(' \n') - outfile.write(' ILD simulation models used for detector optimisation \n') - outfile.write(' \n') - outfile.write(' \n') + outfile.write(' version="v' + version + '">\n') + outfile.write( + " ILD simulation models used for detector optimisation \n" + ) + outfile.write(" \n") + outfile.write(" \n") outfile.write(' \n') outfile.write(' \n') - outfile.write(' \n') - outfile.write(' \n') + outfile.write(" \n") + outfile.write(" \n") if Large: - outfile.write(' \n') + outfile.write( + ' \n' + ) else: - outfile.write(' \n') + outfile.write( + ' \n' + ) outfile.write(' \n') outfile.write(' \n') outfile.write(' \n') @@ -50,41 +61,69 @@ def writeTopCompactXml( outfile, version, name, Large, Option, SolenoidMap, Anti outfile.write(' \n') outfile.write(' \n') outfile.write(' \n') - outfile.write(' \n') + outfile.write( + ' \n' + ) outfile.write(' \n') - outfile.write(' \n') - outfile.write(' \n') - outfile.write(' \n') - outfile.write(' \n') - outfile.write(' \n') - outfile.write(' \n') - outfile.write(' \n') + outfile.write(" \n") + outfile.write( + ' \n' + ) + outfile.write( + ' \n' + ) + outfile.write(" \n") + outfile.write( + ' \n' + ) + outfile.write(" \n") + outfile.write(" \n") outfile.write(' \n') - outfile.write(' \n') - outfile.write(' \n') + outfile.write( + ' \n' + ) + outfile.write(" \n") outfile.write(' \n') - outfile.write(' \n') - outfile.write(' \n') + outfile.write( + ' \n' + ) + outfile.write(" \n") outfile.write(' \n') - outfile.write(' \n') - outfile.write(' \n') - outfile.write(' \n') + outfile.write( + ' \n' + ) + outfile.write(" \n") + outfile.write(" \n") outfile.write(' \n') outfile.write(' \n') outfile.write(' \n') outfile.write(' \n') - outfile.write(' \n') + outfile.write( + ' \n' + ) outfile.write(' \n') - outfile.write(' \n') + outfile.write( + ' \n' + ) outfile.write(' \n') outfile.write(' \n') outfile.write(' \n') outfile.write(' \n') - + if Large: - outfile.write(' \n') + outfile.write( + ' \n' + ) else: - outfile.write(' \n') + outfile.write( + ' \n' + ) outfile.write(' \n') outfile.write(' \n') @@ -94,108 +133,130 @@ def writeTopCompactXml( outfile, version, name, Large, Option, SolenoidMap, Anti outfile.write(' \n') outfile.write(' \n') outfile.write(' \n') - outfile.write(' \n') + outfile.write(" \n") outfile.write(' \n') outfile.write(' \n') - outfile.write(' \n') + outfile.write(" \n") if SolenoidMap: if Large: - outfile.write(' \n') + outfile.write( + ' \n' + ) else: - outfile.write(' \n') + outfile.write( + ' \n' + ) else: outfile.write(' \n') if AntiDID: if Large: - outfile.write(' \n') + outfile.write( + ' \n' + ) else: - outfile.write(' \n') + outfile.write( + ' \n' + ) + + if FwdFields > 0: + outfile.write( + ' \n' + ) + + outfile.write("\n") - if FwdFields>0: - outfile.write(' \n') - outfile.write('\n') +# ----------------------------------------------------- -#----------------------------------------------------- def getVersionParameters(version): - vparams={} - if version==2: - vparams['SolenoidMap']=False - vparams['AntiDID']=False - vparams['FwdFields']=0 - elif version==3: - vparams['SolenoidMap']=True - vparams['AntiDID']=False - vparams['FwdFields']=250 - elif version==4: - vparams['SolenoidMap']=True - vparams['AntiDID']=False - vparams['FwdFields']=500 - elif version==5: - vparams['SolenoidMap']=True - vparams['AntiDID']=True - vparams['FwdFields']=250 - elif version==6: - vparams['SolenoidMap']=True - vparams['AntiDID']=True - vparams['FwdFields']=500 - elif version==7: - vparams['SolenoidMap']=True - vparams['AntiDID']=False - vparams['FwdFields']=1000 - elif version==8: - vparams['SolenoidMap']=True - vparams['AntiDID']=True - vparams['FwdFields']=1000 + vparams = {} + if version == 2: + vparams["SolenoidMap"] = False + vparams["AntiDID"] = False + vparams["FwdFields"] = 0 + elif version == 3: + vparams["SolenoidMap"] = True + vparams["AntiDID"] = False + vparams["FwdFields"] = 250 + elif version == 4: + vparams["SolenoidMap"] = True + vparams["AntiDID"] = False + vparams["FwdFields"] = 500 + elif version == 5: + vparams["SolenoidMap"] = True + vparams["AntiDID"] = True + vparams["FwdFields"] = 250 + elif version == 6: + vparams["SolenoidMap"] = True + vparams["AntiDID"] = True + vparams["FwdFields"] = 500 + elif version == 7: + vparams["SolenoidMap"] = True + vparams["AntiDID"] = False + vparams["FwdFields"] = 1000 + elif version == 8: + vparams["SolenoidMap"] = True + vparams["AntiDID"] = True + vparams["FwdFields"] = 1000 else: - print( 'ERROR: unknown version requested:',version,'!!') + print("ERROR: unknown version requested:", version, "!!") return vparams - if version<10: - vparams['vString']='0'+str(version) + if version < 10: + vparams["vString"] = "0" + str(version) else: - vparams['vString']=str(version) + vparams["vString"] = str(version) return vparams -#----------------------------------------------------- +# ----------------------------------------------------- import os -prename='ILD' # for the real thing +prename = "ILD" # for the real thing # prename='test' # for testing -topdir='../' -mainoutdirname=prename+'_sl5_v02' -mainoutdir=topdir+mainoutdirname +topdir = "../" +mainoutdirname = prename + "_sl5_v02" +mainoutdir = topdir + mainoutdirname if not os.path.exists(mainoutdir): os.makedirs(mainoutdir) for version in range(2, 9): - vparams=getVersionParameters(version) + vparams = getVersionParameters(version) for Large in (True, False): - for Option in range(0,5): - - modelname=prename+'_' + for Option in range(0, 5): + modelname = prename + "_" if Large: - modelname=modelname+'l' + modelname = modelname + "l" else: - modelname=modelname+'s' - modelname=modelname+'5_' + modelname = modelname + "s" + modelname = modelname + "5_" + + if Option > 0: + modelname = modelname + "o" + str(Option) + "_" - if Option>0: - modelname=modelname+'o'+str(Option)+'_' + modelname = modelname + "v" + vparams["vString"] - modelname=modelname+'v'+vparams['vString'] - - outfile=open(mainoutdir+'/'+modelname+'.xml','w') - writeTopCompactXml( outfile, version=vparams['vString'], name=modelname, Large=Large, Option=Option, SolenoidMap=vparams['SolenoidMap'], AntiDID=vparams['AntiDID'], FwdFields=vparams['FwdFields'] ) + outfile = open(mainoutdir + "/" + modelname + ".xml", "w") + writeTopCompactXml( + outfile, + version=vparams["vString"], + name=modelname, + Large=Large, + Option=Option, + SolenoidMap=vparams["SolenoidMap"], + AntiDID=vparams["AntiDID"], + FwdFields=vparams["FwdFields"], + ) outfile.close() - - if not os.path.exists( topdir+modelname ): - os.symlink( mainoutdirname, topdir+modelname ) + + if not os.path.exists(topdir + modelname): + os.symlink(mainoutdirname, topdir + modelname) diff --git a/ILD/doc/latex/ILD_envelopeDict.py b/ILD/doc/latex/ILD_envelopeDict.py index 3bbefa5fc..38ee735c9 100644 --- a/ILD/doc/latex/ILD_envelopeDict.py +++ b/ILD/doc/latex/ILD_envelopeDict.py @@ -1,7 +1,8 @@ -""" - python dictionary with parameters extracted from: /data/ilcsoft/HEAD/lcgeo/HEAD/ILD/compact/ILD_o1_v05/ILD_o1_v05.xml -""" -values={} +""" +python dictionary with parameters extracted from: /data/ilcsoft/HEAD/lcgeo/HEAD/ILD/compact/ILD_o1_v05/ILD_o1_v05.xml +""" + +values = {} values["VXD_inner_radius"] = 16.0 values["VXD_outer_radius"] = 60.0 values["VXD_half_length"] = 177.6 diff --git a/ILD/doc/latex/documentEnvelopes.py b/ILD/doc/latex/documentEnvelopes.py index 1774787c9..e86a2a041 100644 --- a/ILD/doc/latex/documentEnvelopes.py +++ b/ILD/doc/latex/documentEnvelopes.py @@ -1,517 +1,692 @@ """ - Create Latex documents with drawings and tables - documenting envelope parameters +Create Latex documents with drawings and tables +documenting envelope parameters - @author F.Gaede, CERN/DESY - @version 1.0 +@author F.Gaede, CERN/DESY +@version 1.0 """ + import sys import copy import cStringIO - # --- define the envelope parameters for every subdetector ----- -envDict={} -envDict['VXD'] = [ 'VXD_inner_radius', 'VXD_outer_radius', - 'VXD_half_length', 'VXD_cone_min_z', 'VXD_cone_max_z', 'VXD_inner_radius_1' ] - -envDict['SIT'] = [ 'SIT_inner_radius', 'SIT_outer_radius', - 'SIT_half_length', 'SIT_outer_radius_1', 'SIT_half_length_1' ] - -envDict['TPC'] = [ 'TPC_inner_radius', 'TPC_outer_radius', 'TPC_half_length' ] - -envDict['FTD'] = [ 'FTD_inner_radius', 'FTD_outer_radius', 'FTD_half_length', - 'FTD_outer_radius_1', 'FTD_outer_radius_2', - 'FTD_min_z_0', 'FTD_min_z_1', 'FTD_min_z_2', 'FTD_cone_min_z', 'FTD_cone_radius' ] - -envDict['SET'] = [ 'SET_inner_radius', 'SET_outer_radius', 'SET_half_length' ] - - -envDict['Ecal'] = [ 'Ecal_Hcal_symmetry', 'Ecal_inner_radius', 'Ecal_outer_radius', 'Ecal_half_length', 'Ecal_symmetry' ] - -envDict['EcalEndcap'] = [ 'EcalEndcap_inner_radius', 'EcalEndcap_outer_radius', 'EcalEndcap_min_z', 'EcalEndcap_max_z' ] - -envDict['EcalEndcapRing'] = [ 'EcalEndcapRing_inner_radius', 'EcalEndcapRing_outer_radius', 'EcalEndcapRing_min_z', 'EcalEndcapRing_max_z' ] - -envDict['Hcal'] = [ 'Hcal_inner_radius', 'Hcal_outer_radius', 'Hcal_half_length', 'Hcal_inner_symmetry' ] - -envDict['HcalEndcap'] = [ 'EcalEndcap_symmetry', 'HcalEndcap_inner_radius', 'HcalEndcap_outer_radius', 'HcalEndcap_min_z', 'HcalEndcap_max_z' ] - -envDict['HcalEndcapRing'] = [ 'HcalEndcapRing_inner_radius', 'HcalEndcapRing_outer_radius', 'HcalEndcapRing_min_z', 'HcalEndcapRing_max_z', 'HcalEndcapRing_symmetry' ] - -envDict['Coil'] = [ 'Coil_inner_radius', 'Coil_outer_radius', 'Coil_half_length'] - -envDict['Yoke'] = [ 'Yoke_inner_radius', 'Yoke_outer_radius', 'Yoke_half_length', 'Yoke_symmetry' ] - -envDict['YokeEndcap'] = [ 'YokeEndcap_inner_radius', 'YokeEndcap_outer_radius', 'YokeEndcap_min_z', 'YokeEndcap_max_z', 'YokeEndcap_symmetry' ] - -envDict['YokeEndcapPlug'] = [ 'YokeEndcapPlug_inner_radius', 'YokeEndcapPlug_outer_radius', 'YokeEndcapPlug_min_z', 'YokeEndcapPlug_max_z', 'YokeEndcapPlug_symmetry' ] - -envDict['BeamCal'] = [ 'BeamCal_inner_radius', 'BeamCal_outer_radius', 'BeamCal_min_z', 'BeamCal_max_z', 'BeamCal_thickness', 'BeamCal_tubeIncoming_radius' ] - -envDict['LumiCal'] = [ 'LumiCal_inner_radius', 'LumiCal_outer_radius', 'LumiCal_min_z', 'LumiCal_max_z', 'LumiCal_thickness' ] - -envDict['LHCal'] = [ 'LHCal_inner_radius', 'LHCal_outer_radius', 'LHCal_min_z', 'LHCal_max_z', 'LHCal_thickness' ] - - -#----- define the envelope shape points in rz ------------ +envDict = {} +envDict["VXD"] = [ + "VXD_inner_radius", + "VXD_outer_radius", + "VXD_half_length", + "VXD_cone_min_z", + "VXD_cone_max_z", + "VXD_inner_radius_1", +] + +envDict["SIT"] = [ + "SIT_inner_radius", + "SIT_outer_radius", + "SIT_half_length", + "SIT_outer_radius_1", + "SIT_half_length_1", +] + +envDict["TPC"] = ["TPC_inner_radius", "TPC_outer_radius", "TPC_half_length"] + +envDict["FTD"] = [ + "FTD_inner_radius", + "FTD_outer_radius", + "FTD_half_length", + "FTD_outer_radius_1", + "FTD_outer_radius_2", + "FTD_min_z_0", + "FTD_min_z_1", + "FTD_min_z_2", + "FTD_cone_min_z", + "FTD_cone_radius", +] + +envDict["SET"] = ["SET_inner_radius", "SET_outer_radius", "SET_half_length"] + + +envDict["Ecal"] = [ + "Ecal_Hcal_symmetry", + "Ecal_inner_radius", + "Ecal_outer_radius", + "Ecal_half_length", + "Ecal_symmetry", +] + +envDict["EcalEndcap"] = [ + "EcalEndcap_inner_radius", + "EcalEndcap_outer_radius", + "EcalEndcap_min_z", + "EcalEndcap_max_z", +] + +envDict["EcalEndcapRing"] = [ + "EcalEndcapRing_inner_radius", + "EcalEndcapRing_outer_radius", + "EcalEndcapRing_min_z", + "EcalEndcapRing_max_z", +] + +envDict["Hcal"] = [ + "Hcal_inner_radius", + "Hcal_outer_radius", + "Hcal_half_length", + "Hcal_inner_symmetry", +] + +envDict["HcalEndcap"] = [ + "EcalEndcap_symmetry", + "HcalEndcap_inner_radius", + "HcalEndcap_outer_radius", + "HcalEndcap_min_z", + "HcalEndcap_max_z", +] + +envDict["HcalEndcapRing"] = [ + "HcalEndcapRing_inner_radius", + "HcalEndcapRing_outer_radius", + "HcalEndcapRing_min_z", + "HcalEndcapRing_max_z", + "HcalEndcapRing_symmetry", +] + +envDict["Coil"] = ["Coil_inner_radius", "Coil_outer_radius", "Coil_half_length"] + +envDict["Yoke"] = [ + "Yoke_inner_radius", + "Yoke_outer_radius", + "Yoke_half_length", + "Yoke_symmetry", +] + +envDict["YokeEndcap"] = [ + "YokeEndcap_inner_radius", + "YokeEndcap_outer_radius", + "YokeEndcap_min_z", + "YokeEndcap_max_z", + "YokeEndcap_symmetry", +] + +envDict["YokeEndcapPlug"] = [ + "YokeEndcapPlug_inner_radius", + "YokeEndcapPlug_outer_radius", + "YokeEndcapPlug_min_z", + "YokeEndcapPlug_max_z", + "YokeEndcapPlug_symmetry", +] + +envDict["BeamCal"] = [ + "BeamCal_inner_radius", + "BeamCal_outer_radius", + "BeamCal_min_z", + "BeamCal_max_z", + "BeamCal_thickness", + "BeamCal_tubeIncoming_radius", +] + +envDict["LumiCal"] = [ + "LumiCal_inner_radius", + "LumiCal_outer_radius", + "LumiCal_min_z", + "LumiCal_max_z", + "LumiCal_thickness", +] + +envDict["LHCal"] = [ + "LHCal_inner_radius", + "LHCal_outer_radius", + "LHCal_min_z", + "LHCal_max_z", + "LHCal_thickness", +] + + +# ----- define the envelope shape points in rz ------------ envRZDict = {} -envRZDict['VXD'] = [ ( '0' , 'VXD_inner_radius' ) , - ( '0' , 'VXD_outer_radius' ) , - ( 'VXD_half_length', 'VXD_outer_radius' ) , - ( 'VXD_half_length', 'VXD_inner_radius_1') , - ( 'VXD_cone_max_z' , 'VXD_inner_radius_1') , - ( 'VXD_cone_min_z' , 'VXD_inner_radius' ) , - ( '0' , 'VXD_inner_radius' ) ] - -envRZDict['SIT'] = [ ( '0' , 'SIT_inner_radius' ) , - ( '0' , 'SIT_outer_radius' ) , - ( 'SIT_half_length' , 'SIT_outer_radius' ) , - ( 'SIT_half_length' , 'SIT_outer_radius_1' ) , - ( 'SIT_half_length_1', 'SIT_outer_radius_1' ) , - ( 'SIT_half_length_1', 'SIT_inner_radius' ) , - ( '0' , 'SIT_inner_radius' ) ] - -envRZDict['FTD'] = [ ( 'FTD_min_z_0' , 'FTD_inner_radius' ) , - ( 'FTD_min_z_0' , 'FTD_outer_radius_1' ) , - ( 'FTD_min_z_1' , 'FTD_outer_radius_1' ) , - ( 'FTD_min_z_1' , 'FTD_outer_radius_2' ) , - ( 'FTD_min_z_2' , 'FTD_outer_radius_2' ) , - ( 'FTD_min_z_2' , 'FTD_outer_radius' ) , - ( 'FTD_half_length', 'FTD_outer_radius' ) , - ( 'FTD_half_length', 'FTD_cone_radius' ) , - ( 'FTD_cone_min_z', 'FTD_inner_radius' ) , - ( 'FTD_min_z_0' , 'FTD_inner_radius' ) ] - -envRZDict['SET'] = [ ( '0' , 'SET_inner_radius' ) , - ( '0' , 'SET_outer_radius' ) , - ( 'SET_half_length', 'SET_outer_radius' ) , - ( 'SET_half_length', 'SET_inner_radius' ) , - ( '0' , 'SET_inner_radius' ) ] - -envRZDict['TPC'] = [ ( '0' , 'TPC_inner_radius' ) , - ( '0' , 'TPC_outer_radius' ) , - ( 'TPC_half_length', 'TPC_outer_radius' ) , - ( 'TPC_half_length', 'TPC_inner_radius' ) , - ( '0' , 'TPC_inner_radius' ) ] - -envRZDict['Ecal'] = [ ( '0' , 'Ecal_inner_radius' ) , - ( '0' , 'Ecal_outer_radius' ) , - ( 'Ecal_half_length', 'Ecal_outer_radius' ) , - ( 'Ecal_half_length', 'Ecal_inner_radius' ) , - ( '0' , 'Ecal_inner_radius' ) ] - -envRZDict['EcalEndcap'] = [ ( 'EcalEndcap_min_z' , 'EcalEndcap_inner_radius' ) , - ( 'EcalEndcap_min_z' , 'EcalEndcap_outer_radius' ) , - ( 'EcalEndcap_max_z' , 'EcalEndcap_outer_radius' ) , - ( 'EcalEndcap_max_z' , 'EcalEndcap_inner_radius' ) , - ( 'EcalEndcap_min_z' , 'EcalEndcap_inner_radius' ) ] - -envRZDict['EcalEndcapRing'] = [ ( 'EcalEndcapRing_min_z' , 'EcalEndcapRing_inner_radius' ) , - ( 'EcalEndcapRing_min_z' , 'EcalEndcapRing_outer_radius' ) , - ( 'EcalEndcapRing_max_z' , 'EcalEndcapRing_outer_radius' ) , - ( 'EcalEndcapRing_max_z' , 'EcalEndcapRing_inner_radius' ) , - ( 'EcalEndcapRing_min_z' , 'EcalEndcapRing_inner_radius' ) ] - -envRZDict['Hcal'] = [ ( '0' , 'Hcal_inner_radius' ) , - ( '0' , 'Hcal_outer_radius' ) , - ( 'Hcal_half_length', 'Hcal_outer_radius' ) , - ( 'Hcal_half_length', 'Hcal_inner_radius' ) , - ( '0' , 'Hcal_inner_radius' ) ] - - -envRZDict['HcalEndcap'] = [ ( 'HcalEndcap_min_z' , 'HcalEndcap_inner_radius' ) , - ( 'HcalEndcap_min_z' , 'HcalEndcap_outer_radius' ) , - ( 'HcalEndcap_max_z' , 'HcalEndcap_outer_radius' ) , - ( 'HcalEndcap_max_z' , 'HcalEndcap_inner_radius' ) , - ( 'HcalEndcap_min_z' , 'HcalEndcap_inner_radius' ) ] - -envRZDict['HcalEndcapRing'] = [ ( 'HcalEndcapRing_min_z' , 'HcalEndcapRing_inner_radius' ) , - ( 'HcalEndcapRing_min_z' , 'HcalEndcapRing_outer_radius' ) , - ( 'HcalEndcapRing_max_z' , 'HcalEndcapRing_outer_radius' ) , - ( 'HcalEndcapRing_max_z' , 'HcalEndcapRing_inner_radius' ) , - ( 'HcalEndcapRing_min_z' , 'HcalEndcapRing_inner_radius' ) ] - - -envRZDict['Yoke'] = [ ( '0' , 'Yoke_inner_radius' ) , - ( '0' , 'Yoke_outer_radius' ) , - ( 'Yoke_half_length', 'Yoke_outer_radius' ) , - ( 'Yoke_half_length', 'Yoke_inner_radius' ) , - ( '0' , 'Yoke_inner_radius' ) ] - - -envRZDict['YokeEndcap'] = [ ( 'YokeEndcap_min_z' , 'YokeEndcap_inner_radius' ) , - ( 'YokeEndcap_min_z' , 'YokeEndcap_outer_radius' ) , - ( 'YokeEndcap_max_z' , 'YokeEndcap_outer_radius' ) , - ( 'YokeEndcap_max_z' , 'YokeEndcap_inner_radius' ) , - ( 'YokeEndcap_min_z' , 'YokeEndcap_inner_radius' ) ] - -envRZDict['YokeEndcapPlug'] = [ ( 'YokeEndcapPlug_min_z' , 'YokeEndcapPlug_inner_radius' ) , - ( 'YokeEndcapPlug_min_z' , 'YokeEndcapPlug_outer_radius' ) , - ( 'YokeEndcapPlug_max_z' , 'YokeEndcapPlug_outer_radius' ) , - ( 'YokeEndcapPlug_max_z' , 'YokeEndcapPlug_inner_radius' ) , - ( 'YokeEndcapPlug_min_z' , 'YokeEndcapPlug_inner_radius' ) ] - -envRZDict['Coil'] = [ ( '0' , 'Coil_inner_radius' ) , - ( '0' , 'Coil_outer_radius' ) , - ( 'Coil_half_length', 'Coil_outer_radius' ) , - ( 'Coil_half_length', 'Coil_inner_radius' ) , - ( '0' , 'Coil_inner_radius' ) ] - - -envRZDict['BeamCal'] = [ ( 'BeamCal_min_z' , 'BeamCal_inner_radius' ) , - ( 'BeamCal_min_z' , 'BeamCal_outer_radius' ) , - ( 'BeamCal_max_z' , 'BeamCal_outer_radius' ) , - ( 'BeamCal_max_z' , 'BeamCal_inner_radius' ) , - ( 'BeamCal_min_z' , 'BeamCal_inner_radius' ) ] - -envRZDict['LumiCal'] = [ ( 'LumiCal_min_z' , 'LumiCal_inner_radius' ) , - ( 'LumiCal_min_z' , 'LumiCal_outer_radius' ) , - ( 'LumiCal_max_z' , 'LumiCal_outer_radius' ) , - ( 'LumiCal_max_z' , 'LumiCal_inner_radius' ) , - ( 'LumiCal_min_z' , 'LumiCal_inner_radius' ) ] - -envRZDict['LHCal'] = [ ( 'LHCal_min_z' , 'LHCal_inner_radius' ) , - ( 'LHCal_min_z' , 'LHCal_outer_radius' ) , - ( 'LHCal_max_z' , 'LHCal_outer_radius' ) , - ( 'LHCal_max_z' , 'LHCal_inner_radius' ) , - ( 'LHCal_min_z' , 'LHCal_inner_radius' ) ] - - - -#----------------------------------------------- +envRZDict["VXD"] = [ + ("0", "VXD_inner_radius"), + ("0", "VXD_outer_radius"), + ("VXD_half_length", "VXD_outer_radius"), + ("VXD_half_length", "VXD_inner_radius_1"), + ("VXD_cone_max_z", "VXD_inner_radius_1"), + ("VXD_cone_min_z", "VXD_inner_radius"), + ("0", "VXD_inner_radius"), +] + +envRZDict["SIT"] = [ + ("0", "SIT_inner_radius"), + ("0", "SIT_outer_radius"), + ("SIT_half_length", "SIT_outer_radius"), + ("SIT_half_length", "SIT_outer_radius_1"), + ("SIT_half_length_1", "SIT_outer_radius_1"), + ("SIT_half_length_1", "SIT_inner_radius"), + ("0", "SIT_inner_radius"), +] + +envRZDict["FTD"] = [ + ("FTD_min_z_0", "FTD_inner_radius"), + ("FTD_min_z_0", "FTD_outer_radius_1"), + ("FTD_min_z_1", "FTD_outer_radius_1"), + ("FTD_min_z_1", "FTD_outer_radius_2"), + ("FTD_min_z_2", "FTD_outer_radius_2"), + ("FTD_min_z_2", "FTD_outer_radius"), + ("FTD_half_length", "FTD_outer_radius"), + ("FTD_half_length", "FTD_cone_radius"), + ("FTD_cone_min_z", "FTD_inner_radius"), + ("FTD_min_z_0", "FTD_inner_radius"), +] + +envRZDict["SET"] = [ + ("0", "SET_inner_radius"), + ("0", "SET_outer_radius"), + ("SET_half_length", "SET_outer_radius"), + ("SET_half_length", "SET_inner_radius"), + ("0", "SET_inner_radius"), +] + +envRZDict["TPC"] = [ + ("0", "TPC_inner_radius"), + ("0", "TPC_outer_radius"), + ("TPC_half_length", "TPC_outer_radius"), + ("TPC_half_length", "TPC_inner_radius"), + ("0", "TPC_inner_radius"), +] + +envRZDict["Ecal"] = [ + ("0", "Ecal_inner_radius"), + ("0", "Ecal_outer_radius"), + ("Ecal_half_length", "Ecal_outer_radius"), + ("Ecal_half_length", "Ecal_inner_radius"), + ("0", "Ecal_inner_radius"), +] + +envRZDict["EcalEndcap"] = [ + ("EcalEndcap_min_z", "EcalEndcap_inner_radius"), + ("EcalEndcap_min_z", "EcalEndcap_outer_radius"), + ("EcalEndcap_max_z", "EcalEndcap_outer_radius"), + ("EcalEndcap_max_z", "EcalEndcap_inner_radius"), + ("EcalEndcap_min_z", "EcalEndcap_inner_radius"), +] + +envRZDict["EcalEndcapRing"] = [ + ("EcalEndcapRing_min_z", "EcalEndcapRing_inner_radius"), + ("EcalEndcapRing_min_z", "EcalEndcapRing_outer_radius"), + ("EcalEndcapRing_max_z", "EcalEndcapRing_outer_radius"), + ("EcalEndcapRing_max_z", "EcalEndcapRing_inner_radius"), + ("EcalEndcapRing_min_z", "EcalEndcapRing_inner_radius"), +] + +envRZDict["Hcal"] = [ + ("0", "Hcal_inner_radius"), + ("0", "Hcal_outer_radius"), + ("Hcal_half_length", "Hcal_outer_radius"), + ("Hcal_half_length", "Hcal_inner_radius"), + ("0", "Hcal_inner_radius"), +] + + +envRZDict["HcalEndcap"] = [ + ("HcalEndcap_min_z", "HcalEndcap_inner_radius"), + ("HcalEndcap_min_z", "HcalEndcap_outer_radius"), + ("HcalEndcap_max_z", "HcalEndcap_outer_radius"), + ("HcalEndcap_max_z", "HcalEndcap_inner_radius"), + ("HcalEndcap_min_z", "HcalEndcap_inner_radius"), +] + +envRZDict["HcalEndcapRing"] = [ + ("HcalEndcapRing_min_z", "HcalEndcapRing_inner_radius"), + ("HcalEndcapRing_min_z", "HcalEndcapRing_outer_radius"), + ("HcalEndcapRing_max_z", "HcalEndcapRing_outer_radius"), + ("HcalEndcapRing_max_z", "HcalEndcapRing_inner_radius"), + ("HcalEndcapRing_min_z", "HcalEndcapRing_inner_radius"), +] + + +envRZDict["Yoke"] = [ + ("0", "Yoke_inner_radius"), + ("0", "Yoke_outer_radius"), + ("Yoke_half_length", "Yoke_outer_radius"), + ("Yoke_half_length", "Yoke_inner_radius"), + ("0", "Yoke_inner_radius"), +] + + +envRZDict["YokeEndcap"] = [ + ("YokeEndcap_min_z", "YokeEndcap_inner_radius"), + ("YokeEndcap_min_z", "YokeEndcap_outer_radius"), + ("YokeEndcap_max_z", "YokeEndcap_outer_radius"), + ("YokeEndcap_max_z", "YokeEndcap_inner_radius"), + ("YokeEndcap_min_z", "YokeEndcap_inner_radius"), +] + +envRZDict["YokeEndcapPlug"] = [ + ("YokeEndcapPlug_min_z", "YokeEndcapPlug_inner_radius"), + ("YokeEndcapPlug_min_z", "YokeEndcapPlug_outer_radius"), + ("YokeEndcapPlug_max_z", "YokeEndcapPlug_outer_radius"), + ("YokeEndcapPlug_max_z", "YokeEndcapPlug_inner_radius"), + ("YokeEndcapPlug_min_z", "YokeEndcapPlug_inner_radius"), +] + +envRZDict["Coil"] = [ + ("0", "Coil_inner_radius"), + ("0", "Coil_outer_radius"), + ("Coil_half_length", "Coil_outer_radius"), + ("Coil_half_length", "Coil_inner_radius"), + ("0", "Coil_inner_radius"), +] + + +envRZDict["BeamCal"] = [ + ("BeamCal_min_z", "BeamCal_inner_radius"), + ("BeamCal_min_z", "BeamCal_outer_radius"), + ("BeamCal_max_z", "BeamCal_outer_radius"), + ("BeamCal_max_z", "BeamCal_inner_radius"), + ("BeamCal_min_z", "BeamCal_inner_radius"), +] + +envRZDict["LumiCal"] = [ + ("LumiCal_min_z", "LumiCal_inner_radius"), + ("LumiCal_min_z", "LumiCal_outer_radius"), + ("LumiCal_max_z", "LumiCal_outer_radius"), + ("LumiCal_max_z", "LumiCal_inner_radius"), + ("LumiCal_min_z", "LumiCal_inner_radius"), +] + +envRZDict["LHCal"] = [ + ("LHCal_min_z", "LHCal_inner_radius"), + ("LHCal_min_z", "LHCal_outer_radius"), + ("LHCal_max_z", "LHCal_outer_radius"), + ("LHCal_max_z", "LHCal_inner_radius"), + ("LHCal_min_z", "LHCal_inner_radius"), +] + + +# ----------------------------------------------- try: - dictFile = sys.argv[1] + dictFile = sys.argv[1] except IndexError: - print( " usage: python documentEnvelopes.py pyDict.py ") - print( " pyDict.py : python file with a data dictionary (created with extractParameters)") - print() - sys.exit(1) + print(" usage: python documentEnvelopes.py pyDict.py ") + print( + " pyDict.py : python file with a data dictionary (created with extractParameters)" + ) + print() + sys.exit(1) + +# ------ read dictionary 'values' from file +execfile(dictFile) +values["0"] = 0 -#------ read dictionary 'values' from file -execfile( dictFile ) -values['0'] = 0 -#----------------------------------------------- +# ----------------------------------------------- def run(): + writeTexFile("VXD", "_rz_envelope", getRZEnvCmds, 20) + writeTexFile("SIT", "_rz_envelope", getRZEnvCmds, 20) + writeTexFile("FTD", "_rz_envelope", getRZEnvCmds, 20) + writeTexFile("TPC", "_rz_envelope", getRZEnvCmds, 20) + writeTexFile("SET", "_rz_envelope", getRZEnvCmds, 20) - writeTexFile( 'VXD', '_rz_envelope' , getRZEnvCmds, 20 ) - writeTexFile( 'SIT', '_rz_envelope' , getRZEnvCmds, 20 ) - writeTexFile( 'FTD', '_rz_envelope' , getRZEnvCmds, 20 ) - writeTexFile( 'TPC', '_rz_envelope' , getRZEnvCmds, 20 ) - writeTexFile( 'SET', '_rz_envelope' , getRZEnvCmds, 20 ) + writeTexFile("ILD", "_rz_quadrant", getILDRZQuadrantCmds, 20) - writeTexFile( 'ILD', '_rz_quadrant' , getILDRZQuadrantCmds, 20 ) + writeILDEnvTable("ILD_enevelope_table.tex") - writeILDEnvTable('ILD_enevelope_table.tex' ) -#----------------------------------------------- -def writeILDEnvTable( file ): - fn = './ILD_envelopeTable.tex' - of = open( fn , 'w' ) +# ----------------------------------------------- +def writeILDEnvTable(file): + fn = "./ILD_envelopeTable.tex" + of = open(fn, "w") cmds = [] - cmds.extend( getDocHeaderCmds( 'article', ['multirow'] )) - - dets = ['VXD','FTD','SIT','TPC','SET', 'Ecal', 'EcalEndcap', 'EcalEndcapRing', - 'Hcal', 'HcalEndcap', 'HcalEndcapRing', 'Coil', 'Yoke', 'YokeEndcap', 'YokeEndcapPlug', 'BeamCal', 'LHCal', 'LumiCal' ] - - - cmds.extend( getEnvelopeTableCmds( dets , '\\large{Envelope parameters for ILD\_o1\_v05}' ) ) - - cmds.extend( getDocFooterCmds() ) + cmds.extend(getDocHeaderCmds("article", ["multirow"])) + + dets = [ + "VXD", + "FTD", + "SIT", + "TPC", + "SET", + "Ecal", + "EcalEndcap", + "EcalEndcapRing", + "Hcal", + "HcalEndcap", + "HcalEndcapRing", + "Coil", + "Yoke", + "YokeEndcap", + "YokeEndcapPlug", + "BeamCal", + "LHCal", + "LumiCal", + ] + + cmds.extend( + getEnvelopeTableCmds(dets, "\\large{Envelope parameters for ILD\_o1\_v05}") + ) + + cmds.extend(getDocFooterCmds()) for cmd in cmds: - print(cmd , file=of) + print(cmd, file=of) of.close() -#----------------------------------------------- -def getEnvelopeTableCmds( dets , title ): - cmds = [] - cmds.append( '\\begin{tabular}{|l | c | c | c | l r |}' ) - cmds.append( '\\hline' ) - if( len( title )): - cmds.append( '\\multicolumn{6}{|c|}{} \\\\' ) - cmds.append( '\\multicolumn{6}{|c|}{' + title + '} \\\\' ) - cmds.append( '\\multicolumn{6}{|c|}{} \\\\' ) - cmds.append( '\\hline' ) - cmds.append( ' detector & inner radius & outer radius & half length & \multicolumn{2}{c|}{additional parameters} \\\\' ) - cmds.append( ' & & & min z, max z & & \\\\' ) - cmds.append( '\\hline' ) +# ----------------------------------------------- +def getEnvelopeTableCmds(dets, title): + cmds = [] + cmds.append("\\begin{tabular}{|l | c | c | c | l r |}") + cmds.append("\\hline") + + if len(title): + cmds.append("\\multicolumn{6}{|c|}{} \\\\") + cmds.append("\\multicolumn{6}{|c|}{" + title + "} \\\\") + cmds.append("\\multicolumn{6}{|c|}{} \\\\") + cmds.append("\\hline") + + cmds.append( + " detector & inner radius & outer radius & half length & \multicolumn{2}{c|}{additional parameters} \\\\" + ) + cmds.append( + " & & & min z, max z & & \\\\" + ) + cmds.append("\\hline") for d in dets: - cmds.extend( getTableLinesCmds( d ) ) + cmds.extend(getTableLinesCmds(d)) - cmds.append( '\\end{tabular}' ) + cmds.append("\\end{tabular}") return cmds -#----------------------------------------------- + +# ----------------------------------------------- def getTableLinesCmds(det): - cmds=[] - params = copy.deepcopy( envDict[ det ] ) + cmds = [] + params = copy.deepcopy(envDict[det]) - ri = det+'_inner_radius' - ro = det+'_outer_radius' - hl = det+'_half_length' - zs = det+'_min_z' - ze = det+'_max_z' + ri = det + "_inner_radius" + ro = det + "_outer_radius" + hl = det + "_half_length" + zs = det + "_min_z" + ze = det + "_max_z" - line = det + ' & ' + line = det + " & " - if( ri in params): - line += ( ("%.1f"%values[ ri ] ) + ' & ' ) - params.remove( ri ) + if ri in params: + line += ("%.1f" % values[ri]) + " & " + params.remove(ri) else: - line += ' - & ' + line += " - & " - if( ro in params): - line += ( ("%.1f"% values[ ro ] ) + ' & ' ) - params.remove( ro ) + if ro in params: + line += ("%.1f" % values[ro]) + " & " + params.remove(ro) else: - line += ' - & ' + line += " - & " - if( hl in params): - line += ( ("%.1f"% values[ hl ] ) + ' & ' ) - params.remove( hl ) + if hl in params: + line += ("%.1f" % values[hl]) + " & " + params.remove(hl) else: - line += ( ("%.1f"% values[ zs ] ) + ', ' + ("%.1f"% values[ ze ] ) + ' & ' ) - params.remove( zs ) - params.remove( ze ) - - #--- first extra parameter - if any - if len( params)>0: + line += ("%.1f" % values[zs]) + ", " + ("%.1f" % values[ze]) + " & " + params.remove(zs) + params.remove(ze) + + # --- first extra parameter - if any + if len(params) > 0: p = params[0] - line += '\\small{\\verb#'+ p + '#} & ' + ("%.1f"% values[ p ] ) - params.remove( p ) + line += "\\small{\\verb#" + p + "#} & " + ("%.1f" % values[p]) + params.remove(p) else: - line += ' & ' + line += " & " - line += ' \\\\ ' - cmds.append( line ) + line += " \\\\ " + cmds.append(line) - #--- other extra parameters - if any - need extra line + # --- other extra parameters - if any - need extra line - while( len( params)>0 ): - line = ' & & & & ' + while len(params) > 0: + line = " & & & & " p = params[0] - line += '\\small{\\verb#'+ p + '#} & ' + ("%.1f"% values[ p ] ) - params.remove( p ) - line += ' \\\\ ' - cmds.append( line ) - - cmds.append( '\\hline' ) + line += "\\small{\\verb#" + p + "#} & " + ("%.1f" % values[p]) + params.remove(p) + line += " \\\\ " + cmds.append(line) + + cmds.append("\\hline") return cmds -#----------------------------------------------- + + +# ----------------------------------------------- def getILDRZQuadrantCmds(det, width): - cmds = [] - cmds.extend( getColorCmds() ) + cmds.extend(getColorCmds()) + + cmds.append("\\begin{tikzpicture}") - cmds.append( '\\begin{tikzpicture}' ) - scale = 0.01 - #--------------------------------------------------- - - - cmds.append( lineOStr('[fill=VXDcol]', getEnvPoints('VXD',scale) ) ) - cmds.append( lineOStr('[fill=SITcol]', getEnvPoints('SIT',scale) ) ) - cmds.append( lineOStr('[fill=FTDcol]', getEnvPoints('FTD',scale) ) ) - cmds.append( lineOStr('[fill=TPCcol]', getEnvPoints('TPC',scale) ) ) - cmds.append( lineOStr('[fill=ECALcol]', getEnvPoints('Ecal',scale) ) ) - cmds.append( lineOStr('[fill=ECALcol]', getEnvPoints('EcalEndcap',scale) ) ) - cmds.append( lineOStr('[fill=ECALcol]', getEnvPoints('EcalEndcapRing',scale) ) ) - cmds.append( lineOStr('[fill=HCALcol]', getEnvPoints('Hcal',scale) ) ) - cmds.append( lineOStr('[fill=HCALcol]', getEnvPoints('HcalEndcap',scale) ) ) - cmds.append( lineOStr('[fill=HCALcol]', getEnvPoints('HcalEndcapRing',scale) ) ) - cmds.append( lineOStr('[fill=YOKEcol]', getEnvPoints('Yoke',scale) ) ) - cmds.append( lineOStr('[fill=YOKEcol]', getEnvPoints('YokeEndcap',scale) ) ) - cmds.append( lineOStr('[fill=YOKEcol]', getEnvPoints('YokeEndcapPlug',scale) ) ) - cmds.append( lineOStr('[fill=COILcol]', getEnvPoints('Coil',scale) ) ) - cmds.append( lineOStr('[fill=SITcol]', getEnvPoints('BeamCal',scale) ) ) - cmds.append( lineOStr('[fill=SITcol]', getEnvPoints('LumiCal',scale) ) ) - cmds.append( lineOStr('[fill=SITcol]', getEnvPoints('LHCal',scale) ) ) - - - cmds.append( '\\end{tikzpicture}' ) + # --------------------------------------------------- + + cmds.append(lineOStr("[fill=VXDcol]", getEnvPoints("VXD", scale))) + cmds.append(lineOStr("[fill=SITcol]", getEnvPoints("SIT", scale))) + cmds.append(lineOStr("[fill=FTDcol]", getEnvPoints("FTD", scale))) + cmds.append(lineOStr("[fill=TPCcol]", getEnvPoints("TPC", scale))) + cmds.append(lineOStr("[fill=ECALcol]", getEnvPoints("Ecal", scale))) + cmds.append(lineOStr("[fill=ECALcol]", getEnvPoints("EcalEndcap", scale))) + cmds.append(lineOStr("[fill=ECALcol]", getEnvPoints("EcalEndcapRing", scale))) + cmds.append(lineOStr("[fill=HCALcol]", getEnvPoints("Hcal", scale))) + cmds.append(lineOStr("[fill=HCALcol]", getEnvPoints("HcalEndcap", scale))) + cmds.append(lineOStr("[fill=HCALcol]", getEnvPoints("HcalEndcapRing", scale))) + cmds.append(lineOStr("[fill=YOKEcol]", getEnvPoints("Yoke", scale))) + cmds.append(lineOStr("[fill=YOKEcol]", getEnvPoints("YokeEndcap", scale))) + cmds.append(lineOStr("[fill=YOKEcol]", getEnvPoints("YokeEndcapPlug", scale))) + cmds.append(lineOStr("[fill=COILcol]", getEnvPoints("Coil", scale))) + cmds.append(lineOStr("[fill=SITcol]", getEnvPoints("BeamCal", scale))) + cmds.append(lineOStr("[fill=SITcol]", getEnvPoints("LumiCal", scale))) + cmds.append(lineOStr("[fill=SITcol]", getEnvPoints("LHCal", scale))) + + cmds.append("\\end{tikzpicture}") return cmds -#----------------------------------------------- -def getEnvPoints(det,scale): + +# ----------------------------------------------- +def getEnvPoints(det, scale): points = [] env = envRZDict[det] for ep in env: - p = (scale * values[ ep[0] ], scale * values[ ep[1] ] ) - print( det, ' point: ' , p) - points.append( p ) + p = (scale * values[ep[0]], scale * values[ep[1]]) + print(det, " point: ", p) + points.append(p) return points -#----------------------------------------------- -def writeTexFile( det, fileExt, method, width ): - fn = './figs/' + det + fileExt + '.tex' +# ----------------------------------------------- +def writeTexFile(det, fileExt, method, width): + fn = "./figs/" + det + fileExt + ".tex" - of = open( fn , 'w' ) + of = open(fn, "w") cmds = [] - cmds.extend( getDocHeaderCmds( 'standalone', ['tikz','graphicx'] ) ) + cmds.extend(getDocHeaderCmds("standalone", ["tikz", "graphicx"])) - cmds.extend( method( det , width ) ) + cmds.extend(method(det, width)) - cmds.extend( getDocFooterCmds() ) + cmds.extend(getDocFooterCmds()) for cmd in cmds: - print(cmd , file=of) + print(cmd, file=of) of.close() -#----------------------------------------------- -def lineStr( tl, opt="" ): - +# ----------------------------------------------- +def lineStr(tl, opt=""): o = cStringIO.StringIO() - - print('\draw ', opt, file=o) - - i=0 + + print("\draw ", opt, file=o) + + i = 0 for t in tl: - if( i>0 ): - print(' -- ', file=o) - print('(', t[0] ,',', t[1],') ', file=o) + if i > 0: + print(" -- ", file=o) + print("(", t[0], ",", t[1], ") ", file=o) i += 1 - print(';', file=o) + print(";", file=o) str = o.getvalue() o.close() return str -#----------------------------------------------- -def lineOStr( opt, tl ): - return lineStr( tl, opt ) -#----------------------------------------------- +# ----------------------------------------------- + -def getDocHeaderCmds( docClass , packages): +def lineOStr(opt, tl): + return lineStr(tl, opt) + + +# ----------------------------------------------- + + +def getDocHeaderCmds(docClass, packages): cmds = [] - - cmds.append( '\\documentclass[a4]{'+ docClass+'}' ) - if( docClass == 'standalone'): - cmds.append( '\\standaloneconfig{border=20pt}' ) + + cmds.append("\\documentclass[a4]{" + docClass + "}") + if docClass == "standalone": + cmds.append("\\standaloneconfig{border=20pt}") for p in packages: - cmds.append( '\\usepackage{'+p+'}' ) + cmds.append("\\usepackage{" + p + "}") - cmds.append( '\\usepackage[a4paper,top=3cm, bottom=2.5cm, left=1cm, right=2cm ]{geometry}' ) + cmds.append( + "\\usepackage[a4paper,top=3cm, bottom=2.5cm, left=1cm, right=2cm ]{geometry}" + ) - cmds.append( '\\begin{document}' ) + cmds.append("\\begin{document}") return cmds -#----------------------------------------------- + + +# ----------------------------------------------- def getColorCmds(): cmds = [] - cmds.append( '\\definecolor{VXDcol}{RGB}{255,255,255}') - cmds.append( '\\definecolor{SITcol}{RGB}{221,221,221}') - cmds.append( '\\definecolor{SETcol}{RGB}{221,221,221}') - cmds.append( '\\definecolor{TPCcol}{RGB}{245,243,0}') - cmds.append( '\\definecolor{ECALcol}{RGB}{123,243,0}') - cmds.append( '\\definecolor{HCALcol}{RGB}{196,194,49}') - cmds.append( '\\definecolor{YOKEcol}{RGB}{24,194,196}') - cmds.append( '\\definecolor{COILcol}{RGB}{73,73,221}') - cmds.append( '\\definecolor{FTDcol}{RGB}{101,28,147}') - cmds.append( '\\definecolor{FCALcol}{RGB}{171,170,171}') + cmds.append("\\definecolor{VXDcol}{RGB}{255,255,255}") + cmds.append("\\definecolor{SITcol}{RGB}{221,221,221}") + cmds.append("\\definecolor{SETcol}{RGB}{221,221,221}") + cmds.append("\\definecolor{TPCcol}{RGB}{245,243,0}") + cmds.append("\\definecolor{ECALcol}{RGB}{123,243,0}") + cmds.append("\\definecolor{HCALcol}{RGB}{196,194,49}") + cmds.append("\\definecolor{YOKEcol}{RGB}{24,194,196}") + cmds.append("\\definecolor{COILcol}{RGB}{73,73,221}") + cmds.append("\\definecolor{FTDcol}{RGB}{101,28,147}") + cmds.append("\\definecolor{FCALcol}{RGB}{171,170,171}") return cmds + def getDocFooterCmds(): cmds = [] - cmds.append( '\\end{document}' ) + cmds.append("\\end{document}") return cmds -#----------------------------------------------- -def fixstr( aStr ): + + +# ----------------------------------------------- +def fixstr(aStr): l = len(aStr) - s = '' - for i in range(0,l+2): - s = s + ' ' + s = "" + for i in range(0, l + 2): + s = s + " " s = s + aStr return s -#----------------------------------------------- -def getRZEnvCmds( det, width ): +# ----------------------------------------------- + +def getRZEnvCmds(det, width): cmds = [] - envPoints = envRZDict[ det ] + envPoints = envRZDict[det] vals = values - - cmds.append( '\\begin{tikzpicture}' ) + cmds.append("\\begin{tikzpicture}") xmaxOrg = -1e99 # ---- compute the scale such that ymax == width for ep in envPoints: - if( vals[ ep[0] ] > xmaxOrg): - xmaxOrg = vals[ ep[0] ] + if vals[ep[0]] > xmaxOrg: + xmaxOrg = vals[ep[0]] scale = width / xmaxOrg - #--------------------------------------------------- + # --------------------------------------------------- points = [] - xvals = [] - yvals = [] - xmax,ymax= -1.e99, -1e99 + xvals = [] + yvals = [] + xmax, ymax = -1.0e99, -1e99 for ep in envPoints: + p = (scale * vals[ep[0]], scale * vals[ep[1]]) + points.append(p) - p = (scale * vals[ ep[0] ], scale * vals[ ep[1] ] ) - points.append( p ) - - x,y = p - if( x> xmax ): + x, y = p + if x > xmax: xmax = x - if( y> ymax ): + if y > ymax: ymax = y if ep[0] not in xvals: - xvals.append( ep[0] ) - p0 = ( scale * vals[ ep[0] ], 0 ) - cmds.append( lineOStr('[dashed]', [ p , p0 ] ) ) - cmds.append( '\\node [rotate=-90] at (' + str( p0[0] ) +','+ str( p0[1] ) - + ') {{\\verb#' + fixstr( ep[0] ) + '#}};' ) + xvals.append(ep[0]) + p0 = (scale * vals[ep[0]], 0) + cmds.append(lineOStr("[dashed]", [p, p0])) + cmds.append( + "\\node [rotate=-90] at (" + + str(p0[0]) + + "," + + str(p0[1]) + + ") {{\\verb#" + + fixstr(ep[0]) + + "#}};" + ) if ep[1] not in yvals: - yvals.append( ep[1] ) - p1 = ( 0, scale * vals[ ep[1] ] ) - cmds.append( lineOStr('[dashed]', [ p , p1 ] ) ) - cmds.append( '\\node [left] at (' + str(p1[0]) +','+str( p1[1] ) + ') {{\\verb#' - + str( ep[1] ) + '#}};' ) - - cmds.append( lineOStr('[ultra thick]', points ) ) - - cmds.append( lineOStr('[<->,thick]' , ( (0 , 1.25 * ymax ), (0,0), (1.25 * xmax ,0) ) ) ) + yvals.append(ep[1]) + p1 = (0, scale * vals[ep[1]]) + cmds.append(lineOStr("[dashed]", [p, p1])) + cmds.append( + "\\node [left] at (" + + str(p1[0]) + + "," + + str(p1[1]) + + ") {{\\verb#" + + str(ep[1]) + + "#}};" + ) + cmds.append(lineOStr("[ultra thick]", points)) - cmds.append( '\\end{tikzpicture}' ) + cmds.append(lineOStr("[<->,thick]", ((0, 1.25 * ymax), (0, 0), (1.25 * xmax, 0)))) + cmds.append("\\end{tikzpicture}") return cmds -#----------------------------------------------- +# ----------------------------------------------- -#----------------------------------------------- +# ----------------------------------------------- if __name__ == "__main__": - run() -#----------------------------------------------- + run() +# ----------------------------------------------- diff --git a/ILD/doc/latex/extractParameters.py b/ILD/doc/latex/extractParameters.py index cc637bb29..bb9d29d70 100644 --- a/ILD/doc/latex/extractParameters.py +++ b/ILD/doc/latex/extractParameters.py @@ -10,102 +10,97 @@ @version 1.0 """ -#----------------------------------------------- +# ----------------------------------------------- -#------------------------------------------------ +# ------------------------------------------------ # read the compact xml file from the command line # try: - compactFile = sys.argv[1] - paramFile = sys.argv[2] - dictFile = sys.argv[3] + compactFile = sys.argv[1] + paramFile = sys.argv[2] + dictFile = sys.argv[3] except IndexError: - print( " usage: python extractParameters.py compact.xml param_names.txt pyDict.py") - print() - sys.exit(1) + print(" usage: python extractParameters.py compact.xml param_names.txt pyDict.py") + print() + sys.exit(1) -#----------------------------------------------- +# ----------------------------------------------- import os, time, DDG4 from DDG4 import OutputLevel as Output from SystemOfUnits import * -#----------------------------------------------- +# ----------------------------------------------- + def run(): + kernel = DDG4.Kernel() - kernel = DDG4.Kernel() + try: + install_dir = os.environ["DD4hepINSTALL"] - try: - install_dir = os.environ['DD4hepINSTALL'] + except KeyError: + print(" please set the environment variable DD4hepINSTALL ") + print(" to your DD4hep installation path ! ") + exit(1) - except (KeyError): - print( " please set the environment variable DD4hepINSTALL ") - print( " to your DD4hep installation path ! ") - exit(1) + kernel.loadGeometry("file:" + compactFile) + lcdd = kernel.detectorDescription() + DDG4.importConstants(lcdd) - kernel.loadGeometry("file:"+ compactFile ) - lcdd = kernel.detectorDescription() - DDG4.importConstants( lcdd ) + # -------- - #-------- + inf = open(paramFile, "r") + outf = open(dictFile, "w") - inf = open( paramFile , 'r' ) - outf = open( dictFile , 'w' ) + names = readNames(inf) - names = readNames( inf ) - - writeDictionary( names, outf ) - - inf.close() - outf.close() + writeDictionary(names, outf) + inf.close() + outf.close() -#----------------------------------------------- -def readNames( inf ): - - """ - read ascii file with parameter names - """ - names = [] - - for line in inf: - cols = line.split() - for n in cols: - names.append( n ) - - return names -#----------------------------------------------- +# ----------------------------------------------- -def writeDictionary( names, of ): - - of.write( '""" \n' ) - of.write( ' python dictionary with parameters extracted from: ' + compactFile + '\n' ) - of.write( '""" '+ '\n') - of.write( 'values={}'+ '\n') - - for n in names: - of.write( 'values["'+n+'"] = ' + str( getattr( DDG4, n ) ) + '\n') - -#----------------------------------------------- +def readNames(inf): + """ + read ascii file with parameter names + """ + names = [] + for line in inf: + cols = line.split() + for n in cols: + names.append(n) -def printEnvelopeParameters( det ): - - print( " ========== ", det , " ================== ") - for p in dict[ det ]: - print( " ", p , getattr( DDG4, p )) + return names -#----------------------------------------------- +# ----------------------------------------------- -if __name__ == "__main__": - run() +def writeDictionary(names, of): + of.write('""" \n') + of.write(" python dictionary with parameters extracted from: " + compactFile + "\n") + of.write('""" ' + "\n") + of.write("values={}" + "\n") + + for n in names: + of.write('values["' + n + '"] = ' + str(getattr(DDG4, n)) + "\n") + +# ----------------------------------------------- - +def printEnvelopeParameters(det): + print(" ========== ", det, " ================== ") + for p in dict[det]: + print(" ", p, getattr(DDG4, p)) + +# ----------------------------------------------- + +if __name__ == "__main__": + run() diff --git a/ILD/scripts/dumpModelParameters.py b/ILD/scripts/dumpModelParameters.py index b5e63ff4c..e7bc6d8c3 100644 --- a/ILD/scripts/dumpModelParameters.py +++ b/ILD/scripts/dumpModelParameters.py @@ -3,85 +3,90 @@ import sys import time -#--- Mokka DB parameters --------------- -host="pollin1.in2p3.fr" # your host, usually localhost -user="consult" # your username -passwd="consult" # your password -dbName="models03" # name of the data base -#--------------------------------------- - -if len( sys.argv ) != 2: - print( " usage: python dumpModelParameters.py MODEL_NAME ") +# --- Mokka DB parameters --------------- +host = "pollin1.in2p3.fr" # your host, usually localhost +user = "consult" # your username +passwd = "consult" # your password +dbName = "models03" # name of the data base +# --------------------------------------- + +if len(sys.argv) != 2: + print(" usage: python dumpModelParameters.py MODEL_NAME ") sys.exit(0) -model = sys.argv[1] +model = sys.argv[1] -#model="ILD_o1_v05" +# model="ILD_o1_v05" -#----------------------------------------------------------------------- -db = MySQLdb.connect(host, user, passwd, dbName ) -#----------------------------------------------------------------------- +# ----------------------------------------------------------------------- +db = MySQLdb.connect(host, user, passwd, dbName) +# ----------------------------------------------------------------------- -outfile = "model_parameters_"+model+".xml" +outfile = "model_parameters_" + model + ".xml" -file = open( outfile , 'w' ) +file = open(outfile, "w") -#----------------------------------------------------------------------- +# ----------------------------------------------------------------------- # create a Cursor object cur = db.cursor() -#--- param dict: -params = {} +# --- param dict: +params = {} -#----- select all global parameters +# ----- select all global parameters cur.execute("select * from parameters ;") -#--- overwrite values in the dict: -for row in cur.fetchall() : - params[ row[0] ] = row[2] +# --- overwrite values in the dict: +for row in cur.fetchall(): + params[row[0]] = row[2] -# --- now select all sharing parameters for the model -cur.execute("select sub_detector.driver, sharing.parameter, sharing.driver_default_value from ingredients,sub_detector,sharing where (ingredients.model=\""+model+"\" and ingredients.sub_detector=sub_detector.name and sharing.driver=sub_detector.driver) ;") -#cur.execute("select sub_detector.driver, sharing.parameter, sharing.driver_default_value from ingredients,sub_detector,sharing where (ingredients.model=\""+model+"\" and ingredients.sub_detector=sub_detector.name and sharing.driver=sub_detector.driver and sharing.driver_default_value IS NOT NULL) ;") - +# --- now select all sharing parameters for the model +cur.execute( + 'select sub_detector.driver, sharing.parameter, sharing.driver_default_value from ingredients,sub_detector,sharing where (ingredients.model="' + + model + + '" and ingredients.sub_detector=sub_detector.name and sharing.driver=sub_detector.driver) ;' +) +# cur.execute("select sub_detector.driver, sharing.parameter, sharing.driver_default_value from ingredients,sub_detector,sharing where (ingredients.model=\""+model+"\" and ingredients.sub_detector=sub_detector.name and sharing.driver=sub_detector.driver and sharing.driver_default_value IS NOT NULL) ;") # --- safe params in dict -for row in cur.fetchall() : - #print row[1], " " , row[2] - params[ row[1] ] = row[2] +for row in cur.fetchall(): + # print row[1], " " , row[2] + params[row[1]] = row[2] -#----- now select all model specific parameters -cur.execute("select * from model_parameters where model=\""+model+"\" ;") +# ----- now select all model specific parameters +cur.execute('select * from model_parameters where model="' + model + '" ;') -#--- overwrite values in the dict: -for row in cur.fetchall() : - #print row[1], " " , row[2] - params[ row[1] ] = row[2] +# --- overwrite values in the dict: +for row in cur.fetchall(): + # print row[1], " " , row[2] + params[row[1]] = row[2] -#dump params to xml file +# dump params to xml file print("", file=file) -for k in sorted( params ): - v = params[ k ] - if v: - print("", file=file) - else: - cur.execute("select name, default_value from parameters where name=\"" + k + "\";") - for row in cur.fetchall() : - v = row[1] - print("", file=file) +for k in sorted(params): + v = params[k] + if v: + print('', file=file) + else: + cur.execute( + 'select name, default_value from parameters where name="' + k + '";' + ) + for row in cur.fetchall(): + v = row[1] + print('', file=file) diff --git a/detectorSegmentations/tests/options/phiEtaSegmentation.py b/detectorSegmentations/tests/options/phiEtaSegmentation.py index 9c00267ed..d2ade9e77 100644 --- a/detectorSegmentations/tests/options/phiEtaSegmentation.py +++ b/detectorSegmentations/tests/options/phiEtaSegmentation.py @@ -4,52 +4,70 @@ from Configurables import MomentumRangeParticleGun from GaudiKernel import PhysicalConstants as constants + guntool = MomentumRangeParticleGun() -guntool.ThetaMin = 0 -guntool.ThetaMax = 2 * constants.pi +guntool.ThetaMin = 0 +guntool.ThetaMax = 2 * constants.pi guntool.PdgCodes = [11] guntool.MomentumMin = 500 guntool.MomentumMax = 1000 from Configurables import FlatSmearVertex + vertexsmeartool = FlatSmearVertex() -vertexsmeartool.xVertexMin = -25. -vertexsmeartool.xVertexMax = 25. -vertexsmeartool.yVertexMin = -25. -vertexsmeartool.yVertexMax = 25. -vertexsmeartool.zVertexMin = -25. -vertexsmeartool.zVertexMax = 25. +vertexsmeartool.xVertexMin = -25.0 +vertexsmeartool.xVertexMax = 25.0 +vertexsmeartool.yVertexMin = -25.0 +vertexsmeartool.yVertexMax = 25.0 +vertexsmeartool.zVertexMin = -25.0 +vertexsmeartool.zVertexMax = 25.0 from Configurables import GenAlg + gen = GenAlg() -gen.SignalProvider=guntool -gen.VertexSmearingTool=vertexsmeartool +gen.SignalProvider = guntool +gen.VertexSmearingTool = vertexsmeartool gen.hepmc.Path = "hepmc" from Configurables import HepMCToEDMConverter + hepmc_converter = HepMCToEDMConverter("Converter") -hepmc_converter.hepmc.Path="hepmc" -hepmc_converter.genparticles.Path="allGenParticles" -hepmc_converter.genvertices.Path="allGenVertices" +hepmc_converter.hepmc.Path = "hepmc" +hepmc_converter.genparticles.Path = "allGenParticles" +hepmc_converter.genvertices.Path = "allGenVertices" from Configurables import GeoSvc -geoservice = GeoSvc("GeoSvc", detectors=['file:Test/TestGeometry/data/Barrel_testCaloSD_phieta.xml']) + +geoservice = GeoSvc( + "GeoSvc", detectors=["file:Test/TestGeometry/data/Barrel_testCaloSD_phieta.xml"] +) from Configurables import SimG4Svc + geantservice = SimG4Svc("SimG4Svc") from Configurables import SimG4Alg, SimG4SaveCalHits, InspectHitsCollectionsTool -inspecttool = InspectHitsCollectionsTool("inspect", readoutNames=["ECalHits"], OutputLevel = DEBUG) -savecaltool = SimG4SaveCalHits("saveECalHits", readoutNames = ["ECalHits"], OutputLevel = DEBUG) + +inspecttool = InspectHitsCollectionsTool( + "inspect", readoutNames=["ECalHits"], OutputLevel=DEBUG +) +savecaltool = SimG4SaveCalHits( + "saveECalHits", readoutNames=["ECalHits"], OutputLevel=DEBUG +) savecaltool.positionedCaloHits.Path = "positionedCaloHits" savecaltool.caloHits.Path = "caloHits" -geantsim = SimG4Alg("SimG4Alg", outputs= ["SimG4SaveCalHits/saveECalHits","InspectHitsCollectionsTool/inspect"]) +geantsim = SimG4Alg( + "SimG4Alg", + outputs=["SimG4SaveCalHits/saveECalHits", "InspectHitsCollectionsTool/inspect"], +) from Configurables import FCCDataSvc, PodioOutput + podiosvc = FCCDataSvc("EventDataSvc") out = PodioOutput("out", filename="test_phiEtaSegmentation.root") out.outputCommands = ["keep *"] -ApplicationMgr(EvtSel='NONE', - EvtMax=10, - TopAlg=[gen, hepmc_converter, geantsim, out], - ExtSvc = [podiosvc, geoservice, geantservice], - ) +ApplicationMgr( + EvtSel="NONE", + EvtMax=10, + TopAlg=[gen, hepmc_converter, geantsim, out], + ExtSvc=[podiosvc, geoservice, geantservice], +) diff --git a/example/SteeringFile_IDEA_o1_v03.py b/example/SteeringFile_IDEA_o1_v03.py index f9adeb07e..102085aa5 100644 --- a/example/SteeringFile_IDEA_o1_v03.py +++ b/example/SteeringFile_IDEA_o1_v03.py @@ -1,9 +1,10 @@ from DDSim.DD4hepSimulation import DD4hepSimulation from g4units import mm, GeV, MeV + SIM = DD4hepSimulation() ## The compact XML file, or multiple compact files, if the last one is the closer. -SIM.compactFile = ['../FCCee/IDEA/compact/IDEA_o1_v03/IDEA_o1_v03.xml'] +SIM.compactFile = ["../FCCee/IDEA/compact/IDEA_o1_v03/IDEA_o1_v03.xml"] ## Lorentz boost for the crossing angle, in radian! SIM.crossingAngleBoost = 0.0 SIM.enableDetailedShowerMode = False @@ -42,32 +43,32 @@ ################################################################################ ## Helper holding sensitive detector and other actions. -## +## ## The default tracker and calorimeter sensitive actions can be set with -## +## ## >>> SIM = DD4hepSimulation() ## >>> SIM.action.tracker=('Geant4TrackerWeightedAction', {'HitPositionCombination': 2, 'CollectSingleDeposits': False}) ## >>> SIM.action.calo = "Geant4CalorimeterAction" -## +## ## The default sensitive actions for calorimeters and trackers are applied based on the sensitive type. ## The list of sensitive types can be changed with -## +## ## >>> SIM = DD4hepSimulation() ## >>> SIM.action.trackerSDTypes = ['tracker', 'myTrackerSensType'] ## >>> SIM.calor.calorimeterSDTypes = ['calorimeter', 'myCaloSensType'] -## +## ## For specific subdetectors specific sensitive detectors can be set based on patterns in the name of the subdetector. -## +## ## >>> SIM = DD4hepSimulation() ## >>> SIM.action.mapActions['tpc'] = "TPCSDAction" -## +## ## and additional parameters for the sensitive detectors can be set when the map is given a tuple -## +## ## >>> SIM = DD4hepSimulation() ## >>> SIM.action.mapActions['ecal'] =( "CaloPreShowerSDAction", {"FirstLayerNumber": 1} ) -## +## ## Additional actions can be set as well with the following syntax variations: -## +## ## >>> SIM = DD4hepSimulation() ## # single action by name only: ## >>> SIM.action.run = "Geant4TestRunAction" @@ -79,7 +80,7 @@ ## >>> SIM.action.step = { "name": "Geant4TestStepAction", "parameter": {"Property_int": 10} } ## # multiple actions by list of dict of name and parameter dict: ## >>> SIM.action.stack = [ { "name": "Geant4TestStackAction", "parameter": {"Property_int": 10} } ] -## +## ## On the command line or in python, these actions can be specified as JSON strings: ## $ ddsim --action.stack '{ "name": "Geant4TestStackAction", "parameter": { "Property_int": 10 } }' ## or @@ -92,48 +93,51 @@ ## } ## } ## ''' -## -## +## +## ################################################################################ -## set the default calorimeter action +## set the default calorimeter action SIM.action.calo = "Geant4ScintillatorCalorimeterAction" ## List of patterns matching sensitive detectors of type Calorimeter. -SIM.action.calorimeterSDTypes = ['calorimeter', 'DRcaloSiPMSD'] +SIM.action.calorimeterSDTypes = ["calorimeter", "DRcaloSiPMSD"] -## set the default event action +## set the default event action SIM.action.event = [] ## Create a map of patterns and actions to be applied to sensitive detectors. -## +## ## Example: if the name of the detector matches 'tpc' the TPCSDAction is used. -## +## ## SIM.action.mapActions['tpc'] = "TPCSDAction" -## -SIM.action.mapActions = {'DRcalo': 'DRCaloSDAction'} +## +SIM.action.mapActions = {"DRcalo": "DRCaloSDAction"} -## set the default run action +## set the default run action SIM.action.run = [] -## set the default stack action +## set the default stack action SIM.action.stack = [] -## set the default step action +## set the default step action SIM.action.step = [] -## set the default track action +## set the default track action SIM.action.track = [] -## set the default tracker action -SIM.action.tracker = ('Geant4TrackerWeightedAction', {'HitPositionCombination': 2, 'CollectSingleDeposits': False}) +## set the default tracker action +SIM.action.tracker = ( + "Geant4TrackerWeightedAction", + {"HitPositionCombination": 2, "CollectSingleDeposits": False}, +) ## List of patterns matching sensitive detectors of type Tracker. -SIM.action.trackerSDTypes = ['tracker'] +SIM.action.trackerSDTypes = ["tracker"] ################################################################################ -## Configuration for the magnetic field (stepper) +## Configuration for the magnetic field (stepper) ################################################################################ SIM.field.delta_chord = 0.25 SIM.field.delta_intersection = 0.001 @@ -148,37 +152,41 @@ ################################################################################ ## Configuration for sensitive detector filters -## +## ## Set the default filter for 'tracker' ## >>> SIM.filter.tracker = "edep1kev" ## Use no filter for 'calorimeter' by default ## >>> SIM.filter.calo = "" -## +## ## Assign a filter to a sensitive detector via pattern matching ## >>> SIM.filter.mapDetFilter['FTD'] = "edep1kev" -## +## ## Or more than one filter: ## >>> SIM.filter.mapDetFilter['FTD'] = ["edep1kev", "geantino"] -## +## ## Don't use the default filter or anything else: ## >>> SIM.filter.mapDetFilter['TPC'] = None ## or "" or [] -## +## ## Create a custom filter. The dictionary is used to instantiate the filter later on ## >>> SIM.filter.filters['edep3kev'] = dict(name="EnergyDepositMinimumCut/3keV", parameter={"Cut": 3.0*keV} ) -## -## +## +## ################################################################################ -## +## ## default filter for calorimeter sensitive detectors; ## this is applied if no other filter is used for a calorimeter -## +## SIM.filter.calo = "edep0" -## list of filter objects: map between name and parameter dictionary -SIM.filter.filters = {'geantino': {'name': 'GeantinoRejectFilter/GeantinoRejector', 'parameter': {}}, 'edep1kev': {'name': 'EnergyDepositMinimumCut', 'parameter': {'Cut': 0.001}}, 'edep0': {'name': 'EnergyDepositMinimumCut/Cut0', 'parameter': {'Cut': 0.0}}} +## list of filter objects: map between name and parameter dictionary +SIM.filter.filters = { + "geantino": {"name": "GeantinoRejectFilter/GeantinoRejector", "parameter": {}}, + "edep1kev": {"name": "EnergyDepositMinimumCut", "parameter": {"Cut": 0.001}}, + "edep0": {"name": "EnergyDepositMinimumCut/Cut0", "parameter": {"Cut": 0.0}}, +} -## a map between patterns and filter objects, using patterns to attach filters to sensitive detector +## a map between patterns and filter objects, using patterns to attach filters to sensitive detector SIM.filter.mapDetFilter = {} ## default filter for tracking sensitive detectors; this is applied if no other filter is used for a tracker @@ -186,7 +194,7 @@ ################################################################################ -## Configuration for the Detector Construction. +## Configuration for the Detector Construction. ################################################################################ SIM.geometry.dumpGDML = "" SIM.geometry.dumpHierarchy = 0 @@ -223,38 +231,38 @@ ################################################################################ -## Configuration for the GuineaPig InputFiles +## Configuration for the GuineaPig InputFiles ################################################################################ ## Set the number of pair particles to simulate per event. ## Only used if inputFile ends with ".pairs" ## If "-1" all particles will be simulated in a single event -## +## SIM.guineapig.particlesPerEvent = "-1" ################################################################################ -## Configuration for the DDG4 ParticleGun +## Configuration for the DDG4 ParticleGun ################################################################################ -## direction of the particle gun, 3 vector -SIM.gun.direction = (1., 1., 1.) +## direction of the particle gun, 3 vector +SIM.gun.direction = (1.0, 1.0, 1.0) ## choose the distribution of the random direction for theta -## +## ## Options for random distributions: -## +## ## 'uniform' is the default distribution, flat in theta ## 'cos(theta)' is flat in cos(theta) ## 'eta', or 'pseudorapidity' is flat in pseudorapity ## 'ffbar' is distributed according to 1+cos^2(theta) -## +## ## Setting a distribution will set isotrop = True -## +## SIM.gun.distribution = None ## Total energy (including mass) for the particle gun. -## +## ## If not None, it will overwrite the setting of momentumMin and momentumMax SIM.gun.energy = None @@ -265,10 +273,10 @@ SIM.gun.etaMin = None ## isotropic distribution for the particle gun -## +## ## use the options phiMin, phiMax, thetaMin, and thetaMax to limit the range of randomly distributed directions ## if one of these options is not None the random distribution will be set to True and cannot be turned off! -## +## SIM.gun.isotrop = False ## Maximal momentum when using distribution (default = 0.0) @@ -285,7 +293,7 @@ ## Minimal azimuthal angle for random distribution SIM.gun.phiMin = None -## position of the particle gun, 3 vector +## position of the particle gun, 3 vector SIM.gun.position = (0.0, 0.0, 0.0) ## Maximal polar angle for random distribution @@ -296,7 +304,7 @@ ################################################################################ -## Configuration for the hepmc3 InputFiles +## Configuration for the hepmc3 InputFiles ################################################################################ ## Set the name of the attribute contraining color flow information index 0. @@ -306,28 +314,28 @@ SIM.hepmc3.Flow2 = "flow2" ## Set to false if the input should be opened with the hepmc2 ascii reader. -## +## ## If ``True`` a '.hepmc' file will be opened with the HEPMC3 Reader Factory. -## +## ## Defaults to true if DD4hep was build with HEPMC3 support. -## +## SIM.hepmc3.useHepMC3 = True ################################################################################ -## Configuration for Input Files. +## Configuration for Input Files. ################################################################################ ## Set one or more functions to configure input steps. -## +## ## The functions must take a ``DD4hepSimulation`` object as their only argument and return the created generatorAction ## ``gen`` (for example). -## +## ## For example one can add this to the ddsim steering file: -## +## ## def exampleUserPlugin(dd4hepSimulation): ## '''Example code for user created plugin. -## +## ## :param DD4hepSimulation dd4hepSimulation: The DD4hepSimulation instance, so all parameters can be accessed ## :return: GeneratorAction ## ''' @@ -340,27 +348,27 @@ ## gen.Parameters = {'DataFilePath': '/path/to/files/data'} ## gen.enableUI() ## return gen -## +## ## SIM.inputConfig.userInputPlugin = exampleUserPlugin -## +## ## Repeat function definition and assignment to add multiple input steps -## -## +## +## SIM.inputConfig.userInputPlugin = [] ################################################################################ -## Configuration for the generator-level InputFiles +## Configuration for the generator-level InputFiles ################################################################################ ## Set the name of the collection containing the MCParticle input. ## Default is "MCParticle". -## +## SIM.lcio.mcParticleCollectionName = "MCParticle" ################################################################################ -## Configuration for the LCIO output file settings +## Configuration for the LCIO output file settings ################################################################################ ## The event number offset to write in slcio output file. E.g setting it to 42 will start counting events from 42 instead of 0 @@ -374,7 +382,7 @@ ################################################################################ -## Configuration for the output levels of DDG4 components +## Configuration for the output levels of DDG4 components ################################################################################ ## Output level for geometry. @@ -394,7 +402,7 @@ ################################################################################ -## Configuration for Output Files. +## Configuration for Output Files. ################################################################################ ## Use the DD4HEP output plugin regardless of outputfilename. @@ -407,14 +415,14 @@ SIM.outputConfig.forceLCIO = False ## Set a function to configure the outputFile. -## +## ## The function must take a ``DD4hepSimulation`` object as its only argument and return ``None``. -## +## ## For example one can add this to the ddsim steering file: -## +## ## def exampleUserPlugin(dd4hepSimulation): ## '''Example code for user created plugin. -## +## ## :param DD4hepSimulation dd4hepSimulation: The DD4hepSimulation instance, so all parameters can be accessed ## :return: None ## ''' @@ -430,15 +438,19 @@ ## evt_root.enableUI() ## Kernel().eventAction().add(evt_root) ## return None -## +## ## SIM.outputConfig.userOutputPlugin = exampleUserPlugin ## # arbitrary options can be created and set via the steering file or command line ## SIM.outputConfig.myExtension = '.csv' -## +## + def Geant4Output2EDM4hep_DRC_plugin(dd4hepSimulation): from DDG4 import EventAction, Kernel - evt_root = EventAction(Kernel(), 'Geant4Output2EDM4hep_DRC/' + dd4hepSimulation.outputFile, True) + + evt_root = EventAction( + Kernel(), "Geant4Output2EDM4hep_DRC/" + dd4hepSimulation.outputFile, True + ) evt_root.Control = True output = dd4hepSimulation.outputFile evt_root.Output = output @@ -446,34 +458,35 @@ def Geant4Output2EDM4hep_DRC_plugin(dd4hepSimulation): Kernel().eventAction().add(evt_root) return None + SIM.outputConfig.userOutputPlugin = Geant4Output2EDM4hep_DRC_plugin ################################################################################ -## Configuration for the Particle Handler/ MCTruth treatment +## Configuration for the Particle Handler/ MCTruth treatment ################################################################################ ## Enable lots of printout on simulated hits and MC-truth information SIM.part.enableDetailedHitsAndParticleInfo = False -## Keep all created particles +## Keep all created particles SIM.part.keepAllParticles = False ## Minimal distance between particle vertex and endpoint of parent after ## which the vertexIsNotEndpointOfParent flag is set -## +## SIM.part.minDistToParentVertex = 2.2e-14 ## MinimalKineticEnergy to store particles created in the tracking region SIM.part.minimalKineticEnergy = 1.0 -## Printout at End of Tracking +## Printout at End of Tracking SIM.part.printEndTracking = False -## Printout at Start of Tracking +## Printout at Start of Tracking SIM.part.printStartTracking = False ## List of processes to save, on command line give as whitespace separated string in quotation marks -SIM.part.saveProcesses = ['Decay'] +SIM.part.saveProcesses = ["Decay"] ## Optionally enable an extended Particle Handler SIM.part.userParticleHandler = "Geant4TCUserParticleHandler" @@ -481,13 +494,13 @@ def Geant4Output2EDM4hep_DRC_plugin(dd4hepSimulation): ################################################################################ ## Configuration for the PhysicsList and Monte Carlo particle selection. -## +## ## To load arbitrary plugins, add a function to be executed. -## +## ## The function must take the DDG4.Kernel() object as the only argument. -## +## ## For example, add a function definition and the call to a steering file:: -## +## ## def setupCerenkov(kernel): ## from DDG4 import PhysicsList ## seq = kernel.physicsList() @@ -504,106 +517,149 @@ def Geant4Output2EDM4hep_DRC_plugin(dd4hepSimulation): ## ph.enableUI() ## seq.adopt(ph) ## return None -## +## ## SIM.physics.setupUserPhysics(setupCerenkov) -## +## ## # End of example -## +## ################################################################################ ## Set of Generator Statuses that are used to mark unstable particles that should decay inside of Geant4. -## +## SIM.physics.alternativeDecayStatuses = set() ## If true, add decay processes for all particles. -## +## ## Only enable when creating a physics list not based on an existing Geant4 list! -## +## SIM.physics.decays = False ## The name of the Geant4 Physics list. SIM.physics.list = "FTFP_BERT" ## location of particle.tbl file containing extra particles and their lifetime information -## +## ## For example in $DD4HEP/examples/DDG4/examples/particle.tbl -## +## SIM.physics.pdgfile = None ## The global geant4 rangecut for secondary production -## +## ## Default is 0.7 mm as is the case in geant4 10 -## +## ## To disable this plugin and be absolutely sure to use the Geant4 default range cut use "None" -## +## ## Set printlevel to DEBUG to see a printout of all range cuts, ## but this only works if range cut is not "None" -## +## SIM.physics.rangecut = 0.7 ## Set of PDG IDs that will not be passed from the input record to Geant4. -## +## ## Quarks, gluons and W's Z's etc should not be treated by Geant4 -## -SIM.physics.rejectPDGs = {1, 2, 3, 4, 5, 6, 3201, 3203, 4101, 4103, 21, 23, 24, 5401, 25, 2203, 5403, 3101, 3103, 4403, 2101, 5301, 2103, 5303, 4301, 1103, 4303, 5201, 5203, 3303, 4201, 4203, 5101, 5103, 5503} +## +SIM.physics.rejectPDGs = { + 1, + 2, + 3, + 4, + 5, + 6, + 3201, + 3203, + 4101, + 4103, + 21, + 23, + 24, + 5401, + 25, + 2203, + 5403, + 3101, + 3103, + 4403, + 2101, + 5301, + 2103, + 5303, + 4301, + 1103, + 4303, + 5201, + 5203, + 3303, + 4201, + 4203, + 5101, + 5103, + 5503, +} ## Set of PDG IDs for particles that should not be passed to Geant4 if their properTime is 0. -## +## ## The properTime of 0 indicates a documentation to add FSR to a lepton for example. -## +## SIM.physics.zeroTimePDGs = {17, 11, 13, 15} def setupOpticalPhysics(kernel): from DDG4 import PhysicsList + seq = kernel.physicsList() - cerenkov = PhysicsList(kernel, 'Geant4CerenkovPhysics/CerenkovPhys') + cerenkov = PhysicsList(kernel, "Geant4CerenkovPhysics/CerenkovPhys") cerenkov.TrackSecondariesFirst = True cerenkov.VerboseLevel = 1 cerenkov.enableUI() seq.adopt(cerenkov) - scint = PhysicsList(kernel, 'Geant4ScintillationPhysics/ScintillationPhys') + scint = PhysicsList(kernel, "Geant4ScintillationPhysics/ScintillationPhys") scint.VerboseLevel = 1 scint.TrackSecondariesFirst = True scint.BoundaryInvokeSD = True scint.enableUI() seq.adopt(scint) - - opt = PhysicsList(kernel, 'Geant4OpticalPhotonPhysics/OpticalGammaPhys') - opt.addParticleConstructor('G4OpticalPhoton') + + opt = PhysicsList(kernel, "Geant4OpticalPhotonPhysics/OpticalGammaPhys") + opt.addParticleConstructor("G4OpticalPhoton") opt.VerboseLevel = 1 opt.BoundaryInvokeSD = True opt.enableUI() seq.adopt(opt) return None + + SIM.physics.setupUserPhysics(setupOpticalPhysics) + def setupDRCFastSim(kernel): from DDG4 import DetectorConstruction, Geant4, PhysicsList + geant4 = Geant4(kernel) seq = geant4.detectorConstruction() # Create a model for fast simulation - model = DetectorConstruction(kernel, str("Geant4DRCFiberModel/ShowerModel") ) + model = DetectorConstruction(kernel, str("Geant4DRCFiberModel/ShowerModel")) # Mandatory model parameters - model.RegionName = 'FastSimOpFiberRegion' + model.RegionName = "FastSimOpFiberRegion" model.Enable = True - model.ApplicableParticles = ['opticalphoton'] + model.ApplicableParticles = ["opticalphoton"] model.enableUI() seq.adopt(model) # Now build the physics list: phys = kernel.physicsList() - ph = PhysicsList(kernel, str('Geant4FastPhysics/FastPhysicsList')) - ph.EnabledParticles = ['opticalphoton'] + ph = PhysicsList(kernel, str("Geant4FastPhysics/FastPhysicsList")) + ph.EnabledParticles = ["opticalphoton"] ph.BeVerbose = True ph.enableUI() phys.adopt(ph) phys.dump() + + SIM.physics.setupUserPhysics(setupDRCFastSim) ################################################################################ -## Properties for the random number generator +## Properties for the random number generator ################################################################################ ## If True, calculate random seed for each event basedon eventID and runID @@ -618,21 +674,21 @@ def setupDRCFastSim(kernel): ################################################################################ ## Configuration for setting commands to run during different phases. -## +## ## In this section, one can configure commands that should be run during the different phases of the Geant4 execution. -## +## ## 1. Configuration ## 2. Initialization ## 3. Pre Run ## 4. Post Run ## 5. Terminate / Finalization -## +## ## For example, one can add -## +## ## >>> SIM.ui.commandsConfigure = ['/physics_lists/em/SyncRadiation true'] -## +## ## Further details should be taken from the Geant4 documentation. -## +## ################################################################################ ## List of UI commands to run during the 'Configure' phase. diff --git a/example/arcfullsim.py b/example/arcfullsim.py index 41cbabe12..a48819642 100755 --- a/example/arcfullsim.py +++ b/example/arcfullsim.py @@ -2,10 +2,11 @@ Test of ARC detector The lines 27-95 setup the simulation using DD4hep The lines 99-127 run the simulation and produce some plots -An exception is thrown in case the simulation failed or the output file is too small. - Last modification 2023-Jun-23 - Author: Alvaro Tolosa-Delgado +An exception is thrown in case the simulation failed or the output file is too small. + Last modification 2023-Jun-23 + Author: Alvaro Tolosa-Delgado """ + from __future__ import absolute_import, unicode_literals import logging import sys @@ -20,14 +21,14 @@ format="%(name)-16s %(levelname)s %(message)s", level=logging.INFO, stream=sys.stdout, - ) + ) logger = logging.getLogger("DDSim") SIM = DD4hepSimulation() # Default is enable visualization of tracks SIM.runType = "qt" - SIM.macroFile ='vis.mac' + SIM.macroFile = "vis.mac" # Ensure that Cerenkov and optical physics are always loaded def setupCerenkov(kernel): @@ -58,7 +59,7 @@ def setupCerenkov(kernel): SIM.filter.filters["opticalphotons"] = dict( name="ParticleSelectFilter/OpticalPhotonSelector", parameter={"particle": "opticalphoton"}, - ) + ) SIM.filter.mapDetFilter["ARCBARREL"] = "opticalphotons" SIM.filter.mapDetFilter["ARCENDCAP"] = "opticalphotons" @@ -74,15 +75,14 @@ def setupCerenkov(kernel): SIM.enableGun = True SIM.gun.energy = "50*GeV" SIM.gun.particle = "pi+" - #SIM.gun.thetaMin = "30*deg" - #SIM.gun.thetaMax = "150*deg" - #SIM.gun.phiMin = "0*deg" - #SIM.gun.phiMax = "240.1*deg" + # SIM.gun.thetaMin = "30*deg" + # SIM.gun.thetaMax = "150*deg" + # SIM.gun.phiMin = "0*deg" + # SIM.gun.phiMax = "240.1*deg" SIM.gun.distribution = "uniform" SIM.gun.multiplicity = 1 SIM.gun.position = "0 0 0*cm" - # Default compact file SIM.compactFile = "./compact/arc_full_v0.xml" @@ -90,7 +90,7 @@ def setupCerenkov(kernel): SIM.outputFile = "arcsim.root" if hasattr(SIM, "outputConfig") and hasattr(SIM.outputConfig, "forceDD4HEP"): SIM.outputConfig.forceDD4HEP = True # use DD4hep root format, not EDM4HEP - #SIM.outputFile = "arcsim_edm4hep.root" + # SIM.outputFile = "arcsim_edm4hep.root" # Override with user options SIM.parseOptions() @@ -98,32 +98,60 @@ def setupCerenkov(kernel): # Run the simulation try: SIM.run() - if os.path.getsize( SIM.outputFile ) < 1000000 : + if os.path.getsize(SIM.outputFile) < 1000000: raise RuntimeError("Output file not found or size less than 1MB") # Create some images outImagePrefix = "arcsim_" ROOT.gROOT.SetBatch(1) rootfile = ROOT.TFile(SIM.outputFile) - if not "edm4hep" in SIM.outputFile : + if not "edm4hep" in SIM.outputFile: EVENT = rootfile.Get("EVENT") - EVENT.Draw("ArcCollection.position.Z():ArcCollection.position.phi()","((ArcCollection.cellID>>5)&0x7)==0") - ROOT.gPad.SaveAs( outImagePrefix + "barrel_" + SIM.gun.particle + ".png") - EVENT.Draw("ArcCollection.position.Y():ArcCollection.position.X()","((ArcCollection.cellID>>5)&0x7)==1") - ROOT.gPad.SaveAs( outImagePrefix + "endcapZpos_" + SIM.gun.particle + ".png") - EVENT.Draw("ArcCollection.position.Y():ArcCollection.position.X()","((ArcCollection.cellID>>5)&0x7)==2") - ROOT.gPad.SaveAs( outImagePrefix + "endcapZneg_" + SIM.gun.particle + ".png") - EVENT.Draw("ArcCollection.position.Y():ArcCollection.position.X()","((ArcCollection.cellID>>5)&0x7)==2&&ArcCollection.position.Y()>0&&ArcCollection.position.X()>0") - ROOT.gPad.SaveAs( outImagePrefix + "endcapZneg_" + SIM.gun.particle + "zoom.png") - else : + EVENT.Draw( + "ArcCollection.position.Z():ArcCollection.position.phi()", + "((ArcCollection.cellID>>5)&0x7)==0", + ) + ROOT.gPad.SaveAs(outImagePrefix + "barrel_" + SIM.gun.particle + ".png") + EVENT.Draw( + "ArcCollection.position.Y():ArcCollection.position.X()", + "((ArcCollection.cellID>>5)&0x7)==1", + ) + ROOT.gPad.SaveAs(outImagePrefix + "endcapZpos_" + SIM.gun.particle + ".png") + EVENT.Draw( + "ArcCollection.position.Y():ArcCollection.position.X()", + "((ArcCollection.cellID>>5)&0x7)==2", + ) + ROOT.gPad.SaveAs(outImagePrefix + "endcapZneg_" + SIM.gun.particle + ".png") + EVENT.Draw( + "ArcCollection.position.Y():ArcCollection.position.X()", + "((ArcCollection.cellID>>5)&0x7)==2&&ArcCollection.position.Y()>0&&ArcCollection.position.X()>0", + ) + ROOT.gPad.SaveAs( + outImagePrefix + "endcapZneg_" + SIM.gun.particle + "zoom.png" + ) + else: EVENT = rootfile.Get("events") - EVENT.Draw("ArcCollection.position.z:atan(ArcCollection.position.y/ArcCollection.position.x)","((ArcCollection.cellID>>5)&0x7)==0&& ArcCollection.position.x>0") - ROOT.gPad.SaveAs( outImagePrefix + "barrel_" + SIM.gun.particle + ".png") - EVENT.Draw("ArcCollection.position.y:ArcCollection.position.x","((ArcCollection.cellID>>5)&0x7)==1") - ROOT.gPad.SaveAs( outImagePrefix + "endcapZpos_" + SIM.gun.particle + ".png") - EVENT.Draw("ArcCollection.position.y:ArcCollection.position.x","((ArcCollection.cellID>>5)&0x7)==2") - ROOT.gPad.SaveAs( outImagePrefix + "endcapZneg_" + SIM.gun.particle + ".png") - EVENT.Draw("ArcCollection.position.y:ArcCollection.position.x","((ArcCollection.cellID>>5)&0x7)==2&& ArcCollection.position.x>0&& ArcCollection.position.y>0") - ROOT.gPad.SaveAs( outImagePrefix + "endcapZneg_" + SIM.gun.particle + "zoom.png") + EVENT.Draw( + "ArcCollection.position.z:atan(ArcCollection.position.y/ArcCollection.position.x)", + "((ArcCollection.cellID>>5)&0x7)==0&& ArcCollection.position.x>0", + ) + ROOT.gPad.SaveAs(outImagePrefix + "barrel_" + SIM.gun.particle + ".png") + EVENT.Draw( + "ArcCollection.position.y:ArcCollection.position.x", + "((ArcCollection.cellID>>5)&0x7)==1", + ) + ROOT.gPad.SaveAs(outImagePrefix + "endcapZpos_" + SIM.gun.particle + ".png") + EVENT.Draw( + "ArcCollection.position.y:ArcCollection.position.x", + "((ArcCollection.cellID>>5)&0x7)==2", + ) + ROOT.gPad.SaveAs(outImagePrefix + "endcapZneg_" + SIM.gun.particle + ".png") + EVENT.Draw( + "ArcCollection.position.y:ArcCollection.position.x", + "((ArcCollection.cellID>>5)&0x7)==2&& ArcCollection.position.x>0&& ArcCollection.position.y>0", + ) + ROOT.gPad.SaveAs( + outImagePrefix + "endcapZneg_" + SIM.gun.particle + "zoom.png" + ) rootfile.Close() @@ -133,4 +161,7 @@ def setupCerenkov(kernel): logger.fatal("TEST: failed") if "global name" in str(e): globalToSet = str(e).split("'")[1] - logger.fatal("Unknown global variable, please add\nglobal %s\nto your steeringFile" % globalToSet) + logger.fatal( + "Unknown global variable, please add\nglobal %s\nto your steeringFile" + % globalToSet + ) diff --git a/example/ddsim.py b/example/ddsim.py index 0de928c5e..99155c192 100644 --- a/example/ddsim.py +++ b/example/ddsim.py @@ -11,24 +11,24 @@ """ -#------------------------------------------------ +# ------------------------------------------------ # read the compact xml file from the command line # try: - compactFile = sys.argv[1] + compactFile = sys.argv[1] except IndexError: - print( " usage: python ddsim.py compact.xml") - print() - sys.exit(1) + print(" usage: python ddsim.py compact.xml") + print() + sys.exit(1) -#----------------------------------------------- +# ----------------------------------------------- import os, time, DDG4 from DDG4 import OutputLevel as Output from SystemOfUnits import * -#================================================================================== +# ================================================================================== ################################################################################### # some configuration variables (could go to a seperate 'steering' file) # @@ -39,218 +39,218 @@ # input file: either .slcio or .stdhep # -------------------------------------- -lcioInputFile = 'mcparticles.slcio' -#lcioInputFile = 'bbudsc_3evt.stdhep' -#lcioInputFile = 'bbudsc_3evt_dd4hep.slcio' -#lcioInputFile = 'mcparticles_single_muon_5GeV_10deg.slcio' -#lcioInputFile = 'mcparticles_single_muon_5GeV_7deg.slcio' -#lcioInputFile = 'mcparticles_single_muon_5GeV_85deg.slcio' +lcioInputFile = "mcparticles.slcio" +# lcioInputFile = 'bbudsc_3evt.stdhep' +# lcioInputFile = 'bbudsc_3evt_dd4hep.slcio' +# lcioInputFile = 'mcparticles_single_muon_5GeV_10deg.slcio' +# lcioInputFile = 'mcparticles_single_muon_5GeV_7deg.slcio' +# lcioInputFile = 'mcparticles_single_muon_5GeV_85deg.slcio' -#lcioOutputFile = 'bbudsc_3evt_dd4hep_sim.slcio' -#lcioOutputFile = 'simpleCLIC_single_muon_5GeV_85deg.slcio' -#lcioOutputFile = 'simpleILD_single_muon_5GeV_85deg.slcio' -lcioOutputFile = 'simple_lcio.slcio' -#lcioOutputFile = lcioInputFile[:len(lcioInputFile)-len('.slcio')]+'_SIM.slcio' +# lcioOutputFile = 'bbudsc_3evt_dd4hep_sim.slcio' +# lcioOutputFile = 'simpleCLIC_single_muon_5GeV_85deg.slcio' +# lcioOutputFile = 'simpleILD_single_muon_5GeV_85deg.slcio' +lcioOutputFile = "simple_lcio.slcio" +# lcioOutputFile = lcioInputFile[:len(lcioInputFile)-len('.slcio')]+'_SIM.slcio' -physicsList = 'FTFP_BERT' # 'QGSP_BERT' +physicsList = "FTFP_BERT" # 'QGSP_BERT' -#---subset of detectors to initialize (all if list is empty) +# ---subset of detectors to initialize (all if list is empty) # this does not work, as the complete geometry form the compact.xml files # is already instantiated ... -#detectorList = [] -#detectorList = ['VTX','SIT','FTD'] +# detectorList = [] +# detectorList = ['VTX','SIT','FTD'] -#-------- dictionary for configuration variables used below ---------------------- +# -------- dictionary for configuration variables used below ---------------------- cfgDict = {} -#---- B field stepping ------- -cfgDict['field.stepper'] = "HelixSimpleRunge" -cfgDict['field.equation'] = "Mag_UsualEqRhs" -cfgDict['field.eps_min'] = 5e-05*mm -cfgDict['field.eps_max'] = 0.001*mm -cfgDict['field.min_chord_step'] = 0.01*mm -cfgDict['field.delta_chord'] = 0.25*mm -cfgDict['field.delta_intersection'] = 1e-05*mm -cfgDict['field.delta_one_step'] = 1e-04*mm +# ---- B field stepping ------- +cfgDict["field.stepper"] = "HelixSimpleRunge" +cfgDict["field.equation"] = "Mag_UsualEqRhs" +cfgDict["field.eps_min"] = 5e-05 * mm +cfgDict["field.eps_max"] = 0.001 * mm +cfgDict["field.min_chord_step"] = 0.01 * mm +cfgDict["field.delta_chord"] = 0.25 * mm +cfgDict["field.delta_intersection"] = 1e-05 * mm +cfgDict["field.delta_one_step"] = 1e-04 * mm # ################################################################################### -#================================================================================== +# ================================================================================== +def getDetectorLists(lcdd): + """get lists of trackers and calorimeters that are defined in lcdd (the compact xml file)""" + # if len(detectorList): + # print " subset list of detectors given - will only instantiate these: " , detectorList + t, c = [], [] + for i in lcdd.detectors(): + det = DDG4.DetElement(i.second) + name = det.name() + sd = lcdd.sensitiveDetector(name) + if sd.isValid(): + type = sd.type() + # if len(detectorList) and not(name in detectorList): + # continue + print("getDetectorLists - found active detctor ", name, " type: ", type) + if type == "tracker": + t.append(det.name()) + if type == "calorimeter": + c.append(det.name()) + return t, c -def getDetectorLists( lcdd ): - ''' get lists of trackers and calorimeters that are defined in lcdd (the compact xml file)''' -# if len(detectorList): -# print " subset list of detectors given - will only instantiate these: " , detectorList - t,c = [],[] - for i in lcdd.detectors(): - det = DDG4.DetElement(i.second) - name = det.name() - sd = lcdd.sensitiveDetector( name ) - if sd.isValid(): - type = sd.type() -# if len(detectorList) and not(name in detectorList): -# continue - print( 'getDetectorLists - found active detctor ' , name , ' type: ' , type) - if type == "tracker": - t.append( det.name() ) - if type == "calorimeter": - c.append( det.name() ) - return t,c +# ================================================================================== -#================================================================================== def run(): + kernel = DDG4.Kernel() - kernel = DDG4.Kernel() + try: + install_dir = os.environ["DD4hepINSTALL"] + # lcgeo_dir = os.environ['LCGEO'] + except KeyError: + print(" please set the environment variable DD4hepINSTALL ") + print(" to your DD4hep installation path ! ") + exit(1) - try: - install_dir = os.environ['DD4hepINSTALL'] -# lcgeo_dir = os.environ['LCGEO'] - except (KeyError): - print(" please set the environment variable DD4hepINSTALL ") - print( " to your DD4hep installation path ! ") - exit(1) + # example_dir = lcgeo_dir+'/example'; -# example_dir = lcgeo_dir+'/example'; + kernel.loadGeometry("file:" + compactFile) - kernel.loadGeometry("file:"+ compactFile ) + lcdd = kernel.lcdd() - lcdd = kernel.lcdd() + DDG4.importConstants(lcdd) - DDG4.importConstants( lcdd ) + # ---------------------------------------------------------------------------------- -#---------------------------------------------------------------------------------- + # simple = DDG4.Geant4( kernel, tracker='Geant4TrackerCombineAction',calo='Geant4ScintillatorCalorimeterAction') + ## Apply BirksLaw effect for Scintillator Calorimeter by using 'Geant4ScintillatorCalorimeterAction'. + simple = DDG4.Geant4( + kernel, + tracker="Geant4TrackerAction", + calo="Geant4ScintillatorCalorimeterAction", + ) -# simple = DDG4.Geant4( kernel, tracker='Geant4TrackerCombineAction',calo='Geant4ScintillatorCalorimeterAction') -## Apply BirksLaw effect for Scintillator Calorimeter by using 'Geant4ScintillatorCalorimeterAction'. - simple = DDG4.Geant4( kernel, tracker='Geant4TrackerAction',calo='Geant4ScintillatorCalorimeterAction') + simple.printDetectors() - simple.printDetectors() + # Configure UI + # simple.setupCshUI() + simple.setupUI() - # Configure UI - #simple.setupCshUI() - simple.setupUI() + kernel.UI = "" + kernel.NumEvents = numberOfEvents - kernel.UI="" - kernel.NumEvents=numberOfEvents + # ----------------------------------------------------------------------------------- + # setup the magnetic field: -#----------------------------------------------------------------------------------- -# setup the magnetic field: + field = simple.addConfig("Geant4FieldTrackingSetupAction/MagFieldTrackingSetup") + field.stepper = cfgDict["field.stepper"] + field.equation = cfgDict["field.equation"] + field.eps_min = cfgDict["field.eps_min"] + field.eps_max = cfgDict["field.eps_max"] + field.min_chord_step = cfgDict["field.min_chord_step"] + field.delta_chord = cfgDict["field.delta_chord"] + field.delta_intersection = cfgDict["field.delta_intersection"] + field.delta_one_step = cfgDict["field.delta_one_step"] - field = simple.addConfig('Geant4FieldTrackingSetupAction/MagFieldTrackingSetup') - field.stepper = cfgDict['field.stepper'] - field.equation = cfgDict['field.equation'] - field.eps_min = cfgDict['field.eps_min'] - field.eps_max = cfgDict['field.eps_max'] - field.min_chord_step = cfgDict['field.min_chord_step'] - field.delta_chord = cfgDict['field.delta_chord'] - field.delta_intersection = cfgDict['field.delta_intersection'] - field.delta_one_step = cfgDict['field.delta_one_step'] + # ---------------------------------------------------------------------------------- -#---------------------------------------------------------------------------------- + # Configure Run actions + run1 = DDG4.RunAction(kernel, "Geant4TestRunAction/RunInit") + kernel.registerGlobalAction(run1) + kernel.runAction().add(run1) - # Configure Run actions - run1 = DDG4.RunAction(kernel,'Geant4TestRunAction/RunInit') - kernel.registerGlobalAction(run1) - kernel.runAction().add(run1) + # Configure I/O + evt_lcio = simple.setupLCIOOutput("LcioOutput", lcioOutputFile) - # Configure I/O - evt_lcio = simple.setupLCIOOutput('LcioOutput', lcioOutputFile ) - - gen = DDG4.GeneratorAction(kernel,"LCIOInputAction/LCIO1") + gen = DDG4.GeneratorAction(kernel, "LCIOInputAction/LCIO1") - if( lcioInputFile[ (len(lcioInputFile)-6 ) : ] == ".slcio" ): - gen.Input="LCIOFileReader|"+lcioInputFile - else: - gen.Input="LCIOStdHepReader|"+lcioInputFile - - simple.buildInputStage( [gen] , output_level=DDG4.OutputLevel.INFO ) - -#================================================================================================ - - # And handle the simulation particles. - part = DDG4.GeneratorAction(kernel,"Geant4ParticleHandler/ParticleHandler") - kernel.generatorAction().adopt(part) - #part.SaveProcesses = ['conv','Decay'] - part.SaveProcesses = ['Decay'] - part.MinimalKineticEnergy = 100*MeV - part.OutputLevel = Output.INFO #generator_output_level - part.enableUI() - user = DDG4.Action(kernel,"Geant4TCUserParticleHandler/UserParticleHandler") - user.TrackingVolume_Zmax = DDG4.tracker_region_zmax - user.TrackingVolume_Rmax = DDG4.tracker_region_rmax -# user.enableUI() - part.adopt(user) - -#================================================================================= - - - # Setup global filters fur use in sensintive detectors - - f1 = DDG4.Filter(kernel,'GeantinoRejectFilter/GeantinoRejector') - kernel.registerGlobalFilter(f1) - - f4 = DDG4.Filter(kernel,'EnergyDepositMinimumCut') - f4.Cut = 1.*keV - kernel.registerGlobalFilter(f4) - - -#================================================================================= -# get lists of trackers and calorimeters in lcdd - - trk,cal = getDetectorLists( lcdd ) - -# ---- add the trackers: -# fixme: this assumes the same filters for all trackers ... - - for t in trk: - print( 'simple.setupTracker( ' , t , ')') - if( 'tpc' in t.lower() ): - seq,act = simple.setupTracker( t ,type='TPCSDAction') + if lcioInputFile[(len(lcioInputFile) - 6) :] == ".slcio": + gen.Input = "LCIOFileReader|" + lcioInputFile else: - seq,act = simple.setupTracker( t ) - seq.add(f1) - act.HitCreationMode = 2 - -# ---- add the calorimeters: - - for c in cal: - print( 'simple.setupCalorimeter( ' , c , ')') - if( 'ecal' in c.lower() ): - seq,act = simple.setupCalorimeter( c ,type='CaloPreShowerSDAction') - act.FirstLayerNumber = 1 - else: - seq,act = simple.setupCalorimeter( c ) - act.HitCreationMode = 2 - - -#================================================================================= - # Now build the physics list: - phys = simple.setupPhysics( physicsList ) - - #fg: do we need these really ? - #fg: ph = DDG4.PhysicsList(kernel,'Geant4PhysicsList/Myphysics') - #fg: ph.addParticleConstructor('G4BosonConstructor') - #fg: ph.addParticleConstructor('G4LeptonConstructor') - #fg: ph.addParticleProcess('e[+-]','G4eMultipleScattering',-1,1,1) - #fg: ph.addPhysicsConstructor('G4OpticalPhysics') - #fg: ph.enableUI() - #fg: phys.add(ph) - #fg: phys.dump() - - - kernel.configure() - kernel.initialize() + gen.Input = "LCIOStdHepReader|" + lcioInputFile + + simple.buildInputStage([gen], output_level=DDG4.OutputLevel.INFO) + + # ================================================================================================ + + # And handle the simulation particles. + part = DDG4.GeneratorAction(kernel, "Geant4ParticleHandler/ParticleHandler") + kernel.generatorAction().adopt(part) + # part.SaveProcesses = ['conv','Decay'] + part.SaveProcesses = ["Decay"] + part.MinimalKineticEnergy = 100 * MeV + part.OutputLevel = Output.INFO # generator_output_level + part.enableUI() + user = DDG4.Action(kernel, "Geant4TCUserParticleHandler/UserParticleHandler") + user.TrackingVolume_Zmax = DDG4.tracker_region_zmax + user.TrackingVolume_Rmax = DDG4.tracker_region_rmax + # user.enableUI() + part.adopt(user) + + # ================================================================================= + + # Setup global filters fur use in sensintive detectors + + f1 = DDG4.Filter(kernel, "GeantinoRejectFilter/GeantinoRejector") + kernel.registerGlobalFilter(f1) + + f4 = DDG4.Filter(kernel, "EnergyDepositMinimumCut") + f4.Cut = 1.0 * keV + kernel.registerGlobalFilter(f4) + + # ================================================================================= + # get lists of trackers and calorimeters in lcdd + + trk, cal = getDetectorLists(lcdd) + + # ---- add the trackers: + # fixme: this assumes the same filters for all trackers ... + + for t in trk: + print("simple.setupTracker( ", t, ")") + if "tpc" in t.lower(): + seq, act = simple.setupTracker(t, type="TPCSDAction") + else: + seq, act = simple.setupTracker(t) + seq.add(f1) + act.HitCreationMode = 2 + + # ---- add the calorimeters: + + for c in cal: + print("simple.setupCalorimeter( ", c, ")") + if "ecal" in c.lower(): + seq, act = simple.setupCalorimeter(c, type="CaloPreShowerSDAction") + act.FirstLayerNumber = 1 + else: + seq, act = simple.setupCalorimeter(c) + act.HitCreationMode = 2 + + # ================================================================================= + # Now build the physics list: + phys = simple.setupPhysics(physicsList) + + # fg: do we need these really ? + # fg: ph = DDG4.PhysicsList(kernel,'Geant4PhysicsList/Myphysics') + # fg: ph.addParticleConstructor('G4BosonConstructor') + # fg: ph.addParticleConstructor('G4LeptonConstructor') + # fg: ph.addParticleProcess('e[+-]','G4eMultipleScattering',-1,1,1) + # fg: ph.addPhysicsConstructor('G4OpticalPhysics') + # fg: ph.enableUI() + # fg: phys.add(ph) + # fg: phys.dump() + + kernel.configure() + kernel.initialize() + + # DDG4.setPrintLevel(Output.DEBUG) + kernel.run() + kernel.terminate() - #DDG4.setPrintLevel(Output.DEBUG) - kernel.run() - kernel.terminate() if __name__ == "__main__": - run() + run() diff --git a/example/guineapig_to_lcio.py b/example/guineapig_to_lcio.py index 47e3308b6..e2ee1b96b 100755 --- a/example/guineapig_to_lcio.py +++ b/example/guineapig_to_lcio.py @@ -2,7 +2,7 @@ ####################################################### # # simple script to read guineapig pair background files -# and convert them to LCIO files +# and convert them to LCIO files # # @author F.Gaede, DESY # @date 18/01/2017 @@ -20,93 +20,86 @@ from pyLCIO import UTIL, EVENT, IMPL, IO, IOIMPL - -#================================================ -if len( sys.argv ) < 2: +# ================================================ +if len(sys.argv) < 2: print(" usage: python guineapig_to_lcio.py eepair_guineapig.pair ") sys.exit(0) -#================================================= +# ================================================= infile = sys.argv[1] outfile = infile + ".slcio" -wrt = IOIMPL.LCFactory.getInstance().createLCWriter( ) -wrt.open( outfile , EVENT.LCIO.WRITE_NEW ) -col = IMPL.LCCollectionVec( EVENT.LCIO.MCPARTICLE ) +wrt = IOIMPL.LCFactory.getInstance().createLCWriter() +wrt.open(outfile, EVENT.LCIO.WRITE_NEW) +col = IMPL.LCCollectionVec(EVENT.LCIO.MCPARTICLE) -evt = IMPL.LCEventImpl() -evt.setEventNumber( 0 ) +evt = IMPL.LCEventImpl() +evt.setEventNumber(0) -evt.addCollection( col , "MCParticle" ) +evt.addCollection(col, "MCParticle") -# --- +# --- -f = open( infile , 'r' ) +f = open(infile, "r") for lin in f: - d = lin.split() -# print d + # print d - energy = float( d[0] ) - betaX = float( d[1] ) - betaY = float( d[2] ) - betaZ = float( d[3] ) - posX = float( d[4] ) - posY = float( d[5] ) - posZ = float( d[6] ) + energy = float(d[0]) + betaX = float(d[1]) + betaY = float(d[2]) + betaZ = float(d[3]) + posX = float(d[4]) + posY = float(d[5]) + posZ = float(d[6]) -# ---- + # ---- pdg = 11 - charge = -1. + charge = -1.0 if energy < 0: pdg = -11 - energy = - energy - charge = 1. + energy = -energy + charge = 1.0 -#--- + # --- px = betaX * energy py = betaY * energy pz = betaZ * energy - momentum = array('f',[ px, py, pz ] ) + momentum = array("f", [px, py, pz]) - nm2mm = 1e-6 + nm2mm = 1e-6 vtxx = nm2mm * posX vtxy = nm2mm * posY vtxz = nm2mm * posZ - vertex = array('d',[vtxx, vtxy, vtxz ] ) - - - -#--------------- create MCParticle ------------------- - - mcp = IMPL.MCParticleImpl() + vertex = array("d", [vtxx, vtxy, vtxz]) - mcp.setGeneratorStatus(1) + # --------------- create MCParticle ------------------- - mcp.setMass( 0.0005109989461 ) - - mcp.setPDG( pdg ) + mcp = IMPL.MCParticleImpl() - mcp.setMomentum( momentum ) - mcp.setVertex( vertex ) - mcp.setCharge( charge ) + mcp.setGeneratorStatus(1) + mcp.setMass(0.0005109989461) -#------------------------------------------------------- + mcp.setPDG(pdg) + mcp.setMomentum(momentum) + mcp.setVertex(vertex) + mcp.setCharge(charge) - col.addElement( mcp ) + # ------------------------------------------------------- + col.addElement(mcp) -wrt.writeEvent( evt ) -wrt.close() +wrt.writeEvent(evt) +wrt.close() diff --git a/example/lcio_particle_gun.py b/example/lcio_particle_gun.py index b72a5c27f..2a9b47970 100644 --- a/example/lcio_particle_gun.py +++ b/example/lcio_particle_gun.py @@ -16,105 +16,98 @@ # --- LCIO dependencies --- from pyLCIO import UTIL, EVENT, IMPL, IO, IOIMPL -#---- number of events per momentum bin ----- +# ---- number of events per momentum bin ----- nevt = 1000 outfile = "mcparticles.slcio" -#-------------------------------------------- +# -------------------------------------------- -wrt = IOIMPL.LCFactory.getInstance().createLCWriter( ) +wrt = IOIMPL.LCFactory.getInstance().createLCWriter() -wrt.open( outfile , EVENT.LCIO.WRITE_NEW ) +wrt.open(outfile, EVENT.LCIO.WRITE_NEW) -print( " opened outfile: " , outfile ) +print(" opened outfile: ", outfile) random.seed() -#========== particle properties =================== +# ========== particle properties =================== -#momenta = [ 1. , 3., 5., 10., 15., 25., 50., 100. ] -momenta = [ 5. ] +# momenta = [ 1. , 3., 5., 10., 15., 25., 50., 100. ] +momenta = [5.0] -genstat = 1 +genstat = 1 pdg = -13 -charge = +1. -#pdg = 211 -mass = 0.105658 -theta = 85./180. * math.pi -#theta = 20./180. * math.pi +charge = +1.0 +# pdg = 211 +mass = 0.105658 +theta = 85.0 / 180.0 * math.pi +# theta = 20./180. * math.pi -decayLen = 1.e32 -#================================================= +decayLen = 1.0e32 +# ================================================= # write a RunHeader -run = IMPL.LCRunHeaderImpl() -run.setRunNumber( 0 ) -run.parameters().setValue("Generator","${lcgeo}_DIR/examples/lcio_particle_gun.py") -run.parameters().setValue("PDG", pdg ) -run.parameters().setValue("Charge", charge ) -run.parameters().setValue("Mass", mass ) -wrt.writeRunHeader( run ) -#================================================ +run = IMPL.LCRunHeaderImpl() +run.setRunNumber(0) +run.parameters().setValue("Generator", "${lcgeo}_DIR/examples/lcio_particle_gun.py") +run.parameters().setValue("PDG", pdg) +run.parameters().setValue("Charge", charge) +run.parameters().setValue("Mass", mass) +wrt.writeRunHeader(run) +# ================================================ for p in momenta: - - for j in range( 0, nevt ): + for j in range(0, nevt): + col = IMPL.LCCollectionVec(EVENT.LCIO.MCPARTICLE) + evt = IMPL.LCEventImpl() - col = IMPL.LCCollectionVec( EVENT.LCIO.MCPARTICLE ) - evt = IMPL.LCEventImpl() + evt.setEventNumber(j) - evt.setEventNumber( j ) + evt.addCollection(col, "MCParticle") - evt.addCollection( col , "MCParticle" ) + phi = random.random() * math.pi * 2.0 - phi = random.random() * math.pi * 2. - - energy = math.sqrt( mass*mass + p * p ) - - px = p * math.cos( phi ) * math.sin( theta ) - py = p * math.sin( phi ) * math.sin( theta ) - pz = p * math.cos( theta ) + energy = math.sqrt(mass * mass + p * p) - momentum = array('f',[ px, py, pz ] ) + px = p * math.cos(phi) * math.sin(theta) + py = p * math.sin(phi) * math.sin(theta) + pz = p * math.cos(theta) - epx = decayLen * math.cos( phi ) * math.sin( theta ) - epy = decayLen * math.sin( phi ) * math.sin( theta ) - epz = decayLen * math.cos( theta ) + momentum = array("f", [px, py, pz]) - endpoint = array('d',[ epx, epy, epz ] ) - + epx = decayLen * math.cos(phi) * math.sin(theta) + epy = decayLen * math.sin(phi) * math.sin(theta) + epz = decayLen * math.cos(theta) -#--------------- create MCParticle ------------------- - - mcp = IMPL.MCParticleImpl() + endpoint = array("d", [epx, epy, epz]) - mcp.setGeneratorStatus( genstat ) - mcp.setMass( mass ) - mcp.setPDG( pdg ) - mcp.setMomentum( momentum ) - mcp.setCharge( charge ) + # --------------- create MCParticle ------------------- - if( decayLen < 1.e9 ) : # arbitrary ... - mcp.setEndpoint( endpoint ) + mcp = IMPL.MCParticleImpl() + mcp.setGeneratorStatus(genstat) + mcp.setMass(mass) + mcp.setPDG(pdg) + mcp.setMomentum(momentum) + mcp.setCharge(charge) -#------------------------------------------------------- + if decayLen < 1.0e9: # arbitrary ... + mcp.setEndpoint(endpoint) - + # ------------------------------------------------------- -#------------------------------------------------------- + # ------------------------------------------------------- + col.addElement(mcp) - col.addElement( mcp ) + wrt.writeEvent(evt) - wrt.writeEvent( evt ) - -wrt.close() +wrt.close() # @@ -138,10 +131,10 @@ # double VHEP3; // z vertex position in mm # double VHEP4; // production time in mm/c # -# inputFile >> ISTHEP >> IDHEP +# inputFile >> ISTHEP >> IDHEP # >> JMOHEP1 >> JMOHEP2 # >> JDAHEP1 >> JDAHEP2 -# >> PHEP1 >> PHEP2 >> PHEP3 +# >> PHEP1 >> PHEP2 >> PHEP3 # >> PHEP4 >> PHEP5 # >> VHEP1 >> VHEP2 >> VHEP3 # >> VHEP4; diff --git a/example/steeringFile.py b/example/steeringFile.py index 47530cfed..1ea22d36b 100644 --- a/example/steeringFile.py +++ b/example/steeringFile.py @@ -2,44 +2,53 @@ from g4units import mm, GeV, MeV, keV SIM = DD4hepSimulation() -SIM.compactFile = "/data/sailer/software/LCGeo_Auth/ILD/compact/ILD_o1_v05/ILD_o1_v05.xml" +SIM.compactFile = ( + "/data/sailer/software/LCGeo_Auth/ILD/compact/ILD_o1_v05/ILD_o1_v05.xml" +) SIM.runType = "batch" SIM.numberOfEvents = 2 -SIM.field.eps_min = .001*mm +SIM.field.eps_min = 0.001 * mm SIM.gun.multiplicity = 1 -SIM.gun.energy = 40*GeV +SIM.gun.energy = 40 * GeV SIM.gun.direction = (1.0, 1.0, 1.0) SIM.enableGun = True -SIM.part.minimalKineticEnergy = 1*MeV +SIM.part.minimalKineticEnergy = 1 * MeV -SIM.action.mapActions['tpc'] = "TPCSDAction" +SIM.action.mapActions["tpc"] = "TPCSDAction" ## if there is a user provided SDAction which needs additional parameters these can be passed as a dictionary -SIM.action.mapActions['ecal'] = ( "CaloPreShowerSDAction", {"FirstLayerNumber": 1} ) +SIM.action.mapActions["ecal"] = ("CaloPreShowerSDAction", {"FirstLayerNumber": 1}) ## add filter to sensitive detectors: # Either assign dict -SIM.filter.mapDetFilter = {"VXD": "edep1kev"} ## default filter +SIM.filter.mapDetFilter = {"VXD": "edep1kev"} ## default filter # or use bracket operator -SIM.filter.mapDetFilter['VXD'] = "edep1kev" ## default filter -SIM.filter.mapDetFilter['FTD'] = ["edep3kev","geantino"] ## custom filter +SIM.filter.mapDetFilter["VXD"] = "edep1kev" ## default filter +SIM.filter.mapDetFilter["FTD"] = ["edep3kev", "geantino"] ## custom filter -#create your own filter with a dict containing name and parameter -SIM.filter.filters['edep3kev'] = dict(name="EnergyDepositMinimumCut/3keV", parameter={"Cut": 3.0*keV} ) +# create your own filter with a dict containing name and parameter +SIM.filter.filters["edep3kev"] = dict( + name="EnergyDepositMinimumCut/3keV", parameter={"Cut": 3.0 * keV} +) -#chose the physicslist and range cut +# chose the physicslist and range cut SIM.physics.list = "FTFP_BERT" -SIM.physics.rangecut = 1*mm +SIM.physics.rangecut = 1 * mm ## set the particle.tbl file to add extra particles to DDsim (B-Baryons) ## use the power of python to get the file from DD4hep wherever it is import os -if os.path.exists( os.path.join( os.environ.get("DD4hepINSTALL"), "examples/DDG4/examples/particle.tbl") ): - SIM.physics.pdgfile = os.path.join( os.environ.get("DD4hepINSTALL"), "examples/DDG4/examples/particle.tbl") + +if os.path.exists( + os.path.join(os.environ.get("DD4hepINSTALL"), "examples/DDG4/examples/particle.tbl") +): + SIM.physics.pdgfile = os.path.join( + os.environ.get("DD4hepINSTALL"), "examples/DDG4/examples/particle.tbl" + ) ## Add parameters to the run header ## This will store the Parameter "MyNewParameter" in the runHeader of the slcio file diff --git a/utils/dd4hep2root.py b/utils/dd4hep2root.py index a251d8484..ec6c4cd1d 100755 --- a/utils/dd4hep2root.py +++ b/utils/dd4hep2root.py @@ -1,8 +1,8 @@ #!/usr/bin/env python3 -### Script to generate ROOT file with detector geometry from detector xml file, +### Script to generate ROOT file with detector geometry from detector xml file, ### from https://fccsw.web.cern.ch/fccsw/tutorials/static/python/dd4hep2root -### usage described in FCC software tutorial: +### usage described in FCC software tutorial: ### https://hep-fcc.github.io/fcc-tutorials/master/full-detector-simulations/Visualization/Visualization.html#detector-geometry import sys @@ -10,23 +10,31 @@ def main(): - parser = argparse.ArgumentParser(description='Convert detector') - parser.add_argument('-c', '--compact', help='Compact file location(s)', - required=True, type=str, nargs='+') - parser.add_argument('-o', '--out', help='Converted file path', - default='detector.root', type=str) + parser = argparse.ArgumentParser(description="Convert detector") + parser.add_argument( + "-c", + "--compact", + help="Compact file location(s)", + required=True, + type=str, + nargs="+", + ) + parser.add_argument( + "-o", "--out", help="Converted file path", default="detector.root", type=str + ) args = parser.parse_args() - + convert(args.compact, args.out) + def convert(compact_files, out_path): - print('INFO: Converting following compact file(s):') + print("INFO: Converting following compact file(s):") for cfile in compact_files: - print(' ' + cfile) + print(" " + cfile) import ROOT - ROOT.gSystem.Load('libDDCore') + ROOT.gSystem.Load("libDDCore") description = ROOT.dd4hep.Detector.getInstance() for cfile in compact_files: description.fromXML(cfile) @@ -36,5 +44,5 @@ def convert(compact_files, out_path): ROOT.gGeoManager.Export(out_path) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/utils/material_plots.py b/utils/material_plots.py index 580746d22..6f05e9bb6 100644 --- a/utils/material_plots.py +++ b/utils/material_plots.py @@ -1,22 +1,66 @@ from __future__ import print_function import argparse -import sys,os +import sys, os + sys.path.append(os.path.expandvars("$FCCSW") + "/Examples/scripts") from plotstyle import FCCStyle import ROOT + def main(): - parser = argparse.ArgumentParser(description='Material Plotter') - parser.add_argument('--fname', "-f", dest='fname', type=str, help="name of file to read") - parser.add_argument('--angleMin', dest='angleMin', default=-6, type=float, help="minimum eta/theta/cosTheta") - parser.add_argument('--angleMax', dest='angleMax', default=6, type=float, help="maximum eta/theta/cosTheta") - parser.add_argument('--angleDef', dest='angleDef', default="eta", type=str, help="angle definition to use: eta, theta, cosTheta or thetaRad, default: eta") - parser.add_argument('--angleBinning', "-b", dest='angleBinning', default=0.05, type=float, help="eta/theta/cosTheta/thetaRad bin width") - parser.add_argument('--x0max', "-x", dest='x0max', default=0.0, type=float, help="Max of x0") - parser.add_argument('--removeMatsSubstrings', dest='removeMatsSubstrings', nargs='+', default=[], help="Substrings to be removed from materials strings (e.g. '66D' for reduced density materials)") - parser.add_argument('--ignoreMats', "-i", dest='ignoreMats', nargs='+', default=[], help="List of materials that should be ignored") + parser = argparse.ArgumentParser(description="Material Plotter") + parser.add_argument( + "--fname", "-f", dest="fname", type=str, help="name of file to read" + ) + parser.add_argument( + "--angleMin", + dest="angleMin", + default=-6, + type=float, + help="minimum eta/theta/cosTheta", + ) + parser.add_argument( + "--angleMax", + dest="angleMax", + default=6, + type=float, + help="maximum eta/theta/cosTheta", + ) + parser.add_argument( + "--angleDef", + dest="angleDef", + default="eta", + type=str, + help="angle definition to use: eta, theta, cosTheta or thetaRad, default: eta", + ) + parser.add_argument( + "--angleBinning", + "-b", + dest="angleBinning", + default=0.05, + type=float, + help="eta/theta/cosTheta/thetaRad bin width", + ) + parser.add_argument( + "--x0max", "-x", dest="x0max", default=0.0, type=float, help="Max of x0" + ) + parser.add_argument( + "--removeMatsSubstrings", + dest="removeMatsSubstrings", + nargs="+", + default=[], + help="Substrings to be removed from materials strings (e.g. '66D' for reduced density materials)", + ) + parser.add_argument( + "--ignoreMats", + "-i", + dest="ignoreMats", + nargs="+", + default=[], + help="List of materials that should be ignored", + ) args = parser.parse_args() f = ROOT.TFile.Open(args.fname, "read") @@ -34,7 +78,7 @@ def main(): # Removing substrings from materials for substring in args.removeMatsSubstrings: - material = material.replace(substring,"") + material = material.replace(substring, "") # Ignore certain materials if specified if material in args.ignoreMats: @@ -42,31 +86,62 @@ def main(): if material not in histDict.keys(): histDict[material] = { - "x0": ROOT.TH1F("", "", (int)((args.angleMax-args.angleMin) / args.angleBinning), args.angleMin, args.angleMax), - "lambda": ROOT.TH1F("", "", (int)((args.angleMax-args.angleMin) / args.angleBinning), args.angleMin, args.angleMax), - "depth": ROOT.TH1F("", "", (int)((args.angleMax-args.angleMin) / args.angleBinning), args.angleMin, args.angleMax) + "x0": ROOT.TH1F( + "", + "", + (int)((args.angleMax - args.angleMin) / args.angleBinning), + args.angleMin, + args.angleMax, + ), + "lambda": ROOT.TH1F( + "", + "", + (int)((args.angleMax - args.angleMin) / args.angleBinning), + args.angleMin, + args.angleMax, + ), + "depth": ROOT.TH1F( + "", + "", + (int)((args.angleMax - args.angleMin) / args.angleBinning), + args.angleMin, + args.angleMax, + ), } hs = histDict[material] - hs["x0"].SetBinContent(angleBinning+1, hs["x0"].GetBinContent(angleBinning+1) + entry.nX0.at(i)*100.0) - hs["lambda"].SetBinContent(angleBinning+1, hs["lambda"].GetBinContent(angleBinning+1) + entry.nLambda.at(i)) - hs["depth"].SetBinContent(angleBinning+1, hs["depth"].GetBinContent(angleBinning+1) + entry.matDepth.at(i)) - - axis_titles = ["Material budget x/X_{0} [%] ", "Number of #lambda", "Material depth [cm]"] + hs["x0"].SetBinContent( + angleBinning + 1, + hs["x0"].GetBinContent(angleBinning + 1) + entry.nX0.at(i) * 100.0, + ) + hs["lambda"].SetBinContent( + angleBinning + 1, + hs["lambda"].GetBinContent(angleBinning + 1) + entry.nLambda.at(i), + ) + hs["depth"].SetBinContent( + angleBinning + 1, + hs["depth"].GetBinContent(angleBinning + 1) + entry.matDepth.at(i), + ) + + axis_titles = [ + "Material budget x/X_{0} [%] ", + "Number of #lambda", + "Material depth [cm]", + ] # This loop does the drawing, sets the style and saves the pdf files for plot, title in zip(["x0", "lambda", "depth"], axis_titles): - if args.angleDef=="eta": - xtitle="#eta" - legend = ROOT.TLegend(.2, .6, .5, .94) - elif args.angleDef=="theta": - xtitle="#theta" - legend = ROOT.TLegend(.5, .6, .8, .94) - elif args.angleDef=="thetaRad": - xtitle="#theta [rad]" - legend = ROOT.TLegend(.5, .6, .8, .94) - elif args.angleDef=="cosTheta": - xtitle="cos(#theta)" - legend = ROOT.TLegend(.2, .6, .5, .94) + if args.angleDef == "eta": + xtitle = "#eta" + legend = ROOT.TLegend(0.2, 0.6, 0.5, 0.94) + elif args.angleDef == "theta": + xtitle = "#theta" + legend = ROOT.TLegend(0.5, 0.6, 0.8, 0.94) + elif args.angleDef == "thetaRad": + xtitle = "#theta [rad]" + legend = ROOT.TLegend(0.5, 0.6, 0.8, 0.94) + elif args.angleDef == "cosTheta": + xtitle = "cos(#theta)" + legend = ROOT.TLegend(0.2, 0.6, 0.5, 0.94) legend.SetLineColor(0) ths = ROOT.THStack() @@ -75,8 +150,19 @@ def main(): reorder = False histDict_ordered = {} if reorder: - order = ["Silicon", "CarbonFiber", "CarbonFleece", "Rohacell", "Aluminum", "GlueEcobond45", "Kapton", "Water"] - ordered_list = sorted(histDict.items(), key=lambda pair: order.index(pair[0])) + order = [ + "Silicon", + "CarbonFiber", + "CarbonFleece", + "Rohacell", + "Aluminum", + "GlueEcobond45", + "Kapton", + "Water", + ] + ordered_list = sorted( + histDict.items(), key=lambda pair: order.index(pair[0]) + ) for key, value in ordered_list: histDict_ordered[key] = value @@ -87,7 +173,7 @@ def main(): # Make the plots for i, material in enumerate(histDict_ordered.keys()): linecolor = 1 - fillcolor = FCCStyle.fillcolors[i if i<7 else 0] + fillcolor = FCCStyle.fillcolors[i if i < 7 else 0] # If you want to map a material to a specific color, do that here match material: @@ -100,15 +186,15 @@ def main(): case "Rohacell": fillcolor = FCCStyle.fillcolors[4] case "Silicon": - fillcolor = FCCStyle.fillcolors[2] + fillcolor = FCCStyle.fillcolors[2] case "Aluminum": fillcolor = FCCStyle.fillcolors[1] case "Kapton": fillcolor = FCCStyle.fillcolors[3] case "GlueEcobond45": - fillcolor = FCCStyle.fillcolors[6] + fillcolor = FCCStyle.fillcolors[6] case "Water": - fillcolor = FCCStyle.fillcolors[5] + fillcolor = FCCStyle.fillcolors[5] case "PCB": fillcolor = ROOT.kGreen @@ -129,7 +215,7 @@ def main(): legend.SetTextSize(0.04) legend.Draw() - if args.x0max != 0.0 and plot=="x0": + if args.x0max != 0.0 and plot == "x0": ths.SetMaximum(args.x0max) ths.GetXaxis().SetRangeUser(args.angleMin, args.angleMax) @@ -137,6 +223,7 @@ def main(): cv.Print(plot + ".png") cv.SaveAs(plot + ".root") + if __name__ == "__main__": FCCStyle.initialize() main() diff --git a/utils/material_plots_2D.py b/utils/material_plots_2D.py index d87e549f5..2b02e5b8a 100644 --- a/utils/material_plots_2D.py +++ b/utils/material_plots_2D.py @@ -2,22 +2,65 @@ import argparse import math -import sys,os +import sys, os + sys.path.append(os.path.expandvars("$FCCSW") + "/Examples/scripts") from plotstyle import FCCStyle import ROOT def main(): - parser = argparse.ArgumentParser(description='Material Plotter') - parser.add_argument('--fname', "-f", dest='fname', type=str, help="name of file to read") - parser.add_argument('--angleMin', dest='angleMin', default=6, type=float, help="minimum eta/theta/cosTheta") - parser.add_argument('--angleMax', dest='angleMax', default=6, type=float, help="maximum eta/theta/cosTheta") - parser.add_argument('--angleDef', dest='angleDef', default="eta", type=str, help="angle definition to use: eta, theta or cosTheta, default: eta") - parser.add_argument('--angleBinning', "-b", dest='angleBinning', default=0.05, type=float, help="eta/theta/cosTheta bin width") - parser.add_argument('--nPhiBins', dest='nPhiBins', default=100, type=int, help="number of bins in phi") - parser.add_argument('--x0max', "-x", dest='x0max', default=0.0, type=float, help="Max of x0") - parser.add_argument('--ignoreMats', "-i", dest='ignoreMats', nargs='+', default=[], help="List of materials that should be ignored") + parser = argparse.ArgumentParser(description="Material Plotter") + parser.add_argument( + "--fname", "-f", dest="fname", type=str, help="name of file to read" + ) + parser.add_argument( + "--angleMin", + dest="angleMin", + default=6, + type=float, + help="minimum eta/theta/cosTheta", + ) + parser.add_argument( + "--angleMax", + dest="angleMax", + default=6, + type=float, + help="maximum eta/theta/cosTheta", + ) + parser.add_argument( + "--angleDef", + dest="angleDef", + default="eta", + type=str, + help="angle definition to use: eta, theta or cosTheta, default: eta", + ) + parser.add_argument( + "--angleBinning", + "-b", + dest="angleBinning", + default=0.05, + type=float, + help="eta/theta/cosTheta bin width", + ) + parser.add_argument( + "--nPhiBins", + dest="nPhiBins", + default=100, + type=int, + help="number of bins in phi", + ) + parser.add_argument( + "--x0max", "-x", dest="x0max", default=0.0, type=float, help="Max of x0" + ) + parser.add_argument( + "--ignoreMats", + "-i", + dest="ignoreMats", + nargs="+", + default=[], + help="List of materials that should be ignored", + ) args = parser.parse_args() ROOT.gStyle.SetNumberContours(100) @@ -28,9 +71,36 @@ def main(): ROOT.gROOT.SetBatch(1) - h_x0 = ROOT.TH2F("h_x0","h_x0", int((args.angleMax-args.angleMin)/args.angleBinning),args.angleMin,args.angleMax,args.nPhiBins,-math.pi,math.pi) - h_lambda = ROOT.TH2F("h_lambda","h_lambda", int((args.angleMax-args.angleMin)/args.angleBinning),args.angleMin,args.angleMax,args.nPhiBins,-math.pi,math.pi) - h_depth = ROOT.TH2F("h_depth","h_depth", int((args.angleMax-args.angleMin)/args.angleBinning),args.angleMin,args.angleMax,args.nPhiBins,-math.pi,math.pi) + h_x0 = ROOT.TH2F( + "h_x0", + "h_x0", + int((args.angleMax - args.angleMin) / args.angleBinning), + args.angleMin, + args.angleMax, + args.nPhiBins, + -math.pi, + math.pi, + ) + h_lambda = ROOT.TH2F( + "h_lambda", + "h_lambda", + int((args.angleMax - args.angleMin) / args.angleBinning), + args.angleMin, + args.angleMax, + args.nPhiBins, + -math.pi, + math.pi, + ) + h_depth = ROOT.TH2F( + "h_depth", + "h_depth", + int((args.angleMax - args.angleMin) / args.angleBinning), + args.angleMin, + args.angleMax, + args.nPhiBins, + -math.pi, + math.pi, + ) for angleBinning, entry in enumerate(tree): nMat = entry.nMaterials @@ -41,35 +111,39 @@ def main(): if entry.material.at(i) in args.ignoreMats: continue - entry_x0 += entry.nX0.at(i)*100.0 - entry_lambda += entry.nLambda.at(i) - entry_depth += entry.matDepth.at(i) + entry_x0 += entry.nX0.at(i) * 100.0 + entry_lambda += entry.nLambda.at(i) + entry_depth += entry.matDepth.at(i) - h_x0.Fill(tree.angle,tree.phi,entry_x0) - h_lambda.Fill(tree.angle,tree.phi,entry_lambda) - h_depth.Fill(tree.angle,tree.phi,entry_depth) + h_x0.Fill(tree.angle, tree.phi, entry_x0) + h_lambda.Fill(tree.angle, tree.phi, entry_lambda) + h_depth.Fill(tree.angle, tree.phi, entry_depth) - # go through the + # go through the plots = ["x0", "lambda", "depth"] histograms = [h_x0, h_lambda, h_depth] - axis_titles = ["Material budget x/X_{0} [%]", "Number of #lambda", "Material depth [cm]"] + axis_titles = [ + "Material budget x/X_{0} [%]", + "Number of #lambda", + "Material depth [cm]", + ] for i in range(len(plots)): - cv = ROOT.TCanvas("","",800,600) + cv = ROOT.TCanvas("", "", 800, 600) cv.SetRightMargin(0.18) histograms[i].Draw("COLZ") - if args.angleDef=="eta": - title="#eta" - elif args.angleDef=="theta": - title="#theta [#circ]" - elif args.angleDef=="cosTheta": - title="cos(#theta)" + if args.angleDef == "eta": + title = "#eta" + elif args.angleDef == "theta": + title = "#theta [#circ]" + elif args.angleDef == "cosTheta": + title = "cos(#theta)" histograms[i].GetXaxis().SetTitle(title) histograms[i].GetYaxis().SetTitle("#phi") histograms[i].GetZaxis().SetTitle(axis_titles[i]) - if args.x0max != 0.0 and plots[i]=="x0": + if args.x0max != 0.0 and plots[i] == "x0": histograms[i].SetMaximum(args.x0max) histograms[i].GetXaxis().SetRangeUser(args.angleMin, args.angleMax) @@ -79,6 +153,7 @@ def main(): cv.Print(plots[i] + ".png") cv.SaveAs(plots[i] + ".root") + if __name__ == "__main__": FCCStyle.initialize() main() diff --git a/utils/material_scan.py b/utils/material_scan.py index 25ea63563..cf33f6e92 100644 --- a/utils/material_scan.py +++ b/utils/material_scan.py @@ -2,22 +2,23 @@ from Gaudi.Configuration import * from Configurables import ApplicationMgr -ApplicationMgr().EvtSel = 'None' + +ApplicationMgr().EvtSel = "None" ApplicationMgr().EvtMax = 1 ApplicationMgr().OutputLevel = INFO # DD4hep geometry service from Configurables import GeoSvc + ## parse the given xml file geoservice = GeoSvc("GeoSvc") -geoservice.detectors = [ - 'IDEA_o1_v02.xml' - ] -geoservice.OutputLevel = INFO +geoservice.detectors = ["IDEA_o1_v02.xml"] +geoservice.OutputLevel = INFO ApplicationMgr().ExtSvc += [geoservice] # Using material scan from k4SimGeant4: https://github.com/HEP-FCC/k4SimGeant4/tree/main/Detector/DetComponents/src from Configurables import MaterialScan_genericAngle + # Material scan is done from the interaction point to the end of world volume. # In order to use other end boundary, please provide the name of a thin, e.g. cylindrical volume. # For instance adding envelopeName="BoundaryPostCalorimetry" will perform the scan only till the end of calorimetry. @@ -28,7 +29,5 @@ materialservice.angleMin = -3.0 materialservice.angleMax = 3.0 materialservice.nPhiTrials = 100 -materialservice.angleDef = "eta" # eta or cosTheta or theta or thetaRad +materialservice.angleDef = "eta" # eta or cosTheta or theta or thetaRad ApplicationMgr().ExtSvc += [materialservice] - - diff --git a/utils/material_scan_2D.py b/utils/material_scan_2D.py index 041a786ee..ab6ee21eb 100644 --- a/utils/material_scan_2D.py +++ b/utils/material_scan_2D.py @@ -2,22 +2,23 @@ from Gaudi.Configuration import * from Configurables import ApplicationMgr -ApplicationMgr().EvtSel = 'None' + +ApplicationMgr().EvtSel = "None" ApplicationMgr().EvtMax = 1 ApplicationMgr().OutputLevel = INFO # DD4hep geometry service from Configurables import GeoSvc + ## parse the given xml file geoservice = GeoSvc("GeoSvc") -geoservice.detectors = [ - 'IDEA_o1_v02.xml' - ] -geoservice.OutputLevel = INFO +geoservice.detectors = ["IDEA_o1_v02.xml"] +geoservice.OutputLevel = INFO ApplicationMgr().ExtSvc += [geoservice] # Using material scan from k4SimGeant4: https://github.com/HEP-FCC/k4SimGeant4/tree/main/Detector/DetComponents/src from Configurables import MaterialScan_2D_genericAngle + # Material scan is done from the interaction point to the end of world volume. # In order to use other end boundary, please provide the name of a thin, e.g. cylindrical volume. # For instance adding envelopeName="BoundaryPostCalorimetry" will perform the scan only till the end of calorimetry. @@ -25,12 +26,10 @@ materialservice = MaterialScan_2D_genericAngle("GeoDump") materialservice.filename = "out_material_scan.root" -materialservice.angleDef = 'eta' # eta, theta, cosTheta or thetaRad +materialservice.angleDef = "eta" # eta, theta, cosTheta or thetaRad materialservice.angleBinning = 0.05 materialservice.angleMax = 3.0 materialservice.angleMin = -3.0 -materialservice.nPhi = 100 # number of bins in phi +materialservice.nPhi = 100 # number of bins in phi ApplicationMgr().ExtSvc += [materialservice] - -