Beispiel #1
0
def run():

  kernel = DDG4.Kernel()

  try:
    install_dir = os.environ['DD4hepINSTALL']

  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 ) 

  #--------

  inf = open( paramFile , 'r' )
  outf = open( dictFile , 'w' )

  names = readNames( inf ) 
  
  writeDictionary( names, outf )
  
  inf.close()
  outf.close()
def run():

    kernel = DDG4.Kernel()

    try:
        install_dir = os.environ['DD4hepINSTALL']

    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)

    #--------

    inf = open(paramFile, 'r')
    outf = open(dictFile, 'w')

    names = readNames(inf)

    writeDictionary(names, outf)

    inf.close()
    outf.close()
Beispiel #3
0
def run():
    import sys
    import CLICSid
    import DDG4
    from DDG4 import OutputLevel as Output

    sid = CLICSid.CLICSid()
    geant4 = sid.geant4
    kernel = sid.kernel
    sid.loadGeometry(str('CLICSiD_geometry.root'))
    geant4.printDetectors()

    if len(sys.argv) >= 2 and sys.argv[1] == "batch":
        kernel.UI = ''

    geant4.setupCshUI()
    sid.setupField(quiet=False)
    DDG4.importConstants(kernel.detectorDescription(), debug=False)

    prt = DDG4.EventAction(kernel, 'Geant4ParticlePrint/ParticlePrint')
    prt.OutputLevel = Output.INFO
    prt.OutputType = 3  # Print both: table and tree
    kernel.eventAction().adopt(prt)

    gen = DDG4.GeneratorAction(kernel,
                               "Geant4GeneratorActionInit/GenerationInit")
    kernel.generatorAction().adopt(gen)
    logger.info("#  First particle generator: gun")
    gun = DDG4.GeneratorAction(kernel, "Geant4GeneratorWrapper/Gun")
    gun.Uses = 'G4ParticleGun'
    gun.Mask = 1
    kernel.generatorAction().adopt(gun)

    # Merge all existing interaction records
    merger = DDG4.GeneratorAction(kernel,
                                  "Geant4InteractionMerger/InteractionMerger")
    merger.enableUI()
    kernel.generatorAction().adopt(merger)

    # And handle the simulation particles.
    part = DDG4.GeneratorAction(kernel,
                                "Geant4ParticleHandler/ParticleHandler")
    kernel.generatorAction().adopt(part)
    part.OutputLevel = Output.INFO
    part.enableUI()
    user = DDG4.Action(kernel,
                       "Geant4TCUserParticleHandler/UserParticleHandler")
    user.TrackingVolume_Zmax = DDG4.EcalEndcap_zmin
    user.TrackingVolume_Rmax = DDG4.EcalBarrel_rmin
    user.enableUI()
    part.adopt(user)

    sid.setupDetectors()
    sid.setupPhysics('QGSP_BERT')
    sid.test_config()
    gun.generator(
    )  # Instantiate gun to be able to set properties from G4 prompt
    kernel.run()
    kernel.terminate()
Beispiel #4
0
def run():
    kernel = DDG4.Kernel()
    description = kernel.detectorDescription()

    install_dir = os.environ['DD4hepExamplesINSTALL']
    kernel.loadGeometry(
        str("file:" + install_dir +
            "/examples/ClientTests/compact/LheD_tracker.xml"))

    DDG4.importConstants(description, debug=False)
    geant4 = DDG4.Geant4(kernel, tracker='Geant4TrackerCombineAction')
    geant4.printDetectors()

    # Configure UI
    geant4.setupCshUI()
    # geant4.setupCshUI('csh',True,True)
    # geant4.setupCshUI('csh',True,True,'vis.mac')
    if len(sys.argv) >= 2 and sys.argv[1] == "batch":
        kernel.UI = ''

    # Configure field
    geant4.setupTrackingField(prt=True)
    # Configure Event actions
    prt = DDG4.EventAction(kernel, 'Geant4ParticlePrint/ParticlePrint')
    prt.OutputLevel = Output.WARNING  # Output.WARNING
    prt.OutputType = 3  # Print both: table and tree
    kernel.eventAction().adopt(prt)

    # Configure I/O
    geant4.setupROOTOutput('RootOutput',
                           'LHeD_tracker_' + time.strftime('%Y-%m-%d_%H-%M'))
    gen = geant4.setupGun("Gun",
                          particle='geantino',
                          energy=20 * GeV,
                          position=(0 * mm, 0 * mm, 0 * cm),
                          multiplicity=3)
    gen.isotrop = False
    gen.direction = (1, 0, 0)
    gen.OutputLevel = Output.WARNING

    # seq,act = geant4.setupTracker('SiVertexBarrel')

    # Now build the physics list:
    phys = geant4.setupPhysics('QGSP_BERT')
    ph = DDG4.PhysicsList(kernel, 'Geant4PhysicsList/Myphysics')
    ph.addParticleConstructor(str('G4Geantino'))
    ph.addParticleConstructor(str('G4BosonConstructor'))
    ph.enableUI()
    phys.adopt(ph)
    phys.dump()

    kernel.configure()
    kernel.initialize()

    # DDG4.setPrintLevel(Output.DEBUG)
    kernel.run()
    logger.info('End of run. Terminating .......')
    kernel.terminate()
Beispiel #5
0
def run():
  kernel = DDG4.Kernel()
  install_dir = os.environ['DD4hepINSTALL']
  kernel.loadGeometry("file:"+install_dir+"/examples/ClientTests/compact/SiliconBlock.xml")

  DDG4.importConstants(kernel.lcdd(),debug=False)
  geant4 = DDG4.Geant4(kernel,tracker='Geant4TrackerCombineAction')
  geant4.printDetectors()
  # Configure UI
  if len(sys.argv)>1:
    geant4.setupCshUI(macro=sys.argv[1])
  else:
    geant4.setupCshUI()

  # Configure field
  field = geant4.setupTrackingField(prt=True)
  # Configure Event actions
  prt = DDG4.EventAction(kernel,'Geant4ParticlePrint/ParticlePrint')
  prt.OutputLevel = Output.DEBUG
  prt.OutputType  = 3 # Print both: table and tree
  kernel.eventAction().adopt(prt)

  generator_output_level = Output.INFO

  # Configure I/O
  evt_root = geant4.setupROOTOutput('RootOutput','SiliconBlock_'+time.strftime('%Y-%m-%d_%H-%M'))

  # Setup particle gun
  gun = geant4.setupGun("Gun",particle='mu-',energy=20*GeV,multiplicity=1)
  gun.output_level = generator_output_level

  # And handle the simulation particles.
  part = DDG4.GeneratorAction(kernel,"Geant4ParticleHandler/ParticleHandler")
  kernel.generatorAction().adopt(part)
  part.SaveProcesses = ['Decay']
  part.MinimalKineticEnergy = 100*MeV
  part.OutputLevel = Output.INFO #generator_output_level
  part.enableUI()
  user = DDG4.Action(kernel,"Geant4TCUserParticleHandler/UserParticleHandler")
  user.TrackingVolume_Zmax = 3.0*m
  user.TrackingVolume_Rmax = 3.0*m
  user.enableUI()
  part.adopt(user)

  geant4.setupTracker('SiliconBlockUpper')
  geant4.setupTracker('SiliconBlockDown')

  # Now build the physics list:
  phys = geant4.setupPhysics('QGSP_BERT')
  ph = DDG4.PhysicsList(kernel,'Geant4PhysicsList/Myphysics')
  ph.addParticleConstructor('G4Geantino')
  ph.addParticleConstructor('G4BosonConstructor')
  ph.enableUI()
  phys.adopt(ph)
  phys.dump()

  geant4.execute()
Beispiel #6
0
def run():
  kernel = DDG4.Kernel()
  lcdd = kernel.lcdd()
  install_dir = os.environ['DD4hepINSTALL']
  DDG4.Core.setPrintFormat("%-32s %6s %s")
  kernel.loadGeometry("file:"+install_dir+"/DDDetectors/compact/SiD.xml")
  DDG4.importConstants(lcdd)

  kernel.NumberOfThreads = 3
  geant4 = DDG4.Geant4(kernel,tracker='Geant4TrackerCombineAction')
  print "#  Configure UI"
  geant4.setupCshUI()

  print "#  Geant4 user initialization action"
  geant4.addUserInitialization(worker=setupWorker, worker_args=(geant4,),
                               master=setupMaster,master_args=(geant4,))

  print "#  Configure G4 geometry setup"
  seq,act = geant4.addDetectorConstruction("Geant4DetectorGeometryConstruction/ConstructGeo")

  print "# Configure G4 sensitive detectors: python setup callback"
  seq,act = geant4.addDetectorConstruction("Geant4PythonDetectorConstruction/SetupSD",
                                           sensitives=setupSensitives,sensitives_args=(geant4,))
  print "# Configure G4 sensitive detectors: atach'em to the sensitive volumes"
  seq,act = geant4.addDetectorConstruction("Geant4DetectorSensitivesConstruction/ConstructSD")
  #                                           allow_threads=True)

  print "#  Configure G4 magnetic field tracking"
  seq,field = geant4.addDetectorConstruction("Geant4FieldTrackingConstruction/MagFieldTrackingSetup")
  field.stepper            = "HelixGeant4Runge"
  field.equation           = "Mag_UsualEqRhs"
  field.eps_min            = 5e-05 * mm
  field.eps_max            = 0.001 * mm
  field.min_chord_step     = 0.01 * mm
  field.delta_chord        = 0.25 * mm
  field.delta_intersection = 1e-05 * mm
  field.delta_one_step     = 0.001 * mm
  print '+++++> ',field.name,'-> stepper  = ',field.stepper
  print '+++++> ',field.name,'-> equation = ',field.equation
  print '+++++> ',field.name,'-> eps_min  = ',field.eps_min
  print '+++++> ',field.name,'-> eps_max  = ',field.eps_max
  print '+++++> ',field.name,'-> delta_one_step = ',field.delta_one_step

  print "#  Setup random generator"
  rndm = DDG4.Action(kernel,'Geant4Random/Random')
  rndm.Seed = 987654321
  rndm.initialize()
  ##rndm.showStatus()

  print "#  Now build the physics list:"
  phys = geant4.setupPhysics('QGSP_BERT')
  phys.dump()

  geant4.run()
Beispiel #7
0
def run():
    kernel = DDG4.Kernel()
    description = kernel.detectorDescription()
    install_dir = os.environ['DD4hepINSTALL']
    DDG4.Core.setPrintFormat(str("%-32s %6s %s"))
    kernel.loadGeometry(
        str("file:" + install_dir + "/DDDetectors/compact/SiD.xml"))
    DDG4.importConstants(description)

    kernel.NumberOfThreads = 3
    kernel.RunManagerType = 'G4MTRunManager'
    geant4 = DDG4.Geant4(kernel, tracker='Geant4TrackerCombineAction')
    logger.info("#  Configure UI")
    geant4.setupCshUI()

    logger.info("#  Geant4 user initialization action")
    geant4.addUserInitialization(worker=setupWorker,
                                 worker_args=(geant4, ),
                                 master=setupMaster,
                                 master_args=(geant4, ))

    logger.info("#  Configure G4 geometry setup")
    seq, act = geant4.addDetectorConstruction(
        "Geant4DetectorGeometryConstruction/ConstructGeo")

    logger.info("# Configure G4 sensitive detectors: python setup callback")
    seq, act = geant4.addDetectorConstruction(
        "Geant4PythonDetectorConstruction/SetupSD",
        sensitives=setupSensitives,
        sensitives_args=(geant4, ))
    logger.info(
        "# Configure G4 sensitive detectors: atach'em to the sensitive volumes"
    )
    seq, act = geant4.addDetectorConstruction(
        "Geant4DetectorSensitivesConstruction/ConstructSD")
    #                                           allow_threads=True)

    logger.info("#  Configure G4 magnetic field tracking")
    geant4.setupTrackingFieldMT()

    logger.info("#  Setup random generator")
    rndm = DDG4.Action(kernel, 'Geant4Random/Random')
    rndm.Seed = 987654321
    rndm.initialize()
    # rndm.showStatus()

    logger.info("#  Now build the physics list:")
    phys = geant4.setupPhysics('QGSP_BERT')
    phys.dump()

    geant4.run()
Beispiel #8
0
def run():
  kernel = DDG4.Kernel()
  lcdd = kernel.lcdd()
  
  install_dir = os.environ['DD4hepINSTALL']
  kernel.loadGeometry("file:"+install_dir+"/examples/ClientTests/compact/LheD_tracker.xml")

  DDG4.importConstants(lcdd,debug=False)
  geant4 = DDG4.Geant4(kernel,tracker='Geant4TrackerCombineAction')
  geant4.printDetectors()

  # Configure UI
  geant4.setupCshUI()
  ##geant4.setupCshUI('csh',True,True)
  ##geant4.setupCshUI('csh',True,True,'vis.mac')
  if len(sys.argv) >= 2 and sys.argv[1] =="batch":
    kernel.UI = ''
    
  # Configure field
  field = geant4.setupTrackingField(prt=True)
  # Configure Event actions
  prt = DDG4.EventAction(kernel,'Geant4ParticlePrint/ParticlePrint')
  prt.OutputLevel = Output.WARNING # Output.WARNING
  prt.OutputType  = 3 # Print both: table and tree
  kernel.eventAction().adopt(prt)

  # Configure I/O
  evt_root = geant4.setupROOTOutput('RootOutput','LHeD_tracker_'+time.strftime('%Y-%m-%d_%H-%M'))
  gen = geant4.setupGun("Gun",particle='geantino',energy=20*GeV,position=(0*mm,0*mm,0*cm),multiplicity=3)
  gen.isotrop = False
  gen.direction = (1,0,0)
  gen.OutputLevel = Output.WARNING

  #seq,act = geant4.setupTracker('SiVertexBarrel')

  # Now build the physics list:
  phys = geant4.setupPhysics('QGSP_BERT')
  ph = DDG4.PhysicsList(kernel,'Geant4PhysicsList/Myphysics')
  ph.addParticleConstructor('G4Geantino')
  ph.addParticleConstructor('G4BosonConstructor')
  ph.enableUI()
  phys.adopt(ph)
  phys.dump()

  kernel.configure()
  kernel.initialize()

  #DDG4.setPrintLevel(Output.DEBUG)
  kernel.run()
  print 'End of run. Terminating .......'
  kernel.terminate()
Beispiel #9
0
def run():
  import logging, LHeD, DDG4
  from DDG4 import OutputLevel as Output
  
  logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG)
  lhed = LHeD.LHeD()
  geant4 = lhed.geant4
  kernel = lhed.kernel
  lhed.loadGeometry()
  geant4.printDetectors()
  kernel.UI = "UI"
  geant4.setupCshUI()
  lhed.setupField(quiet=False)
  DDG4.importConstants(kernel.detectorDescription(),debug=False)

  prt = DDG4.EventAction(kernel,'Geant4ParticlePrint/ParticlePrint')
  prt.OutputLevel = Output.INFO
  prt.OutputType  = 3 # Print both: table and tree
  kernel.eventAction().adopt(prt)

  gen = DDG4.GeneratorAction(kernel,"Geant4GeneratorActionInit/GenerationInit")
  kernel.generatorAction().adopt(gen)
  logging.info("#  First particle generator: gun")
  gun = DDG4.GeneratorAction(kernel,"Geant4GeneratorWrapper/Gun");
  gun.Uses     = 'G4ParticleGun'
  gun.Mask     = 1
  kernel.generatorAction().adopt(gun)

  # Merge all existing interaction records
  merger = DDG4.GeneratorAction(kernel,"Geant4InteractionMerger/InteractionMerger")
  merger.enableUI()
  kernel.generatorAction().adopt(merger)


  # And handle the simulation particles.
  part = DDG4.GeneratorAction(kernel,"Geant4ParticleHandler/ParticleHandler")
  kernel.generatorAction().adopt(part)
  part.OutputLevel = Output.INFO
  part.enableUI()
  user = DDG4.Action(kernel,"Geant4TCUserParticleHandler/UserParticleHandler")
  user.TrackingVolume_Zmax = DDG4.EcalEndcap_zmin
  user.TrackingVolume_Rmax = DDG4.EcalBarrel_rmin
  user.enableUI()
  part.adopt(user)

  lhed.setupDetectors()
  lhed.setupPhysics('QGSP_BERT')
  lhed.test_config()
  gun.generator()  # Instantiate gun to be able to set properties from G4 prompt
  kernel.run()
  kernel.terminate()
Beispiel #10
0
def run():
    import CLICSid, DDG4
    from DDG4 import OutputLevel as Output

    sid = CLICSid.CLICSid()
    geant4 = sid.geant4
    kernel = sid.kernel
    sid.loadGeometry()
    geant4.printDetectors()
    kernel.UI = "UI"
    geant4.setupCshUI()
    sid.setupField(quiet=False)
    DDG4.importConstants(kernel.lcdd(), debug=False)

    prt = DDG4.EventAction(kernel, "Geant4ParticlePrint/ParticlePrint")
    prt.OutputLevel = Output.INFO
    prt.OutputType = 3  # Print both: table and tree
    kernel.eventAction().adopt(prt)

    gen = DDG4.GeneratorAction(kernel, "Geant4GeneratorActionInit/GenerationInit")
    kernel.generatorAction().adopt(gen)
    print "#  First particle generator: gun"
    gun = DDG4.GeneratorAction(kernel, "Geant4GeneratorWrapper/Gun")
    gun.Uses = "G4ParticleGun"
    gun.Mask = 1
    kernel.generatorAction().adopt(gun)

    # Merge all existing interaction records
    merger = DDG4.GeneratorAction(kernel, "Geant4InteractionMerger/InteractionMerger")
    merger.enableUI()
    kernel.generatorAction().adopt(merger)

    # And handle the simulation particles.
    part = DDG4.GeneratorAction(kernel, "Geant4ParticleHandler/ParticleHandler")
    kernel.generatorAction().adopt(part)
    part.OutputLevel = Output.INFO
    part.enableUI()
    user = DDG4.Action(kernel, "Geant4TCUserParticleHandler/UserParticleHandler")
    user.TrackingVolume_Zmax = DDG4.EcalEndcap_zmin
    user.TrackingVolume_Rmax = DDG4.EcalBarrel_rmin
    user.enableUI()
    part.adopt(user)

    sid.setupDetectors()
    sid.setupPhysics("QGSP_BERT")
    sid.test_config()
    gun.generator()  # Instantiate gun to be able to set properties from G4 prompt
    kernel.run()
    kernel.terminate()
Beispiel #11
0
def run():
    kernel = DDG4.Kernel()
    install_dir = os.environ['DD4hepExamplesINSTALL']
    kernel.loadGeometry("file:" + install_dir +
                        "/examples/ClientTests/compact/SiliconBlock.xml")
    DDG4.importConstants(kernel.detectorDescription(), debug=False)
    # =======================================================================================
    # ===> This is actually the ONLY difference to ClientTests/scripts/SiliconBlock.py
    # =======================================================================================
    geant4 = DDG4.Geant4(kernel, tracker='MyTrackerSDAction')

    geant4.printDetectors()
    kernel.NumEvents = 5
    kernel.UI = ''

    # Configure field
    field = geant4.setupTrackingField(prt=True)
    # Configure Event actions
    prt = DDG4.EventAction(kernel, 'Geant4ParticlePrint/ParticlePrint')
    prt.OutputLevel = Output.WARNING
    prt.OutputType = 3  # Print both: table and tree
    kernel.eventAction().adopt(prt)

    # Configure I/O
    evt_root = geant4.setupROOTOutput('RootOutput',
                                      'MySD_' +
                                      time.strftime('%Y-%m-%d_%H-%M'),
                                      mc_truth=False)
    # Setup particle gun
    gun = geant4.setupGun("Gun",
                          particle='mu-',
                          energy=5 * GeV,
                          multiplicity=1,
                          Standalone=True,
                          position=(0, 0, 0))
    seq, act = geant4.setupTracker('SiliconBlockUpper')
    act.OutputLevel = Output.INFO
    seq, act = geant4.setupTracker('SiliconBlockDown')
    act.OutputLevel = Output.INFO
    # Now build the physics list:
    phys = kernel.physicsList()
    phys.extends = 'QGSP_BERT'
    phys.enableUI()
    phys.dump()
    # run
    kernel.configure()
    kernel.initialize()
    kernel.run()
    kernel.terminate()
Beispiel #12
0
def run():
    kernel = DDG4.Kernel()
    install_dir = os.environ['DD4hepExamplesINSTALL']
    kernel.loadGeometry(
        str("file:" + install_dir +
            "/examples/ClientTests/compact/GdmlDetector.xml"))

    DDG4.importConstants(kernel.detectorDescription(), debug=False)
    geant4 = DDG4.Geant4(kernel, tracker='Geant4TrackerCombineAction')
    geant4.printDetectors()
    # Configure UI
    if len(sys.argv) > 1:
        geant4.setupCshUI(macro=sys.argv[1])
    else:
        geant4.setupCshUI()

    # Configure field
    geant4.setupTrackingField(prt=True)

    generator_output_level = Output.INFO

    # Configure G4 geometry setup
    seq, act = geant4.addDetectorConstruction(
        "Geant4DetectorGeometryConstruction/ConstructGeo")
    act.DebugVolumes = True
    act.DebugShapes = True
    act.DebugPlacements = True
    act.DumpHierarchy = True

    # Setup particle gun
    gun = geant4.setupGun("Gun",
                          particle='mu-',
                          energy=20 * GeV,
                          multiplicity=1)
    gun.OutputLevel = generator_output_level

    # Now build the physics list:
    phys = geant4.setupPhysics('QGSP_BERT')
    phys.dump()

    geant4.execute()
Beispiel #13
0
def run():
  kernel = DDG4.Kernel()
  install_dir = os.environ['DD4hepExamplesINSTALL']
  kernel.loadGeometry("file:"+install_dir+"/examples/ClientTests/compact/SiliconBlock.xml")
  DDG4.importConstants(kernel.detectorDescription(),debug=False)
  # =======================================================================================
  # ===> This is actually the ONLY difference to ClientTests/scripts/SiliconBlock.py
  # =======================================================================================
  geant4 = DDG4.Geant4(kernel,tracker='MyTrackerSDAction')

  geant4.printDetectors()
  kernel.NumEvents = 5
  kernel.UI = ''

  # Configure field
  field = geant4.setupTrackingField(prt=True)
  # Configure Event actions
  prt = DDG4.EventAction(kernel,'Geant4ParticlePrint/ParticlePrint')
  prt.OutputLevel = Output.WARNING
  prt.OutputType  = 3 # Print both: table and tree
  kernel.eventAction().adopt(prt)

  # Configure I/O
  evt_root = geant4.setupROOTOutput('RootOutput','MySD_'+time.strftime('%Y-%m-%d_%H-%M'),mc_truth=False)
  # Setup particle gun
  gun = geant4.setupGun("Gun",particle='mu-',energy=5*GeV,multiplicity=1,Standalone=True,position=(0,0,0))
  geant4.setupTracker('SiliconBlockUpper')
  geant4.setupTracker('SiliconBlockDown')
  # Now build the physics list:
  phys = kernel.physicsList()
  phys.extends = 'QGSP_BERT'
  phys.enableUI()
  phys.dump()
  # run
  kernel.configure()
  kernel.initialize()
  kernel.run()
  kernel.terminate()
Beispiel #14
0
def run():
    kernel = DDG4.Kernel()
    install_dir = os.environ['DD4hepExamplesINSTALL']
    kernel.loadGeometry("file:" + install_dir +
                        "/examples/ClientTests/compact/SiliconBlock.xml")

    DDG4.importConstants(kernel.detectorDescription(), debug=False)
    geant4 = DDG4.Geant4(kernel, tracker='Geant4TrackerCombineAction')
    geant4.printDetectors()
    # Configure UI
    if len(sys.argv) > 1:
        geant4.setupCshUI(macro=sys.argv[1])
    else:
        geant4.setupCshUI()

    # Configure field
    field = geant4.setupTrackingField(prt=True)
    # Configure Event actions
    prt = DDG4.EventAction(kernel, 'Geant4ParticlePrint/ParticlePrint')
    prt.OutputLevel = Output.DEBUG
    prt.OutputType = 3  # Print both: table and tree
    kernel.eventAction().adopt(prt)

    generator_output_level = Output.INFO

    # Configure G4 geometry setup
    seq, act = geant4.addDetectorConstruction(
        "Geant4DetectorGeometryConstruction/ConstructGeo")
    act.DebugMaterials = True
    act.DebugElements = False
    act.DebugVolumes = True
    act.DebugShapes = True

    # Configure I/O
    evt_root = geant4.setupROOTOutput(
        'RootOutput', 'SiliconBlock_' + time.strftime('%Y-%m-%d_%H-%M'))

    # Setup particle gun
    gun = geant4.setupGun("Gun",
                          particle='mu-',
                          energy=20 * GeV,
                          multiplicity=1)
    gun.OutputLevel = generator_output_level

    # And handle the simulation particles.
    part = DDG4.GeneratorAction(kernel,
                                "Geant4ParticleHandler/ParticleHandler")
    kernel.generatorAction().adopt(part)
    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 = 3.0 * m
    user.TrackingVolume_Rmax = 3.0 * m
    user.enableUI()
    part.adopt(user)

    geant4.setupTracker('SiliconBlockUpper')
    geant4.setupTracker('SiliconBlockDown')

    # Now build the physics list:
    phys = geant4.setupPhysics('QGSP_BERT')
    ph = DDG4.PhysicsList(kernel, 'Geant4PhysicsList/Myphysics')
    ph.addParticleConstructor('G4Geantino')
    ph.addParticleConstructor('G4BosonConstructor')
    ph.enableUI()
    phys.adopt(ph)
    phys.dump()

    geant4.execute()
Beispiel #15
0
def run():
    kernel = DDG4.Kernel()
    description = kernel.detectorDescription()
    install_dir = os.environ['DD4hepINSTALL']
    kernel.loadGeometry("file:" + install_dir + "/DDDetectors/compact/SiD.xml")
    DDG4.importConstants(description)

    geant4 = DDG4.Geant4(kernel, tracker='Geant4TrackerCombineAction')
    geant4.printDetectors()
    logging.info("#  Configure UI")
    geant4.setupCshUI()

    logging.info("#  Configure G4 magnetic field tracking")
    geant4.setupTrackingField()

    logging.info("#  Setup random generator")
    rndm = DDG4.Action(kernel, 'Geant4Random/Random')
    rndm.Seed = 987654321
    rndm.initialize()
    ##rndm.showStatus()

    logging.info("#  Configure Run actions")
    run1 = DDG4.RunAction(kernel, 'Geant4TestRunAction/RunInit')
    run1.Property_int = 12345
    run1.Property_double = -5e15 * keV
    run1.Property_string = 'Startrun: Hello_2'
    logging.info("%s %s %s", run1.Property_string, str(run1.Property_double),
                 str(run1.Property_int))
    run1.enableUI()
    kernel.registerGlobalAction(run1)
    kernel.runAction().adopt(run1)

    logging.info("#  Configure Event actions")
    prt = DDG4.EventAction(kernel, 'Geant4ParticlePrint/ParticlePrint')
    prt.OutputLevel = Output.INFO
    prt.OutputType = 3  # Print both: table and tree
    kernel.eventAction().adopt(prt)

    logging.info("""
  Configure I/O
  """)
    #evt_lcio = geant4.setupLCIOOutput('LcioOutput','CLICSiD_'+time.strftime('%Y-%m-%d_%H-%M'))
    #evt_lcio.OutputLevel = Output.ERROR

    evt_root = geant4.setupROOTOutput(
        'RootOutput', 'CLICSiD_' + time.strftime('%Y-%m-%d_%H-%M'))

    generator_output_level = Output.INFO

    gen = DDG4.GeneratorAction(kernel,
                               "Geant4GeneratorActionInit/GenerationInit")
    kernel.generatorAction().adopt(gen)

    #VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
    logging.info("""
  Generation of isotrope tracks of a given multiplicity with overlay:
  """)
    logging.info("#  First particle generator: pi+")
    gen = DDG4.GeneratorAction(kernel, "Geant4IsotropeGenerator/IsotropPi+")
    gen.Mask = 1
    gen.Particle = 'pi+'
    gen.Energy = 100 * GeV
    gen.Multiplicity = 2
    gen.Distribution = 'cos(theta)'
    kernel.generatorAction().adopt(gen)
    logging.info("#  Install vertex smearing for this interaction")
    gen = DDG4.GeneratorAction(kernel, "Geant4InteractionVertexSmear/SmearPi+")
    gen.Mask = 1
    gen.Offset = (20 * mm, 10 * mm, 10 * mm, 0 * ns)
    gen.Sigma = (4 * mm, 1 * mm, 1 * mm, 0 * ns)
    kernel.generatorAction().adopt(gen)

    logging.info("#  Second particle generator: e-")
    gen = DDG4.GeneratorAction(kernel, "Geant4IsotropeGenerator/IsotropE-")
    gen.Mask = 2
    gen.Particle = 'e-'
    gen.Energy = 25 * GeV
    gen.Multiplicity = 3
    gen.Distribution = 'uniform'
    kernel.generatorAction().adopt(gen)
    logging.info("  Install vertex smearing for this interaction")
    gen = DDG4.GeneratorAction(kernel, "Geant4InteractionVertexSmear/SmearE-")
    gen.Mask = 2
    gen.Offset = (-20 * mm, -10 * mm, -10 * mm, 0 * ns)
    gen.Sigma = (12 * mm, 8 * mm, 8 * mm, 0 * ns)
    kernel.generatorAction().adopt(gen)
    #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    logging.info("#  Merge all existing interaction records")
    gen = DDG4.GeneratorAction(kernel,
                               "Geant4InteractionMerger/InteractionMerger")
    gen.OutputLevel = 4  #generator_output_level
    gen.enableUI()
    kernel.generatorAction().adopt(gen)

    logging.info("#  Finally generate Geant4 primaries")
    gen = DDG4.GeneratorAction(kernel, "Geant4PrimaryHandler/PrimaryHandler")
    gen.OutputLevel = 4  #generator_output_level
    gen.enableUI()
    kernel.generatorAction().adopt(gen)

    logging.info("#  ....and handle the simulation particles.")
    part = DDG4.GeneratorAction(kernel,
                                "Geant4ParticleHandler/ParticleHandler")
    kernel.generatorAction().adopt(part)
    #part.SaveProcesses = ['conv','Decay']
    part.SaveProcesses = ['Decay']
    part.MinimalKineticEnergy = 100 * MeV
    part.OutputLevel = 5  # generator_output_level
    part.enableUI()
    user = DDG4.Action(kernel,
                       "Geant4TCUserParticleHandler/UserParticleHandler")
    user.TrackingVolume_Zmax = DDG4.EcalEndcap_zmin
    user.TrackingVolume_Rmax = DDG4.EcalBarrel_rmin
    user.enableUI()
    part.adopt(user)

    logging.info("#  Setup global filters fur use in sensitive detectors")
    f1 = DDG4.Filter(kernel, 'GeantinoRejectFilter/GeantinoRejector')
    f2 = DDG4.Filter(kernel, 'ParticleRejectFilter/OpticalPhotonRejector')
    f2.particle = 'opticalphoton'
    f3 = DDG4.Filter(kernel, 'ParticleSelectFilter/OpticalPhotonSelector')
    f3.particle = 'opticalphoton'
    f4 = DDG4.Filter(kernel, 'EnergyDepositMinimumCut')
    f4.Cut = 10 * MeV
    f4.enableUI()
    kernel.registerGlobalFilter(f1)
    kernel.registerGlobalFilter(f2)
    kernel.registerGlobalFilter(f3)
    kernel.registerGlobalFilter(f4)

    logging.info("#  First the tracking detectors")
    seq, act = geant4.setupTracker('SiVertexBarrel')
    seq.adopt(f1)
    #seq.adopt(f4)
    act.adopt(f1)

    seq, act = geant4.setupTracker('SiVertexEndcap')
    seq.adopt(f1)
    #seq.adopt(f4)

    seq, act = geant4.setupTracker('SiTrackerBarrel')
    seq, act = geant4.setupTracker('SiTrackerEndcap')
    seq, act = geant4.setupTracker('SiTrackerForward')
    logging.info("#  Now setup the calorimeters")
    seq, act = geant4.setupCalorimeter('EcalBarrel')
    seq, act = geant4.setupCalorimeter('EcalEndcap')
    seq, act = geant4.setupCalorimeter('HcalBarrel')
    seq, act = geant4.setupCalorimeter('HcalEndcap')
    seq, act = geant4.setupCalorimeter('HcalPlug')
    seq, act = geant4.setupCalorimeter('MuonBarrel')
    seq, act = geant4.setupCalorimeter('MuonEndcap')
    seq, act = geant4.setupCalorimeter('LumiCal')
    seq, act = geant4.setupCalorimeter('BeamCal')

    logging.info("#  Now build the physics list:")
    phys = geant4.setupPhysics('QGSP_BERT')
    ph = geant4.addPhysics('Geant4PhysicsList/Myphysics')
    #ph.addParticleConstructor('G4BosonConstructor')
    #ph.addParticleConstructor('G4LeptonConstructor')
    #ph.addParticleProcess('e[+-]','G4eMultipleScattering',-1,1,1)
    #ph.addPhysicsConstructor('G4OpticalPhysics')

    # Add special particle types from specialized physics constructor
    part = geant4.addPhysics('Geant4ExtraParticles/ExtraParticles')
    part.pdgfile = 'checkout/DDG4/examples/particle.tbl'

    # Add global range cut
    rg = geant4.addPhysics('Geant4DefaultRangeCut/GlobalRangeCut')
    rg.RangeCut = 0.7 * mm

    phys.dump()

    kernel.configure()
    kernel.initialize()

    #DDG4.setPrintLevel(Output.DEBUG)
    kernel.run()
    kernel.terminate()
Beispiel #16
0
def run():

  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)

#  example_dir = lcgeo_dir+'/example';

  kernel.loadGeometry("file:"+ compactFile )

  lcdd = kernel.lcdd() 

  DDG4.importConstants( lcdd ) 

#----------------------------------------------------------------------------------

  simple = DDG4.Geant4( kernel, tracker='Geant4TrackerAction',calo='Geant4CalorimeterAction')
## Apply BirksLaw effect for Scintillator Calorimeter by using 'Geant4ScintillatorCalorimeterAction'.
#  simple = DDG4.Geant4( kernel, tracker='Geant4TrackerAction',calo='Geant4ScintillatorCalorimeterAction')

  simple.printDetectors()

  # Configure UI
  #simple.setupCshUI()
  simple.setupUI()

  kernel.UI=""
  kernel.NumEvents=numberOfEvents 

#-----------------------------------------------------------------------------------
#  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']    

#----------------------------------------------------------------------------------

  # 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 )
  
  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 , ')'
    seq,act = simple.setupTracker( t )
    seq.add(f1)
    act.HitCreationMode = 2

# ---- add the calorimeters:

  for c in cal:
    print 'simple.setupCalorimeter(  ' , c , ')'
    seq,act = simple.setupCalorimeter( c )


#=================================================================================
  # 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()
Beispiel #17
0
def run():
  kernel = DDG4.Kernel()
  install_dir = os.environ['DD4hepExamplesINSTALL']
  kernel.loadGeometry("file:"+install_dir+"/examples/DDCodex/compact/CODEX-b-alone.xml")

  DDG4.importConstants(kernel.detectorDescription(),debug=False)
  geant4 = DDG4.Geant4(kernel,tracker='Geant4TrackerCombineAction')
  geant4.printDetectors()
  # Configure UI
  if len(sys.argv)>1:
    geant4.setupCshUI(macro=sys.argv[1])
  else:
    geant4.setupCshUI()

  # Configure field
  field = geant4.setupTrackingField(prt=True)
  # Configure Event actions
  prt = DDG4.EventAction(kernel,'Geant4ParticlePrint/ParticlePrint')
  prt.OutputLevel = Output.WARNING
  prt.OutputType  = 3 # Print both: table and tree
  kernel.eventAction().adopt(prt)

  # Configure I/O
  evt_root = geant4.setupROOTOutput('RootOutput','CodexB_'+time.strftime('%Y-%m-%d_%H-%M'))

  # Setup particle gun
  
  #gun = geant4.setupGun("Gun",particle='pi+',
  gun = geant4.setupGun("Gun",particle='mu-',
                        energy=1000*GeV,
                        multiplicity=1,
                        isotrop=False,Standalone=True,
                        direction=(1,0,0),
                        #direction=(0.866025,0,0.5),
                        position='(0,0,12650)')
                        #position='(0,0,0)')
  setattr(gun,'print',True)
  """
  gen =  DDG4.GeneratorAction(kernel,"Geant4InputAction/Input")
  ##gen.Input = "Geant4EventReaderHepMC|"+ "/afs/cern.ch/work/j/jongho/Project_DD4hep/Test/DD4hep/examples/DDG4/data/hepmc_geant4.dat"
  gen.Input = "Geant4EventReaderHepMC|"+ "/afs/cern.ch/work/j/jongho/Project_DD4hep/Test/DD4hep/DDG4/examples/MinBias_HepMC.txt"
  gen.MomentumScale = 1.0
  gen.Mask = 1
  geant4.buildInputStage([gen],output_level=Output.DEBUG)
  """

  seq,action = geant4.setupTracker('CODEXb')
  #action.OutputLevel = Output.ERROR
  #seq,action = geant4.setupTracker('Shield')
  #action.OutputLevel = Output.ERROR

  # And handle the simulation particles.
  part = DDG4.GeneratorAction(kernel,"Geant4ParticleHandler/ParticleHandler")
  kernel.generatorAction().adopt(part)
  part.OutputLevel = Output.INFO
  part.enableUI()
  user = DDG4.Action(kernel,"Geant4TCUserParticleHandler/UserParticleHandler")
  user.TrackingVolume_Zmax = 999999.*m  # Something big. All is a tracker
  user.TrackingVolume_Rmax = 999999.*m
  user.enableUI()
  part.adopt(user)


  # Now build the physics list:
  ##phys = kernel.physicsList()
  phys = geant4.setupPhysics('QGSP_BERT')
  ph = DDG4.PhysicsList(kernel,'Geant4PhysicsList/Myphysics')
  ph.addParticleConstructor('G4LeptonConstructor')
  ph.addParticleConstructor('G4BaryonConstructor')
  ph.addParticleConstructor('G4MesonConstructor')
  ph.addParticleConstructor('G4BosonConstructor')
  ph.enableUI()
  phys.adopt(ph)
  phys.enableUI()
  phys.dump()
  # run
  kernel.configure()
  kernel.initialize()
  kernel.run()
  kernel.terminate()
Beispiel #18
0
def run():
  hlp = False
  vis = False
  dump = False
  batch = False
  install_dir = os.environ['DD4hepINSTALL']
  #
  for i in list(range(len(sys.argv))):
    c = sys.argv[i].upper()
    if c.find('BATCH') < 2 and c.find('BATCH') >= 0:
      batch = True
    elif c[:4] == '-VIS':
      vis = True
    elif c[:4] == '-DUM':
      dump = True
    elif c[:2] == '-H':
      hlp = True

  if hlp:
    help()
    sys.exit(1)

  kernel = DDG4.Kernel()
  description = kernel.detectorDescription()
  install_dir = os.environ['DD4hepExamplesINSTALL']
  geant4 = DDG4.Geant4(kernel, tracker='Geant4TrackerCombineAction')
  #
  logger.info("#  Configure UI")
  ui = None
  if batch:
    geant4.setupCshUI(ui=None, vis=None)
    kernel.UI = 'UI'
  else:
    ui = geant4.setupCshUI(vis=vis)

  kernel.loadGeometry(str("file:" + install_dir + "/examples/ClientTests/compact/NestedBoxReflection.xml"))
  DDG4.importConstants(description)

  geant4.printDetectors()
  if dump:
    seq, act = geant4.addDetectorConstruction("Geant4DetectorGeometryConstruction/ConstructGeo")
    act.DebugReflections = True
    act.DebugMaterials = False
    act.DebugElements = False
    act.DebugVolumes = False
    act.DebugShapes = False
    act.DumpHierarchy = ~0x0

  logger.info("#  Configure G4 magnetic field tracking")
  geant4.setupTrackingField()

  logger.info("#  Setup random generator")
  rndm = DDG4.Action(kernel, 'Geant4Random/Random')
  rndm.Seed = 987654321
  rndm.initialize()
  #
  logger.info("#  Configure Event actions")
  prt = DDG4.EventAction(kernel, 'Geant4ParticlePrint/ParticlePrint')
  prt.OutputType = 3  # Print both: table and tree
  prt.OutputLevel = Output.INFO
  kernel.eventAction().adopt(prt)
  #
  logger.info("#  Configure I/O")
  geant4.setupROOTOutput('RootOutput', 'BoxReflect_' + time.strftime('%Y-%m-%d_%H-%M'))
  #
  gen = DDG4.GeneratorAction(kernel, "Geant4GeneratorActionInit/GenerationInit")
  gen.enableUI()
  kernel.generatorAction().adopt(gen)
  #
  logger.info("#  Generation of isotrope tracks of a given multiplicity with overlay:")
  gen = DDG4.GeneratorAction(kernel, "Geant4ParticleGun/IsotropE+")
  gen.mask = 4
  gen.isotrop = True
  gen.particle = 'e+'
  gen.energy = 100 * GeV
  gen.multiplicity = 200
  gen.position = (0 * m, 0 * m, 0 * m)
  gen.direction = (0, 0, 1.)
  gen.distribution = 'uniform'
  gen.standalone = False
  # gen.PhiMin = 0.0*rad
  # gen.PhiMax = 2.0*math.pi*rad
  # gen.ThetaMin = 0.0*math.pi*rad
  # gen.ThetaMax = 1.0*math.pi*rad
  gen.enableUI()
  kernel.generatorAction().adopt(gen)
  #
  logger.info("#  Merge all existing interaction records")
  gen = DDG4.GeneratorAction(kernel, "Geant4InteractionMerger/InteractionMerger")
  gen.OutputLevel = 4  # generator_output_level
  gen.enableUI()
  kernel.generatorAction().adopt(gen)
  #
  logger.info("#  Finally generate Geant4 primaries")
  gen = DDG4.GeneratorAction(kernel, "Geant4PrimaryHandler/PrimaryHandler")
  gen.OutputLevel = 4  # generator_output_level
  gen.enableUI()
  kernel.generatorAction().adopt(gen)
  #
  logger.info("#  ....and handle the simulation particles.")
  part = DDG4.GeneratorAction(kernel, "Geant4ParticleHandler/ParticleHandler")
  kernel.generatorAction().adopt(part)
  # part.SaveProcesses = ['conv','Decay']
  part.SaveProcesses = ['Decay']
  part.MinimalKineticEnergy = 100 * MeV
  part.OutputLevel = 5  # generator_output_level
  part.enableUI()
  user = DDG4.Action(kernel, "Geant4TCUserParticleHandler/UserParticleHandler")
  user.TrackingVolume_Zmax = 3.0 * m
  user.TrackingVolume_Rmax = 3.0 * m
  user.enableUI()
  part.adopt(user)
  #
  logger.info("#  Now setup the calorimeters")
  seq, actions = geant4.setupDetectors()
  #
  logger.info("#  Now build the physics list:")
  geant4.setupPhysics('QGSP_BERT')
  ph = geant4.addPhysics(str('Geant4PhysicsList/Myphysics'))
  ph.addPhysicsConstructor(str('G4StepLimiterPhysics'))
  #
  # Add special particle types from specialized physics constructor
  part = geant4.addPhysics('Geant4ExtraParticles/ExtraParticles')
  part.pdgfile = os.path.join(install_dir, 'examples/DDG4/examples/particle.tbl')
  #
  # Add global range cut
  rg = geant4.addPhysics('Geant4DefaultRangeCut/GlobalRangeCut')
  rg.RangeCut = 0.7 * mm
  #
  #
  if ui and vis:
    cmds = []
    cmds.append('/control/verbose 2')
    cmds.append('/run/initialize')
    cmds.append('/vis/open OGL')
    cmds.append('/vis/verbose errors')
    cmds.append('/vis/drawVolume')
    cmds.append('/vis/viewer/set/viewpointThetaPhi 55. 45.')
    cmds.append('/vis/scene/add/axes 0 0 0 3 m')
    ui.Commands = cmds

  kernel.configure()
  kernel.initialize()

  # DDG4.setPrintLevel(Output.DEBUG)
  kernel.run()
  kernel.terminate()
Beispiel #19
0
def run():
  global geant4
  kernel = DDG4.Kernel()
  lcdd = kernel.lcdd()
  install_dir = os.environ['DD4hepINSTALL']
  kernel.loadGeometry("file:"+install_dir+"/DDDetectors/compact/SiD_Markus.xml")
  DDG4.importConstants(lcdd)
  DDG4.Core.setPrintLevel(Output.DEBUG)
  DDG4.Core.setPrintFormat("%-32s %6s %s")

  kernel.NumberOfThreads = 1
  geant4 = DDG4.Geant4(kernel,tracker='Geant4TrackerWeightedAction')
  geant4.printDetectors()
  # Configure UI
  geant4.setupCshUI()

  # Geant4 user initialization action
  geant4.addUserInitialization(worker=setupWorker, master=setupMaster)

  # Configure G4 geometry setup
  seq,act = geant4.addDetectorConstruction("Geant4DetectorGeometryConstruction/ConstructGeo")

  # Configure G4 magnetic field tracking
  seq,fld = geant4.addDetectorConstruction("Geant4FieldTrackingConstruction/MagFieldTrackingSetup")
  fld.stepper            = "HelixGeant4Runge"
  fld.equation           = "Mag_UsualEqRhs"
  fld.eps_min            = 5e-05 * mm
  fld.eps_max            = 0.001 * mm
  fld.min_chord_step     = 0.01 * mm
  fld.delta_chord        = 0.25 * mm
  fld.delta_intersection = 1e-05 * mm
  fld.delta_one_step     = 0.001 * mm
  print '+++++> ',fld.name,'-> stepper  = ',fld.stepper
  print '+++++> ',fld.name,'-> equation = ',fld.equation
  print '+++++> ',fld.name,'-> eps_min  = ',fld.eps_min
  print '+++++> ',fld.name,'-> eps_max  = ',fld.eps_max
  print '+++++> ',fld.name,'-> delta_one_step = ',fld.delta_one_step

  seq,act = geant4.addDetectorConstruction("Geant4PythonDetectorConstruction/DummyDet",
                                           geometry=dummy_geom,
                                           sensitives=dummy_sd)
  # Configure G4 sensitive detectors
  seq,act = geant4.addDetectorConstruction("Geant4PythonDetectorConstruction/SetupSD",
                                           sensitives=setupSensitives)

  # Configure G4 sensitive detectors
  seq,act = geant4.addDetectorConstruction("Geant4DetectorSensitivesConstruction/ConstructSD",
                                           allow_threads=True)

  # Setup random generator
  rndm = DDG4.Action(kernel,'Geant4Random/Random')
  rndm.Seed = 987654321
  rndm.initialize()

  # Setup global filters fur use in sensntive detectors
  f1 = DDG4.Filter(kernel,'GeantinoRejectFilter/GeantinoRejector')
  kernel.registerGlobalFilter(f1)

  #seq,act = geant4.setupTracker('SiTrackerBarrel')
  #seq,act = geant4.setupTracker('SiTrackerEndcap')
  #seq,act = geant4.setupTracker('SiTrackerForward')
  # Now the calorimeters
  #seq,act = geant4.setupCalorimeter('EcalBarrel')
  #seq,act = geant4.setupCalorimeter('EcalEndcap')
  #seq,act = geant4.setupCalorimeter('HcalBarrel')
  #seq,act = geant4.setupCalorimeter('HcalEndcap')
  #seq,act = geant4.setupCalorimeter('HcalPlug')
  #seq,act = geant4.setupCalorimeter('MuonBarrel')
  #seq,act = geant4.setupCalorimeter('MuonEndcap')
  #seq,act = geant4.setupCalorimeter('LumiCal')
  #seq,act = geant4.setupCalorimeter('BeamCal')

  # Now build the physics list:
  seq = geant4.setupPhysics('QGSP_BERT')
  phys = DDG4.PhysicsList(geant4.master(),'Geant4PhysicsList/MyPhysics')
  part = DDG4.Action(geant4.master(),'Geant4ExtraParticles/extraparts')
  part.pdgfile = 'checkout/DDG4/examples/particle.tbl'
  phys.adoptPhysicsConstructor(part.get())
  seq.add(phys)

  geant4.run()

  #kernel.configure()
  #kernel.initialize()

  #DDG4.setPrintLevel(Output.DEBUG)
  #kernel.run()
  #kernel.terminate()
  return 1
Beispiel #20
0
    def run(self):
        """setup the geometry and dd4hep and geant4 and do what was asked to be done"""
        import ROOT
        ROOT.PyConfig.IgnoreCommandLineOptions = True

        import DDG4, DD4hep

        self.printLevel = getOutputLevel(self.printLevel)

        kernel = DDG4.Kernel()
        DD4hep.setPrintLevel(self.printLevel)
        #kernel.setOutputLevel('Compact',1)

        kernel.loadGeometry("file:" + self.compactFile)
        lcdd = kernel.lcdd()

        DDG4.importConstants(lcdd)

        #----------------------------------------------------------------------------------

        #simple = DDG4.Geant4( kernel, tracker='Geant4TrackerAction',calo='Geant4CalorimeterAction')
        #simple = DDG4.Geant4( kernel, tracker='Geant4TrackerCombineAction',calo='Geant4ScintillatorCalorimeterAction')
        simple = DDG4.Geant4(kernel,
                             tracker=self.action.tracker,
                             calo=self.action.calo)

        simple.printDetectors()

        if self.runType == "vis":
            simple.setupUI(typ="csh", vis=True, macro=self.macroFile)
        elif self.runType == "run":
            simple.setupUI(typ="csh",
                           vis=False,
                           macro=self.macroFile,
                           ui=False)
        elif self.runType == "shell":
            simple.setupUI(typ="csh", vis=False, macro=None, ui=True)
        elif self.runType == "batch":
            simple.setupUI(typ="csh", vis=False, macro=None, ui=False)
        else:
            print "ERROR: unknown runType"
            exit(1)

        #kernel.UI="csh"
        kernel.NumEvents = self.numberOfEvents

        #-----------------------------------------------------------------------------------
        # setup the magnetic field:
        self.__setMagneticFieldOptions(simple)

        #----------------------------------------------------------------------------------

        # Configure Run actions
        run1 = DDG4.RunAction(kernel, 'Geant4TestRunAction/RunInit')
        kernel.registerGlobalAction(run1)
        kernel.runAction().add(run1)

        # Configure the random seed, do it before the I/O because we might change the seed!
        _rndm = self.random.initialize(DDG4, kernel, self.output.random)

        # Configure I/O
        if self.outputFile.endswith(".slcio"):
            lcOut = simple.setupLCIOOutput('LcioOutput', self.outputFile)
            lcOut.RunHeader = self.__addParametersToRunHeader()
        elif self.outputFile.endswith(".root"):
            simple.setupROOTOutput('RootOutput', self.outputFile)

        actionList = []

        if self.enableGun:
            gun = DDG4.GeneratorAction(kernel, "Geant4ParticleGun/" + "Gun")
            self.gun.setOptions(gun)
            gun.Standalone = False
            gun.Mask = 1
            actionList.append(gun)
            self.__applyBoostOrSmear(kernel, actionList, 1)
            print "++++ Adding DD4hep Particle Gun ++++"

        if self.enableG4Gun:
            ## GPS Create something
            self._g4gun = DDG4.GeneratorAction(kernel,
                                               "Geant4GeneratorWrapper/Gun")
            self._g4gun.Uses = 'G4ParticleGun'
            self._g4gun.Mask = 2
            print "++++ Adding Geant4 Particle Gun ++++"
            actionList.append(self._g4gun)

        if self.enableG4GPS:
            ## GPS Create something
            self._g4gps = DDG4.GeneratorAction(kernel,
                                               "Geant4GeneratorWrapper/GPS")
            self._g4gps.Uses = 'G4GeneralParticleSource'
            self._g4gps.Mask = 3
            print "++++ Adding Geant4 General Particle Source ++++"
            actionList.append(self._g4gps)

        for index, inputFile in enumerate(self.inputFiles, start=4):
            if inputFile.endswith(".slcio"):
                gen = DDG4.GeneratorAction(kernel,
                                           "LCIOInputAction/LCIO%d" % index)
                gen.Input = "LCIOFileReader|" + inputFile
            elif inputFile.endswith(".stdhep"):
                gen = DDG4.GeneratorAction(kernel,
                                           "LCIOInputAction/STDHEP%d" % index)
                gen.Input = "LCIOStdHepReader|" + inputFile
            elif inputFile.endswith(".HEPEvt"):
                gen = DDG4.GeneratorAction(
                    kernel, "Geant4InputAction/HEPEvt%d" % index)
                gen.Input = "Geant4EventReaderHepEvtShort|" + inputFile
            elif inputFile.endswith(".hepevt"):
                gen = DDG4.GeneratorAction(
                    kernel, "Geant4InputAction/hepevt%d" % index)
                gen.Input = "Geant4EventReaderHepEvtLong|" + inputFile
            elif inputFile.endswith(".hepmc"):
                gen = DDG4.GeneratorAction(kernel,
                                           "Geant4InputAction/hepmc%d" % index)
                gen.Input = "Geant4EventReaderHepMC|" + inputFile
            elif inputFile.endswith(".pairs"):
                gen = DDG4.GeneratorAction(
                    kernel, "Geant4InputAction/GuineaPig%d" % index)
                gen.Input = "Geant4EventReaderGuineaPig|" + inputFile
                gen.Parameters = self.guineapig.getParameters()
            else:
                ##this should never happen because we already check at the top, but in case of some LogicError...
                raise RuntimeError("Unknown input file type: %s" % inputFile)
            gen.Sync = self.skipNEvents
            gen.Mask = index
            actionList.append(gen)
            self.__applyBoostOrSmear(kernel, actionList, index)

        if actionList:
            simple.buildInputStage(actionList,
                                   output_level=self.output.inputStage,
                                   have_mctruth=self._enablePrimaryHandler())

        #================================================================================================

        # And handle the simulation particles.
        part = DDG4.GeneratorAction(kernel,
                                    "Geant4ParticleHandler/ParticleHandler")
        kernel.generatorAction().adopt(part)
        #part.SaveProcesses = ['conv','Decay']
        part.SaveProcesses = self.part.saveProcesses
        part.MinimalKineticEnergy = self.part.minimalKineticEnergy
        part.KeepAllParticles = self.part.keepAllParticles
        part.PrintEndTracking = self.part.printEndTracking
        part.PrintStartTracking = self.part.printStartTracking
        part.MinDistToParentVertex = self.part.minDistToParentVertex
        part.OutputLevel = self.output.part
        part.enableUI()

        if self.part.enableDetailedHitsAndParticleInfo:
            self.part.setDumpDetailedParticleInfo(kernel, DDG4)

        #----------------------------------

        user = DDG4.Action(kernel,
                           "Geant4TCUserParticleHandler/UserParticleHandler")
        try:
            user.TrackingVolume_Zmax = DDG4.tracker_region_zmax
            user.TrackingVolume_Rmax = DDG4.tracker_region_rmax

            print " *** definition of tracker region *** "
            print "    tracker_region_zmax = ", user.TrackingVolume_Zmax
            print "    tracker_region_rmax = ", user.TrackingVolume_Rmax
            print " ************************************ "

        except AttributeError as e:
            print "ERROR - attribute of tracker region missing in detector model   ", str(
                e)
            print "   make sure to specify the global constants tracker_region_zmax and tracker_region_rmax "
            print "   this is needed for the MC-truth link of created sim-hits  !  "
            exit(1)

        #  user.enableUI()
        part.adopt(user)

        #=================================================================================

        # Setup global filters for use in sensitive detectors
        try:
            self.filter.setupFilters(kernel)
        except RuntimeError as e:
            print "ERROR", str(e)
            exit(1)

        #=================================================================================
        # get lists of trackers and calorimeters in lcdd

        trk, cal = self.getDetectorLists(lcdd)

        # ---- add the trackers:
        try:
            self.__setupSensitiveDetectors(trk, simple.setupTracker,
                                           self.filter.tracker)
        except Exception as e:
            print "ERROR setting up sensitive detector", str(e)
            raise

    # ---- add the calorimeters:
        try:
            self.__setupSensitiveDetectors(cal, simple.setupCalorimeter,
                                           self.filter.calo)
        except Exception as e:
            print "ERROR setting up sensitive detector", str(e)
            raise

    #=================================================================================
    # Now build the physics list:
        _phys = self.physics.setupPhysics(kernel, name=self.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()

        DD4hep.setPrintLevel(self.printLevel)

        kernel.configure()
        kernel.initialize()

        ## GPS
        if self._g4gun is not None:
            self._g4gun.generator()
        if self._g4gps is not None:
            self._g4gps.generator()

        #DDG4.setPrintLevel(Output.DEBUG)

        kernel.run()
        kernel.terminate()
Beispiel #21
0
def run():
    import LHeD, DDG4, os, SystemOfUnits
    from DDG4 import OutputLevel as Output

    lhed = LHeD.LHeD()
    geant4 = lhed.geant4
    kernel = lhed.kernel
    lhed.loadGeometry()
    geant4.printDetectors()
    kernel.UI = "UI"
    geant4.setupCshUI()
    lhed.setupField(quiet=False)
    DDG4.importConstants(kernel.detectorDescription(), debug=False)

    dd4hep_dir = os.environ['DD4hep']
    kernel.loadXML("file:" + dd4hep_dir +
                   "/examples/LHeD/scripts/DDG4_field.xml")

    geant4 = DDG4.Geant4(kernel, tracker='Geant4TrackerCombineAction')
    geant4.printDetectors()

    # Configure G4 magnetic field tracking
    field = geant4.addConfig(
        'Geant4FieldTrackingSetupAction/MagFieldTrackingSetup')
    field.stepper = "HelixGeant4Runge"
    field.equation = "Mag_UsualEqRhs"
    field.eps_min = 5e-0520 * SystemOfUnits.mm
    field.eps_max = 0.001 * SystemOfUnits.mm
    field.min_chord_step = 0.01 * SystemOfUnits.mm
    field.delta_chord = 0.25 * SystemOfUnits.mm
    field.delta_intersection = 1e-05 * SystemOfUnits.mm
    field.delta_one_step = 0.001 * SystemOfUnits.mm
    print '+++++> ', field.name, '-> stepper  = ', field.stepper
    print '+++++> ', field.name, '-> equation = ', field.equation
    print '+++++> ', field.name, '-> eps_min  = ', field.eps_min
    print '+++++> ', field.name, '-> eps_max  = ', field.eps_max
    print '+++++> ', field.name, '-> delta_one_step = ', field.delta_one_step
    """
  # Setup random generator
  rndm = DDG4.Action(kernel,'Geant4Random/Random')
  rndm.Seed = 987654321
  rndm.initialize()
  rndm.showStatus()
  rndm.Seed = 987654321
  """

    # Configure Run actions
    run1 = DDG4.RunAction(kernel, 'Geant4TestRunAction/RunInit')
    """
  run1.Property_int    = 12345
  run1.Property_double = -5e15*keV
  run1.Property_string = 'Startrun: Hello_LHeD'
  print run1.Property_string, run1.Property_double, run1.Property_int
  """
    run1.enableUI()
    kernel.registerGlobalAction(run1)
    kernel.runAction().adopt(run1)

    # 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)

    # Configure I/O
    #evt_lcio = geant4.setupLCIOOutput('LcioOutput','Lhe_dip_sol_circ-higgs-bb')
    #evt_lcio.OutputLevel = Output.ERROR

    evt_root = geant4.setupROOTOutput('RootOutput',
                                      'Lhe_dip_sol_circ-higgs-bb')
    evt_root.OutputLevel = Output.INFO

    gen = DDG4.GeneratorAction(kernel,
                               "Geant4GeneratorActionInit/GenerationInit")
    kernel.generatorAction().adopt(gen)
    """
  # First particle generator: e-  non-isotropic generation using Gun: 
  gun = DDG4.GeneratorAction(kernel,"Geant4ParticleGenerator/Gun");
  gun.Particle = 'e-'
  gun.Energy = 60 * GeV
  gun.Multiplicity = 1
  gun.Position = (0.*mm,0.*mm,0.*mm)
  gun.Direction = (1.,0.,0.)
  gun.Mask = 2
  gun.enableUI()
  kernel.generatorAction().adopt(gun)
  # Install vertex smearing for this primary e-
  gen = DDG4.GeneratorAction(kernel,"Geant4InteractionVertexSmear/SmearE-");
  gen.Mask = 1
  gen.Sigma = (0*mm, 0*mm, 0*mm, 0*ns)
  kernel.generatorAction().adopt(gen)
  """

    #VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
    """
  Generation of isotrope tracks of a given multiplicity with overlay:
  """
    #VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
    """
  # First particle generator: pi+
  gen = DDG4.GeneratorAction(kernel,"Geant4IsotropeGenerator/IsotropPi+");
  gen.Particle = 'pi+'
  gen.Energy = 200*GeV
  gen.Multiplicity = 1
  gen.Mask = 1
  kernel.generatorAction().adopt(gen)
  # Install vertex smearing for this interaction
  gen = DDG4.GeneratorAction(kernel,"Geant4InteractionVertexSmear/SmearPi+");
  gen.Mask = 1
  gen.Offset = (20*mm, 10*mm, 10*mm, 0*ns)
  gen.Sigma = (4*mm, 1*mm, 1*mm, 0*ns)
  kernel.generatorAction().adopt(gen)

  # Second particle generator: e-
  gen = DDG4.GeneratorAction(kernel,"Geant4IsotropeGenerator/IsotropE-");
  gen.Particle = 'e-'
  gen.Energy = 60 * GeV
  gen.Multiplicity = 2
  gen.Mask = 2
  kernel.generatorAction().adopt(gen)
  # Install vertex smearing for this interaction
  gen = DDG4.GeneratorAction(kernel,"Geant4InteractionVertexSmear/SmearE-");
  gen.Mask = 2
  gen.Offset = (-20*mm, -10*mm, -10*mm, 0*ns)
  gen.Sigma = (12*mm, 8*mm, 8*mm, 0*ns)
  kernel.generatorAction().adopt(gen)
  """
    #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    #VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
    """
  Generation of primary particles from LCIO input files
  """
    #VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV

    # First particle file reader
    gen = DDG4.GeneratorAction(kernel, "LCIOInputAction/LCIO1")
    # gen.Input = "LCIOStdHepReader|/afs/.cern.ch/project/lhec/software/aidasoft/DD4hep/DD4hep/files/NC_bb_tag_2_pythia_events.hep"
    #gen.Input = "LCIOStdHepReader|/opt/DD4hep/files/NC_bb_tag_2_pythia_events.hep"
    gen.Input = "LCIOStdHepReader|/opt/DD4hep/files/lhec_for_peter/tag_2_pythia_events.hep"
    # gen.Input = "LCIOStdHepReader|/opt/DD4hep/files/single-top-tag_1_pythia_events.hep"

    # gen.Input = "Geant4EventReaderHepMC|/opt/DD4hep/files/ePb-q2-0-i.mc2"
    # gen.Input = "LCIOStdHepReader|/opt/DD4hep/files/single-top-tag_1_pythia_events.hep"
    # gen.Input = "LCIOStdHepReader|/opt/DD4hep/files/root.hep"

    gen.OutputLevel = 2  # generator_output_level
    gen.MomentumScale = 1.0
    gen.Mask = 1
    gen.enableUI()
    kernel.generatorAction().adopt(gen)

    # Install vertex smearing for this interaction
    gen = DDG4.GeneratorAction(kernel, "Geant4InteractionVertexSmear/Smear1")
    gen.OutputLevel = 4  #generator_output_level
    gen.Mask = 1
    gen.Offset = (-20 * SystemOfUnits.mm, -10 * SystemOfUnits.mm,
                  -10 * SystemOfUnits.mm, 0 * SystemOfUnits.ns)
    gen.Sigma = (12 * SystemOfUnits.mm, 8 * SystemOfUnits.mm,
                 8 * SystemOfUnits.mm, 0 * SystemOfUnits.ns)
    gen.enableUI()
    kernel.generatorAction().adopt(gen)

    #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    # Merge all existing interaction records
    gen = DDG4.GeneratorAction(kernel,
                               "Geant4InteractionMerger/InteractionMerger")
    gen.OutputLevel = 4  #generator_output_level
    gen.enableUI()
    kernel.generatorAction().adopt(gen)

    # Finally generate Geant4 primaries
    gen = DDG4.GeneratorAction(kernel, "Geant4PrimaryHandler/PrimaryHandler")
    gen.OutputLevel = 4  #generator_output_level
    gen.enableUI()
    kernel.generatorAction().adopt(gen)

    # And handle the simulation particles.
    part = DDG4.GeneratorAction(kernel,
                                "Geant4ParticleHandler/ParticleHandler")
    kernel.generatorAction().adopt(part)
    #part.SaveProcesses = ['conv','Decay']
    part.SaveProcesses = ['Decay']
    part.MinimalKineticEnergy = 10 * SystemOfUnits.MeV
    part.OutputLevel = 5  # generator_output_level
    part.enableUI()

    user = DDG4.Action(kernel,
                       "Geant4TCUserParticleHandler/UserParticleHandler")
    user.TrackingVolume_Zmax = DDG4.EcalEndcap_zmin_fwd
    user.TrackingVolume_Rmax = DDG4.EcalBarrel_rmin
    user.enableUI()
    part.adopt(user)
    """
  rdr = DDG4.GeneratorAction(kernel,"LcioGeneratorAction/Reader")
  rdr.zSpread = 0.0
  rdr.lorentzAngle = 0.0
  rdr.OutputLevel = DDG4.OutputLevel.INFO
  rdr.Input = "LcioEventReader|test.data"
  rdr.enableUI()
  kernel.generatorAction().adopt(rdr)
  """

    # Setup global filters fur use in sensntive detectors
    f1 = DDG4.Filter(kernel, 'GeantinoRejectFilter/GeantinoRejector')
    kernel.registerGlobalFilter(f1)
    f2 = DDG4.Filter(kernel, 'ParticleRejectFilter/OpticalPhotonRejector')
    f2.particle = 'opticalphoton'
    kernel.registerGlobalFilter(f2)
    f3 = DDG4.Filter(kernel, 'ParticleSelectFilter/OpticalPhotonSelector')
    f3.particle = 'opticalphoton'
    kernel.registerGlobalFilter(f3)

    f4 = DDG4.Filter(kernel, 'EnergyDepositMinimumCut')
    f4.Cut = 0.5 * SystemOfUnits.MeV
    f4.enableUI()
    kernel.registerGlobalFilter(f4)

    # First the tracking detectors
    seq, act = geant4.setupTracker('SiVertexBarrel')
    seq.adopt(f1)
    act.adopt(f1)

    seq, act = geant4.setupTracker('SiTrackerBarrel')
    seq.adopt(f1)
    act.adopt(f1)
    seq, act = geant4.setupTracker('SiTrackerForward')
    seq.adopt(f1)
    act.adopt(f1)
    seq, act = geant4.setupTracker('SiTrackerBackward')
    seq.adopt(f1)
    act.adopt(f1)

    # Now the calorimeters
    seq, act = geant4.setupCalorimeter('EcalBarrel')
    seq.adopt(f3)
    act.adopt(f3)
    seq.adopt(f4)
    act.adopt(f4)

    seq, act = geant4.setupCalorimeter('EcalEndcap_fwd')
    seq.adopt(f3)
    act.adopt(f3)
    seq.adopt(f4)
    act.adopt(f4)
    seq, act = geant4.setupCalorimeter('EcalEndcap_bwd')
    seq.adopt(f3)
    act.adopt(f3)
    seq.adopt(f4)
    act.adopt(f4)

    seq, act = geant4.setupCalorimeter('HcalBarrel')
    seq.adopt(f3)
    act.adopt(f3)
    seq.adopt(f4)
    act.adopt(f4)
    seq, act = geant4.setupCalorimeter('HcalEndcap_fwd')
    seq.adopt(f3)
    act.adopt(f3)
    seq.adopt(f4)
    act.adopt(f4)
    seq, act = geant4.setupCalorimeter('HcalEndcap_bwd')
    seq.adopt(f3)
    act.adopt(f3)
    seq.adopt(f4)
    act.adopt(f4)

    seq, act = geant4.setupCalorimeter('HcalPlug_fwd')
    seq.adopt(f3)
    act.adopt(f3)
    seq.adopt(f4)
    act.adopt(f4)
    seq, act = geant4.setupCalorimeter('HcalPlug_bwd')
    seq.adopt(f3)
    act.adopt(f3)
    seq.adopt(f4)
    act.adopt(f4)

    seq, act = geant4.setupCalorimeter('MuonBarrel')
    seq.adopt(f2)
    act.adopt(f2)
    seq, act = geant4.setupCalorimeter('MuonEndcap_fwd1')
    seq.adopt(f2)
    act.adopt(f2)
    seq, act = geant4.setupCalorimeter('MuonEndcap_fwd2')
    seq.adopt(f2)
    act.adopt(f2)
    seq, act = geant4.setupCalorimeter('MuonEndcap_bwd1')
    seq.adopt(f2)
    act.adopt(f2)
    seq, act = geant4.setupCalorimeter('MuonEndcap_bwd2')
    seq.adopt(f2)
    act.adopt(f2)
    """
  scan = DDG4.SteppingAction(kernel,'Geant4MaterialScanner/MaterialScan')
  kernel.steppingAction().adopt(scan)
  """

    # Now build the physics list:
    phys = geant4.setupPhysics('QGSP_BERT')
    ph = DDG4.PhysicsList(kernel, 'Geant4PhysicsList/Myphysics')
    ph.addParticleConstructor('G4Geantino')
    ph.addParticleConstructor('G4BosonConstructor')
    ph.addParticleConstructor('G4LeptonConstructor')
    ph.addParticleProcess('e[+-]', 'G4eMultipleScattering', -1, 1, 1)
    ph.addPhysicsConstructor('G4OpticalPhysics')
    ph.enableUI()
    phys.adopt(ph)
    phys.dump()

    kernel.configure()
    kernel.initialize()

    #DDG4.setPrintLevel(Output.DEBUG)
    kernel.run()
    print 'End of run. Terminating .......'
    kernel.terminate()
Beispiel #22
0
def run():
  kernel = DDG4.Kernel()
  description = kernel.detectorDescription()
  install_dir = os.environ['DD4hepINSTALL']
  example_dir = install_dir+'/examples/DDG4/examples';
  kernel.loadGeometry("file:"+install_dir+"/DDDetectors/compact/SiD_Markus.xml")
  ##kernel.loadXML("file:"+example_dir+"/DDG4_field.xml")
  DDG4.importConstants(description,debug=False)
  geant4 = DDG4.Geant4(kernel,tracker='Geant4TrackerCombineAction')
  geant4.printDetectors()
  # Configure UI
  #geant4.setupCshUI(macro='run.mac',ui=None)
  geant4.setupCshUI()
  geant4.setupTrackingField()

  # Configure Run actions
  run1 = DDG4.RunAction(kernel,'Geant4TestRunAction/RunInit')
  run1.enableUI()
  kernel.registerGlobalAction(run1)
  kernel.runAction().adopt(run1)

  # Configure Event actions
  prt = DDG4.EventAction(kernel,'Geant4ParticlePrint/ParticlePrint')
  prt.OutputLevel = Output.WARNING
  prt.OutputType  = 3 # Print both: table and tree
  kernel.eventAction().adopt(prt)

  generator_output_level = Output.WARNING

  # Configure I/O
  evt_lcio = geant4.setupLCIOOutput('LcioOutput','CLICSiD_'+time.strftime('%Y-%m-%d_%H-%M'))
  ##evt_lcio.OutputLevel = generator_output_level
  #evt_root = geant4.setupROOTOutput('RootOutput','CLICSiD_'+time.strftime('%Y-%m-%d_%H-%M'))

  prim = DDG4.GeneratorAction(kernel,"Geant4GeneratorActionInit/GenerationInit")
  #VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
  """
  Generation of primary particles from LCIO input files
  """
  """
  # First particle file reader
  gen = DDG4.GeneratorAction(kernel,"LCIOInputAction/LCIO1");
  #gen.Input = "LCIOStdHepReader|/home/frankm/SW/data/e2e2nn_gen_1343_1.stdhep"
  #gen.Input = "LCIOStdHepReader|/home/frankm/SW/data/qq_gen_128_999.stdhep"
  #gen.Input = "LCIOStdHepReader|/home/frankm/SW/data/smuonLR_PointK_3TeV_BS_noBkg_run0001.stdhep"
  #gen.Input = "LCIOStdHepReader|/home/frankm/SW/data/bbbb_3TeV.stdhep"
  #gen.Input = "LCIOFileReader|/home/frankm/SW/data/mcparticles_pi-_5GeV.slcio"
  #gen.Input = "LCIOFileReader|/home/frankm/SW/data/mcparticles_mu-_5GeV.slcio"
  #gen.Input = "LCIOFileReader|/home/frankm/SW/data/bbbb_3TeV.slcio"
  #gen.Input = "LCIOStdHepReader|/home/frankm/SW/data/FCC-eh.stdhep"
  #gen.Input = "Geant4EventReaderHepMC|/home/frankm/SW/data/data.hepmc.txt"
  #gen.Input = "Geant4EventReaderHepMC|/home/frankm/SW/data/sherpa-2.1.1_zjets.hepmc2g"
  gen.Input = "LCIOFileReader|/afs/cern.ch/user/n/nikiforo/public/Markus/muons.slcio"
  #gen.Input = "LCIOFileReader|/afs/cern.ch/user/n/nikiforo/public/Markus/geantinos.slcio"
  gen.MomentumScale = 1.0
  gen.Mask = 1
  geant4.buildInputStage([gen],output_level=generator_output_level)
  """
  #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  gen = geant4.setupGun("Gun",particle='mu+',energy=20*GeV,position=(0*mm,0*mm,0*cm),multiplicity=3)
  gen.isotrop = True
  gen.direction = (1,0,0)
  gen.OutputLevel = generator_output_level
  gen.Standalone = False
  """
  # 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.EcalEndcap_zmin
  user.TrackingVolume_Rmax = DDG4.EcalBarrel_rmin
  user.enableUI()
  part.adopt(user)
  """
  geant4.buildInputStage([prim,gen],Output.ERROR)

  """
  """

  """
  rdr = DDG4.GeneratorAction(kernel,"LcioGeneratorAction/Reader")
  rdr.zSpread = 0.0
  rdr.lorentzAngle = 0.0
  rdr.OutputLevel = DDG4.OutputLevel.INFO
  rdr.Input = "LcioEventReader|test.data"
  rdr.enableUI()
  kernel.generatorAction().adopt(rdr)
  """


  # First the tracking detectors
  seq,act = geant4.setupTracker('SiTrackerBarrel')
  seq,act = geant4.setupTracker('SiTrackerEndcap')
  seq,act = geant4.setupTracker('SiTrackerForward')
  """
  # Now the calorimeters
  seq,act = geant4.setupTracker('SiVertexBarrel')
  seq,act = geant4.setupTracker('SiVertexEndcap')

  seq,act = geant4.setupCalorimeter('EcalBarrel')
  seq,act = geant4.setupCalorimeter('EcalEndcap')
  seq,act = geant4.setupCalorimeter('HcalBarrel')
  seq,act = geant4.setupCalorimeter('HcalEndcap')
  seq,act = geant4.setupCalorimeter('HcalPlug')
  seq,act = geant4.setupCalorimeter('MuonBarrel')
  seq,act = geant4.setupCalorimeter('MuonEndcap')
  seq,act = geant4.setupCalorimeter('LumiCal')
  seq,act = geant4.setupCalorimeter('BeamCal')
  """
  """
  scan = DDG4.SteppingAction(kernel,'Geant4MaterialScanner/MaterialScan')
  kernel.steppingAction().adopt(scan)
  """


  # Now build the physics list:
  phys = geant4.setupPhysics('QGSP_BERT')
  ph = DDG4.PhysicsList(kernel,'Geant4PhysicsList/Myphysics')
  ph.addParticleConstructor('G4Geantino')
  ph.addParticleConstructor('G4BosonConstructor')
  ph.enableUI()
  phys.adopt(ph)
  phys.dump()

  kernel.configure()
  kernel.initialize()

  #DDG4.setPrintLevel(Output.DEBUG)
  kernel.run()
  logging.info('End of run. Terminating .......')
  kernel.terminate()
Beispiel #23
0
def run():

  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)

#  example_dir = lcgeo_dir+'/example';

  kernel.loadGeometry("file:"+ compactFile )

  lcdd = kernel.lcdd() 

  DDG4.importConstants( lcdd ) 

#----------------------------------------------------------------------------------

  simple = DDG4.Geant4( kernel, tracker='Geant4TrackerAction',calo='Geant4CalorimeterAction')
## Apply BirksLaw effect for Scintillator Calorimeter by using 'Geant4ScintillatorCalorimeterAction'.
#  simple = DDG4.Geant4( kernel, tracker='Geant4TrackerAction',calo='Geant4ScintillatorCalorimeterAction')

  simple.printDetectors()

  # Configure UI
  #simple.setupCshUI()
  simple.setupUI()

  kernel.UI=""
  kernel.NumEvents=numberOfEvents 

#-----------------------------------------------------------------------------------
#  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']    

#----------------------------------------------------------------------------------

  # 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 )
  
  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 , ')'
    seq,act = simple.setupTracker( t )
    seq.add(f1)
    act.HitCreationMode = 2

# ---- add the calorimeters:

  for c in cal:
    print 'simple.setupCalorimeter(  ' , c , ')'
    seq,act = simple.setupCalorimeter( c )


#=================================================================================
  # 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()
Beispiel #24
0
def run():
  import CLICSid
  import DDG4
  import os
  import sys
  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)

  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 = os.environ['DD4hepExamplesINSTALL'] + '/examples/DDG4/data/hepmc_geant4.dat'
  input.Input = "Geant4EventReaderHepMC|" + 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')
  sid.test_run(have_geo=True, num_events=1)
Beispiel #25
0
def run():
  global geant4
  kernel = DDG4.Kernel()
  description = kernel.detectorDescription()
  install_dir = os.environ['DD4hepINSTALL']
  kernel.loadGeometry(str("file:" + install_dir + "/DDDetectors/compact/SiD_Markus.xml"))
  DDG4.importConstants(description)
  DDG4.Core.setPrintLevel(Output.DEBUG)
  DDG4.Core.setPrintFormat(str("%-32s %6s %s"))

  kernel.NumberOfThreads = 1
  geant4 = DDG4.Geant4(kernel, tracker='Geant4TrackerWeightedAction')
  geant4.printDetectors()
  # Configure UI
  geant4.setupCshUI()

  # Geant4 user initialization action
  geant4.addUserInitialization(worker=setupWorker, master=setupMaster)

  # Configure G4 geometry setup
  seq, act = geant4.addDetectorConstruction("Geant4DetectorGeometryConstruction/ConstructGeo")

  # Configure G4 magnetic field tracking
  self.setupTrackingFieldMT()  # noqa: F821

  seq, act = geant4.addDetectorConstruction("Geant4PythonDetectorConstruction/DummyDet",
                                            geometry=dummy_geom,
                                            sensitives=dummy_sd)
  # Configure G4 sensitive detectors
  seq, act = geant4.addDetectorConstruction("Geant4PythonDetectorConstruction/SetupSD",
                                            sensitives=setupSensitives)

  # Configure G4 sensitive detectors
  seq, act = geant4.addDetectorConstruction("Geant4DetectorSensitivesConstruction/ConstructSD",
                                            allow_threads=True)

  # Setup random generator
  rndm = DDG4.Action(kernel, 'Geant4Random/Random')
  rndm.Seed = 987654321
  rndm.initialize()

  # Setup global filters fur use in sensntive detectors
  f1 = DDG4.Filter(kernel, 'GeantinoRejectFilter/GeantinoRejector')
  kernel.registerGlobalFilter(f1)

  # seq,act = geant4.setupTracker('SiTrackerBarrel')
  # seq,act = geant4.setupTracker('SiTrackerEndcap')
  # seq,act = geant4.setupTracker('SiTrackerForward')
  # Now the calorimeters
  # seq,act = geant4.setupCalorimeter('EcalBarrel')
  # seq,act = geant4.setupCalorimeter('EcalEndcap')
  # seq,act = geant4.setupCalorimeter('HcalBarrel')
  # seq,act = geant4.setupCalorimeter('HcalEndcap')
  # seq,act = geant4.setupCalorimeter('HcalPlug')
  # seq,act = geant4.setupCalorimeter('MuonBarrel')
  # seq,act = geant4.setupCalorimeter('MuonEndcap')
  # seq,act = geant4.setupCalorimeter('LumiCal')
  # seq,act = geant4.setupCalorimeter('BeamCal')

  # Now build the physics list:
  seq = geant4.setupPhysics('QGSP_BERT')
  phys = DDG4.PhysicsList(geant4.master(), 'Geant4PhysicsList/MyPhysics')
  part = DDG4.Action(geant4.master(), 'Geant4ExtraParticles/extraparts')
  part.pdgfile = 'checkout/DDG4/examples/particle.tbl'
  phys.adoptPhysicsConstructor(part.get())
  seq.add(phys)

  geant4.run()

  # kernel.configure()
  # kernel.initialize()

  # DDG4.setPrintLevel(Output.DEBUG)
  # kernel.run()
  # kernel.terminate()
  return 1
Beispiel #26
0
def run():
    kernel = DDG4.Kernel()
    description = kernel.detectorDescription()
    install_dir = os.environ['DD4hepINSTALL']
    DDG4.Core.setPrintFormat("%-32s %6s %s")
    kernel.loadGeometry("file:" + install_dir + "/DDDetectors/compact/SiD.xml")
    DDG4.importConstants(description)

    kernel.NumberOfThreads = 3
    geant4 = DDG4.Geant4(kernel, tracker='Geant4TrackerCombineAction')
    print "#  Configure UI"
    geant4.setupCshUI()

    print "#  Geant4 user initialization action"
    geant4.addUserInitialization(worker=setupWorker,
                                 worker_args=(geant4, ),
                                 master=setupMaster,
                                 master_args=(geant4, ))

    print "#  Configure G4 geometry setup"
    seq, act = geant4.addDetectorConstruction(
        "Geant4DetectorGeometryConstruction/ConstructGeo")

    print "# Configure G4 sensitive detectors: python setup callback"
    seq, act = geant4.addDetectorConstruction(
        "Geant4PythonDetectorConstruction/SetupSD",
        sensitives=setupSensitives,
        sensitives_args=(geant4, ))
    print "# Configure G4 sensitive detectors: atach'em to the sensitive volumes"
    seq, act = geant4.addDetectorConstruction(
        "Geant4DetectorSensitivesConstruction/ConstructSD")
    #                                           allow_threads=True)

    print "#  Configure G4 magnetic field tracking"
    seq, field = geant4.addDetectorConstruction(
        "Geant4FieldTrackingConstruction/MagFieldTrackingSetup")
    field.stepper = "HelixGeant4Runge"
    field.equation = "Mag_UsualEqRhs"
    field.eps_min = 5e-05 * mm
    field.eps_max = 0.001 * mm
    field.min_chord_step = 0.01 * mm
    field.delta_chord = 0.25 * mm
    field.delta_intersection = 1e-05 * mm
    field.delta_one_step = 0.001 * mm
    print '+++++> ', field.name, '-> stepper  = ', field.stepper
    print '+++++> ', field.name, '-> equation = ', field.equation
    print '+++++> ', field.name, '-> eps_min  = ', field.eps_min
    print '+++++> ', field.name, '-> eps_max  = ', field.eps_max
    print '+++++> ', field.name, '-> delta_one_step = ', field.delta_one_step

    print "#  Setup random generator"
    rndm = DDG4.Action(kernel, 'Geant4Random/Random')
    rndm.Seed = 987654321
    rndm.initialize()
    ##rndm.showStatus()

    print "#  Now build the physics list:"
    phys = geant4.setupPhysics('QGSP_BERT')
    phys.dump()

    geant4.run()
Beispiel #27
0
def run():
    geo = None
    vis = False
    dump = False
    batch = False
    install_dir = os.environ['DD4hepINSTALL']
    #
    for i in list(range(len(sys.argv))):
        c = sys.argv[i].upper()
        if c.find('BATCH') < 2 and c.find('BATCH') >= 0:
            batch = True
        elif c[:4] == '-GEO':
            geo = sys.argv[i + 1]
        elif c[:4] == '-VIS':
            vis = True
        elif c[:4] == '-DUM':
            dump = True

    if not geo:
        help()
        sys.exit(1)

    import DDG4
    kernel = DDG4.Kernel()
    description = kernel.detectorDescription()
    DDG4.setPrintLevel(DDG4.OutputLevel.INFO)
    DDG4.importConstants(description)
    #
    # Configure UI
    geant4 = DDG4.Geant4(kernel)
    ui = None
    if batch:
        geant4.setupCshUI(ui=None, vis=None)
        kernel.UI = 'UI'
    else:
        ui = geant4.setupCshUI(vis=vis)
    Output = DDG4.OutputLevel

    seq, act = geant4.addDetectorConstruction(
        "Geant4DetectorGeometryConstruction/ConstructGeo")
    act.DebugReflections = True
    act.DebugMaterials = False
    act.DebugElements = False
    act.DebugVolumes = False
    act.DebugShapes = False
    if dump:
        act.DumpHierarchy = ~0x0
    #
    kernel.setOutputLevel(str('Geant4Converter'), Output.WARNING)
    kernel.loadGeometry(geo)
    #
    geant4.printDetectors()
    # Configure field
    geant4.setupTrackingField(prt=True)
    logger.info("#  Setup random generator")
    rndm = DDG4.Action(kernel, 'Geant4Random/Random')
    rndm.Seed = 987654321
    rndm.initialize()
    #
    # Setup detector
    seq, act = geant4.setupCalorimeter('NestedBox')
    #
    # Configure I/O
    geant4.setupROOTOutput('RootOutput',
                           'Reflections_' + time.strftime('%Y-%m-%d_%H-%M'),
                           mc_truth=True)
    #
    # Setup particle gun
    geant4.setupGun(name="Gun",
                    particle='e-',
                    energy=1000 * GeV,
                    isotrop=True,
                    multiplicity=1,
                    position=(0 * m, 0 * m, 0 * m),
                    PhiMin=0.0 * rad,
                    PhiMax=math.pi * 2.0 * rad,
                    ThetaMin=0.0 * rad,
                    ThetaMax=math.pi * rad)

    logger.info("#  ....and handle the simulation particles.")
    part = DDG4.GeneratorAction(kernel,
                                str('Geant4ParticleHandler/ParticleHandler'))
    kernel.generatorAction().adopt(part)
    part.MinimalKineticEnergy = 100 * MeV
    part.SaveProcesses = ['Decay']
    part.OutputLevel = 5  # generator_output_level
    part.enableUI()
    user = DDG4.Action(kernel,
                       str('Geant4TCUserParticleHandler/UserParticleHandler'))
    user.TrackingVolume_Rmax = 3.0 * m
    user.TrackingVolume_Zmax = 2.0 * m
    user.enableUI()
    part.adopt(user)
    #
    #
    prt = DDG4.EventAction(kernel, str('Geant4ParticlePrint/ParticlePrint'))
    prt.OutputLevel = Output.INFO
    prt.OutputType = 3  # Print both: table and tree
    kernel.eventAction().adopt(prt)
    #
    # Now build the physics list:
    phys = geant4.setupPhysics(str('QGSP_BERT'))
    ph = geant4.addPhysics(str('Geant4PhysicsList/Myphysics'))
    ph.addPhysicsConstructor(str('G4StepLimiterPhysics'))
    ph.addParticleConstructor(str('G4Geantino'))
    ph.addParticleConstructor(str('G4BosonConstructor'))
    #
    # Add special particle types from specialized physics constructor
    part = geant4.addPhysics('Geant4ExtraParticles/ExtraParticles')
    part.pdgfile = os.path.join(install_dir,
                                'examples/DDG4/examples/particle.tbl')
    #
    # Add global range cut
    rg = geant4.addPhysics('Geant4DefaultRangeCut/GlobalRangeCut')
    rg.RangeCut = 0.7 * mm
    #
    phys.dump()
    #
    #
    if ui and vis:
        cmds = []
        cmds.append('/control/verbose 2')
        cmds.append('/run/initialize')
        cmds.append('/vis/open OGL')
        cmds.append('/vis/verbose errors')
        cmds.append('/vis/drawVolume')
        cmds.append('/vis/viewer/set/viewpointThetaPhi 55. 45.')
        cmds.append('/vis/scene/add/axes 0 0 0 3 m')
        ui.Commands = cmds
    kernel.NumEvents = 0
    kernel.configure()
    kernel.initialize()
    kernel.run()
    kernel.terminate()
Beispiel #28
0
def run():
    hlp = False
    vis = False
    batch = False
    #
    for i in list(range(len(sys.argv))):
        c = sys.argv[i].upper()
        if c.find('BATCH') < 2 and c.find('BATCH') >= 0:
            batch = True
        elif c[:4] == '-VIS':
            vis = True
        elif c[:2] == '-H':
            hlp = True

    if hlp:
        help()
        sys.exit(1)

    kernel = DDG4.Kernel()
    description = kernel.detectorDescription()
    install_dir = os.environ['DD4hepINSTALL']
    kernel.loadGeometry(
        str("file:" + install_dir + "/DDDetectors/compact/SiD.xml"))
    DDG4.importConstants(description)

    geant4 = DDG4.Geant4(kernel, tracker='Geant4TrackerCombineAction')
    geant4.printDetectors()
    logger.info("#  Configure UI")
    ui = None
    if batch:
        geant4.setupCshUI(ui=None, vis=None)
        kernel.UI = 'UI'
    else:
        ui = geant4.setupCshUI(vis=vis)

    logger.info("#  Configure G4 magnetic field tracking")
    geant4.setupTrackingField()

    logger.info("#  Setup random generator")
    rndm = DDG4.Action(kernel, 'Geant4Random/Random')
    rndm.Seed = 987654321
    rndm.initialize()
    # rndm.showStatus()

    logger.info("#  Configure Run actions")
    run1 = DDG4.RunAction(kernel, 'Geant4TestRunAction/RunInit')
    run1.Property_int = 12345
    run1.Property_double = -5e15 * keV
    run1.Property_string = 'Startrun: Hello_2'
    logger.info("%s %s %s", run1.Property_string, str(run1.Property_double),
                str(run1.Property_int))
    run1.enableUI()
    kernel.registerGlobalAction(run1)
    kernel.runAction().adopt(run1)

    logger.info("#  Configure Event actions")
    prt = DDG4.EventAction(kernel, 'Geant4ParticlePrint/ParticlePrint')
    prt.OutputLevel = Output.INFO
    prt.OutputType = 3  # Print both: table and tree
    kernel.eventAction().adopt(prt)

    logger.info("""
  Configure I/O
  """)
    # evt_lcio = geant4.setupLCIOOutput('LcioOutput','CLICSiD_'+time.strftime('%Y-%m-%d_%H-%M'))
    # evt_lcio.OutputLevel = Output.ERROR

    geant4.setupROOTOutput('RootOutput',
                           'CLICSiD_' + time.strftime('%Y-%m-%d_%H-%M'))

    gen = DDG4.GeneratorAction(kernel,
                               "Geant4GeneratorActionInit/GenerationInit")
    kernel.generatorAction().adopt(gen)

    # VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
    logger.info("""
  Generation of isotrope tracks of a given multiplicity with overlay:
  """)
    logger.info("#  First particle generator: pi+")
    gen = DDG4.GeneratorAction(kernel, "Geant4IsotropeGenerator/IsotropPi+")
    gen.Mask = 1
    gen.Particle = 'pi+'
    gen.Energy = 100 * GeV
    gen.Multiplicity = 2
    gen.Distribution = 'cos(theta)'
    kernel.generatorAction().adopt(gen)
    logger.info("#  Install vertex smearing for this interaction")
    gen = DDG4.GeneratorAction(kernel, "Geant4InteractionVertexSmear/SmearPi+")
    gen.Mask = 1
    gen.Offset = (20 * mm, 10 * mm, 10 * mm, 0 * ns)
    gen.Sigma = (4 * mm, 1 * mm, 1 * mm, 0 * ns)
    kernel.generatorAction().adopt(gen)

    logger.info("#  Second particle generator: e-")
    gen = DDG4.GeneratorAction(kernel, "Geant4IsotropeGenerator/IsotropE-")
    gen.Mask = 2
    gen.Particle = 'e-'
    gen.Energy = 25 * GeV
    gen.Multiplicity = 2
    gen.Distribution = 'uniform'
    kernel.generatorAction().adopt(gen)
    logger.info("  Install vertex smearing for this interaction")
    gen = DDG4.GeneratorAction(kernel, "Geant4InteractionVertexSmear/SmearE-")
    gen.Mask = 2
    gen.Offset = (-20 * mm, -10 * mm, -10 * mm, 0 * ns)
    gen.Sigma = (12 * mm, 8 * mm, 8 * mm, 0 * ns)
    kernel.generatorAction().adopt(gen)

    logger.info("#  Second particle generator: mu+")
    gen = DDG4.GeneratorAction(kernel, "Geant4IsotropeGenerator/IsotropMu+")
    gen.Mask = 3
    gen.Particle = 'mu+'
    gen.Energy = 100 * GeV
    gen.Multiplicity = 3
    gen.Distribution = 'uniform'
    kernel.generatorAction().adopt(gen)
    # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    logger.info("#  Merge all existing interaction records")
    gen = DDG4.GeneratorAction(kernel,
                               "Geant4InteractionMerger/InteractionMerger")
    gen.OutputLevel = 4  # generator_output_level
    gen.enableUI()
    kernel.generatorAction().adopt(gen)
    #
    logger.info("#  Finally generate Geant4 primaries")
    gen = DDG4.GeneratorAction(kernel, "Geant4PrimaryHandler/PrimaryHandler")
    gen.OutputLevel = 4  # generator_output_level
    gen.enableUI()
    kernel.generatorAction().adopt(gen)
    #
    logger.info("#  ....and handle the simulation particles.")
    part = DDG4.GeneratorAction(kernel,
                                "Geant4ParticleHandler/ParticleHandler")
    kernel.generatorAction().adopt(part)
    # part.SaveProcesses = ['conv','Decay']
    part.SaveProcesses = ['Decay']
    part.MinimalKineticEnergy = 100 * MeV
    part.OutputLevel = 5  # generator_output_level
    part.enableUI()
    user = DDG4.Action(kernel,
                       "Geant4TCUserParticleHandler/UserParticleHandler")
    user.TrackingVolume_Zmax = DDG4.EcalEndcap_zmin
    user.TrackingVolume_Rmax = DDG4.EcalBarrel_rmin
    user.enableUI()
    part.adopt(user)
    #
    logger.info("#  Setup global filters fur use in sensitive detectors")
    f1 = DDG4.Filter(kernel, 'GeantinoRejectFilter/GeantinoRejector')
    f2 = DDG4.Filter(kernel, 'ParticleRejectFilter/OpticalPhotonRejector')
    f2.particle = 'opticalphoton'
    f3 = DDG4.Filter(kernel, 'ParticleSelectFilter/OpticalPhotonSelector')
    f3.particle = 'opticalphoton'
    f4 = DDG4.Filter(kernel, 'EnergyDepositMinimumCut')
    f4.Cut = 10 * MeV
    f4.enableUI()
    kernel.registerGlobalFilter(f1)
    kernel.registerGlobalFilter(f2)
    kernel.registerGlobalFilter(f3)
    kernel.registerGlobalFilter(f4)
    #
    logger.info("#  First the tracking detectors")
    seq, act = geant4.setupTracker('SiVertexBarrel')
    seq.adopt(f1)
    act.adopt(f1)
    #
    seq, act = geant4.setupTracker('SiVertexEndcap')
    seq.adopt(f1)
    #
    seq, act = geant4.setupTracker('SiTrackerBarrel')
    seq, act = geant4.setupTracker('SiTrackerEndcap')
    seq, act = geant4.setupTracker('SiTrackerForward')
    logger.info("#  Now setup the calorimeters")
    seq, act = geant4.setupCalorimeter('EcalBarrel')
    seq, act = geant4.setupCalorimeter('EcalEndcap')
    seq, act = geant4.setupCalorimeter('HcalBarrel')
    seq, act = geant4.setupCalorimeter('HcalEndcap')
    seq, act = geant4.setupCalorimeter('HcalPlug')
    seq, act = geant4.setupCalorimeter('MuonBarrel')
    seq, act = geant4.setupCalorimeter('MuonEndcap')
    seq, act = geant4.setupCalorimeter('LumiCal')
    seq, act = geant4.setupCalorimeter('BeamCal')
    #
    logger.info("#  Now build the physics list:")
    phys = geant4.setupPhysics('QGSP_BERT')
    ph = geant4.addPhysics(str('Geant4PhysicsList/Myphysics'))
    ph.addPhysicsConstructor(str('G4StepLimiterPhysics'))
    #
    # Add special particle types from specialized physics constructor
    part = geant4.addPhysics(str('Geant4ExtraParticles/ExtraParticles'))
    part.pdgfile = os.path.join(install_dir,
                                'examples/DDG4/examples/particle.tbl')
    #
    # Add global range cut
    rg = geant4.addPhysics(str('Geant4DefaultRangeCut/GlobalRangeCut'))
    rg.RangeCut = 0.7 * mm
    #
    phys.dump()
    #
    #
    if ui and vis:
        cmds = []
        cmds.append('/control/verbose 2')
        cmds.append('/run/initialize')
        cmds.append('/vis/open OGL')
        cmds.append('/vis/verbose errors')
        cmds.append('/vis/drawVolume')
        cmds.append('/vis/viewer/set/viewpointThetaPhi 55. 45.')
        cmds.append('/vis/scene/add/axes 0 0 0 10 m')
        ui.Commands = cmds

    kernel.configure()
    kernel.initialize()

    # DDG4.setPrintLevel(Output.DEBUG)
    kernel.run()
    kernel.terminate()
Beispiel #29
0
    def run(self):
        """setup the geometry and dd4hep and geant4 and do what was asked to be done"""
        import ROOT
        ROOT.PyConfig.IgnoreCommandLineOptions = True

        import DDG4, dd4hep

        self.printLevel = getOutputLevel(self.printLevel)

        kernel = DDG4.Kernel()
        dd4hep.setPrintLevel(self.printLevel)
        #kernel.setOutputLevel('Compact',1)

        kernel.loadGeometry("file:" + self.compactFile)
        detectorDescription = kernel.detectorDescription()

        DDG4.importConstants(detectorDescription)

        #----------------------------------------------------------------------------------

        #simple = DDG4.Geant4( kernel, tracker='Geant4TrackerAction',calo='Geant4CalorimeterAction')
        #simple = DDG4.Geant4( kernel, tracker='Geant4TrackerCombineAction',calo='Geant4ScintillatorCalorimeterAction')
        simple = DDG4.Geant4(kernel,
                             tracker=self.action.tracker,
                             calo=self.action.calo)

        simple.printDetectors()

        if self.runType == "vis":
            simple.setupUI(typ="csh", vis=True, macro=self.macroFile)
        elif self.runType == "run":
            simple.setupUI(typ="csh",
                           vis=False,
                           macro=self.macroFile,
                           ui=False)
        elif self.runType == "shell":
            simple.setupUI(typ="csh", vis=False, macro=None, ui=True)
        elif self.runType == "batch":
            simple.setupUI(typ="csh", vis=False, macro=None, ui=False)
        else:
            print "ERROR: unknown runType"
            exit(1)

        #kernel.UI="csh"
        kernel.NumEvents = self.numberOfEvents

        #-----------------------------------------------------------------------------------
        # setup the magnetic field:
        self.__setMagneticFieldOptions(simple)

        #----------------------------------------------------------------------------------

        # Configure Run actions
        run1 = DDG4.RunAction(kernel, 'Geant4TestRunAction/RunInit')
        kernel.registerGlobalAction(run1)
        kernel.runAction().add(run1)

        # Configure the random seed, do it before the I/O because we might change the seed!
        _rndm = self.random.initialize(DDG4, kernel, self.output.random)

        # Configure I/O
        if self.outputFile.endswith(".slcio"):
            lcOut = simple.setupLCIOOutput('LcioOutput', self.outputFile)
            lcOut.RunHeader = self.meta.addParametersToRunHeader(self)
            lcOut.EventParametersString, lcOut.EventParametersInt, lcOut.EventParametersFloat = self.meta.parseEventParameters(
            )
            lcOut.RunNumberOffset = self.meta.runNumberOffset if self.meta.runNumberOffset > 0 else 0
            lcOut.EventNumberOffset = self.meta.eventNumberOffset if self.meta.eventNumberOffset > 0 else 0
        elif self.outputFile.endswith(".root"):
            simple.setupROOTOutput('RootOutput', self.outputFile)

        actionList = []

        if self.enableGun:
            gun = DDG4.GeneratorAction(kernel, "Geant4ParticleGun/" + "Gun")
            self.gun.setOptions(gun)
            gun.Standalone = False
            gun.Mask = 1
            actionList.append(gun)
            self.__applyBoostOrSmear(kernel, actionList, 1)
            print "++++ Adding DD4hep Particle Gun ++++"

        if self.enableG4Gun:
            ## GPS Create something
            self._g4gun = DDG4.GeneratorAction(kernel,
                                               "Geant4GeneratorWrapper/Gun")
            self._g4gun.Uses = 'G4ParticleGun'
            self._g4gun.Mask = 2
            print "++++ Adding Geant4 Particle Gun ++++"
            actionList.append(self._g4gun)

        if self.enableG4GPS:
            ## GPS Create something
            self._g4gps = DDG4.GeneratorAction(kernel,
                                               "Geant4GeneratorWrapper/GPS")
            self._g4gps.Uses = 'G4GeneralParticleSource'
            self._g4gps.Mask = 3
            print "++++ Adding Geant4 General Particle Source ++++"
            actionList.append(self._g4gps)

        for index, inputFile in enumerate(self.inputFiles, start=4):
            if inputFile.endswith(".slcio"):
                gen = DDG4.GeneratorAction(kernel,
                                           "LCIOInputAction/LCIO%d" % index)
                gen.Parameters = self.lcio.getParameters()
                gen.Input = "LCIOFileReader|" + inputFile
            elif inputFile.endswith(".stdhep"):
                gen = DDG4.GeneratorAction(kernel,
                                           "LCIOInputAction/STDHEP%d" % index)
                gen.Input = "LCIOStdHepReader|" + inputFile
            elif inputFile.endswith(".HEPEvt"):
                gen = DDG4.GeneratorAction(
                    kernel, "Geant4InputAction/HEPEvt%d" % index)
                gen.Input = "Geant4EventReaderHepEvtShort|" + inputFile
            elif inputFile.endswith(".hepevt"):
                gen = DDG4.GeneratorAction(
                    kernel, "Geant4InputAction/hepevt%d" % index)
                gen.Input = "Geant4EventReaderHepEvtLong|" + inputFile
            elif inputFile.endswith(".hepmc"):
                gen = DDG4.GeneratorAction(kernel,
                                           "Geant4InputAction/hepmc%d" % index)
                gen.Input = "Geant4EventReaderHepMC|" + inputFile
            elif inputFile.endswith(".pairs"):
                gen = DDG4.GeneratorAction(
                    kernel, "Geant4InputAction/GuineaPig%d" % index)
                gen.Input = "Geant4EventReaderGuineaPig|" + inputFile
                gen.Parameters = self.guineapig.getParameters()
            else:
                ##this should never happen because we already check at the top, but in case of some LogicError...
                raise RuntimeError("Unknown input file type: %s" % inputFile)
            gen.Sync = self.skipNEvents
            gen.Mask = index
            actionList.append(gen)
            self.__applyBoostOrSmear(kernel, actionList, index)

        if actionList:
            self._buildInputStage(simple,
                                  actionList,
                                  output_level=self.output.inputStage,
                                  have_mctruth=self._enablePrimaryHandler())

        #================================================================================================

        # And handle the simulation particles.
        part = DDG4.GeneratorAction(kernel,
                                    "Geant4ParticleHandler/ParticleHandler")
        kernel.generatorAction().adopt(part)
        #part.SaveProcesses = ['conv','Decay']
        part.SaveProcesses = self.part.saveProcesses
        part.MinimalKineticEnergy = self.part.minimalKineticEnergy
        part.KeepAllParticles = self.part.keepAllParticles
        part.PrintEndTracking = self.part.printEndTracking
        part.PrintStartTracking = self.part.printStartTracking
        part.MinDistToParentVertex = self.part.minDistToParentVertex
        part.OutputLevel = self.output.part
        part.enableUI()

        if self.part.enableDetailedHitsAndParticleInfo:
            self.part.setDumpDetailedParticleInfo(kernel, DDG4)

        self.part.setupUserParticleHandler(part, kernel, DDG4)

        #=================================================================================

        # Setup global filters for use in sensitive detectors
        try:
            self.filter.setupFilters(kernel)
        except RuntimeError as e:
            print "ERROR", str(e)
            exit(1)

        #=================================================================================
        # get lists of trackers and calorimeters in detectorDescription

        trk, cal = self.getDetectorLists(detectorDescription)

        # ---- add the trackers:
        try:
            self.__setupSensitiveDetectors(trk, simple.setupTracker,
                                           self.filter.tracker)
        except Exception as e:
            print "ERROR setting up sensitive detector", str(e)
            raise

    # ---- add the calorimeters:
        try:
            self.__setupSensitiveDetectors(cal, simple.setupCalorimeter,
                                           self.filter.calo)
        except Exception as e:
            print "ERROR setting up sensitive detector", str(e)
            raise

    #=================================================================================
    # Now build the physics list:
        _phys = self.physics.setupPhysics(kernel, name=self.physicsList)

        ## add the G4StepLimiterPhysics to activate the max step limits in volumes
        ph = DDG4.PhysicsList(kernel, 'Geant4PhysicsList/Myphysics')
        ph.addPhysicsConstructor('G4StepLimiterPhysics')
        _phys.add(ph)

        dd4hep.setPrintLevel(self.printLevel)

        kernel.configure()
        kernel.initialize()

        ## GPS
        if self._g4gun is not None:
            self._g4gun.generator()
        if self._g4gps is not None:
            self._g4gps.generator()

        startUpTime, _sysTime, _cuTime, _csTime, _elapsedTime = os.times()

        kernel.run()
        kernel.terminate()

        totalTimeUser, totalTimeSys, _cuTime, _csTime, _elapsedTime = os.times(
        )
        if self.printLevel <= 3:
            print "DDSim            INFO  Total Time:   %3.2f s (User), %3.2f s (System)" % (
                totalTimeUser, totalTimeSys)
            if self.numberOfEvents != 0:
                eventTime = totalTimeUser - startUpTime
                perEventTime = eventTime / float(self.numberOfEvents)
                print "DDSim            INFO  StartUp Time: %3.2f s, Event Processing: %3.2f s (%3.2f s/Event) " \
                    % (startUpTime, eventTime, perEventTime)
Beispiel #30
0
def run():
    kernel = DDG4.Kernel()
    install_dir = os.environ['DD4hepExamplesINSTALL']
    kernel.loadGeometry("file:" + install_dir +
                        "/examples/DDCodex/compact/CODEX-b-alone.xml")

    DDG4.importConstants(kernel.detectorDescription(), debug=False)
    geant4 = DDG4.Geant4(kernel, tracker='Geant4TrackerCombineAction')
    geant4.printDetectors()
    # Configure UI
    if len(sys.argv) > 1:
        geant4.setupCshUI(macro=sys.argv[1])
    else:
        geant4.setupCshUI()

    # Configure field
    field = geant4.setupTrackingField(prt=True)
    # Configure Event actions
    prt = DDG4.EventAction(kernel, 'Geant4ParticlePrint/ParticlePrint')
    prt.OutputLevel = Output.WARNING
    prt.OutputType = 3  # Print both: table and tree
    kernel.eventAction().adopt(prt)

    # Configure I/O
    evt_root = geant4.setupROOTOutput(
        'RootOutput', 'CodexB_' + time.strftime('%Y-%m-%d_%H-%M'))

    # Setup particle gun

    #gun = geant4.setupGun("Gun",particle='pi+',
    gun = geant4.setupGun(
        "Gun",
        particle='mu-',
        energy=1000 * GeV,
        multiplicity=1,
        isotrop=False,
        Standalone=True,
        direction=(1, 0, 0),
        #direction=(0.866025,0,0.5),
        position='(0,0,12650)')
    #position='(0,0,0)')
    setattr(gun, 'print', True)
    """
  gen =  DDG4.GeneratorAction(kernel,"Geant4InputAction/Input")
  ##gen.Input = "Geant4EventReaderHepMC|"+ "/afs/cern.ch/work/j/jongho/Project_DD4hep/Test/DD4hep/examples/DDG4/data/hepmc_geant4.dat"
  gen.Input = "Geant4EventReaderHepMC|"+ "/afs/cern.ch/work/j/jongho/Project_DD4hep/Test/DD4hep/DDG4/examples/MinBias_HepMC.txt"
  gen.MomentumScale = 1.0
  gen.Mask = 1
  geant4.buildInputStage([gen],output_level=Output.DEBUG)
  """

    seq, action = geant4.setupTracker('CODEXb')
    #action.OutputLevel = Output.ERROR
    #seq,action = geant4.setupTracker('Shield')
    #action.OutputLevel = Output.ERROR

    # And handle the simulation particles.
    part = DDG4.GeneratorAction(kernel,
                                "Geant4ParticleHandler/ParticleHandler")
    kernel.generatorAction().adopt(part)
    part.OutputLevel = Output.INFO
    part.enableUI()
    user = DDG4.Action(kernel,
                       "Geant4TCUserParticleHandler/UserParticleHandler")
    user.TrackingVolume_Zmax = 999999. * m  # Something big. All is a tracker
    user.TrackingVolume_Rmax = 999999. * m
    user.enableUI()
    part.adopt(user)

    # Now build the physics list:
    ##phys = kernel.physicsList()
    phys = geant4.setupPhysics('QGSP_BERT')
    ph = DDG4.PhysicsList(kernel, 'Geant4PhysicsList/Myphysics')
    ph.addParticleConstructor('G4LeptonConstructor')
    ph.addParticleConstructor('G4BaryonConstructor')
    ph.addParticleConstructor('G4MesonConstructor')
    ph.addParticleConstructor('G4BosonConstructor')
    ph.enableUI()
    phys.adopt(ph)
    phys.enableUI()
    phys.dump()
    # run
    kernel.configure()
    kernel.initialize()
    kernel.run()
    kernel.terminate()
Beispiel #31
0
def run():
    kernel = DDG4.Kernel()
    install_dir = os.environ['DD4hepExamplesINSTALL']
    kernel.loadGeometry(
        str("file:" + install_dir +
            "/examples/OpticalSurfaces/compact/OpNovice.xml"))

    DDG4.importConstants(kernel.detectorDescription(), debug=False)
    geant4 = DDG4.Geant4(kernel, tracker='Geant4TrackerCombineAction')
    geant4.printDetectors()
    # Configure UI
    if len(sys.argv) > 1:
        geant4.setupCshUI(macro=sys.argv[1])
    else:
        geant4.setupCshUI()

    # Configure field
    geant4.setupTrackingField(prt=True)
    # Configure Event actions
    prt = DDG4.EventAction(kernel, 'Geant4ParticlePrint/ParticlePrint')
    prt.OutputLevel = Output.DEBUG
    prt.OutputType = 3  # Print both: table and tree
    kernel.eventAction().adopt(prt)

    generator_output_level = Output.INFO

    # Configure G4 geometry setup
    seq, act = geant4.addDetectorConstruction(
        "Geant4DetectorGeometryConstruction/ConstructGeo")
    act.DebugMaterials = True
    act.DebugElements = False
    act.DebugVolumes = True
    act.DebugShapes = True
    act.DebugSurfaces = True

    # Configure I/O
    # evt_root = geant4.setupROOTOutput('RootOutput','OpNovice_'+time.strftime('%Y-%m-%d_%H-%M'))

    # Setup particle gun
    gun = geant4.setupGun("Gun",
                          particle='gamma',
                          energy=5 * keV,
                          multiplicity=1)
    gun.OutputLevel = generator_output_level

    # And handle the simulation particles.
    """
  part = DDG4.GeneratorAction(kernel,"Geant4ParticleHandler/ParticleHandler")
  kernel.generatorAction().adopt(part)
  part.SaveProcesses = ['Decay']
  part.MinimalKineticEnergy = 100*MeV
  part.OutputLevel = Output.INFO #generator_output_level
  part.enableUI()
  user = DDG4.Action(kernel,"Geant4TCUserParticleHandler/UserParticleHandler")
  user.TrackingVolume_Zmax = 3.0*m
  user.TrackingVolume_Rmax = 3.0*m
  user.enableUI()
  part.adopt(user)
  """
    geant4.setupTracker('BubbleDevice')

    # Now build the physics list:
    phys = geant4.setupPhysics('')
    ph = DDG4.PhysicsList(kernel,
                          'Geant4OpticalPhotonPhysics/OpticalGammaPhys')
    ph.VerboseLevel = 2
    ph.addParticleGroup('G4BosonConstructor')
    ph.addParticleGroup('G4LeptonConstructor')
    ph.addParticleGroup('G4MesonConstructor')
    ph.addParticleGroup('G4BaryonConstructor')
    ph.addParticleGroup('G4IonConstructor')
    ph.addParticleConstructor('G4OpticalPhoton')

    ph.addDiscreteParticleProcess('gamma', 'G4GammaConversion')
    ph.addDiscreteParticleProcess('gamma', 'G4ComptonScattering')
    ph.addDiscreteParticleProcess('gamma', 'G4PhotoElectricEffect')
    ph.addParticleProcess(str('e[+-]'), str('G4eMultipleScattering'), -1, 1, 1)
    ph.addParticleProcess(str('e[+-]'), str('G4eIonisation'), -1, 2, 2)
    ph.addParticleProcess(str('e[+-]'), str('G4eBremsstrahlung'), -1, 3, 3)
    ph.addParticleProcess(str('e+'), str('G4eplusAnnihilation'), 0, -1, 4)
    ph.addParticleProcess(str('mu[+-]'), str('G4MuMultipleScattering'), -1, 1,
                          1)
    ph.addParticleProcess(str('mu[+-]'), str('G4MuIonisation'), -1, 2, 2)
    ph.addParticleProcess(str('mu[+-]'), str('G4MuBremsstrahlung'), -1, 3, 3)
    ph.addParticleProcess(str('mu[+-]'), str('G4MuPairProduction'), -1, 4, 4)
    ph.enableUI()
    phys.adopt(ph)

    ph = DDG4.PhysicsList(kernel,
                          'Geant4ScintillationPhysics/ScintillatorPhys')
    ph.ScintillationYieldFactor = 1.0
    ph.ScintillationExcitationRatio = 1.0
    ph.TrackSecondariesFirst = False
    ph.VerboseLevel = 2
    ph.enableUI()
    phys.adopt(ph)

    ph = DDG4.PhysicsList(kernel, 'Geant4CerenkovPhysics/CerenkovPhys')
    ph.MaxNumPhotonsPerStep = 10
    ph.MaxBetaChangePerStep = 10.0
    ph.TrackSecondariesFirst = True
    ph.VerboseLevel = 2
    ph.enableUI()
    phys.adopt(ph)

    phys.dump()

    geant4.execute()
Beispiel #32
0
def run():
    kernel = DDG4.Kernel()
    lcdd = kernel.lcdd()
    install_dir = os.environ['DD4hepINSTALL']
    example_dir = install_dir + '/examples/DDG4/examples'
    kernel.loadGeometry("file:" + install_dir +
                        "/DDDetectors/compact/SiD_Markus.xml")
    ##kernel.loadXML("file:"+example_dir+"/DDG4_field.xml")
    DDG4.importConstants(lcdd, debug=False)
    geant4 = DDG4.Geant4(kernel, tracker='Geant4TrackerCombineAction')
    geant4.printDetectors()
    # Configure UI
    #geant4.setupCshUI(macro='run.mac',ui=None)
    geant4.setupCshUI()

    field = geant4.addConfig(
        'Geant4FieldTrackingSetupAction/MagFieldTrackingSetup')
    field.stepper = "HelixSimpleRunge"
    field.equation = "Mag_UsualEqRhs"
    field.eps_min = 5e-05 * mm
    field.eps_max = 0.001 * mm
    field.min_chord_step = 0.01 * mm
    field.delta_chord = 0.25 * mm
    field.delta_intersection = 1e-05 * mm
    field.delta_one_step = 0.001 * mm
    print '+++++> ', field.name, '-> stepper  = ', field.stepper
    print '+++++> ', field.name, '-> equation = ', field.equation
    print '+++++> ', field.name, '-> eps_min  = ', field.eps_min
    print '+++++> ', field.name, '-> eps_max  = ', field.eps_max
    print '+++++> ', field.name, '-> delta_one_step = ', field.delta_one_step

    # Configure Run actions
    run1 = DDG4.RunAction(kernel, 'Geant4TestRunAction/RunInit')
    run1.enableUI()
    kernel.registerGlobalAction(run1)
    kernel.runAction().adopt(run1)

    # Configure Event actions
    prt = DDG4.EventAction(kernel, 'Geant4ParticlePrint/ParticlePrint')
    prt.OutputLevel = Output.WARNING
    prt.OutputType = 3  # Print both: table and tree
    kernel.eventAction().adopt(prt)

    generator_output_level = Output.WARNING

    # Configure I/O
    evt_lcio = geant4.setupLCIOOutput(
        'LcioOutput', 'CLICSiD_' + time.strftime('%Y-%m-%d_%H-%M'))
    ##evt_lcio.OutputLevel = generator_output_level
    #evt_root = geant4.setupROOTOutput('RootOutput','CLICSiD_'+time.strftime('%Y-%m-%d_%H-%M'))

    prim = DDG4.GeneratorAction(kernel,
                                "Geant4GeneratorActionInit/GenerationInit")
    #VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
    """
  Generation of primary particles from LCIO input files
  """
    """
  # First particle file reader
  gen = DDG4.GeneratorAction(kernel,"LCIOInputAction/LCIO1");
  #gen.Input = "LCIOStdHepReader|/home/frankm/SW/data/e2e2nn_gen_1343_1.stdhep"
  #gen.Input = "LCIOStdHepReader|/home/frankm/SW/data/qq_gen_128_999.stdhep"
  #gen.Input = "LCIOStdHepReader|/home/frankm/SW/data/smuonLR_PointK_3TeV_BS_noBkg_run0001.stdhep"
  #gen.Input = "LCIOStdHepReader|/home/frankm/SW/data/bbbb_3TeV.stdhep"
  #gen.Input = "LCIOFileReader|/home/frankm/SW/data/mcparticles_pi-_5GeV.slcio"
  #gen.Input = "LCIOFileReader|/home/frankm/SW/data/mcparticles_mu-_5GeV.slcio"
  #gen.Input = "LCIOFileReader|/home/frankm/SW/data/bbbb_3TeV.slcio"
  #gen.Input = "LCIOStdHepReader|/home/frankm/SW/data/FCC-eh.stdhep"
  #gen.Input = "Geant4EventReaderHepMC|/home/frankm/SW/data/data.hepmc.txt"
  #gen.Input = "Geant4EventReaderHepMC|/home/frankm/SW/data/sherpa-2.1.1_zjets.hepmc2g"
  gen.Input = "LCIOFileReader|/afs/cern.ch/user/n/nikiforo/public/Markus/muons.slcio"
  #gen.Input = "LCIOFileReader|/afs/cern.ch/user/n/nikiforo/public/Markus/geantinos.slcio"
  gen.MomentumScale = 1.0
  gen.Mask = 1
  geant4.buildInputStage([gen],output_level=generator_output_level)
  """
    #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    gen = geant4.setupGun("Gun",
                          particle='mu+',
                          energy=20 * GeV,
                          position=(0 * mm, 0 * mm, 0 * cm),
                          multiplicity=3)
    gen.isotrop = True
    gen.direction = (1, 0, 0)
    gen.OutputLevel = generator_output_level
    gen.Standalone = False
    """
  # 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.EcalEndcap_zmin
  user.TrackingVolume_Rmax = DDG4.EcalBarrel_rmin
  user.enableUI()
  part.adopt(user)
  """
    geant4.buildInputStage([prim, gen], Output.ERROR)
    """
  """
    """
  rdr = DDG4.GeneratorAction(kernel,"LcioGeneratorAction/Reader")
  rdr.zSpread = 0.0
  rdr.lorentzAngle = 0.0
  rdr.OutputLevel = DDG4.OutputLevel.INFO
  rdr.Input = "LcioEventReader|test.data"
  rdr.enableUI()
  kernel.generatorAction().adopt(rdr)
  """

    # First the tracking detectors
    seq, act = geant4.setupTracker('SiTrackerBarrel')
    seq, act = geant4.setupTracker('SiTrackerEndcap')
    seq, act = geant4.setupTracker('SiTrackerForward')
    """
  # Now the calorimeters
  seq,act = geant4.setupTracker('SiVertexBarrel')
  seq,act = geant4.setupTracker('SiVertexEndcap')

  seq,act = geant4.setupCalorimeter('EcalBarrel')
  seq,act = geant4.setupCalorimeter('EcalEndcap')
  seq,act = geant4.setupCalorimeter('HcalBarrel')
  seq,act = geant4.setupCalorimeter('HcalEndcap')
  seq,act = geant4.setupCalorimeter('HcalPlug')
  seq,act = geant4.setupCalorimeter('MuonBarrel')
  seq,act = geant4.setupCalorimeter('MuonEndcap')
  seq,act = geant4.setupCalorimeter('LumiCal')
  seq,act = geant4.setupCalorimeter('BeamCal')
  """
    """
  scan = DDG4.SteppingAction(kernel,'Geant4MaterialScanner/MaterialScan')
  kernel.steppingAction().adopt(scan)
  """

    # Now build the physics list:
    phys = geant4.setupPhysics('QGSP_BERT')
    ph = DDG4.PhysicsList(kernel, 'Geant4PhysicsList/Myphysics')
    ph.addParticleConstructor('G4Geantino')
    ph.addParticleConstructor('G4BosonConstructor')
    ph.enableUI()
    phys.adopt(ph)
    phys.dump()

    kernel.configure()
    kernel.initialize()

    #DDG4.setPrintLevel(Output.DEBUG)
    kernel.run()
    print 'End of run. Terminating .......'
    kernel.terminate()
Beispiel #33
0
def run():
  import LHeD, DDG4, os, SystemOfUnits
  from DDG4 import OutputLevel as Output
  
  lhed = LHeD.LHeD()
  geant4 = lhed.geant4
  kernel = lhed.kernel
  lhed.loadGeometry()
  geant4.printDetectors()
  kernel.UI = "UI"
  geant4.setupCshUI()
  lhed.setupField(quiet=False)
  DDG4.importConstants(kernel.detectorDescription(),debug=False)

  dd4hep_dir = os.environ['DD4hep']
  kernel.loadXML("file:"+dd4hep_dir+"/examples/LHeD/scripts/DDG4_field.xml")

  geant4 = DDG4.Geant4(kernel,tracker='Geant4TrackerCombineAction')
  geant4.printDetectors()

  # Configure G4 magnetic field tracking
  field = geant4.addConfig('Geant4FieldTrackingSetupAction/MagFieldTrackingSetup')
  field.stepper            = "HelixGeant4Runge"
  field.equation           = "Mag_UsualEqRhs"
  field.eps_min            = 5e-0520*SystemOfUnits.mm
  field.eps_max            = 0.001*SystemOfUnits.mm
  field.min_chord_step     = 0.01*SystemOfUnits.mm
  field.delta_chord        = 0.25*SystemOfUnits.mm
  field.delta_intersection = 1e-05*SystemOfUnits.mm
  field.delta_one_step     = 0.001*SystemOfUnits.mm
  print '+++++> ',field.name,'-> stepper  = ',field.stepper
  print '+++++> ',field.name,'-> equation = ',field.equation
  print '+++++> ',field.name,'-> eps_min  = ',field.eps_min
  print '+++++> ',field.name,'-> eps_max  = ',field.eps_max
  print '+++++> ',field.name,'-> delta_one_step = ',field.delta_one_step


  """
  # Setup random generator
  rndm = DDG4.Action(kernel,'Geant4Random/Random')
  rndm.Seed = 987654321
  rndm.initialize()
  rndm.showStatus()
  rndm.Seed = 987654321
  """

  # Configure Run actions
  run1 = DDG4.RunAction(kernel,'Geant4TestRunAction/RunInit')
  """
  run1.Property_int    = 12345
  run1.Property_double = -5e15*keV
  run1.Property_string = 'Startrun: Hello_LHeD'
  print run1.Property_string, run1.Property_double, run1.Property_int
  """
  run1.enableUI()
  kernel.registerGlobalAction(run1)
  kernel.runAction().adopt(run1)

  # 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)

  # Configure I/O
  #evt_lcio = geant4.setupLCIOOutput('LcioOutput','Lhe_dip_sol_circ-higgs-bb')
  #evt_lcio.OutputLevel = Output.ERROR
  
  evt_root = geant4.setupROOTOutput('RootOutput','Lhe_dip_sol_circ-higgs-bb')
  evt_root.OutputLevel = Output.INFO

  gen = DDG4.GeneratorAction(kernel,"Geant4GeneratorActionInit/GenerationInit")
  kernel.generatorAction().adopt(gen)

  """
  # First particle generator: e-  non-isotropic generation using Gun: 
  gun = DDG4.GeneratorAction(kernel,"Geant4ParticleGenerator/Gun");
  gun.Particle = 'e-'
  gun.Energy = 60 * GeV
  gun.Multiplicity = 1
  gun.Position = (0.*mm,0.*mm,0.*mm)
  gun.Direction = (1.,0.,0.)
  gun.Mask = 2
  gun.enableUI()
  kernel.generatorAction().adopt(gun)
  # Install vertex smearing for this primary e-
  gen = DDG4.GeneratorAction(kernel,"Geant4InteractionVertexSmear/SmearE-");
  gen.Mask = 1
  gen.Sigma = (0*mm, 0*mm, 0*mm, 0*ns)
  kernel.generatorAction().adopt(gen)
  """

  #VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
  """
  Generation of isotrope tracks of a given multiplicity with overlay:
  """
  #VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
  """
  # First particle generator: pi+
  gen = DDG4.GeneratorAction(kernel,"Geant4IsotropeGenerator/IsotropPi+");
  gen.Particle = 'pi+'
  gen.Energy = 200*GeV
  gen.Multiplicity = 1
  gen.Mask = 1
  kernel.generatorAction().adopt(gen)
  # Install vertex smearing for this interaction
  gen = DDG4.GeneratorAction(kernel,"Geant4InteractionVertexSmear/SmearPi+");
  gen.Mask = 1
  gen.Offset = (20*mm, 10*mm, 10*mm, 0*ns)
  gen.Sigma = (4*mm, 1*mm, 1*mm, 0*ns)
  kernel.generatorAction().adopt(gen)

  # Second particle generator: e-
  gen = DDG4.GeneratorAction(kernel,"Geant4IsotropeGenerator/IsotropE-");
  gen.Particle = 'e-'
  gen.Energy = 60 * GeV
  gen.Multiplicity = 2
  gen.Mask = 2
  kernel.generatorAction().adopt(gen)
  # Install vertex smearing for this interaction
  gen = DDG4.GeneratorAction(kernel,"Geant4InteractionVertexSmear/SmearE-");
  gen.Mask = 2
  gen.Offset = (-20*mm, -10*mm, -10*mm, 0*ns)
  gen.Sigma = (12*mm, 8*mm, 8*mm, 0*ns)
  kernel.generatorAction().adopt(gen)
  """
  #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 


  #VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
  """
  Generation of primary particles from LCIO input files
  """
  #VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
    
  # First particle file reader
  gen = DDG4.GeneratorAction(kernel,"LCIOInputAction/LCIO1");
  # gen.Input = "LCIOStdHepReader|/afs/.cern.ch/project/lhec/software/aidasoft/DD4hep/DD4hep/files/NC_bb_tag_2_pythia_events.hep"
  #gen.Input = "LCIOStdHepReader|/opt/DD4hep/files/NC_bb_tag_2_pythia_events.hep"
  gen.Input = "LCIOStdHepReader|/opt/DD4hep/files/lhec_for_peter/tag_2_pythia_events.hep"
  # gen.Input = "LCIOStdHepReader|/opt/DD4hep/files/single-top-tag_1_pythia_events.hep"
  
  # gen.Input = "Geant4EventReaderHepMC|/opt/DD4hep/files/ePb-q2-0-i.mc2"
  # gen.Input = "LCIOStdHepReader|/opt/DD4hep/files/single-top-tag_1_pythia_events.hep"
  # gen.Input = "LCIOStdHepReader|/opt/DD4hep/files/root.hep"

  gen.OutputLevel = 2 # generator_output_level
  gen.MomentumScale = 1.0
  gen.Mask = 1
  gen.enableUI()
  kernel.generatorAction().adopt(gen)

  # Install vertex smearing for this interaction
  gen = DDG4.GeneratorAction(kernel,"Geant4InteractionVertexSmear/Smear1");  
  gen.OutputLevel = 4 #generator_output_level
  gen.Mask = 1
  gen.Offset = (-20*SystemOfUnits.mm, -10*SystemOfUnits.mm, -10*SystemOfUnits.mm, 0*SystemOfUnits.ns)
  gen.Sigma = (12*SystemOfUnits.mm, 8*SystemOfUnits.mm, 8*SystemOfUnits.mm, 0*SystemOfUnits.ns)
  gen.enableUI()
  kernel.generatorAction().adopt(gen)

  #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  
  # Merge all existing interaction records
  gen = DDG4.GeneratorAction(kernel,"Geant4InteractionMerger/InteractionMerger")
  gen.OutputLevel = 4 #generator_output_level
  gen.enableUI()
  kernel.generatorAction().adopt(gen)

  # Finally generate Geant4 primaries
  gen = DDG4.GeneratorAction(kernel,"Geant4PrimaryHandler/PrimaryHandler")
  gen.OutputLevel = 4 #generator_output_level
  gen.enableUI()
  kernel.generatorAction().adopt(gen)

  # And handle the simulation particles.
  part = DDG4.GeneratorAction(kernel,"Geant4ParticleHandler/ParticleHandler")
  kernel.generatorAction().adopt(part)
  #part.SaveProcesses = ['conv','Decay']
  part.SaveProcesses = ['Decay']
  part.MinimalKineticEnergy = 10*SystemOfUnits.MeV
  part.OutputLevel = 5 # generator_output_level
  part.enableUI()

  user = DDG4.Action(kernel,"Geant4TCUserParticleHandler/UserParticleHandler")
  user.TrackingVolume_Zmax = DDG4.EcalEndcap_zmin_fwd
  user.TrackingVolume_Rmax = DDG4.EcalBarrel_rmin
  user.enableUI()
  part.adopt(user)


  """
  rdr = DDG4.GeneratorAction(kernel,"LcioGeneratorAction/Reader")
  rdr.zSpread = 0.0
  rdr.lorentzAngle = 0.0
  rdr.OutputLevel = DDG4.OutputLevel.INFO
  rdr.Input = "LcioEventReader|test.data"
  rdr.enableUI()
  kernel.generatorAction().adopt(rdr)
  """

  # Setup global filters fur use in sensntive detectors
  f1 = DDG4.Filter(kernel,'GeantinoRejectFilter/GeantinoRejector')
  kernel.registerGlobalFilter(f1)
  f2 = DDG4.Filter(kernel,'ParticleRejectFilter/OpticalPhotonRejector')
  f2.particle = 'opticalphoton'
  kernel.registerGlobalFilter(f2)
  f3 = DDG4.Filter(kernel,'ParticleSelectFilter/OpticalPhotonSelector') 
  f3.particle = 'opticalphoton'
  kernel.registerGlobalFilter(f3)

  f4 = DDG4.Filter(kernel,'EnergyDepositMinimumCut')
  f4.Cut = 0.5*SystemOfUnits.MeV
  f4.enableUI()
  kernel.registerGlobalFilter(f4)

  # First the tracking detectors
  seq,act = geant4.setupTracker('SiVertexBarrel')
  seq.adopt(f1)
  act.adopt(f1)
  
  seq,act = geant4.setupTracker('SiTrackerBarrel')
  seq.adopt(f1)
  act.adopt(f1)
  seq,act = geant4.setupTracker('SiTrackerForward')
  seq.adopt(f1)
  act.adopt(f1)
  seq,act = geant4.setupTracker('SiTrackerBackward')
  seq.adopt(f1)
  act.adopt(f1)

  # Now the calorimeters
  seq,act = geant4.setupCalorimeter('EcalBarrel')
  seq.adopt(f3)
  act.adopt(f3)
  seq.adopt(f4)
  act.adopt(f4)

  seq,act = geant4.setupCalorimeter('EcalEndcap_fwd')
  seq.adopt(f3)
  act.adopt(f3)
  seq.adopt(f4)
  act.adopt(f4)
  seq,act = geant4.setupCalorimeter('EcalEndcap_bwd')
  seq.adopt(f3)
  act.adopt(f3)
  seq.adopt(f4)
  act.adopt(f4)
    
  seq,act = geant4.setupCalorimeter('HcalBarrel')
  seq.adopt(f3)
  act.adopt(f3)
  seq.adopt(f4)
  act.adopt(f4)
  seq,act = geant4.setupCalorimeter('HcalEndcap_fwd')
  seq.adopt(f3)
  act.adopt(f3)
  seq.adopt(f4)
  act.adopt(f4)
  seq,act = geant4.setupCalorimeter('HcalEndcap_bwd')
  seq.adopt(f3)
  act.adopt(f3)
  seq.adopt(f4)
  act.adopt(f4)

  seq,act = geant4.setupCalorimeter('HcalPlug_fwd')
  seq.adopt(f3)
  act.adopt(f3)
  seq.adopt(f4)
  act.adopt(f4)
  seq,act = geant4.setupCalorimeter('HcalPlug_bwd')
  seq.adopt(f3)
  act.adopt(f3)
  seq.adopt(f4)
  act.adopt(f4)
    
  seq,act = geant4.setupCalorimeter('MuonBarrel')
  seq.adopt(f2)
  act.adopt(f2)
  seq,act = geant4.setupCalorimeter('MuonEndcap_fwd1')
  seq.adopt(f2)
  act.adopt(f2)
  seq,act = geant4.setupCalorimeter('MuonEndcap_fwd2')
  seq.adopt(f2)
  act.adopt(f2)
  seq,act = geant4.setupCalorimeter('MuonEndcap_bwd1')
  seq.adopt(f2)
  act.adopt(f2)
  seq,act = geant4.setupCalorimeter('MuonEndcap_bwd2')
  seq.adopt(f2)
  act.adopt(f2)


  """
  scan = DDG4.SteppingAction(kernel,'Geant4MaterialScanner/MaterialScan')
  kernel.steppingAction().adopt(scan)
  """

  # Now build the physics list:
  phys = geant4.setupPhysics('QGSP_BERT')
  ph = DDG4.PhysicsList(kernel,'Geant4PhysicsList/Myphysics')
  ph.addParticleConstructor('G4Geantino')
  ph.addParticleConstructor('G4BosonConstructor')
  ph.addParticleConstructor('G4LeptonConstructor')
  ph.addParticleProcess('e[+-]','G4eMultipleScattering',-1,1,1)
  ph.addPhysicsConstructor('G4OpticalPhysics')
  ph.enableUI()
  phys.adopt(ph)
  phys.dump()

  kernel.configure()
  kernel.initialize()

  #DDG4.setPrintLevel(Output.DEBUG)
  kernel.run()
  print 'End of run. Terminating .......'
  kernel.terminate()
Beispiel #34
0
def run():
  kernel = DDG4.Kernel()
  lcdd = kernel.lcdd()
  install_dir = os.environ['DD4hepINSTALL']
  kernel.loadGeometry("file:"+install_dir+"/DDDetectors/compact/SiD.xml")
  DDG4.importConstants(lcdd)

  geant4 = DDG4.Geant4(kernel,tracker='Geant4TrackerCombineAction')
  geant4.printDetectors()
  print "#  Configure UI"
  geant4.setupCshUI()

  print "#  Configure G4 magnetic field tracking"
  field = geant4.addConfig('Geant4FieldTrackingSetupAction/MagFieldTrackingSetup')
  field.stepper            = "HelixGeant4Runge"
  field.equation           = "Mag_UsualEqRhs"
  field.eps_min            = 5e-05 * mm
  field.eps_max            = 0.001 * mm
  field.min_chord_step     = 0.01 * mm
  field.delta_chord        = 0.25 * mm
  field.delta_intersection = 1e-05 * mm
  field.delta_one_step     = 0.001 * mm
  print '+++++> ',field.name,'-> stepper  = ',field.stepper
  print '+++++> ',field.name,'-> equation = ',field.equation
  print '+++++> ',field.name,'-> eps_min  = ',field.eps_min
  print '+++++> ',field.name,'-> eps_max  = ',field.eps_max
  print '+++++> ',field.name,'-> delta_one_step = ',field.delta_one_step

  print "#  Setup random generator"
  rndm = DDG4.Action(kernel,'Geant4Random/Random')
  rndm.Seed = 987654321
  rndm.initialize()
  ##rndm.showStatus()

  print "#  Configure Run actions"
  run1 = DDG4.RunAction(kernel,'Geant4TestRunAction/RunInit')
  run1.Property_int    = 12345
  run1.Property_double = -5e15*keV
  run1.Property_string = 'Startrun: Hello_2'
  print run1.Property_string, run1.Property_double, run1.Property_int
  run1.enableUI()
  kernel.registerGlobalAction(run1)
  kernel.runAction().adopt(run1)

  print "#  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)

  print """
  Configure I/O
  """
  evt_lcio = geant4.setupLCIOOutput('LcioOutput','CLICSiD_'+time.strftime('%Y-%m-%d_%H-%M'))
  evt_lcio.OutputLevel = Output.ERROR

  evt_root = geant4.setupROOTOutput('RootOutput','CLICSiD_'+time.strftime('%Y-%m-%d_%H-%M'))

  generator_output_level = Output.INFO

  gen = DDG4.GeneratorAction(kernel,"Geant4GeneratorActionInit/GenerationInit")
  kernel.generatorAction().adopt(gen)

  #VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
  print """
  Generation of isotrope tracks of a given multiplicity with overlay:
  """
  print "#  First particle generator: pi+"
  gen = DDG4.GeneratorAction(kernel,"Geant4IsotropeGenerator/IsotropPi+");
  gen.Mask     = 1
  gen.Particle = 'pi+'
  gen.Energy   = 100 * GeV
  gen.Multiplicity = 2
  gen.Distribution = 'cos(theta)'
  kernel.generatorAction().adopt(gen)
  print "#  Install vertex smearing for this interaction"
  gen = DDG4.GeneratorAction(kernel,"Geant4InteractionVertexSmear/SmearPi+");
  gen.Mask   = 1
  gen.Offset = (20*mm, 10*mm, 10*mm, 0*ns)
  gen.Sigma  = (4*mm, 1*mm, 1*mm, 0*ns)
  kernel.generatorAction().adopt(gen)

  print "#  Second particle generator: e-"
  gen = DDG4.GeneratorAction(kernel,"Geant4IsotropeGenerator/IsotropE-");
  gen.Mask     = 2
  gen.Particle = 'e-'
  gen.Energy   = 25 * GeV
  gen.Multiplicity = 3
  gen.Distribution = 'uniform'
  kernel.generatorAction().adopt(gen)
  print "  Install vertex smearing for this interaction"
  gen = DDG4.GeneratorAction(kernel,"Geant4InteractionVertexSmear/SmearE-");
  gen.Mask   = 2
  gen.Offset = (-20*mm, -10*mm, -10*mm, 0*ns)
  gen.Sigma  = (12*mm, 8*mm, 8*mm, 0*ns)
  kernel.generatorAction().adopt(gen)
  #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

  print "#  Merge all existing interaction records"
  gen = DDG4.GeneratorAction(kernel,"Geant4InteractionMerger/InteractionMerger")
  gen.OutputLevel = 4 #generator_output_level
  gen.enableUI()
  kernel.generatorAction().adopt(gen)

  print "#  Finally generate Geant4 primaries"
  gen = DDG4.GeneratorAction(kernel,"Geant4PrimaryHandler/PrimaryHandler")
  gen.OutputLevel = 4 #generator_output_level
  gen.enableUI()
  kernel.generatorAction().adopt(gen)

  print "#  ....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 = 5 # generator_output_level
  part.enableUI()
  user = DDG4.Action(kernel,"Geant4TCUserParticleHandler/UserParticleHandler")
  user.TrackingVolume_Zmax = DDG4.EcalEndcap_zmin
  user.TrackingVolume_Rmax = DDG4.EcalBarrel_rmin
  user.enableUI()
  part.adopt(user)

  print "#  Setup global filters fur use in sensntive detectors"
  f1 = DDG4.Filter(kernel,'GeantinoRejectFilter/GeantinoRejector')
  f2 = DDG4.Filter(kernel,'ParticleRejectFilter/OpticalPhotonRejector')
  f2.particle = 'opticalphoton'
  f3 = DDG4.Filter(kernel,'ParticleSelectFilter/OpticalPhotonSelector') 
  f3.particle = 'opticalphoton'
  f4 = DDG4.Filter(kernel,'EnergyDepositMinimumCut')
  f4.Cut = 10*MeV
  f4.enableUI()
  kernel.registerGlobalFilter(f1)
  kernel.registerGlobalFilter(f2)
  kernel.registerGlobalFilter(f3)
  kernel.registerGlobalFilter(f4)

  print "#  First the tracking detectors"
  seq,act = geant4.setupTracker('SiVertexBarrel')
  seq.adopt(f1)
  #seq.adopt(f4)
  act.adopt(f1)

  seq,act = geant4.setupTracker('SiVertexEndcap')
  seq.adopt(f1)
  #seq.adopt(f4)

  seq,act = geant4.setupTracker('SiTrackerBarrel')
  seq,act = geant4.setupTracker('SiTrackerEndcap')
  seq,act = geant4.setupTracker('SiTrackerForward')
  print "#  Now setup the calorimeters"
  seq,act = geant4.setupCalorimeter('EcalBarrel')
  seq,act = geant4.setupCalorimeter('EcalEndcap')
  seq,act = geant4.setupCalorimeter('HcalBarrel')
  seq,act = geant4.setupCalorimeter('HcalEndcap')
  seq,act = geant4.setupCalorimeter('HcalPlug')
  seq,act = geant4.setupCalorimeter('MuonBarrel')
  seq,act = geant4.setupCalorimeter('MuonEndcap')
  seq,act = geant4.setupCalorimeter('LumiCal')
  seq,act = geant4.setupCalorimeter('BeamCal')

  print "#  Now build the physics list:"
  phys = geant4.setupPhysics('QGSP_BERT')
  ph = geant4.addPhysics('Geant4PhysicsList/Myphysics')
  #ph.addParticleConstructor('G4BosonConstructor')
  #ph.addParticleConstructor('G4LeptonConstructor')
  #ph.addParticleProcess('e[+-]','G4eMultipleScattering',-1,1,1)
  #ph.addPhysicsConstructor('G4OpticalPhysics')

  # Add special particle types from specialized physics constructor
  part = geant4.addPhysics('Geant4ExtraParticles/ExtraParticles')
  part.pdgfile = 'checkout/DDG4/examples/particle.tbl'

  # Add global range cut
  rg = geant4.addPhysics('Geant4DefaultRangeCut/GlobalRangeCut')
  rg.RangeCut = 0.7*mm

  phys.dump()

  kernel.configure()
  kernel.initialize()

  #DDG4.setPrintLevel(Output.DEBUG)
  kernel.run()
  kernel.terminate()