def append_to_skymaps(row, times, data_map, ref_map, local_map,
                      n_side, n_resamples):

    local_zenith = row['lap_zenith']
    local_azimuth = row['lap_azimuth']
    local_time = row['start_time_mjd']

    # Local skymap
    pix = hp.ang2pix(n_side, local_zenith, local_azimuth)
    local_skymap[pix] += 1

    # Data skymap
    ra, dec = astro.dir_to_equa(local_zenith, local_azimuth, local_time)
    hp_theta, hp_phi = equatorial_to_healpy(ra, dec)
    pix = hp.ang2pix(n_side, hp_theta, hp_phi)
    data_skymap[pix] += 1

    # Reference skymap
    rand_times = np.random.choice(times, size=n_resamples)
    ra, dec = astro.dir_to_equa(local_zenith, local_azimuth, rand_times)
    hp_theta, hp_phi = equatorial_to_healpy(ra, dec)
    ref_skymap = append_time_scrambled_events(
                                hp_theta, hp_phi, ref_skymap,
                                n_side=n_side, n_resamples=20)

    return
def make_skymaps(df, times, n_resamples=20, n_side=64, verbose=False):

    n_pix = hp.nside2npix(n_side)
    data_skymap = np.zeros(n_pix, dtype=float)
    ref_skymap = np.zeros(n_pix, dtype=float)
    local_skymap = np.zeros(n_pix, dtype=float)

    for idx, row in df.iterrows():
        local_zenith = row['lap_zenith']
        local_azimuth = row['lap_azimuth']
        local_time = row['start_time_mjd']

        # Local skymap
        pix = hp.ang2pix(n_side, local_zenith, local_azimuth)
        local_skymap[pix] += 1

        # Data skymap
        ra, dec = astro.dir_to_equa(local_zenith, local_azimuth, local_time)
        hp_theta, hp_phi = equatorial_to_healpy(ra, dec)
        pix = hp.ang2pix(n_side, hp_theta, hp_phi)
        data_skymap[pix] += 1

        # Reference skymap
        rand_times = np.random.choice(times, size=n_resamples)
        ra, dec = astro.dir_to_equa(local_zenith, local_azimuth, rand_times)
        hp_theta, hp_phi = equatorial_to_healpy(ra, dec)
        ref_skymap = add_to_skymap(hp_theta, hp_phi, ref_skymap,
                                   n_side=n_side, weights=1/n_resamples)

    return data_skymap, ref_skymap, local_skymap
Beispiel #3
0
def get_coords():
	ra86I_sim,dec86I_sim=astro.dir_to_equa(zen86I_sim,azi86I_sim,mjd86I_sim)
	ra86I_data,dec86I_data=astro.dir_to_equa(zen86I_data,azi86I_data,mjd86I_data) 
	#scramble RA! We can't know this until unblinding. (Should I fix these in place, or renew them each time?)
	ra86I_sim = np.random.random(len(ra86I_sim))*2*np.pi
	ra86I_data = np.random.random(len(ra86I_data))*2*np.pi
	return ra86I_sim, dec86I_sim , ra86I_data, dec86I_data
Beispiel #4
0
def getDecRA(d, verbose=True):

    if verbose:
        print('Calculating equatorial coordinates...')
    nevents = len(d['zenith'])
    t = dc.I3Time()
    # t = astro.Time()
    # local = astro.LocalCoord()
    # ice = astro.IceCubeDetector()
    ra, dec = np.zeros((2, nevents))

    for i in range(nevents):

        zen = d['zenith'][i]
        azi = d['azimuth'][i]
        mjd = d['mjd'][i]

        # t.set_mod_julian_time_double(mjd)
        # t.SetTime(mjd)
        # local.SetLocalRad(zen, azi)
        # eqApparent = ice.LocalToEquatorial(local, t)
        # dec[i] = eqApparent.GetDecRad()
        # ra[i]  = eqApparent.GetRaRad()
        ra, dec = astro.dir_to_equa(zen, azi, mjd)

    dec = np.pi/2. - dec
    while ra.min() < 0:
        ra[ra < 0] += 2*np.pi

    if verbose:
        print('Finished')

    return dec, ra
def gen_appendix(frame, outcsv, inputparticle="OnlineL2_SplineMPE",
                 jsonfile="AlertShortFollowupMsg", eventheader="I3EventHeader"):
    mpe = frame[inputparticle]
    header = frame[eventheader]
    info = frame[jsonfile]
    message = info.value
    time_mjd = header.start_time.mod_julian_day_double
    zen_rad = mpe.dir.zenith
    azi_rad = mpe.dir.azimuth
    ra_rad, dec_rad = astro.dir_to_equa(zen_rad, azi_rad, time_mjd)
    temp = flatten(eval(message.replace("null","None")))
    df = pd.DataFrame(temp, index=[temp["event_id"]])

    df_out = pd.DataFrame(data={"evtid":df.event_id.values[0],
                                "mjd":time_mjd,
                                "rec_x":mpe.pos.x,
                                "rec_y":mpe.pos.y,
                                "rec_z":mpe.pos.z,
                                "rec_t0":mpe.time,
                                "zen_rad":zen_rad,
                                "azi_rad":azi_rad,
                                "ra_rad":ra_rad,
                                "dec_rad":dec_rad},
                          index=df.run_id)
    df_out.to_csv(outcsv, header=False)
Beispiel #6
0
def make_skymaps(df, times, n_side=64, verbose=False):

    if not isinstance(df, pd.DataFrame):
        raise ValueError('df must be a pandas DataFrame')
    if not isinstance(times, np.ndarray):
        raise ValueError('times must be a numpy array')
    if not df.shape[0] == times.shape[0]:
        raise ValueError('df and times are not compatible')

    n_pix = hp.nside2npix(n_side)
    data_skymap = np.zeros(n_pix, dtype=float)
    ref_skymap = np.zeros(n_pix, dtype=float)
    local_skymap = np.zeros(n_pix, dtype=float)

    for idx, row in df.iterrows():
        local_zenith = row['lap_zenith']
        local_azimuth = row['lap_azimuth']
        local_time = row['start_time_mjd']

        # Local skymap
        pix = hp.ang2pix(n_side, local_zenith, local_azimuth)
        local_skymap[pix] += 1

        # Data skymap
        ra, dec = astro.dir_to_equa(local_zenith, local_azimuth, local_time)
        hp_theta, hp_phi = equatorial_to_healpy(ra, dec)
        pix = hp.ang2pix(n_side, hp_theta, hp_phi)
        data_skymap[pix] += 1

        # Reference skymap
        rand_times = times[idx]
        n_resamples = len(rand_times)
        ra, dec = astro.dir_to_equa(local_zenith, local_azimuth, rand_times)
        hp_theta, hp_phi = equatorial_to_healpy(ra, dec)
        ref_skymap = add_to_skymap(hp_theta,
                                   hp_phi,
                                   ref_skymap,
                                   n_side=n_side,
                                   weights=1 / n_resamples)

    return data_skymap, ref_skymap, local_skymap
def oversample(tmp_weight, tmp_nu_type,
               tmp_energy_true, tmp_energy_reco,
               tmp_zenith_true, tmp_zenith_reco,
               tmp_azimuth_true, tmp_azimuth_reco,
               nOversampling):
    
    stime = time.mktime(time.strptime("1/1/2022/00/00/00", '%m/%d/%Y/%H/%M/%S'))
    etime = time.mktime(time.strptime("1/1/2023/00/00/00", '%m/%d/%Y/%H/%M/%S'))
    
    
    oversampled_psi_true = np.zeros((nOversampling,len(tmp_weight)))
    oversampled_psi_reco = np.zeros((nOversampling,len(tmp_weight)))
    
    oversampled_RA_reco = np.zeros((nOversampling,len(tmp_weight)))
    oversampled_Dec_reco = np.zeros((nOversampling,len(tmp_weight)))


    for i in range(nOversampling):

        eventTime = stime + random.random() * (etime - stime)
        eventTime = apTime(eventTime,format='unix').mjd

        RA_true, DEC_true = astro.dir_to_equa(tmp_zenith_true,tmp_azimuth_true,eventTime)
        RA_reco, DEC_reco = astro.dir_to_equa(tmp_zenith_reco,tmp_azimuth_reco,eventTime)

        oversampled_psi_true[i] = astro.angular_distance(RA_true,DEC_true,GC_Pos[0],GC_Pos[1])
        oversampled_psi_reco[i] = astro.angular_distance(RA_reco,DEC_reco,GC_Pos[0],GC_Pos[1])

        oversampled_RA_reco[i] = RA_reco
        oversampled_Dec_reco[i] = DEC_reco
        
        
    # append n versions
    oversampled_weight = np.tile(tmp_weight/nOversampling,nOversampling)
    oversampled_nu_type = np.tile(tmp_nu_type,nOversampling)
    oversampled_energy_true = np.tile(tmp_energy_true,nOversampling)
    oversampled_energy_reco = np.tile(tmp_energy_reco,nOversampling)

    return oversampled_weight, oversampled_nu_type, oversampled_energy_true, oversampled_energy_reco, oversampled_psi_true.flatten(), oversampled_psi_reco.flatten(), oversampled_RA_reco.flatten() , oversampled_Dec_reco.flatten()
Beispiel #8
0
def extract_MC_truth(state_dict):
    if "GCDQp_packet" not in state_dict:
        raise RuntimeError("GCDQp_packet not found in state_dict")
    frame_packet = state_dict["GCDQp_packet"]

    p_frame = frame_packet[-1]
    if p_frame.Stop != icetray.I3Frame.Stream(
            'p') and p_frame.Stop != icetray.I3Frame.Physics:
        raise RuntimeError("last frame of GCDQp is neither Physics not 'p'")

    q_frame = frame_packet[-2]
    if q_frame.Stop != icetray.I3Frame.DAQ:
        raise RuntimeError("second to last frame of GCDQp is not type Q")

    if "I3MCTree_preMuonProp" not in q_frame:
        return state_dict
    mc_tree = q_frame["I3MCTree_preMuonProp"]

    # find the muon
    muon = None
    for particle in mc_tree:
        if particle.type not in [
                dataclasses.I3Particle.ParticleType.MuPlus,
                dataclasses.I3Particle.ParticleType.MuMinus
        ]:
            continue
        if muon is not None:
            print("More than one muon in MCTree")
            if particle.energy < muon.energy: continue
        muon = particle

    if muon is None:
        # must be NC
        return state_dict

    # get event time
    mjd = get_event_mjd(state_dict)

    # convert to RA and dec
    ra, dec = astro.dir_to_equa(muon.dir.zenith, muon.dir.azimuth, mjd)
    ra = float(ra)
    dec = float(dec)
    dec = dec

    state_dict['MCradec'] = (ra, dec)

    return state_dict
Beispiel #9
0
parser = argparse.ArgumentParser(
    description='Calculate opening angle between monopod and pegleg')
parser.add_argument('--infile',
                    type=str,
                    required=True,
                    help='Numpy file to read in')
args = parser.parse_args()

from numpy.lib.recfunctions import append_fields

neutrinos = np.load(args.infile)

mzens = neutrinos['monopod_zen'].astype(float)
mazis = neutrinos['monopod_azi'].astype(float)
times = neutrinos['time'].astype(float)
monopod_ra, monopod_dec = astro.dir_to_equa(mzens, mazis, times)

monopod_pegleg_dpsi = hp.rotator.angdist(
    [np.rad2deg(neutrinos['ra']),
     np.rad2deg(neutrinos['dec'])],
    [np.rad2deg(monopod_ra), np.rad2deg(monopod_dec)],
    lonlat=True)

newsavefile = append_fields(neutrinos, 'monopod_ra', monopod_ra, usemask=False)
newsavefile = append_fields(newsavefile,
                            'monopod_dec',
                            monopod_dec,
                            usemask=False)
newsavefile = append_fields(newsavefile,
                            'monopod_pegleg_dpsi',
                            monopod_pegleg_dpsi,
Beispiel #10
0
                    required=True,
                    help='Numpy file to read in')
args = parser.parse_args()

from numpy.lib.recfunctions import append_fields

neutrinos = np.load(args.infile)
true_dpsi = hp.rotator.angdist(
    [np.rad2deg(neutrinos['ra']),
     np.rad2deg(neutrinos['dec'])],
    [np.rad2deg(neutrinos['trueRa']),
     np.rad2deg(neutrinos['trueDec'])],
    lonlat=True)

monopod_ra, monopod_dec = astro.dir_to_equa(
    neutrinos['monopod_zen'].astype(float),
    neutrinos['monopod_azi'].astype(float), neutrinos['time'].astype(float))

monopod_pegleg_dpsi = hp.rotator.angdist(
    [np.rad2deg(neutrinos['ra']),
     np.rad2deg(neutrinos['dec'])],
    [np.rad2deg(monopod_ra), np.rad2deg(monopod_dec)],
    lonlat=True)

newsavefile = append_fields(neutrinos, 'monopod_ra', monopod_ra, usemask=False)
newsavefile = append_fields(newsavefile,
                            'monopod_dec',
                            monopod_dec,
                            usemask=False)
newsavefile = append_fields(newsavefile,
                            'monopod_pegleg_dpsi',
Beispiel #11
0
from load_model import *

parser = argparse.ArgumentParser(
    description='Calculate opening angle between monopod and pegleg')
parser.add_argument('--infiles',
                    type=str,
                    required=True,
                    help='Numpy file to read in')
args = parser.parse_args()

infiles = glob(args.infiles)
for infile in infiles:
    events = np.load(infile)

    monopod_ra, monopod_dec = astro.dir_to_equa(
        events['monopod_zen'].astype(float),
        events['monopod_azi'].astype(float), events['time'].astype(float))

    monopod_pegleg_dpsi = hp.rotator.angdist(
        [np.rad2deg(events['ra']),
         np.rad2deg(events['dec'])],
        [np.rad2deg(monopod_ra),
         np.rad2deg(monopod_dec)],
        lonlat=True)

    #Add some fields to the numpy recarray
    appended_events = append_fields(events,
                                    'monopod_ra',
                                    monopod_ra,
                                    usemask=False)
    appended_events = append_fields(appended_events,