Skip to content

Instantly share code, notes, and snippets.

@lgray
Last active August 18, 2022 21:17
Show Gist options
  • Select an option

  • Save lgray/7c70092f76d6dea573279f206691344f to your computer and use it in GitHub Desktop.

Select an option

Save lgray/7c70092f76d6dea573279f206691344f to your computer and use it in GitHub Desktop.
# ==========================================================================
# AIDA Detector description implementation
# --------------------------------------------------------------------------
# Copyright (C) Organisation europeenne pour la Recherche nucleaire (CERN)
# All rights reserved.
#
# For the licensing terms see $DD4hepINSTALL/LICENSE.
# For the list of contributors see $DD4hepINSTALL/doc/CREDITS.
#
# ==========================================================================
#
"""
Subtest using CLICSid showing the usage the HEPMC file reader
@author M.Frank
@version 1.0
"""
from __future__ import absolute_import, unicode_literals
import logging
logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
def run():
import CLICSid
import DDG4
import os
import sys
import time
from DDG4 import OutputLevel as Output
sid = CLICSid.CLICSid(no_physics=False)
geant4 = sid.geant4
kernel = sid.kernel
sid.loadGeometry()
geant4.printDetectors()
kernel.UI = 'UI'
if len(sys.argv) >= 2 and sys.argv[1] == "batch":
DDG4.setPrintLevel(DDG4.OutputLevel.WARNING)
kernel.UI = ''
geant4.setupCshUI()
sid.setupField(quiet=False)
DDG4.importConstants(kernel.detectorDescription(), debug=False)
geant4.setupROOTOutput('ROOTOutput', 'C3SiD_' + time.strftime('%Y-%m-%d_%H-%M'))
prt = DDG4.EventAction(kernel, 'Geant4ParticlePrint/ParticlePrint')
prt.OutputLevel = Output.INFO
prt.OutputType = 3 # Print both: table and tree
kernel.eventAction().adopt(prt)
# First particle file reader
gen = DDG4.GeneratorAction(kernel, "Geant4GeneratorActionInit/GenerationInit")
kernel.generatorAction().adopt(gen)
input = DDG4.GeneratorAction(kernel, "Geant4InputAction/Input")
fname = "./pairs_rndm_seed_100805.dat" # os.environ['DD4hepINSTALL'] + '/examples/CLICSiD/scripts/pairs_rndm_seed_100805.dat'
input.Input = "Geant4EventReaderGuineaPig|" + fname
input.MomentumScale = 1.0
input.Mask = 1
kernel.generatorAction().adopt(input)
# Merge all existing interaction records
merger = DDG4.GeneratorAction(kernel, "Geant4InteractionMerger/InteractionMerger")
merger.enableUI()
kernel.generatorAction().adopt(merger)
logger.info("# Finally generate Geant4 primaries")
gen = DDG4.GeneratorAction(kernel, "Geant4PrimaryHandler/PrimaryHandler")
gen.OutputLevel = 4 # generator_output_level
gen.enableUI()
kernel.generatorAction().adopt(gen)
# And handle the simulation particles.
part = DDG4.GeneratorAction(kernel, "Geant4ParticleHandler/ParticleHandler")
kernel.generatorAction().adopt(part)
part.OutputLevel = Output.INFO
part.enableUI()
logger.info("# Configure Event actions")
prt = DDG4.EventAction(kernel, 'Geant4ParticlePrint/ParticlePrint')
prt.OutputLevel = Output.INFO
prt.OutputType = 3 # Print both: table and tree
kernel.eventAction().adopt(prt)
user = DDG4.Action(kernel, "Geant4TCUserParticleHandler/UserParticleHandler")
user.TrackingVolume_Zmax = DDG4.ECalEndcap_zmin
user.TrackingVolume_Rmax = DDG4.ECalBarrel_rmin
user.enableUI()
part.adopt(user)
#
sid.setupDetectors()
sid.setupPhysics('QGSP_BERT')
rng = sid.setupRandom('R1', seed=76545678, type='MTwistEngine')
DDG4.Geant4Random.setMainInstance(rng.get())
sid.test_run(have_geo=True, num_events=1)
if __name__ == "__main__":
run()
# ==========================================================================
# AIDA Detector description implementation
# --------------------------------------------------------------------------
# Copyright (C) Organisation europeenne pour la Recherche nucleaire (CERN)
# All rights reserved.
#
# For the licensing terms see $DD4hepINSTALL/LICENSE.
# For the list of contributors see $DD4hepINSTALL/doc/CREDITS.
#
# ==========================================================================
#
from __future__ import absolute_import, unicode_literals
import sys
import logging
import DDG4
logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
class CLICSid:
def __init__(self, tracker='Geant4TrackerCombineAction', no_physics=True):
self.kernel = DDG4.Kernel()
self.description = self.kernel.detectorDescription()
self.geant4 = DDG4.Geant4(self.kernel, tracker=tracker)
self.kernel.UI = ""
if no_physics:
self.noPhysics()
def loadGeometry(self, file=None):
import os
if file is None:
#install_dir = #os.environ['DD4hepINSTALL']
level = DDG4.printLevel()
DDG4.setPrintLevel(DDG4.OutputLevel.WARNING)
self.kernel.loadGeometry(str("file:/uscms/home/lagray/nobackup/dd4hep/lcgeo/SiD/compact/SiD_o2_v04/SiD_o2_v04.xml"))
DDG4.setPrintLevel(level)
else:
ui = DDG4.DD4hepUI(self.description)
ui.importROOT(file)
return self
# Example to show how to configure G4 magnetic field tracking
def setupField(self, quiet=True):
return self.geant4.setupTrackingField(prt=True)
# Example to show how to setup random generator
def setupRandom(self, name, type=None, seed=None, quiet=True):
rndm = DDG4.Action(self.kernel, 'Geant4Random/' + name)
if seed:
rndm.Seed = seed
if type:
rndm.Type = type
rndm.initialize()
if not quiet:
rndm.showStatus()
return rndm
# Example to show how to configure the Geant4 physics list
def setupPhysics(self, model):
phys = self.geant4.setupPhysics(model)
ph = DDG4.PhysicsList(self.kernel, str('Geant4PhysicsList/Myphysics'))
# Add bosons to the model (redundant if already implemented by the model)
ph.addParticleGroup(str('G4BosonConstructor'))
# Add leptons to the model (redundant if already implemented by the model)
ph.addParticleGroup(str('G4LeptonConstructor'))
# Add multiple scattering in the material
ph.addParticleProcess(str('e[+-]'), str('G4eMultipleScattering'), -1, 1, 1)
# Add optical physics (RICH dets etc)
ph.addPhysicsConstructor(str('G4OpticalPhysics'))
# Interactivity
ph.enableUI()
phys.adopt(ph)
phys.dump()
return phys
# No physics list wanted for tests ? See how:
def noPhysics(self):
self.geant4.setupPhysics('')
return self
def setupDetectors(self):
logger.info("# First the tracking detectors")
seq, act = self.geant4.setupTracker('SiVertexBarrel')
seq, act = self.geant4.setupTracker('SiVertexEndcap')
seq, act = self.geant4.setupTracker('SiTrackerBarrel')
seq, act = self.geant4.setupTracker('SiTrackerEndcap')
seq, act = self.geant4.setupTracker('SiTrackerForward')
logger.info("# Now setup the calorimeters")
seq, act = self.geant4.setupCalorimeter('ECalBarrel')
seq, act = self.geant4.setupCalorimeter('ECalEndcap')
seq, act = self.geant4.setupCalorimeter('HCalBarrel')
seq, act = self.geant4.setupCalorimeter('HCalEndcap')
seq, act = self.geant4.setupCalorimeter('MuonBarrel')
seq, act = self.geant4.setupCalorimeter('MuonEndcap')
seq, act = self.geant4.setupCalorimeter('LumiCal')
seq, act = self.geant4.setupCalorimeter('BeamCal')
return self
# Test the configuration
def test_config(self, have_geo=True):
self.kernel.configure()
if have_geo:
self.kernel.initialize()
return self
# Test runner
def test_run(self, have_geo=True, have_physics=False, num_events=0):
self.test_config(have_geo)
if have_geo:
self.kernel.NumEvents = num_events
self.kernel.run()
self.kernel.terminate()
logger.info('+++++ All Done....\n\nTEST_PASSED')
sys.exit(0)
source /cvmfs/sft.cern.ch/lcg/views/LCG_101/x86_64-centos7-gcc11-opt/setup.sh
source ${DD4hepINSTALL}/bin/thisdd4hep.sh
source /path/to/your/lcgeo/install/bin/thislcgeo.sh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment