def hp_fits(num_v, ths, phs, nside=64, toy=False):
    xs = FB8Distribution.spherical_coordinates_to_nu(ths, phs)
    z, x, y = xs.T
    s_index = np.random.choice(xs.shape[0], 10000, replace=False)
    s_ths = [ths[i] for i in s_index]
    s_phs = [phs[i] for i in s_index]

    fit8 = fb8_mle(xs, True)
    hp_plot_fb8(fit8, nside)
    hp.projscatter(s_ths, s_phs, marker='.', linewidths=0, s=5, c='k')
    ax = plt.gca()
    ax.annotate(r"$\bf{-180^\circ}$", xy=(1.7, 0.625), size="medium")
    ax.annotate(r"$\bf{180^\circ}$", xy=(-1.95, 0.625), size="medium")
    ax.annotate("Galactic",
                xy=(0.8, -0.05),
                size="medium",
                xycoords="axes fraction")
    if toy:
        plt.savefig('figs/{}_toy_fb8.pdf'.format(num_v))
    else:
        plt.savefig('figs/{}_fb8.pdf'.format(num_v))
    plt.clf()
    plt.close('all')
    gc.collect()
    return fit8
Пример #2
0
def animation_path(sched,rot,title,*args, **kwargs):
    vid_title = "videos/"+title + ".mp4"
    hpy.mollview(title=title,rot=rot)
    hpy.graticule(verbose=0)
    points = hpy.projscatter(np.pi/2-sched[:,1],sched[:,0],lonlat=False,cmap="hsv",c=np.arange(np.size(sched,0)),*args, **kwargs)
    offto = points.get_offsets()
    arrayto = points.get_array()
    climto = points.get_clim()
    cmapto = points.get_cmap()

    plt.clf()
    hpy.mollview(title=title,rot=rot)
    hpy.graticule(verbose=0)
    points = hpy.projscatter([],[],lonlat=False,*args, **kwargs)
    fig = points.get_figure()
    points.set_clim(climto)
    points.set_cmap(cmapto)

    def animate(i,data,color):
        start_data = max(0,i-300)
        # start_data = 0
        points.set_offsets(data[start_data:i,:])
        points.set_array(color[start_data:i])
        return points,

    anim = animation.FuncAnimation(fig, animate,fargs=(offto,arrayto),frames=np.size(offto,0), interval=20, blit=True)
    anim.save(vid_title)
Пример #3
0
def hp_fits(ths, phs, nside=64):
    import healpy as hp
    xs = FB8Distribution.spherical_coordinates_to_nu(ths, phs)
    z, x, y = xs.T
    fit5 = fb8_mle(xs, True, fb5_only=True)
    hp_plot_fb8(fit5, nside)
    hp.projscatter(ths, phs, marker='.', linewidths=0, s=5, c='k')
    ax = plt.gca()
    ax.annotate(r"$\bf{-180^\circ}$", xy=(1.7, 0.625), size="medium")
    ax.annotate(r"$\bf{180^\circ}$", xy=(-1.95, 0.625), size="medium")
    ax.annotate("Galactic",
                xy=(0.8, -0.05),
                size="medium",
                xycoords="axes fraction")
    plt.savefig('figs/Fig5_fb5.png')

    fit8 = fb8_mle(xs, True)
    hp_plot_fb8(fit8, nside)
    hp.projscatter(ths, phs, marker='.', linewidths=0, s=5, c='k')
    ax = plt.gca()
    ax.annotate(r"$\bf{-180^\circ}$", xy=(1.7, 0.625), size="medium")
    ax.annotate(r"$\bf{180^\circ}$", xy=(-1.95, 0.625), size="medium")
    ax.annotate("Galactic",
                xy=(0.8, -0.05),
                size="medium",
                xycoords="axes fraction")
    plt.savefig('figs/Fig5_fb8.png')
Пример #4
0
def graphtargets(info, targets, skymap):
    "Generate a graph with the targets generated over the sky map"
    import healpy as hp
    from io import BytesIO
    import matplotlib.pyplot as plt

    aligo_banana = hp.read_map(skymap)
    numfig = 1
    fig = plt.figure(numfig, figsize=(10, 5))
    graph_title = "{} -{}-{}\nBayestar Prob. Sky Map with Targets".format(
        info["graceid"], info["pkt_ser_num"], info["alerttype"])
    hp.mollview(
        aligo_banana,
        title=graph_title,
        flip="astro",
        unit="$\Delta$",
        fig=numfig,
        cmap=plt.cm.gist_heat_r,
    )
    fig.axes[1].texts[0].set_fontsize(8)

    for obs in targets:
        ra_pointings = np.array(obs["targets"]["RA"])
        dec_pointings = np.array(obs["targets"]["Dec"])
        hp.projscatter(ra_pointings,
                       dec_pointings,
                       lonlat=True,
                       color="green",
                       marker=".")
    hp.graticule()

    graphIO = BytesIO()
    plt.savefig(graphIO)
    return graphIO.getvalue()
Пример #5
0
    def compute_visibility(self):
        #       coord=SkyCoord(ra.flatten(),dec.flatten(),unit=u.deg)
        #       m=Visibility().for_time("2016-10-09T17:31:06",coord=coord)

        #      figure(figsize=(20,10))
        #      scatter(ra,dec,s=100,c=m,lw=0,alpha=0.4)

        visibility = Visibility()

        gwm = healpy.read_map(rootd + "/" + self.skymap)
        nsides = healpy.npix2nside(gwm.shape[0])
        vmap = visibility.for_time(self.utc, nsides=nsides)

        healpy.mollview(
            gwm * (vmap * 2 - 1),
            title="visibility for INTEGRAL due to sun constrains\n" + self.utc)

        healpy.projscatter(self.ra, self.dec, lonlat=True)
        healpy.graticule()
        plot.plot(self.dir + "/visibility.png")

        healpy.write_map(self.dir + "/visibility.fits", vmap)

        source_theta = (90 - self.dec) / 180 * pi
        source_phi = (self.ra) / 180 * pi

        visibility = dict(probability_visible=sum(gwm * vmap),
                          source_visible=vmap[healpy.ang2pix(
                              nsides, source_theta, source_phi)])

        json.dump(visibility, open(self.dir + "/visibility.json", "w"))
Пример #6
0
def plot_procedure(given_coords, given_color):
    gala_coords = equatorial2galactic(given_coords)
    hp.projscatter( gala_coords[:,0], gala_coords[:,1], \
                    lonlat = True, \
                    s=1, \
                    c = given_color, \
                  )
Пример #7
0
def plot_galaxies_and_density(t, p, M):
    """Plots galaxies and pixels from polar form."""
    plt.figure(1, dpi=100)
    hp.mollview(M, fig=1, nest=True, title='Density')
    plt.figure(2, dpi=100)
    hp.mollview(M*0-1, fig=2, nest=True, cbar=False, cmap=cm.binary,
        min=-1, max=1, title='Galaxies')
    hp.projscatter(t, p, marker='.', facecolor='white', s=0.1, alpha=0.9)
Пример #8
0
 def plot_zoom_with_bg_scatter(self, ind, reso=20):
     self.plot_zoom_from_map(ind, reso=reso)
     bg = self.background(ind)
     zero_msk = np.asarray(bg['ts_prior']) == 0.
     non_zero_ra = np.asarray(bg['ra'])[~zero_msk]
     non_zero_dec = np.asarray(bg['dec'])[~zero_msk]
     hp.projscatter(np.pi / 2. - non_zero_dec,
                    non_zero_ra,
                    marker='x',
                    alpha=0.5,
                    color=sns.xkcd_rgb['battleship grey'])
Пример #9
0
def selectcenter(hpmap,
                 center,
                 delta=3,
                 nside=256,
                 nest=False,
                 threshold=3,
                 displaycenters=False,
                 doplot=False):

    #return the pixel of the central peak
    npix = 12 * nside**2
    centerarr = [
        center,
        center - delta * np.array([1, 0]),
        #center - 2 * delta * np.array([1,0]),
        center + delta * np.array([1, 0]),
        #center + 2 * delta * np.array([1,0]),
        center - delta * np.array([0, 1]),
        #center - 2 * delta * np.array([0,1]),
        center + delta * np.array([0, 1])
    ]
    #center + 2 * delta * np.array([0,1])]

    fullvec = hp.pix2vec(nside, range(0, npix), nest=nest)
    relmaxpx = np.zeros((len(centerarr), ))
    px = np.zeros((len(centerarr), ), dtype=int)

    for j, icenter in enumerate(centerarr):
        ivec = hp.ang2vec(np.deg2rad(icenter[0]), np.deg2rad(icenter[1]))
        imaskpx = np.rad2deg(np.arccos(np.dot(ivec, fullvec))) < threshold
        imaskidx = np.where(imaskpx == True)[0]
        relmaxpx[j] = np.max(hpmap[imaskpx])
        px[j] = imaskidx[np.argmax(hpmap[imaskpx])]

    indxmax = np.argmax(relmaxpx)
    pixmax, newcenter = px[indxmax], centerarr[indxmax]
    if doplot:
        hp.gnomview(hpmap,
                    reso=12,
                    rot=np.array([90, 0]) - newcenter,
                    nest=nest)
        if displaycenters:
            for each in centerarr:
                hp.projscatter(np.deg2rad(each), marker='+', color='r')
        hp.projscatter(hp.pix2ang(256, pixmax, nest=nest),
                       marker='+',
                       color='r')

    return pixmax, newcenter
Пример #10
0
def plot_map_withsources(positionalmap,foregrounds):
    ps_x=[]
    ps_y=[]
    
    for j in range(np.shape(positionalmap)[0]):
        if positionalmap[j]==1:
            ps_x.append(hp.pix2ang(2048,j)[0])
            ps_y.append(hp.pix2ang(2048,j)[1])
    
    hp.mollview(foregrounds,cmap=plt.get_cmap('Blues'),max=4,min=-0.2,title='')#, title='PS detection in map, thrs='+str(threshold))
    hp.projscatter(ps_x,ps_y,s=5,color='green')
    hp.visufunc.graticule(dpar=15, dmer=30)
    print('Number of detections: '+str(len(ps_x)))
    
    plt.savefig('mollplanck75-98.png', format='png', dpi=300)
Пример #11
0
def plot_cats(cats_path_list, cats_name_list, output_path):

    color = 'mcrbgk'

    #fig = plt.figure(1, figsize=(8, 5))
    #hp.mollview(title='Galaxy Groups', fig=1, coord='G')
    #hp.graticule(dpar=30., dmer=30., coord='C')
    for i in range(len(cats_path_list)):
        cats_path = cats_path_list[i]
        cats_name = cats_name_list[i]
        fig = plt.figure(i + 1, figsize=(8, 5))
        hp.mollview(title=cats_name.replace('_', ' '), fig=i + 1, coord='G')
        hp.graticule(dpar=30., dmer=30., coord='C')
        ga = GAMA_CAT(cats_path)
        ga.catalog = cats_name
        s = 5
        if cats_name == 'galcat_6dFGPCM.dat':
            #ga.mask_bad(ga.catalog['NMEM'] )
            ga.mask_bad(ga.catalog['Z'] < 0.01)
            #ga.mask_bad(ga.catalog['NMEM']>1)
            #ga.mask_bad(ga.catalog['LOGHALOMASS']>14)
            s = ga.catalog['NMEM'] * 5
            ga.rm_masked()
        radec = np.concatenate(
            [ga.catalog['RA'][None, :], ga.catalog['DEC'][None, :]], axis=0)
        hp.projscatter(radec,
                       lonlat=True,
                       coord=['C', 'G'],
                       edgecolors=None,
                       c=color[i],
                       s=s,
                       alpha=0.1)

        z1 = ga.cmbrest_to_heliocentric(l_helio=263.85,
                                        b_helio=48.25,
                                        v_helio=368.)
        z2 = ga.cmbrest_to_heliocentric(l_helio=263.85,
                                        b_helio=48.25,
                                        v_helio=368.)

        print(z1 - z2).max()
        print(z1 - z2).min()

        plt.savefig(output_path + cats_name.replace('.dat', '.png'))

    plt.show()
Пример #12
0
 def plot_map_with_bg_scatter(self, ind):
     skymap = self.cascade_info['skymap'][ind]
     hp.mollview(skymap,
         title=f"Run {self.cascade_info['run'][ind]} " \
                 + f"Event {self.cascade_info['event'][ind]}",
         unit='Prob.')
     hp.graticule(dmer=30, dpar=30)
     bg = self.background(ind)
     zero_msk = np.asarray(bg['ts_prior']) == 0.
     non_zero_ra = np.asarray(bg['ra'])[~zero_msk]
     non_zero_dec = np.asarray(bg['dec'])[~zero_msk]
     hp.projscatter(np.pi / 2. - non_zero_dec,
                    non_zero_ra,
                    s=5,
                    marker='x',
                    alpha=0.5,
                    color=sns.xkcd_rgb['battleship grey'])
Пример #13
0
    def true_image_overlay(self, location, utc_date):
        """Plot current sky.
        Theta is colatitude and measured from North pole. 0 .. pi
         (straight up) |  el:  pi/2   | theta 0
         (horizon)     |  el:  0      | theta pi/2
        Th = pi/2 - el

        flip : {'astro', 'geo''}, optional
        Defines the convention of projection : 'astro'' (default, east towards left, west towards right) or 'geo' (east towards right, west towards left)
        """
        l_el, l_az, l_name = self.get_src_positions(location, utc_date)

        th = np.pi / 2.0 - np.array(l_el)
        l_phi = -np.array(l_az)
        # _ = [hp.projtext(i, j, n, rot=(0,90,0), color='black', weight='light', ha='left', va='center') for i, j, n in zip(th, l_phi, l_name)]
        _ = [
            hp.projtext(
                i,
                j,
                n,
                rot=(0, 90, 0),
                color="gray",
                alpha=0.8,
                weight="bold",
                ha="center",
                va="bottom",
            )
            for i, j, n in zip(th, l_phi, l_name)
        ]
        _ = [
            hp.projscatter(i, j, rot=(0, 90, 0), color="black", alpha=1.0, s=25)
            for i, j, n in zip(th, l_phi, l_name)
        ]
        _ = [
            hp.projscatter(i, j, rot=(0, 90, 0), color="white", alpha=1.0, s=10)
            for i, j, n in zip(th, l_phi, l_name)
        ]

        hp.projtext(np.pi / 2, 0.0, "N", rot=(0, 90, 0), va="top", ha="center")
        hp.projtext(np.pi / 2, -np.pi / 2.0, "E", rot=(0, 90, 0), va="center")
        hp.projtext(np.pi / 2, -np.pi, "S", rot=(0, 90, 0), ha="center")
        hp.projtext(
            np.pi / 2, -np.pi * 3.0 / 2.0, "W", rot=(0, 90, 0), ha="right", va="center"
        )
Пример #14
0
    def check_map(self, catalog=None, ra=None, dec=None):

        if self.mask is not None:
            fig = plt.figure(1, figsize=(8, 5))
            hp.mollview(self.mask, title='MASK', fig=1, coord='G')
            hp.graticule(dpar=30., dmer=30., coord='C')
            fig.delaxes(fig.axes[1])

        if self.kSZ_map is not None:
            fig = plt.figure(2, figsize=(8, 5))
            hp.mollview(self.kSZ_map, title='kSZ', fig=2, coord='G')
            hp.graticule(dpar=30., dmer=30., coord='C')
        if catalog is not None:
            radec = np.concatenate(
                [catalog['RA'][None, :], catalog['DEC'][None, :]], axis=0)
            hp.projscatter(radec,
                           lonlat=True,
                           coord=['C', 'G'],
                           edgecolors=None,
                           c='r',
                           alpha=0.01,
                           s=10)
        if ra is not None and dec is not None:
            radec = np.concatenate([ra[None, :], dec[None, :]], axis=0)
            hp.projscatter(radec,
                           lonlat=True,
                           coord='G',
                           edgecolors=None,
                           c='k',
                           alpha=0.01,
                           s=10)

        if self.kSZ_noise is not None:
            fig = plt.figure(3, figsize=(8, 5))
            hp.mollview(self.kSZ_noise, title='kSZ noise', fig=3, coord='G')
            hp.graticule(dpar=30., dmer=30., coord='E')

        if self.random_map is not None:
            fig = plt.figure(4, figsize=(8, 5))
            print self.random_map[1000:1020]
            hp.mollview(self.random_map, title='random', fig=4, coord='G')
            hp.graticule(dpar=30., dmer=30., coord='C')
Пример #15
0
def plotEq():
    hp.mollview(title="SwiftBAT 70 month Seyfert-0 Catalogue")
    hp.graticule(coord='C', color='DimGrey')
    hp.projscatter(ra, dec, coord='C')
    horizon = 90.
    hp.projtext(np.pi / 2, 0.15, s='0$^\circ$', color='DimGrey')
    hp.projtext(np.pi / 2, 2 * np.pi - 0.05, color='DimGrey', s='360$^\circ$')
    ras = np.arange(0., 361., 1.) * np.pi / 180.
    decls_1 = np.ones(len(ras)) * (180. - horizon) * np.pi / 180.
    hp.projplot(decls_1,
                ras,
                color='DimGrey',
                linewidth=1.,
                alpha=0.5,
                coord='G')
    hp.projscatter(0.0,
                   0.0,
                   color='DimGrey',
                   marker='s',
                   coord='G',
                   lonlat=True)
Пример #16
0
def plot_map_withsources(positionalmap,foregrounds):
    """
    Creates and plots the map where point sources (detections, undetected
    and spurious) are plotted in their respective positions.
    """
    true_ps_x=[]
    spur_ps_x=[]
    nondetected_ps_x=[]
    true_ps_y=[]
    spur_ps_y=[]
    nondetected_ps_y=[]
    for j in range(np.shape(positionalmap)[0]):
        if positionalmap[j]==2:
            true_ps_x.append(hp.pix2ang(2048,j)[0])
            true_ps_y.append(hp.pix2ang(2048,j)[1])
        if positionalmap[j]==1:
            nondetected_ps_x.append(hp.pix2ang(2048,j)[0])
            nondetected_ps_y.append(hp.pix2ang(2048,j)[1])
        if positionalmap[j]==-1:
            spur_ps_x.append(hp.pix2ang(2048,j)[0])
            spur_ps_y.append(hp.pix2ang(2048,j)[1])
    
    hp.mollview(foregrounds,cmap=plt.get_cmap('Blues'),max=4,min=-0.2,title='')#, title='PS location, t='+str(threshold)+r',$ S_{min}=$'+str(fluxjy)+' Jy')
    hp.projscatter(true_ps_x,true_ps_y,s=5,color='green')
    hp.projscatter(spur_ps_x,spur_ps_y,s=5,color='red')
    hp.visufunc.graticule(dpar=15, dmer=30)
    hp.projscatter(nondetected_ps_x,nondetected_ps_y,s=5,color='yellow')
    plt.savefig('pslocationscnn2.svg', format='svg')
    plt.savefig('pslocationscnn2.png', format='png', dpi=400)
    
    print('Number of true detections: '+str(len(true_ps_x)))
    print('Number of spurious: '+str(len(spur_ps_x)))
    print('Number of non-detected: '+str(len(nondetected_ps_x)))
    print('Completeness: '+str(len(true_ps_x)/(len(true_ps_x)+len(nondetected_ps_x))))
Пример #17
0
def _plot_onemap(filemaps,
                 az,
                 el,
                 phth,
                 proj_name,
                 makerotation=False,
                 angs=None):
    indxmap = 0
    if proj_name == "flat":
        plt.title("Checking coord. of peaks and display of map.")
        plt.imshow(filemaps[indxmap, :, :],
                   extent=[np.max(az),
                           np.min(az),
                           np.min(el),
                           np.max(el)])
        plt.plot(np.degrees(phth[0][indxmap, :]),
                 np.degrees(phth[1][indxmap, :]),
                 color='r',
                 marker='.',
                 linestyle='')

    elif proj_name == "healpix":
        hp.gnomview(
            filemaps[indxmap],
            min=0,
            cbar=False,  #rot = (azcen_fov, elcen_fov),
            title='Checking coord. of peaks and display of map',
            reso=10,
            rot=(0, 50))
        hp.projscatter(phth[1][indxmap, :],
                       phth[0][indxmap, :],
                       color='r',
                       marker='.')
        hp.graticule(verbose=0, alpha=0.4)

    plt.show()

    return
Пример #18
0
  def true_image_overlay(self, location, utc_date):
    '''Plot current sky.
    Theta is colatitude and measured from North pole. 0 .. pi
     (straight up) |  el:  pi/2   | theta 0
     (horizon)     |  el:  0      | theta pi/2
    Th = pi/2 - el

    flip : {'astro', 'geo''}, optional
    Defines the convention of projection : 'astro'' (default, east towards left, west towards right) or 'geo' (east towards right, west towards left)
    '''
    l_el, l_az, l_name = self.get_src_positions(location, utc_date)

    th = np.pi/2. - np.array(l_el)
    l_phi = -np.array(l_az)
    #_ = [hp.projtext(i, j, n, rot=(0,90,0), color='black', weight='light', ha='left', va='center') for i, j, n in zip(th, l_phi, l_name)]
    _ = [hp.projtext(i, j, n, rot=(0,90,0), color='gray', alpha=0.8, weight='bold', ha='center', va='bottom') for i, j, n in zip(th, l_phi, l_name)]
    _ = [hp.projscatter(i, j, rot=(0,90,0), color='black', alpha=1.0, s=25) for i, j, n in zip(th, l_phi, l_name)]
    _ = [hp.projscatter(i, j, rot=(0,90,0), color='white', alpha=1.0, s=10) for i, j, n in zip(th, l_phi, l_name)]

    hp.projtext(np.pi/2, 0., 'N', rot=(0,90,0), va='top', ha='center')
    hp.projtext(np.pi/2, -np.pi/2., 'E', rot=(0,90,0), va='center')
    hp.projtext(np.pi/2, -np.pi, 'S', rot=(0,90,0), ha='center')
    hp.projtext(np.pi/2, -np.pi*3./2., 'W', rot=(0,90,0), ha='right', va='center')
Пример #19
0
def plot_events(dec,
                ra,
                sigmas,
                src_ra,
                src_dec,
                reso,
                sigma_scale=5.,
                col='k',
                constant_sigma=False,
                same_marker=False,
                energy_size=False,
                with_mark=True,
                with_dash=False,
                label=''):
    """Adds events to a healpy zoom, get events from llh."""
    cos_ev = np.cos(dec)
    tmp = np.cos(src_ra -
                 ra) * np.cos(src_dec) * cos_ev + np.sin(src_dec) * np.sin(dec)
    dist = np.arccos(tmp)

    if sigma_scale is not None:
        sigma = np.degrees(sigmas) / sigma_scale
        sizes = 5200 * sigma**2
        if constant_sigma:
            sizes = 20 * np.ones_like(sizes)
        if with_dash:
            hp.projscatter(np.pi / 2 - dec,
                           ra,
                           marker='o',
                           linewidth=2,
                           edgecolor=col,
                           linestyle=':',
                           facecolor="None",
                           s=sizes,
                           alpha=1.0)
        else:
            hp.projscatter(np.pi / 2 - dec,
                           ra,
                           marker='o',
                           linewidth=2,
                           edgecolor=col,
                           facecolor="None",
                           s=sizes,
                           alpha=1.0)
    if with_mark:
        hp.projscatter(np.pi / 2 - dec,
                       ra,
                       marker='x',
                       linewidth=2,
                       edgecolor=col,
                       facecolor=col,
                       s=60,
                       alpha=1.0)
Пример #20
0
dec_gtest=(5,-5,5,-5)

ra_ctest=(265,265,255,255)
dec_ctest=(-35,-25,-35,-25)

#This is the actual plotting part
#If you don't specify, it's in equatorial
#Rot = 180 shifts the axis from the center to the edge
#centered by default
hp.mollview(title = 'Equatorial Map of SwiftBAT AGNs', cbar = False,
            rot = 180, notext = False, cmap=None,coord='C')
hp.graticule(coord='C', color='DimGrey')
#hp.graticule(coord='G', color='DimGrey')
py.title("SwiftBAT 70 month Seyfert-0 Catalogue - Equatorial")
#hp.projscatter(ra,dec,coord='C',lonlat=True)
hp.projscatter(ra_ctest,dec_ctest, coord='C',lonlat=True)
hp.projtext(185, 2,'180', lonlat=True, fontweight = 'bold')
hp.projtext(95, 2, '90', lonlat=True, fontweight = 'bold')
hp.projtext(275, 2, '270', lonlat=True, fontweight = 'bold')
hp.projtext(8, 2,'0', lonlat=True, fontweight = 'bold')
hp.projtext(359, 2, '360', lonlat=True, fontweight = 'bold')
hp.projtext(193, -8, 'RA (deg)', lonlat=True, fontweight = 'bold')
hp.projtext(350, 30, '30', lonlat=True, fontweight = 'bold')
hp.projtext(340, 60, '60', lonlat=True, fontweight = 'bold')
#hp.projtext(5, -5, 'Dec (deg)', lonlat=True)
hp.projtext(358, -33.5, '-30', lonlat=True, fontweight = 'bold')
hp.projtext(358, -63.5, '-60', lonlat=True, fontweight = 'bold')
ra_gplane = np.arange(0.,361.,1.)
dec_gplane = np.ones(len(ra_gplane))*(90)
hp.projplot(dec_gplane,ra_gplane, rot=180, coord='G', lonlat=True, color='DimGrey', linewidth=2., alpha=0.5)
py.savefig('/home/relethford/Documents/IceCube_Research/Plots/AGNCore/X-Ray_Catalogue/SwiftBAT_70M/equatorialmap.png')
Пример #21
0
    print(llh)

    # iterator of all-sky scan with follow up scans of most interesting points
    for i, (scan, hotspot) in enumerate(llh.all_sky_scan(nside=16, pVal=pVal_func, decRange=np.radians([-90.0, 90.0]))):
        if i > 0:
            # break after first follow up
            break

    # plot results
    hp.mollview(scan["pVal"], min=0.0, cmap=plt.cm.afmhot, rot=[-180.0, 0.0, 0.0])
    if isinstance(llh, MultiPointSourceLLH):
        for llh in llh._sams.itervalues():
            hp.projscatter(
                np.degrees(llh.exp["ra"]),
                np.degrees(np.arcsin(llh.exp["sinDec"])),
                rot=[-180.0, 0.0, 0.0],
                lonlat=True,
                marker="x",
                color=plt.gca()._get_lines.color_cycle.next(),
            )
    else:
        hp.projscatter(
            np.degrees(llh.exp["ra"]),
            np.degrees(np.arcsin(llh.exp["sinDec"])),
            rot=[-180.0, 0.0, 0.0],
            lonlat=True,
            marker="x",
            color="red",
        )

    plt.show()
Пример #22
0
def searchByDistance(nside, data, distance_modulus, ra_select, dec_select, magnitude_threshold=24.5, plot=False, fracdet=None):
    """
    Idea: 
    Send a data extension that goes to faint magnitudes, e.g., g < 24.
    Use the whole region to identify hotspots using a slightly brighter 
    magnitude threshold, e.g., g < 23, so not susceptible to variations 
    in depth. Then compute the local field density using a small annulus 
    around each individual hotspot, e.g., radius 0.3 to 0.5 deg.

    plot = True enables diagnostic plotting for testings
    fracdet corresponds to a fracdet map (numpy array, assumed to be EQUATORIAL and RING)
    """

    SCALE = 2.75 * (healpy.nside2resol(nside, arcmin=True) / 60.) # deg, scale for 2D histogram and various plotting
    
    print('Distance = %.1f kpc (m-M = %.1f)'%(ugali.utils.projector.distanceModulusToDistance(distance_modulus), distance_modulus))

    dirname = '/home/s1/kadrlica/.ugali/isochrones/des/dotter2016/'
    #dirname = '/Users/keithbechtol/Documents/DES/projects/mw_substructure/ugalidir/isochrones/des/dotter2016/'
    iso = ugali.isochrone.factory('Dotter', hb_spread=0, dirname=dirname)
    iso.age = 12.
    iso.metallicity = 0.0001
    iso.distance_modulus = distance_modulus

    cut = cutIsochronePath(data[mag_g_dred_flag], data[mag_r_dred_flag], data[mag_err_g_flag], data[mag_err_r_flag], iso, radius=0.1)
    data = data[cut]
    cut_magnitude_threshold = (data[mag_g_dred_flag] < magnitude_threshold)

    print('%i objects left after isochrone cut...'%(len(data)))

    ###

    proj = ugali.utils.projector.Projector(ra_select, dec_select)
    x, y = proj.sphereToImage(data['RA'][cut_magnitude_threshold], data['DEC'][cut_magnitude_threshold]) # Trimmed magnitude range for hotspot finding
    x_full, y_full = proj.sphereToImage(data['RA'], data['DEC']) # In we want to use full magnitude range for significance evaluation
    delta_x = 0.01
    area = delta_x**2
    smoothing = 2. / 60. # Was 3 arcmin
    bins = np.arange(-1. * SCALE, SCALE + 1.e-10, delta_x)
    centers = 0.5 * (bins[0: -1] + bins[1:])
    yy, xx = np.meshgrid(centers, centers)

    h = np.histogram2d(x, y, bins=[bins, bins])[0]

    if plot:
        #pylab.figure('raw')
        #pylab.clf()
        #pylab.imshow(h.T, interpolation='nearest', extent=[-1. * SCALE, SCALE, -1. * SCALE, SCALE], origin='lower', cmap='binary')
        #pylab.xlim([SCALE, -1. * SCALE])
        #pylab.ylim([-1. * SCALE, SCALE])
        #pylab.colorbar()

        ##import skymap
        ##s = skymap.Skymap(projection='laea',llcrnrlon=340,llcrnrlat=-60,urcrnrlon=360,urcrnrlat=-50,lon_0 =355,lat_0=-55,celestial=False)
        ##s.draw_hpxmap(fracdet)
        #pix = skymap.healpix.ang2disc(355,-63,1)
        #pix = skymap.healpix.ang2disc(4096,355,-63,1)
        #s = skymap.Skymap()
        #s.draw_hpxmap(m[pix],pix,4096)
        #s.zoom_to_fit()
        #s.zoom_to_fit(4096,m[pix],pix)

        reso = 0.25
        pylab.figure('gnom')
        pylab.clf()
        healpy.gnomview(fracdet, fig='gnom', rot=(ra_select, dec_select, 0.), reso=reso, xsize=(2. * SCALE * 60. / reso), 
                        cmap='Greens', title='Fracdet') #binary
        healpy.projscatter(data['RA'], data['DEC'], edgecolor='none', c='red', lonlat=True, s=2)

    h_g = scipy.ndimage.filters.gaussian_filter(h, smoothing / delta_x)

    #cut_goodcoverage = (data['NEPOCHS_G'][cut_magnitude_threshold] >= 2) & (data['NEPOCHS_R'][cut_magnitude_threshold] >= 2)
    # expect NEPOCHS to be good in DES data

    delta_x_coverage = 0.1
    area_coverage = (delta_x_coverage)**2
    bins_coverage = np.arange(-5., 5. + 1.e-10, delta_x_coverage)
    h_coverage = np.histogram2d(x, y, bins=[bins_coverage, bins_coverage])[0]
    #h_goodcoverage = np.histogram2d(x[cut_goodcoverage], y[cut_goodcoverage], bins=[bins_coverage, bins_coverage])[0]
    h_goodcoverage = np.histogram2d(x, y, bins=[bins_coverage, bins_coverage])[0]

    n_goodcoverage = h_coverage[h_goodcoverage > 0].flatten()

    #characteristic_density = np.mean(n_goodcoverage) / area_coverage # per square degree
    characteristic_density = np.median(n_goodcoverage) / area_coverage # per square degree
    print('Characteristic density = %.1f deg^-2'%(characteristic_density))

    # Use pixels with fracdet ~1.0 to estimate the characteristic density
    if fracdet is not None:
        fracdet_zero = np.tile(0., len(fracdet))
        cut = (fracdet != healpy.UNSEEN)
        fracdet_zero[cut] = fracdet[cut]

        nside_fracdet = healpy.npix2nside(len(fracdet))
        
        subpix_region_array = []
        for pix in np.unique(ugali.utils.healpix.angToPix(nside, data['RA'], data['DEC'])):
            subpix_region_array.append(ugali.utils.healpix.subpixel(pix, nside, nside_fracdet))
        subpix_region_array = np.concatenate(subpix_region_array)

        # Compute mean fracdet in the region so that this is available as a correction factor
        cut = (fracdet[subpix_region_array] != healpy.UNSEEN)
        mean_fracdet = np.mean(fracdet[subpix_region_array[cut]])

        subpix_region_array = subpix_region_array[fracdet[subpix_region_array] > 0.99]
        subpix = ugali.utils.healpix.angToPix(nside_fracdet, 
                                              data['RA'][cut_magnitude_threshold], 
                                              data['DEC'][cut_magnitude_threshold]) # Remember to apply mag threshold to objects
        characteristic_density_fracdet = float(np.sum(np.in1d(subpix, subpix_region_array))) \
                                         / (healpy.nside2pixarea(nside_fracdet, degrees=True) * len(subpix_region_array)) # deg^-2
        print('Characteristic density fracdet = %.1f deg^-2'%(characteristic_density_fracdet))
        
        # Correct the characteristic density by the mean fracdet value
        characteristic_density_raw = 1. * characteristic_density
        characteristic_density /= mean_fracdet 
        print('Characteristic density (fracdet corrected) = %.1f deg^-2'%(characteristic_density))

    if plot:
        pylab.figure('poisson')
        pylab.clf()
        n_max = np.max(h_coverage)
        pylab.hist(n_goodcoverage, bins=np.arange(n_max) - 0.5, color='blue', histtype='step', lw=2, normed=True)
        pylab.scatter(np.arange(n_max), scipy.stats.poisson.pmf(np.arange(n_max), mu=np.median(n_goodcoverage)), c='red', edgecolor='none', zorder=10)
        #pylab.plot(np.arange(n_max), scipy.stats.poisson.pmf(np.arange(n_max), mu=np.median(n_goodcoverage)), c='red', lw=2, zorder=10)
        pylab.axvline(characteristic_density * area_coverage, c='black', ls='--')
        if fracdet is not None:
            pylab.axvline(characteristic_density_raw * area_coverage, c='orange', ls='--')
            pylab.axvline(characteristic_density_fracdet * area_coverage, c='green', ls='--')
        pylab.xlabel('Counts per %.3f deg^-2 pixel'%(area_coverage))
        pylab.ylabel('PDF')

    if plot:
        vmax = min(3. * characteristic_density * area, np.max(h_g))
    
        pylab.figure('smooth')
        pylab.clf()
        pylab.imshow(h_g.T,
                     interpolation='nearest', extent=[-1. * SCALE, SCALE, -1. * SCALE, SCALE], origin='lower', cmap='gist_heat', vmax=vmax)
        pylab.colorbar()
        pylab.xlim([SCALE, -1. * SCALE])
        pylab.ylim([-1. * SCALE, SCALE])
        pylab.xlabel(r'$\Delta$ RA (deg)')
        pylab.ylabel(r'$\Delta$ Dec (deg)')
        pylab.title('(RA, Dec, mu) = (%.2f, %.2f, %.2f)'%(ra_select, dec_select, distance_modulus))

    factor_array = np.arange(1., 5., 0.05)
    rara, decdec = proj.imageToSphere(xx.flatten(), yy.flatten())
    cutcut = (ugali.utils.healpix.angToPix(nside, rara, decdec) == pix_nside_select).reshape(xx.shape)
    threshold_density = 5 * characteristic_density * area
    for factor in factor_array:
        h_region, n_region = scipy.ndimage.measurements.label((h_g * cutcut) > (area * characteristic_density * factor))
        #print 'factor', factor, n_region, n_region < 10
        if n_region < 10:
            threshold_density = area * characteristic_density * factor
            break
    
    h_region, n_region = scipy.ndimage.measurements.label((h_g * cutcut) > threshold_density)
    h_region = np.ma.array(h_region, mask=(h_region < 1))
    if plot:
        pylab.figure('regions')
        pylab.clf()
        pylab.imshow(h_region.T,
                     interpolation='nearest', extent=[-1. * SCALE, SCALE, -1. * SCALE, SCALE], origin='lower')
        pylab.colorbar()
        pylab.xlim([SCALE, -1. * SCALE])
        pylab.ylim([-1. * SCALE, SCALE])

    ra_peak_array = []
    dec_peak_array = []
    r_peak_array = []
    sig_peak_array = []
    distance_modulus_array = []

    pylab.figure('sig')
    pylab.clf()
    for index in range(1, n_region + 1):
        index_peak = np.argmax(h_g * (h_region == index))
        x_peak, y_peak = xx.flatten()[index_peak], yy.flatten()[index_peak]
        #print index, np.max(h_g * (h_region == index))
        if plot:
            pylab.figure('regions')
            #pylab.scatter(x_peak, y_peak, marker='x', c='white')
            pylab.scatter(x_peak, y_peak, marker='o', c='none', edgecolor='black', s=50)

        
        #angsep_peak = np.sqrt((x_full - x_peak)**2 + (y_full - y_peak)**2) # Use full magnitude range, NOT TESTED!!!
        angsep_peak = np.sqrt((x - x_peak)**2 + (y - y_peak)**2) # Impose magnitude threshold

        # Compute the local characteristic density
        # If fracdet map is available, use that information to either compute local density,
        # or in regions of spotty coverage, use the typical density of the region
        if fracdet is not None:
            ra_peak, dec_peak = proj.imageToSphere(x_peak, y_peak)
            subpix_all = ugali.utils.healpix.angToDisc(nside_fracdet, ra_peak, dec_peak, 0.5)
            subpix_inner = ugali.utils.healpix.angToDisc(nside_fracdet, ra_peak, dec_peak, 0.3)
            subpix_annulus = subpix_all[~np.in1d(subpix_all, subpix_inner)]
            mean_fracdet = np.mean(fracdet_zero[subpix_annulus])
            print('mean_fracdet', mean_fracdet)
            if mean_fracdet < 0.5:
                characteristic_density_local = characteristic_density
                print('characteristic_density_local baseline', characteristic_density_local)
            else:
                # Check pixels in annulus with complete coverage
                subpix_annulus_region = np.intersect1d(subpix_region_array, subpix_annulus)
                print(float(len(subpix_annulus_region)) / len(subpix_annulus))
                if (float(len(subpix_annulus_region)) / len(subpix_annulus)) < 0.25:
                    characteristic_density_local = characteristic_density
                    print('characteristic_density_local spotty', characteristic_density_local)
                else:
                    characteristic_density_local = float(np.sum(np.in1d(subpix, subpix_annulus_region))) \
                                                   / (healpy.nside2pixarea(nside_fracdet, degrees=True) * len(subpix_annulus_region)) # deg^-2
                    print('characteristic_density_local cleaned up', characteristic_density_local)
        else:
            # Compute the local characteristic density
            area_field = np.pi * (0.5**2 - 0.3**2)
            n_field = np.sum((angsep_peak > 0.3) & (angsep_peak < 0.5))
            characteristic_density_local = n_field / area_field

            # If not good azimuthal coverage, revert
            cut_annulus = (angsep_peak > 0.3) & (angsep_peak < 0.5) 
            #phi = np.degrees(np.arctan2(y_full[cut_annulus] - y_peak, x_full[cut_annulus] - x_peak)) # Use full magnitude range, NOT TESTED!!!
            phi = np.degrees(np.arctan2(y[cut_annulus] - y_peak, x[cut_annulus] - x_peak)) # Impose magnitude threshold
            h = np.histogram(phi, bins=np.linspace(-180., 180., 13))[0]
            if np.sum(h > 0) < 10 or np.sum(h > 0.5 * np.median(h)) < 10:
                #angsep_peak = np.sqrt((x - x_peak)**2 + (y - y_peak)**2)
                characteristic_density_local = characteristic_density

        print('Characteristic density local = %.1f deg^-2'%(characteristic_density_local))

        size_array = np.arange(0.01, 0.3, 0.01)
        sig_array = np.tile(0., len(size_array))
        for ii in range(0, len(size_array)):
            n_peak = np.sum(angsep_peak < size_array[ii])
            n_model = characteristic_density_local * (np.pi * size_array[ii]**2)
            sig_array[ii] = scipy.stats.norm.isf(scipy.stats.poisson.sf(n_peak, n_model))
            if sig_array[ii] > 25:
                sig_array[ii] = 25. # Set a maximum significance value

        if plot:
            pylab.figure('sig')
            pylab.plot(size_array, sig_array)
            pylab.xlabel('Radius used to compute significance (deg)')
            pylab.ylabel('Detection significance')

        ra_peak, dec_peak = proj.imageToSphere(x_peak, y_peak)
        r_peak = size_array[np.argmax(sig_array)]
        if np.max(sig_array) == 25.:
            r_peak = 0.5

        #print 'Candidate:', x_peak, y_peak, r_peak, np.max(sig_array), ra_peak, dec_peak
        print('Candidate: %12.3f %12.3f %12.3f %12.3f %12.3f %12.3f'%(x_peak, y_peak, r_peak, np.max(sig_array), ra_peak, dec_peak))
        if np.max(sig_array) > 5.:
            if plot:
                x_circle, y_circle = circle(x_peak, y_peak, r_peak)
                pylab.figure('smooth')
                pylab.plot(x_circle, y_circle, c='gray')
                pylab.text(x_peak - r_peak, y_peak + r_peak, r'%.2f $\sigma$'%(np.max(sig_array)), color='gray')
    
            ra_peak_array.append(ra_peak)
            dec_peak_array.append(dec_peak)
            r_peak_array.append(r_peak)
            sig_peak_array.append(np.max(sig_array))
            distance_modulus_array.append(distance_modulus)

    if plot:
        input('Plots are ready...')

    return ra_peak_array, dec_peak_array, r_peak_array, sig_peak_array, distance_modulus_array
Пример #23
0
def visualize_map(args):
    """Visualize sky maps in hdf5 files.

    Arguments
    ---------
    args : argparse namespace.
    """
    import numpy as np
    import h5py
    import healpy
    # import hpvisual
    import matplotlib
    matplotlib.use('Agg')
    try:
        # for new version matplotlib
        import matplotlib.style as mstyle
        mstyle.use('classic')
    except ImportError:
        pass
    from matplotlib import pyplot as plt

    # Read in maps data
    hpmap = None
    for mapname in args.mapfiles:
        with h5py.File(mapname, 'r') as f:
            if hpmap is None:
                hpmap = f['map'][:]
            else:
                hpmap += f['map'][:]

    # Check args validity
    if args.ifreq < -(hpmap.shape)[0] or args.ifreq >= (hpmap.shape)[0]:
        raise Exception('Invalid frequency channel %d, should be in range(-%d, %d).'%(args.ifreq, (hpmap.shape)[0], (hpmap.shape)[0]))
    else:
        ifreq = args.ifreq if args.ifreq >= 0 else args.ifreq + (hpmap.shape)[0]
    if args.pol >= (hpmap.shape)[1]:
        raise Exception('Invalid frequency channel %d, should be in range(0, %d).'%(args.pol, (hpmap.shape)[1]))
    if args.figlength <= 0:
        raise Exception('Figure length figlength (= %f) must greater than 0'%args.figlength)
    if args.figwidth <= 0:
        raise Exception('Figure width figwidth (= %f) must greater than 0'%args.figwidth)

    # Create output image file name
    if args.outfile:
        out_file = args.outfile
    else:
        out_file = ((args.mapfiles[0].split('/')[-1]).split('.')[0] + '_' + str(ifreq) + '_{' + str(args.pol) + '}' +  '.' + args.figfmt).format('T', 'Q', 'U', 'V')

    # Plot and save image
    if args.view == 'o':
        fig = plt.figure(1, figsize=(8, 6))
    else:
        fig = plt.figure(1, figsize=(args.figlength,args.figwidth))

    map_data = hpmap[ifreq][args.pol]
    if args.sqrt:
        map_data = map_data / np.sqrt(np.abs(map_data))
        map_data = map_data / np.sqrt(np.abs(map_data))
        # map_data = map_data / np.sqrt(np.abs(map_data))

    # smoothing the map with a Gaussian symmetric beam
    if args.fwhm is not None:
        fwhm = np.radians(args.fwhm)
        map_data = healpy.smoothing(map_data, fwhm=fwhm)

    if args.view == 'm':
        # set color map
        if args.cmap is None:
            cmap = None
        else:
            if args.cmap == 'jet09':
                import colormap
                cmap = colormap.jet09
            else:
                from pylab import cm
                # cmap = cm.hot
                cmap = getattr(cm, args.cmap)
            cmap.set_under('w')

        if args.abs:
            healpy.mollview(np.abs(map_data), fig=1, title='', unit=args.unit, cmap=cmap, min=args.min, max=args.max)
        else:
            healpy.mollview(map_data, fig=1, title='', unit=args.unit, cmap=cmap, min=args.min, max=args.max)

        # plot NVSS sources
        if args.nvss is not None:
            import aipy as a

            flux = args.nvss
            frequency = 750 # MHz
            catalog = 'nvss'
            # catalog = 'wenss'
            src = '%f/%f' % (flux, frequency / 1.0e3)
            srclist, cutoff, catalogs = a.scripting.parse_srcs(src, catalog)
            cat = a.src.get_catalog(srclist, cutoff, catalogs)
            nsrc = len(cat) # number of sources in cat
            ras = [ np.degrees(cat.values()[i]._ra) for i in range(nsrc) ]
            decs = [ np.degrees(cat.values()[i]._dec) for i in range(nsrc) ]
            jys = [ cat.values()[i].get_jys() for i in range(nsrc) ]

            # select sources
            inds = np.where(np.array(decs)>-15.0)[0]
            ras = np.array(ras)[inds]
            decs = np.array(decs)[inds]
            jys = np.array(jys)[inds]

            # healpy.projscatter(ras, decs, lonlat=True, s=jys, facecolors='none', edgecolors='w', alpha=1.0, linewidth=1.0)
            healpy.projscatter(ras, decs, lonlat=True, s=150, facecolors='none', edgecolors='w', alpha=1.0, linewidth=1.0)

    elif args.view == 'c':
        healpy.cartview(map_data, fig=1, title='', unit=args.unit, min=args.min, max=args.max)
    elif args.view == 'o':
        healpy.orthview(map_data, rot=(0, 90, 0), fig=1, title='', unit=args.unit, min=args.min, max=args.max, half_sky=True) # rot to make NCP at the center
    # fig = plt.figure()
    # ax = fig.add_axes()
    # cbar.solids.set_rasterized(True)
    if args.grid:
        healpy.graticule()
    if args.tight:
        fig.savefig(out_file, bbox_inches='tight')
    else:
        fig.savefig(out_file)
    fig.clf()
Пример #24
0
    parser.add_option('-t','--targets',default=None)
    parser.add_option('-c','--coord',default='GAL')
    parser.add_option('-p','--proj',default='MOL',choices=['MOL','CAR'])
    parser.add_option('-f','--field',default='LOG_LIKELIHOOD')

    (opts, args) = parser.parse_args()

    nside = pyfits.open(args[0])[1].header['NSIDE']
    map = healpy.UNSEEN * numpy.ones( healpy.nside2npix(nside) )
    pix,vals = ugali.utils.skymap.readSparseHealpixMap(args[0],opts.field,construct_map=False)
    map[pix] = vals[0]

    if opts.coord.upper() == "GAL":
        coord = 'G'
    elif opts.coord.upper() == "CEL":
        coord = 'GC'
    if opts.proj.upper() == "MOL":
        healpy.mollview(map,coord=coord,xsize=1000)
    elif opts.proj.upper() == "CAR":
        healpy.cartview(map,coord=coord,xsize=1000)
    else:
        raise Exception("...")
    healpy.graticule()

    if opts.targets:
        data = numpy.loadtxt(opts.targets,unpack=True,dtype='str')
        coord = 'CG' # For RA/DEC input
        healpy.projscatter(data[1].astype(float),data[2].astype(float),
                           lonlat=True,coord=coord,marker='o',c='w')
    plt.savefig(opts.outfile)
Пример #25
0
import healpy as hp
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from astropy import units as uwell
from astropy.coordinates import SkyCoord

cat_path = "catalog.csv"
rand_cat_path = "random_catalog.csv"
sel_func_path = " HFI_PCCS_SZ-selfunc-union-survey_R2.08.fits"
title = "Planck Clusters"
out_path = "Planck_scatter.pdf"

if __name__ == "__main__":
    catalog = pd.read_csv(cat_path)
    random_catalog = pd.read_csv(rand_cat_path)

    ra = np.asarray(catalog["RA"].values)
    dec = np.asarray(catalog["DEC"].values)
    rand_ra = np.asarray(random_catalog["RA"].values)
    rand_dec = np.asarray(random_catalog["DEC"].values)

    seln_func = hp.read_map(sel_func_path)
    hp.visufunc.mollview(seln_func, title=title, coord=["G", "C"])
    hp.projscatter(ra, dec, lonlat=True, s=3, c='r')
    #hp.projscatter(rand_ra, rand_dec, lonlat=True, s = 3, c = 'b')
    hp.graticule()
    plt.savefig(out_path)
Пример #26
0
from scipy.stats import chi2
import healpy as hp
import numpy as np
import matplotlib.pyplot as plt

# convert test statistic to a p-value for a given point
pVal_func = lambda TS, dec: -np.log10(0.5 * (chi2(1).sf(TS) + chi2(1).cdf(-TS)))

if __name__=="__main__":

    # init the llh class
    llh = init(1000, 10000, ncpu=1, energy=True)

    print(llh)

    # iterator of all-sky scan with follow up scans of most interesting points
    for i, (scan, hotspot) in enumerate(llh.all_sky_scan(nside=16,
                                                         pVal=pVal_func)):
        if i > 0:
            # break after first follow up
            break

    # plot results
    hp.mollview(scan["pVal"], min=0., cmap=plt.cm.afmhot)
    hp.projscatter(np.degrees(llh.exp["ra"]),
                   np.degrees(np.arcsin(llh.exp["sinDec"])),
                   lonlat=True, marker="x", color="red")
    plt.show()

Пример #27
0
def coverage(params, map_struct, coverage_struct, catalog_struct=None):

    unit = 'Gravitational-wave probability'
    cbar = False

    plotName = os.path.join(params["outputDir"], 'mollview_coverage.pdf')
    plt.figure()
    hp.mollview(map_struct["prob"], title='', unit=unit, cbar=cbar, cmap=cmap)
    hp.projplot(coverage_struct["data"][:, 0],
                coverage_struct["data"][:, 1],
                'wx',
                lonlat=True,
                coord='G')
    add_edges()
    plt.show()
    plt.savefig(plotName, dpi=200)
    plt.close('all')

    idx = np.isfinite(coverage_struct["data"][:, 4])
    if not idx.size: return
    min_time = np.min(coverage_struct["data"][idx, 4])
    max_time = np.max(coverage_struct["data"][idx, 4])

    plotName = os.path.join(params["outputDir"], 'coverage.pdf')
    plt.figure(figsize=(10, 8))
    ax = plt.gca()
    for ii in range(len(coverage_struct["ipix"])):
        data = coverage_struct["data"][ii, :]
        filt = coverage_struct["filters"][ii]
        ipix = coverage_struct["ipix"][ii]
        patch = coverage_struct["patch"][ii]
        FOV = coverage_struct["FOV"][ii]

        if filt == "g":
            color = "g"
        elif filt == "r":
            color = "r"
        else:
            color = "k"

        plt.scatter(data[2], data[5], s=20, color=color)

    plt.xlabel("Time [MJD]")
    plt.ylabel("Tile Number")
    plt.show()
    plt.savefig(plotName, dpi=200)
    plt.close('all')

    plotName = os.path.join(params["outputDir"], 'tiles_coverage.pdf')
    plt.figure()
    hp.mollview(map_struct["prob"], title='', unit=unit, cbar=cbar, cmap=cmap)
    add_edges()
    ax = plt.gca()
    for ii in range(len(coverage_struct["ipix"])):
        data = coverage_struct["data"][ii, :]
        filt = coverage_struct["filters"][ii]
        ipix = coverage_struct["ipix"][ii]
        patch = coverage_struct["patch"][ii]
        FOV = coverage_struct["FOV"][ii]

        #hp.visufunc.projplot(corners[:,0], corners[:,1], 'k', lonlat = True)
        if patch == []:
            continue

        patch_cpy = copy.copy(patch)
        patch_cpy.axes = None
        patch_cpy.figure = None
        patch_cpy.set_transform(ax.transData)
        hp.projaxes.HpxMollweideAxes.add_patch(ax, patch_cpy)
        #tiles.plot()
    plt.show()
    plt.savefig(plotName, dpi=200)
    plt.close('all')

    diffs = []
    if params["tilesType"] == "galaxy":
        coverage_ras = coverage_struct["data"][:, 0]
        coverage_decs = coverage_struct["data"][:, 1]
        coverage_mjds = coverage_struct["data"][:, 2]

        for ii in range(len(coverage_ras) - 1):
            current_ra, current_dec = coverage_ras[ii], coverage_decs[ii]
            current_mjd = coverage_mjds[ii]

            dist = angular_distance(current_ra, current_dec,
                                    coverage_ras[ii + 1:],
                                    coverage_decs[ii + 1:])
            idx = np.where(dist <= 1 / 3600.0)[0]
            if len(idx) > 0:
                jj = idx[0]
                diffs.append(
                    np.abs(coverage_struct["data"][ii, 2] -
                           coverage_struct["data"][jj, 2]))
    else:
        for ii in range(len(coverage_struct["ipix"])):
            ipix = coverage_struct["ipix"][ii]
            for jj in range(len(coverage_struct["ipix"])):
                if ii >= jj: continue
                if coverage_struct["telescope"][ii] == coverage_struct[
                        "telescope"][jj]:
                    continue
                ipix2 = coverage_struct["ipix"][jj]
                overlap = np.intersect1d(ipix, ipix2)
                rat = np.array([
                    float(len(overlap)) / float(len(ipix)),
                    float(len(overlap)) / float(len(ipix2))
                ])
                if np.any(rat > 0.5):
                    diffs.append(
                        np.abs(coverage_struct["data"][ii, 2] -
                               coverage_struct["data"][jj, 2]))

    filename = os.path.join(params["outputDir"], 'tiles_coverage_hist.dat')
    fid = open(filename, 'w')
    for ii in range(len(diffs)):
        fid.write('%.10f\n' % diffs[ii])
    fid.close()

    plotName = os.path.join(params["outputDir"], 'tiles_coverage_hist.pdf')
    fig = plt.figure(figsize=(12, 8))
    #hist, bin_edges = np.histogram(diffs, bins=20)
    bins = np.linspace(0.0, 24.0, 25)
    plt.hist(24.0 * np.array(diffs), bins=bins)
    plt.xlabel('Difference Between Observations [hours]')
    plt.ylabel('Number of Observations')
    plt.show()
    plt.savefig(plotName, dpi=200)
    plt.close('all')

    gpstime = params["gpstime"]
    event_mjd = Time(gpstime, format='gps', scale='utc').mjd

    colors = cm.rainbow(np.linspace(0, 1, len(params["telescopes"])))
    plotName = os.path.join(params["outputDir"], 'tiles_coverage_int.pdf')

    fig = plt.figure(figsize=(12, 8))

    gs = fig.add_gridspec(4, 1)
    ax1 = fig.add_subplot(gs[0:3, 0], projection='astro hours mollweide')
    ax2 = fig.add_subplot(gs[3, 0])
    ax3 = ax2.twinx()  # mirror them

    plt.axes(ax1)
    hp.mollview(map_struct["prob"],
                title='',
                unit=unit,
                cbar=cbar,
                cmap=cmap,
                hold=True)
    add_edges()
    ax = plt.gca()
    data = {}

    if params["tilesType"] == "galaxy":
        for telescope, color in zip(params["telescopes"], colors):
            idx = np.where(coverage_struct["telescope"] == telescope)[0]
            hp.projscatter(coverage_struct["data"][idx, 0],
                           coverage_struct["data"][idx, 1],
                           lonlat=True,
                           s=10,
                           color=color)
    else:
        for ii in range(len(coverage_struct["ipix"])):
            data = coverage_struct["data"][ii, :]
            filt = coverage_struct["filters"][ii]
            ipix = coverage_struct["ipix"][ii]
            patch = coverage_struct["patch"][ii]
            FOV = coverage_struct["FOV"][ii]

            idx = params["telescopes"].index(coverage_struct["telescope"][ii])

            if patch == []:
                continue
            #hp.visufunc.projplot(corners[:,0], corners[:,1], 'k', lonlat = True)
            patch_cpy = copy.copy(patch)
            patch_cpy.axes = None
            patch_cpy.figure = None
            patch_cpy.set_transform(ax.transData)
            patch_cpy.set_facecolor(colors[idx])

            hp.projaxes.HpxMollweideAxes.add_patch(ax, patch_cpy)
            #tiles.plot()

    idxs = np.argsort(coverage_struct["data"][:, 2])
    plt.axes(ax2)
    for telescope, color in zip(params["telescopes"], colors):
        ipixs = np.empty((0, 2))
        cum_prob = 0.0
        cum_area = 0.0

        tts, cum_probs, cum_areas = [], [], []
        if params["tilesType"] == "galaxy":
            cum_galaxies = []

        for jj, ii in enumerate(idxs):
            if np.mod(jj, 100) == 0:
                print('%s: %d/%d' % (telescope, jj, len(idxs)))

            data = coverage_struct["data"][ii, :]
            filt = coverage_struct["filters"][ii]
            ipix = coverage_struct["ipix"][ii]
            patch = coverage_struct["patch"][ii]
            FOV = coverage_struct["FOV"][ii]
            area = coverage_struct["area"][ii]
            if params["tilesType"] == "galaxy":
                galaxies = coverage_struct["galaxies"][ii]

            if not telescope == coverage_struct["telescope"][ii]:
                continue

            if params["tilesType"] == "galaxy":
                overlap = np.setdiff1d(galaxies, cum_galaxies)
                if len(overlap) > 0:
                    for galaxy in galaxies:
                        if galaxy in cum_galaxies: continue
                        if catalog_struct is None: continue
                        if params["galaxy_grade"] == "Sloc":
                            cum_prob = cum_prob + catalog_struct["Sloc"][galaxy]
                        elif params["galaxy_grade"] == "S":
                            cum_prob = cum_prob + catalog_struct["S"][galaxy]
                    cum_galaxies = np.append(cum_galaxies, galaxies)
                    cum_galaxies = np.unique(cum_galaxies).astype(int)
                cum_area = len(cum_galaxies)
            else:
                ipixs = np.append(ipixs, ipix)
                ipixs = np.unique(ipixs).astype(int)

                cum_prob = np.sum(map_struct["prob"][ipixs])
                cum_area = len(ipixs) * map_struct["pixarea_deg2"]

            cum_probs.append(cum_prob)
            cum_areas.append(cum_area)
            tts.append(data[2] - event_mjd)

        ax2.plot(tts, cum_probs, color=color, linestyle='-', label=telescope)
        ax3.plot(tts, cum_areas, color=color, linestyle='--')

    ax2.set_xlabel('Time since event [days]')
    if params["tilesType"] == "galaxy":
        ax2.set_ylabel('Integrated Metric')
    else:
        ax2.set_ylabel('Integrated Probability')

    if params["tilesType"] == "galaxy":
        ax3.set_ylabel('Number of galaxies')
    else:
        ax3.set_ylabel('Sky area [sq. deg.]')

    ipixs = np.empty((0, 2))
    cum_prob = 0.0
    cum_area = 0.0

    tts, cum_probs, cum_areas = [], [], []
    if params["tilesType"] == "galaxy":
        cum_galaxies = []

    for jj, ii in enumerate(idxs):
        data = coverage_struct["data"][ii, :]
        filt = coverage_struct["filters"][ii]
        ipix = coverage_struct["ipix"][ii]
        patch = coverage_struct["patch"][ii]
        FOV = coverage_struct["FOV"][ii]
        area = coverage_struct["area"][ii]
        if params["tilesType"] == "galaxy":
            galaxies = coverage_struct["galaxies"][ii]

        if params["tilesType"] == "galaxy":
            overlap = np.setdiff1d(galaxies, cum_galaxies)
            if len(overlap) > 0:
                for galaxy in galaxies:
                    if galaxy in cum_galaxies: continue
                    if catalog_struct is None: continue
                    if params["galaxy_grade"] == "Sloc":
                        cum_prob = cum_prob + catalog_struct["Sloc"][galaxy]
                    elif params["galaxy_grade"] == "S":
                        cum_prob = cum_prob + catalog_struct["S"][galaxy]
                cum_galaxies = np.append(cum_galaxies, galaxies)
                cum_galaxies = np.unique(cum_galaxies).astype(int)
            cum_area = len(cum_galaxies)
        else:
            ipixs = np.append(ipixs, ipix)
            ipixs = np.unique(ipixs).astype(int)

            cum_prob = np.sum(map_struct["prob"][ipixs])
            cum_area = len(ipixs) * map_struct["pixarea_deg2"]

        tts.append(data[2] - event_mjd)
        cum_probs.append(cum_prob)
        cum_areas.append(cum_area)

    ax2.plot(tts, cum_probs, color='k', linestyle='-', label='All')
    ax3.plot(tts, cum_areas, color='k', linestyle='--')

    if len(params["telescopes"]) > 3:
        ax2.legend(loc=1, ncol=3, fontsize=10)
        ax2.set_ylim([0, 1])
        ax3.set_ylim([0, 2000])
    elif "IRIS" in params["telescopes"]:
        ax2.set_ylim([0, 0.3])
        ax3.set_ylim([0, 1200])
        ax2.legend(loc=1)
    elif "ZTF" in params["telescopes"]:
        ax2.set_ylim([0, 0.6])
        ax3.set_ylim([0, 6000])
        ax2.legend(loc=1)
    elif "PS1" in params["telescopes"]:
        ax2.set_ylim([0, 0.6])
        ax3.set_ylim([0, 6000])
        ax2.legend(loc=1)
    else:
        ax2.legend(loc=1)
    plt.show()
    plt.savefig(plotName, dpi=200)
    plt.close('all')

    filename = os.path.join(params["outputDir"], 'tiles_coverage_int.dat')
    fid = open(filename, 'w')
    for ii in range(len(tts)):
        fid.write('%.10f %.10e %.10f\n' %
                  (tts[ii], cum_probs[ii], cum_areas[ii]))
    fid.close()

    print('Total Cumulative Probability, Area: %.5f, %.5f' %
          (cum_probs[-1], cum_areas[-1]))

    plotName = os.path.join(params["outputDir"], 'tiles_coverage_scaled.pdf')
    plt.figure()
    hp.mollview(map_struct["prob"], title='', unit=unit, cbar=cbar, cmap=cmap)
    add_edges()
    ax = plt.gca()
    for ii in range(len(coverage_struct["ipix"])):
        data = coverage_struct["data"][ii, :]
        filt = coverage_struct["filters"][ii]
        ipix = coverage_struct["ipix"][ii]
        patch = coverage_struct["patch"][ii]
        FOV = coverage_struct["FOV"][ii]

        if patch == []:
            continue

        #hp.visufunc.projplot(corners[:,0], corners[:,1], 'k', lonlat = True)
        patch_cpy = copy.copy(patch)
        patch_cpy.axes = None
        patch_cpy.figure = None
        patch_cpy.set_transform(ax.transData)
        current_alpha = patch_cpy.get_alpha()

        if current_alpha > 0.0:
            alpha = data[4] / max_time
            if alpha > 1:
                alpha = 1.0
            patch_cpy.set_alpha(alpha)
        hp.projaxes.HpxMollweideAxes.add_patch(ax, patch_cpy)
        #tiles.plot()
    plt.show()
    plt.savefig(plotName, dpi=200)
    plt.close('all')

    if params["doMovie"]:
        idx = np.isfinite(coverage_struct["data"][:, 2])
        mjd_min = np.min(coverage_struct["data"][idx, 2])
        mjd_max = np.max(coverage_struct["data"][idx, 2])
        mjd_N = 100

        mjds = np.linspace(mjd_min, mjd_max, num=mjd_N)
        moviedir = os.path.join(params["outputDir"], 'movie')
        if not os.path.isdir(moviedir): os.mkdir(moviedir)

        #for jj in range(len(coverage_struct["ipix"])):
        #    mjd = coverage_struct["data"][jj,3]
        for jj in range(len(mjds)):
            mjd = mjds[jj]
            plotName = os.path.join(moviedir, 'coverage-%04d.png' % jj)
            title = "Coverage Map: %.2f" % mjd

            plt.figure()
            hp.mollview(map_struct["prob"],
                        title=title,
                        unit=unit,
                        cbar=cbar,
                        cmap=cmap)
            add_edges()
            ax = plt.gca()

            idx = np.where(coverage_struct["data"][:, 2] <= mjd)[0]
            #for ii in range(jj):
            for ii in idx:
                data = coverage_struct["data"][ii, :]
                filt = coverage_struct["filters"][ii]
                ipix = coverage_struct["ipix"][ii]
                patch = coverage_struct["patch"][ii]
                FOV = coverage_struct["FOV"][ii]

                if patch == []:
                    continue

                #hp.visufunc.projplot(corners[:,0], corners[:,1], 'k', lonlat = True)
                patch_cpy = copy.copy(patch)
                patch_cpy.axes = None
                patch_cpy.figure = None
                patch_cpy.set_transform(ax.transData)
                #alpha = data[4]/max_time
                #if alpha > 1:
                #    alpha = 1.0
                #patch_cpy.set_alpha(alpha)
                hp.projaxes.HpxMollweideAxes.add_patch(ax, patch_cpy)
                #tiles.plot()
            plt.show()
            plt.savefig(plotName, dpi=200)
            plt.close('all')

        moviefiles = os.path.join(moviedir, "coverage-%04d.png")
        filename = os.path.join(params["outputDir"], "coverage.mpg")
        ffmpeg_command = 'ffmpeg -an -y -r 20 -i %s -b:v %s %s' % (
            moviefiles, '5000k', filename)
        os.system(ffmpeg_command)
        filename = os.path.join(params["outputDir"], "coverage.gif")
        ffmpeg_command = 'ffmpeg -an -y -r 20 -i %s -b:v %s %s' % (
            moviefiles, '5000k', filename)
        os.system(ffmpeg_command)
        rm_command = "rm %s/*.png" % (moviedir)
        os.system(rm_command)
Пример #28
0
import numpy as np
import matplotlib.pyplot as plt

# convert test statistic to a p-value for a given point
pVal_func = lambda TS, dec: -np.log10(0.5 * (chi2(1).sf(TS) + chi2(1).cdf(-TS)))

if __name__=="__main__":

    # init the llh class
    llh = multi_init(3, 1000, 10000,
                     energy=False, ncpu=4)

    print(llh)

    # iterator of all-sky scan with follow up scans of most interesting points
    for i, (scan, hotspot) in enumerate(llh.all_sky_scan(nside=32,
                                                         pVal=pVal_func)):
        if i > 0:
            # break after first follow up
            break

    # plot results
    hp.mollview(scan["pVal"], min=0., cmap=plt.cm.afmhot)
    col = plt.gca()._get_lines.color_cycle
    for enum, llh_i in llh._sams.iteritems():
        hp.projscatter(np.degrees(llh_i.exp["ra"]),
                       np.degrees(np.arcsin(llh_i.exp["sinDec"])),
                       lonlat=True, marker="x", color=col.next())
    plt.show()

Пример #29
0
    zred = zred[idy]
    mu_r = -1.0 + 2.*np.random.random(size = Nsize)
    phi_r = 2.0*np.pi*np.random.random(size = Nsize)
    theta_r = np.arccos(mu_r)

    pix = healpy.pixelfunc.ang2pix(2048, theta_r, phi_r)
    mask = (seln_func[pix] == 1) #Select only points within the seln_func
    theta_r = theta_r[mask]
    phi_r = phi_r[mask]
    zred_r = zred[np.random.permutation(phi_r.size) % zred.size] #Produce 'random' redshifts

    fig = plt.figure(1)
    healpy.mollview(seln_func,norm = 'hist', cmap = 'PRGn')
    fig.savefig(sel_fig)

    fig = plt.figure(2)
    healpy.mollview(seln_func, norm = 'hist', cmap = 'PRGn')
    healpy.projscatter(planck_theta, planck_phi, s = 1, lw = 0)
    fig.savefig(bcg_fig)

    fig = plt.figure(3)
    healpy.mollview(seln_func, norm = 'hist', cmap = 'PRGn')
    healpy.projscatter(theta_r, phi_r, s = 1, lw = 0)
    fig.savefig(dist_fig)

    # Now convert using astropy coordinates
    c = SkyCoord(l = phi_r, b = np.pi/2 - theta_r, frame = 'galactic', unit = 'radian')
    output = np.transpose([c.icrs.ra.deg,c.icrs.dec.deg,zred_r])
    output = np.vstack((['RA','DEC','REDSHIFT'], output))
    np.savetxt(out_path, output, fmt = '%s', delimiter = ',')
Пример #30
0
def creat_map(mkffile, ra, dec, time, outfile):

    mkfdata = fits.getdata(mkffile, 1)

    #Calculate Earth and CZTI Coords
    earth_coo, czti_z = get_angles(mkfdata, time, ra, dec, window=10)

    plotfile = PdfPages(outfile)

    #Calculate Earth RA DEC Dist
    earth_ra = earth_coo.fk5.ra.rad
    earth_dec = earth_coo.fk5.dec.rad
    earth_dist = earth_coo.fk5.distance.km

    #CZTI RA DEC
    czti_ra = czti_z.fk5.ra.rad
    czti_dec = czti_z.fk5.dec.rad

    #Load Bayestar File
    NSIDE = 512
    no_pix = hp.nside2npix(NSIDE)
    prob = np.zeros(no_pix)
    #	prob = hp.read_map(loc_map)
    #	NSIDE = fits.open(args.loc_map)[1].header['NSIDE']
    prob2 = np.copy(prob)
    prob3 = np.copy(prob)
    #
    #	#ColorMap
    cmap = plt.cm.YlOrRd
    cmap.set_under("w")
    #
    #	hp.mollview(prob, title='Complete Localisation Map', rot=(180, 0), cmap=cmap)
    #
    #	hp.graticule()
    #	plotfile.savefig()

    #Earth Occult

    czti_theta = np.pi / 2 - czti_dec
    czti_phi = czti_ra
    earth_theta = np.pi / 2 - earth_dec
    earth_phi = earth_ra
    earth_occult = np.arcsin(6378. / earth_dist)
    earth_vec = hp.ang2vec(earth_theta, earth_phi)
    earth = hp.query_disc(NSIDE, earth_vec, earth_occult)

    prob[earth] = np.nan
    not_occult = np.nansum(prob)

    # Add the GRB now
    grb_theta = np.pi / 2 - dec
    grb_phi = ra

    hp.mollview(
        prob,
        title=
        "Earth Occulted Localisation Map (Remaining Probability = {not_occult:2.3f})"
        .format(not_occult=not_occult),
        rot=(earth_theta, earth_phi),
        cmap=cmap)
    hp.graticule()
    hp.projscatter(czti_theta, czti_phi, color='r', marker='x')
    hp.projtext(czti_theta, czti_phi, 'CZTI')
    hp.projscatter(grb_theta, grb_phi, color='k', marker='o')
    hp.projtext(grb_theta, grb_phi, grbdir)
    hp.projscatter(earth_theta, earth_phi, color='g', marker='^')
    hp.projtext(earth_theta, earth_phi, 'Earth')

    plotfile.savefig()

    #Above Focal Plane
    back_vec = hp.ang2vec(np.pi - czti_theta, czti_phi)
    front = hp.query_disc(NSIDE, back_vec, np.pi / 2)

    prob2[front] = np.nan
    front_prob = np.nansum(prob2)

    hp.mollview(
        prob2,
        title=
        "Above the Focal Plane Localisation Map (Remaining Probability = {front_prob:2.3f})"
        .format(front_prob=front_prob),
        rot=(180, 0),
        cmap=cmap)
    hp.graticule()
    hp.projscatter(czti_theta, czti_phi, color='r', marker='x')
    hp.projtext(czti_theta, czti_phi, 'CZTI')
    hp.projscatter(grb_theta, grb_phi, color='k', marker='o')
    hp.projtext(grb_theta, grb_phi, grbdir)
    hp.projscatter(earth_theta, earth_phi, color='g', marker='^')
    hp.projtext(earth_theta, earth_phi, 'Earth')

    plotfile.savefig()

    #Earth Occult and Above Focal Plane
    prob2[earth] = np.nan
    final_prob = np.nansum(prob2)

    hp.mollview(
        prob2,
        title=
        "Earth Occult + Above Focal Plane (Remaining Probability = {final_prob:2.3f})"
        .format(final_prob=final_prob),
        rot=(180, 0),
        cmap=cmap)
    hp.graticule()
    hp.projscatter(czti_theta, czti_phi, color='r', marker='x')
    hp.projtext(czti_theta, czti_phi, 'CZTI')
    hp.projscatter(grb_theta, grb_phi, color='k', marker='o')
    hp.projtext(grb_theta, grb_phi, grbdir)
    hp.projscatter(earth_theta, earth_phi, color='g', marker='^')
    hp.projtext(earth_theta, earth_phi, 'Earth')

    plotfile.savefig()

    plotfile.close()

    return
Пример #31
0
def _plot_exampleSED(dictionary, center, nus_out, maskmaps, mapsarray = False, 
					DeltaTheta = 0, DeltaPhi = 0, savefig = False, set_logscale = False,
					newnside = None, intensity = True, covmap = None):

	"""
	Plot an example of Figure 10 (map + SED ) in paper 1

	===============
	Parameters: 
		dictionary:
			QUBIC dictionary
		center: 
			center of the FOV for the map (maskmap)
		nus_out:
			frequencies where was reconstructed the map
		maskmap:
			a sky map. 'mask' prefix it's because is recommended to use masked maps (unseen values) in the unobserved region
	===============
	Return:
		Figure with 2 subplots. At left a sky region (healpix projection), right subplot the SED.
	"""

	capsize=3
	plt.rc('font', size=16)
	if newnside == None:	
		nside = dictionary['nside']
	else:
		nside = newnside

	pixG = [hp.ang2pix(nside, np.pi / 2 - np.deg2rad(center[1] + DeltaTheta ), 
					   np.deg2rad(center[0] + DeltaPhi) ), ]


	fig,ax = plt.subplots(nrows=1,ncols=2,figsize=(14,5),)
	ax = ax.ravel()
	IPIXG = pixG[0] 
	color = ['g','g','k']
	label = ['dust', 'synchrotron', 'dust+synchrotron']
	marker = ['d', 's', 'o']

	mask = covmap > 0.01 * np.max(covmap)
	mask = mask[0]
	print(mask.shape) 

	if mapsarray:
		if intensity:
			for j, imap in enumerate(maskmaps):
				print(imap[:,IPIXG,0])
				ax[1].plot(nus_out, imap[:,IPIXG,0], marker = marker[j], color=color[j], label = label[j],
					linestyle = "")
			ax[1].legend()
			ax[1].set_yscale("log")
			ax[0].cla()	
			plt.axes(ax[0])
			hp.gnomview(maskmaps[-1][-1,:,0], reso = 15,hold = True, title = ' ',unit = r'$\mu$K$_{CMB}$', notext =True,
						min = 0 ,
						max = 0.23 * np.max(maskmaps[2][-1,:,0]), rot = center)
		elif not intensity:
			for j, imap in enumerate(maskmaps):
				#print(np.sqrt(imap[:,IPIXG,1]**2 + imap[:,IPIXG,2]**2))
				ax[1].plot(nus_out, np.sqrt(imap[:,IPIXG,1]**2 + imap[:,IPIXG,2]**2), 
					marker = marker[j], color=color[j], label = label[j],
					linestyle = "")
			ax[1].legend()
			ax[1].set_yscale("log")
			ax[0].cla()	
			plt.axes(ax[0])
			maximum = np.max(np.sqrt(maskmaps[-1][-1,mask,1]**2 + maskmaps[-1][-1,mask,2]**2))
			print(maximum)
			visumap = np.sqrt(maskmaps[-1][-1,:,1]**2 + maskmaps[-1][-1,:,2]**2)
			visumap[~mask] = hp.UNSEEN
			hp.gnomview(visumap, 
				reso = 15,hold = True, title = ' ',
				unit = r'$\mu$K$_{CMB}$', notext =True,
				min = -80 ,
				max = 80, rot = center)

	else:
		ax[1].plot(nus_out, maskmaps[:,IPIXG,0], 'o-', color='r')
		ax[0].cla()
		plt.axes(ax[0])
		hp.gnomview(maskmaps[-1,:,0], reso = 15,hold = True, title = ' ',unit = r'$\mu$K$_{CMB}$', notext =True,
					min = 0 ,
					max = 0.23 * np.max(maskmaps[-1,:,0]), rot = center)
	hp.projscatter(hp.pix2ang(dictionary['nside'], IPIXG), marker = '*', color = 'r',s = 180)
	ylim = ax[1].get_ylim()
	xlim = ax[1].get_xlim()
	#ax[1].set_ylim(ylim[0], ylim[1]*2)
	if set_logscale:
		ax[1].set_xscale("log")
		ax[1].set_yscale("log")
		#ax[1].set_xticks([150, 220], ['150','220'])
		ax[1].xaxis.set_major_formatter(mtick.FormatStrFormatter('%.1f'))
		ax[1].xaxis.set_minor_formatter(mtick.ScalarFormatter())
		ax[1].tick_params(axis = "both", which = "both",
		                  direction='in',width=1.3,)
	ax[1].grid(which="both")

	ax[1].set_ylabel(r'$I_\nu$ [$\mu$K$_{CMB}$]' if intensity else r'$P_\nu$ [$\mu$K$_{CMB}$]')
	ax[1].set_xlabel(r'$\nu$[GHz]')
	dpar = 10
	dmer = 20
	#Watch out, the names are wrong (change it)
	mer_coordsG = [ center[0] - dmer,   center[0], center[0] + dmer]
	long_coordsG = [center[1] - 2*dpar, center[1] - dpar, center[1], 
					center[1] + dpar,   center[1] + 2 * dpar]
	#paralels
	for ilong in long_coordsG:
		plt.text(np.deg2rad(mer_coordsG[0] - 13), 1.1*np.deg2rad(ilong), 
				 r'{}$\degree$'.format(ilong))
	#meridians
	for imer in mer_coordsG:
		if imer < 0:
			jmer = imer + 360
			ip, dp = divmod(jmer/15,1)
		else:
			ip, dp = divmod(imer/15,1)
		if imer == 0:
			plt.text(-np.deg2rad(imer + 3), np.deg2rad(long_coordsG[-1] + 6), 
				 r'{}$\degree$'.format(int(ip) ))
		else:
			plt.text(-np.deg2rad(imer + 3), np.deg2rad(long_coordsG[-1] + 6), 
				 r'{}$\degree$'.format(imer))

	hp.projtext(mer_coordsG[1] + 2, long_coordsG[0] - 6, '$l$',  color = 'k', lonlat=True)
	hp.projtext(mer_coordsG[2] + 12.5, long_coordsG[2] - 1, '$b$', rotation = 90, color = 'k', lonlat=True)
	hp.graticule(dpar = dpar, dmer = dmer, alpha = 0.6, verbose = False)
	plt.tight_layout()
	if savefig:
		plt.savefig('SED-components.svg', format = 'svg',  bbox_inches='tight')
		plt.savefig('SED-components.pdf', format = 'pdf',  bbox_inches='tight')
		plt.savefig('SED-components',  bbox_inches='tight')
	plt.show()
Пример #32
0
cut = np.logical_or(cut, labels == crab)
ax.legend(handles[cut], labels[cut], loc=2)
fig.tight_layout()

# Plot the histogram of redshifts
fig = plt.figure(2)
ax = fig.add_subplot(111)

nZ, Zbins, Zedges, Zwidths = zhist.GetHistogram()
ax.bar(Zedges[:-1], nZ, width=Zwidths, fc="#aaaaff")  #log=True, alpha=0.3)
ax.set_xlabel("redshift")
ax.set_ylabel("count")
ax.set_title("1FHL Redshift Distribution")
ax.grid(True)
fig.tight_layout()

# Plot the distribution of points on the sky
title = r"GeV Sources within 50$^\circ$ of HAWC Zenith"
if args.mapTitle:
    title = args.mapTitle

fig = plt.figure(3, figsize=(9, 5))
hp.mollview(fig=3, coord="CG", title=title, rot=0)
Decs = [90 * degree - d for d in Decs]
fmax = np.max(iFlux)
size = [100 * np.sqrt(1e14 * f) for f in iFlux]
hp.projscatter(Decs, RAs, coord="CG", s=size, alpha=0.3)
hp.graticule(coord="G", dpar=15, dmer=30)

plt.show()
Пример #33
0
# In[23]:

from astropy.io import fits
hdr1 = fits.getheader(aligo_alert_data_file)


# plot the banana map
fig = plt.figure(2, figsize=(10, 10))
hp.mollview(aligo_banana, title='aLIGO alert Likelihood level', flip="astro",
            unit='$\Delta$', fig=2)
fig.axes[1].texts[0].set_fontsize(8)

#mean_zenith_ra = 15.*(alpha_observable_max.hour+alpha_observable_min.hour)/2.
#zenith_dec = float(ephem.degrees(macon.lat*180./m.pi))

hp.projscatter(mean_zenith_ra, zenith_dec
               , lonlat=True, color="red")
hp.projtext(mean_zenith_ra, zenith_dec,
            'Macon Zenith\n (mean position\n over the night)', lonlat=True, color="red")
for ra in range(0,360,60):
    for dec in range(-60,90,30):
        if not (ra == 300 and dec == -30):
                hp.projtext(ra,dec,'({}, {})'.format(ra,dec), lonlat=True, color='red')

hp.graticule()

plt.savefig(os.path.join(plots, 'allsky_likelihoodmap.png'), dpi=300)
#plt.show()


# In[28]:
Пример #34
0
else:
	print("# Choosing pixels from pixel number")

# Where the sky pixel is in the reduce format (pixels seen array and not full map)
pixQ_red = np.where(np.where(cov_ud[0] == True)[0] == pixQ_ud)[0][0]
pixG_red = np.where(np.where(cov_ud[2] == True)[0] == pixG_ud)[0][0]
print("# Done. Pixel in QUBIC FOV: {} \n \t Pixel in galactic center FOV: {}".format(pixQ_ud, pixG_ud))
print("# Reduce array. Pixel in QUBIC FOV: {} \n \t Pixel in galactic center FOV: {}".format(pixQ_red, pixG_red))

plt.figure(figsize = (10,4))
hp.gnomview(maps_ud[2,-1,:,0], reso = 15,#hold = True, 
			notext = False, title = 'G patch ', sub = (121),
			max = 0.4*np.max(maps_ud[2,-1,:,0]), 
			unit = r'$\mu$K',
			rot = centers[2])
hp.projscatter(hp.pix2ang(nside_new, pixG_ud), marker = '*', color = 'r', s = 200)
hp.gnomview(maps_ud[1,-1,:,0], reso = 15, title = 'Q patch ',
			unit = r'$\mu$K', sub = (122),
			rot = centerQ)
hp.projscatter(hp.pix2ang(nside_new, pixQ_ud), marker = '*', color = 'r', s = 200)
hp.graticule(dpar = 10, dmer = 20, alpha = 0.6, verbose = False)
plt.show()

print("# Preparing for run MCMC ")
_, nus150, nus_out150, _, _, _ = qubic.compute_freq(dictionaries[0]['filter_nu'] / 1e9,  
							dictionaries[0]['nf_recon'],
							dictionaries[0]['filter_relative_bandwidth'])
_, nus220, nus_out220, _, _, _ = qubic.compute_freq(dictionaries[1]['filter_nu'] / 1e9,  
							dictionaries[1]['nf_recon'],
							dictionaries[1]['filter_relative_bandwidth'])
nus_out = [nus_out150, nus_out220, nus_out150, nus_out220]
Пример #35
0
    elif opts.coord.upper() == "CEL":
        coord = 'GC'
    if opts.proj.upper() == "MOL":
        #map = numpy.where( map < 20, healpy.UNSEEN, map)
        healpy.mollview(map,coord=coord,xsize=1000,min=20)
    elif opts.proj.upper() == "CAR":
        healpy.cartview(map,coord=coord,xsize=1000)
    else:
        raise Exception("...")
    healpy.graticule()

    if opts.targets:
        targets = numpy.genfromtxt(opts.targets,unpack=True,dtype=None)
        if not targets.shape: targets = targets.reshape(-1)
        coord = 'CG' # For RA/DEC input
        healpy.projscatter(targets['f1'],targets['f2'],
                           lonlat=True,coord=coord,marker='o',c='w')
        fig = plt.gcf()
        # This is pretty hackish (but is how healpy does it...)
        for ax in fig.get_axes():
            if isinstance(ax,healpy.projaxes.SphericalProjAxes): break

        for target in targets:
            text = TARGETS[target[0]][0]
            kwargs = TARGETS[target[0]][1]
            glon,glat = celToGal(target[1],target[2])

            vec = healpy.rotator.dir2vec(glon,glat,lonlat=True)
            vec = (healpy.rotator.Rotator(rot=None,coord='G',eulertype='Y')).I(vec)

            x,y = ax.proj.vec2xy(vec,direct=False)
            ax.annotate(text,xy=(x,y),xycoords='data',**kwargs)
Пример #36
0
fluxplot = [(i * 100) / max(flux) for i in flux]
#fluxplot=[(np.log10(i)*30)/np.log10(max(flux)) for i in flux]

#Rot = 180 shifts the axis from the center to the edge
#centered by default
hp.mollview(title='Equatorial Map of SwiftBAT AGNs',
            cbar=False,
            rot=180,
            notext=True,
            cmap=None,
            coord='C')
hp.graticule(coord='C', color='DimGrey')
py.title(r"wrongdec - Equatorial", fontsize=25, fontweight='bold')
#hp.projscatter(0,0,coord='G',lonlat=True) # This one used to test GC
hp.projscatter(ra, dec, coord='C', lonlat=True, s=fluxplot)
hp.projtext(185, 2, '180', lonlat=True, fontweight='bold')
hp.projtext(95, 2, '90', lonlat=True, fontweight='bold')
hp.projtext(275, 2, '270', lonlat=True, fontweight='bold')
hp.projtext(8, 2, '0', lonlat=True, fontweight='bold')
hp.projtext(359, 2, '360', lonlat=True, fontweight='bold')
hp.projtext(193, -8, 'RA (deg)', lonlat=True, fontweight='bold')
hp.projtext(350, 30, '30', lonlat=True, fontweight='bold')
hp.projtext(340, 60, '60', lonlat=True, fontweight='bold')
#hp.projtext(5, -5, 'Dec (deg)', lonlat=True)
hp.projtext(358, -33.5, '-30', lonlat=True, fontweight='bold')
hp.projtext(358, -63.5, '-60', lonlat=True, fontweight='bold')
ra_gplane = np.arange(0., 361., 1.)
dec_gplane = np.zeros(len(ra_gplane))

hp.projplot(ra_gplane,
Пример #37
0
def getObsWindow(date, obs_window):
    # ===================================
    # date is a string with the
    # Universal time, e.g. '2019/3/9 5:13'
    # obs_window is the radius(in degrees)
    # of the maximum deviation from the
    # Sun's antipodal point that HaloSat
    # is allowed to observe.
    # ===================================

    # Define the Sun object
    # ----------------------
    sun = ephem.Sun()

    # Define the observer
    # -------------------
    halosat = ephem.Observer()
    halosat.date = date

    # Get the location of the Sun
    # ----------------------------
    sun.compute(halosat)
    hours = ephem.hours
    deg = ephem.degrees

    # Print out the antipodal point
    # -------------------------------
    print('On the data', halosat.date)
    print('The RA of the Sun is', sun.ra)
    print('The Dec of the Sun is', sun.dec)
    print('So the HaloSat will observe')
    win_ra = hours(sun.ra + pi).norm
    win_dec = deg(sun.dec * (-1.))
    print('      RA ', win_ra)
    print('      DEC', win_dec)

    # Read map of the galaxy for plotting the window
    # ----------------------------------------------
    map = hp.read_map('ROSAT_Total_hp_filt.fits')
    cone_radius = obs_window / 57.2958  # convert to radians

    # Convert to Galactic coordinates
    # -------------------------------
    ap = ephem.Equatorial(win_ra, win_dec, epoch='2000')
    sp = ephem.Equatorial(sun.ra, sun.dec, epoch='2000')
    g = ephem.Galactic(ap)
    s = ephem.Galactic(sp)
    print(g.lon, g.lat)
    vec = hp.ang2vec(g.lon * 57.4, g.lat * 57.2958, lonlat=True)
    local = hp.query_disc(512, vec, cone_radius)
    map[local] = nan
    hp.mollview(map,
                max=6000,
                title='Date: ' + str(halosat.date) + ', Window Center: [RA ' +
                str(win_ra) + ', DEC ' + str(win_dec) + ']')
    hp.projtext(g.lon * 57.2958 + 20,
                g.lat * 57.2958,
                'Obs Window',
                lonlat=True,
                coord='G',
                fontsize=20)
    hp.projscatter(s.lon * 57.2958,
                   s.lat * 57.2958,
                   lonlat=True,
                   s=55,
                   coord='G',
                   color='yellow')
    hp.projtext(s.lon * 57.2958 - 5,
                s.lat * 57.2958,
                'Sun',
                lonlat=True,
                coord='G',
                fontsize=20)
Пример #38
0
def projected_density_plot(
        hitmap,
        figname     = "skyplot.png",
        title       = "", 
        mincount    = 35, 
        maxcount    = 40, 
        NSIDE       = 512, 
        dpi         = 150, 
        xsize       = 2000, 
        inertia     = [], 
        walldir     = [], 
        filamentdir = [], 
        cmap        = cm_plusmin(under="w"),
        cbar        = True, 
        grid        = False,
        scale       = "log",
        ):

    if scale == "log":
        displayhitmap   = np.log10(hitmap) 
    else:
        displayhitmap   = hitmap

    if mincount == "auto":
        mincount = min(displayhitmap)
    if maxcount == "auto":
        maxcount = max(displayhitmap)

    hp.mollview(
            displayhitmap, 
            xsize   = xsize, 
            norm    = 'lin', 
            min     = mincount, 
            max     = maxcount,
            title   = title, 
            cbar    = cbar, 
            cmap    = cmap,
            )

    if grid: hp.graticule()

    if len(filamentdir)!=0:
        filament = hp.vec2ang(filamentdir)
        anti_filament = hp.vec2ang(-filamentdir)
        hp.projscatter(filament, color='#ffff99')
        hp.projscatter(anti_filament, color='#ffff99')

    if len(walldir)!=0:
        wall = hp.vec2ang(walldir)
        anti_wall = hp.vec2ang(-walldir)
        hp.projscatter(wall, color='#ff99ff')
        hp.projscatter(anti_wall, color='#ff99ff')

    if len(inertia)!=0:
        inertia_axis_a = hp.vec2ang(inertia[0])
        anti_inertia_axis_a = hp.vec2ang(-inertia[0])
        inertia_axis_b = hp.vec2ang(inertia[1])
        anti_inertia_axis_b = hp.vec2ang(-inertia[1])
        inertia_axis_c = hp.vec2ang(inertia[2])
        anti_inertia_axis_c = hp.vec2ang(-inertia[2])
        hp.projscatter(inertia_axis_a, color='r')
        hp.projscatter(anti_inertia_axis_a, color='r')
        hp.projscatter(inertia_axis_b, color='y')
        hp.projscatter(anti_inertia_axis_b, color='y')
        hp.projscatter(inertia_axis_c, color='g')
        hp.projscatter(anti_inertia_axis_c, color='g')

    print "#saving fig as %s"%figname
    plt.savefig(
            figname, 
            dpi = dpi,
            #bbox_inches='tight',
            )
    plt.clf()
    return
Пример #39
0
def get_map():
    # Get current time
    now = Time.now()
    T = datetime.utcnow() + timedelta(hours=0)
    T = Time(T, format="datetime")
    loc = astropy.coordinates.EarthLocation(lon=22.13303, lat=-31.58)

    ra = (T.sidereal_time("mean", longitude=22.13303)) / u.hourangle
    lon = ra * 15 - 360
    rot = [(lon), -31.58]
    sid_time = T.sidereal_time("mean", longitude=22.13303)
    sidstr = sid_time.to_string()
    print(sidstr)

    moon = astropy.coordinates.get_moon(T, location=loc, ephemeris=None)
    sun = astropy.coordinates.get_sun(T)

    ssbodies = ["mercury", "venus", "mars", "jupiter", "saturn", "neptune", "uranus"]
    colors = ["grey", "pink", "red", "orange", "yellow", "blue", "blue", "blue"]

    pic = astropy.coordinates.SkyCoord(
        ra="05h19m49.7230919028", dec="-45d 46m 44s"
    )  # Pictor
    forn = astropy.coordinates.SkyCoord(ra="03h23m25.1s", dec="-37d 08m")
    cass = astropy.coordinates.SkyCoord(ra="23h 23m 24s", dec="+58d 48.9m")
    crab = astropy.coordinates.SkyCoord(ra="05h 34m 31s", dec="+22d 00m 52.2s")
    lmc = astropy.coordinates.SkyCoord(ra="05h 40m 05s", dec="-69d 45m 51s")
    smc = astropy.coordinates.SkyCoord(ra="00h 52m 44.8s", dec="-72d 49m 43s")
    cenA = astropy.coordinates.SkyCoord(ra="13h 25m 27.6s", dec="-43d 01m 09s")
    callibrator1 = astropy.coordinates.SkyCoord(
        ra=109.32351 * u.degree, dec=-25.0817 * u.degree
    )
    callibrator2 = astropy.coordinates.SkyCoord(
        ra=30.05044 * u.degree, dec=-30.89106 * u.degree
    )
    callibrator3 = astropy.coordinates.SkyCoord(
        ra=6.45484 * u.degree, dec=-26.0363 * u.degree
    )

    source_list = [
        [moon, "moon", "slategrey"],
        [sun, "sun", "y"],
        [pic, "pictor", "w"],
        [forn, "fornax", "w"],
        [cass, "Cass A", "w"],
        [crab, "Crab", "w"],
        [lmc, "LMC", "w"],
        [cenA, "Cen A", "w"],
        [smc, "SMC", "w"],
        [callibrator1, "J071717.6-250454", "r"],
        [callibrator2, "J020012.1-305327", "r"],
        [callibrator3, " J002549.1-260210", "r"],
    ]

    healpy.orthview(
        np.log10(mappy),
        title=sidstr,
        coord=["G", "C"],
        rot=rot,
        return_projected_map=True,
        min=0,
        max=2,
        half_sky=1,
    )

    for item in source_list:
        if item[1] == "sun":
            name = item[1]
            healpy.projscatter(
                item[0].ra, item[0].dec, lonlat=True, s=1000, c=item[2], label=name
            )
            healpy.projtext(item[0].ra, item[0].dec, lonlat=True, color="k", s=name)
        if item[1] == "moon":
            name = item[1]
            healpy.projscatter(
                item[0].ra, item[0].dec, lonlat=True, s=200, c=item[2], label=name
            )
            healpy.projtext(item[0].ra, item[0].dec, lonlat=True, color="k", s=name)
        else:
            name = item[1]
            healpy.projscatter(
                item[0].ra, item[0].dec, lonlat=True, s=50, color=item[2], label=name
            )
            healpy.projtext(item[0].ra, item[0].dec, lonlat=True, color="k", s=name)

    count = 0
    for body in ssbodies:
        name = body
        body = astropy.coordinates.get_body(body, T)
        healpy.projscatter(
            body.ra, body.dec, lonlat=True, s=50, color=colors[count], label=name
        )
        healpy.projtext(body.ra, body.dec, lonlat=True, color="k", s=name)
        count += 1
Пример #40
0
import healpy as hp
import numpy as np
import pylab as pl

hp.mollview(title="Galactic map of Test Fields")
# hp.graticule()

x = [-37, 88, -137, -139, -136, -44]
y = [27, -60, -1.4, -50, -77, -46]
lab = ['TF0.1', 'TF0.2', 'TF0.3', 'TF0.4', 'TF0.5', 'TF0.6' ]

hp.projscatter(x, y, lonlat=True, coord='G')

hp.projtext(-37., 27., 'TF0.1', lonlat=True, coord='G')
hp.projtext(88, -60, 'TF0.2', lonlat=True, coord='G')
hp.projtext(-137, -1.4, 'TF0.3', lonlat=True, coord='G')
hp.projtext(-139, -50, 'TF0.4', lonlat=True, coord='G')
hp.projtext(-136, -77, 'TF0.5', lonlat=True, coord='G')
hp.projtext(-44, -46, 'TF0.6', lonlat=True, coord='G')

# equateur_lon = [-45.,45.]
# equateur_lat = [-30.,30.]
# hp.projplot(equateur_lon, equateur_lat, 'ro-', lonlat=True, coord='G')
pl.show()