Пример #1
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)
Пример #2
0
try:
  import dd4hep
except ImportError,X:
  logging.error('dd4hep python interface not accessible: %s',str(X))
  logging.error("%s",parser.format_help())
  sys.exit(errno.ENOENT)
#
try:
  import DDRec
except ImportError,X:
  logging.error('ddrec python interface not accessible: %s',str(X))
  logging.error("%s",parser.format_help())
  sys.exit(errno.ENOENT)
#

dd4hep.setPrintLevel(dd4hep.OutputLevel.ERROR)
logging.info('+++%s\n+++ Loading compact geometry:%s\n+++%s',120*'=',opts.compact,120*'=')



description = dd4hep.Detector.getInstance()
description.fromXML(opts.compact)


## ------ loop over detectors and print their detector data objects

for n,d in description.detectors():

    print 
    print " ------------- detector :  " , d.name()
    print 
Пример #3
0
try:
    import ROOT
    from ROOT import gROOT
    gROOT.SetBatch(1)
except ImportError, X:
    logging.error('PyROOT interface not accessible: %s', str(X))
    sys.exit(errno.ENOENT)

try:
    import dd4hep
except ImportError, X:
    logging.error('dd4hep python interface not accessible: %s', str(X))
    sys.exit(errno.ENOENT)

dd4hep.setPrintLevel(dd4hep.OutputLevel.ERROR)
logging.info('+++%s\n+++ Loading compact geometry:%s\n+++%s', 120 * '=',
             opts.compact, 120 * '=')
description = dd4hep.Detector.getInstance()
description.fromXML(opts.compact)
opts.num_tracks = int(opts.num_tracks)
opts.vx = float(opts.vx)
opts.vy = float(opts.vy)
opts.vz = float(opts.vz)
logging.info('+++%s\n+++ Checking geometry:%s full-check:%s\n+++%s', 120 * '=',
             opts.compact, opts.full, 120 * '=')
if opts.full:
    logging.info('+++ # tracks:%d vertex:(%7.3f, %7.3f, %7.3f) [cm]',
                 opts.num_tracks, opts.vx, opts.vy, opts.vz)
    description.manager().CheckGeometryFull(opts.num_tracks, opts.vx, opts.vy,
                                            opts.vz, opts.option)