Exemplo n.º 1
0
def rotate_map_inv(Imag,
                   a1,
                   a2,
                   a3,
                   X=True,
                   Y=False,
                   ZYX=False,
                   deg=False,
                   nested=False):
    npix = np.shape(Imag)[0]
    nside = npix2nside(npix)
    indices = np.arange(0, npix)
    ang_coord = pix2vec(nside, indices, nested)
    ang_coord_array = np.vstack((ang_coord[0], ang_coord[1], ang_coord[2]))
    eul = np.linalg.inv(
        euler_matrix_new(a1, a2, a3, X=X, Y=Y, ZYX=ZYX, deg=deg))
    new_coord = np.dot(eul, ang_coord_array)
    theta_arr, phi_arr = vec2ang(new_coord.T)
    neigh, weigh = get_interp_weights(nside,
                                      theta_arr,
                                      phi=phi_arr,
                                      nest=nested,
                                      lonlat=False)
    thr_val = 1e-8
    weigh[np.where(np.abs(weigh) < thr_val)] = 0
    weigh = weigh / np.sum(weigh, axis=0)
    rotIm = np.zeros_like(Imag)
    for k in range(neigh.shape[0]):
        rotIm = rotIm + weigh[k] * Imag[neigh[k]]
    return rotIm
Exemplo n.º 2
0
def find_pointon_healpxs(ra_poi, dec_poi, ang_cut, nhpside=512):
    NPIX = hppf.nside2npix(nhpside)
#    MAX_PIX_DEG = degrees(hppf.max_pixrad(nhpside))
    RADEC_POI = [radians(ra_poi), radians(dec_poi)]
    VEC_POI = hppf.ang2vec(pi/2.-RADEC_POI[1], RADEC_POI[0])
    ar_pix_incl = []
    ang_cut_rad = radians(ang_cut)
    for ipix in range(NPIX):
        vec = hppf.pix2vec(nhpside, ipix)
        ang_dist = get_ang_dist_vectors(VEC_POI, vec)
        if ang_dist<ang_cut_rad:
            ar_pix_incl.append(ipix)
    return ar_pix_incl
Exemplo n.º 3
0
def rotate_map(Imag,
               a1,
               a2,
               a3,
               X=True,
               Y=False,
               ZYX=False,
               deg=False,
               nested=False):
    # X :   rotation a1 around original Z
    #       rotation a2 around interm   X
    #       rotation a3 around final    Z
    #            DEFAULT,  classical mechanics convention

    #  Y :  rotation a1 around original Z
    #       rotation a2 around interm   Y
    #       rotation a3 around final    Z
    #            quantum mechanics convention (override X)

    #  ZYX :rotation a1 around original Z
    #       rotation a2 around interm   Y
    #       rotation a3 around final    X
    #            aeronautics convention (override X)
    #  * these last three keywords are obviously mutually exclusive *

    npix = np.shape(Imag)[0]
    nside = npix2nside(npix)
    indices = np.arange(0, npix)
    ang_coord = pix2vec(nside, indices, nested)
    ang_coord_array = np.vstack((ang_coord[0], ang_coord[1], ang_coord[2]))
    eul = euler_matrix_new(a1, a2, a3, X=X, Y=Y, ZYX=ZYX, deg=deg)
    new_coord = np.dot(eul, ang_coord_array)
    theta_arr, phi_arr = vec2ang(new_coord.T)
    neigh, weigh = get_interp_weights(nside,
                                      theta_arr,
                                      phi=phi_arr,
                                      nest=nested,
                                      lonlat=False)
    thr_val = 1e-8
    weigh[np.where(np.abs(weigh) < thr_val)] = 0
    weigh = weigh / np.sum(weigh, axis=0)
    rotIm = np.zeros_like(Imag)
    for k in range(neigh.shape[0]):
        rotIm = rotIm + weigh[k] * Imag[neigh[k]]
    return rotIm
Exemplo n.º 4
0
    infoubl = info['ubl'].dot([[4, 0, 0], [0, 15, 0], [0, 0, 0]])
    calfile = 'psa6240_v003'
    ######get array  information and accurate ubl vectors
    aa = ap.cal.get_aa(calfile, np.array([freq / 1000.]))

    ######load beam
    nsideB = 8
    Bl = nsideB * 3 - 1

    beam_healpix = np.zeros(12 * nsideB**2, dtype='float32')
    if pol[0] != pol[-1]:
        raise Exception(
            'ERROR: polarization string %s not supported in the code.' % pol)
    for i in range(12 * nsideB**2):
        beam_healpix[i] = aa[0].bm_response(
            sv.rotatez_matrix(-np.pi / 2).dot(hpf.pix2vec(nsideB, i)), pol[0]
        )[0]  #in paper's bm_response convention, (x,y) = (0,1) points north.
else:
    raise Exception('Cant tell if the iinfo is for PAPER or MITEoR')

vs.initial_zenith = np.array([0, lat_degree * np.pi / 180])  #self.zenithequ
beam_heal_equ = np.array(
    sv.rotate_healpixmap(beam_healpix, 0, np.pi / 2 - vs.initial_zenith[1],
                         vs.initial_zenith[0]))
timer = time.time()

if all_ubl:
    ubls = infoubl
else:
    ubls = [
        ubl for ubl in infoubl
######load beam
bnside = 64
beam_freqs = np.arange(110., 195., 5.)
print "Reading calfile %s..."%calfile,
sys.stdout.flush()

######cal file loaded
aa = ap.cal.get_aa(calfile, beam_freqs/1000.)
print "Done. Antenna layout:"
print aa.ant_layout
sys.stdout.flush()


beam_healpix = np.zeros((len(beam_freqs), 2, 12*bnside**2), dtype='float32')

healpixvecs = np.array(hpf.pix2vec(bnside, range(12*bnside**2)))
paper_healpixvecs = (healpixvecs[:, healpixvecs[2]>=0]).transpose().dot(sv.rotatez_matrix(-np.pi/2).transpose())#in paper's bm_response convention, (x,y) = (0,1) points north.
for p, pol in enumerate(['x', 'y']):
    for i, paper_angle in enumerate(paper_healpixvecs):
        beam_healpix[:, p, i] = (aa[0].bm_response(paper_angle, pol)**2.).flatten()

local_beam_unpol = si.interp1d(beam_freqs, beam_healpix, axis=0)

freq = 110.
for p in range(2):
    plt.subplot(2, 1, p+1)
    plt.plot(hpf.get_interp_val(local_beam_unpol(freq)[p], np.arange(0, PI/2, .01), 0))
    plt.plot(hpf.get_interp_val(local_beam_unpol(freq)[p], np.arange(0, PI/2, .01), PI/2))
plt.show()

    raise Exception('PSA point source not yet programmed.')
    lat_degree = -(30.+ 43./60. + 17.5/3600.)
    infoubl = info['ubl'].dot([[4,0,0],[0,15,0],[0,0,0]])
    calfile = 'psa6240_v003'
    ######get array  information and accurate ubl vectors
    aa = ap.cal.get_aa(calfile, np.array([freq/1000.]))

    ######load beam
    nsideB = 8
    Bl = nsideB*3 - 1

    beam_healpix = np.zeros(12*nsideB**2, dtype='float32')
    if pol[0] != pol[-1]:
        raise Exception('ERROR: polarization string %s not supported in the code.'%pol)
    for i in range(12*nsideB**2):
        beam_healpix[i] = aa[0].bm_response(sv.rotatez_matrix(-np.pi/2).dot(hpf.pix2vec(nsideB, i)), pol[0])[0]#in paper's bm_response convention, (x,y) = (0,1) points north.
else:
    raise Exception('Cant tell if the iinfo is for PAPER or MITEoR')

vs.initial_zenith = np.array([0, lat_degree*np.pi/180])#self.zenithequ
beam_heal_equ = np.array(sv.rotate_healpixmap(beam_healpix, 0, np.pi/2 - vs.initial_zenith[1], vs.initial_zenith[0]))
timer = time.time()

if all_ubl:
    ubls = infoubl
else:
    ubls = [ubl for ubl in infoubl if la.norm(ubl) < inclusion_thresh * (nside_target * 299.792458 / freq)]
print "%i UBLs to include"%len(ubls)

if len(tlist)*len(ubls) < 12*nside**2:
    for i in range(5):
Exemplo n.º 7
0
    pretty_fig(4)
    peak_rs, peak_heights = kde_peak_heights(ipix, r_bins, h, (0, max_r))
    plt.plot(peak_rs, peak_heights, "wo")
    r_cut = 1.3 * mode_radius(rs)
    plt.plot(peak_rs[peak_rs < r_cut], peak_heights[peak_rs < r_cut], "ro")
    plt.xlabel(r"$r_{\rm KDE}$ [Mpc/$h$]")
    plt.ylabel(r"$h_{\rm KDE}$")
    plt.title(r"KDE Peak Locations")

    valid_peaks = peak_heights > 0

    N = 2
    ipix = np.arange(npix)[valid_peaks]
    peak_rs = peak_rs[valid_peaks]
    kde_xs, kde_ys, kde_zs = pf.pix2vec(nside, ipix) * peak_rs
    c_ijks = penna_coeff(N, kde_xs, kde_ys, kde_zs)

    cut_ipix = ipix[peak_rs < r_cut]
    cut_peak_rs = peak_rs[peak_rs < r_cut]
    cut_kde_xs,cut_kde_ys,cut_kde_zs = pf.pix2vec(nside,cut_ipix)*cut_peak_rs
    cut_cijks = penna_coeff(N, cut_kde_xs, cut_kde_ys, cut_kde_zs)

    cut_raw_cijks = penna_coeff(N, xs[rs<r_cut], ys[rs<r_cut], zs[rs<r_cut])
    raw_cijks = penna_coeff(N, xs, ys, zs)


    for n, plane_fname in enumerate([x_plane_fname,
                                     y_plane_fname,
                                     z_plane_fname]):
        pretty_fig(n)
sys.exit(0)
#clean
bright_points = {'cyg':{'ra': '19:59:28.3', 'dec': '40:44:02'}, 'cas':{'ra': '23:23:26', 'dec': '58:48:00'}}
pt_source_range = PI / 40
smooth_scale = PI / 30
pt_source_neighborhood_range = [smooth_scale, PI / 9]
bright_pt_mask = np.zeros(Ashape1, dtype=bool)
bright_pt_neighborhood_mask = np.zeros(Ashape1, dtype=bool)
for source in bright_points.keys():
    bright_points[source]['body'] = ephem.FixedBody()
    bright_points[source]['body']._ra = bright_points[source]['ra']
    bright_points[source]['body']._dec = bright_points[source]['dec']
    theta = PI / 2 - bright_points[source]['body']._dec
    phi = bright_points[source]['body']._ra
    pt_coord = np.array([np.sin(theta) * np.cos(phi), np.sin(theta) * np.sin(phi), np.cos(theta)])
    sky_vecs = np.array(hpf.pix2vec(nside_start, np.arange(hpf.nside2npix(nside_start)), nest=True))[:, valid_pix_mask]
    bright_pt_mask = bright_pt_mask | (la.norm(sky_vecs - pt_coord[:, None], axis=0) < pt_source_range)
    bright_pt_neighborhood_mask = bright_pt_neighborhood_mask | (la.norm(sky_vecs - pt_coord[:, None], axis=0) >= pt_source_neighborhood_range[0])
    bright_pt_neighborhood_mask = bright_pt_neighborhood_mask | (la.norm(sky_vecs - pt_coord[:, None], axis=0) <= pt_source_neighborhood_range[1])

raw_psf = psf[:, bright_pt_mask]
cleaned_result2 = np.copy(result[bright_pt_mask])
cleaned_accumulate = np.zeros_like(cleaned_result2)
# clean_stop = 10**3.5 * np.median(sizes)#2 * np.min(np.abs(cleaned_result2))
step_size = 0.02
while np.max(np.abs(cleaned_result2)) > np.median(np.abs(cleaned_result2)) * 1.1:
    clean_pix = np.argmax(np.abs(cleaned_result2))
    cleaned_accumulate[clean_pix] += step_size * cleaned_result2[clean_pix]
    cleaned_result2 -= step_size * cleaned_result2[clean_pix] * raw_psf[bright_pt_mask, clean_pix]
cleaned_result2 = result - raw_psf.dot(cleaned_accumulate)
plot_IQU(result, 'Simulated Dirty Map (Log(K))', 1, shape=(2, 1), coord='cg')
Exemplo n.º 9
0
    pretty_fig(4)
    peak_rs, peak_heights = kde_peak_heights(ipix, r_bins, h, (0, max_r))
    plt.plot(peak_rs, peak_heights, "wo")
    r_cut = 1.3 * mode_radius(rs)
    plt.plot(peak_rs[peak_rs < r_cut], peak_heights[peak_rs < r_cut], "ro")
    plt.xlabel(r"$r_{\rm KDE}$ [Mpc/$h$]")
    plt.ylabel(r"$h_{\rm KDE}$")
    plt.title(r"KDE Peak Locations")

    valid_peaks = peak_heights > 0

    N = 2
    ipix = np.arange(npix)[valid_peaks]
    peak_rs = peak_rs[valid_peaks]
    kde_xs, kde_ys, kde_zs = pf.pix2vec(nside, ipix) * peak_rs
    c_ijks = penna_coeff(N, kde_xs, kde_ys, kde_zs)

    cut_ipix = ipix[peak_rs < r_cut]
    cut_peak_rs = peak_rs[peak_rs < r_cut]
    cut_kde_xs, cut_kde_ys, cut_kde_zs = pf.pix2vec(nside,
                                                    cut_ipix) * cut_peak_rs
    cut_cijks = penna_coeff(N, cut_kde_xs, cut_kde_ys, cut_kde_zs)

    cut_raw_cijks = penna_coeff(N, xs[rs < r_cut], ys[rs < r_cut],
                                zs[rs < r_cut])
    raw_cijks = penna_coeff(N, xs, ys, zs)

    for n, plane_fname in enumerate(
        [x_plane_fname, y_plane_fname, z_plane_fname]):
        pretty_fig(n)
    vartag = '_lstbineven_avg4'
    datadir = '/home/omniscope/data/PAPER/lstbin_fg/even/'
    antpairs = None


    #cal file
    calfile = 'psa6622_v002'
    print "Reading calfile %s..."%calfile,
    sys.stdout.flush()
    aa = ap.cal.get_aa(calfile, beam_freqs/1000.)
    print "Done."
    sys.stdout.flush()

    bnside = 64
    beam_healpix = np.zeros((len(beam_freqs), 2, 12*bnside**2), dtype='float32')
    healpixvecs = np.array(hpf.pix2vec(bnside, range(12*bnside**2)))
    paper_healpixvecs = (healpixvecs[:, healpixvecs[2]>=0]).transpose().dot(sv.rotatez_matrix(-np.pi/2).transpose())#in paper's bm_response convention, (x,y) = (0,1) points north.
    for p, pol in enumerate(['x', 'y']):
        for i, paper_angle in enumerate(paper_healpixvecs):
            beam_healpix[:, p, i] = (aa[0].bm_response(paper_angle, pol)**2.).flatten()

    local_beam_unpol = si.interp1d(beam_freqs, beam_healpix, axis=0)
tag = INSTRUMENT + '_%.2fMHz'%freq
data_tag = 'sim'
vartag = '%.2e'%(bw * deltat)
print '#####################################################'
print '###############',tag,'###########'
print '#####################################################'
A_version = 1.0
nf = 1
# data_filename = glob.glob(datadir + tag + '_xx_*_*' + datatag)[0]

bright_points = {'cyg':{'ra': '19:59:28.3', 'dec': '40:44:02'}, 'cas':{'ra': '23:23:26', 'dec': '58:48:00'}}
pt_source_range = PI / 60
smooth_scale = PI / 30
pt_source_neighborhood_range = [smooth_scale, PI / 9]
bright_pt_mask = np.zeros(npix_nonzero, dtype=bool)
bright_pt_neighborhood_mask = np.zeros(npix_nonzero, dtype=bool)
for source in bright_points.keys():
    bright_points[source]['body'] = ephem.FixedBody()
    bright_points[source]['body']._ra = bright_points[source]['ra']
    bright_points[source]['body']._dec = bright_points[source]['dec']
    theta = PI / 2 - bright_points[source]['body']._dec
    phi = bright_points[source]['body']._ra
    pt_coord = np.array([np.sin(theta) * np.cos(phi), np.sin(theta) * np.sin(phi), np.cos(theta)])
    sky_vecs = np.array(hpf.pix2vec(nside, np.arange(hpf.nside2npix(nside)), nest=True))[:, total_mask]
    bright_pt_mask = bright_pt_mask | (la.norm(sky_vecs - pt_coord[:, None], axis=0) < pt_source_range)
    bright_pt_neighborhood_mask = bright_pt_neighborhood_mask | (la.norm(sky_vecs - pt_coord[:, None], axis=0) >= pt_source_neighborhood_range[0])
    bright_pt_neighborhood_mask = bright_pt_neighborhood_mask | (la.norm(sky_vecs - pt_coord[:, None], axis=0) <= pt_source_neighborhood_range[1])
AtNiA_sum = np.fromfile(AtNiA_filename, dtype='float64')
AtNiA_sum.shape = (npix_nonzero, npix_nonzero)
raw_psf_name = AtNiAi_filename + '_rawPSF_ptrange%.3f'%pt_source_range
if os.path.isfile(raw_psf_name):
    raw_psf = np.fromfile(raw_psf_name, dtype='float64')
    raw_psf.shape = (npix_nonzero, np.sum(bright_pt_mask))
else:
    print "Computing PSFs...",
    sys.stdout.flush()
    timer = time.time()
    raw_psf = AtNiAi.dot(AtNiA_sum[:, bright_pt_mask])
    print "%.1f min."%((time.time() - timer) / 60.)
elif 'PSA' in infofile:
    lat_degree = -(30.+ 43./60. + 17.5/3600.)
    infoubl = info['ubl'].dot([[4,0,0],[0,15,0],[0,0,0]])
    calfile = 'psa6240_v003'
    ######get array  information and accurate ubl vectors
    aa = ap.cal.get_aa(calfile, np.array([freq/1000.]))

    ######load beam
    nsideB = 8
    Bl = nsideB*3 - 1

    beam_healpix = np.zeros(12*nsideB**2, dtype='float32')
    if pol[0] != pol[-1]:
        raise Exception('ERROR: polarization string %s not supported in the code.'%pol)
    for i in range(12*nsideB**2):
        beam_healpix[i] = aa[0].bm_response(sv.rotatez_matrix(-np.pi/2).dot(hpf.pix2vec(nsideB, i)), pol[0])[0]#in paper's bm_response convention, (x,y) = (0,1) points north.
else:
    raise Exception('Cant tell if the iinfo is for PAPER or MITEoR')

vs.initial_zenith = np.array([0, lat_degree*np.pi/180])#self.zenithequ
beam_heal_equ = np.array(sv.rotate_healpixmap(beam_healpix, 0, np.pi/2 - vs.initial_zenith[1], vs.initial_zenith[0]))
timer = time.time()

if all_ubl:
    ubls = infoubl
else:
    ubls = [ubl for ubl in infoubl if la.norm(ubl) < inclusion_thresh * (nside_target * 299.792458 / freq)]
print "%i UBLs to include"%len(ubls)

if len(tlist)*len(ubls) < 12*nside**2:
    for i in range(5):
#####get ubl information########
#calibrator = omni.RedundantCalibrator_PAPER(aa)
#ubls = calibrator.compute_redundantinfo()
ubls = np.array([[0,0,0]])
unit_ubls = np.round(ubls)
######construct visibility_simulatorplt.imshow()a
vs = sv.Visibility_Simulator()
vs.initial_zenith = np.array([initial_lst, aa.lat])

######load beam
nsideB = 32
Bl = nsideB*3 - 1

beam_healpix = np.zeros((len(freqs),12*nsideB**2), dtype='float32')

healpixvecs = np.array(hpf.pix2vec(nsideB, range(12*nsideB**2)))
for i, paper_angle in enumerate((healpixvecs[:, healpixvecs[2]>=0]).transpose().dot(sv.rotatez_matrix(-np.pi/2).transpose())):#in paper's bm_response convention, (x,y) = (0,1) points north.
    beam_healpix[:, i] = (aa[0].bm_response(paper_angle, pol[0]) * aa[0].bm_response(paper_angle, pol[1])).flatten()

#hpv.mollview(beam_healpix[0], title='PAPER_beam')
#plt.show()
#exit()

######load GSM weights
gsm_weights = np.loadtxt(datadir + '/components.dat')
gsm_weight0_f = si.interp1d(np.log(gsm_weights[:,0]), np.log(gsm_weights[:,1]), kind = 'linear', axis = 0)
gsm_weights_f = si.interp1d(gsm_weights[:,0], gsm_weights[:,2:], kind = 'linear', axis = 0)
#for i in range(4):
    #plt.plot(np.log(gsm_weights[:,0]), [gsm_weights_f(np.log(freq))[i]/gsm_weights_f(np.log(45))[i] for freq in gsm_weights[:,0]])
#plt.show()