def Physics(self, frame):
        q_tot = NaN
        n_channels = 0
        n_hits = 0
        max_qfrac = NaN
        pulse_map = dataclasses.I3RecoPulseSeriesMap.from_frame(
            frame, self.pulses)
        charge_list = []
        for omkey, pulses in pulse_map:
            # Throw out Deep Core strings (want homogenized total charge)
            if (omkey.string < 79) and (omkey.om >= self.min_DOM) and (
                    omkey.om <= self.max_DOM):
                n_channels += 1
                for pulse in pulses:
                    charge_list += [pulse.charge]
        # Check to see if DOMs with signal are in the min_DOM to
        # max_DOM range
        if n_channels == 0:
            q_tot = NaN
            max_qfrac = NaN
        else:
            q_tot = np.sum(charge_list)
            n_hits = len(charge_list)
            max_qfrac = np.max(charge_list) / q_tot

        frame.Put('InIce_charge_{}_{}'.format(self.min_DOM, self.max_DOM),
                  dataclasses.I3Double(q_tot))
        frame.Put('NChannels_{}_{}'.format(self.min_DOM, self.max_DOM),
                  icetray.I3Int(n_channels))
        frame.Put('NHits_{}_{}'.format(self.min_DOM, self.max_DOM),
                  icetray.I3Int(n_hits))
        frame.Put('max_qfrac_{}_{}'.format(self.min_DOM, self.max_DOM),
                  dataclasses.I3Double(max_qfrac))
        self.PushFrame(frame)
Beispiel #2
0
def process_frame(frame, gcdfile='/cvmfs/icecube.opensciencegrid.org/data/GCD/GeoCalibDetectorStatus_2013.56429_V0.i3.gz', charge_scale=1.0, time_scale=1e-3):
    """ Processes a frame to create an event graph and metadata out of it.
    
    Parameters:
    -----------
    frame : I3Frame
        The data frame to extract an event graph with features from.
    gcd_file : str
        Path to the gcd file.
    charge_scale : float
        The normalization constant for charge.
    time_scale : float
        The normalization constant for time.
    """

    ### Meta data of the event for analysis of the classifier and creation of ground truth
    primary = dataclasses.get_most_energetic_neutrino(frame['I3MCTree'])
    if primary is None:
        get_weighted_primary(frame, MCPrimary='MCPrimary')
        primary = frame['MCPrimary']

    # Obtain the PDG Encoding for ground truth
    #frame['PDGEncoding'] = dataclasses.I3Double(primary.pdg_encoding)
    #frame['InteractionType'] = dataclasses.I3Double(frame['I3MCWeightDict']['InteractionType'])

    frame['RunID'] = icetray.I3Int(frame['I3EventHeader'].run_id)
    frame['EventID'] = icetray.I3Int(frame['I3EventHeader'].event_id)
    frame['PrimaryEnergy'] = dataclasses.I3Double(primary.energy)

    ### Create features for each event 
    features, coordinates, _ = get_events_from_frame(frame, charge_scale=charge_scale, time_scale=time_scale)
    for feature_name in vertex_features:
        frame[feature_name] = dataclasses.I3VectorFloat(features[feature_name])
    
    ### Create offset lookups for the flattened feature arrays per event
    frame['NumberVertices'] = icetray.I3Int(len(features[features.keys()[0]]))

    ### Create coordinates for each vertex
    C = np.vstack(coordinates.values()).T
    #C, C_mean, C_std = normalize_coordinates(C, weights=None, copy=True)
    #C_cog, C_mean_cog, C_std_cog = normalize_coordinates(C, weights=features['TotalCharge'], copy=True)


    frame['VertexX'] = dataclasses.I3VectorFloat(C[:, 0])
    frame['VertexY'] = dataclasses.I3VectorFloat(C[:, 1])
    frame['VertexZ'] = dataclasses.I3VectorFloat(C[:, 2])

    ### Output centering and true debug information
    frame['PrimaryX'] = dataclasses.I3Double(primary.pos.x)
    frame['PrimaryY'] = dataclasses.I3Double(primary.pos.y)
    frame['PrimaryZ'] = dataclasses.I3Double(primary.pos.z)
    frame['PrimaryAzimuth'] = dataclasses.I3Double(primary.dir.azimuth)
    frame['PrimaryZenith'] = dataclasses.I3Double(primary.dir.zenith)

    ### Apply labeling
    classify_wrapper(frame, None, gcdfile=gcdfile)
    return True
Beispiel #3
0
    def CreatePFrame(self, nside, pixel):
        dec, ra = healpy.pix2ang(nside, pixel)
        dec = dec - numpy.pi / 2.
        zenith, azimuth = astro.equa_to_dir(ra, dec, self.event_mjd)
        zenith = float(zenith)
        azimuth = float(azimuth)
        direction = dataclasses.I3Direction(zenith, azimuth)

        position = self.seed_position
        time = self.seed_time
        energy = self.seed_energy

        variationDistance = 20. * I3Units.m
        posVariations = [
            dataclasses.I3Position(0., 0., 0.),
            dataclasses.I3Position(-variationDistance, 0., 0.),
            dataclasses.I3Position(variationDistance, 0., 0.),
            dataclasses.I3Position(0., -variationDistance, 0.),
            dataclasses.I3Position(0., variationDistance, 0.),
            dataclasses.I3Position(0., 0., -variationDistance),
            dataclasses.I3Position(0., 0., variationDistance)
        ]

        for i in range(0, len(posVariations)):
            posVariation = posVariations[i]
            p_frame = icetray.I3Frame(icetray.I3Frame.Physics)
            thisPosition = dataclasses.I3Position(position.x + posVariation.x,
                                                  position.y + posVariation.y,
                                                  position.z + posVariation.z)

            # generate the particle from scratch
            particle = dataclasses.I3Particle()
            particle.shape = dataclasses.I3Particle.ParticleShape.InfiniteTrack
            particle.fit_status = dataclasses.I3Particle.FitStatus.OK
            particle.pos = thisPosition
            particle.dir = direction
            particle.time = time
            particle.energy = energy
            p_frame[self.output_particle_name] = particle

            # generate a new event header
            eventHeader = dataclasses.I3EventHeader(self.event_header)
            eventHeader.sub_event_stream = "SCAN_nside%04u_pixel%04u_posvar%04u" % (
                nside, pixel, i)
            eventHeader.sub_event_id = pixel
            p_frame["I3EventHeader"] = eventHeader
            p_frame["SCAN_HealpixPixel"] = icetray.I3Int(int(pixel))
            p_frame["SCAN_HealpixNSide"] = icetray.I3Int(int(nside))
            p_frame["SCAN_PositionVariationIndex"] = icetray.I3Int(int(i))

            for frame in self.GCDQpFrames[0:-1]:
                self.PushFrame(frame)
            self.PushFrame(p_frame)
Beispiel #4
0
			def RFrame(self, frame):
				position = frame[self.input_pos_name]
				time = frame[self.input_time_name].value
				energy = float('NaN')

				self.PushFrame(frame)

				for pixel in self.pixels:
					p_frame = icetray.I3Frame(icetray.I3Frame.Physics)
				
					zenith, azimuth = healpy.pix2ang(self.nside, pixel)
					direction = dataclasses.I3Direction(zenith,azimuth)

					#print "reconstructing with fixed direction", direction, "(npixels=", self.npix, ", pixel=", pixel, ")"
				
				
					variationDistance = 20.*I3Units.m
					posVariations = [dataclasses.I3Position(0.,0.,0.),
									dataclasses.I3Position(-variationDistance,0.,0.),
									dataclasses.I3Position( variationDistance,0.,0.),
									dataclasses.I3Position(0.,-variationDistance,0.),
									dataclasses.I3Position(0., variationDistance,0.),
									dataclasses.I3Position(0.,0.,-variationDistance),
									dataclasses.I3Position(0.,0., variationDistance)]
				
					for i in range(len(posVariations)):
						thisPosition = dataclasses.I3Position(position.x + posVariations[i].x,position.y + posVariations[i].y,position.z + posVariations[i].z)
					
						# generate the particle from scratch
						particle = dataclasses.I3Particle()
						particle.shape = dataclasses.I3Particle.ParticleShape.Cascade
						particle.fit_status = dataclasses.I3Particle.FitStatus.OK
						particle.pos = thisPosition
						particle.dir = direction
						particle.time = time
						particle.energy = energy
					
						thisParticleName = self.output_particle_name
						if i>0: thisParticleName = thisParticleName+"_%i"%i
					
						p_frame[thisParticleName] = particle
					
					p_frame["HealpixPixel"] = icetray.I3Int(int(pixel))
					p_frame["HealpixNSide"] = icetray.I3Int(int(self.nside))
				
					# generate a new event header
					eventHeader = dataclasses.I3EventHeader(frame["I3EventHeader"])
					eventHeader.sub_event_stream = "millipede_scan_nside%04u" % self.nside
					eventHeader.sub_event_id = pixel
					p_frame["I3EventHeader"] = eventHeader
				
					self.PushFrame(p_frame)
def coincidenceLabel_poly(p_frame):
    if is_data(p_frame):
        return True
    if 'I3MCWeightDict' not in p_frame.keys():
        return
    poly = p_frame['PolyplopiaCount']
    #print('Poly? {}'.format(poly.value))
    if poly == icetray.I3Int(0):
        coincidence = 0
    else:
        coincidence = 1
    p_frame.Put("multiplicity", icetray.I3Int(coincidence))
    return
Beispiel #6
0
    def FramePacket(self, frames):
        n_reduced = 0
        oframes = []
        for frame in frames:
            if (frame.Has("I3EventHeader") and
                    frame["I3EventHeader"].sub_event_stream == self.splitName):
                r = dataclasses.I3RecoPulseSeriesMap.from_frame(
                    frame, self.pulsesName)
                keep = True
                if (len(r) == 0):
                    keep = False
                else:
                    for item in r:
                        keep = False
                        if (len(item[1])):
                            keep = True
                            break

                if (keep):
                    oframes.append(frame)
                else:
                    n_reduced += 1
            else:
                oframes.append(frame)

        for frame in oframes:
            if (frame.Stop == icetray.I3Frame.DAQ):
                red_value = frame[self.splitName + "ReducedCount"].value
                frame.Delete(self.splitName + "ReducedCount")
                frame.Put(self.splitName + "ReducedCount",
                          icetray.I3Int((red_value + n_reduced)))
            self.PushFrame(frame)
Beispiel #7
0
def fix_pixel_num(frame):
    nside = frame["SCAN_HealpixNSide"].value
    pixel = frame["SCAN_HealpixPixel"].value
    posvar = frame["SCAN_PositionVariationIndex"].value
    header = frame["I3EventHeader"]

    # we used to do this to go from pixel to dec/ra:
    dec, ra = healpy.pix2ang(nside, pixel)
    dec = dec - numpy.pi / 2.

    # this is what we *should* have done:
    # dec = numpy.pi/2. - dec

    new_pixel = healpy.ang2pix(nside, numpy.pi / 2. - dec, ra)

    # --- sanity check
    # (this is how we *want* this to be converted. Make sure the above did the right thing)
    new_dec, new_ra = healpy.pix2ang(nside, new_pixel)
    new_dec = numpy.pi / 2. - new_dec
    if abs(new_dec - dec) > 1e-7:
        raise RuntimeError(
            "Logic error in pixel conversion. new_dec={}, dec={}".format(
                new_dec, dec))
    # --- end sanity check

    new_header = copy.copy(header)
    new_header.sub_event_id = new_pixel
    new_header.sub_event_stream = "SCAN_nside%04u_pixel%04u_posvar%04u" % (
        nside, new_pixel, posvar)

    del frame["SCAN_HealpixPixel"]
    frame["SCAN_HealpixPixel"] = icetray.I3Int(new_pixel)

    del frame["I3EventHeader"]
    frame["I3EventHeader"] = new_header
Beispiel #8
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 DAQ(self, frame):
     print('DAQ Frame')
     self.PushFrame(frame)
     for i in range(0, max_phys_frames):
         subframe = self.get_next_sub_event(frame)
         subframe['TriggerID'] = icetray.I3Int(i)
         self.PushFrame(subframe)
     return True
Beispiel #10
0
 def make_and_push_P(self, pspec):
     newPframe = I3Frame('P')
     for i in range(pspec['nP']):
         newPframe = I3Frame('P')
         ehP = self.make_header(i, pspec['name'])
         newPframe.Put('I3EventHeader', ehP)
         newPframe.Put('NCh', icetray.I3Int(
             12 + 5 * i))  # note: unphysical nonsense! just for this test.
         self.PushFrame(newPframe)
Beispiel #11
0
def GetStations(frame, InputITpulses, output):
    nstation = 0
    if InputITpulses in frame:
        vemPulses = frame[InputITpulses]
        if vemPulses.__class__ == dc.I3RecoPulseSeriesMapMask:
            vemPulses = vemPulses.apply(frame)
        stationList = set([pulse.key().string for pulse in vemPulses])
        nstation = len(stationList)
    frame[output] = icetray.I3Int(nstation)
Beispiel #12
0
    def CreatePFrame(self, nside, pixel, pixel_index):
        dec, ra = healpy.pix2ang(nside, pixel)
        dec = numpy.pi/2. - dec
        zenith, azimuth = astro.equa_to_dir(ra, dec, self.event_mjd)
        zenith = float(zenith)
        azimuth = float(azimuth)
        direction = dataclasses.I3Direction(zenith,azimuth)

        position = self.seed_position
        time = self.seed_time
        energy = self.seed_energy

        for i in range(0,len(self.posVariations)):
            posVariation = self.posVariations[i]
            p_frame = icetray.I3Frame(icetray.I3Frame.Physics)

            thisPosition = dataclasses.I3Position(position.x + posVariation.x, position.y + posVariation.y, position.z + posVariation.z)

            # generate the particle from scratch
            particle = dataclasses.I3Particle()
            particle.shape = dataclasses.I3Particle.ParticleShape.InfiniteTrack
            particle.fit_status = dataclasses.I3Particle.FitStatus.OK
            particle.pos = thisPosition
            particle.dir = direction
            particle.time = time
            particle.energy = energy
            p_frame[self.output_particle_name] = particle

            # generate a new event header
            eventHeader = dataclasses.I3EventHeader(self.event_header)
            eventHeader.sub_event_stream = "SCAN_nside%04u_pixel%04u_posvar%04u" % (nside, pixel, i)
            eventHeader.sub_event_id = pixel
            p_frame["I3EventHeader"] = eventHeader
            p_frame["SCAN_HealpixPixel"] = icetray.I3Int(int(pixel))
            p_frame["SCAN_HealpixNSide"] = icetray.I3Int(int(nside))
            p_frame["SCAN_PositionVariationIndex"] = icetray.I3Int(int(i))

            # an overall sequence index, 0-based, in case we need to re-start
            p_frame["SCAN_EventOverallIndex"] = icetray.I3Int( int(i) + pixel_index*len(self.posVariations))
            if self.inject_event_name is not None:
                p_frame["SCAN_EventName"] = dataclasses.I3String(self.inject_event_name)

            self.PushFrame(p_frame)
Beispiel #13
0
def coincidenceLabel_poly(physics_frame, gcdfile):
    poly = physics_frame['PolyplopiaCount']
    #print "Poly {}".format(poly)
    if poly == icetray.I3Int(0):
        coincidence = 0
    #elif poly == icetray.I3Int(0):
    #    coincidence = 0
    else:
        coincidence = 1
    return coincidence
def set_signature(frame, gcdfile=None, surface=None):
    if is_data(frame):
        return True
    if surface is None:
        if gcdfile is None:
            surface = icecube.MuonGun.ExtrudedPolygon.from_I3Geometry(
                frame['I3Geometry'])
        else:
            surface = icecube.MuonGun.ExtrudedPolygon.from_file(gcdfile,
                                                                padding=0)
    if "visible_track" in frame.keys():
        p = frame["visible_track"]
        intersections = surface.intersection(p.pos, p.dir)
    elif "visible_nu" in frame.keys():
        p = frame["visible_nu"]
        intersections = surface.intersection(p.pos + p.length * p.dir, p.dir)
    else:
        val = -1
        frame.Put("signature", icetray.I3Int(val))
        return
    if not np.isfinite(intersections.first):
        val = -1
    elif p.is_neutrino:
        if intersections.first <= 0 and intersections.second > 0:
            val = 0  # starting event
        else:
            val = -1  # vertex outside detector
    elif p.is_track:
        if intersections.first <= 0 and intersections.second > 0:
            val = 0  # starting event
        elif intersections.first > 0 and intersections.second > 0:
            if p.length <= intersections.first:
                val = -1  # no hit
            elif p.length > intersections.second:
                val = 1  # through-going event
            else:
                val = 2  # stopping event
        else:
            val = -1  # vertex behind detector
    frame.Put("signature", icetray.I3Int(val))
    return
Beispiel #15
0
 def FramePacket(self, frames):
     count = 0
     for frame in frames:
         if (frame.Stop == icetray.I3Frame.Physics):
             if (frame.Has("I3EventHeader")):
                 if (frame["I3EventHeader"].sub_event_stream ==
                         self.splitname):
                     count += 1
     frames[0].Put(self.splitname + "SplitCount", icetray.I3Int(count))
     for frame in frames:
         self.PushFrame(frame)
     return
Beispiel #16
0
def selectFinalFit(frame):
    fits = [
        "SplineMPE_split", "MPEFit_split", "SPEFit4_split",
        "SPEFitSingle_split", "ImprovedLineFit_split"
    ]
    resultName = "TrackFit"
    result = None
    params = None
    for fitName in fits:
        if (not frame.Has(fitName)):
            continue
        fit = frame.Get(fitName)
        if (fit.fit_status == dataclasses.I3Particle.OK):
            frame.Put(resultName, fit)
            frame.Put(resultName + "Fallback",
                      icetray.I3Int(fits.index(fitName)))
            if (frame.Has(fitName + "FitParams")):
                frame.Put(resultName + "FitParams",
                          frame.Get(fitName + "FitParams"))
            break
    if (not frame.Has(resultName + "Fallback")):
        frame.Put(resultName + "Fallback", icetray.I3Int(len(fits)))
Beispiel #17
0
def setUpModule():
    """
     Generate .i3 file (borrowed from dataio test_randomaccess_file)
    """
    i3f = dataio.I3File(test_filename, dataio.I3File.Mode.Writing)
    frames = test_frames

    for pr in frames:
        frame = icetray.I3Frame(icetray.I3Frame.Stream(pr[0]))
        frame[pr[0]] = icetray.I3Int(pr[1])
        i3f.push(frame)

    i3f.close()
def classify_corsika(p_frame, gcdfile=None, surface=None):
    if is_data(p_frame):
        return True
    if surface is None:
        if gcdfile is None:
            surface = icecube.MuonGun.ExtrudedPolygon.from_I3Geometry(
                p_frame['I3Geometry'])
        else:
            surface = icecube.MuonGun.ExtrudedPolygon.from_file(gcdfile,
                                                                padding=0)
    mu_list = []
    I3Tree = p_frame['I3MCTree']
    primaries = I3Tree.get_primaries()
    for p in primaries:
        tlist = []
        find_muons(p, I3Tree, surface, plist=tlist)
        mu_list.append(tlist[-1])

    if len(np.concatenate(mu_list)) == 0:
        pclass = 11  # Passing Track
    elif len(mu_list) > 1:
        pclass = 21  # several events
        clist = np.concatenate(mu_list)
        energies = np.array(
            [calc_depositedE_single_p(p, I3Tree, surface) for p in clist])
        inds = np.argsort(energies)
        p_frame.Put("visible_track", clist[inds[-1]])

    else:
        if len(mu_list[0]) > 1:
            energies = np.array([
                calc_depositedE_single_p(p, I3Tree, surface)
                for p in mu_list[0]
            ])
            mu_signatures = np.array(
                [has_signature(p, surface) for p in mu_list[0]])
            if np.any(mu_signatures == 1):
                pclass = 22  # Through Going Bundle
            else:
                pclass = 23  # Stopping Muon Bundle
            inds = np.argsort(energies)
            p_frame.Put("visible_track", mu_list[0][inds[-1]])
        else:
            if has_signature(mu_list[0][0], surface) == 2:
                pclass = 4  # Stopping Track
            else:
                pclass = 2  # Through Going Track
            p_frame.Put("visible_track", mu_list[0][0])
    p_frame.Put("classification", icetray.I3Int(pclass))
    return
    def test_default(self):
        h = PhysicsHistogram(0,
                             10,
                             10,
                             "DerivedHistogram",
                             expression="frame['integer'].value")

        for i in range(10):
            frame = icetray.I3Frame()
            frame["integer"] = icetray.I3Int(i)
            h.Physics(frame)

        for bin_value in h.bin_values:
            self.assertEqual(bin_value, 1)
def Split_Recombine(tray, name, Params=RunParameters()):
    #tray.AddModule("Keep","HouseCleaning",
    #Keys = ["I3Geometry",
    #"I3Calibration",
    #"I3DetectorStatus",
    #"I3DetectorConfiguration",
    #"I3EventHeader",
    #"OfflinePulses",
    #"I3MCTree"])

    # NOTE Define the name of the unultered Pulses in the Q-frame
    OrgPulses = "OfflinePulses"
    # NOTE Define the name of the subevent stream that you like to create
    SplitName = "org"
    # NOTE Define how the split Pulses should be named
    SplitPulses = "org"

    from icecube import CoincSuite
    # NOTE Create a complement object <I3Int>(SplitName+"ReducedName") in the Q frame keeping trace of the number of frames which have been recombined
    tray.AddModule(
        lambda f: f.Put(SplitName + "ReducedCount", icetray.I3Int(0)),
        "ReducedCountMaker",
        Streams=[icetray.I3Frame.DAQ])

    # NOTE Discard frames that you do not want to concider for recombinations early on.
    # NOTE every discarded frame should be accounted for by increasing the 'ReducedCount'
    tray.AddModule(
        "AfterpulseDiscard",
        "AfterpulseDiscard",
        SplitName=
        SplitName,  #NOTE Run on the splitframes; this paramater should be set for all modules
        RecoMapName=
        SplitPulses,  #NOTE use the SplitPulses; this paramater should be set for all modules
        QTotFraction=.1,
        TimeOffset=3.E3 * I3Units.ns,
        OverlapFraction=0.75)

    # NOTE remove the frames the you do not want to use
    #  tray.AddModule(lambda f: which_split(f,split_name=SplitName) and f.Has("Afterpulse"), "KillAfterpulseFrame")

    # NOTE create the HypoFrames from all remaining SplitFrames
    tray.AddModule(
        "HypoFrameCreator",
        "ForceHypoFrames",
        SplitName=SplitName,
        HypoName="hypoframe",  # NOTE give the stream of Hypoframes a unique name
        RecoMapName=SplitPulses,
        MaxTimeSeparation=3000. * I3Units.ns
    )  # NOTE specify that frames timely spaced too far apart should not be recombined
Beispiel #21
0
    def test_fill(self):
        h = DerivedHistogram(0, 10, 10, "DerivedHistogram")

        for i in range(10):
            frame = icetray.I3Frame()
            frame["integer"] = icetray.I3Int(i)
            h.DAQ(frame)

        frame = icetray.I3Frame()
        frame["integer"] = icetray.I3Int(-1)
        h.DAQ(frame)

        frame = icetray.I3Frame()
        frame["integer"] = icetray.I3Int(10)
        h.DAQ(frame)

        self.assertEqual(len(h.bin_values), 10)
        self.assertEqual(h.name, "DerivedHistogram")

        for bin_value in h.bin_values:
            self.assertEqual(bin_value, 1)

        self.assertEqual(h.overflow, 1)
        self.assertEqual(h.underflow, 1)
Beispiel #22
0
def classify_muongun(p_frame,
                     gcdfile=None,
                     surface=None,
                     primary_key='MCPrimary'):
    p = p_frame[primary_key]
    if has_signature(p, surface) == 1:
        pclass = 2  # Through Going Track
    elif has_signature(p, surface) == 2:
        pclass = 4  # Stopping Track
    else:
        pclass = 0
    p_frame.Put("classification_truth_id", icetray.I3Int(pclass))
    p_frame.Put("classification_truth", dataclasses.I3String(decode[pclass]))
    p_frame.Put("visible_track", p)
    return
Beispiel #23
0
def classify_muongun(p_frame, gcdfile=None, surface=None, primary_key='MCPrimary'):
    if is_data(p_frame):
        return True
    if surface is None:
        if gcdfile is None:
            surface = icecube.MuonGun.ExtrudedPolygon.from_I3Geometry(p_frame['I3Geometry'])
        else:
            surface = icecube.MuonGun.ExtrudedPolygon.from_file(gcdfile, padding=0)
    p = p_frame[primary_key]
    if has_signature(p, surface) == 1:
        pclass = 2  # Through Going Track
    elif has_signature(p, surface) == 2:
        pclass = 4  # Stopping Track
    else:
        pclass = 0
    p_frame.Put("classification", icetray.I3Int(pclass))
    p_frame.Put("visible_track", p)
    return
    def test_daq(self):
        '''
        This tests that nothing happens when the DAQ
        method is called.
        '''
        h = PhysicsHistogram(0,
                             10,
                             10,
                             "DerivedHistogram",
                             expression="frame['integer'].value")

        for i in range(10):
            frame = icetray.I3Frame()
            frame["integer"] = icetray.I3Int(i)
            h.DAQ(frame)

        # all the bins should still be empty
        for bin_value in h.bin_values:
            self.assertEqual(bin_value, 0)
Beispiel #25
0
def classify_corsika(p_frame, gcdfile=None, surface=None):
    mu_list = []
    I3Tree = p_frame['I3MCTree']
    primaries = I3Tree.get_primaries()
    for p in primaries:
        tlist = []
        find_muons(p, I3Tree, surface, plist=tlist)
        mu_list.append(tlist[-1])

    if len(np.concatenate(mu_list)) == 0:
        pclass = 11  # Passing Track
    elif len(mu_list) > 1:
        pclass = 21  # several events
        clist = np.concatenate(mu_list)
        energies = np.array(
            [calc_depositedE_single_p(p, I3Tree, surface) for p in clist])
        inds = np.argsort(energies)
        p_frame.Put("visible_track", clist[inds[-1]])

    else:
        if len(mu_list[0]) > 1:
            energies = np.array([
                calc_depositedE_single_p(p, I3Tree, surface)
                for p in mu_list[0]
            ])
            mu_signatures = np.array(
                [has_signature(p, surface) for p in mu_list[0]])
            if np.any(mu_signatures == 1):
                pclass = 22  # Through Going Bundle
            else:
                pclass = 23  # Stopping Muon Bundle
            inds = np.argsort(energies)
            p_frame.Put("visible_track", mu_list[0][inds[-1]])
        else:
            if has_signature(mu_list[0][0], surface) == 2:
                pclass = 4  # Stopping Track
            else:
                pclass = 2  # Through Going Track
            p_frame.Put("visible_track", mu_list[0][0])
    p_frame.Put("classification_truth_id", icetray.I3Int(pclass))
    p_frame.Put("classification_truth", dataclasses.I3String(decode[pclass]))
    return
Beispiel #26
0
 def FramePacket(self, frames):
     reducedValue = 0
     qframe = frames[0]
     if (qframe.Has(self.splitName + "SplitCount")):
         splits = qframe[self.splitName + "SplitCount"].value
         nsplitframes = 0
         for frame in frames:
             if (frame.Has("I3EventHeader")):
                 if (frame["I3EventHeader"].sub_event_stream ==
                         self.splitName):
                     nsplitframes += 1
         reducedValue = splits - nsplitframes
         if (reducedValue < 0):
             icetray.logging.log_fatal(
                 "Something is wrong with your SplitCount-variable")
     qframe.Put(self.splitName + "ReducedCount",
                icetray.I3Int(reducedValue))
     for frame in frames:
         self.PushFrame(frame)
     return
Beispiel #27
0
    def Physics(self, frame):
        q_tot = -1.0
        n_channels = -1
        max_charge_frac = -1.0
        if self.inice_pulses in frame:
            VEMpulses = frame[self.inice_pulses]
            if VEMpulses.__class__ == dc.I3RecoPulseSeriesMapMask:
                VEMpulses = VEMpulses.apply(frame)
                charge_list = []
                n_channels = 0
                for om, pulses in VEMpulses:
                    n_channels += 1
                    for pulse in pulses:
                        charge_list += [pulse.charge]
                q_tot = sum(charge_list)
                max_charge_frac = max(charge_list)/q_tot

        frame.Put('InIce_charge', dc.I3Double(q_tot))
        frame.Put('NChannels', icetray.I3Int(n_channels))
        frame.Put('max_charge_frac', dc.I3Double(max_charge_frac))
        self.PushFrame(frame)
Beispiel #28
0
    def CalculateNAbove200( frame, PulseSeries, ConfigID):

        # Loop over all the triggers looking
        # for the times of all the selected triggers
        
        triggerTimes = []
        for trigger in frame[ "I3TriggerHierarchy"]:
            if trigger.key.config_id == ConfigID:
                triggerTimes.append( trigger.time)
            # end if()
        # end for()

        # Check that there is at least one of the
        # selected triggers.
        
        if len(triggerTimes) == 0:
            frame[ "NAbove200"] = icetray.I3Int( 0)
            return
        # end if()

        triggerTimes.sort()
        earliestTriggerTime = triggerTimes[0]

        chargeCounter = 0        
        geometry = frame[ "I3Geometry"]
        
        for omkey in frame[ PulseSeries]:
            if not geometry.omgeo[ omkey[0]].position.z > -200 * I3Units.m:
                continue
            # end if()
            for pulse in omkey[1]:
                if (pulse.time - earliestTriggerTime) < 0 and (pulse.time - earliestTriggerTime) > -2000:
                    chargeCounter += pulse.charge
                # end if()
            # end for()            
        # end for()

        frame[ "NAbove200"] = dataclasses.I3Double( chargeCounter)

        return
Beispiel #29
0
 def Process(self):
   """ deliver frames QP with only a bit of rudamentary information """
   #make a Q-frame
   Qframe = icetray.I3Frame(icetray.I3Frame.DAQ)
   Qeh = dataclasses.I3EventHeader()
   Qeh.start_time = (dataclasses.I3Time(2011, 0))
   Qeh.end_time = (dataclasses.I3Time(2011, 2))
   Qeh.run_id = 1
   Qeh.event_id = 1
   Qframe.Put("I3EventHeader", Qeh)
   Qrecomap = dataclasses.I3RecoPulseSeriesMap()
   recopulse1 = dataclasses.I3RecoPulse()
   recopulse1.time = 0
   recopulse1.charge = 1
   recopulse2 = dataclasses.I3RecoPulse()
   recopulse2.time = 1
   recopulse2.charge = 2
   Qrecomap[icetray.OMKey(1,1)] = [recopulse1]
   Qrecomap[icetray.OMKey(2,2)] = [recopulse2]
   Qframe.Put(OrgPulses, Qrecomap)
   Qframe.Put(SplitName+"SplitCount", icetray.I3Int(1))
   self.PushFrame(Qframe)
   #now make the first p-frame containing one I3RecoPulse
   P1frame = icetray.I3Frame(icetray.I3Frame.Physics)
   P1eh = dataclasses.I3EventHeader()
   P1eh.start_time = (dataclasses.I3Time(2011, 0))
   P1eh.end_time = (dataclasses.I3Time(2011, 1))
   P1eh.run_id = 1
   P1eh.event_id = 1
   P1eh.sub_event_stream = "split"
   P1eh.sub_event_id = 0
   P1frame.Put("I3EventHeader", P1eh)
   P1recomap = dataclasses.I3RecoPulseSeriesMap()
   P1recomap[icetray.OMKey(1,1)] = [recopulse1]
   P1recomask = dataclasses.I3RecoPulseSeriesMapMask(Qframe, OrgPulses, Qrecomap)
   P1frame.Put(SplitPulses, P1recomask)
   self.PushFrame(P1frame)
   
   self.RequestSuspension()
Beispiel #30
0
def putints(frame, where, value):
    frame[where] = icetray.I3Int(value)
    print('put value %s at %s' % (value, where))