Пример #1
0
def detector_Shelf(description, det):

    plane = det.find('planes')
    mat = det.find('material')
    # pos   = det.find('position')
    # rot   = det.find('rotation')
    book = det.find('books')

    # ---Construct the ensamble plane+books volume-------------------------------------------------------------
    e_vol = Volume(
        description,
        'ensemble',  # noqa: F821
        Box(description, 'box', plane.x, plane.y + book.y,
            plane.z),  # noqa: F821
        description.material('Air'))
    e_vol.setVisAttributes(description, 'InvisibleWithDaughters')

    # ---Construct the plane and place it----------------------------------------------------------------------
    p_vol = Volume(
        description,
        'plane',  # noqa: F821
        Box(description, 'plane', plane.x, plane.y, plane.z),  # noqa: F821
        description.material(mat.name))
    p_vol.setVisAttributes(description, plane.vis)
    e_vol.placeVolume(p_vol, Position(0, -book.y, 0))  # noqa: F821

    # ---Construct a book and place it number of times---------------------------------------------------------
    b_vol = Volume(
        description,
        'book',  # noqa: F821
        Box(description, 'book', book.x, book.y, book.z),  # noqa: F821
        description.material('Carbon'))
    b_vol.setVisAttributes(description, book.vis)
    x, y, z = plane.x - book.x, plane.y, -plane.z + book.z
    for n in range(book.number):
        e_vol.placeVolume(b_vol, Position(x, y, z))  # noqa: F821
        z += 2 * book.z + book.getF('dz')

    # --Construct the overal envelope and Detector element-----------------------------------------------------
    g_x, g_y, g_z = plane.x, plane.number * plane.getF('dy'), plane.z
    g_vol = Volume(
        description,
        det.name,  # noqa: F821
        Box(description, 'box', g_x, g_y, g_z),
        description.material('Air'))  # noqa: F821
    g_vol.setVisAttributes(description, 'InvisibleWithDaughters')
    de = DetElement(description, det.name, det.type, det.id)  # noqa: F821
    phv = description.worldVolume().placeVolume(g_vol,
                                                Position(g_x, g_y,
                                                         g_z))  # noqa: F821
    phv.addPhysVolID('id', det.id)
    de.addPlacement(phv)
    x, y, z = 0, book.y + plane.y - 2 * plane.getF('dy'), 0
    for n in range(plane.number):
        g_vol.placeVolume(e_vol, Position(x, y, z))  # noqa: F821
        y += plane.getF('dy')
    # ---Return detector element---------------------------------------------------------------------------------
    return de
Пример #2
0
 def factories(self):
     facts = {}
     n = _lib.cgaudi_pluginsvc_get_factory_size(self)
     for i in range(n):
         f = _lib.cgaudi_pluginsvc_get_factory_at(self, i)
         facts[f.name] = f
     return facts
Пример #3
0
 def properties(self):
     props = {}
     nprops = _lib.cgaudi_factory_get_property_size(self)
     for i in range(nprops):
         prop = _lib.cgaudi_factory_get_property_at(self, i)
         props[prop.key] = prop.value
     return props
Пример #4
0
    def mapDetFilter(self, val):
        if isinstance(val, dict):
            self._mapDetFilter.update(val)
            return

        if isinstance(val, six.string_types):
            vals = val.split(" ")
        elif isinstance(val, list):
            vals = val
        if len(vals) % 2 != 0:
            raise RuntimeError("Not enough parameters for mapDetFilter")
        for index in range(0, len(vals), 2):
            self._mapDetFilter[vals[index]] = vals[index + 1]
Пример #5
0
def run():
    batch = False
    kernel = DDG4.Kernel()
    install_dir = os.environ['DD4hepExamplesINSTALL']
    geometry = "file:" + install_dir + "/examples/ClientTests/compact/MultiCollections.xml"
    kernel.setOutputLevel(str('Geant4Converter'), Output.DEBUG)
    kernel.setOutputLevel(str('Gun'), Output.INFO)
    for i in range(len(sys.argv)):
        if sys.argv[i] == '-compact':
            geometry = sys.argv[i + 1]
        elif sys.argv[i] == '-input':
            geometry = sys.argv[i + 1]
        elif sys.argv[i] == '-batch':
            batch = True
        elif sys.argv[i] == 'batch':
            batch = True

    kernel.loadGeometry(str(geometry))
    geant4 = DDG4.Geant4(kernel)
    geant4.printDetectors()
    geant4.setupCshUI()
    if batch:
        kernel.UI = ''

    # Configure field
    geant4.setupTrackingField(prt=True)
    # Configure I/O
    geant4.setupROOTOutput('RootOutput',
                           'Multi_coll_' + time.strftime('%Y-%m-%d_%H-%M'),
                           mc_truth=True)
    # Setup particle gun
    geant4.setupGun("Gun", particle='pi-', energy=10 * GeV, multiplicity=1)

    # Now the test calorimeter with multiple collections
    seq, act = geant4.setupCalorimeter('TestCal')

    # And handle the simulation particles.
    part = DDG4.GeneratorAction(kernel,
                                "Geant4ParticleHandler/ParticleHandler")
    kernel.generatorAction().adopt(part)
    part.MinimalKineticEnergy = 1 * MeV
    part.enableUI()

    # Now build the physics list:
    phys = kernel.physicsList()
    phys.extends = 'QGSP_BERT'
    phys.enableUI()
    phys.dump()
    # and run
    geant4.execute()
Пример #6
0
    def mapActions(self, val):
        """check if the argument is a dict, then we just update mapActions
    if it is a string or list, we use pairs as patterns --> Action
    """
        if isinstance(val, dict):
            self._mapActions.update(val)
            return

        if isinstance(val, six.string_types):
            vals = val.split(" ")
        elif isinstance(val, list):
            vals = val
        if len(vals) % 2 != 0:
            raise RuntimeError("Not enough parameters for mapActions")
        for index in range(0, len(vals), 2):
            self._mapActions[vals[index]] = vals[index + 1]
Пример #7
0
def run():
    geo = None
    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] == '-GEO':
            geo = sys.argv[i + 1]
        elif c[:4] == '-VIS':
            vis = True

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

    import DDG4
    kernel = DDG4.Kernel()
    # Configure UI
    geant4 = DDG4.Geant4(kernel, tracker='Geant4TrackerCombineAction')
    if batch:
        ui = geant4.setupCshUI(ui=None, vis=None)
        kernel.UI = 'UI'
    else:
        ui = geant4.setupCshUI(vis=vis)
    kernel.loadGeometry(geo)
    # Configure field
    geant4.setupTrackingField(prt=True)
    # Now build the physics list:
    geant4.setupPhysics('')
    kernel.physicsList().enableUI()
    DDG4.setPrintLevel(DDG4.OutputLevel.DEBUG)
    #
    cmds = []
    cmds.append(
        '/ddg4/ConstructGeometry/printVolume /world_volume_1/Shape_Test_0/Shape_Test_vol_0_0'
    )
    cmds.append('/ddg4/UI/exit')
    ui.Commands = cmds
    kernel.NumEvents = 0
    kernel.configure()
    kernel.initialize()
    kernel.run()
    kernel.terminate()
Пример #8
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()
Пример #9
0
def run():
    kernel = DDG4.Kernel()
    install_dir = os.environ['DD4hepExamplesINSTALL']
    kernel.setOutputLevel(str('Geant4Converter'), Output.DEBUG)
    kernel.setOutputLevel(str('Gun'), Output.INFO)
    kernel.detectorDescription().fromXML(
        str("file:" + install_dir + "/examples/DDCMS/data/dd4hep-ecal.xml"))
    kernel.NumEvents = 5
    geant4 = DDG4.Geant4(kernel, tracker='Geant4TrackerCombineAction')
    geant4.printDetectors()

    batch = False
    test = False
    vis = False
    ui = None
    for i in range(len(sys.argv)):
        arg = sys.argv[i].lower()
        if arg == 'batch':
            batch = True
        elif arg[:4] == '-vis':
            vis = True
        elif arg == 'test':
            test = True
        elif arg == 'numevents':
            kernel.NumEvents = int(sys.argv[i + 1])
    if batch or test:
        geant4.setupCshUI(ui=None, vis=None)
        kernel.UI = 'UI'
    else:
        ui = geant4.setupCshUI(vis=vis)

    # Configure field
    geant4.setupTrackingField(prt=True)
    # Configure I/O
    geant4.setupROOTOutput('RootOutput',
                           'CMSEcal_' + time.strftime('%Y-%m-%d_%H-%M'),
                           mc_truth=True)
    # Setup particle gun
    generators = []
    generators.append(
        geant4.setupGun("GunPi-",
                        particle='pi-',
                        energy=300 * GeV,
                        multiplicity=1,
                        Standalone=False,
                        register=False,
                        Mask=1))
    if not test:
        generators.append(
            geant4.setupGun("GunE+",
                            particle='e+',
                            energy=100 * GeV,
                            multiplicity=1,
                            Standalone=False,
                            register=False,
                            Mask=8))
    geant4.buildInputStage(generators)
    # Now setup all tracking detectors
    for i in geant4.description.detectors():
        o = DDG4.DetElement(i.second.ptr())
        sd = geant4.description.sensitiveDetector(o.name())
        if sd.isValid():
            type = geant4.sensitive_types[sd.type()]
            logger.info('CMSTracker: Configure subdetector %-24s of type %s' %
                        (
                            o.name(),
                            type,
                        ))
            geant4.setupDetector(o.name(), type)

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

    # Now build the physics list:
    phys = kernel.physicsList()
    phys.extends = 'QGSP_BERT'
    phys.enableUI()
    #
    #
    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
    #
    # and run
    geant4.execute()
Пример #10
0
def run():
    batch = False
    kernel = DDG4.Kernel()
    install_dir = os.environ['DD4hepExamplesINSTALL']
    geometry = "file:" + install_dir + "/examples/ClientTests/compact/MultiSegmentCollections.xml"
    kernel.setOutputLevel(str('Geant4Converter'), Output.DEBUG)
    kernel.setOutputLevel(str('Gun'), Output.INFO)
    for i in range(len(sys.argv)):
        if sys.argv[i] == '-compact':
            geometry = sys.argv[i + 1]
        elif sys.argv[i] == '-input':
            geometry = sys.argv[i + 1]
        elif sys.argv[i] == '-batch':
            batch = True
        elif sys.argv[i] == 'batch':
            batch = True

    kernel.loadGeometry(str(geometry))
    geant4 = DDG4.Geant4(kernel)
    geant4.printDetectors()
    geant4.setupCshUI()
    if batch:
        kernel.UI = ''

    # Configure field
    geant4.setupTrackingField(prt=True)
    # Setup particle gun
    geant4.setupGun("Gun", particle='pi-', energy=50 * GeV, multiplicity=1)

    # Now the test calorimeter with multiple collections
    seq, act = geant4.setupCalorimeter('TestCal')

    # And handle the simulation particles.
    part = DDG4.GeneratorAction(kernel,
                                "Geant4ParticleHandler/ParticleHandler")
    kernel.generatorAction().adopt(part)
    part.MinimalKineticEnergy = 1 * MeV
    part.enableUI()

    # Add the particle dumper to associate the MC truth
    evt = DDG4.EventAction(kernel, "Geant4ParticleDumpAction/ParticleDump")
    kernel.eventAction().adopt(evt)
    evt.enableUI()

    # Add the hit dumper BEFORE any hit truth is fixed
    evt = DDG4.EventAction(kernel, "Geant4HitDumpAction/RawDump")
    kernel.eventAction().adopt(evt)
    evt.enableUI()

    # Add the hit dumper to the event action sequence
    evt = DDG4.EventAction(kernel, "Geant4HitTruthHandler/HitTruth")
    kernel.eventAction().adopt(evt)
    evt.enableUI()

    # Add the hit dumper AFTER any hit truth is fixed. We should see the reduced track references
    evt = DDG4.EventAction(kernel, "Geant4HitDumpAction/HitDump")
    kernel.eventAction().adopt(evt)
    evt.enableUI()

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

    # Now build the physics list:
    phys = kernel.physicsList()
    phys.extends = 'QGSP_BERT'
    phys.enableUI()
    phys.dump()
    # and run
    geant4.execute()
Пример #11
0
def run():
    geo = None
    vis = 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

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

    import DDG4
    Output = DDG4.OutputLevel
    kernel = DDG4.Kernel()
    # Configure UI
    geant4 = DDG4.Geant4(kernel, tracker='Geant4TrackerCombineAction')
    if batch:
        ui = geant4.setupCshUI(ui=None, vis=None)
        kernel.UI = 'UI'
    else:
        ui = geant4.setupCshUI(vis=vis)
    kernel.loadGeometry(geo)
    # 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.setupDetectors()
    #
    # Configure I/O
    geant4.setupROOTOutput('RootOutput',
                           'CheckShape_' + time.strftime('%Y-%m-%d_%H-%M'),
                           mc_truth=True)
    #
    # Setup particle gun
    geant4.setupGun(name="Gun",
                    particle='e-',
                    energy=100 * 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)
    #
    prt = DDG4.EventAction(kernel, str('Geant4ParticlePrint/ParticlePrint'))
    prt.OutputLevel = Output.INFO
    prt.OutputType = 3  # Print both: table and tree
    kernel.eventAction().adopt(prt)
    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()
    #
    cmds = []
    if vis:
        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. 11.')
        cmds.append('/vis/scene/add/axes 0 0 0 1 m')
    #
    #  cmds.append('/ddg4/ConstructGeometry/printVolume /world_volume_1/Shape_Test_0/Shape_Test_vol_0_0')
    #  cmds.append('/ddg4/UI/exit')
    #
    ui.Commands = cmds
    kernel.NumEvents = 0
    kernel.configure()
    kernel.initialize()
    kernel.run()
    kernel.terminate()
Пример #12
0
    DDG4.Geant4Random.setMainInstance(rndm1.get())
    rndm1.showStatus()

    # Move main geant random instance from rndm1 to rndm2:
    # See how gRandom and HepRandom instances move
    DDG4.Geant4Random.setMainInstance(rndm1.get())
    logger.info('DEFAULT Engine: %s',
                DDG4.CLHEP.HepRandom.getTheEngine().name())
    logger.info('DDG4   DEFAULT: %s',
                DDG4.Geant4Random.instance().engine().name())
    rndm = DDG4.Geant4Random.instance()

    rndm.setSeed(1234)
    rndm.showStatus()
    for i in range(10):
        logger.info("%s  -- 0 gRandome.Rndm()        -- Shoot random[[%d]= %f",
                    rndm.name(), i, gRandom.Rndm())

    rndm.setSeed(1234)
    for i in range(10):
        logger.info("%s  -- 1 gRandome.Rndm()        -- Shoot random[[%d]= %f",
                    rndm.name(), i, gRandom.Rndm())

    rndm.setSeed(1234)
    for i in range(10):
        logger.info("%s  -- 2 Geant4Random(CLHEP)    -- Shoot random[[%d]= %f",
                    rndm.name(), i, rndm.rndm_clhep())

    rndm.setSeed(1234)
    for i in range(10):