Ejemplo n.º 1
0
def make_healpix_image(plt, img, title, num_bins, source_json=None):
    """
    Writes out an image as a healpy image
    """
    nside = hp.pixelfunc.get_min_valid_nside(num_bins*num_bins*3/4)
    npix = hp.nside2npix(nside)

    pixels = np.arange(npix)
    m = np.zeros(npix) + hp.UNSEEN

    window_d = np.degrees(hp.nside2resol(nside))

    for i in pixels:
        theta, phi = hp.pix2ang(nside, i)
        if (theta < np.pi / 2):
            el = np.degrees(np.pi/2 - theta)
            az = np.degrees(phi)
            s = elaz.ElAz(el, az)
            x_min, x_max, y_min, y_max, area = s.get_px_window(num_bins, window_deg=window_d)
            s_px = img[y_min:y_max, x_min:x_max]

            m[i] = np.sum(s_px)/area

    hp.orthview(m, rot=(0, 90, 180), title=title, xsize=3000, cbar=False, half_sky=True)
    hp.graticule()
    if source_json is not None:
        src_list = elaz.from_json(source_json, el_limit=20.0, jy_limit=1e4)
        output_list = []
        for s in src_list:
            l, m = s.get_lm()
            output_list.append(plt.Circle([-l, m], 0.03, color=(0.9, 0.2, 0.3), fill=False))
        ax = plt.gca()
        for circle in output_list:
            ax.add_artist(circle)
Ejemplo n.º 2
0
    def plot(self, plt, src_list):
        """
        Modified plot to deal with the reduced number of pixels
        """
        all_npix = hp.nside2npix(self.nside)
        all_pixels = np.zeros(all_npix) + hp.UNSEEN
        all_pixels[self.pixel_indices] = self.pixels

        rot = (0, 90, 0)
        plt.figure()  # (figsize=(6,6))
        logger.info("self.pixels: {}".format(self.pixels.shape))
        if True:
            hp.orthview(all_pixels,
                        rot=rot,
                        xsize=1000,
                        cbar=True,
                        half_sky=True,
                        hold=False)
            hp.graticule(verbose=False)
        else:
            hp.mollview(all_pixels, rot=rot, xsize=1000, cbar=True)
            hp.graticule(verbose=True)

        if src_list is not None:
            for s in src_list:
                self.plot_x(plt, s.el_r, s.az_r)
Ejemplo n.º 3
0
 def show_CMB_T_map(self,Tmap=None, max=100, title = "CMB graviational potential fluctuations as seen from inside the LSS", from_perspective_of = "observer", cmap=None):
     if Tmap is None:
         self.NSIDE = 256
         self.Tmap = hp.alm2map(self.alm,self.NSIDE)
     else:
         self.Tmap = Tmap
         
     if from_perspective_of == "observer":
         
         dpi = 300
         figsize_inch = 60, 40
         fig = plt.figure(figsize=figsize_inch, dpi=dpi)
         # Sky map:
         hp.mollview(self.Tmap, rot=(-90,0,0),  min=-max, max=max,  title=title + ", $\ell_{max}=$%d " % self.truncated_lmax, cmap=cmap, unit="$\mu$K")
         
         plt.savefig(title+".png", dpi=dpi, bbox_inches="tight")
     
     else:
         # Interactive "external" view ([like this](http://zonca.github.io/2013/03/interactive-3d-plot-of-sky-map.html))            pass
         #   beatbox.zoncaview(self.Tmap)
         # This did not work, sadly. Maybe we can find a 3D
         # spherical surface plot routine using matplotlib? For
         # now, just use the healpix vis.
         R = (0.0,0.0,0.0) # (lon,lat,psi) to specify center of map and rotation to apply
         hp.orthview(self.Tmap,rot=R,flip='geo',half_sky=True,title="CMB graviational potential fluctuations as seen from outside the LSS, $\ell_{max}$=%d" % self.truncated_lmax)
         print "Ahem - we can't visualize maps on the surface of the sphere yet, sorry."
     return
Ejemplo n.º 4
0
 def orth(i, j, panel, ttl=None):
     if ttl is None:
         ttl = str(i) + ', ' + str(j)
     hp.orthview(func(A[:, i, j]),
                 rot=[0, 90],
                 half_sky=True,
                 sub=[5, 4, panel],
                 title=ttl)
def update(val):
    latitude = latitude_slider.val
    longitude = longitude_slider.val
    angle = angle_slider.val
    hp.orthview(data,
                fig=1,
                sub=211,
                half_sky=True,
                rot=(longitude, latitude, angle),
                norm='hist')
Ejemplo n.º 6
0
 def view_healpix(self, n_side=32, show=True):
     """ View the beam pattern as a healpix map
     
     Shows orthographic view of beam pattern, using healpy plotting routines.
     """
     hmap = self.to_healpix(n_side)
     
     hp.orthview(hmap)
     if show:
         plt.show()
Ejemplo n.º 7
0
def displaymaps(zup,cen=[45.,-44.],cmap='inferno'):
        z=zup[::-1]
        i=0
        for (z2,z1) in zip(z[:-1],np.roll(z,-1)):
                myMap=hp.read_map("map{:02d}.fits".format(i))
                fig=plt.figure(figsize=(10,10))
                hp.orthview(myMap,fig=1,half_sky=True,cbar=False,rot=cen,cmap=cmap,title=r"{:.1f}<z<{:.1f}".format(z1,z2),min=-0.4,max=1,margins=(0,0,0,0))
                plt.savefig("map{:02d}.png".format(i))
                plt.close(1)
                i=i+1
Ejemplo n.º 8
0
def plot_skymap(skymap, smooth=None, decmax=None, scale=None, color_bins=40,
                color_palette='viridis', symmetric=False, cbar_min=None,
                cbar_max=None, cbar_title='Skymap', llabel=None, polar=False,
                fig=None, sub=None):

    cpalette = sns.color_palette(color_palette, color_bins)
    cmap = ListedColormap(cpalette.as_hex())
    cmap.set_under('white')
    cmap.set_bad('gray')

    # if cbar_max and cbar_max and symmetric and (cbar_max != -cbar_min):
    #     raise ValueError('The max/min colorbar values can\'t be symmetric')
    # elif cbar_max and cbar_max:
    #     pass
    # elif:
    #     skymap_min = skymap.min()
    #     skymap_max = skymap.max()
    #     maximum = np.max(np.abs([skymap_min, skymap_max]))
    #     cbar_min = np.sign(skymap_min) * maximum
    #     cbar_max = np.sign(skymap_max) * maximum
    # else:
    #     cbar_min = cbar_min if cbar_min else skymap.min()
    #     cbar_max = cbar_max if cbar_max else skymap.max()

    if polar:
        shrink = 0.6
        rot = [0,-90,180]
        hp.orthview(skymap, half_sky=True, rot=rot, coord='C', title='',
                    min=cbar_min, max=cbar_max, cbar=False, cmap=cmap,
                    fig=fig, sub=sub)
    else:
        shrink = 1.0
        hp.mollview(skymap, rot=180, coord='C', title='', min=cbar_min,
                    max=cbar_max, cbar=False, cmap=cmap, fig=fig, sub=sub)
    hp.graticule(verbose=False)

    fig = plt.gcf()
    ax = plt.gca()
    image = ax.get_images()[0]
    cbar = fig.colorbar(image, orientation='horizontal', aspect=50,
                        pad=0.01, fraction=0.1, ax=ax,
                        format=FormatStrFormatter('%g'),
                        shrink=shrink)
    if cbar_title:
        cbar.set_label(cbar_title, size=14)

    if not polar:
        ax.set_ylim(-1, 0.005)
        ax.annotate('0$^\circ$', xy=(1.8, -0.75), size=14)
        ax.annotate('360$^\circ$', xy=(-1.99, -0.75), size=14)

    if llabel:
        ax.annotate(llabel, xy=(-1.85,-0.24), size=20, color='white')

    return fig, ax
Ejemplo n.º 9
0
def plot_efield_beams(xt,xp,yt,yp,rot=[0,0],minv = [-1,-1,-1,-1],maxv=[1,1,1,1],figno=1):
    
    A = [xt,xp,yt,yp]
    plt.figure(figno)
    plt.clf()
    for a in range(4):
        hp.orthview(A[a],half_sky=True,sub=(2,2,a+1),min=minv[a],max=maxv[a],rot=rot)
        #plt.title(beam_labels[a,b])
        hp.graticule()
#    plt.show()
    return
Ejemplo n.º 10
0
    def show_CMB_T_map(
            self,
            Tmap=None,
            max=100,
            title="CMB graviational potential fluctuations as seen from inside the LSS",
            from_perspective_of="observer",
            cmap=None):
        if Tmap is None:
            self.NSIDE = 256
            self.Tmap = hp.alm2map(self.alm, self.NSIDE)
        else:
            self.Tmap = Tmap

        if from_perspective_of == "observer":

            dpi = 300
            figsize_inch = 60, 40
            fig = plt.figure(figsize=figsize_inch, dpi=dpi)
            # Sky map:
            hp.mollview(self.Tmap,
                        rot=(-90, 0, 0),
                        min=-max,
                        max=max,
                        title=title +
                        ", $\ell_{max}=$%d " % self.truncated_lmax,
                        cmap=cmap,
                        unit="$\mu$K")

            plt.savefig(title + ".png", dpi=dpi, bbox_inches="tight")

        else:
            # Interactive "external" view ([like this](http://zonca.github.io/2013/03/interactive-3d-plot-of-sky-map.html))            pass
            #   beatbox.zoncaview(self.Tmap)
            # This did not work, sadly. Maybe we can find a 3D
            # spherical surface plot routine using matplotlib? For
            # now, just use the healpix vis.
            R = (
                0.0, 0.0, 0.0
            )  # (lon,lat,psi) to specify center of map and rotation to apply
            hp.orthview(
                self.Tmap,
                rot=R,
                flip='geo',
                half_sky=True,
                title=
                "CMB graviational potential fluctuations as seen from outside the LSS, $\ell_{max}$=%d"
                % self.truncated_lmax)
            print "Ahem - we can't visualize maps on the surface of the sphere yet, sorry."
        return
Ejemplo n.º 11
0
 def plot(self, plt, sphere, src_list):
     rot = (0, 90, 0)
     plt.figure() # (figsize=(6,6))
     logger.info('sphere.pixels: {}'.format(sphere.pixels.shape))
     if True:
         hp.orthview(sphere.pixels, rot=rot, xsize=1000, cbar=True, half_sky=True, hold=True)
         hp.graticule(verbose=False)
         plt.tight_layout()
     else:
         hp.mollview(sphere.pixels, rot=rot, xsize=1000, cbar=True)
         hp.graticule(verbose=True)
     
     if src_list is not None:
         for s in src_list:
             sphere.plot_x(s.el_r, s.az_r)
Ejemplo n.º 12
0
    def view(self, logged=False, show=False, **kwargs):
        """ View the local sky, in orthographic projection.

        Parameters
        ----------
        logged: bool
            Default False, return the log2 image
        """
        sky = self.observed_sky
        if logged:
            sky = np.log2(sky)

        hp.orthview(sky, half_sky=True, **kwargs)

        if show:
            show_plt()
        return sky
Ejemplo n.º 13
0
 def plot_polarisation(sky,
                       fig=3,
                       title="",
                       mode=3,
                       sub=(1, 2, 1),
                       show=False):
     import matplotlib.pyplot as plt
     assert (isinstance(mode, int) and 0 <= mode < 4) or isinstance(mode, str), \
         "Mode should be an integer between 0 and 3, or a string of the form 'bb' where b is for binary."
     if isinstance(mode, str):
         mode = (int(mode[0]) << 1) + (int(mode[1]) << 0)
     sub2 = sub[2]
     lon, lat = sun2lonlat(sky.sun)
     f = plt.figure(fig, figsize=(15, 5))
     if (mode >> 1) % 2 == 1:
         hp.orthview(sky.DOP,
                     rot=SkyModel.VIEW_ROT,
                     min=0,
                     max=1,
                     flip="geo",
                     cmap="Greys",
                     half_sky=True,
                     title="Degree of (linear) Polarisation",
                     unit=r'',
                     sub=(sub[0], sub[1], sub2),
                     fig=fig)
         sub2 += 1
     if (mode >> 0) % 2 == 1:
         hp.orthview(sky.AOP,
                     rot=SkyModel.VIEW_ROT,
                     min=0,
                     max=np.pi,
                     flip="geo",
                     cmap="Greys",
                     half_sky=True,
                     title="Angle of (linear) Polarisation",
                     unit=r'rad',
                     sub=(sub[0], sub[1], sub2),
                     fig=fig)
         sub2 += 1
     hp.projplot(lat, lon, 'yo')
     f.suptitle(title)
     if show:
         plt.show()
     return f
Ejemplo n.º 14
0
    def view(self, logged=False, show=False, **kwargs):
        """ View the local sky, in orthographic projection.

        Parameters
        ----------
        logged: bool
            Default False, return the log2 image
        """
        sky = self.observed_sky
        if logged:
            sky = np.log2(sky)

        hp.orthview(sky, half_sky=True, **kwargs)

        if show:
            plt.show()

        return sky
Ejemplo n.º 15
0
def orth(base_UT22, start_UT22, unit, show=False):
    UT22_interp = np.zeros_like(base_UT22)
    c = 0
    for i, val in enumerate(start_UT22):
        if np.isnan(val):
            c += 1
            theta, phi = hp.pix2ang(nside, i)
            neybs = hp.get_neighbours(nside, theta, phi=phi) 
            UT22_interp[i] = np.nanmean(start_UT22[neybs[0]])

        else:
            UT22_interp[i] = val

    print(c, 'NaN vals')

    hp.orthview(UT22_interp, rot=[0, 90], min=0, max=2, unit=unit, title='SAST 00:00 2012-02-13', half_sky=True)
    if show:
        pylab.show()

    return UT22_interp
Ejemplo n.º 16
0
def make_healpix_image(plt, img, title, num_bins, source_json=None):
    """
    Writes out an image as a healpy image
    """
    nside = hp.pixelfunc.get_min_valid_nside(num_bins * num_bins * 3 / 4)
    npix = hp.nside2npix(nside)

    pixels = np.arange(npix)
    m = np.zeros(npix) + hp.UNSEEN

    window_d = np.degrees(hp.nside2resol(nside))

    for i in pixels:
        theta, phi = hp.pix2ang(nside, i)
        if theta < np.pi / 2:
            el = np.degrees(np.pi / 2 - theta)
            az = np.degrees(phi)
            s = elaz.ElAz(el, az)
            x_min, x_max, y_min, y_max, area = s.get_px_window(
                num_bins, window_deg=window_d)
            s_px = img[y_min:y_max, x_min:x_max]

            m[i] = np.sum(s_px) / area

    hp.orthview(m,
                rot=(0, 90, 180),
                title=title,
                xsize=3000,
                cbar=False,
                half_sky=True)
    hp.graticule()
    if source_json is not None:
        src_list = elaz.from_json(source_json, el_limit=20.0, jy_limit=1e4)
        output_list = []
        for s in src_list:
            l, m = s.get_lm()
            output_list.append(
                plt.Circle([-l, m], 0.03, color=(0.9, 0.2, 0.3), fill=False))
        ax = plt.gca()
        for circle in output_list:
            ax.add_artist(circle)
Ejemplo n.º 17
0
    def mapplot(self, mapstr=None, coord="C", norm="hist", **kwargs):
        """

        Plots a molliweide projection of a map using healpy.mollview

        Parameters
        ----------
        mapstr : str, {"mapname", "all"} or None
            Name of the map that should be plotted. Running with no
            arguments will list the available maps for plotting.

        kwargs
            Optional arguments passed to healpy.mollview
            Default coord="C", norm="hist"

        """

        if isnone(mapstr):
            print("Here's the available keys:")
            print(list(self.maps.keys()))
        elif mapstr == 'all':
            [
                hp.orthview(self.maps[ms].values,
                            title=ms,
                            coord=coord,
                            norm=norm,
                            **kwargs) for ms in self.maps.keys()
            ]
        else:
            try:
                hp.orthview(self.maps[mapstr],
                            title=mapstr,
                            coord=coord,
                            norm=norm,
                            **kwargs)
                hp.graticule()
            except KeyError:
                print("The map ''" + mapstr + "'' does not exist!")
                print("Here's the available keys:")
                print(list(self.maps.keys()))
                return 0
Ejemplo n.º 18
0
        def view(self, logged=False, show=False, **kwargs):
            """ View the local sky, in orthographic projection.
	
			Parameters
			----------
			logged: bool
				Default False, return the log2 image
			"""
            import healpy as hp
            import pylab as plt
            sky = self.observed_sky
            if logged:
                import numpy as np
                sky = np.log2(sky)

            hp.orthview(sky, half_sky=True, **kwargs)

            if show:
                plt.show()

            return sky
Ejemplo n.º 19
0
def plot_leakage_beams(nom_vis,rot=[0,0],mn=-2,mx=0,log=True,figno=2):
    if log:
        nom_vis_to_plot = np.log10(np.abs(nom_vis.copy()))
    else:
        nom_vis_to_plot = nom_vis.copy()
    fig = plt.figure(figno)
    plt.clf()
    for a in range(4):
        for b in range(4):
            if (a==b) and (not log):
                mn_plot = 0
                mx_plot = 1
            else:
                mn_plot = mn
                mx_plot = mx
            print mn_plot, mx_plot
            hp.orthview(nom_vis_to_plot[a,b,:],half_sky=True,title='',sub=(4,4,4*a+b+1),min=mn_plot,max=mx_plot,rot=rot)#,margins=[0.1,0.9,0.9,0.1])
        hp.graticule()
    #fig.tight_layout()
#    plt.show()

    return
Ejemplo n.º 20
0
    def create_background(self):

#        hp.orthview(map=self.background, rot=[0.0,270.0,0.0], coord=['G','C'], half_sky=True, notext=True, min=-400, max=400, xsize=3000)

        m = self.background * self.factor + self.offset * self.factor
        msinh = np.arcsinh(m * 0.5)/np.log(10.0)

        cbticks = np.array([-500.0,0.0,100.0,1000.0, 1e6])
        cbticklabels = np.array([r'$-500$',r'$0$',r'$100$',r'$1000$',r'$10^6$'])
        cbticks = np.arcsinh( (cbticks-80.0) * 0.5) / np.log(10.0)
         
        if not (self.bad_pixels is None):
            msinh[self.bad_pixels] = -1.6375e30
        
        if (self.cbar):
            orth = hp.orthview(map=msinh, rot=[0.0,270.0,0.0], coord=[self.input_coord,'C'], half_sky=True, notext=True, xsize=3000, cmap=self.planck_color_map(), min=-3.1, max=7, cbticks=cbticks, cbticklabels=cbticklabels, title=self.title, cbtitle=r'$\mathrm{\mu K}$', sub=self.sub, return_projected_map=True)
        else:
            orth = hp.orthview(map=msinh, rot=[0.0,270.0,0.0], coord=[self.input_coord,'C'], half_sky=True, notext=True, xsize=3000, cmap=self.planck_color_map(), min=-3.1, max=7, cbar=False, title=self.title, sub=self.sub, return_projected_map=True)

#        self.create_spt_area()
#        self.create_graticule([160,140,120,100], np.arange(0,360,45))
#        plt.savefig('test.png', format='png', dpi=600)

        return orth
Ejemplo n.º 21
0
    def view(self, inclination=90*u.deg, phase=0.0, what='fluxes',
             projection='mollweide', cmap='magma',
             savefig=False, filename='star_surface.png',
             dlat=30, dlon=30, **kwargs):
        rot = (360*phase, 90-inclination.to(u.deg).value, 0)
        if what == 'fluxes':
            vals = self.tile_fluxes * self.tile_scales
            vals = vals / vals.max()
        elif what == 'areas':
            vals = self.tile_areas / self.tile_areas.max()

        if 'mollweide'.find(projection) == 0:
            hp.mollview(vals, rot=rot, cmap=cmap, **kwargs)
        elif 'cartesian'.find(projection) == 0:
            hp.cartview(vals, rot=rot, cmap=cmap, **kwargs)
        elif 'orthographic'.find(projection) == 0:
            hp.orthview(vals, rot=rot, cmap=cmap, **kwargs)
        else:
            raise ValueError('Unrecognised projection')
        hp.graticule(dlat, dlon)
        if savefig:
            plt.savefig(filename)
        else:
            plt.show()
Ejemplo n.º 22
0
def plot_healpix_projection(file,
                            nside,
                            outside=False,
                            rotp=True,
                            multiple=False,
                            **kwargs):
    import matplotlib.pyplot as plt
    import matplotlib.colors as colors
    try:
        mesh = ToMesh(file, rot=rotp, tr=0.)
        data = ProjectOnSphere(nside, mesh, outside, multiple)
    except:
        print("Exception during transform of {}".format(file))
        raise
    im1 = data[:, 0]
    id_im = os.path.splitext(os.path.basename(file))[0]
    cm = plt.cm.RdBu_r
    cm.set_under('w')
    cmin = np.min(im1)
    cmax = np.max(im1)
    im1[im1 > cmax] = np.nan
    #norm = colors.LogNorm(vmin=cmin, vmax=cmax)
    #norm = colors.PowerNorm(gamma=4)
    hp.orthview(im1,
                title='',
                nest=True,
                cmap=cm,
                min=cmin,
                max=cmax,
                **kwargs)
    plt.plot()
    if multiple:
        hp.orthview(data[:, 1],
                    title=id_im,
                    nest=True,
                    cmap=cm,
                    min=cmin,
                    max=cmax,
                    norm=norm)
        plt.plot()
        hp.orthview(data[:, 2],
                    title=id_im,
                    nest=True,
                    cmap=cm,
                    min=cmin,
                    max=cmax,
                    norm=norm)
    return im1
Ejemplo n.º 23
0
def test(nested=False):

    # test map previously masked and smoothed by gauss_beam 30'
    #testMap = '/Data/planckMaskedSmoothed.fits'
    # test map previously smoothed by gauss_beam 30'
    testMap = '/Data/planckSmoothed.fits'
    # test mask previously smoothed by gauss_beam 30'
    testMask = '/Data/pMaskSmoothed.fits'

    # test get_temps
    #result = get_temps(testMap,radius=3.5,maskFile=testMask,nside=2048,nested=nested)
    #print 'get_temps result: ',result

    # test getSDSSrnd
    result = getSDSSrnd()
    print 'getSDSSrnd result: ',result

    # 2d histogram in healpix map; check uniformity
    nside = 32
    nrnd = 1000#0
    title = 'test of random coordinate generator'
    mapArray = np.zeros(hp.nside2npix(nside))
    for drawNum in range(nrnd):
        print 'draw ',drawNum+1,' of ',nrnd
        randomCoord = getSDSSrnd()
        print 'random coord: ',randomCoord
        randomVec = mm.glgb2vec(randomCoord[0],randomCoord[1]) #returns array of unit vectors
        randomPix = hp.query_disc(nside,randomVec,1e-5,nest=nested,inclusive=True)
        print 'random pixel: ',randomPix[0]
        mapArray[randomPix[0]] += 1.0
    projected = hp.orthview(mapArray,rot=[180,35],coord=['C'],half_sky=True, #,coord=['G','C']
                          nest=nested,flip='geo',title=title)
    hp.graticule(dpar=30,dmer=30)
    plt.show()

    # test checknoise
    cSN,vSN = checknoise(testMap,radius=3.5,ntries=100,maskFile=testMask)
    print 'Signal to Noise ratios: ', cSN, vSN
Ejemplo n.º 24
0
def showMap(mapFile,
            nested=False,
            return_projected_map=False,
            title='ISW map over SDSS region'):
    """
  Purpose:
      make orthographic plots of maps or masks over the SDSS region
  Note:
      This is translated from IDL function sdss_plot.pro.  The IDL
        graphics are superior to the ones available in python, and
        the plotting functions have more options.
  Args:
      mapFile:
      nested:
      return_projected_map: pass to orthview, get back numpy map
        note: I don't know how to use this now 2016.01.19
      title: the title of the plot
  Returns:
      if return_projected_map is set: the projected map in a numpy array
  """

    #subTitle = 'equitorial coordinates with RA flipped'
    map = hp.read_map(mapFile, nest=nested)
    projected = hp.orthview(map,
                            rot=[180, 35],
                            coord=['G', 'C'],
                            half_sky=True,
                            nest=nested,
                            flip='geo',
                            title=title,
                            return_projected_map=return_projected_map)  #,
    #max=60,min=-60,unit='microK')
    hp.graticule(dpar=30, dmer=30)
    plt.show()

    return projected
Ejemplo n.º 25
0
ras,decs = [],[]
for p in ipix:
    dec,ra = IndexToDeclRa(p)
    ras.append(ra)
    decs.append(dec)
###### 

#dates = ['2012-02-10', '2012-02-11', '2012-02-13', '2012-02-14', '2012-02-15', '2012-02-16', '2012-02-17','2012-02-18', '2012-02-19', '2012-02-20', '2012-02-21',  '2012-02-22']
dates = ['2011-12-06', '2011-12-07', '2011-12-08', '2011-12-09', '2011-12-10', '2011-12-11', '2011-12-12', '2011-12-13', '2011-12-14', '2011-12-15', '2011-12-16', '2011-12-17', '2011-12-18', '2011-12-19', '2011-12-20', '2011-12-21', '2011-12-22', '2011-12-23', '2011-12-24', '2011-12-25', '2011-12-26', '2011-12-27', '2011-12-28', '2011-12-29', '2011-12-30', '2011-12-31', '2012-01-01', '2012-01-02', '2012-01-03', '2012-01-04', '2012-01-05', '2012-01-06', '2012-01-07', '2012-01-08', '2012-01-09', '2012-01-10', '2012-01-11', '2012-01-12', '2012-01-13', '2012-01-14', '2012-01-15', '2012-01-16', '2012-01-17', '2012-01-18', '2012-01-19', '2012-01-20', '2012-01-21', '2012-01-22', '2012-01-23', '2012-01-24', '2012-01-25', '2012-01-26', '2012-01-27', '2012-01-28', '2012-01-29', '2012-01-30', '2012-01-31', '2012-02-01', '2012-02-02', '2012-02-03', '2012-02-04', '2012-02-05', '2012-02-06', '2012-02-07', '2012-02-08', '2012-02-09', '2012-02-10', '2012-02-11', '2012-02-12', '2012-02-13', '2012-02-14', '2012-02-15', '2012-02-16', '2012-02-17', '2012-02-18', '2012-02-19', '2012-02-20', '2012-02-21', '2012-02-22', '2012-02-23', '2012-02-24', '2012-02-25', '2012-02-26', '2012-02-27', '2012-02-28']
if not os.path.exists('%s_to_%s.pkl'%(dates[0],dates[-1])):
    IM = rm.IonoMap('30d43m17.5ss','21d25m41.9se',dates)
    IM.get_radec_RM(ras,decs)

    datadict = {}
    bm = beamPAPER(150.,nside=16)
    bm_map = np.ma.masked_invalid(hp.orthview(bm,return_projected_map=True))[:,:400]
    plt.close() #negate orthview launching xwindow
    datadict['bm'] = bm_map

    for dayindex in range(IM.RMs.shape[0]):
        datadict[dates[dayindex]] = {}
        #TODO convert keys to JDs? would be neater for everything to be numeric
        for ut in range(IM.RMs.shape[1]):
            map = hp.orthview(IM.RMs[dayindex,ut,:],rot=[0,90],return_projected_map=True)
            map = np.ma.masked_invalid(map)[:,:400] #only get above horizon, mask elsewhere
            datadict[dates[dayindex]][ut] = map
            plt.close() #negate orthview launching xwindow
    output = open('%s_to_%s.pkl'%(dates[0],dates[-1]),'wb')
    pickle.dump(datadict,output)
    output.close()
else: print 'Opening %s_to_%s.pkl'%(dates[0],dates[-1])
Ejemplo n.º 26
0
 def plot_sun(sky, fig=1, title="", mode=15, sub=(1, 4, 1), show=False):
     assert (isinstance(mode, int) and 0 <= mode < 16) or isinstance(mode, str), \
         "Mode should be an integer between 0 and 15, or a string of the form 'bbbb' where b is for binary."
     if isinstance(mode, str):
         mode = (int(mode[0]) << 3) + (int(mode[1]) << 2) + (
             int(mode[2]) << 1) + (int(mode[3]) << 0)
     sub2 = sub[2]
     lon, lat = sun2lonlat(sky.sun)
     f = plt.figure(fig, figsize=(15, 5))
     if (mode >> 3) % 2 == 1:
         hp.orthview(sky.theta_z,
                     rot=SkyModel.VIEW_ROT,
                     min=0,
                     max=np.pi,
                     flip="geo",
                     cmap="Greys",
                     half_sky=True,
                     title="Elevation",
                     unit=r'rad',
                     sub=(sub[0], sub[1], sub2),
                     fig=fig)
         sub2 += 1
     if (mode >> 2) % 2 == 1:
         hp.orthview(sky.phi_z,
                     rot=SkyModel.VIEW_ROT,
                     min=0,
                     max=2 * np.pi,
                     flip="geo",
                     cmap="Greys",
                     half_sky=True,
                     title="Azimuth",
                     unit=r'rad',
                     sub=(sub[0], sub[1], sub2),
                     fig=fig)
         sub2 += 1
     if (mode >> 1) % 2 == 1:
         hp.orthview(sky.theta_s,
                     rot=SkyModel.VIEW_ROT,
                     min=0,
                     max=np.pi,
                     flip="geo",
                     cmap="Greys",
                     half_sky=True,
                     title="Elevation",
                     unit=r'rad',
                     sub=(sub[0], sub[1], sub2),
                     fig=fig)
         sub2 += 1
     if (mode >> 0) % 2 == 1:
         hp.orthview(sky.phi_s,
                     rot=SkyModel.VIEW_ROT,
                     min=0,
                     max=2 * np.pi,
                     flip="geo",
                     cmap="Greys",
                     half_sky=True,
                     title="Azimuth",
                     unit=r'rad',
                     sub=(sub[0], sub[1], sub2),
                     fig=fig)
         sub2 += 1
     hp.projplot(lat, lon, 'yo')
     f.suptitle(title)
     if show:
         plt.show()
     return f
Ejemplo n.º 27
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
Ejemplo n.º 28
0
nom_vis = np.zeros([4,4,npix],dtype='complex64')

S = 1./2*np.array([[1.,1,0,0],[0,0,1,1j],[0,0,1,-1j],[1,-1,0,0]])
Sinv = np.array([[1.,0,0,1],[1,0,0,-1],[0,1,1,0],[0,-1j,1j,0]])

for i in range(npix):
    J = A[:,:,i]
    AA[:,:,i] = np.kron(J,J)
    nom_vis[:,:,i] = np.dot(Sinv,np.dot(AA[:,:,i],S)) 

nom_vis = nom_vis.real
    
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
    
beam_labels = np.array([[r'A_x^{\theta}',r'A_x^\phi'],[r'A_y^{\theta}',r'A_y^\phi']])
plt.figure(1)
for a in range(2):
    for b in range(2):
        hp.orthview(A[a,b,:],rot=[0,90],half_sky=True,sub=(2,2,2*a+b+1),min=-1,max=1)
        plt.title(beam_labels[a,b])
        hp.graticule()

plt.figure(2)
for a in range(4):
    for b in range(4):
        hp.orthview(nom_vis[a,b,:],rot=[0,90],half_sky=True,title='',sub=(4,4,4*a+b+1),min=0,max=1)
        hp.graticule()

plt.show()
Ejemplo n.º 29
0
for p in ipix:
    dec,ra = IndexToDeclRa(p)
    ras.append(ra)
    decs.append(dec)

tec,rmstec,ionh = IM.ionex_data(YYYY,MM,DD)
IM.get_radec_RM(ras,decs)

mc = Basemap(projection='cyl', resolution='c')
mo = Basemap(projection='ortho',lon_0=Plon,lat_0=Plat,resolution='c')
 
for ut in range(24):
    print 'UT=%i'%ut
    
    tecUT=hp.cartview(0.1*tec[ut,:],flip='geo',max=90,min=0,return_projected_map=True)
    mc.drawcoastlines()
    _tec = mc.imshow(tecUT, alpha=0.6,vmax=90,vmin=0)
    plt.title('UT %i hr, %s-%s-%s, TEC'%(ut,YYYY,MM,DD))
    mc.colorbar(location='bottom')
    #plt.show()
    plt.savefig('TEC_%s-%s-%s_UT%i.png'%(YYYY,MM,DD,ut))
    plt.close()
    
    hp.orthview(IM.RMs[0,ut,:],half_sky=True,rot=[0,90],flip='astro',max=5,min=-2,unit=r'${\rm rad\,m^{-2}}$',return_projected_map=True)
    #mo.drawcoastlines()
    #_rm = mo.imshow(rmUT,alpha=0.6,vmax=3,vmin=-3)
    plt.title('UT %i hr, %s-%s-%s'%(ut,YYYY,MM,DD))
    #mo.colorbar(location='bottom')
    plt.savefig('RM_%s-%s-%s_UT%i.png'%(YYYY,MM,DD,ut))
    plt.close()
Ejemplo n.º 30
0
	trot,prot = r(t,p)
	ipix_rot = hp.ang2pix(nside,trot,prot)

	rotmap = map[ipix_rot]

	return rotmap

beam = np.load('XX_beam_maps.npz')['maps']
freqs = np.linspace(0.117,0.182,num=131) #aipy likes GHz units. avoiding band edges
nside = 128
npix = hp.nside2npix(nside)

beam_167 = beam[100,:]
#beam_167 += 1e-9


def brp(beam,rotarr,log=False):
	a1 = np.sqrt(beam)
	a2 = np.sqrt(rotate_hmap(beam_167,rotarr))
	if not log: return a1*a2
	else: return np.log10(a1*a2)

L = True
lb = '\n'
#f,axarr = pylab.subplots(4,1)

for i,rot in enumerate([0,10,20,30]):
	R = hp.orthview(brp(beam_167,[rot,0],log=L), rot=[180,0], half_sky=True, max=0, min=-3, title='Rotation=%i'%rot, unit=lb+r'$\log_{10}({\rm Normalized Response})$')#,hold=True)


pylab.show()
Ejemplo n.º 31
0
    pixels = hp.ang2pix(nside, thetas, j)
    n[pixels] = func[pixels]
    n[n < 0] = 0
filter_array = n  # This is the filter to apply to GSM

(latitude, longitude, elevation) = ('-32.998370', '148.263659', 100
                                    )  # Near EDGES site
delta_t = 60  # EDGES antenna takes a number of measurements in 24 hours; this is the time between measurements in minutes
sky_array = []
timer = datetime(2018, 1, 1, 0, 0)
while timer.hour < 23:
    gsm = GSMObserver()
    gsm.lon = longitude
    gsm.lat = latitude
    gsm.elev = elevation
    gsm.date = timer
    g = hp.ud_grade(
        gsm.generate(78),
        nside)  # 78MHz is the frequency of the 21cm signal absorption feature
    g_filt = g * n
    #g_filt = g_filt*(np.amax(g)/np.amax(g_filt)) # normalisation
    hp.orthview(g_filt, half_sky=True)
    plt.savefig(timer.strftime("%H:%M:%S") + "_filtered.png")
    g_int = np.trapz(g_filt)
    sky_array.append(g_int)
    timer = timer + timedelta(minutes=delta_t)

sky_array = np.array(sky_array)
sky = np.trapz(sky_array)
print(sky)
Ejemplo n.º 32
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()
Ejemplo n.º 33
0
 def test_radec_multip(self):
     self.rm_map.get_radec_RM(testRAs,testDecs)
     assert(self.rm_map.RMs.shape == (1,24,npix))
     assert(self.rm_map.dRMs.shape == (1,24,npix))
     hp.orthview(self.rm_map.RMs[0,0,:],half_sky=True,rot=[0,90])
     plt.close()
Ejemplo n.º 34
0

# Set up the observer
(latitude, longitude, elevation) = ('-30.7224', '21.4278', 1100)
ov = GSMObserver()
ov.lon = longitude
ov.lat = latitude
ov.elev = elevation

fig = plt.figure("Tsky calc")
for poli, pol in enumerate(pols):
    for fi, freq in enumerate(freqs):
        print 'Forming HERA Tsky for frequency ' + str(freq) + ' MHz.'
        # Rotate and project hera beam (Need to figure out how to do this w/o making figure)
        pol_ang = 90 * (1 - poli)  # Extra rotation for X
        hbeam = hp.orthview(hera_beam[pol][:, fi], rot=[pol_ang, 90], fig=fig.number,
                            xsize=400, return_projected_map=True, half_sky=True)
        hbeam[np.isinf(hbeam)] = np.nan
        if calc_paper:
            pbeam = hp.orthview(paper_beam[pol][:, fi], rot=[pol_ang, 90], fig=fig.number,
                                xsize=400, return_projected_map=True, half_sky=True)
            pbeam[np.isinf(pbeam)] = np.nan
        for ti, t in enumerate(hours):
            plt.clf()
            dt = datetime(2013, 1, 1, np.int(t), np.int(60.0 * (t - np.floor(t))),
                          np.int(60.0 * (60.0 * t - np.floor(t * 60.0))))
            lsts[ti] = Time(dt).sidereal_time('apparent', longitude).hour
            ov.date = dt
            ov.generate(freq)
            d = ov.view(fig=fig.number)
            sky = hp.orthview(d, fig=fig.number, xsize=400, return_projected_map=True,
                              half_sky=True)
Ejemplo n.º 35
0
#!/opt/local/bin/python2.7

import smallfield
import healmap
import healpy as hp
import numpy as np

if __name__ == "__main__":
  use_split = 'D'
  use_nside = 512

  h1,h2 = healmap.get_input_maps(use_split,use_nside=use_nside,dir='..')
  sfac = 0.0395
  squ = 10
  st = 200
  rot=[0,90,0]
  #
  hp.orthview(h1.map[0,:]*sfac,rot=rot,nest=False,title="Split 1 T",min=0,max=st)
  hp.orthview(h1.map[1,:]*sfac,rot=rot,nest=False,title="Split 1 Q",min=-squ,max=squ)
  hp.orthview(h1.map[2,:]*sfac,rot=rot,nest=False,title="Split 1 U",min=-squ,max=squ)
  #
  hp.orthview(h2.map[0,:]*sfac,rot=rot,nest=False,title="Split 2 T",min=0,max=st)
  hp.orthview(h2.map[1,:]*sfac,rot=rot,nest=False,title="Split 2 Q",min=-squ,max=squ)
  hp.orthview(h2.map[2,:]*sfac,rot=rot,nest=False,title="Split 2 U",min=-squ,max=squ)
  #
  plt.show()

Ejemplo n.º 36
0
    def plot_luminance(cls,
                       sky,
                       fig=2,
                       title="",
                       mode=31,
                       sub=(1, 5, 1),
                       show=False):
        import matplotlib.pyplot as plt

        assert (isinstance(mode, int) and 0 <= mode < 32) or isinstance(mode, str), \
            "Mode should be an integer between 0 and 15, or a string of the form 'bbbb' where b is for binary."

        if isinstance(mode, str):
            mode = (int(mode[0]) << 3) + (int(mode[1]) << 2) + (
                int(mode[2]) << 1) + (int(mode[3]) << 0)
        sub2 = sub[2]

        lon, lat = sun2lonlat(sky.sun)
        f = plt.figure(fig,
                       figsize=(5 + 3 * (sub[1] - 1), 5 + 3 * (sub[0] - 1)))
        if (mode >> 4) % 2 == 1:
            hp.orthview(sky.si,
                        rot=cls.VIEW_ROT,
                        min=0,
                        max=12,
                        flip="geo",
                        cmap="Greys",
                        half_sky=True,
                        title="Scattering indicatrix",
                        unit=r'',
                        sub=(sub[0], sub[1], sub2),
                        fig=fig)
            sub2 += 1
        if (mode >> 3) % 2 == 1:
            hp.orthview(sky.lg,
                        rot=cls.VIEW_ROT,
                        min=0,
                        max=3,
                        flip="geo",
                        cmap="Greys",
                        half_sky=True,
                        title="Luminance gradation",
                        unit=r'cd/m^2',
                        sub=(sub[0], sub[1], sub2),
                        fig=fig)
            sub2 += 1
        if (mode >> 2) % 2 == 1:
            hp.orthview(sky.L,
                        rot=cls.VIEW_ROT,
                        min=0,
                        max=30,
                        flip="geo",
                        cmap="Greys",
                        half_sky=True,
                        title="Luminance",
                        unit=r'K cd/m^2',
                        sub=(sub[0], sub[1], sub2),
                        fig=fig)
            sub2 += 1
        if (mode >> 1) % 2 == 1:
            hp.orthview(sky.C_x,
                        rot=cls.VIEW_ROT,
                        min=0,
                        max=1.5,
                        flip="geo",
                        cmap="Greys",
                        half_sky=True,
                        title="Chromaticity x",
                        sub=(sub[0], sub[1], sub2),
                        fig=fig)
            sub2 += 1
        if (mode >> 0) % 2 == 1:
            hp.orthview(sky.C_y,
                        rot=cls.VIEW_ROT,
                        min=0,
                        max=1.5,
                        flip="geo",
                        cmap="Greys",
                        half_sky=True,
                        title="Chromaticity y",
                        sub=(sub[0], sub[1], sub2),
                        fig=fig)
            sub2 += 1
        # hp.projplot(lat, lon, 'yo')
        f.suptitle(title)

        if show:
            plt.show()

        return f
def plot_healpix(data_map=None,
                 sub=None,
                 title=None,
                 vmin=None,
                 vmax=None,
                 cmap=None,
                 labels=True):
    '''Y'know, plot healpix maps'''
    rot = (-45, 90, 0)

    if vmin == None:
        if cmap == None:
            hp.orthview(map=data_map,
                        coord='E',
                        half_sky=True,
                        xsize=400,
                        title=title,
                        rot=rot,
                        sub=sub,
                        notext=True,
                        unit='dB',
                        cbar=None)
        else:
            hp.orthview(map=data_map,
                        coord='E',
                        half_sky=True,
                        xsize=400,
                        title=title,
                        rot=rot,
                        sub=sub,
                        cmap=cmap,
                        notext=True,
                        unit='dB',
                        cbar=None)
    else:
        if cmap == None:
            hp.orthview(map=data_map,
                        coord='E',
                        half_sky=True,
                        xsize=400,
                        title=title,
                        rot=rot,
                        sub=sub,
                        min=vmin,
                        max=vmax,
                        notext=True,
                        unit='dB',
                        cbar=None)
        else:
            hp.orthview(map=data_map,
                        coord='E',
                        half_sky=True,
                        xsize=400,
                        title=title,
                        rot=rot,
                        sub=sub,
                        min=vmin,
                        max=vmax,
                        cmap=cmap,
                        notext=True,
                        unit='dB',
                        cbar=None)

    hp.graticule(dpar=10, coord='E', color='k', alpha=0.1, dmer=45)

    if labels == True:

        hp.projtext(0.0 * (pi / 180.0), 0.0, r'$0^\circ$', coord='E')
        hp.projtext(30.0 * (pi / 180.0), 0.0, r'$30^\circ$', coord='E')
        hp.projtext(60.0 * (pi / 180.0), 0.0, r'$60^\circ$', coord='E')

        hp.projtext(80.0 * (pi / 180.0), (0.0 + rot[0]) * (pi / 180.0),
                    "S",
                    coord='E',
                    color='w',
                    verticalalignment='bottom',
                    weight='bold')
        hp.projtext(80.0 * (pi / 180.0), (90.0 + rot[0]) * (pi / 180.0),
                    "W",
                    coord='E',
                    color='w',
                    horizontalalignment='left',
                    weight='bold')
        hp.projtext(80.0 * (pi / 180.0), (180.0 + rot[0]) * (pi / 180.0),
                    "N",
                    coord='E',
                    color='w',
                    verticalalignment='top',
                    weight='bold')
        hp.projtext(80.0 * (pi / 180.0), (270.0 + rot[0]) * (pi / 180.0),
                    'E',
                    coord='E',
                    color='w',
                    horizontalalignment='right',
                    weight='bold')
Ejemplo n.º 38
0
plt.title(title)

plt.subplot(233)
plt.semilogy(tau,Ptau_T_nu)
plt.semilogy(-tau0.value*np.array([1.,1.]),[1e-2,1e5],'r--')
plt.semilogy(tau0.value*np.array([1.,1.]),[1e-2,1e5],'r--')

plt.subplot(234)
plt.plot(C_f/C_f.max(),label='C_l,fringe')
plt.plot(C_a/C_a.max(),label='C_l,beam')
plt.xlim([0,150])
#plt.ylim([1e-8,1e1])
plt.legend()

plt.subplot(235)
plt.plot(ell,C_fa/C_fa.max())
plt.xlim([0,30])

hp.orthview((beam_nu*fringe)[:,100].real,rot=[0,90],half_sky=True,sub=236)
hp.graticule()


    
    
    
    
    
    
    
    
    
Ejemplo n.º 39
0
                    if ut == 4.: UT4[p] = RM[i]
                    if ut == 6.: UT6[p] = RM[i]
                    if ut == 22.:
                        UT22[p] = RM[i]
                        eUT22[p] = eRM[i]
            except TypeError:
                continue
        except IOError:
            print 'issue with %s' % filename
            UT22[p] = np.nan
            c += 1
            continue
print c, 'IOErrors'
hp.orthview(UT22,
            rot=[0, 90],
            max=2,
            unit=r'rad m$^{-1}$',
            title='SAST 00:00 2012-02-13',
            half_sky=True)
#pylab.show()
print UT22
print 'Interpolating NaNs'
UT22_interp = np.zeros_like(UT22)
c = 0
for i, val in enumerate(UT22):
    if np.isnan(val):
        c += 1
        theta, phi = hp.pix2ang(nside, i)
        neybs = hp.get_interp_weights(nside, theta, phi=phi)

        v = np.nanmean(UT22[neybs[0]])
        UT22_interp[i] = v
import healpy as hp
import astropy.io.fits as ap
import astropy.table as table
import numpy as np
import matplotlib.pyplot as plt
import pylab
from matplotlib.pyplot import Slider, Button

filename = 'commander_synch.fits'
data = hp.fitsfunc.read_map(filename)
b = table.Table.read(filename, hdu=1)

fig1 = plt.figure(1, figsize=(16, 9))

hp.orthview(data, fig=1, sub=211, norm='hist', half_sky=True)

axcolor = 'lightgoldenrodyellow'
axlatitude = plt.axes([0.2, 0.35, 0.65, 0.03], axisbg=axcolor)
axlongitude = plt.axes([0.2, 0.4, 0.65, 0.03], axisbg=axcolor)
axangle = plt.axes([0.2, 0.45, 0.65, 0.03], axisbg=axcolor)

latitude_slider = Slider(axlatitude, 'Latitude', -90, 90, valinit=0)
longitude_slider = Slider(axlongitude, 'Longitude', -90, 90, valinit=0)
angle_slider = Slider(axangle, 'Angle', -90, 90, valinit=0)


def update(val):
    latitude = latitude_slider.val
    longitude = longitude_slider.val
    angle = angle_slider.val
    hp.orthview(data,
Ejemplo n.º 41
0
def plot_healpix(
    data_map=None,
    fig=None,
    sub=None,
    title=None,
    vmin=None,
    vmax=None,
    cmap=None,
    cbar=True,
):
    """Yeesh do some healpix magic to plot the thing"""

    # Disable cryptic healpy warnings. Can't figure out where they originate
    import warnings

    warnings.filterwarnings("ignore", category=RuntimeWarning)

    hp.delgraticules()
    hp.orthview(
        map=data_map,
        coord="E",
        fig=fig,
        half_sky=True,
        rot=(0, 90, 180),
        xsize=1200,
        title=title,
        sub=sub,
        min=vmin,
        max=vmax,
        cmap=cmap,
        notext=True,
        hold=True,
        cbar=cbar,
        return_projected_map=False,
    )

    hp.graticule(dpar=10,
                 coord="E",
                 color="k",
                 alpha=0.7,
                 dmer=45,
                 lw=0.4,
                 ls=":")

    # Altitude grid
    hp.projtext(
        00.0 * (np.pi / 180.0),
        225.0 * (np.pi / 180),
        "0",
        color="k",
        coord="E",
        fontsize=6,
        fontweight="light",
    )
    hp.projtext(
        30.0 * (np.pi / 180.0),
        225.0 * (np.pi / 180),
        "30",
        color="k",
        coord="E",
        fontsize=6,
        fontweight="light",
    )
    hp.projtext(
        60.0 * (np.pi / 180.0),
        225.0 * (np.pi / 180),
        "60",
        color="k",
        coord="E",
        fontsize=6,
        fontweight="light",
    )

    # NSEW
    hp.projtext(
        80.0 * (np.pi / 180.0),
        000.0 * (np.pi / 180.0),
        r"$N  $",
        coord="E",
        color="w",
        fontweight="light",
        verticalalignment="top",
    )
    hp.projtext(
        80.0 * (np.pi / 180.0),
        090.0 * (np.pi / 180.0),
        r"$E  $",
        coord="E",
        color="w",
        fontweight="light",
        horizontalalignment="right",
    )
    hp.projtext(
        80.0 * (np.pi / 180.0),
        180.0 * (np.pi / 180.0),
        r"$S  $",
        coord="E",
        color="w",
        fontweight="light",
        verticalalignment="bottom",
    )
    hp.projtext(
        80.0 * (np.pi / 180.0),
        270.0 * (np.pi / 180.0),
        r"$W  $",
        coord="E",
        color="w",
        fontweight="light",
        horizontalalignment="left",
    )
Ejemplo n.º 42
0
def myPlot(x, xerr, args):

    # General setup
    npix = len(x)
    nside = hp.npix2nside(npix)
    theta, phi = hp.pix2ang(nside, range(npix))
    degree = np.pi / 180.
    fDict = {'chi2':getChi2, 'pvals':getChi2, 'bayes':bayesFactor, 'test':getTest}
    f = fDict[args.maptype]

    # Compare each pixel to ensemble distribution for given declination
    map = np.zeros(npix, dtype=np.double)
    if args.decbands:
        thetaRings = np.array(sorted(list(set(theta))))
        thetaRings = thetaRings[thetaRings > (180-args.thetaMax)*degree]
        for i, th in enumerate(thetaRings):
            c0 = (theta == th)
            map[c0] += f(x[c0], xerr[c0], args)
    else:
        map = f(x, xerr, args)

    # Option to calculate p-values
    #if args.maptype == 'pvals':
    #    pvals = np.zeros(len(chi2), dtype=np.double)
    #    for i, chi in enumerate(chi2):
    #        if chi == 0:
    #            continue
    #        pvals[i] = stats.chisqprob(chi2[i], ndof[i])
    #    map = np.log10(pvals)

    # Mask
    map = mf.maskMap(map, args.thetaMin-90, args.thetaMax-90)
    if args.scale:
        map[map!=hp.UNSEEN] *= (10**args.scale)

    temp = {'Excess':(150,185)}

    title = makeTitle(args)

    ### SETUP FROM PLOTFITS ###
    unmasked = np.array([i for i in map if (i!=hp.UNSEEN and i!=np.inf)])
    min = float(args.min) if args.min else unmasked.min()
    max = float(args.max) if args.max else unmasked.max()
    if not args.min:
        args.min = '%.2f' % min
    if not args.max:
        args.max = '%.2f' % max

    # Setup colormap with option for threshold
    colormap = plt.get_cmap('jet')
    colormap.set_under('white')
    colormap.set_bad('gray')

    pltParams = {'fig':1, 'rot':[0, -90, 180], 'title':'', 'min':min, \
            'max':max, 'cbar':False, 'notext':True, 'coord':'C', \
            'cmap':colormap}
    ###

    if args.polar:
        #hp.orthview(map, rot=(0,90,180), title=title, half_sky=True)
        hp.orthview(map, half_sky=True, **pltParams)
        for key in temp.keys():
            hp.projtext(temp[key][0]*degree, temp[key][1]*degree, key)
    else:
        #hp.mollview(map, rot=(0,0,180), title=title)
        #hp.mollview(map, rot=(0,0,180), title='')
        hp.mollview(map, rot=180, title='')
    #for key in temp.keys():
    #    hp.projtext(temp[key][0]*degree, temp[key][1]*degree, key)
    hp.graticule(verbose=False)

    ### MORE SETUP FROM PLOTFITS ###
    labelDict = {'bayes':r'Bayes Factor [$\ln(B_{21})$]'}
    labelDict['test'] = r'Difference from Mean [$\overline{D_i} - \overline{D_{tot}}$]'
    label = labelDict[args.maptype]
    if args.scale:
        label += ' [x 10$^{-%d}$]' % args.scale
    cbarParams = {'label':label, 'min':args.min, 'max':args.max, \
            'coord':'C', 'fontsize':'small', \
            'projaxis':hp.projaxes.HpxOrthographicAxes}
    SetupColorBar(**cbarParams)


    if args.out != None:
        plt.savefig(args.out, dpi=300, bbox_inches='tight')

    if not args.batch:
        plt.show()
Ejemplo n.º 43
0
def healpy_orthview(plot_map,
                    fig=None,
                    coord='G',
                    xsize=2000,
                    title='',
                    min_value=0.0,
                    max_value=0.0,
                    cbar=True,
                    notext=False,
                    norm=None,
                    name_out=None,
                    cmap=plt.cm.viridis,
                    return_projected=False):
    """
    map - healpix map (1-d array),
    fig - figure number to use,
    coord - coordinate system of the map ('G', ['G', 'E'] or ['G', 'C']),
    xsize - size of the image,
    title - title of the plot,
    min_value - minimum range value,
    max_value - maximum range value,
    cbar - display the colorbar,
    notext - if True, no text is printed around the map,
    norm - color normalization (None (linear), 'hist' or 'log'),
    name_out - name of the output picture,
    cmap - color map of the plot (jet, viridis, jet and other)
    """

    cmap.set_under("w")

    if fig is None:
        fig = plt.figure(figsize=(20, 10))

    if return_projected:
        if min_value != 0.0 or max_value != 0.0:
            plot_map_out = hp.orthview(plot_map,
                                       fig.number,
                                       coord=coord,
                                       xsize=xsize,
                                       title=title,
                                       min=min_value,
                                       max=max_value,
                                       cbar=cbar,
                                       notext=notext,
                                       norm=norm,
                                       cmap=cmap,
                                       return_projected_map=True)
        else:
            plot_map_out = hp.orthview(plot_map,
                                       fig.number,
                                       coord=coord,
                                       xsize=xsize,
                                       title=title,
                                       cbar=cbar,
                                       notext=notext,
                                       norm=norm,
                                       cmap=cmap,
                                       return_projected_map=True)

        if name_out is not None:
            plt.savefig(name_out, dpi=400)

        return plot_map_out
    else:
        if min_value != 0.0 or max_value != 0.0:
            hp.orthview(plot_map,
                        fig.number,
                        coord=coord,
                        xsize=xsize,
                        title=title,
                        min=min_value,
                        max=max_value,
                        cbar=cbar,
                        notext=notext,
                        norm=norm,
                        cmap=cmap)
        else:
            hp.orthview(plot_map,
                        fig.number,
                        coord=coord,
                        xsize=xsize,
                        title=title,
                        cbar=cbar,
                        notext=notext,
                        norm=norm,
                        cmap=cmap)

        if name_out is not None:
            plt.savefig(name_out, dpi=400)
Ejemplo n.º 44
0
			try:
				for i, ut in enumerate(UT):
					if ut==0.: UT0[p]=RM[i]
					if ut==4.: UT4[p]=RM[i]
					if ut==6.: UT6[p]=RM[i]
					if ut==22.: 
						UT22[p]=RM[i]
						eUT22[p]=eRM[i]
			except TypeError: continue
		except IOError:
			print 'issue with %s'%filename
			UT22[p] = np.nan
			c+=1
			continue
print c,'IOErrors'	
hp.orthview(UT22,rot=[0,90],max=2,unit=r'rad m$^{-1}$',title='SAST 00:00 2012-02-13',half_sky=True)
#pylab.show()
print UT22
print 'Interpolating NaNs'
UT22_interp = np.zeros_like(UT22)
c=0
for i,val in enumerate(UT22):
	if np.isnan(val):
		c+=1
		theta,phi = hp.pix2ang(nside,i)
		neybs = hp.get_neighbours(nside,theta,phi=phi) 
		
		v = np.nanmean(UT22[neybs[0]])
		UT22_interp[i] = v
		
	else: UT22_interp[i]=val
Ejemplo n.º 45
0
def Orth(map):
    hp.orthview(map,rot=[0,90],half_sky=True)
    return
Ejemplo n.º 46
0
def Orth(map):
    hp.orthview(map,half_sky=True)
    return
Ejemplo n.º 47
0
             norm=" ",
             sub=221,
             xsize=2000)  #, min=-5e-7, max=5e7, xsize=2000)
 hp.orthview(map=eqdata,
             fig=3,
             rot=None,
             coord=None,
             unit='',
             xsize=800,
             half_sky=False,
             title='Orthographic view',
             nest=False,
             min=None,
             max=None,
             flip='astro',
             remove_dip=False,
             remove_mono=False,
             gal_cut=0,
             format='%g',
             format2='%g',
             cbar=True,
             cmap=None,
             notext=False,
             norm=" ",
             hold=False,
             margins=None,
             sub=222,
             return_projected_map=False)
 hp.gnomview(map=eqdata,
             fig=3,
             rot=None,
Ejemplo n.º 48
0
for i in ip: map[i]+=1
map = hp.smoothing(map, fwhm=np.radians(14))
map = map/np.max(map)
fsky = map.sum()/len(map)

hp.mollview(map, title='Fractime: {0:4.1f}% - fsky: {1:4.1f}%'.format(fractime, fsky*100))



nside = 8
map = np.arange(12*8**2)
idbicep2 = hp.ang2pix(nside, np.radians(90-galbicep2[1]), np.radians(galbicep2[0]))
map[idbicep2]+=100
idnew = hp.ang2pix(nside, np.radians(90-galnew[1]), np.radians(galnew[0]))
map[idnew]+=100
hp.orthview(map, rot=[0,90])




############# Tower
time, azimuth, elevation = observe_onespot(spot_bicep2, domec,  nt=1000, DEFAULT_DATE_OBS='2016-01-01 00:00:00')
time2, azimuth2, elevation2 = observe_onespot(newspot, domec,  nt=1000, DEFAULT_DATE_OBS='2016-01-01 00:00:00')

htower = 45.
dtower = np.array([45., 70.])
thetatower = np.degrees(arctan2(htower, dtower))

clf()
plot(azimuth, elevation)
Ejemplo n.º 49
0
hpxidx = np.arange(npix)
theta, phi = hp.pix2ang(nside, hpxidx)
phi = 2. * np.pi - phi

RotAngle = np.radians(30.)
RotAxis = np.array([0, -1, 0])

R = rotation_matrix(RotAxis, RotAngle)

cosX, sinX = spherical_basis_transformation_components(theta, phi, R)

fig = plt.figure(figsize=(16, 8))
hp.orthview(cosX,
            rot=[-45, 45],
            cmap='RdBu_r',
            sub=(1, 2, 1),
            half_sky=True,
            min=-1,
            max=1)
ax = plt.gca()
ax.set_aspect('equal')
ax.set_title(r'$\cos \chi$', fontsize=32)

hp.orthview(sinX,
            rot=[-45, 45],
            cmap='RdBu_r',
            sub=(1, 2, 2),
            half_sky=True,
            min=-1,
            max=1)
ax = plt.gca()
Ejemplo n.º 50
0
def Orth90(map):
    hp.orthview(map,half_sky=True,rot=[0,90])
    return
Ejemplo n.º 51
0
plt.plot(nu, T_nu.real, 'b')
plt.plot(nu, T_nu.real - T_nu.mean(), 'b--')
plt.plot(nu, window * T_nu.real, 'g')
plt.plot(nu, T_nu.imag, 'r')

plt.subplot(232)
plt.plot(nu, T_nu.real / omega_nu)
plt.title(title)

plt.subplot(233)
plt.semilogy(tau, Ptau_T_nu)
plt.semilogy(-tau0.value * np.array([1., 1.]), [1e-2, 1e5], 'r--')
plt.semilogy(tau0.value * np.array([1., 1.]), [1e-2, 1e5], 'r--')

plt.subplot(234)
plt.plot(C_f / C_f.max(), label='C_l,fringe')
plt.plot(C_a / C_a.max(), label='C_l,beam')
plt.xlim([0, 150])
#plt.ylim([1e-8,1e1])
plt.legend()

plt.subplot(235)
plt.plot(ell, C_fa / C_fa.max())
plt.xlim([0, 30])

hp.orthview((beam_nu * fringe)[:, 100].real,
            rot=[0, 90],
            half_sky=True,
            sub=236)
hp.graticule()
Ejemplo n.º 52
0
        m[:ring_max] = hp.pixelfunc.UNSEEN

    # replace nan values with zero
    if opts.fill: m = np.nan_to_num(m)

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

    if opts.mode.lower()=='h':
        norm = 'hist'
    elif opts.mode.lower()=='i':
        norm = None
    elif opts.mode.lower()=='l':
        norm = 'log'
    elif opts.mode.lower()=='s':
        norm = None

    if opts.visu.lower().startswith('moll'): # Mollweide projection
        hp.mollview(m, coord=coord_proj, norm=norm, max=opts.max, min=opts.min, cmap=plt.get_cmap(opts.cmap), cbar=cbar, fig=1, unit=unit, title=opts.title, xsize=xsize, rot=rot)
    elif opts.visu.lower().startswith('cart'): # Cartesian
        hp.cartview(m, coord=coord_proj, norm=norm, max=opts.max, min=opts.min, cmap=plt.get_cmap(opts.cmap), cbar=cbar, fig=1, unit=unit, title=opts.title, xsize=xsize, rot=rot)
    elif opts.visu.lower().startswith('ortho'): # Orthographic
        hp.orthview(m, coord=coord_proj, norm=norm, max=opts.max, min=opts.min, cmap=plt.get_cmap(opts.cmap), cbar=cbar, fig=1, unit=unit, title=opts.title, xsize=xsize, rot=rot)

    # set grid lines
    hp.graticule(dpar=5, dmer=5)

    if not(opts.savefig is None):
        plt.savefig(opts.savefig)
    else: plt.show()