def book_weights(infiles, outfile, model='Hoerandel5_atmod12_SIBYLL'): tray = I3Tray() tray.AddModule('I3Reader', 'reader', filenamelist=infiles) tray.AddModule( lambda frame: frame.Put('MCPrimary', frame['I3MCTree'].primaries[0]), Streams=[icetray.I3Frame.DAQ]) tray.AddModule(lambda frame: frame.Put('Muon', frame['I3MCTree'][1]), Streams=[icetray.I3Frame.DAQ]) model = MuonGun.load_model(model) generator = harvest_generators(infiles) tray.AddModule('I3MuonGun::WeightCalculatorModule', 'MuonWeight', Model=model, Generator=generator) from icecube.hdfwriter import I3SimHDFWriter tray.AddSegment(I3SimHDFWriter, 'scribe', Output=outfile, Keys=[ 'MCPrimary', 'Muon', 'MuonWeight', dict(key='I3MCTree', name='BundleParameters', converter=MuonGun.converters.MuonBundleConverter( 1, generator.surface)) ], Types=[]) tray.Execute()
def get_fluxes_and_names(): """Get fluxes and names of all available models. Returns ------- list of MuonGun models, list of str List of MuonGun models List of model names """ table_path = os.path.expandvars('$I3_BUILD/MuonGun/resources/tables/*') table_files = glob(table_path) table_files = [os.path.basename(table_file) for table_file in table_files] flux_names = np.unique( [table_file.split('.')[0] for table_file in table_files]) fluxes = [] for flux_name in flux_names: fluxes.append(MuonGun.load_model(flux_name)) return fluxes, flux_names
def book_weights(infiles, outfile, model='Hoerandel5_atmod12_SIBYLL'): tray = I3Tray() tray.AddModule('I3Reader', 'reader', filenamelist=infiles) tray.AddModule('I3NullSplitter', 'nullsplit') tray.AddModule( lambda frame: frame.Put('MCPrimary', frame['I3MCTree'].primaries[0])) tray.AddModule( lambda frame: frame.Put('Muon', frame['I3MCTree'].most_energetic_muon)) model = MuonGun.load_model(model) generator = harvest_generators(infiles) tray.AddModule('I3MuonGun::WeightCalculatorModule', 'MuonWeight', Model=model, Generator=generator) from icecube.hdfwriter import I3HDFWriter tray.AddSegment( I3HDFWriter, 'scribe', Output=outfile, Keys=[ 'MCPrimary', 'Muon', 'MuonWeight', dict(key='I3MCTree', name='BundleParameters', converter=MuonGun.converters.MuonBundleConverter( 1, generator.surface)) ], Types=[], SubEventStreams=['nullsplit'], ) tray.AddModule('TrashCan', 'YesWeCan') tray.Execute() tray.Finish()
from icecube import dataclasses, MuonGun surface = MuonGun.Cylinder(1600, 800) area = numpy.pi**2 * surface.radius * (surface.radius + surface.length) # 1 file of E^-2.6 5-component 3e4-1e9 GeV (3:2:1:1:1) soft = 4e5 * MuonGun.corsika_genprob('CascadeOptimized5Comp') # 1 file of E^-2 5-component 6e2-1e11 GeV (10:5:3:2:1) hard = 2.5e6 * MuonGun.corsika_genprob('Standard5Comp') # In order to compare to "unweighted" CORSIKA, turn the Hoerandel flux # into a probability (since we happen to know the integral) areanorm = 0.131475115 * area # 1 file of natural-spectrum ("unweighted") CORSIKA unweighted = (2.5e7 / areanorm) * MuonGun.corsika_genprob('Hoerandel5') model = MuonGun.load_model('GaisserH4a_atmod12_SIBYLL') model.flux.min_multiplicity = 1 model.flux.max_multiplicity = 1 # spectrum = MuonGun.OffsetPowerLaw(5.0, 5e2, 8e2, 10**4.5) spectrum = MuonGun.OffsetPowerLaw(5, 8e2, 2e3, 1e5) # spectrum = MuonGun.OffsetPowerLaw(1.1, 650, 800, 1e8) gun = 1e5 * MuonGun.EnergyDependentSurfaceInjector(surface, model.flux, spectrum, model.radius) # gun = 1e5*MuonGun.StaticSurfaceInjector(surface, model.flux, spectrum, model.radius) # gun.target_surface = lambda e: surface def get_weight(weighter, energy, zenith=numpy.pi / 8, scale=True): shape = energy.shape
def cascade_l5_cuts_muongun(tray, name, infiles): from icecube import MuonGun if 'high' in infiles[1]: sframe_file = '/data/user/nwandkowsky/utils/sframes/muongun_highe_sframe.i3.bz2' elif 'med' in infiles[1]: sframe_file = '/data/user/nwandkowsky/utils/sframes/muongun_mede_sframe.i3.bz2' elif 'low' in infiles[1]: sframe_file = '/data/user/nwandkowsky/utils/sframes/muongun_lowe_sframe.i3.bz2' print( '\033[93mWarning: Inserting {} to infiles.\033[0m'.format(sframe_file)) print('\033[93m Make sure this is correct... \033[0m') infiles.insert(0, sframe_file) tray.Add('Rename', Keys=["I3MCTree_preMuonProp", "I3MCTree"]) def harvest_generators(sinfiles): from icecube.icetray.i3logging import log_info as log generator = None f = dataio.I3File(sinfiles[0]) while True: try: fr = f.pop_frame(icetray.I3Frame.Stream('S')) except RuntimeError as e: log('Caught the following exception:', str(e)) fr = None if fr is None: break for k in fr.keys(): v = fr[k] if isinstance(v, MuonGun.GenerationProbability): log('%s: found "%s" (%s)' % (sinfiles[0], k, type(v).__name__), unit="MuonGun") if generator is None: generator = v else: generator += v #print generator f.close() return generator generator = harvest_generators(infiles) def track_energy(frame): energy = [] energy.append(frame["SplineMPEMuEXDifferential"].energy + frame["MillipedeDepositedEnergy"].value) energy.append(frame["SplineMPEMuEXDifferential"].energy + frame["L5MonopodFit4"].energy) energy.append(frame["L5MonopodFit4"].energy + frame["MillipedeDepositedEnergy"].value) frame["TrackEnergy"] = dataclasses.I3Double(min(energy)) tray.Add(track_energy) def remove_background(frame): if frame["IsHese"].value == True: return True if frame["IsCascade_reco"].value == False and ( (numpy.cos(frame["SplineMPEMuEXDifferential"].dir.zenith) > 0.4 and frame["SplineMPEMuEXDifferential"].energy < 1e4) or numpy.cos(frame["SplineMPEMuEXDifferential"].dir.zenith) > 0.6 and frame["SplineMPEMuEXDifferential"].energy < 3e4): print("Likely a background event (spline)... removing...", frame["I3EventHeader"].run_id, frame["I3EventHeader"].event_id) return False if frame["IsCascade"].value == True and frame["TrackFit"].pos.z > 370.: print("Potentially coincident cascade removed...", frame["I3EventHeader"].run_id, frame["I3EventHeader"].event_id) return False tray.Add(remove_background) def printy(frame): del frame["MillipedeDepositedEnergy"] del frame["TrackEnergy"] if "MuonLosses" in frame: losses = frame["MuonLosses"] first_loss_found = False deposited_energy = 0 for i in range(0, len(losses)): if losses[i].pos.z < 500 and losses[ i].pos.z > -500 and math.sqrt( losses[i].pos.x * losses[i].pos.x + losses[i].pos.y * losses[i].pos.y) < 550: deposited_energy = deposited_energy + losses[i].energy else: deposited_energy = 0. frame["MillipedeDepositedEnergy"] = dataclasses.I3Double( deposited_energy) frame["TrackEnergy"] = dataclasses.I3Double(deposited_energy) if frame["IsHese"].value == False and frame[ "IsCascade_reco"].value == False and deposited_energy == 0.: return False if frame["IsCascade_reco"] == True and frame[ "L5MonopodFit4"].energy > 6e4: del frame["IsCascade_reco"] del frame["IsTrack_reco"] if frame["TrackLength"] > 550: frame["IsCascade_reco"] = icetray.I3Bool(False) frame["IsTrack_reco"] = icetray.I3Bool(True) else: frame["IsCascade_reco"] = icetray.I3Bool(True) frame["IsTrack_reco"] = icetray.I3Bool(False) if frame["IsCascade_reco"].value == False and frame[ "TrackEnergy"].value > 6e4: del frame["IsCascade_reco"] del frame["IsTrack_reco"] if frame["TrackLength"] > 550: frame["IsCascade_reco"] = icetray.I3Bool(False) frame["IsTrack_reco"] = icetray.I3Bool(True) else: frame["IsCascade_reco"] = icetray.I3Bool(True) frame["IsTrack_reco"] = icetray.I3Bool(False) if frame["IsCascade_reco"].value == True and abs( frame["L5MonopodFit4"].pos.z) > 550.: return False if frame["IsHese"].value == True and frame[ "IsHESE_ck"].value == False and frame[ "CascadeFilter"].value == False: #and frame["L4VetoLayer1"].value<10: del frame["IsHese"] frame["IsHese"] = icetray.I3Bool(False) if frame["IsCascade"].value == True and frame[ "IsCascade_reco"].value == True and ( frame["L5MonopodFit4"].pos.z < -500 or frame["L5MonopodFit4"].pos.z > 500 or numpy.sqrt(frame["L5MonopodFit4"].pos.x * frame["L5MonopodFit4"].pos.x + frame["L5MonopodFit4"].pos.y * frame["L5MonopodFit4"].pos.y) > 550): print("Cascade event outside of detector... ", frame["I3EventHeader"].run_id, frame["I3EventHeader"].event_id) del frame["IsCascade"] frame["IsCascade"] = icetray.I3Bool(False) if frame["IsCascade"].value == True and frame[ "IsCascade_reco"].value == False and ( frame["L4VetoTrackMilliOfflineVetoCharge"].value > 2 or frame['L4VetoTrackMarginMilliOfflineSide'].value < 125): del frame["IsCascade"] frame["IsCascade"] = icetray.I3Bool(False) if frame["IsUpgoingMuon"].value == True: #print "UpMu event: ", frame["I3EventHeader"].run_id, frame["I3EventHeader"].event_id return True elif frame["IsHese"].value == True: print("HESE event: ", frame["I3EventHeader"].run_id, frame["I3EventHeader"].event_id) return True elif frame["IsCascade"].value == True and frame[ "L4VetoTrackOfflineVetoCharge"].value < 6 and frame[ "L4VetoTrackL5OfflineVetoCharge"].value < 2: #print "Cascade event: ", frame["I3EventHeader"].run_id, frame["I3EventHeader"].event_id return True elif frame["IsCascade"].value == True and frame[ "L4VetoTrackOfflineVetoCharge"].value < 2 and frame[ "L4VetoTrackL5OfflineVetoCharge"].value < 3: #print "Cascade event: ", frame["I3EventHeader"].run_id, frame["I3EventHeader"].event_id return True else: if ( ( frame['L4UpgoingTrackOfflineVetoCharge'].value > 10 and frame['L4UpgoingTrackOfflineVetoCharge'].value > \ frame['L4VetoTrackOfflineVetoCharge'].value and frame['L4UpgoingTrackOfflineVetoChannels'].value > 3 ) or \ ( frame['L4UpgoingTrackSplitVetoCharge'].value > 10 and frame['L4UpgoingTrackSplitVetoCharge'].value > \ frame['L4VetoTrackSplitVetoCharge'].value and frame['L4UpgoingTrackSplitVetoChannels'].value > 3 ) or \ ( frame['L4UpgoingTrackMilliOfflineVetoCharge'].value > 10 and frame['L4UpgoingTrackMilliOfflineVetoCharge'].value > \ frame['L4VetoTrackMilliOfflineVetoCharge'].value and frame['L4UpgoingTrackMilliOfflineVetoChannels'].value > 3 and \ frame['L4UpgoingTrackSplitVetoCharge'].value > 6 ) )\ and frame["TrackFit"].dir.zenith>1.5 and frame["MuonFilter"].value==True:# and frame["OnlineL2Filter"].value==True: del frame["IsUpgoingMuon"] del frame["IsCascade"] frame["IsUpgoingMuon"] = icetray.I3Bool(True) frame["IsCascade"] = icetray.I3Bool(False) #print "UpMu event!", frame["I3EventHeader"].run_id, frame["I3EventHeader"].event_id return True else: return False tray.Add(printy, streams=[icetray.I3Frame.Physics]) def bug_filter(frame): #if frame["I3EventHeader"].run_id==16 and frame["I3EventHeader"].event_id==17967: # return False #if frame["I3EventHeader"].run_id==16780 and frame["I3EventHeader"].event_id==34774: # return False print(frame["I3EventHeader"].run_id, frame["I3EventHeader"].event_id) tray.Add(bug_filter, streams=[icetray.I3Frame.DAQ, icetray.I3Frame.Physics]) tray.AddModule('I3MuonGun::WeightCalculatorModule', 'MuonWeight_Hoerandel5', Model=MuonGun.load_model('Hoerandel5_atmod12_SIBYLL'), Generator=generator) tray.AddModule('I3MuonGun::WeightCalculatorModule', 'MuonWeight_GaisserH4a', Model=MuonGun.load_model('GaisserH4a_atmod12_SIBYLL'), Generator=generator)
args = parser.parse_args() from icecube import icetray, dataclasses, dataio from icecube import phys_services, simclasses, MuonGun from I3Tray import I3Tray from os.path import expandvars tray = I3Tray() tray.context['I3RandomService'] = phys_services.I3GSLRandomService(1337) from icecube.MuonGun.segments import GenerateBundles outer = MuonGun.Cylinder(1600, 800) inner = MuonGun.Cylinder(300, 150, dataclasses.I3Position(0, 0, -350)) spectrum = MuonGun.OffsetPowerLaw(5, 1e3, 1e1, 1e4) model = MuonGun.load_model('GaisserH4a_atmod12_SIBYLL') generator = MuonGun.EnergyDependentSurfaceInjector( outer, model.flux, spectrum, model.radius, MuonGun.ConstantSurfaceScalingFunction(inner)) tray.AddSegment( GenerateBundles, 'BundleGen', NEvents=1000, Generator=generator, GCDFile=expandvars( '$I3_TESTDATA/GCD/GeoCalibDetectorStatus_IC86.55697_corrected_V2.i3.gz' )) class Harvest(icetray.I3ConditionalModule): def __init__(self, context):
#inner = MuonGun.Cylinder(700, 125, dataclasses.I3Position(29.3,52.6,-150)) #inner = outer #Most tested spectrum #spectrum = MuonGun.OffsetPowerLaw(5.0, 7e2, 0, 1e5) spectrum = MuonGun.OffsetPowerLaw(5.0, 7e2, 500, 1e5) #Limited spectrum range #spectrum = MuonGun.OffsetPowerLaw(5.2, 7e2, 150, 1e4) #spectrum = MuonGun.OffsetPowerLaw(2, 1*I3Units.TeV, 1*I3Units.TeV, 1*I3Units.PeV) #Good spectrum producing ~1 day with 10k evts above 200 GeV #spectrum = MuonGun.OffsetPowerLaw(5.2, 7e2, 200, 1e6) #Jackob's spectrum #spectrum = MuonGun.OffsetPowerLaw(5.0, 5e2, 200, 1e6) #Good spectrum producing ~1 day with 5000 evts above 400 GeV #spectrum = MuonGun.OffsetPowerLaw(5.25, 1000, 1, 1e6) model = MuonGun.load_model('/home/mamday/icesim/build/MuonGun/resources/tables/GaisserH4a_atmod12_SIBYLL') #gun = .365e4*MuonGun.EnergyDependentSurfaceInjector(outer, model.flux, spectrum, model.radius, gun = 5000*MuonGun.EnergyDependentSurfaceInjector(outer, model.flux, spectrum, model.radius, #gun = 680*MuonGun.EnergyDependentSurfaceInjector(outer, model.flux, spectrum, model.radius, MuonGun.ConstantSurfaceScalingFunction(inner)) def get_weight(weighter, energy, zenith=numpy.pi/8, scale=True): # def get_weight(weighter, energy, zenith=0, z=0): shape = energy.shape if scale: x = numpy.array([gun.target_surface(e).radius - 1 for e in energy]) else: # x = numpy.ones(shape[0])*surface.radius - 1 x = numpy.ones(shape[0])*surface.radius - 1
#inner = outer #Most tested spectrum #spectrum = MuonGun.OffsetPowerLaw(5.0, 7e2, 0, 1e5) spectrum = MuonGun.OffsetPowerLaw(5.0, 7e2, 500, 1e5) #Limited spectrum range #spectrum = MuonGun.OffsetPowerLaw(5.2, 7e2, 150, 1e4) #spectrum = MuonGun.OffsetPowerLaw(2, 1*I3Units.TeV, 1*I3Units.TeV, 1*I3Units.PeV) #Good spectrum producing ~1 day with 10k evts above 200 GeV #spectrum = MuonGun.OffsetPowerLaw(5.2, 7e2, 200, 1e6) #Jackob's spectrum #spectrum = MuonGun.OffsetPowerLaw(5.0, 5e2, 200, 1e6) #Good spectrum producing ~1 day with 5000 evts above 400 GeV #spectrum = MuonGun.OffsetPowerLaw(5.25, 1000, 1, 1e6) model = MuonGun.load_model( '/home/mamday/icesim/build/MuonGun/resources/tables/GaisserH4a_atmod12_SIBYLL' ) #gun = .365e4*MuonGun.EnergyDependentSurfaceInjector(outer, model.flux, spectrum, model.radius, gun = 5000 * MuonGun.EnergyDependentSurfaceInjector( outer, model.flux, spectrum, model.radius, #gun = 680*MuonGun.EnergyDependentSurfaceInjector(outer, model.flux, spectrum, model.radius, MuonGun.ConstantSurfaceScalingFunction(inner)) def get_weight(weighter, energy, zenith=numpy.pi / 8, scale=True): # def get_weight(weighter, energy, zenith=0, z=0):
print 'Usage: %prog [options] output.i3 input1.i3 [input2.i3] ...' sys.exit(1) tray = I3Tray() tray.AddModule('I3Reader', 'reader', FilenameList=filenamelist) #Add muon weight that I guess I should have added before from icecube import MuonGun, sim_services from icecube.icetray import I3Units from icecube.dataclasses import * from icecube.sim_services.propagation import get_propagators from icecube.MuonGun.segments import GenerateBundles from icecube.MuonGun import load_model, EnergyDependentSurfaceInjector, ConstantSurfaceScalingFunction, StaticSurfaceInjector, Cylinder, OffsetPowerLaw #Flux model model = MuonGun.load_model('GaisserH4a_atmod12_SIBYLL') model.flux.min_multiplicity = 1 model.flux.max_multiplicity = 1 #Inner and outher target surfaces outSurface = Cylinder(1600*I3Units.m, 800*I3Units.m) inSurface = Cylinder(700*I3Units.m, 125*I3Units.m, I3Position(29.3,52.6,-150)) #Sets energy and spectral index of muons spectrum = MuonGun.OffsetPowerLaw(5.2, 7e2, 200, 1e6) #This version only aims at inSurface, but muons originate at outSurface scaling = MuonGun.ConstantSurfaceScalingFunction(inSurface) generator = MuonGun.EnergyDependentSurfaceInjector(outSurface, model.flux, spectrum, model.radius, scaling,0,1) tray.AddModule('I3MuonGun::WeightCalculatorModule', 'MuonWeight', Model=model, Generator=generator, )
for k,v in sorted(vars(args).items()): print( " {0}: {1}".format(k,v)) print "------ end ------ " ######################### # I3 ######################### tray = I3Tray() ######################### # FLUX ######################### # Flux model model = MuonGun.load_model('GaisserH4a_atmod12_SIBYLL') #TODO Do we need a new fit to the latest CORSIKA (including SYBYLL 2.3c)??? model.flux.min_multiplicity = 1 model.flux.max_multiplicity = 1 # Check the spectral index is negative # This is for consistency with CORSIKA scripts # Will convert to a positve number (as MuonGun expects it) later assert args.power_law_index <= 0., "Spectral index must be negative" power_law_index = args.power_law_index positive_power_law_index = -1. * power_law_index # Muon spectrum (spectral index, break in power law, and energy range) power_law_offset = args.power_law_offset * icecube.icetray.I3Units.GeV min_energy = args.min_energy * icecube.icetray.I3Units.GeV max_energy = args.max_energy * icecube.icetray.I3Units.GeV spectrum = MuonGun.OffsetPowerLaw(
print DOM_file f = dataio.I3File(DOM_file) n_events = 0 for frame in f: if ("I3RecoPulseSeriesMapGen2" not in frame): continue if (n_events % 100 == 0): print "runing event: %s" % str(n_events) n_events += 1 #propagate muons to surface, if they dont intersect, throw the event away entering_muon_bool = todet(frame, surface_det) if not entering_muon_bool: continue #should we include this cut if len(frame["I3RecoPulseSeriesMapGen2"]) < 1: continue #sometimes no charge is even recorded #first store the event level info like weights energy zeniths etc... model = MuonGun.load_model('GaisserH4a_atmod12_SIBYLL') #natural rate muon = frame["MCMuon"] flux = model.flux(MuonGun.depth(muon.pos.z), np.cos( muon.dir.zenith), 1) * model.energy(MuonGun.depth( muon.pos.z), np.cos(muon.dir.zenith), 1, 0, muon.energy) weight = flux * frame['MuonEffectiveArea'].value energy = frame["EnteringMuon_0"].energy cos_zenith = np.cos(frame["EnteringMuon_0"].dir.zenith) area_eff = frame["MuonEffectiveArea"].value #now work on the triggers passes_cut = 0 times = [] ndom = 0 string_dom = "" spes_times = [] spes = []
def PolyplopiaSegment( tray, name, mctype='CORSIKA', RandomService=None, mctree_name="I3MCTree_preMuonProp", separate_coincident_mctree_name="", # leave empty to combine bgfile=None, timewindow=40. * I3Units.microsecond, rate=float('nan'), If=lambda f: True): """ There are three scenarios for polyplopia: 1. bgfile: We are reading background MC from a separate file and injecting events to signal (or weighted background) based on a Poisson distribution within the given time window. 2. we are generating MuonGun bundles and injecting events to signal (or weighted background) based on a Poisson distribution within the given time window. """ from icecube import polyplopia, MuonGun #tray.AddModule("ParticleMapper","mapprimary") if bgfile: # merge bg into signal background = polyplopia.CoincidentI3ReaderService(bgfile) else: # Use MuonGun # Default: use Hoerandel as a template for generating muons. model = MuonGun.load_model("Hoerandel5_atmod12_SIBYLL") #model = MuonGun.load_model('GaisserH4a_atmod12_SIBYLL') # Generate bundles (even if not 100 percent accurate). model.flux.max_multiplicity = 100 gamma_index = 2.6 energy_offset = 700. energy_min = 1e4 energy_max = 1e7 cylinder_length = 1600. cylinder_radius = 800. cylinder_x = 0. cylinder_y = 0. cylinder_z = 0. # Default: cylinder aligned with z-axis at detector center as injection # surface. outsurface_center = dataclasses.I3Position(cylinder_x * I3Units.m, cylinder_y * I3Units.m, cylinder_z * I3Units.m) outsurface = MuonGun.Cylinder(length=cylinder_length * I3Units.m, radius=cylinder_radius * I3Units.m, center=outsurface_center) generator = MuonGun.NaturalRateInjector(outsurface, model.flux, model.energy) background = polyplopia.MuonGunBackgroundService() background.set_generator(generator) background.set_rng(RandomService) background.set_rate(rate) background.set_mctree_name(mctree_name) tray.AddModule("PoissonMerger", "merge", CoincidentEventService=background, PrimaryType=mctype, MCTreeName=mctree_name, Rate=rate, SeparateMCTree=separate_coincident_mctree_name, TimeWindow=timewindow) return tray
def main(cfg, run_number, scratch): with open(cfg, 'r') as stream: if int(yaml.__version__[0]) < 5: # backwards compatibility for yaml versions before version 5 cfg = yaml.load(stream) else: cfg = yaml.full_load(stream) cfg['run_number'] = run_number cfg['run_folder'] = get_run_folder(run_number) tray = I3Tray() random_services, _ = create_random_services( dataset_number=cfg['dataset_number'], run_number=cfg['run_number'], seed=cfg['seed'], n_services=2) random_service, random_service_prop = random_services tray.context['I3RandomService'] = random_service model = MuonGun.load_model(cfg['muongun_model']) model.flux.min_multiplicity = cfg['muongun_min_multiplicity'] model.flux.max_multiplicity = cfg['muongun_max_multiplicity'] spectrum = MuonGun.OffsetPowerLaw(cfg['gamma'], cfg['e_min'] * icetray.I3Units.GeV, cfg['e_min'] * icetray.I3Units.GeV, cfg['e_max'] * icetray.I3Units.GeV) surface = MuonGun.Cylinder(1600, 800, dataclasses.I3Position(31.25, 19.64, 0)) if cfg['muongun_generator'] == 'energy': scale = MuonGun.BasicSurfaceScalingFunction() scale.SetSideScaling(4., 17266, 3.41, 1.74) scale.SetCapScaling(4., 23710, 3.40, 1.88) generator = MuonGun.EnergyDependentSurfaceInjector( surface, model.flux, spectrum, model.radius, scale) elif cfg['muongun_generator'] == 'static': generator = MuonGun.StaticSurfaceInjector(surface, model.flux, spectrum, model.radius) elif cfg['muongun_generator'] == 'floodlight': generator = MuonGun.Floodlight( surface=surface, energyGenerator=spectrum, cosMin=cfg['muongun_floodlight_min_cos'], cosMax=cfg['muongun_floodlight_max_cos'], ) else: err_msg = 'MuonGun generator {} is not known.' err_msg += " Must be 'energy','static' or 'floodlight" raise ValueError(err_msg.format(cfg['muongun_generator'])) tray.Add(MuonGun.segments.GenerateBundles, 'MuonGenerator', Generator=generator, NEvents=cfg['n_events_per_run'], GCDFile=cfg['gcd']) tray.Add("Rename", keys=["I3MCTree", "I3MCTree_preMuonProp"]) tray.AddSegment(segments.PropagateMuons, "PropagateMuons", RandomService=random_service_prop, **cfg['muon_propagation_config']) if scratch: outfile = cfg['scratchfile_pattern'].format(**cfg) else: outfile = cfg['outfile_pattern'].format(**cfg) outfile = outfile.replace(' ', '0') if cfg['distance_splits'] is not None: click.echo('SplittingDistance: {}'.format(cfg['distance_splits'])) distance_splits = np.atleast_1d(cfg['distance_splits']) dom_limits = np.atleast_1d(cfg['threshold_doms']) if len(dom_limits) == 1: dom_limits = np.ones_like(distance_splits) * cfg['threshold_doms'] oversize_factors = np.atleast_1d(cfg['oversize_factors']) order = np.argsort(distance_splits) distance_splits = distance_splits[order] dom_limits = dom_limits[order] oversize_factors = oversize_factors[order] stream_objects = generate_stream_object(distance_splits, dom_limits, oversize_factors) tray.AddModule(OversizeSplitterNSplits, "OversizeSplitterNSplits", thresholds=distance_splits, thresholds_doms=dom_limits, oversize_factors=oversize_factors) for stream_i in stream_objects: outfile_i = stream_i.transform_filepath(outfile) tray.AddModule("I3Writer", "writer_{}".format(stream_i.stream_name), Filename=outfile_i, Streams=[ icetray.I3Frame.DAQ, icetray.I3Frame.Physics, icetray.I3Frame.Stream('S'), icetray.I3Frame.Stream('M') ], If=stream_i) click.echo('Output ({}): {}'.format(stream_i.stream_name, outfile_i)) else: click.echo('Output: {}'.format(outfile)) tray.AddModule("I3Writer", "writer", Filename=outfile, Streams=[ icetray.I3Frame.DAQ, icetray.I3Frame.Physics, icetray.I3Frame.Stream('S'), icetray.I3Frame.Stream('M') ]) click.echo('Scratch: {}'.format(scratch)) tray.AddModule("TrashCan", "the can") tray.Execute() tray.Finish()
def main(cfg, run_number, scratch): with open(cfg, 'r') as stream: cfg = yaml.load(stream) cfg['run_number'] = run_number cfg['run_folder'] = get_run_folder(run_number) tray = I3Tray() random_service, random_service_prop, _ = create_random_services( dataset_number=cfg['dataset_number'], run_number=cfg['run_number'], seed=cfg['seed']) tray.context['I3RandomService'] = random_service model = MuonGun.load_model(cfg['muongun_model']) model.flux.min_multiplicity = cfg['muongun_min_multiplicity'] model.flux.max_multiplicity = cfg['muongun_max_multiplicity'] spectrum = MuonGun.OffsetPowerLaw( cfg['gamma'], cfg['e_min']*icetray.I3Units.TeV, cfg['e_min']*icetray.I3Units.TeV, cfg['e_max']*icetray.I3Units.TeV) surface = MuonGun.Cylinder(1600, 800, dataclasses.I3Position(31.25, 19.64, 0)) if cfg['muongun_generator'] == 'energy': scale = MuonGun.BasicSurfaceScalingFunction() scale.SetSideScaling(4., 17266, 3.41, 1.74) scale.SetCapScaling(4., 23710, 3.40, 1.88) generator = MuonGun.EnergyDependentSurfaceInjector(surface, model.flux, spectrum, model.radius, scale) elif cfg['muongun_generator'] == 'static': generator = MuonGun.StaticSurfaceInjector(surface, model.flux, spectrum, model.radius) elif cfg['muongun_generator'] =='floodlight': generator = MuonGun.Floodlight(surface = surface, energyGenerator=spectrum, cosMin=cfg['muongun_floodlight_min_cos'], cosMax=cfg['muongun_floodlight_max_cos'], ) else: err_msg = 'MuonGun generator {} is not known.' err_msg += " Must be 'energy','static' or 'floodlight" raise ValueError(err_msg.format(cfg['muongun_generator'])) tray.Add(MuonGun.segments.GenerateBundles, 'MuonGenerator', Generator=generator, NEvents=cfg['n_events_per_run'], GCDFile=cfg['gcd']) tray.Add("Rename", keys=["I3MCTree", "I3MCTree_preMuonProp"]) tray.AddSegment( segments.PropagateMuons, "PropagateMuons", RandomService=random_service_prop) if scratch: outfile = cfg['scratchfile_pattern'].format(**cfg) else: outfile = cfg['outfile_pattern'].format(**cfg) outfile = outfile.replace(' ', '0') outfile = outfile.replace('.bz2', '') tray.AddModule("I3Writer", "writer", Filename=outfile, Streams=[icetray.I3Frame.DAQ, icetray.I3Frame.Physics, icetray.I3Frame.Stream('S'), icetray.I3Frame.Stream('M')]) tray.AddModule("TrashCan", "the can") tray.Execute() tray.Finish()
def main(cfg, run_number, scratch): with open(cfg, 'r') as stream: cfg = yaml.load(stream, Loader=yaml.Loader) cfg['run_number'] = run_number cfg['run_folder'] = get_run_folder(run_number) if scratch: outfile = cfg['scratchfile_pattern'].format(**cfg) else: outfile = cfg['outfile_pattern'].format(**cfg) outfile = outfile.replace(' ', '0') if cfg['distance_splits'] is not None: click.echo('SplittingDistances: {}'.format(cfg['distance_splits'])) click.echo('Oversizefactors: {}'.format(cfg['oversize_factors'])) click.echo('NEvents: {}'.format(cfg['n_events_per_run'])) click.echo('EMin: {}'.format(cfg['e_min'])) click.echo('EMax: {}'.format(cfg['e_max'])) click.echo('EBreak: {}'.format(cfg['muongun_e_break'])) click.echo('Gamma: {}'.format(cfg['gamma'])) click.echo('ZenithMin: {}'.format(cfg['zenith_min'])) click.echo('ZenithMax: {}'.format(cfg['zenith_max'])) # create convex hull if 'use_convex_hull' in cfg and cfg['use_convex_hull']: # hardcode icecube corner points # ToDo: read from geometry file points = [ [-570.90002441, -125.13999939, 501], # string 31 [-256.14001465, -521.08001709, 501], # string 1 [361., -422.82998657, 501], # string 6 [576.36999512, 170.91999817, 501], # string 50 [338.44000244, 463.72000122, 501], # string 74 [101.04000092, 412.79000854, 501], # string 72 [22.11000061, 509.5, 501], # string 78 [-347.88000488, 451.51998901, 501], # string 75 [-570.90002441, -125.13999939, -502], # string 31 [-256.14001465, -521.08001709, -502], # string 1 [361., -422.82998657, -502], # string 6 [576.36999512, 170.91999817, -502], # string 50 [338.44000244, 463.72000122, -502], # string 74 [101.04000092, 412.79000854, -502], # string 72 [22.11000061, 509.5, -502], # string 78 [-347.88000488, 451.51998901, -502], # string 75 ] convex_hull = ConvexHull(points) else: convex_hull = None if 'extend_past_hull' not in cfg: cfg['extend_past_hull'] = 0.0 random_services, _ = create_random_services( dataset_number=cfg['dataset_number'], run_number=cfg['run_number'], seed=cfg['seed'], n_services=2) random_service, random_service_prop = random_services # create muon muon = create_muon( azimuth_range=[cfg['azimuth_min'], cfg['azimuth_max']], zenith_range=[cfg['zenith_min'], cfg['zenith_max']], energy_range=[cfg['e_min'], cfg['e_max']], anchor_time_range=cfg['anchor_time_range'], anchor_x_range=cfg['anchor_x_range'], anchor_y_range=cfg['anchor_y_range'], anchor_z_range=cfg['anchor_z_range'], length_to_go_back=cfg['length_to_go_back'], convex_hull=convex_hull, extend_past_hull=cfg['extend_past_hull'], random_service=random_services[0], ) tray = I3Tray() tray.context['I3RandomService'] = random_service tray.AddModule("I3InfiniteSource", "TheSource", Prefix=cfg['gcd'], Stream=icetray.I3Frame.DAQ) if cfg['MuonGenerator'] == 'MuonGunSinglemuons': tray.AddSegment(segments.GenerateSingleMuons, "GenerateCosmicRayMuons", NumEvents=cfg['n_events_per_run'], FromEnergy=cfg['e_min'] * icetray.I3Units.GeV, ToEnergy=cfg['e_max'] * icetray.I3Units.GeV, BreakEnergy=cfg['muongun_e_break'] * icetray.I3Units.GeV, GammaIndex=cfg['gamma'], ZenithRange=[ cfg['zenith_min'] * icetray.I3Units.deg, cfg['zenith_max'] * icetray.I3Units.deg ]) elif cfg['MuonGenerator'] == 'MuonGunGeneral': model = MuonGun.load_model(cfg['muongun_model']) model.flux.min_multiplicity = cfg['muongun_min_multiplicity'] model.flux.max_multiplicity = cfg['muongun_max_multiplicity'] spectrum = MuonGun.OffsetPowerLaw(cfg['gamma'], cfg['e_min'] * icetray.I3Units.GeV, cfg['e_min'] * icetray.I3Units.GeV, cfg['e_max'] * icetray.I3Units.GeV) surface = MuonGun.Cylinder(1600, 800, dataclasses.I3Position(31.25, 19.64, 0)) if cfg['muongun_generator'] == 'energy': scale = MuonGun.BasicSurfaceScalingFunction() scale.SetSideScaling(4., 17266, 3.41, 1.74) scale.SetCapScaling(4., 23710, 3.40, 1.88) generator = MuonGun.EnergyDependentSurfaceInjector( surface, model.flux, spectrum, model.radius, scale) elif cfg['muongun_generator'] == 'static': generator = MuonGun.StaticSurfaceInjector(surface, model.flux, spectrum, model.radius) elif cfg['muongun_generator'] == 'floodlight': generator = MuonGun.Floodlight( surface=surface, energyGenerator=spectrum, cosMin=cfg['muongun_floodlight_min_cos'], cosMax=cfg['muongun_floodlight_max_cos'], ) else: err_msg = 'MuonGun generator {} is not known.' err_msg += " Must be 'energy','static' or 'floodlight" raise ValueError(err_msg.format(cfg['muongun_generator'])) tray.Add(MuonGun.segments.GenerateBundles, 'MuonGenerator', Generator=generator, NEvents=cfg['n_events_per_run'], GCDFile=cfg['gcd']) tray.Add("Rename", keys=["I3MCTree", "I3MCTree_preMuonProp"]) elif cfg['MuonGenerator'] == 'MuonResimulation': tray.AddModule(ParticleMultiplier, 'make_particles', num_events=cfg['n_events_per_run'], primary=muon) else: err_msg = 'MuonGenerator {} is not known.' err_msg += " Must be 'MuonGunSinglemuons','MuonGunGeneral' or 'MuonResimulation" raise ValueError(err_msg.format(cfg['MuonGenerator'])) # -------------------------------------- # Propagate Muons # -------------------------------------- tray.AddSegment(segments.PropagateMuons, "PropagateMuons", RandomService=random_service_prop, **cfg['muon_propagation_config']) # -------------------------------------- # Distance Splits # -------------------------------------- if cfg['distance_splits'] is not None: click.echo('SplittingDistance: {}'.format(cfg['distance_splits'])) distance_splits = np.atleast_1d(cfg['distance_splits']) dom_limits = np.atleast_1d(cfg['threshold_doms']) if len(dom_limits) == 1: dom_limits = np.ones_like(distance_splits) * cfg['threshold_doms'] oversize_factors = np.atleast_1d(cfg['oversize_factors']) order = np.argsort(distance_splits) distance_splits = distance_splits[order] dom_limits = dom_limits[order] oversize_factors = oversize_factors[order] stream_objects = generate_stream_object(distance_splits, dom_limits, oversize_factors) tray.AddModule(OversizeSplitterNSplits, "OversizeSplitterNSplits", thresholds=distance_splits, thresholds_doms=dom_limits, oversize_factors=oversize_factors) for stream_i in stream_objects: outfile_i = stream_i.transform_filepath(outfile) tray.AddModule("I3Writer", "writer_{}".format(stream_i.stream_name), Filename=outfile_i, Streams=[ icetray.I3Frame.DAQ, icetray.I3Frame.Physics, icetray.I3Frame.Stream('S'), icetray.I3Frame.Stream('M') ], If=stream_i) click.echo('Output ({}): {}'.format(stream_i.stream_name, outfile_i)) else: click.echo('Output: {}'.format(outfile)) tray.AddModule("I3Writer", "writer", Filename=outfile, Streams=[ icetray.I3Frame.DAQ, icetray.I3Frame.Physics, icetray.I3Frame.Stream('S'), icetray.I3Frame.Stream('M') ]) click.echo('Scratch: {}'.format(scratch)) tray.Execute() del tray