def Execute(self, stats):
        'Runs the tray, but the important stuff happens in segment_X(...)'

        if not ipmodule.ParsingModule.Execute(self, stats):
            return 0

        # Load libraries
        from icecube import (earthmodel_service, PROPOSAL, cmc, phys_services)
        from icecube import (polyplopia, dataclasses, dataio)

        # support json ParamsMap, so we can get our dict from the iceprod config file
        try:
            import json
        except ImportError:
            json = None

        # Instantiate a tray
        tray = I3Tray()

        randomService = phys_services.I3SPRNGRandomService(
             seed = self.seed,
             nstreams = self.nproc,
             streamnum = self.procnum)\
            if not self.usegslrng else phys_services.I3GSLRandomService(seed)

        tray.context['I3RandomService'] = randomService

        # Configure IceTray modules
        tray.AddModule("I3Reader",
                       "reader",
                       FilenameList=[self.gcdfile, self.inputfile])

        from .. import segments
        from I3Tray import I3Units

        tray.Add(segments.PolyplopiaMergePEs,
                 "merge",
                 mctype=self.mctype,
                 RandomService=randomService,
                 mctree_name="I3MCTree",
                 bgfile=self.backgroundfile,
                 separate_coincident_mctree_name="BackgroundI3MCTree",
                 timewindow=self.timewindow,
                 rate=5.0 * I3Units.kilohertz)

        tray.AddModule("I3Writer",
                       "writer",
                       Filename=self.outputfile,
                       Streams=[
                           icetray.I3Frame.TrayInfo, icetray.I3Frame.DAQ,
                           icetray.I3Frame.Stream('S'),
                           icetray.I3Frame.Stream('M')
                       ])

        # Execute the Tray
        tray.Execute()

        # Free memory
        del tray
        return 0
Beispiel #2
0
   def Configure(self,tray):
        from icecube import icetray, dataclasses, dataio, phys_services, interfaces
        from .ppc import PPCTraySegment
        from I3Tray import I3Tray,I3Units


        from .. import segments
        if self.propagatemuons:
        	randomServiceForPropagators = phys_services.I3SPRNGRandomService(
             		seed = self.seed,
             		nstreams = self.nproc*2,
             		streamnum = self.nproc + self.procnum)\
                if not self.usegslrng else phys_services.I3GSLRandomService(seed = self.seed*self.nproc+self.procnum)

        	tray.context['I3PropagatorRandomService'] = randomServiceForPropagators

        	tray.AddModule("Rename","rename_corsika_mctree",Keys=['I3MCTree','I3MCTree_preMuonProp'])
        	tray.AddSegment(segments.PropagateMuons, 'propagator',
                        RandomService= randomServiceForPropagators,
                        **self.proposalparams
        	) 


        
        tray.AddSegment(PPCTraySegment,"ppc_photons",
			gpu = self.gpu,
			usegpus = self.usegpus,
			UnshadowedFraction = self.efficiency,
			DOMOversizeFactor = self.oversize,
			IceModelLocation = self.icemodellocation,
			HoleIceParameterization = self.holeiceparametrization,
			IceModel = self.icemodel,
			volumecyl = self.volumecyl,
			gpulib = self.gpulib,
			InputMCTree = self.mctreename,
			keep_empty_events = self.keepemptyevents,
			MCPESeriesName = self.photonseriesname,
                        tempdir = self.tempdir)

        if self.runmphitfilter:
           tray.AddModule("MPHitFilter","hitfilter",
              HitOMThreshold=1,
              RemoveBackgroundOnly=False,
              I3MCPESeriesMapName=self.photonseriesname)

        if self.enablehistogram and self.histogramfilename:         
            from icecube.production_histograms import ProductionHistogramModule
            from icecube.production_histograms.histogram_modules.simulation.mcpe_module import I3MCPEModule
        
            tray.AddModule(ProductionHistogramModule, 
                           Histograms = [I3MCPEModule],
                           OutputFilename = self.histogramfilename)


        tray.AddModule("I3Writer","writer", 
            filename=self.outputfile,
            Streams=[icetray.I3Frame.TrayInfo,
                     icetray.I3Frame.DAQ,
                     icetray.I3Frame.Stream('S'),
                     icetray.I3Frame.Stream('M')])
Beispiel #3
0
def create_random_services(dataset_number,
                           run_number,
                           seed,
                           n_services=1,
                           use_gslrng=False):
    from icecube import phys_services, icetray, dataclasses
    if run_number < 0:
        raise RuntimeError("negative run numbers are not supported")
    elif run_number >= MAX_RUN_NUMBER:
        raise RuntimeError(
            "run numbers > %u are not supported".format(MAX_RUN_NUMBER))

    if dataset_number < 0:
        raise RuntimeError("negative dataset numbers are not supported")

    max_run_num = MAX_RUN_NUMBER // 10

    int_run_number = dataset_number * max_run_num + run_number

    random_services = []
    for i in range(n_services):
        streamnum = run_number + (MAX_RUN_NUMBER * i)

        if use_gslrng:
            random_services.append(
                phys_services.I3GSLRandomService(
                    seed=seed * MAX_RUN_NUMBER * n_services + streamnum))
        else:
            random_services.append(
                phys_services.I3SPRNGRandomService(seed=seed,
                                                   nstreams=MAX_RUN_NUMBER *
                                                   n_services,
                                                   streamnum=streamnum))

    return random_services, int_run_number
Beispiel #4
0
def setup_converter(useGeant4=False):
    # make a converter
    if useGeant4:
        ppcConverter = clsim.I3CLSimLightSourceToStepConverterGeant4()
    else:
        ppcConverter = clsim.I3CLSimLightSourceToStepConverterPPC(
            photonsPerStep=200)

    # initialize it
    randomGen = phys_services.I3SPRNGRandomService(seed=123456,
                                                   nstreams=10000,
                                                   streamnum=1)
    mediumProperties = clsim.MakeIceCubeMediumProperties()

    #DOMRadius = 0.16510*icetray.I3Units.m # 13" diameter
    #RadiusOverSizeFactor = 5.
    #domAcceptance = clsim.GetIceCubeDOMAcceptance(domRadius = DOMRadius*RadiusOverSizeFactor)
    domAcceptance = clsim.I3CLSimFunctionConstant(1.)

    # lets set it up
    ppcConverter.SetMediumProperties(mediumProperties)
    ppcConverter.SetRandomService(randomGen)
    ppcConverter.SetWlenBias(domAcceptance)

    ppcConverter.SetMaxBunchSize(10240)
    ppcConverter.SetBunchSizeGranularity(1)

    ppcConverter.Initialize()

    return ppcConverter
def generate(nevents=1, fname='foo.i3'):
    tray = I3Tray()

    generator = MuonGun.Floodlight()

    # set up a random number generator
    randomService = phys_services.I3SPRNGRandomService(seed=1,
                                                       nstreams=10000,
                                                       streamnum=1)
    tray.context['I3RandomService'] = randomService

    def make_particle():
        p = dataclasses.I3Particle()
        p.pos = dataclasses.I3Position(0, 0, 2e3)
        p.dir = dataclasses.I3Direction(0, 0)
        p.time = 0
        p.energy = 10**randomService.Uniform(3, 6)
        p.type = p.DeltaE
        p.location_type = p.InIce
        return p

    make_particle.i = 0

    def make_mctree(frame):
        mctree = dataclasses.I3MCTree()
        primary = make_particle()
        primary.location_type = primary.Anywhere
        primary.type = primary.unknown
        muon = make_particle()
        mctree.add_root(primary)
        mctree.append_child(primary, muon)
        frame['I3MCTree'] = mctree

    tray.AddSegment(GenerateBundles,
                    'BundleGen',
                    Generator=generator,
                    NEvents=nevents,
                    GCDFile=gcd)

    def stash(frame):
        frame['RemadeMCTree'] = dataclasses.I3MCTree(frame['I3MCTree'])

    tray.AddModule(stash, 'copy', Streams=[icetray.I3Frame.DAQ])

    tray.AddModule('I3PropagatorModule',
                   'propagator',
                   PropagatorServices=make_propagators(),
                   RandomService=randomService,
                   RNGStateName="RNGState")

    tray.AddModule('I3Writer',
                   'writer',
                   Streams=[icetray.I3Frame.DAQ, icetray.I3Frame.Physics],
                   filename=fname)

    tray.Execute(nevents + 3)
Beispiel #6
0
def configure_tray(tray, params, stats, logger):
    """
    Configures the I3Tray instance: adds modules, segments, services, etc.
    
    Args:
        tray (I3Tray): the IceProd tray instance
        params (dict): command-line arguments (and default values)
                            referenced as dict entries; see add_args()
        stats (dict): dictionary that collects run-time stats
        logger (logging.Logger): the logger for this script
    """
    # first check some variables that might need to be set
    dataset = 0
    if params['runid'] is None:
        runid = int(10**math.ceil(math.log10(params['nproc'])) * dataset +
                    params['procnum'])
    else:
        runid = params['runid']

    # THE THING
    tray.AddSegment(segments.GenerateIceTopShowers,
                    "GenerateIceTopShowers",
                    NSamples=params['samples'],
                    Files=params['inputfilelist'],
                    GCDFile=params['gcdfile'],
                    x=params['x'],
                    y=params['y'],
                    r=params['r'] * I3Units.meter,
                    TankResponse=params['tank_response'],
                    TankSamplingRadius=params['tank_sampling_radius'],
                    UnthinRadius=params['unthin_r'],
                    RunID=runid,
                    RaiseObservationLevel=params['raise_observation_level'] *
                    I3Units.m)

    if params['propagatemuons']:
        # segments.PropagateMuons requires a random service, I would prefer to use the same one used above.
        # I could also set the state of randomService to the state of tray.context['I3RandomService'] before running this segment.
        if params['usegslrng']:
            randomService = phys_services.I3GSLRandomService(
                seed=params['seed'] * params['nproc'] + params['procnum'])
        else:
            randomService = phys_services.I3SPRNGRandomService(
                seed=params['seed'],
                nstreams=params['nproc'],
                streamnum=params['procnum'])

        tray.Add('Rename', Keys=['I3MCTree', 'I3MCTree_preMuonProp'])
        tray.AddSegment(segments.PropagateMuons,
                        "PropagateMuons",
                        RandomService=randomService)

    tray.AddModule(PrintContext, "ctx")
    if params['dump']:
        tray.AddModule("Dump", "dump")
Beispiel #7
0
   def run_tray(self, cors):
        from icecube import icetray,phys_services, dataio, dataclasses
        from .. import segments
        # Instantiate a tray 
        tray = I3Tray()

        # Configure IceTray services
        summary = dataclasses.I3MapStringDouble()
        tray.context['I3SummaryService'] = summary
        
        if self.usegslrng:
            randomService = phys_services.I3GSLRandomService(self.seed)
        else:
            randomService = phys_services.I3SPRNGRandomService(self.seed, self.nproc, self.procnum)
        tray.context["I3RandomService"] = randomService

        tray.AddSegment(CorsikaReaderTraySegment,
                  gcdfile=self.gcdfile, randomService=randomService,
                  SimulateIceTop=self.simulateicetop,
                  select_neutrino=self.selectneutrino, 
                  legacyoversampling=self.legacyoversampling,
                  oversampling=self.oversampling, cors=cors, stats=self.stats)


        if self.enablehistogram and self.histogramfilename:         
            from icecube.production_histograms import ProductionHistogramModule
            from icecube.production_histograms.histogram_modules.simulation.mctree_primary import I3MCTreePrimaryModule
        
            tray.AddModule(ProductionHistogramModule, 
                           Histograms = [I3MCTreePrimaryModule],
                           OutputFilename = self.histogramfilename)
       
        tray.AddModule("I3Writer", 
                       filename = self.outputfile, 
                       Streams=[icetray.I3Frame.TrayInfo,
                                icetray.I3Frame.DAQ,
                                icetray.I3Frame.Stream('S'),
                                icetray.I3Frame.Stream('M')])
         
        # Execute the Tray
        tray.Execute()

        # Save stats
        summary = tray.context['I3SummaryService']

        for k in tray.Usage():
            self.stats[str(k.key())+":usr"] = k.data().usertime
            summary[str(k.key())+":usr"] = k.data().usertime
            self.stats[str(k.key())+":sys"] = k.data().systime
            summary[str(k.key())+":sys"] = k.data().systime
            self.stats[str(k.key())+":ncall"] = k.data().systime
            summary[str(k.key())+":ncall"] = k.data().systime

        WriteI3Summary(summary, self.summaryfile)
def _add_i3_random_service(tray, usegslrng, seed, nstreams, streamnum):
    if (nstreams is None) or (streamnum is None):  #either may be 0
        rand = phys_services.I3GSLRandomService(seed=seed)
    elif usegslrng:
        rand = phys_services.I3GSLRandomService(seed=seed * nstreams +
                                                streamnum)
    else:
        rand = phys_services.I3SPRNGRandomService(seed=seed,
                                                  nstreams=nstreams,
                                                  streamnum=streamnum)
    tray.context['I3RandomService'] = rand
Beispiel #9
0
def create_random_services(dataset_number, run_number, seed):
    from icecube import phys_services, icetray, dataclasses
    if run_number < 0:
        raise RuntimeError("negative run numbers are not supported")
    elif run_number >= MAX_RUN_NUMBER:
        raise RuntimeError(
            "run numbers > %u are not supported".format(MAX_RUN_NUMBER))

    if dataset_number < 0:
        raise RuntimeError("negative dataset numbers are not supported")

    int_run_number = dataset_number * MAX_RUN_NUMBER + run_number

    random_service = phys_services.I3SPRNGRandomService(
        seed=seed,
        nstreams=MAX_RUN_NUMBER * 2,
        streamnum=run_number + MAX_RUN_NUMBER)

    random_service_prop = phys_services.I3SPRNGRandomService(
        seed=seed, nstreams=MAX_RUN_NUMBER * 2, streamnum=run_number)
    return random_service, random_service_prop, int_run_number
Beispiel #10
0
    def run_tray(self, cors):
        from icecube import icetray, phys_services, dataio, dataclasses
        # Instantiate a tray
        tray = I3Tray()

        # Configure IceTray services
        tray.AddService("I3XMLSummaryServiceFactory",
                        "summary",
                        outputfilename=self.summaryfile)

        randomService = phys_services.I3SPRNGRandomService(
            self.seed, self.nproc, self.procnum)
        tray.context["I3RandomService"] = randomService

        if self.oversampling > 1 and self.usepipe:
            self.logger.fatal(
                "Oversampling is not compatible with UsePIPE at this time")
            sys.exit(1)

        tray.AddSegment(CorsikaReaderTraySegment,
                        gcdfile="",
                        randomService=randomService,
                        SimulateIceTop=self.simulateicetop,
                        oversampling=self.oversampling,
                        cors=cors,
                        stats=self.stats)

        if self.histogramfilename:
            from icecube.production_histograms import ProductionHistogramModule
            from icecube.production_histograms.histogram_modules.simulation.mctree_primary import I3MCTreePrimaryModule

            tray.AddModule(ProductionHistogramModule,
                           Histograms=[I3MCTreePrimaryModule],
                           OutputFilename=self.histogramfilename)

        tray.AddModule("I3Writer",
                       filename=self.outputfile,
                       streams=[icetray.I3Frame.DAQ])

        # Execute the Tray
        tray.Execute()
        tray.Finish()

        # Save stats
        tray.PrintUsage()
        for k in tray.Usage():
            self.stats[str(k.key()) + ":usr"] = k.data().usertime
            self.stats[str(k.key()) + ":sys"] = k.data().systime
            self.stats[str(k.key()) + ":ncall"] = k.data().systime
Beispiel #11
0
def configure_tray(tray, params, stats, logger):
    """
    Configures the I3Tray instance: adds modules, segments, services, etc.

    Args:
        tray (I3Tray): the IceProd tray instance
        params (dict): command-line arguments (and default values)
                            referenced as dict entries; see add_args()
        stats (dict): dictionary that collects run-time stats
        logger (logging.Logger): the logger for this script
    """
    if params['propagatemuons']:
        if params['usegslrng']:
            randomServiceForPropagators = phys_services.I3GSLRandomService(seed=params['seed'] * params['nproc'] + params['procnum'])
        else:
            randomServiceForPropagators = phys_services.I3SPRNGRandomService(seed=params['seed'], nstreams=params['nproc'] * 2, streamnum=params['nproc'] + params['procnum'])

        tray.context['I3PropagatorRandomService'] = randomServiceForPropagators
        tray.AddModule("Rename", "rename_corsika_mctree", Keys=['I3MCTree', 'I3MCTree_preMuonProp'])
        tray.AddSegment(segments.PropagateMuons, 'propagator',
                        RandomService=randomServiceForPropagators,
                        **params['proposalparams'])

    tray.AddSegment(segments.PPCTraySegment, "ppc_photons",
                    GPU=params['gpu'],
                    UseGPUs=params['usegpus'],
                    UnshadowedFraction=params['efficiency'],
                    DOMOversizeFactor=params['oversize'],
                    IceModelLocation=params['icemodellocation'],
                    HoleIceParameterization=params['holeiceparametrization'],
                    IceModel=params['icemodel'],
                    volumecyl=params['volumecyl'],
                    gpulib=params['gpulib'],
                    InputMCTree=params['mctreename'],
                    keep_empty_events=params['keepemptyevents'],
                    MCPESeriesName=params['photonseriesname'],
                    tempdir=params['tempdir'])

    if params['runmphitfilter']:
        tray.AddModule("MPHitFilter", "hitfilter",
                       HitOMThreshold=1,
                       RemoveBackgroundOnly=False,
                       I3MCPESeriesMapName=params['photonseriesname'])

    if params['enablehistogram'] and params['histogramfilename']:
        tray.AddModule(ProductionHistogramModule,
                       Histograms=[I3MCPEModule],
                       OutputFilename=params['histogramfilename'])
   def Execute(self,stats):
        if not ipmodule.ParsingModule.Execute(self,stats): return 0

        # Instantiate a tray 
        tray = I3Tray()

        randomService = phys_services.I3SPRNGRandomService(self.rngseed, self.rngnumberofstreams, self.rngstream)
        tray.context['I3RandomService'] = randomService

        if not self.summaryfile:
            raise Exception('must define summary file')
        tray.AddService("I3XMLSummaryServiceFactory","summary")(
            ("outputfilename",self.summaryfile),
        )
         
        tray.AddSegment(NuGenTraySegment,"nugen",
             gcdfile=self.gcdfile,
             nuflavor=self.nuflavor,
             mjd=self.mjd, 
             nevents=self.nevents,
             cssflag=self.usecss, 
             runId=self.runid,
             randomService=randomService,
             elogmax=self.elogmax,
             elogmin=self.elogmin,
             gamma=self.gamma,
             stats=stats,
             bs=self.bs,
             ph=self.ph,
             bb=self.bb,
             sh=self.sh)

        tray.AddModule("I3Writer","writer")(
            ("filename",self.outputfile),
            ("streams",[icetray.I3Frame.DAQ])
        )

        tray.AddModule("TrashCan","trashcan")

        # Execute the Tray
        tray.Execute()
        tray.Finish()

        # Free memory
        del tray
        return 0
   def Execute(self,stats):
        if not ipmodule.ParsingModule.Execute(self,stats): return 0

        # Instantiate a tray 
        tray = I3Tray()

        randomService = phys_services.I3SPRNGRandomService(self.rngseed, self.rngnumberofstreams, self.rngstream)
        tray.context['I3RandomService'] = randomService

        summary = dataclasses.I3MapStringDouble()
        tray.context["I3SummaryService"] = summary
         
        tray.AddSegment(NuGenTraySegment,"nugen",
             gcdfile=self.gcdfile,
             nuflavor=self.nuflavor,
             mjd=self.mjd, 
             nevents=self.nevents,
             cssflag=self.usecss, 
             runId=self.runid,
             randomService=randomService,
             elogmax=self.elogmax,
             elogmin=self.elogmin,
             gamma=self.gamma,
             stats=stats,
             bs=self.bs,
             ph=self.ph,
             bb=self.bb,
             sh=self.sh)

        tray.AddModule("I3Writer","writer")(
            ("filename",self.outputfile),
            ("streams",[icetray.I3Frame.DAQ])
        )

        

        # Execute the Tray
        tray.Execute()
        

        # Free memory
        del tray
        return 0
Beispiel #14
0
   def Execute(self,stats={}):
        from .. import segments
        if not ipmodule.ParsingModule.Execute(self,stats): return 0

        from icecube import icetray, dataclasses, dataio, phys_services, interfaces
        from icecube import corsika_reader
        from I3Tray import I3Tray,I3Units

        # Instantiate a tray 
        tray = I3Tray()

        summary_in  = self.summaryfile
        summary_out = self.summaryfile
        if not os.path.exists(self.summaryfile):
           summary_in  = ''

        randomService = phys_services.I3SPRNGRandomService(
             		seed = self.seed,
             		nstreams = self.nproc,
             		streamnum = self.procnum)\
            if not self.usegslrng else phys_services.I3GSLRandomService(seed = self.seed*self.nproc+self.procnum)

        tray.context['I3RandomService'] = randomService



        inputfiles  = self.GetParameter('inputfilelist')
        # Configure IceTray modules 
        tray.AddModule("I3Reader", "reader",filenamelist=[self.gcdfile]+inputfiles)
        tray.AddModule("CORSIKAResampler","resample",
	        OverSampling=self.oversampling,
	        CylinderHeight=self.cylinderheight, 
	        CylinderRadius=self.cylinderradius)
        self.Configure(tray)

       # Execute 
        print(tray) 
        tray.Execute()

        del tray
        return 0
Beispiel #15
0
def configure_tray(tray, params, stats, logger):
    """
    Configures the I3Tray instance: adds modules, segments, services, etc.

    Args:
        tray (I3Tray): the IceProd tray instance
        params (dict): command-line arguments (and default values)
                            referenced as dict entries; see add_args()
        stats (dict): dictionary that collects run-time stats
        logger (logging.Logger): the logger for this script
    """
    if params['usegslrng']:
        randomServiceForPropagators = phys_services.I3GSLRandomService(
            seed=2 * (params['seed'] * params['nproc'] + params['procnum']))
    else:
        randomServiceForPropagators = phys_services.I3SPRNGRandomService(
            seed=params['seed'],
            nstreams=params['nproc'] * 2,
            streamnum=params['nproc'] + params['procnum'])

    tray.AddModule("I3InfiniteSource",
                   "TheSource",
                   Prefix=params['gcdfile'],
                   Stream=icetray.I3Frame.DAQ)
    tray.AddModule(DAQCounter, "counter3", nevents=int(params['nevents']))

    vnutypes = []
    vtyperatio = []
    for key in params['nutypes']:
        vnutypes.append(key)
        vtyperatio.append(params['nutypes[key]'])

    tray.AddSegment(segments.GenerateNeutrinos,
                    'generator',
                    RandomService=tray.context['I3RandomService'],
                    RunID=params['runid'],
                    NumEvents=params['nevents'],
                    SimMode=params['simmode'],
                    VTXGenMode=params['vtxgenmode'],
                    InjectionMode=params['injectionmode'],
                    CylinderParams=params['cylinderparams'],
                    AutoExtendMuonVolume=params['autoextendmuonvolume'],
                    Flavor=params['nuflavor'],
                    NuTypes=vnutypes,
                    PrimaryTypeRatio=vtyperatio,
                    GammaIndex=params['gamma'],
                    FromEnergy=params['fromenergy'],
                    ToEnergy=params['toenergy'],
                    ZenithRange=[params['zenithmin'], params['zenithmax']],
                    AzimuthRange=[params['azimuthmin'], params['azimuthmax']],
                    UseDifferentialXsection=params['usedifferentialxsection'],
                    CrossSections=params['crosssections'],
                    CrossSectionsPath=params['crosssectionspath'],
                    ZenithSamplingMode=params['zenithsamplingmode'],
                    ParamsMap=params['paramsmap'])

    if params['polyplopia']:
        tray.AddSegment(segments.PolyplopiaSegment,
                        "coincify",
                        RandomService=tray.context['I3RandomService'],
                        mctype='NuGen',
                        bgfile=params['backgroundfile'],
                        timewindow=40. * I3Units.microsecond,
                        rate=5.0 * I3Units.kilohertz)

    if params['propagatemuons']:
        tray.context['I3PropagatorRandomService'] = randomServiceForPropagators
        tray.AddSegment(segments.PropagateMuons,
                        'propagator',
                        RandomService=randomServiceForPropagators,
                        **params['proposalparams'])

    tray.AddModule(BasicCounter,
                   "count_g",
                   Streams=[icetray.I3Frame.DAQ],
                   name="Generated Events",
                   Stats=stats)

    if params['enablehistogram'] and params['histogramfilename']:
        tray.AddModule(ProductionHistogramModule,
                       Histograms=[I3MCTreePrimaryModule, I3MCTreeModule],
                       OutputFilename=params['histogramfilename'])
elif options.RUNNUMBER >= maxRunNumber:
    raise RuntimeError("run numbers > %u are not supported" % maxRunNumber)

if options.DATASETNUMBER < 0:
    raise RuntimeError("negative dataset numbers are not supported")
elif options.DATASETNUMBER >= maxDatasetNumber:
    raise RuntimeError("dataset numbers > %u are not supported" %
                       maxDatasetNumber)

internalRunNumber = options.DATASETNUMBER * maxRunNumber + options.RUNNUMBER

# make sure we use the same seed for all RNGs (different streams are okay!)

# set up a random number generator
randomService = phys_services.I3SPRNGRandomService(
    seed=options.SEED,
    nstreams=maxInternalRunNumber * 2,
    streamnum=internalRunNumber + maxInternalRunNumber)
# re-use the same RNG for modules that need it on the context
tray.context['I3RandomService'] = randomService

# a special random service for muon propagation
randomServiceForPropagators = phys_services.I3SPRNGRandomService(
    seed=options.SEED,
    nstreams=maxInternalRunNumber * 2,
    streamnum=internalRunNumber)

if options.GENERATOR.lower() == "nugen":

    tray.AddModule("I3InfiniteSource",
                   "TheSource",
                   Prefix=gcdFile,
def PerformPropagationSimulation():
    tray = I3Tray()
    tray.AddModule("I3Reader", FilenameList=input_files)
    tray.AddService("I3SPRNGRandomServiceFactory",
                    Seed=options.seed,
                    NStreams=2,
                    StreamNum=1)
    randomService = phys_services.I3SPRNGRandomService(seed=options.seed,
                                                       nstreams=10000,
                                                       streamnum=1)

    common_clsim_parameters = dict(
        PhotonSeriesName="PropagatedPhotons",
        RandomService=randomService,
        UseGPUs=options.use_gpus,
        UseCPUs=not options.use_gpus,
        ParallelEvents=options.number_of_parallel_runs,
        IceModelLocation=options.ice_model_file,
        UnWeightedPhotons=True,
        #UnWeightedPhotonsScalingFactor=0.01,
        DOMOversizeFactor=1.0,
        UnshadowedFraction=1.0,
        FlasherInfoVectName=("I3FlasherInfo"
                             if options.use_flasher_info_vect else ""),
        FlasherPulseSeriesName=("PhotonFlasherPulseSeries"
                                if not options.use_flasher_info_vect else ""),
        UseHoleIceParameterization=options.
        use_hole_ice_approximation,  # Angular Acceptance Modification.
    )

    # In production, we do not need to save the photons. Thus, we skip this for
    # performance and disk space reasons. But one can activate
    # `--save-photon-paths` for visualization or debug reasons.
    #
    if options.save_photon_paths:
        tray.AddSegment(
            clsim.I3CLSimMakePhotons,
            StopDetectedPhotons=False,
            PhotonHistoryEntries=10000,
            ExtraArgumentsToI3CLSimModule=dict(
                SaveAllPhotons=True,
                SaveAllPhotonsPrescale=1.0,
                MaxNumOutputPhotonsCorrectionFactor=1.0,
                SimulateHoleIce=options.use_hole_ice_simulation,
                HoleIceScatteringLengthFactor=options.scattering_factor,
                HoleIceAbsorptionLengthFactor=options.absorption_factor),
            **common_clsim_parameters)
        icetray.set_log_level(icetray.I3LogLevel.LOG_DEBUG)
    else:

        extra_args = dict()
        if options.use_hole_ice_simulation:
            extra_args = dict(
                SimulateHoleIce=options.use_hole_ice_simulation,
                HoleIceScatteringLengthFactor=options.scattering_factor,
                HoleIceAbsorptionLengthFactor=options.absorption_factor)

        tray.AddSegment(clsim.I3CLSimMakeHits,
                        StopDetectedPhotons=True,
                        ExtraArgumentsToI3CLSimModule=extra_args,
                        **common_clsim_parameters)

    if not options.save_photon_paths:
        # This does only work with the `I3CLSimMakeHits` module, thus does
        # not work with `save_photon_paths`.
        tray.AddModule(ReadOutAngularAcceptance, Streams=[icetray.I3Frame.DAQ])

    tray.AddModule("I3Writer", Filename=options.output_i3_file)
    tray.AddModule("TrashCan")

    if options.number_of_frames == 0:
        tray.Execute()
    else:
        tray.Execute(options.number_of_frames)

    tray.Finish()
Beispiel #18
0
    infileRootDir, infileRootFile = os.path.split(infileRoot)
    outfile = infileRootFile + "_calib"
    outfile = outfile + infileExt
print("output dir is %s" % outdir)
print("output file is %s" % outdir + outfile)

########################

mask = options.FLASHERMASK
nled = bin(mask).count("1")

tray = I3Tray()

# set up a random number generator
randomService = phys_services.I3SPRNGRandomService(seed=options.SEED,
                                                   nstreams=options.NSTREAMS,
                                                   streamnum=options.RUNNUMBER)

# re-use the same RNG for modules that need it on the context
tray.context['I3RandomService'] = randomService

tray.AddModule("I3InfiniteSource",
               Prefix=options.GCDFILE,
               Stream=icetray.I3Frame.DAQ)

if options.USEGENERATEFLASHERS:
    print("segments.GenerateFlashers")
    tray.AddModule(segments.GenerateFlashers,
                   Streams=[icetray.I3Frame.DAQ],
                   FlashString=options.FSTR,
                   FlashDOM=options.FDOM,
Beispiel #19
0
    emax = sys.argv[5]
if (len(sys.argv) > 6):
    minzen = sys.argv[6]
if (len(sys.argv) > 7):
    maxzen = sys.argv[7]
if (len(sys.argv) > 8):
    zenithweightparam = sys.argv[8]
if (len(sys.argv) > 9):
    injectionmode = sys.argv[9]

outi3filename = flavorString + "_" + xsec + "_ZenA" + zenithweightparam + "_InjMode" + injectionmode + "_MinZen" + minzen + "_MaxZen" + maxzen + "_ELogMin" + emin + "_ELogMax" + emax + "_E" + gamma + ".i3"

print("out i3 filename is ", outi3filename)

# generate random service
random = phys_services.I3SPRNGRandomService(1, 10000, 1)
tray.context['I3RandomService'] = random

from os.path import expandvars
tray.AddModule(
    "I3InfiniteSource",
    "source",
    prefix=expandvars(
        "$I3_TESTDATA/sim/GeoCalibDetectorStatus_IC86.55380_corrected.i3.gz"))

tray.AddModule("I3MCEventHeaderGenerator", "ev")

#
# At least EarthModelService & Steering Service are required
#
outfile = args.OUTPUT

print("Command line options parsed...")

import os, sys

tray = I3Tray()

# import phys_services which includes rng
from icecube import phys_services

print("RNG being initiated...")
# set up a random number generator
randomService = phys_services.I3SPRNGRandomService(seed=args.SEED,
                                                   nstreams=100000000,
                                                   streamnum=args.RUNNUMBER)

tray.context['I3RandomService'] = randomService

tray.AddModule('I3Reader', 'reader', filenamelist=[args.GCDFILE, args.INPUT])

tray.Add('Delete', 'initial_clean', Keys=['I3MCPESeriesMap'])

holeiceparameterization = expandvars(args.HOLEICE)

print("mcpes:", args.MCPES)

tray.AddModule("I3GeometryDecomposer", "decomposeGeometry")

from icecube import clsim
   def Execute(self,stats):
        if not ipmodule.ParsingModule.Execute(self,stats): return 0

        import icecube.icetray
        from icecube import icetray,dataclasses, phys_services, dataio
        from icecube.MuonGun import load_model, StaticSurfaceInjector, Cylinder, OffsetPowerLaw
        from icecube.MuonGun.segments import GenerateBundles

        from I3Tray import I3Tray, I3Units
        
        modelstr = self.GetParameter('model')
        emax   = self.GetParameter("eprimarymax")
        emin   = self.GetParameter("eprimarymin")
        length = self.GetParameter("length")
        radius = self.GetParameter("radius")
        cthmin = self.GetParameter('cthmin')
        cthmax = self.GetParameter('cthmax')
        gamma  = self.GetParameter('gamma')

        seed   = self.GetParameter('seed')
        nproc  = self.GetParameter('nproc')
        procnum  = self.GetParameter('procnum')
        gcdfile = self.GetParameter('gcdfile')
    
        # Instantiate a tray 
        tray = I3Tray()

        # Configure IceTray services
        summary = dataclasses.I3MapStringDouble()
        tray.context["I3SummaryService"] = summary
         
        randomService = phys_services.I3SPRNGRandomService(seed, nproc, procnum)
        tray.context["I3RandomService"] = randomService


        # Use Hoerandel as a template for generating muons
        model = load_model(modelstr)
        # Generate only single muons, no bundles
        model.flux.max_multiplicity = 1
        # Center the sampling surface on the barycenter of IC79 strings
        #surface = Cylinder(1600*I3Units.m, 800*I3Units.m, dataclasses.I3Position(31.25, 19.64, 0))
        surface = Cylinder(length*I3Units.m, radius*I3Units.m)
        # Draw energies from an E^-2 power law broken at 1 TeV, from 10 TeV to 10 PeV
        spectrum = OffsetPowerLaw(gamma, 1*I3Units.TeV, 10*I3Units.TeV, 10*I3Units.PeV)
        # Set up the generator. This gets stored in a special frame for later reference
        generator = StaticSurfaceInjector(surface, model.flux, spectrum, model.radius)

        # Configure TraySegment that actually does stuff
        tray.AddSegment(GenerateBundles,"corsika-background", Generator=generator, 
              RunNumber=self.runid, NEvents=self.nshowers, 
              GCDFile=self.gcdfile,
              FromTime=dataclasses.I3Time(self.mjd),
              ToTime=dataclasses.I3Time(self.mjd))

        def renameMCTree(frame):
          mctree = frame["I3MCTree"]
          del frame["I3MCTree"]
          frame["I3MCTree_preMuonProp"] = mctree
        tray.AddModule(renameMCTree, "renameMCTree", Streams=[icetray.I3Frame.DAQ])
        tray.AddSegment(PropagateMuons,'propagator', RandomService=randomService, 
             CylinderLength=self.length,
             CylinderRadius=self.radius,
             bs=self.bs,
             ph=self.ph,
             bb=self.bb,
             sh=self.sh)

        tray.AddModule(BasicCounter,"count_g", Streams = [icetray.I3Frame.DAQ], 
              name = "Generated Events", Stats = stats)
       
        tray.AddModule("I3Writer","writer", filename = self.outputfile, streams =[icecube.icetray.I3Frame.DAQ] )

        

        # Execute the Tray
        tray.Execute()
        

        del tray
        return 0
   def Execute(self,stats):
        if not ipmodule.ParsingModule.Execute(self,stats): return 0

        from I3Tray import I3Tray
        from icecube import icetray,phys_services, dataio, dataclasses
        
   
        if self.cutofftype == "EnergyPerNucleon" : self.spric = True
        elif cutofftype == "EnergyPerParticle" : self.spric = False
        else: raise Exception, "Undefined CutoffType %s" % cutoff_typ
        print self.atmospheres
        cors = configure_corsika(self)
        cors.f2k = "F"

        print self.runcorsika, "runcorsika",self.inputfile
        if self.runcorsika and not self.inputfile:
           # Run corsika
           retval = cors.Execute(stats) 

           if retval: 
              raise Exception, "dCorsika exited with return value %s" % retval
        elif self.inputfile:
           cors.outfile = self.inputfile
           print self.runcorsika, "runcorsika",self.inputfile
        elif not self.runcorsika:
             cors.configure()
             cors.write_steering()
    
        # Instantiate a tray 
        tray = I3Tray()

        # Configure IceTray services
        summary = dataclasses.I3MapStringDouble()
        tray.context["I3SummaryService"] = summary
         
        randomService = phys_services.I3SPRNGRandomService(self.seed, self.nproc, self.procnum)#, oustatefile="rng.state")
        tray.context["I3RandomService"] = randomService

        # Configure TraySegment that actually does stuff
        tray.AddSegment(CorsikaReaderTraySegment,"corsika-reader",
              gcdfile=self.gcdfile, mjd=self.mjd, runId=self.runid, randomService=randomService,
              oversampling=self.oversampling, fluxsum=self.fluxsum, cors=cors, stats={}, 
             CylinderLength=self.length,
             CylinderRadius=self.radius,
             bs=self.bs,
             ph=self.ph,
             bb=self.bb,
             sh=self.sh)

        tray.AddModule(BasicCounter,"count_g", Streams = [icetray.I3Frame.DAQ], 
              name = "Generated Events", Stats = stats)
       
        tray.AddModule("I3Writer","writer", filename = self.outputfile, streams =[icetray.I3Frame.DAQ] )

        

        # Execute the Tray
        tray.Execute()
        

        del tray
        return 0
Beispiel #23
0
import sys, os
from I3Tray import *
from icecube.simprod.util import *
import icecube.simclasses
from icecube.clsim.shadow import *
from icecube.simclasses import I3CylinderMap
from os.path import expandvars
from generateEvent import *

cable_map = I3CylinderMap()

outfile = sys.argv[1]
seed = int(sys.argv[2])

randomService = phys_services.I3SPRNGRandomService(
    seed = 1,
    nstreams = 100000,
    streamnum = seed)


gcd_file = "GeoCalibDetectorStatus_2013.56429_V1.i3.gz"

tray = I3Tray()

tray.AddModule("I3InfiniteSource" , "streams" , Prefix=expandvars(gcd_file),Stream = icetray.I3Frame.DAQ)

tray.Add(AddCylinders , Cable_map = cable_map ,Length_of_cylinder = 17.0, Radius_of_cylinder = 0.023)

tray.Add("Dump")

tray.AddModule("I3MCEventHeaderGenerator","gen_header",
               Year = 2009,
Beispiel #24
0

#TODO Are these stored in the I frame


#########################
# MUONGUN 
#########################

# Use dataset number for seeding
seed = 139005

# Set up random number generator
from globals import max_num_files_per_dataset
randomService = phys_services.I3SPRNGRandomService(
        seed = seed*2, #TODO Store to I frame
        nstreams = max_num_files_per_dataset,
        streamnum = args.filenr)
tray.context['I3RandomService'] = randomService

# Generate bundles of muons
tray.AddSegment(GenerateBundles, 'BundleGen', Generator=generator, NEvents=args.numevents, GCDFile=expandvars(args.gcdfile))

#TODO simprod-scripts/python/segments/GenerateCosmicRayMuons.py add generator module in a differnt way (see line below). Are these equivalent?
# tray.AddModule('I3MuonGun::GeneratorModule',name,Generator=num_events*generator)

# Propogate the muons in the detector
tray.AddModule('I3PropagatorModule', PropagatorServices=get_propagators(), RandomService=randomService)

# Calculate event weights
raw_weight_name = 'MuonWeight'
tray.AddModule('I3MuonGun::WeightCalculatorModule', raw_weight_name, Model=model, Generator=generator)
def check(fname='foo.i3', fraction=0.1):

    from unittest import TestCase

    tray = I3Tray()

    tray.AddModule('I3Reader', 'reader', filenamelist=[gcd, fname])

    # set up a random number generator
    randomService = phys_services.I3SPRNGRandomService(seed=2,
                                                       nstreams=10000,
                                                       streamnum=1)

    # Throw out a random subset of events. The remainder must be reproducible
    # given the same random number sequence
    def drop_random_events(frame, fraction=fraction):
        return randomService.uniform(0, 1) < (1 - fraction)

    tray.AddModule(drop_random_events,
                   'triggerhappy',
                   Streams=[icetray.I3Frame.DAQ])

    tray.Add("Rename", keys=["MMCTrackList", "OldMMCTrackList"])

    tray.AddModule('I3PropagatorModule',
                   'propagator',
                   PropagatorServices=make_propagators(),
                   RandomService=randomService,
                   RNGStateName="RNGState",
                   InputMCTreeName="RemadeMCTree",
                   OutputMCTreeName="RemadeMCTree")

    class MCTreeCompare(TestCase):
        """
		Ensure that every entry in the re-simulated MCTree is completely
		identical to the original one.
		"""
        def setUp(self):
            self.orig_tree = self.frame['I3MCTree']
            self.orig_mmctracks = self.frame['OldMMCTrackList']
            self.new_tree = self.frame['RemadeMCTree']
            self.new_mmctracks = self.frame['MMCTrackList']

        def testTotalSize(self):
            self.assertEquals(len(self.orig_tree), len(self.new_tree))
            self.assertEquals(len(self.orig_mmctracks),
                              len(self.new_mmctracks))

        def testParticleContent(self):

            for p1, p2 in zip(self.orig_tree, self.new_tree):
                if p1.location_type != p1.InIce:
                    continue
                self.assertEquals(p1.energy, p2.energy)
                self.assertEquals(p1.type, p2.type)
                self.assertEquals(p1.time, p2.time)
                self.assertEquals(p1.length, p2.length)
                for d in 'x', 'y', 'z':
                    self.assertEquals(getattr(p1.pos, d), getattr(p2.pos, d))
                for d in 'zenith', 'azimuth':
                    self.assertEquals(getattr(p1.dir, d), getattr(p2.dir, d))
            for t1, t2 in zip(self.orig_mmctracks, self.new_mmctracks):
                for prop in 'E', 'X', 'Y', 'Z', 'T':
                    for location in 'i', 'c', 'f':
                        method = 'Get' + prop + location
                        self.assertEquals(
                            getattr(t1, method)(),
                            getattr(t2, method)())

    tray.AddModule(icetray.I3TestModuleFactory(MCTreeCompare),
                   'testy',
                   Streams=[icetray.I3Frame.DAQ])

    tray.Execute()
Beispiel #26
0
def RecreateMCTree(tray,
                   name,
                   MCTree="I3MCTree",
                   RawMCTree="I3MCTreeRaw",
                   RNGState="RNGState",
                   Propagators=None,
                   Paranoia=True):
    """
	Recreate the results of lepton propagation and shower simulation that
	were discarded in order to save space.
	
	:param RawMCTree: name of the un-propagated I3MCTree to use as input
	:param MCTree: name of the re-propagated I3MCTree to put back in the frame
	:param RNGState: name of the object storing the state of the random number generator
	:param Propagators: an I3ParticleTypePropagatorServiceMap giving the propagators
	                    to use for each kind of particle. If this is None, use
	                    PROPOSAL for muons and CMC for showers.
	:param Paranoia: if True, compare the re-propagated result to the original when
	                 it is present in the frame and raise an assertion if they differ.
	"""
    from icecube import phys_services, sim_services

    if Propagators is None:
        Propagators = get_propagators()

    # NB: the parameters given here do not matter. If they are different
    #     from the stored state the generator will be re-initialized.
    randomService = phys_services.I3SPRNGRandomService(seed=2,
                                                       nstreams=10000,
                                                       streamnum=1)

    recreate = lambda frame: RNGState in frame and MCTree not in frame
    audit = lambda frame: RNGState in frame and MCTree in frame

    tray.AddModule('I3PropagatorModule',
                   name + 'Propagator',
                   PropagatorServices=Propagators,
                   RandomService=randomService,
                   RNGStateName=RNGState,
                   InputMCTreeName=RawMCTree,
                   OutputMCTreeName=MCTree,
                   If=recreate)

    if Paranoia:
        # Paranoid mode: check results
        ParanoidMCTree = name + "MCTree"
        tray.AddModule('I3PropagatorModule',
                       name + 'ParanoidPropagator',
                       PropagatorServices=Propagators,
                       RandomService=randomService,
                       RNGStateName=RNGState,
                       InputMCTreeName=RawMCTree,
                       OutputMCTreeName=ParanoidMCTree,
                       If=audit)

        from unittest import TestCase
        from unittest.util import safe_repr

        def assertClose(self, a, b, rtol=1e-8, atol=0, msg=None):
            """
			a and b are equal to within tolerances
		
			:param rtol: relative tolerance
			:param atol: absolute tolerance
			"""
            if abs(a - b) > atol + rtol * abs(b):
                if (atol > 0 and abs(a - b) > atol):
                    standardMsg = "%s != %s to within %s (absolute)" % (
                        safe_repr(a), safe_repr(b), safe_repr(atol))
                else:
                    standardMsg = "%s != %s to within %s (relative)" % (
                        safe_repr(a), safe_repr(b), safe_repr(rtol))

                msg = self._formatMessage(msg, standardMsg)
                raise self.failureException(msg)
            else:
                return

        TestCase.assertClose = assertClose

        class MCTreeAudit(TestCase):
            """
			Ensure that every entry in the re-simulated MCTree is
			identical to the original one to within round-off error.
			"""
            def setUp(self):
                self.orig_tree = self.frame[MCTree]
                self.new_tree = self.frame[ParanoidMCTree]

            def testTotalSize(self):
                self.assertEquals(len(self.orig_tree), len(self.new_tree))

            def testParticleContent(self):

                for p1, p2 in zip(self.orig_tree, self.new_tree):
                    if p1.location_type != p1.InIce:
                        continue
                    self.assertEquals(p1.type, p2.type)
                    self.assertClose(p1.energy,
                                     p2.energy,
                                     atol=1e-6,
                                     rtol=1e-9)
                    self.assertClose(p1.time, p2.time, atol=1, rtol=1e-9)
                    self.assertClose(p1.length,
                                     p2.length,
                                     atol=1e-6,
                                     rtol=1e-9)
                    for d in 'x', 'y', 'z':
                        self.assertClose(getattr(p1.pos, d),
                                         getattr(p2.pos, d),
                                         atol=1e-6,
                                         rtol=1e-9)
                    for d in 'zenith', 'azimuth':
                        self.assertClose(getattr(p1.dir, d),
                                         getattr(p2.dir, d),
                                         atol=1e-6,
                                         rtol=1e-9)

        tray.AddModule(icetray.I3TestModuleFactory(MCTreeAudit),
                       name + 'ParanoidCheck',
                       Streams=[icetray.I3Frame.DAQ],
                       If=audit)
        tray.AddModule('Delete',
                       name + 'DeleteParanoidCruft',
                       Keys=[ParanoidMCTree],
                       If=audit)
Beispiel #27
0
(options, args) = parser.parse_args()
if len(args) != 0:
    crap = "Got undefined options:"
    for a in args:
        crap += a
        crap += " "
    parser.error(crap)

tray = I3Tray()

gcdfile = options.GCDFILE
inputfile = options.INPUTFILE

randomService = phys_services.I3SPRNGRandomService(options.SEED,
                                                   nstreams=2,
                                                   streamnum=0)
randomServiceForPropagators = phys_services.I3SPRNGRandomService(options.SEED,
                                                                 nstreams=2,
                                                                 streamnum=1)

tray.context["I3RandomService"] = randomService
tray.context["I3RandomServiceForPropagators"] = randomServiceForPropagators

tray.AddService("I3XMLSummaryServiceFactory",
                "summary",
                outputfilename="muongunbg.xml")

# Default: use Hoerandel as a template for generating muons.
model = icecube.MuonGun.load_model("Hoerandel5_atmod12_SIBYLL")
Beispiel #28
0
    def Execute(self, stats):
        if not ipmodule.ParsingModule.Execute(self, stats): return 0

        # Load libraries
        from icecube import (neutrino_generator, earthmodel_service, PROPOSAL,
                             cmc, phys_services)
        from .. import segments

        # support json ParamsMap, so we can get our dict from the iceprod config file
        try:
            import json
        except ImportError:
            json = None
        if isinstance(self.paramsmap, str):
            if not json:
                raise Exception(
                    'ParamsMap provided as string, but python does not understand json'
                )
            self.paramsmap = json.loads(self.paramsmap)

        if isinstance(self.proposalparams, str):
            if not json:
                raise Exception(
                    'ProposalParams provided as string, but python does not understand json'
                )
            self.proposalparams = json.loads(self.proposalparams)
        # Instantiate a tray
        tray = I3Tray()

        randomService = phys_services.I3SPRNGRandomService(
            seed=self.rngseed,
            nstreams=self.rngnumberofstreams,
            streamnum=self.rngstream)

        randomServiceForPropagators = phys_services.I3SPRNGRandomService(
            seed=self.rngseed,
            nstreams=self.rngnumberofstreams * 2,
            streamnum=self.rngnumberofstreams + self.rngstream)

        tray.context['I3RandomService'] = randomService
        tray.context['I3PropagatorRandomService'] = randomServiceForPropagators

        if not self.summaryfile:
            raise Exception('must define summary file')
        tray.AddService(
            "I3XMLSummaryServiceFactory",
            "summary",
            outputfilename=self.summaryfile,
        )

        tray.AddModule("I3InfiniteSource",
                       "TheSource",
                       Prefix=self.gcdfile,
                       Stream=icetray.I3Frame.DAQ)
        tray.AddModule(DAQCounter, "counter3", nevents=int(self.nevents))

        tray.AddSegment(segments.GenerateNeutrinos,
                        'generator',
                        RandomService=randomService,
                        NumEvents=self.nevents,
                        SimMode=self.simmode,
                        VTXGenMode=self.vtxgenmode,
                        InjectionMode=self.injectionmode,
                        CylinderParams=self.cylinderparams,
                        AutoExtendMuonVolume=self.autoextendmuonvolume,
                        Flavor=self.nuflavor,
                        GammaIndex=self.gamma,
                        FromEnergy=self.fromenergy,
                        ToEnergy=self.toenergy,
                        ZenithRange=[self.zenithmin, self.zenithmax],
                        AzimuthRange=[self.azimuthmin, self.azimuthmax],
                        CrossSections=self.crosssections,
                        CrossSectionsPath=self.crosssectionspath,
                        ParamsMap=self.paramsmap)

        if self.polyplopia:
            tray.AddSegment(
                segments.PolyplopiaSegment,
                "coincify",
                RandomService=randomService,
                mctype='NuGen',
                bgfile=self.backgroundfile,
                timewindow=40. * I3Units.microsecond,
                rate=5.0 * I3Units.kilohertz,
            )

        tray.AddSegment(segments.PropagateMuons,
                        'propagator',
                        RandomService=randomServiceForPropagators,
                        **self.proposalparams)

        tray.AddModule(
            BasicCounter,
            "count_g",
            Streams=[icetray.I3Frame.DAQ],
            name="Generated Events",
            Stats=stats,
        )

        if self.histogramfilename:
            from icecube.production_histograms import ProductionHistogramModule
            from icecube.production_histograms.histogram_modules.simulation.mctree_primary import I3MCTreePrimaryModule
            from icecube.production_histograms.histogram_modules.simulation.mctree import I3MCTreeModule

            tray.AddModule(ProductionHistogramModule,
                           Histograms=[I3MCTreePrimaryModule, I3MCTreeModule],
                           OutputFilename=self.histogramfilename)

        tray.AddModule(
            "I3Writer",
            "writer",
            filename=self.outputfile,
            streams=[icetray.I3Frame.DAQ],
        )

        tray.AddModule("TrashCan", "trashcan")

        # Execute the Tray
        tray.Execute()
        tray.Finish()

        tray.PrintUsage()
        for k in tray.Usage():
            stats[str(k.key()) + ":usr"] = k.data().usertime
            stats[str(k.key()) + ":sys"] = k.data().systime
            stats[str(k.key()) + ":ncall"] = k.data().systime

        # Free memory
        del tray
        return 0
outfile = options.OUTPUT

print("Command line options parsed...")

import os, sys

tray = I3Tray()

# import phys_services which includes rng
from icecube import phys_services

print("RNG being initiated...")
# set up a random number generator
randomService = phys_services.I3SPRNGRandomService(
    seed = options.SEED,
    nstreams = 100000000,
    streamnum = options.RUNNUMBER)
    
# and one for the propagators, that should be hit slightly less often
prandomService = phys_services.I3SPRNGRandomService(
    seed = options.SEED,
    nstreams = 200000000,
    streamnum = options.RUNNUMBER+100000000)

tray.context['I3RandomService'] = randomService

# 1. generate empty events
tray.AddModule("I3InfiniteSource","TheSource",
                   Prefix=options.GCDFILE,
                   Stream=icetray.I3Frame.DAQ) 
Beispiel #30
0
    value = (2. * math.pi /
             (137. * (wlen**2.))) * (1. - 1. /
                                     ((beta * getPhaseRefIndex(wlen))**2.))
    return numpy.where(value > 0., value, 0.)


def Cherenkov_dN_dXdE(energy, beta=1.):
    value = (2. * math.pi / (137. * h_times_c)) * (1. - 1. / (
        (beta * getPhaseRefIndex(h_times_c / energy))**2.))
    return numpy.where(value > 0., value, 0.)


from icecube import icetray, dataclasses, clsim, phys_services
from I3Tray import I3Units

rng = phys_services.I3SPRNGRandomService(seed=3244, nstreams=2, streamnum=0)

# get OpenCL CPU devices
openCLDevices = [
    device for device in clsim.I3CLSimOpenCLDevice.GetAllDevices()
    if device.cpu
]
if len(openCLDevices) == 0:
    raise RuntimeError("No CPU OpenCL devices available!")
openCLDevice = openCLDevices[0]

openCLDevice.useNativeMath = False
workgroupSize = 1
workItemsPerIteration = 10240
print("           using platform:", openCLDevice.platform)
print("             using device:", openCLDevice.device)