def testTypes(self): #try to access all keys of the params if self.frame.Has("n_Wframes"): if self.frame["n_Wframes"].value == 1: DeliveredWeight = self.frame[self.DeliveredWeightName] self.assert_( isinstance(DeliveredWeight, dataclasses.I3MapStringDouble) and DeliveredWeight != dataclasses.I3MapStringDouble(), "NeutrinoOscParams and not the default constructor") self.assert_( set([ "nu_weight", "lowe_weight", "lep_weight", "e_weight", "mu_weight", "tau_weight", "nc_weight", "had_weight" ]).issubset(list(DeliveredWeight.keys())), "All keys in DeliveredWeigh are accessable") TotalWeight = self.frame[self.TotalWeightName] self.assert_( isinstance(TotalWeight, dataclasses.I3MapStringDouble) and TotalWeight != dataclasses.I3MapStringDouble(), "NeutrinoOscParams and not the default constructor") self.assert_( set([ "nu_weight", "lowe_weight", "lep_weight", "e_weight", "mu_weight", "tau_weight", "nc_weight", "had_weight" ]).issubset(list(TotalWeight.keys())), "All keys in DeliveredWeigh are accessable")
def testTypes(self): #try to access all keys of the params if self.frame.Has("n_Wframes"): if self.frame["n_Wframes"].value == 0: NeutrinoOscParams = self.frame[self.NeutrinoOscParamsName] self.assert_( isinstance(NeutrinoOscParams, dataclasses.I3MapStringDouble) and NeutrinoOscParams != dataclasses.I3MapStringDouble(), "NeutrinoOscParamsexists and not the default constructor") self.assert_( set([ "theta_12", "theta_13", "theta_23", "delta", "delta_m^2_21", "delta_m^2_31" ]).issubset(list(NeutrinoOscParams.keys())), "All keys in NeutrinoOscParams are accessable") WimpSimParams = self.frame[self.WimpSimParamsName] self.assert_( isinstance(WimpSimParams, dataclasses.I3MapStringDouble) and WimpSimParams != dataclasses.I3MapStringDouble(), "WimpSimParams exists and not the default constructor") self.assert_( set([ "WIMP_mass", "Annihilation_Channel", "Number_of_Annihilations", "Source", "Detector_Longitude", "Detector_Latitude", "mjd1", "mjd2" ]).issubset(list(WimpSimParams.keys())), "All keys in WimpSimParams are accessable") WimpSimReaderParams = self.frame[self.WimpSimReaderParamsName] self.assert_( isinstance(WimpSimReaderParams, dataclasses.I3MapStringDouble) and WimpSimReaderParams != dataclasses.I3MapStringDouble(), "WimpSimReaderParams exists and not the default constructor" ) self.assert_( set([ "NEvents", "PositionLimitsXmin", "PositionLimitsXmax", "PositionLimitsYmin", "PositionLimitsYmax", "PositionLimitsZmin", "PositionLimitsZmax", "InjectionRadius", "LowZenCut", "UpperZenCut", "UseElectrons", "UseMuons", "UseTaus", "UseNC", "Oversampling", "SensitiveHeight", "SensitiveRadius" ]).issubset(list(WimpSimReaderParams.keys())), "All keys in WimpSimReaderParams are accessable") File = self.frame[self.FileName] self.assert_( isinstance(File, dataclasses.I3String) and File != dataclasses.I3String(), "File exists and is the not the default constructor") Source = self.frame[self.SourceName] self.assert_( isinstance(Source, dataclasses.I3String) and Source != dataclasses.I3String(), "Source exists and is not the default constructor")
def Process(self): # get next frame frame = self.PopFrame() if not self._frame_has_been_pushed: # create settings frame and push it settings_frame = icetray.I3Frame('m') # add meta data on ranges settings_data = {} for key, value_range in self.proposal_storm.uniform_ranges.items(): settings_data[key+'RangeMin'] = value_range[0] settings_data[key+'RangeMax'] = value_range[1] # write to frame settings_frame[self._output_key+'UniformRanges'] = ( dataclasses.I3MapStringDouble(settings_data) ) settings_frame[self._output_key] = dataclasses.I3MapStringDouble( self.proposal_storm.sampled_settings) self.PushFrame(settings_frame) self._frame_has_been_pushed = True self.PushFrame(frame)
def get_prop_dict(props, ranged): """ This function takes the list/tuple of a an event's properties. It converts it into an I3MapstringDouble (basically a dictionary) """ pdict = {} pdict['totalEnergy'] = props[0]*I3Units.GeV pdict['zenith'] = props[1]*I3Units.rad pdict['azimuth'] = props[2]*I3Units.rad pdict['finalStateX'] = props[3] pdict['finalStateY'] = props[4] pdict['finalType1'] = props[5] pdict['finalType2'] = props[6] pdict['initialType'] = props[7] if ranged: pdict['impactParameters']=props[8] pdict['totalColumnDepth']=props[9] else: pdict['radius'] = props[8] pdict['z'] = props[9] pdict['totalColumnDepth']=props[10] for key in pdict: pdict[key] = float(pdict[key]) return(dataclasses.I3MapStringDouble(pdict))
def Physics(self, frame): labels = hl.get_muon_bundle_information(frame=frame, convex_hull=self._convex_hull) labels['num_coincident_events'] = \ general.get_num_coincident_events(frame) primary = frame[self._primary_key] labels['PrimaryEnergy'] = primary.energy labels['PrimaryAzimuth'] = primary.dir.azimuth labels['PrimaryZenith'] = primary.dir.zenith labels['PrimaryDirectionX'] = primary.dir.x labels['PrimaryDirectionY'] = primary.dir.y labels['PrimaryDirectionZ'] = primary.dir.z label_names = [ 'num_coincident_events', 'num_muons', 'num_muons_at_cyl', 'num_muons_at_cyl_above_threshold', 'num_muons_at_entry', 'num_muons_at_entry_above_threshold' ] pid_names = [ 'p_is_coincident_event', 'p_is_muon_bundle', 'p_is_muon_bundle_at_cyl', 'p_is_muon_bundle_at_cyl_above_threshold', 'p_is_muon_bundle_at_entry', 'p_is_muon_bundle_at_entry_above_threshold' ] for label, p_name in zip(label_names, pid_names): labels[p_name] = labels[label] > 1 # write to frame frame.Put(self._output_key, dataclasses.I3MapStringDouble(labels)) self.PushFrame(frame)
def Physics(self, frame): # get muon muon = mu_utils.get_muon( frame=frame, primary=frame[self._primary_key], convex_hull=self._convex_hull, ) labels = dataclasses.I3MapStringDouble() binned_energy_losses = mu_utils.get_binned_energy_losses_in_cylinder( frame=frame, muon=muon, bin_width=self._bin_width, num_bins=self._num_bins, cylinder_height=self._cylinder_height, cylinder_radius=self._cylinder_radius, ) # write to frame labels['track_anchor_x'] = muon.pos.x labels['track_anchor_y'] = muon.pos.y labels['track_anchor_z'] = muon.pos.z labels['track_anchor_time'] = muon.time labels['azimuth'] = muon.dir.azimuth labels['zenith'] = muon.dir.zenith for i, energy_i in enumerate(binned_energy_losses): labels['EnergyLoss_{:05d}'.format(i)] = energy_i frame.Put(self._output_key, labels) self.PushFrame(frame)
def Physics(self, frame): # create empty labelDict labels = dataclasses.I3MapStringDouble() muons_inside = mu_utils.get_muons_inside(frame, self._convex_hull) labels['NoOfMuonsInside'] = len(muons_inside) # get muons mostEnergeticMuon = mu_utils.get_most_energetic_muon_inside( frame, self._convex_hull, muons_inside=muons_inside) if mostEnergeticMuon is None: labels['Muon_energy'] = np.nan labels['Muon_vertexX'] = np.nan labels['Muon_vertexY'] = np.nan labels['Muon_vertexZ'] = np.nan labels['Muon_vertexTime'] = np.nan labels['Muon_azimuth'] = np.nan labels['Muon_zenith'] = np.nan else: labels['Muon_energy'] = mostEnergeticMuon.energy labels['Muon_vertexX'] = mostEnergeticMuon.pos.x labels['Muon_vertexY'] = mostEnergeticMuon.pos.y labels['Muon_vertexZ'] = mostEnergeticMuon.pos.z labels['Muon_vertexTime'] = mostEnergeticMuon.time labels['Muon_azimuth'] = mostEnergeticMuon.dir.azimuth labels['Muon_zenith'] = mostEnergeticMuon.dir.zenith # write to frame frame.Put(self._output_key, labels) self.PushFrame(frame)
def Execute(self,stats): from icecube import dataclasses if not ipmodule.ParsingModule.Execute(self,stats): return 0 # Instantiate a tray tray = I3Tray() # Configure IceTray services if os.path.exists(self.summaryfile): summary = ReadI3Summary(self.summaryfile) else: summary = dataclasses.I3MapStringDouble() tray.context['I3SummaryService'] = summary # Configure IceTray modules tray.AddModule("I3Reader", "reader",filenamelist=[self.gcdfile]+self.inputfilelist) self.Configure(tray) # Execute the Tray tray.Execute() summary = tray.context['I3SummaryService'] save_stats(tray,summary,stats) WriteI3Summary(summary, self.summaryfile) del tray return 0
def MicroCount(frame): MicroValuesHits = dataclasses.I3MapStringInt() MicroValuesPE = dataclasses.I3MapStringDouble() DTWs = ["DTW175","DTW200", "DTW250", "DTW300"] for DTW in DTWs: totalCharge = 0 if not frame.Has("DCFidPulses_" + DTW): MicroValuesHits["STW9000_" + DTW] = icetray.I3Int(0) MicroValuesPE["STW9000_" + DTW] = dataclasses.I3Double( totalCharge) continue # end if() for omkey in frame["DCFidPulses_" + DTW].apply(frame): for pulse in omkey[1]: totalCharge += pulse.charge # end for() # end for() MicroValuesHits["STW9000_" + DTW] = len(frame["DCFidPulses_" + DTW].apply(frame)) MicroValuesPE["STW9000_" + DTW] = totalCharge # end for() frame["MicroCountHits"] = MicroValuesHits frame["MicroCountPE"] = MicroValuesPE return
def _add_i3_summary_service(tray, summaryfile, summaryin): if not summaryin is None: #summary might be {}, that's okay summary = summaryin elif os.path.exists(summaryfile): summary = ReadI3Summary(summaryfile) else: summary = dataclasses.I3MapStringDouble() tray.context['I3SummaryService'] = summary
def _create_mc_tree(self, inj_pos, inj_time, inj_dir): """Inject accompanying muon in provided I3MCTree Parameters ---------- inj_pos : I3Position The position at which to inject the muon. inj_time : double The time at which to inject the muon. inj_dir : I3Direction The direction of the injected muon. Returns ------- I3MCTree The modified I3MCTree with the injected Muon. I3MapStringDouble Information on the injected muon. """ mc_tree = dataclasses.I3MCTree() muon_primary = dataclasses.I3Particle() muon_primary.shape = dataclasses.I3Particle.ParticleShape.Primary muon_primary.dir = dataclasses.I3Direction(inj_dir) muon_primary.pos = dataclasses.I3Position(inj_pos) muon_primary.time = inj_time muon = dataclasses.I3Particle() muon.dir = dataclasses.I3Direction(inj_dir) muon.pos = dataclasses.I3Position(inj_pos) muon.time = inj_time muon.location_type = dataclasses.I3Particle.LocationType.InIce # sample type: MuPlus or MuMinus u = self.random_service.uniform(0., 1.) if u > 0.5: pdg_encoding = 13 else: pdg_encoding = -13 muon.pdg_encoding = pdg_encoding # sample energy muon.energy = self._sample_energy() # add muon primary to I3MCTree mc_tree.add_primary(muon_primary) # add muon as new child mc_tree.append_child(muon_primary, muon) # add info injection_info = dataclasses.I3MapStringDouble({ 'muon_energy': muon.energy, 'muon_pdg_encoding': muon.pdg_encoding, }) return mc_tree, injection_info
def add_dict_to_frame(frame, value_dict, name): ''' Function to add a dict of doubles to a frame in frame[key][dict_key]. ''' I3_double_container = dataclasses.I3MapStringDouble() for key in value_dict.keys(): key.replace('-', '_') I3_double_container[key] = value_dict[key] frame.Put(name, I3_double_container)
def check_alerts(frame): alert_dict = json.loads(frame["AlertShortFollowupMsg"].value) alert_dict = {'value': {'data': alert_dict}} gfu_val = gfu_alert_eval(alert_dict) hese_val = hese_alert_eval(alert_dict) if (gfu_val is not None and gfu_val['pass_tight'] == True): #print 'This is a GOLD GFU alert' alert_pass = '******' elif (hese_val is not None and hese_val['pass_tight'] == True): #print 'This is a GOLD HESE alert' alert_pass = '******' elif (gfu_val is not None and gfu_val['pass_loose'] == True): #print 'This is a BRONZE GFU alert' alert_pass = '******' elif (hese_val is not None and hese_val['pass_loose'] == True): #print 'This is a BRONZE HESE alert' alert_pass = '******' else: #print 'No Bronze or gold alerts found' alert_pass = '******' frame["AlertPassed"] = dataclasses.I3String(alert_pass) def conv_to_float(a): if a is None: return numpy.nan else: return float(a) if gfu_val is not None: gfu_val = {k: conv_to_float(v) for k, v in gfu_val.iteritems()} else: gfu_val = {} frame["AlertInfoGFU"] = dataclasses.I3MapStringDouble(gfu_val) if hese_val is not None: hese_val = {k: conv_to_float(v) for k, v in hese_val.iteritems()} else: hese_val = {} frame["AlertInfoHESE"] = dataclasses.I3MapStringDouble(hese_val) return frame
def get_tau_labels(frame, convex_hull): labels = dataclasses.I3MapStringDouble() primary_nu, tau, first_cascade, second_cascade = get_nutau_interactions( frame) labels['MC_PrimaryInDetectorEnergyLoss'] = get_tau_energy_deposited( frame, convex_hull, tau, first_cascade, second_cascade) labels['MC_PrimaryEnergy'] = primary_nu.energy return labels
def update_weight_dict(frame, frame_key, flux_name): if not frame.Has(frame_key): I3_double_container = dataclasses.I3MapStringDouble() I3_double_container[flux_name] = deepcopy(frame[flux_name].value) else: I3_double_container = deepcopy(frame[frame_key]) I3_double_container[flux_name] = deepcopy(frame[flux_name].value) frame.Delete(frame_key) frame.Put(frame_key, I3_double_container) return True
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 Execute(self, stats): if not ipmodule.IPBaseClass.Execute(self, stats): return 0 import icecube.icetray from I3Tray import I3Tray from icecube import dataio, dataclasses, phys_services inputfile = self.GetParameter('inputfile') outputfile = self.GetParameter('outputfile') # Instantiate a tray tray = I3Tray() # Configure IceTray services summary = dataclasses.I3MapStringDouble() summaryfile = self.GetParameter('summaryfile') if os.path.exists(summaryfile): summary = ReadI3Summary(summaryfile) tray.context['I3SummaryService'] = summary # Configure IceTray modules tray.AddModule("I3Reader", "reader", filenamelist=[inputfile]) tray.AddModule(ModifyEventTime, "mod_mjd", MJD=self.GetParameter('mjd'), MJDSeconds=self.GetParameter('mjdseconds'), MJDNanoSeconds=self.GetParameter('mjdnanoseconds')) tray.AddModule("I3Writer", "writer", filename=outputfile) # Execute the Tray tray.Execute() tray.PrintUsage() summary = tray.context['I3SummaryService'] # Save stats for k in tray.Usage(): stats[str(k.key()) + ":usr"] = k.data().usertime summary[str(k.key()) + ":usr"] = k.data().usertime stats[str(k.key()) + ":sys"] = k.data().systime summary[str(k.key()) + ":sys"] = k.data().systime stats[str(k.key()) + ":ncall"] = k.data().ncall summary[str(k.key()) + ":ncall"] = k.data().ncall WriteI3Summary(summary, summaryfile) # Free memory del tray return 0
def DAQ(self, frame): #Physics ### # Read a line from the file ### line = self.f.readline() ### # If an empty line is returned this means the end of the file is reached # In that case I3Module::RequestSuspension is called to stop the IceTray flow. ### if len(line) == 0: self.RequestSuspension() return # ignore possible lines starting with # while line[0] == '#': line = self.f.readline() ### # First line of an event is event number, number of particles ### #print "line is ",line eventNumber = int(line.split()[0]) numberMapEntries = int(line.split()[1]) numberParticles = int(line.split()[2]) nuPdg = int(line.split()[3]) nuE = float(line.split()[4]) ## @@check if we are dealing with the same event! ## get the physics frame and compare with values 2,3 & 4 #frame['I3MCTree'] = mctree #add event id to the eventheader #evthdr = frame.Get('I3EventHeader') #evthdr.EventID=eventNumber #print "evtnum etc is ",eventNumber, numberMapEntries, numberParticles,nuPdg, nuE weightdict = dataclasses.I3MapStringDouble() for ip in range(numberMapEntries): line = self.f.readline() wdkey = str(line.split()[0]) wdvalue = float(line.split()[1]) weightdict[wdkey] = wdvalue #for kk,vv in weightdict.iteritems(): # print " >>> ", kk, vv frame['I3MCWeightDict'] = weightdict self.PushFrame(frame)
def SetMultiplicity(frame, mctreelist=[], weightmap="CorsikaWeightMap"): if weightmap in frame: wm = frame[weightmap] else: wm = dataclasses.I3MapStringDouble() multiplicity = 0 for t in mctreelist: multiplicity += len(frame[t].primaries) wm["Multiplicity"] = multiplicity if weightmap in frame: frame.Delete(weightmap) frame.Put(weightmap, wm) return True
def Process(self): frame = self.PopFrame() # update meta data if it exists in this frame if (self._frame_key in frame and frame.get_stop(self._frame_key) == frame.Stop): meta = frame[self._frame_key] if self._last_n_events_per_run is not None: if meta['n_events_per_run'] != self._last_n_events_per_run: raise ValueError('N events per Run changes: {} {}'.format( self._last_n_events_per_run, meta['n_events_per_run'], )) # keep track of the last n_files: N_i self._last_n_files = meta['n_files'] self._last_n_events_per_run = meta['n_events_per_run'] # update total n_files meta['n_files'] = self._total_n_files # replace meta data del frame[self._frame_key] frame[self._frame_key] = meta # update weight data if it exists in this frame if self._key in frame and frame.get_stop(self._key) == frame.Stop: weights = frame[self._key] if self._last_n_files is None: raise ValueError('Did not find meta data!', frame) updated_weights = dataclasses.I3MapStringDouble() for name, weight in weights.items(): updated_weights[name] = (float(weight) * self._last_n_files / frame[self._frame_key]['n_files']) del frame[self._key] frame[self._key] = updated_weights # only write one W-frame per file if (frame.Stop.id == 'W' and self._frame_key in frame and frame.get_stop(self._frame_key) == frame.Stop): if self._already_pushed_w_frame: return else: self.PushFrame(frame) self._already_pushed_w_frame = True else: self.PushFrame(frame)
def calculate_coincident_cut_containment(frame, pulsesname, outputname): '''Calculate containment variables for a given hit map. These variables are used for co-incident muon rejection. ''' # taken from http://wiki.icecube.wisc.edu/index.php/Deployment_order ic86 = [ 21, 29, 39, 38, 30, 40, 50, 59, 49, 58, 67, 66, 74, 73, 65, 72, 78, 48, 57, 47, 46, 56, 63, 64, 55, 71, 70, 76, 77, 75, 69, 60, 68, 61, 62, 52, 44, 53, 54, 45, 18, 27, 36, 28, 19, 20, 13, 12, 6, 5, 11, 4, 10, 3, 2, 83, 37, 26, 17, 8, 9, 16, 25, 85, 84, 82, 81, 86, 35, 34, 24, 15, 23, 33, 43, 32, 42, 41, 51, 31, 22, 14, 7, 1, 79, 80 ] deep_core_strings = [79, 80, 81, 82, 83, 84, 85, 86] outer_strings = [ 31, 41, 51, 60, 68, 75, 76, 77, 78, 72, 73, 74, 67, 59, 50, 40, 30, 21, 13, 6, 5, 4, 3, 2, 1, 7, 14, 22 ] vars = dataclasses.I3MapStringDouble() vars['n_top15'] = 0. vars['n_top10'] = 0. vars['n_top5'] = 0. vars['z_travel_top15'] = 0. vars['n_outer'] = 0. if type(frame[pulsesname]) == dataclasses.I3RecoPulseSeriesMap: hit_map = frame.Get(pulsesname) elif type(frame[pulsesname]) == dataclasses.I3RecoPulseSeriesMapMask: hit_map = frame[pulsesname].apply(frame) omgeo = frame['I3Geometry'].omgeo z_pulses = [] t_pulses = [] for om in hit_map.keys(): if om.string in ic86 and om.string not in deep_core_strings: if om.om <= 15: vars['n_top15'] += 1. z_pulses.append(omgeo[om].position.z) t_pulses.append(np.min([p.time for p in hit_map[om]])) if om.om <= 10: vars['n_top10'] += 1. if om.om <= 5: vars['n_top5'] += 1. if om.string in outer_strings: vars['n_outer'] += 1. z_pulses = np.array(z_pulses) z_pulses = z_pulses[np.argsort(t_pulses)] if len(z_pulses) >= 4: len_quartile = np.floor(len(z_pulses) / 4) mean_first_quartile = np.mean(z_pulses[:int(len_quartile)]) vars['z_travel_top15'] = np.mean(z_pulses - mean_first_quartile) frame[outputname] = vars return True
def main(): # Get Params parser = argparse.ArgumentParser(description="NuGen script") add_args(parser) params = vars(parser.parse_args()) # dict() # Execute Tray summary = RunI3Tray(params, configure_tray, "NuGen", summaryfile=params['summaryfile'], summaryin=dataclasses.I3MapStringDouble(), outputfile=params['outputfile'], seed=params['seed'], nstreams=params['nproc'], streamnum=params['procnum'], usegslrng=params['usegslrng'])
def DAQ(self, frame): """Bias events based on the specified bias function. """ # start timer t_0 = timeit.default_timer() # compute keep probability bias_data = { 'frame': frame, } keep_prob, additional_bias_info = self.bias_function(bias_data) keep_prob = float(keep_prob) assert keep_prob > 0. and keep_prob <= 1., keep_prob keep_prob = np.clip(keep_prob, self.lower_probability_bound, 1.0) passed = self.random_service.uniform(0., 1.) <= keep_prob bias_weights = dataclasses.I3MapStringDouble({ 'keep_prob': keep_prob, 'weight_multiplier': 1. / keep_prob, 'passed': float(passed), }) # stop timer t_1 = timeit.default_timer() # add verbose output if desired if self.verbose_output: bias_weights['runtime_total'] = t_1 - t_0 for key, value in additional_bias_info.items(): bias_weights[key] = float(value) if self.verbose: print('Biasing took: {:3.3f}ms'.format((t_1 - t_0) * 1000)) frame[self.output_key] = bias_weights # push frame to next modules if self.keep_all_events: self.PushFrame(frame) else: if passed: self.PushFrame(frame)
def _CalcLLHRPhysics(self, frame): """ calls the llhratio function what it does is: find the 3D slice of 5D PDF based on the energy/zenith of the event. Calculate a 3D llh ratio using the q,t,r values for this event. """ from general_functions import calc_LLHR in_array = self._create_in_array(frame) d = calc_LLHR(in_array, self.sig_hist, self.bkg_hist, self.binedges, self.distinct_regions_binedges, self.SubtractEventFromPDF) frame.Put(self.objname, dataclasses.I3MapStringDouble(d)) return
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
def push_aggregated_frame(self): # adjust charges of pulses for om_key in self.merged_pulse_series.keys(): for pulse in self.merged_pulse_series[om_key]: pulse.charge /= self.oversampling_counter self.current_aggregation_frame['AggregatedPulses'] = \ self.merged_pulse_series # update oversampling dictionary dic = dict(self.current_aggregation_frame['oversampling']) del self.current_aggregation_frame['oversampling'] dic['num_aggregated_pulses'] = self.oversampling_counter dic['time_shift'] = self.current_time_shift self.current_aggregation_frame['oversampling'] = \ dataclasses.I3MapStringDouble(dic) self.PushFrame(self.current_daq_frame) self.PushFrame(self.current_aggregation_frame) self.current_daq_frame = None self.pushed_frame_already = True
def main(): """ Wrapper runs GenerateIceTopShowers Tray segment """ # Get Params parser = argparse.ArgumentParser( description="IceTopShowerGenerator script") add_args(parser) params = vars(parser.parse_args()) # dict() # Execute Tray summary = RunI3Tray(params, configure_tray, "IceTopShowerGenerator", summaryfile=params['summaryfile'], summaryin=dataclasses.I3MapStringDouble(), outputfile=params['outputfile'], outputstreams=[icetray.I3Frame.DAQ], seed=params['seed'], nstreams=params['nproc'], streamnum=params['procnum'], usegslrng=params['usegslrng'])
def Physics(self, frame): """Add MCEq weights to existing weights key in frame Parameters ---------- frame : I3Frame Current i3 frame. """ weights = dataclasses.I3MapStringDouble(frame[self.weight_key]) ow = frame['I3MCWeightDict']['OneWeight'] type_weight = frame['I3MCWeightDict']['TypeWeight'] ptype = frame['I3MCWeightDict']['PrimaryNeutrinoType'] energy = frame['I3MCWeightDict']['PrimaryNeutrinoEnergy'] cos_zen = np.cos(frame['I3MCWeightDict']['PrimaryNeutrinoZenith']) n_events = frame['I3MCWeightDict']['NEvents'] for primary_model, flux in self.fluxes.items(): for flux_type in ['total', 'pr', 'conv']: flux_val = flux.getFlux( ptype=ptype, energy=energy, costheta=cos_zen, flux_type=flux_type, ) weight = flux_val * ow / (type_weight * n_events * self.n_files) flux_name = 'MCEq_{}_{}_{}'.format( primary_model, self.interaction_model.lower(), flux_type, ).replace('.', '_') weights[flux_name] = float(weight) del frame[self.weight_key] frame[self.weight_key] = weights self.PushFrame(frame)
def Execute(self, stats): if not ipmodule.ParsingModule.Execute(self, stats): return 0 from . import ReadI3Summary, WriteI3Summary from icecube import dataclasses import math filelist = self.GetParameter('inputfilelist') outfile = self.GetParameter('outputfile') retval = 0 cmd = '' summary = dataclasses.I3MapStringDouble() for file in filelist: stats = ReadI3Summary(file) for key, value in stats.items(): if isinstance(value, float) and math.isnan(value): continue # don't add NaN if summary.has_key(key): summary[key] += value else: summary[key] = value WriteI3Summary(summary, outfile) return 0
def Physics(self, frame): """Add MCEq weights to existing weights key in frame Parameters ---------- frame : I3Frame Current i3 frame. """ veto_pf = dataclasses.I3MapStringDouble() ow = frame['I3MCWeightDict']['OneWeight'] type_weight = frame['I3MCWeightDict']['TypeWeight'] ptype = frame['I3MCWeightDict']['PrimaryNeutrinoType'] energy = frame['I3MCWeightDict']['PrimaryNeutrinoEnergy'] cos_zen = np.cos(frame['I3MCWeightDict']['PrimaryNeutrinoZenith']) n_events = frame['I3MCWeightDict']['NEvents'] for primary_model, veto_obj in self.veto_objects.items(): for flux_type in ['total', 'pr', 'conv']: pf = veto_obj.get_passing_fraction( ptype=ptype, energy=energy, costheta=cos_zen, flux_type=flux_type, ) flux_name = 'pf_{}_{}_{}_{}'.format( self.prpl, primary_model, self.interaction_model, flux_type, ).replace('.', '_') veto_pf[flux_name] = float(pf) frame[self.output_key] = veto_pf self.PushFrame(frame)