Ejemplo n.º 1
0
def show_kmap(klm=None,
              fname=None,
              lmin=200,
              lmax=1024,
              nside=1024,
              v=.1,
              lonra=[147, 244],
              latra=[-3, 21],
              output=False,
              title=''):
    import curvedsky
    if fname is not None:
        Flm, __ = pickle.load(open(fname, "rb"))
    if klm is not None:
        Flm = klm.copy()
    Flm[:lmin, :] = 0.
    kmap = curvedsky.utils.hp_alm2map(nside, lmax, lmax,
                                      Flm[:lmax + 1, :lmax + 1])
    print('max,min:', np.max(kmap), np.min(kmap))
    hp.cartview(kmap,
                lonra=lonra,
                latra=latra,
                min=-v,
                max=v,
                cbar=False,
                title=title)
    if output:
        return kmap
Ejemplo n.º 2
0
def plot_sky_projection_healpy_count(Sliced_Halo_data,nside):
    HEALPix_mode = read_data_bool(tag_name = 'HEALPix_Cartesian',file_name = 'parameters/Output_Parameters.xml')
    HEALPix_grat = read_data_bool(tag_name = 'HEALPix_Graticule',file_name = 'parameters/Output_Parameters.xml')
    fdir  = './Output/plots/HEALPix/'
    Sl_n  = len(Sliced_Halo_data)
    Z_max = max(Sliced_Halo_data[Sl_n-1].Z_red[:])
    rc('text',usetex=True)
    for k in range(Sl_n):
        pix     = zeros(12*nside**2)
        n       = len(Sliced_Halo_data[k].RA[:])
        for i in range(n):
           j    = hp.ang2pix(nside,DtoR*(90.0-Sliced_Halo_data[k].DEC[i]),DtoR*Sliced_Halo_data[k].RA[i])
           pix[j] += 1
        clf()
        if (HEALPix_mode):
           hp.cartview(pix)           
        else:
           hp.mollview(pix)
        if (HEALPix_grat):
           hp.graticule()
        fname = 'sky_projection_HEALPix_Count_%i_%i.pdf'%(nside,(k+1))
        title(r'sky projection for redshift between %0.2f and %0.2f'%(Sliced_Halo_data[k].z_min,Sliced_Halo_data[k].z_max),fontsize = 20)
        print 'Saving plot', fname
        savefig(fdir+fname,bbox_inches='tight')
    rc('text',usetex=False)
    close()  
    return 0
Ejemplo n.º 3
0
    def plot_healpix(self, map_name, view='cart', **kwargs):
        import healpy
        import numpy as np

        m, pix, nside = self.read_healpix(map_name, return_all=True)
        lon, lat = healpy.pix2ang(nside, pix, lonlat=True)
        npix = healpy.nside2npix(nside)
        if len(pix) == 0:
            print(f"Empty map {map_name}")
            return
        if len(pix) == len(m):
            w = np.where((m != healpy.UNSEEN) & (m != 0))
        else:
            w = None
        lon_range = [lon[w].min() - 0.1, lon[w].max() + 0.1]
        lat_range = [lat[w].min() - 0.1, lat[w].max() + 0.1]
        m[m == 0] = healpy.UNSEEN
        title = kwargs.pop('title', map_name)
        if view == 'cart':
            healpy.cartview(m,
                            lonra=lon_range,
                            latra=lat_range,
                            title=title,
                            hold=True,
                            **kwargs)
        elif view == 'moll':
            healpy.mollview(m, title=title, hold=True, **kwargs)
        else:
            raise ValueError(f"Unknown Healpix view mode {mode}")
Ejemplo n.º 4
0
  def footprint_area(cat,ngal=1,mask=None,nside=4096,nest=True,label=''):
    import healpy as hp
    import matplotlib
    matplotlib.use ('agg')
    import matplotlib.pyplot as plt
    # plt.style.use('/home/troxel/SVA1/SVA1StyleSheet.mplstyle')
    from matplotlib.colors import LogNorm
    import pylab

    mask=CatalogMethods.check_mask(cat.coadd,mask)

    if not hasattr(cat, 'pix'):
      cat.pix=CatalogMethods.radec_to_hpix(cat.ra,cat.dec,nside=nside,nest=True)
    area=hp.nside2pixarea(nside)*(180./np.pi)**2
    print 'pixel area (arcmin)', area*60**2
    mask1=np.bincount(cat.pix[mask])>ngal
    print 'footprint area (degree)', np.sum(mask1)*area

    pix=np.arange(len(mask1))[mask1]
    print pix
    tmp=np.zeros((12*nside**2), dtype=[('hpix','int')])
    tmp['hpix'][pix.astype(int)]=1
    print tmp['hpix'][pix.astype(int)]
    fio.write('footprint_hpix'+label+'.fits.gz',tmp,clobber=True)

    tmp2=np.zeros(12*nside**2)
    tmp2[tmp.astype(int)]=1
    hp.cartview(tmp2,nest=True)
    plt.savefig('footprint_hpix'+label+'.png')
    plt.close()

    return 
Ejemplo n.º 5
0
    def plot_footprint_base(cat, mask=None, label='', bins=100, part=''):

        if not hasattr(cat, 'gdmask'):
            cat.gdmask = hp.read_map(config.golddir +
                                     'y1a1_gold_1.0.1_wide_footprint_4096.fit')
            cat.badmask = hp.read_map(config.golddir +
                                      'y1a1_gold_1.0.1_wide_badmask_4096.fit')
        if not hasattr(cat, 'pix'):
            cat.pix = hp.ang2pix(4096,
                                 np.pi / 2. - np.radians(cat.dec),
                                 np.radians(cat.ra),
                                 nest=False)

        mask0 = (cat.gdmask >= 1) & (cat.badmask == 0)

        hpmap = np.ones((12 * 4096**2)) * hp.UNSEEN
        hpmap[(cat.gdmask >= 1)] = 0
        cnt = np.zeros(12 * 4096**2)
        cnt[:np.max(cat.pix[mask]) + 1] = np.bincount(cat.pix[mask])
        hpmap[mask0] = cnt[mask0]
        hp.cartview(hpmap,
                    latra=config.dec_lim.get(part),
                    lonra=config.ra_lim.get(part),
                    xsize=10000,
                    title=label)
        plt.savefig('plots/footprint/footprint_' + cat.name + '_' + label +
                    '_' + part + '.png',
                    dpi=1000,
                    bbox_inches='tight')
        plt.close()

        # dra=config.ra_lim.get(part)[1]-config.ra_lim.get(part)[0]
        # ddec=config.dec_lim.get(part)[1]-config.dec_lim.get(part)[0]

        # plt.figure()
        # tmp=config.ra_lim.get(part),config.dec_lim.get(part)
        # a=plt.hist2d(cat.ra[mask],cat.dec[mask],bins=(int(dra*bins),int(ddec*bins)),range=tmp,normed=True, cmap=plt.cm.afmhot)

        # cb = plt.colorbar(orientation='horizontal')
        # plt.gca().set_aspect('equal', 'box')
        # plt.savefig('plots/footprint/footprint_'+cat.name+'_'+label+'_'+part+'.png', dpi=500, bbox_inches='tight')
        # plt.close()

        # plt.figure()
        # plt.hist2d(cat.ra[mask],cat.dec[mask],bins=(int(dra*bins),int(ddec*bins)),range=((np.min(cat.ra[mask])-.1*dra,np.max(cat.ra[mask])+.1*dra),(np.min(cat.dec[mask])-.1*ddec,np.max(cat.dec[mask])+.1*ddec)),normed=True,norm=LogNorm(), cmap=plt.cm.afmhot)
        # #cb = plt.colorbar()
        # plt.gca().set_aspect('equal', 'box')
        # plt.savefig('plots/footprint/footprint_'+cat.name+'_'+label+'_log.png', dpi=500, bbox_inches='tight')
        # plt.close()

        return
Ejemplo n.º 6
0
 def display_healpix(self, map_name, **kwargs):
     import healpy
     import numpy as np
     m, pix, nside = self.read_healpix(map_name, return_all=True)
     lon, lat = healpy.pix2ang(nside, pix, lonlat=True)
     npix = healpy.nside2npix(nside)
     lon_range = [lon.min() - 0.1, lon.max() + 0.1]
     lat_range = [lat.min() - 0.1, lat.max() + 0.1]
     title = kwargs.pop('title', map_name)
     healpy.cartview(m,
                     lonra=lon_range,
                     latra=lat_range,
                     title=title,
                     **kwargs)
Ejemplo n.º 7
0
 def plot_sky(self,ra=None,dec=None,norm = 'log',unit='Kelvin',heapix_array=None):
     """ plot_sky plots the sky tempreture and overlays pointing centers as red dots
     The sky tempreture is the data that was loaded when the class was iniitated.
     plot_sky takes in 3 optional parameters:
             ra,dec  are list/1D-array like values of right assension and declanation
     returns matplotlib figure object that the plot is assosated with.
     """
     #self.freq_map
     fig = plt.figure(figsize=(16,9))
     hp.cartview(self.freq_map,norm = norm,unit=unit,fig=fig.number)
     c = SkyCoord(ra=ra*u.degree, dec=dec*u.degree, frame='icrs')
     l = np.degrees(angle_wrap(-c.galactic.l.radian % (np.pi*2)) )
     b = np.degrees(c.galactic.b.radian)
     plt.plot(l,b,'ro')
     #hp.graticule()
     return fig
Ejemplo n.º 8
0
def plot_lotss_map(mp, title=None, cbar=True, mask=None, fname=None, **kwargs):
    lonra = [159.5, 232.5]
    latra = [44, 59]
    if mask is not None:
        mp2plot = mp.copy()
        mp2plot[mask <= 0] = np.inf
    else:
        mp2plot = mp
    arr = hp.cartview(mp2plot,
                      lonra=lonra,
                      latra=latra,
                      return_projected_map=True)
    plt.cla()
    plt.close(plt.gcf())

    fig = plt.figure()
    if title is not None:
        plt.title(title, fontsize=14)
    im = plt.imshow(arr,
                    origin='lower',
                    extent=(lonra[1], lonra[0], latra[0], latra[1]),
                    interpolation='none',
                    **kwargs)
    plt.xlabel(r'${\rm R.A.}$', fontsize=15)
    plt.ylabel(r'${\rm dec.}$', fontsize=15)
    if cbar:
        fig.colorbar(im, orientation='horizontal', aspect=40)
    if fname is not None:
        plt.savefig(fname, bbox_inches='tight')
Ejemplo n.º 9
0
    def plot(self, ax=None, projection='mollweide', **kwargs):
        """
        Plot healpix sky image using a global projection.

        Parameters
        ----------
        projection : ['mollweide', 'cartesian']
            Which projection to use for plotting.
        """
        #TODO: add other projections
        if projection == 'mollweide':
            hp.mollview(map=self.data, nest=self.wcs.nested, **kwargs)
        elif projection == 'cartesian':
            hp.cartview(map=self.data, nest=self.wcs.nested, **kwargs)
        else:
            raise ValueError("Projection must be 'cartesian' or 'mollweide'")
Ejemplo n.º 10
0
def plot_map(totCl, FileName=False, view='Mollweide'):

    np.random.seed(42)

    l = np.arange(len(totCl)) + 1

    totCl_raw = totCl * 2 * np.pi / (l * (l + 1))

    # --- create healpix map
    map = hp.synfast(totCl_raw, nside=2048)

    if view == 'Mollweide':

        # --- Mollweide plot
        m = hp.mollview(map, return_projected_map=True, cmap=cmap)

        dpi = 600
        figsize_inch = 6, 4
        fig = plt.figure(figsize=figsize_inch, dpi=dpi)
        ax = fig.add_axes([0, 0, 1, 1])
        ax.imshow(m, cmap=cmap)
        ax.axis('off')

        if FileName:
            fig.savefig(FileName, dpi=dpi, bbox_inches="tight")  # save
        else:
            plt.show()

        fig.clf()

    if view == 'Cartesian':

        # --- Cartesian view of a 20 deg2 region

        # hp.cartview(map=None, fig=None, rot=None, zat=None, coord=None, unit='', xsize=800, ysize=None, lonra=None, latra=None, title='Cartesian view', nest=False, remove_dip=False, remove_mono=False, gal_cut=0, min=None, max=None, flip='astro', format='%.3g', cbar=True, cmap=None, badcolor='gray', bgcolor='white', norm=None, aspect=None, hold=False, sub=None, margins=None, notext=False, return_projected_map=False)

        m = hp.cartview(map=map,
                        xsize=300,
                        lonra=[-5, 5],
                        latra=[-5, 5],
                        title=None,
                        return_projected_map=True)
        plt.close()

        dpi = 150
        figsize_inch = 2, 2
        fig = plt.figure(figsize=figsize_inch, dpi=dpi)
        ax = fig.add_axes([0, 0, 1, 1])
        ax.imshow(m, cmap=cmap, vmin=-500, vmax=500)
        ax.axis('off')

        if FileName:
            fig.savefig(FileName, dpi=dpi)  # save
        else:
            plt.show()

        fig.clf()
Ejemplo n.º 11
0
def halo():
    # Set stage
    grid = hp.Harpix().adddisc(vec=(1, 0, 0), radius=2, nside=256)
    #grid.addsingularity((0,0), 0.3, 2, n = 1000)
    expo = 10

    r = lambda l, b: np.sqrt(l**2 + b**2)

    # Signal shape
    sig_shape = hp.zeroslike(grid).addfunc(lambda l, b: 0 + 1. /
                                           (r(l, b) + 10.)**1)

    # Background shapes (and error)
    bkg_shape = hp.zeroslike(grid).addfunc(lambda l, b: 1. /
                                           (r(l, b) + 1.0)**2)
    #err_shape = bkg_shape * 0.0001
    #cov = hp.HarpixSigma1D(err_shape, corrlength = 1.)

    print(bkg_shape.getintegral() * expo)

    # Background component model
    bkg_comp = BkgComponent(
        lambda x: expo *
        (bkg_shape.getdata(mul_sr=True) * x[0] + bkg_shape.getdata(mul_sr=True)
         **3 * x[1] + bkg_shape.getdata(mul_sr=True)**2.5 * x[2] + x[3]),
        x0=[1e8, 1e8, 1e8, 1.],
        xerr=[0e3, 0e3, 0e3, 1.0],
        cov=None)
    SF = bkg_comp.getSwordfish()

    # Signal model
    #S = np.multiply.outer(sig_shape.getdata(mul_sr = True), sig_spec).flatten()
    S = sig_shape.getdata(mul_sr=True)

    #UL = SF.upperlimit(S, 0.05)
    print('infoflux...')
    F = SF.infoflux(S * expo, solver='direct')
    print('...done')
    grid.data = F
    grid._div_sr()
    m = grid.gethealpix(nside=256)
    #healpy.mollview(m, nest=True)
    healpy.cartview(m, nest=True, lonra=[-10, 10], latra=[-10, 10])
    plt.show()
Ejemplo n.º 12
0
def Healpix2Cartesian(fname):                        
    # Read from hdf5 file
    f = h5py.File(fname,'r')
    
    for t in f['templates/']:
        print "Writing", t
        if t=="energies": 
            continue
        
        
        # Get the cartesian maps for each energy
        hpixcube = f['templates/'+t][()]
        cartcube = np.zeros((hpixcube.shape[0], 721,1440), dtype=np.float32)
        for i in range(hpixcube.shape[0]):
            cartcube[i] = healpy.cartview(hpixcube[i], hold=True, return_projected_map=True,
                                                  xsize=1440, lonra=[-179.875, 179.875],flip='geo')
            plt.gcf()
        
        # Generate new hdu object
        hdu_new = pyfits.PrimaryHDU(cartcube.astype(np.float32))
        
        # Copy galdef into header
        galdef = dict(f['/galdef'].attrs.items())
        hdu_new.header.add_comment("Diffuse model generated by Eric Carlson ([email protected])")
        for key, val in galdef.items():
            hdu_new.header.add_comment(key + "=" +val)
        
        hdu_new.header['CRVAL1'] = 0.0
        hdu_new.header['CRPIX1'] = 720
        hdu_new.header['CDELT1'] = 0.25
        hdu_new.header['CUNIT1']= 'deg'
        hdu_new.header['CTYPE2']= 'GLON-CAR'
        hdu_new.header['CRVAL2'] = 0
        hdu_new.header['CRPIX2'] = 361
        hdu_new.header['CDELT2'] = 0.25
        hdu_new.header['CUNIT2']= 'deg'
        hdu_new.header['CTYPE2']= 'GLAT-CAR'
        hdu_new.header['CRVAL3'] = float(galdef['E_gamma_min'])
        hdu_new.header['CRPIX3'] = 0
        hdu_new.header['CDELT3'] = np.log10(float(galdef['E_gamma_factor']))
        hdu_new.header['CTYPE2']= 'Energy'
        hdu_new.header['CUNIT3']= 'MeV'
        hdu_new.header['EXTEND']=True
        hdu_new.header['CREATOR'] = ('Eric Carlson ([email protected])', '')

        # Write energy extension table
        energies = np.array([50*float(galdef['E_gamma_factor'])**i for i in range(cartcube.shape[0])])
        tbhdu = pyfits.BinTableHDU.from_columns([
                pyfits.Column(name='Energy', format='D', array=energies),])
        tbhdu.header['EXTNAME']="ENERGIES"
        
        hdulist = pyfits.HDUList([hdu_new,tbhdu])
        
        # Write to file
        fname_out = fname.split('.')[0]+"_"+t +'_mapcube.fits.gz'
        hdulist.writeto(fname_out,clobber=True)
Ejemplo n.º 13
0
def test3():
    # Set stage
    grid = hp.Harpix().adddisc(vec=(1, 0, 0), radius=2, nside=1024)
    #grid.addsingularity((0,0), 0.3, 2, n = 1000)
    print(len(grid.data))
    #quit()
    E = np.linspace(1, 2, 2)

    # Signal shape
    sig_shape = hp.zeroslike(grid).addfunc(lambda l, b: 1. /
                                           (l**2 + b**2 + 2.))
    sig_spec = np.exp(-E)

    # Background shapes (and error)
    bkg_shape = hp.zeroslike(grid).addfunc(
        lambda l, b: 1 + 0 * np.cos(l / 10) * np.cos(b / 10) + 0 / (b**2 + 1))
    bkg_spec = lambda x: E**-x[0] * x[1]
    err_shape = bkg_shape * 0.0001
    cov = hp.HarpixSigma1D(err_shape, corrlength=1.)

    # Background component model
    bkg_comp = BkgComponent(lambda x: bkg_shape.getdata(mul_sr=True) * x[0],
                            x0=[1.],
                            xerr=[0.001],
                            cov=cov).tensordot(
                                BkgComponent(bkg_spec,
                                             x0=[2., 1.],
                                             xerr=[0.001, 0.001]))
    SF = bkg_comp.getSwordfish()

    # Signal model
    S = np.multiply.outer(sig_shape.getdata(mul_sr=True), sig_spec).flatten()

    #UL = SF.upperlimit(S, 0.05)
    print('infoflux...')
    F = SF.infoflux(S, solver='cg').reshape(-1, 2)
    print('...done')
    grid.data = F[:, 1]
    grid._div_sr()
    m = grid.gethealpix(nside=256)
    #healpy.mollview(m, nest=True)
    healpy.cartview(m, nest=True, lonra=[-10, 10], latra=[-10, 10])
    plt.show()
Ejemplo n.º 14
0
 def cut_map(self, rot, res=900, out_put_file = None):
     """
     Returns map cut from desired region from the given longitudinal and latitudinal ranges (assuming small engough for flat sky limit)"
     """
     map_cut=cartview(self.map, rot=rot,lonra=[-10,10],latra=[-5,5],xsize=res,ysize=res,return_projected_map=True)
     close()
     return map_cut
 
     if out_put_file != None:
         dump(map_cut,open(out_put_file,'wb'), protocol = -1)
Ejemplo n.º 15
0
    def footprint_area(cat,
                       ngal=1,
                       mask=None,
                       nside=4096,
                       nest=True,
                       label=''):
        import healpy as hp
        import matplotlib
        matplotlib.use('agg')
        import matplotlib.pyplot as plt
        # plt.style.use('/home/troxel/SVA1/SVA1StyleSheet.mplstyle')
        from matplotlib.colors import LogNorm
        import pylab

        mask = CatalogMethods.check_mask(cat.coadd, mask)

        if not hasattr(cat, 'pix'):
            cat.pix = CatalogMethods.radec_to_hpix(cat.ra,
                                                   cat.dec,
                                                   nside=nside,
                                                   nest=True)
        area = hp.nside2pixarea(nside) * (180. / np.pi)**2
        print 'pixel area (arcmin)', area * 60**2
        mask1 = np.bincount(cat.pix[mask]) > ngal
        print 'footprint area (degree)', np.sum(mask1) * area

        pix = np.arange(len(mask1))[mask1]
        print pix
        tmp = np.zeros((12 * nside**2), dtype=[('hpix', 'int')])
        tmp['hpix'][pix.astype(int)] = 1
        print tmp['hpix'][pix.astype(int)]
        fio.write('footprint_hpix' + label + '.fits.gz', tmp, clobber=True)

        tmp2 = np.zeros(12 * nside**2)
        tmp2[tmp.astype(int)] = 1
        hp.cartview(tmp2, nest=True)
        plt.savefig('footprint_hpix' + label + '.png')
        plt.close()

        return
Ejemplo n.º 16
0
def show_tmap(Tlm,
              ocl,
              mask=1,
              lmin=500,
              lmax=3000,
              v=3e11,
              nside=512,
              lonra=[148, 243],
              latra=[-3, 20],
              title=''):
    import curvedsky
    Flm = Tlm.copy()
    Flm[:lmin, :] = 0.
    Tmap = curvedsky.utils.hp_alm2map(
        nside, lmax, lmax,
        Flm[:lmax + 1, :lmax + 1] / (ocl[:lmax + 1, None] + 1e-30))
    hp.cartview(mask * Tmap,
                lonra=lonra,
                latra=latra,
                min=-v,
                max=v,
                cbar=False,
                title=title)
Ejemplo n.º 17
0
def plot_full_sky_cart(Output_Para,pix,pix_bool):
    rc('font',family='serif')
    if (pix_bool):
       plt.clf()
       hp.cartview(pix, fig = 1)
       hp.graticule()
       plt.show()
       plt.close()
    else:
       print "Please, first load a HEALPix map file ."
       raw_input("Press enter to continue ... ")
       return 0
    save_ques = Read_YN_Input("Do you want to save its picture (please enter Y, y, N, or n)? ")
    if save_ques :
       rc('text',usetex=True)
       plt.clf()
       hp.cartview(pix, fig = 1)
       hp.graticule()
       print 'Saving plot', fname
       plt.savefig(fdir+fname+'_cart.pdf',bbox_inches='tight')
#       plt.savefig(fdir+fname+'.pdf')
       rc('text',usetex=False)
       plt.close()
Ejemplo n.º 18
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.º 19
0
def view_maps(output_maps, conds):
    '''
    Display the output maps and the relative condition number.
    ---------
    output_maps : array-like
        healpy maps array
    conds: array-like
        ondition number relative to the scan 

    '''
    Freq = [90, 95, 100, 105, 110]
    for maps, cond in zip(output_maps, conds):
        cond[cond == np.inf] = hp.UNSEEN
        cart_opts = dict(unit=r'[$\mu K_{\mathrm{CMB}}$]')
        hp.cartview(cond, **cart_opts)
        hp.cartview(maps[0], min=-250, max=250, **cart_opts)
        hp.cartview(maps[1], min=-5, max=5, **cart_opts)
        hp.cartview(maps[2], min=-5, max=5, **cart_opts)
        plt.show()
Ejemplo n.º 20
0
def cart_proj(args):
    """Cartesian projection to get a square part of a full sky map.
    """
    import numpy as np
    import healpy
    import h5py
    import rotate as rot
    import matplotlib
    matplotlib.use('Agg')
    # 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 == None:
                hpmap = f['map'][:]
            else:
                hpmap += f['map'][:]

    lat_range = [args.clat - args.lat_ext, args.clat + args.lat_ext]
    lon_range = [args.clon - args.lon_ext, args.clon + args.lon_ext]
    # first rotate the map to let the point [clat, clon] be at the center
    # must rotate clon and clat separately, and NOTE the negative sign
    hpmap = rot.rotate_map(hpmap, rot=(-args.clon, 0.0, 0.0))
    hpmap = rot.rotate_map(hpmap, rot=(0.0, -args.clat, 0.0))

    # lat, lon value after rotation
    rot_lat_range = [lat_range[0] - args.clat, lat_range[1] - args.clat]
    rot_lon_range = [lon_range[0] - args.clon, lon_range[1] - args.clon]

    # cartesian projection
    cart_map = healpy.cartview(hpmap[args.ifreq, args.pol], latra=rot_lat_range, lonra=rot_lon_range, return_projected_map=True) # only T map

    out_file = args.outfile or 'cart_%.1f_%.1f_%.1f_%.1f.hdf5' % (lat_range[0], lat_range[1], lon_range[0], lon_range[1])
    with h5py.File(out_file, 'w') as f:
        f.create_dataset('map', data=cart_map)
        f.attrs['lat_min'] = lat_range[0]
        f.attrs['lat_max'] = lat_range[1]
        f.attrs['lon_min'] = lon_range[0]
        f.attrs['lon_max'] = lon_range[1]
Ejemplo n.º 21
0
def plot_cart(map, min=None, max=None, title='', label=r'[$\#$ $deg^{-2}$]', savename=None, show=True, galactic_plane=False, ecliptic_plane=False, sgr_plane=False):
    #attention au sens de l'axe en RA ! --> la on le prend normal et on le retourne à la fin :)
    plt.figure(1)
    m = hp.ma(map)
    map_to_plot = hp.cartview(m, nest=True, flip='geo', rot=120, fig=1, return_projected_map=True)
    plt.close()

    fig, ax = plt.subplots(figsize=(11,7))
    map_plotted = plt.imshow(map_to_plot, vmin=min, vmax=max, cmap='jet', origin='lower', extent=[-60, 300, -90, 90])
    if label!=None:
        cb = plt.colorbar(map_plotted, ax=ax, orientation='horizontal', shrink=0.8, aspect=40)
        cb.set_label(label)
    if galactic_plane:
        ax.plot(galactic_plane_icrs.ra.wrap_at(300*u.deg).degree[index_galactic], galactic_plane_icrs.dec.degree[index_galactic], linestyle='-', color='black', label='Galactic plane')
    if ecliptic_plane:
        ax.plot(ecliptic_plane_icrs.ra.wrap_at(300*u.deg).degree[index_ecliptic], ecliptic_plane_icrs.dec.degree[index_ecliptic], linestyle=':', color='slategrey', label='Ecliptic plane')
    if sgr_plane:
        ax.plot(sgr_plane_icrs.ra.wrap_at(300*u.deg).degree[index_sgr], sgr_plane_icrs.dec.degree[index_sgr], linestyle='--', color='navy', label='Sgr. plane')

    ax.set_xlim(-60, 300)
    ax.xaxis.set_ticks(np.arange(-60, 330, 30))
    plt.gca().invert_xaxis()
    ax.set_xlabel('R.A. [deg]')
    ax.set_ylim(-90, 90)
    ax.yaxis.set_ticks(np.arange(-90, 120, 30))
    ax.set_ylabel('Dec. [deg]')

    if galactic_plane or ecliptic_plane:
        ax.legend(loc='lower right')
    if title!='':
        plt.title(title)
    if savename != None:
        plt.savefig(savename)
    if show:
        plt.show()
    else:
        plt.close()
Ejemplo n.º 22
0
    def gen_plots(self,lon,lat,width):
        mapT_ol = np.zeros(self.nbpix,dtype='int')
#        if self.indT[0] != 0: mapT_ol[self.indT[0]] = 0
        h.cartview(self.T/self.stdT,max=5,min=-5,rot=[lon,lat],lonra=[-width/2.,width/2.],latra=[-width/2.,width/2.],title='T S/N')
        h.graticule(dpar=10,dmer=10,coord='C')
        py.savefig(self.outdir+'/png/'+self.dir_coadd+'/mapT_sn.png')

        mapQ_ol = np.zeros(self.nbpix,dtype='int')
#        if self.indQ_ol[0] != 0: mapQ_ol[self.indQ_ol[0]] = 1
        h.cartview(self.Q/self.stdQ,max=5,min=-5,rot=[lon,lat],lonra=[-width/2.,width/2.],latra=[-width/2.,width/2.],title='Q S/N')
        h.graticule(dpar=10,dmer=10,coord='C')
        py.savefig(self.outdir+'/png/'+self.dir_coadd+'/mapQ_sn.png')

        mapU_ol = np.zeros(self.nbpix,dtype='int')
#        if self.indU_ol[0] != 0: mapU_ol[self.indU_ol[0]] = 1
        h.cartview(self.U/self.stdU,max=5,min=-5,rot=[lon,lat],lonra=[-width/2.,width/2.],latra=[-width/2.,width/2.],title='U S/N')
        h.graticule(dpar=10,dmer=10,coord='C')
        py.savefig(self.outdir+'/png/'+self.dir_coadd+'/mapU_sn.png')

        py.figure(10)
        par = plot_hist(self.T[self.indT[0]], 40, init_auto=True, xtitle='T', \
                            fname=self.outdir+'/png/'+self.dir_coadd+'/histT.png')
        py.figure(11)
        par = plot_hist(self.T[self.indT[0]], 40, init_auto=True, xtitle='T', \
                            fname=self.outdir+'/png/'+self.dir_coadd+'/histT_log.png',option_ylog=True)
        py.figure(12)
        par = plot_hist(self.Q[self.indQ[0]], 40, init_auto=True, xtitle='Q', \
                            fname=self.outdir+'/png/'+self.dir_coadd+'/histQ.png')
        py.figure(13)
        par = plot_hist(self.Q[self.indQ[0]], 40, init_auto=True, xtitle='Q', \
                            fname=self.outdir+'/png/'+self.dir_coadd+'/histQ_log.png',option_ylog=True)
        py.figure(14)
        par = plot_hist(self.U[self.indU[0]], 40, init_auto=True, xtitle='U', \
                            fname=self.outdir+'/png/'+self.dir_coadd+'/histU.png')
        py.figure(15)
        par = plot_hist(self.U[self.indU[0]], 40, init_auto=True, xtitle='U', \
                            fname=self.outdir+'/png/'+self.dir_coadd+'/histU_log.png',option_ylog=True)
Ejemplo n.º 23
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)
Ejemplo n.º 24
0
	return ret	

#================= MAIN ========================#	

info = read_info_no_co()

# NSIDE = 2048
fact     = 1.42144524614e-05 
filename = 'HFI_CompMap_ThermalDustModel_2048_R1.20.fits'

test_map = hp.read_map(filename, field = 0)
#hp.mollview(test_map, title=filename, coord='G', unit='K', norm='hist', min=1e-7,max=1e-3, xsize=800)

#hp.mollview(test_map)
tmap = hp.cartview(test_map, title=filename, coord='G', rot=[0,0], unit='K', 
	norm='hist', min=1e-7,max=1e-3, xsize=800, lonra=[-180,-160], latra=[63,90],
	return_projected_map=True, cbar=True)
#hp.orthview(test_map)
#hp.gnomview(test_map)

# print hp.get_nside(test_map)
# print hp.maptype(test_map)
# print hp.get_map_size(test_map)
# print len(test_map)
# print test_map[0:10]*np.float(fact)

# print test_map
n     = 16
rang  = range(0,12*n**2)
npix  = hp.nside2npix(n)
angs  = hp.pix2ang(n,rang)
Ejemplo n.º 25
0
    ymax = 1.0

    xgrid, ygrid = NP.meshgrid(NP.linspace(xmin, xmax, backdrop_xsize), NP.linspace(ymin, ymax, backdrop_xsize))
    nanind = (xgrid**2 + ygrid**2) > 1.0
    goodind = (xgrid**2 + ygrid**2) <= 1.0
    zgrid = NP.empty_like(xgrid)
    zgrid[nanind] = NP.nan
    zgrid[goodind] = NP.sqrt(1.0 - (xgrid[goodind]**2 + ygrid[goodind]**2))

    xvect = xgrid.ravel()
    yvect = ygrid.ravel()
    zvect = zgrid.ravel()
    xyzvect = NP.hstack((xvect.reshape(-1,1), yvect.reshape(-1,1), zvect.reshape(-1,1)))

if use_DSM or use_GSM:
    backdrop = HP.cartview(fluxes_DSM.ravel(), coord=['G','E'], rot=[180,0,0], xsize=backdrop_xsize, return_projected_map=True)
elif use_GLEAM or use_SUMSS:
    if backdrop_coords == 'radec':
        backdrop = griddata(NP.hstack((ra_deg.reshape(-1,1), dec_deg.reshape(-1,1))), fpeak, NP.hstack((xvect.reshape(-1,1), yvect.reshape(-1,1))), method='cubic')
        backdrop = backdrop.reshape(backdrop_xsize/2, backdrop_xsize)
    elif backdrop_coords == 'dircos':
        if (telescope == 'mwa_dipole') or (obs_mode == 'drift'):
            backdrop = PB.primary_beam_generator(xyzvect, freq, telescope=telescope, freq_scale='Hz', skyunits='dircos', phase_center=[0.0,0.0,1.0])
            backdrop = backdrop.reshape(backdrop_xsize, backdrop_xsize)
else:
    if backdrop_coords == 'radec':
        backdrop = griddata(NP.hstack((ra_deg.reshape(-1,1), dec_deg.reshape(-1,1))), fpeak, NP.hstack((xvect.reshape(-1,1), yvect.reshape(-1,1))), method='nearest')
        backdrop = backdrop.reshape(backdrop_xsize/2, backdrop_xsize)
    elif backdrop_coords == 'dircos':
        if (telescope == 'mwa_dipole') or (obs_mode == 'drift'):
            backdrop = PB.primary_beam_generator(xyzvect, freq, telescope=telescope, freq_scale='Hz', skyunits='dircos', phase_center=[0.0,0.0,1.0])
Ejemplo n.º 26
0
def plot_cartmap(lvc_healpix_file,
                 levels=[0.5, 0.9],
                 angsize=3.,
                 tile_ra=None,
                 tile_dec=None,
                 targ_ra=None,
                 targ_dec=None):
    """Plot the GW map with the DESI footprint in a Cartesian projection.
    
    Parameters
    ----------
    lvc_healpix_file : str
        Relative or absolute path to LIGO/Virgo HEALPix angular reconstruction file.
    levels : list
        List of credible interval thresholds, e.g., 0.5, 0.9, etc.
    angsize : float
        Size of plot (-angsize, +angsize) in degrees about the center.
    tile_ra : list or ndarray
        List of RAs for DESI tiles (in deg).
    tile_dec : list or ndarray
        List of declinations for DESI tiles (in deg).
    targ_ra : list or ndarray
        List of RAs for DESI targets (in deg).
    targ_dec : list or ndarray
        List of declinations for DESI targets (in deg).
    
    Returns
    -------
    fig : matplotlib.Figure
        Figure object for accessing or saving a plot.
    """
    gwmap = hp.read_map(lvc_healpix_file)
    npix = len(gwmap)
    nside = hp.npix2nside(npix)

    # Compute contours.
    if nside > 256:
        _gwmap = hp.pixelfunc.ud_grade(gwmap, 256)
        _gwmap = _gwmap / np.sum(_gwmap)
    else:
        _gwmap = gwmap
    ra_contour, dec_contour = compute_contours(levels, _gwmap)

    # Create a temporary plot to produce a nice image array.
    # This code sets the size of the map around the maximum value.
    maxpix = np.argmax(gwmap)
    ra_c, dec_c = hp.pix2ang(nside, maxpix, lonlat=True)

    xmin = np.round(ra_c - angsize)
    xmax = np.round(ra_c + angsize)
    if xmax < xmin:
        xmin, xmax = xmax, xmin
    cxmin, cxmax = xmin, xmax
    frot = 0.
    if xmax > 90 and xmax < -90:
        frot, cxmin, cmax = 180., xmax - 180., xmax + 180.
    ymin = np.round(dec_c - angsize)
    ymax = np.round(dec_c + angsize)

    faspect = np.abs(cxmax - cxmin) / np.abs(ymax - ymin)
    fysize = 4
    figsize = (fysize * faspect + 1, fysize + 2)

    # Open and close the temporary plot.
    tfig = plt.figure(num=2, figsize=figsize)
    rotimg = hp.cartview(gwmap,
                         fig=2,
                         coord='C',
                         title="",
                         cbar=False,
                         flip='astro',
                         lonra=[cxmin, cxmax],
                         latra=[ymin, ymax],
                         rot=frot,
                         notext=True,
                         xsize=1000,
                         return_projected_map=True)
    plt.close(tfig)

    # Now make the real plot with the desired angular contours.
    fig, ax = plt.subplots(1, 1, num=1, figsize=figsize)
    img = ax.imshow(rotimg,
                    extent=[cxmax, cxmin, ymin, ymax],
                    origin='lower',
                    cmap='OrRd')

    for i, (rc, dc, lstyle, clev) in enumerate(
            zip(ra_contour, dec_contour, ['--', '-'], ['50', '90'])):
        p = ax.plot(rc, dc, 'g-', ls=lstyle, lw=2, label='{}% CI'.format(clev))

    ax.set(xlim=(cxmax, cxmin), xlabel='RA [deg]', ylabel='Dec [deg]')
    ax.grid(ls=':')

    _h, _l = ax.get_legend_handles_labels()

    # Add DESI tile drawings, specified by central RA, Dec.
    if tile_ra is not None and tile_dec is not None:
        for _ra_c, _dec_c in zip(tile_ra, tile_dec):
            circ = plt.Circle((_ra_c, _dec_c),
                              radius=1.6,
                              fc='None',
                              ec='b',
                              ls=':',
                              lw=2)
            ax.add_artist(circ)

        _h.append(circ)
        _l.append('DESI FOV')

    # Add DESI targets, specified by RA, Dec.
    if targ_ra is not None and targ_dec is not None:
        ax.plot(targ_ra, targ_dec, 'k.', alpha=0.1)

    ax.legend(handles=_h, labels=_l, fontsize=10, ncol=2)

    cb = fig.colorbar(img,
                      orientation='horizontal',
                      shrink=0.95,
                      fraction=0.04,
                      pad=0.2,
                      ax=ax)
    cb.set_label(r'$dp/d\Omega$ [deg$^{-2}$]')

    return fig
Ejemplo n.º 27
0
bmap.draw_parallels(); bmap.draw_meridians()

for band,sky in sum_skymaps.items():
    outfile = outbase%(band,NSIDE)+'.fits.gz'
    print "Writing %s..."%outfile
    hp.write_map(outfile,sky)

    outfile = outbase%(band,NSIDE)+'_mbt.png'
    print "Writing %s..."%outfile
    bmap.draw_hpxmap(np.log10(sky))
    plt.savefig(outfile,bbox_inches='tight')
    plt.clf()

    outfile = outbase%(band,NSIDE)+'_car.png'
    print "Writing %s..."%outfile
    hp.cartview(np.log10(sky),title='DECam Coverage (%s-band)'%band,
                unit='log10(TEFF*EXPTIME)',fig=1)
    plt.savefig(outfile,bbox_inches='tight')
    plt.clf()

    outfile = outbase%(band,NSIDE)+'_hist.png'
    plt.hist(sky,bins=np.linspace(1,1e3,50),color=COLORS['band'])
    plt.title('%s-band'%band); plt.xlabel('sum(TEFF * EXPTIME)')
    plt.savefig(outfile,bbox_inches='tight')
    plt.clf()

fig = plt.figure(1)
bmap = DECamMcBride()
bmap.draw_parallels(); bmap.draw_meridians()

outbase = "decam_max_expmap_%s_n%s"
for band,sky in max_skymaps.items():
Ejemplo n.º 28
0
def convert(infile='empty', i_ext=-1, i_col=-1, coordsys_out='-1'):
    """Main function of makeFitsImage.py
    
    Execute makeFitsImage.py --help for more details (it is not yet been fully implemented to be loaded within Python, also it should work already).
    """

    warnings.warn(
        'Attention: Conversion from HEALPix format to FITS image causes degradation.\n All information in the FITS header corresponds to the original HEALPix data.'
    )

    #  read header:
    hdulist_in = fits.open(infile)
    type = hdulist_in[1].header['TTYPE1']

    # detect type of input file
    if type[:5] == 'PIXEL':
        print('  ... detected Healpix part-sky map...')
        fullsky = False
        if (hp_version > 1.2 and hp_version < 1.9):
            raise IOError(
                'Handling of part-sky FITS files not supported by healpy versions < 1.9.0.'
            )
    else:
        try:
            scheme = hdulist_in[1].header['INDXSCHM']
            if scheme[:8] == 'IMPLICIT':
                print(
                    '  ... detected Healpix full-sky map, e.g. created by Clumpy with the -o2 option.'
                )
                fullsky = True
            elif scheme[:8] == 'EXPLICIT':
                print(
                    '  ... detected Healpix part-sky map, e.g. created by Clumpy with the -o2 option.'
                )
                fullsky = False
            else:
                raise IOError(
                    'FITS keyword "INDXSCHM" must be either "IMPLICIT" or "EXPLICIT".'
                )
        except:
            warnings.warn(
                'Possibly wrong input file format. Must contain Healpix sky map.\n'
            )
            fullsky = True
            i_ext = 1
            i_col = 1

    if i_ext == -1:
        warnings.warn(
            'No input extension specified with --extension or -e. Set to first extension.'
        )
        i_ext = 1
    if i_col == -1:
        warnings.warn(
            'No input column specified with --column or -c. Set to first column.'
        )
        i_col = 1

    input_header = hdulist_in[i_ext].header
    ext_name = input_header['EXTNAME']
    columns = hdulist_in[i_ext].columns
    if fullsky == False:
        column = columns[i_col]  # zeroth column is PIXEL
    else:
        column = columns[i_col - 1]

    try:
        map_center_psi_deg = input_header['PSI_0']
    except:
        raise IOError(
            'Necessary input information "PSI_0" missing.\n Note: This script is tailored to read Healpix maps created by Clumpy > 2015.06_corr3.'
        )
    try:
        map_center_theta_deg = input_header['THETA_0']
    except:
        raise IOError(
            'Necessary input information "THETA_0" missing.\n Note: This script is tailored to read Healpix maps created by Clumpy > 2015.06_corr3.'
        )
    try:
        map_diam_theta_deg = input_header['SIZE_Y']
    except:
        raise IOError(
            'Necessary input information "SIZE_Y" missing.\n Note: This script is tailored to read Healpix maps created by Clumpy > 2015.06_corr3.'
        )
    try:
        map_diam_theta_orth_deg = input_header['SIZE_X']
    except:
        map_diam_theta_orth_deg = map_diam_theta_deg
    try:
        coordsys_in = input_header['COORDSYS']
    except:
        raise IOError(
            'Necessary input information "COORDSYS" missing.\n Note: This script is tailored to read Healpix maps created by Clumpy > 2015.06_corr3.'
        )
    try:
        units = input_header['TUNIT' + str(i_col + 1)]
    except:
        units = 'not specified'
    try:
        fsky = input_header['F_SKY']
    except:
        fsky = 'not specified'
    try:
        map_mean = input_header['MEAN']
    except:
        map_mean = 'not specified'
    try:
        nside = input_header['NSIDE']
    except:
        raise IOError('Necessary input information "NSIDE" missing.')
    try:
        dtype_hpx = input_header['HPX_TYPE']
    except:
        raise IOError('Necessary input information "HPX_TYPE" missing.')

    # special treatment for clumpy halo mode files:
    map_center_psi_deg_out = map_center_psi_deg
    map_center_theta_deg_out = map_center_theta_deg
    try:
        simumode = input_header['SIMUMODE']
        if (simumode[0] == 'h'):
            map_center_psi_deg = 0.
            map_center_theta_deg = 0.
    except:
        warnings.warn(
            'Could not read "SIMUMODE" keyword. Possibly wrong sky area exported.'
        )
        simumode = "-1"

    tbdata = hdulist_in[i_ext].data
    npix_fov = len(tbdata[column.name])

    map_sum = tbdata[column.name].sum(dtype=np.float64)
    if map_mean == 'not specified':
        print('Calculate mean...')
        map_mean = tbdata[column.name].mean(dtype=np.float64)
    hdulist_in.close()

    #  read map:
    dtype_map = np.float64
    if dtype_hpx == 'FLOAT32':
        dtype_map = np.float32
    elif dtype_hpx == 'FLOAT64':
        dtype_map = np.float64
    else:
        raise IOError(
            'Healpix datatype (keyword "HPX_TYPE" in input file header) must be FLOAT32 or FLOAT64.'
        )

    print('Read input map...')
    if fullsky == True:
        map_in = hp.read_map(infile)
    else:
        map_in = hp.read_map(infile,
                             partial=True,
                             field=i_col - 1,
                             hdu=i_ext,
                             dtype=dtype_map)

    if fsky == 'not specified':
        npix = len(map_in)
        fsky = float(npix_fov) / float(npix)

    if map_diam_theta_orth_deg < 342.85:
        map_diam_theta_orth_deg *= 1.05
    if map_diam_theta_deg < 171.42:
        map_diam_theta_deg *= 1.05

    pixelnr = hp.nside2npix(nside)
    resol_deg = hp.nside2resol(nside) * 180. / np.pi
    # make sure that npix_x, npix_y are odd numbers:
    npix_x_check = int(map_diam_theta_orth_deg / resol_deg) * 2 + 1
    npix_y_check = int(map_diam_theta_deg / resol_deg) * 2 + 1
    if npix_x_check > 1999:
        npix_x_check = 1997
        warnings.warn(
            'Maximum number of 1997 pixels in x-dimension is reached.')
    if npix_y_check > 1999:
        npix_y_check = 1997
        warnings.warn(
            'Maximum number of 1997 pixels in y-dimension is reached.')

    flip = 'astro'
    ## flip map for odd behavior at the gal. anticenter:
    #if abs(map_center_psi_deg) == 180.0 and map_center_theta_deg == 0:
    #    flip='geo'

    # transform to galactic coordinates:
    if coordsys_in[:5] == 'G':
        print('Detected galactic coordinate system')
        if coordsys_out == '-1' or coordsys_out == 'G':
            coord = 'G'
            coordsys_out = coord
        else:
            coord = ['G', coordsys_out]

    elif coordsys_in[:5] == 'C':
        print('Detected equatorial coordinate system')
        coord = ['C', 'G']
        if coordsys_out == '-1' or coordsys_out == 'C':
            coord = 'C'
            coordsys_out = coord
        else:
            coord = ['C', coordsys_out]
    elif coordsys_in[:5] == 'E':
        print('Detected ecliptic coordinate system')
        coord = ['E', 'G']
        if coordsys_out == '-1' or coordsys_out == 'E':
            coord = 'E'
            coordsys_out = coord
        else:
            coord = ['E', coordsys_out]

    else:
        raise IOError(
            'Input coordinate system not recognized. Must be either G, C, or E.'
        )

    if coordsys_out not in ['-1', 'G', 'C', 'E']:
        raise IOError(
            'Output coordinate system not recognized. Must be either G, C, or E.'
        )

    if len(coord) > 1:
        map_center_theta_deg, map_center_psi_deg = hp.Rotator(
            coord=coord,
            deg=False)(np.pi / 2 - map_center_theta_deg / 180. * np.pi,
                       map_center_psi_deg / 180. * np.pi)
        map_center_psi_deg *= 180. / np.pi
        map_center_theta_deg = 90. - map_center_theta_deg * 180. / np.pi

    #  get projected map
    image_array = hp.cartview(map_in, rot = [map_center_psi_deg,map_center_theta_deg], \
                              lonra = [- map_diam_theta_orth_deg/2, map_diam_theta_orth_deg/2], \
                              latra = [- map_diam_theta_deg/2, map_diam_theta_deg/2], \
                              xsize=npix_x_check, \
                              flip=flip, \
                              coord=coord, \
                              return_projected_map = True)

    npix_x = image_array.shape[1]
    npix_y = image_array.shape[0]
    if npix_x_check != npix_x:
        warnings.warn('Attention!  npix_x_check =' + str(npix_x_check) +
                      '!= npix_x=' + str(npix_x))
    if npix_y_check != npix_y:
        warnings.warn('Attention!  npix_y_check =' + str(npix_y_check) +
                      '!= npix_y=' + str(npix_y))

    x_center = (npix_x + 1) / 2
    y_center = (npix_y + 1) / 2

    delta_x = map_diam_theta_orth_deg / npix_x
    delta_y = map_diam_theta_deg / npix_y
    print('Resolution of map ( delta_x , delta_y ): (' + str(delta_x) + ',' +
          str(delta_y) + ')')

    # rotate map for odd behavior at the gal. poles:
    #if abs(map_center_theta_deg) == 90.0:
    #map_center_psi_deg = map_center_psi_deg + 180

    if map_center_psi_deg < 0:
        map_center_psi_deg += 360.

    map_out = np.zeros((npix_y, npix_x), dtype=dtype_map)
    map_out[:][:] = image_array[:][:]

    # replace 1e-40 values by HEALPIX blind value
    map_out[map_out < 4e-40] = -1.6375e30

    # write out total J-Factor/flux in map:
    if 'sr^-1' in units:
        totalflux = map_mean * 4. * np.pi * fsky
    else:
        totalflux = map_sum

    # create fits header:
    if coordsys_out == 'G':
        coordlon = 'GLON-CAR'
        coordlat = 'GLAT-CAR'
    elif coordsys_out == 'C':
        coordlon = 'RA---CAR'
        coordlat = 'DEC--CAR'
    elif coordsys_out == 'E':
        coordlon = 'ELON-CAR'
        coordlat = 'ELAT-CAR'

    reference_header = input_header[41:]
    reference_header.update({'EXTNAME' : ('Skymap'), \
                             'CDELT1'  : (- delta_x, 'pixel size (approx.) in longitude-dir. [deg]'), \
                             'CDELT2'  : (delta_y, 'pixel size (approx.) in latitude-dir. [deg]'), \
                             'CRPIX1'  : (x_center, 'central pixel in longitude direction'), \
                             'CRPIX2'  : (y_center, 'central pixel in latitude direction'), \
                             'CRVAL1'  : (map_center_psi_deg_out, 'longitude coordinate of map center [deg]'), \
                             'CRVAL2'  : (map_center_theta_deg_out, 'latitude coordinate of map center [deg]'), \
                             'CTYPE1'  : (coordlon, 'longitude coord. system (cartesian projection)'), \
                             'CTYPE2'  : (coordlat, 'latitude coord. system (cartesian projection)'), \
                             'CUNIT1'  : ('deg', 'longitude axis unit'), \
                             'CUNIT2'  : ('deg', 'latitude axis unit'), \
                             'NAXIS'   : 2, \
                             'NAXIS1'  : (npix_x, 'number of pixels in longitude direction'), \
                             'NAXIS2'  : (npix_y, 'number of pixels in latitude direction'), \
                             'BUNIT'   : (units, 'pixel value unit'),\
                             'F_SKY'   : (fsky, 'fraction of sky covered by FOV'), \
                             'MEAN'    : (map_mean, 'mean value in FOV (same unit as BUNIT)'), \
                             'FLUX_TOT': (totalflux, 'total integrated J-Factor (flux) in FOV'), \
                             'NSIDE'   : (nside, 'HEALPix resolution of original image'), \
                             'AUTHOR'  : 'file created by Clumpy, makeFitsImage.py'})

    # write fits file:
    if len(columns) > 1:
        outfile = infile[:-5] + '-' + ext_name + '-' + column.name + '-image.fits'
    else:
        outfile = infile[:-5] + '-image.fits'

    if astropy_version < 2:
        fits.writeto(outfile, map_out, reference_header, clobber=True)
    else:
        fits.writeto(outfile, map_out, reference_header, overwrite=True)
    print('Output file written to: ' + outfile)
Ejemplo n.º 29
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.º 30
0
def plot_patches(src_num, info):
	# Define constants #
	deg2rad   = np.pi/180.
	# Define the width of area #
	beam   = 14.4           # Beam = 3.5'
	dbeam  = beam/60./2.     # Beam = 3.5' -> dbeam = beam/60/2 in degree
	offset = dbeam          # degree

	# HI continuum map and resolution #
	cont  = hp.read_map(os.getenv("HOME")+'/hdata/hi/lambda_chipass_healpix_r10.fits', field = 0, h=False)
	nside = hp.get_nside(cont)
	res   = hp.nside2resol(nside, arcmin=False)
	dd    = res/deg2rad/5.0

	# OK - Go #
	tb    = {}
	for i in range(0,src_num):
		if(i ==2): continue
		if(i ==3): continue
		if(i ==6): continue
		if(i ==11): continue
		## Find the values of Continuum temperature #
		tb[i] = []
		
		## Longitude and latitude ##
		l     = info['l'][i]
		b     = info['b'][i]

		# if(i != 14): continue

		# Plot cartview a/o mollview #
		ll = l
		if (l>180):
			ll = ll-360.

		f = 10.
		# if (i == sr):
		proj = hp.cartview(cont, title=info['src'][i]+'('+str(info['l'][i])+','+str(info['b'][i])+')', coord='G', unit='',
				norm=None, xsize=1920, lonra=[ll-0.5,ll+0.5], latra=[b-0.5,b+0.5],
				return_projected_map=True)

		# hp.cartview(cont, title=info['src'][i]+'('+str(info['l'][i])+','+str(info['b'][i])+')', coord='G', unit='',
		# 		norm='hist', xsize=800, lonra=[ll-offset-f*offset,ll+offset+f*offset], latra=[b-offset-f*offset,b+offset+f*offset],
		# 		return_projected_map=True)

		# hp.orthview(cont, title=info['src'][i]+'('+str(info['l'][i])+','+str(info['b'][i])+')', coord='G', unit='',
		# 		norm='hist', xsize=800, return_projected_map=True)

		# hp.mollview(cont, title=info['src'][i]+'('+str(info['l'][i])+','+str(info['b'][i])+')',
		# 	coord='G', unit='', rot=[0,0,0], norm='hist')

		# hp.mollzoom(cont, title=info['src'][i]+'('+str(info['l'][i])+','+str(info['b'][i])+')',
		# 	coord='G', unit='', rot=[0,0,0], norm=None, min=4599., max=4600.)

		print proj
		print proj.shape

		# Cal. #
		theta = (90.0-b)*deg2rad
		phi   = l*deg2rad
		pix   = hp.ang2pix(nside, theta, phi, nest=False)

		if (cont[pix] > -1.0e30) : # Some pixels not defined
			tb[i].append(cont[pix])

		for x in pl.frange(l-offset, l+offset, dd):
			for y in pl.frange(b-offset, b+offset, dd):
				cosb = np.cos(b*deg2rad)
				cosy = np.cos(y*deg2rad)
				if ( (((x-l)**2 + (y-b)**2) <= offset**2) ):
					theta = (90.0 - y)*deg2rad
					phi   = x*deg2rad
					pix   = hp.ang2pix(nside, theta, phi, nest=False)
					# hp.projtext(x, y, '.'+str(pix)+str(cont[pix]), lonlat=True, coord='G')
					# hp.projtext(x, y, '.'+str(cont[pix]), lonlat=True, coord='G')
					hp.projtext(x, y, '.', lonlat=True, coord='G')

		plt.show()
Ejemplo n.º 31
0
                notext=False,
                return_projected_map=False)
    hp.cartview(map=eqdata,
                fig=3,
                rot=None,
                zat=None,
                coord=None,
                unit='',
                xsize=800,
                ysize=None,
                lonra=None,
                latra=None,
                title='Cartesian view',
                nest=False,
                remove_dip=False,
                remove_mono=False,
                gal_cut=0,
                min=None,
                max=None,
                flip='astro',
                format='%.3g',
                cbar=True,
                cmap=None,
                norm=" ",
                aspect=None,
                hold=False,
                sub=224,
                margins=None,
                notext=False,
                return_projected_map=False)

plt.show()
Ejemplo n.º 32
0
 def __call__(self, metricValueIn, slicer, userPlotDict, fignum=None):
     """
     Plot the sky map of metricValue using healpy cartview plots in thin strips.
     raMin: Minimum RA to plot (deg)
     raMax: Max RA to plot (deg).  Note raMin/raMax define the centers that will be plotted.
     raLen:  Length of the plotted strips in degrees
     decMin: minimum dec value to plot
     decMax: max dec value to plot
     metricValueIn: metric values
     """
     plotDict = {}
     plotDict.update(self.defaultPlotDict)
     plotDict.update(userPlotDict)
     metricValue = applyZPNorm(metricValueIn, plotDict)
     norm = None
     if plotDict['logScale']:
         norm = 'log'
     clims = setColorLims(metricValue, plotDict)
     cmap = setColorMap(plotDict)
     racenters = np.arange(plotDict['raMin'], plotDict['raMax'],
                           plotDict['raLen'])
     nframes = racenters.size
     fig = plt.figure(fignum)
     # Do not specify or use plotDict['subplot'] because this is done in each call to hp.cartview.
     for i, racenter in enumerate(racenters):
         if i == 0:
             useTitle = plotDict['title'] + ' /n' + '%i < RA < %i' % (
                 racenter - plotDict['raLen'], racenter + plotDict['raLen'])
         else:
             useTitle = '%i < RA < %i' % (racenter - plotDict['raLen'],
                                          racenter + plotDict['raLen'])
         hp.cartview(metricValue.filled(slicer.badval),
                     title=useTitle,
                     cbar=False,
                     min=clims[0],
                     max=clims[1],
                     flip='astro',
                     rot=(racenter, 0, 0),
                     cmap=cmap,
                     norm=norm,
                     lonra=[-plotDict['raLen'], plotDict['raLen']],
                     latra=[plotDict['decMin'], plotDict['decMax']],
                     sub=(nframes + 1, 1, i + 1),
                     fig=fig)
         hp.graticule(dpar=20, dmer=20, verbose=False)
     # Add colorbar (not using healpy default colorbar because want more tickmarks).
     ax = fig.add_axes([0.1, .15, .8, .075])  # left, bottom, width, height
     # Add label.
     if plotDict['label'] is not None:
         plt.figtext(0.8, 0.9, '%s' % plotDict['label'])
     # Make the colorbar as a seperate figure,
     # from http: //matplotlib.org/examples/api/colorbar_only.html
     cnorm = colors.Normalize(vmin=clims[0], vmax=clims[1])
     # supress silly colorbar warnings
     with warnings.catch_warnings():
         warnings.simplefilter("ignore")
         cb = mpl.colorbar.ColorbarBase(ax,
                                        cmap=cmap,
                                        norm=cnorm,
                                        orientation='horizontal',
                                        format=plotDict['cbarFormat'])
         cb.set_label(plotDict['xlabel'])
         cb.ax.tick_params(labelsize=plotDict['labelsize'])
         if norm == 'log':
             tick_locator = ticker.LogLocator(numticks=plotDict['nTicks'])
             cb.locator = tick_locator
             cb.update_ticks()
         if (plotDict['nTicks'] is not None) & (norm != 'log'):
             tick_locator = ticker.MaxNLocator(nbins=plotDict['nTicks'])
             cb.locator = tick_locator
             cb.update_ticks()
     # If outputing to PDF, this fixes the colorbar white stripes
     if plotDict['cbar_edge']:
         cb.solids.set_edgecolor("face")
     fig = plt.gcf()
     return fig.number
Ejemplo n.º 33
0
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import healpy as hp


gauss_data = '/tigress/nrodd/NPTFWorking/FindPS/plots/nptf/IG_NDI/FD_check.txt.gz'
king_data = '/tigress/nrodd/NPTFWorking/FindPS/plots/nptf_king/IG_NDI/FD_check.txt.gz'

gaussload = np.loadtxt(gauss_data)
gaussmap = np.sum(gaussload[8:16,::],axis=0)
kingload = np.loadtxt(king_data)
kingmap = np.sum(kingload[8:16,::],axis=0)

hp.cartview(gaussmap,lonra=[-10,10], latra=[-10,10],title='Gauss NFW+Disk PS 10x10',max=30)
plt.savefig('./Plots/gauss10to10.pdf')
plt.close()

hp.cartview(kingmap,lonra=[-10,10], latra=[-10,10],title='King NFW+Disk PS 10x10',max=30)
plt.savefig('./Plots/king10to10.pdf')
plt.close()

hp.cartview(gaussmap,lonra=[-30,30], latra=[-30,30],title='Gauss NFW+Disk PS 30x30',max=30)
plt.savefig('./Plots/gauss30to30.pdf')
plt.close()

hp.cartview(kingmap,lonra=[-30,30], latra=[-30,30],title='King NFW+Disk PS 30x30',max=30)
plt.savefig('./Plots/king30to30.pdf')
plt.close()
Ejemplo n.º 34
0
plt.grid()
plt.show()

l  = 51.641648
b  = -9.6750019

# Plot cartview a/o mollview #
ll = l
if (l>180):
	ll = ll-360.

offset = 1.
lonr = [51.25, 52.0]
latr = [-10., -9.35]
m    = hp.cartview(ir_map, title=r'$CO$', coord='G', unit='Krj km/s', #min=-2.,max=3.,
		norm=None, xsize=800, lonra=lonr, latra=latr, #lonra=[ll-offset,ll+offset], latra=[b-offset,b+offset],
		return_projected_map=True)

# hp.mollview(tau_map, title=info['src'][i]+'('+str(info['l'][i])+','+str(info['b'][i])+') - '+map_file,
# 	coord='G', unit='', rot=[l,b,0], norm='hist', min=1e-7,max=1e-3, xsize=800)

# Cal. #
hp.projplot(ll, b, 'bo', lonlat=True, coord='G')
hp.projtext(ll, b, ' (' + str(round(ll,2)) + ',' + str(round(b,2)) + ')', lonlat=True, coord='G', fontsize=18, weight='bold')

# theta = (90.0-b)*deg2rad
# phi   = l*deg2rad
# pix   = hp.ang2pix(nside, theta, phi, nest=False)

# for x in pl.frange(l-offset, l+offset, dd):
# 	for y in pl.frange(b-offset, b+offset, dd):
Ejemplo n.º 35
0
def plot_haslam_408mhz_map():
	# map_file = 'data/haslam408_dsds_Remazeilles2014.fits'
	# lambda_haslam408_nofilt.fits
	# lambda_haslam408_dsds.fits
	# lambda_zea_haslam408_dsds.fits
	# haslam408_dsds_Remazeilles2014.fits
	# haslam408_ds_Remazeilles2014.fits
	# lambda_chipass_healpix_r10.fits

	# Define constants #
	map_file = os.getenv("HOME")+'/hdata/oh/haslam408_dsds_Remazeilles2014.fits'
	deg2rad  = np.pi/180.
	factor   = (408./1665.)**2.8

	# Define the width of area #
	beam   = 51.            # Beam for Haslam survey = 51'
	dbeam  = beam/120.0     # Beam = 51' -> dbeam = beam/60/2 in degree
	offset = dbeam          # degree
	edge   = dbeam/40.      # To plot a rectangle about the source

	info = read_src_lb()
	src  = info['src']
	gl   = info['l']
	gb   = info['b']
	il   = info['il']
	ib   = info['ib']
	tbg  = info['tbg']
	lid  = info['l-idx']
	bid  = info['b-idx']
	bg1  = info['tbg1']
	bgh  = info['tbg_hpy']

	tb408 = hp.read_map(map_file,field=0, nest=False, hdu=1, h=False, verbose=False)
	nside = hp.get_nside(tb408)
	res   = hp.nside2resol(nside, arcmin=False)
	dd    = res/deg2rad/10.0
	hp.cartview(tb408, title='Continuum background at 408 MHz from Haslam et al. Survey', coord='G', unit='K',\
		norm='hist', xsize=800) #min=19.9,max=20.6

	# hp.mollview(tb408, title='Continuum background at 408 MHz from Haslam et al. Survey', coord='G', unit='K', norm='hist', xsize=800) #min=19.9,max=20.6

	for i in range(len(src)):
		sl = gl[i]
		sb = gb[i]

		if (sl > 180.) :
			sl = sl - 360.

		## Plot cartview a/o mollview #
		# ll = sl
		# if (sl>180):
		# 	ll = ll-360.

		# hp.cartview(tb408, title=src[i]+': ' + str(sl) + ',' + str(sb), coord='G', unit='',
		# 		norm='hist', xsize=800, lonra=[ll-offset-0.1*offset,ll+offset+0.1*offset], latra=[sb-offset-0.1*offset,sb+offset+0.1*offset],
		# 		return_projected_map=True)
		## End Plot cartview a/o mollview ##

		theta = (90.0 - sb)*deg2rad
		phi   = sl*deg2rad
		pix   = hp.ang2pix(nside, theta, phi, nest=False)

		tbg_i = []
		if (tb408[pix] > 0.) : # Some pixels not defined
			tbg_i.append(tb408[pix])

		for x in pl.frange(sl-offset, sl+offset, dd):
				for y in pl.frange(sb-offset, sb+offset, dd):
					cosb = np.cos(sb*deg2rad)
					cosy = np.cos(y*deg2rad)

					if ( ((x-sl)**2 + (y-sb)**2) <= offset**2 ):
						# hp.projtext(x, y, '.', lonlat=True, coord='G')
						theta = (90.0 - y)*deg2rad
						phi   = x*deg2rad
						pix   = hp.ang2pix(nside, theta, phi, nest=False)

						if (tb408[pix] > 0.) :
							tbg_i.append(tb408[pix])

		# plt.show()
		# tbg_i = list(set(tbg_i))
		tbg_i = np.asarray(tbg_i, dtype = np.float32)	
		val   = np.mean(tbg_i)

		if(i<18):
			print '{0}\t\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}\t{9}'\
			.format(src[i], gl[i], gb[i], il[i], ib[i], tbg[i], lid[i], bid[i], bg1[i], val)
		else:
			print '{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}\t{9}'\
			.format(src[i], gl[i], gb[i], il[i], ib[i], tbg[i], lid[i], bid[i], bg1[i], val)

		b_edge = 300.*edge
		l_edge = b_edge/np.cos(sb*deg2rad)

		equateur_lon = [sl-l_edge, sl+l_edge, sl+l_edge, sl-l_edge, sl-l_edge]
		equateur_lat = [sb+b_edge, sb+b_edge, sb-b_edge, sb-b_edge, sb+b_edge]
		# hp.projplot(equateur_lon, equateur_lat, lonlat=True, coord='G')
		hp.projplot(sl, sb, 'ko', lonlat=True, coord='G')

		# hp.projtext(sl, sb, src[i] +' ('+ str("{0:.4e}".format(val))+')', lonlat=True, coord='G') 
		hp.projtext(sl, sb, src[i], lonlat=True, coord='G', fontsize=14) 

	plt.show()
Ejemplo n.º 36
0
def plot_patches(map_file, info):
	src = info['src']

	# Define constants #
	deg2rad   = np.pi/180.

	# Define the width of area #
	beam   = 4.3            # Beam = 4.3'
	dbeam  = beam/120.0     # Beam = 30' -> dbeam = beam/60/2 in degree
	offset = dbeam          # degree

	# TTYPE1  = 'TAU353  '           / Optical depth at 353GHz                        
	# TTYPE2  = 'ERR_TAU '           / Error on optical depth                         
	# TTYPE3  = 'EBV     '           / E(B-V) color excess                            
	# TTYPE4  = 'RADIANCE'           / Integrated emission                            
	# TTYPE5  = 'TEMP    '           / Dust equilibrium temperature                   
	# TTYPE6  = 'ERR_TEMP'           / Error on T                                     
	# TTYPE7  = 'BETA    '           / Dust emission spectral index                   
	# TTYPE8  = 'ERR_BETA'           / error on Beta  
	ir_map = hp.read_map(map_file, field = 0)
	nside  = hp.get_nside(ir_map)
	res    = hp.nside2resol(nside, arcmin=False)
	dd     = res/deg2rad/2.0

	# OK - Go #
	ebv    = []
	nh     = []
	nhi    = []

	for i in range(0,len(src)):

		# if( i != 15):
		# 	continue

		l  = info['l'][i]
		b  = info['b'][i]

		# Plot cartview a/o mollview #
		ll = l
		if (l>180):
			ll = ll-360.

		# offset = 1.
		hp.cartview(ir_map, title=info['src'][i], coord='G', unit='',
				norm='hist', xsize=800, lonra=[ll-offset-0.1*offset,ll+offset+0.1*offset], latra=[b-offset-0.1*offset,b+offset+0.1*offset],
				return_projected_map=True)

		# hp.mollview(tau_map, title=info['src'][i]+'('+str(info['l'][i])+','+str(info['b'][i])+') - '+map_file,
		# 	coord='G', unit='', rot=[l,b,0], norm='hist', min=1e-7,max=1e-3, xsize=800)

		# Cal. #
		hp.projplot(ll, b, 'bo', lonlat=True, coord='G')
		hp.projtext(ll, b, ' (' + str(round(ll,2)) + ',' + str(round(b,2)) + ')', lonlat=True, coord='G', fontsize=18, weight='bold')

		theta = (90.0-b)*deg2rad
		phi   = l*deg2rad
		pix   = hp.ang2pix(nside, theta, phi, nest=False)

		for x in pl.frange(l-offset, l+offset, dd):
			for y in pl.frange(b-offset, b+offset, dd):
				cosb = np.cos(b*deg2rad)
				cosy = np.cos(y*deg2rad)
				if ( (((x-l)**2 + (y-b)**2) <= offset**2) ):
					# hp.projtext(x, y, '.', lonlat=True, coord='G')
					hp.projplot(x, y, 'kx', lonlat=True, coord='G')

		mpl.rcParams.update({'font.size':30})
		plt.show()
Ejemplo n.º 37
0
def plot_patches(map_file, src_num, info):

	# Define constants #
	deg2rad   = np.pi/180.
	fukui_cf  = 2.10 #2.10e26
	planck_cf = 0.84 #8.40e-27, 0.84e-26

	pl_fact_err = 0.3 #3.0e-27
	fk_fact_err = 0.0 #unknown

	# Define the width of area #
	beam   = 5.0            # Beam = map_resolution = 5'
	dbeam  = beam/120.0     # Beam = 3.5' -> dbeam = beam/60/2 in degree
	offset = dbeam          # degree

	# tau353 map, err_tau353 map and resolution #
	tau_map  = hp.read_map(map_file, field = 0)
	err_map  = hp.read_map(map_file, field = 1)
	nside    = hp.get_nside(tau_map)
	res      = hp.nside2resol(nside, arcmin=False)
	dd       = res/deg2rad/5.0

	# OK - Go #
	tau353 = []
	nh     = []
	nhi    = []

	tau    = {}
	t_err  = {}

	rat_fk = 0.
	rat_pl = 0.

	for i in range(0,src_num):

		# Find the values of Tau353 and Err_tau353 in small area #
		tau[i]   = []
		t_err[i] = []

		l  = info['l'][i]
		b  = info['b'][i]

		# Plot cartview a/o mollview #
		ll = l
		if (l>180):
			ll = ll-360.

		hp.cartview(tau_map, title=info['src'][i]+'('+str(info['l'][i])+','+str(info['b'][i])+') - '+map_file, coord='G', unit='',
				norm='hist', xsize=800, lonra=[ll-offset-0.1*offset,ll+offset+0.1*offset], latra=[b-offset-0.1*offset,b+offset+0.1*offset],
				return_projected_map=True)

		# hp.mollview(tau_map, title=info['src'][i]+'('+str(info['l'][i])+','+str(info['b'][i])+') - '+map_file,
		# 	coord='G', unit='', rot=[l,b,0], norm='hist', min=1e-7,max=1e-3, xsize=800)

		# Cal. #
		theta = (90.0-b)*deg2rad
		phi   = l*deg2rad
		pix   = hp.ang2pix(nside, theta, phi, nest=False)

		if (tau_map[pix] > -1.0e30) : # Some pixels not defined
			tau[i].append(tau_map[pix])

		if (err_map[pix] >= 6.9e-11 and err_map[pix] <= 0.00081): # Checked Invalid error
			t_err[i].append(err_map[pix])

		for x in pl.frange(l-offset, l+offset, dd):
			for y in pl.frange(b-offset, b+offset, dd):
				cosb = np.cos(b*deg2rad)
				cosy = np.cos(y*deg2rad)
				if ( (((x-l)**2 + (y-b)**2) <= offset**2) ):
					# hp.projtext(x, y, '.', lonlat=True, coord='G')
					hp.projplot(x, y, 'kx', lonlat=True, coord='G')

		plt.show()
mw=hp.ud_grade(hp.ma(hp.read_map(flw[1])),512,order_out='Ring')*1000.
m30=hp.ud_grade(hp.ma(hp.read_map(fll[0])),512)*1.e6
m44=hp.ud_grade(hp.ma(hp.read_map(fll[1])),512)*1.e6
m70=hp.ud_grade(hp.ma(hp.read_map(fll[2])),512)*1.e6
m100=hp.ud_grade(hp.ma(hp.read_map(flh[0])),512)*1.e6
m143=hp.ud_grade(hp.ma(hp.read_map(flh[1])),512)*1.e6
m217=hp.ud_grade(hp.ma(hp.read_map(flh[2])),512)*1.e6
mv.mask=mv.mask|psmask|galmask40
mw.mask=mw.mask|psmask|galmask40
m30.mask=m30.mask|psmask|galmask40
m44.mask=m44.mask|psmask|galmask40
m70.mask=m70.mask|psmask|galmask40
m100.mask=m100.mask|psmask|galmask40
m143.mask=m143.mask|psmask|galmask40
m217.mask=m217.mask|psmask|galmask40
hp.cartview(mw-np.mean(mw[sgppix]),cmap=cmap,min=-250,max=250,lonra=[-20,20],latra=[-20,20],rot=[0,-90,0],remove_mono=True,title='WMAP W: SGP $\pm 10 \deg$',unit='$\mu K$')
savefig('/global/u1/p/peterm/plots/map_comparisons/sgp_w.png')
hp.cartview(mv-np.mean(mv[sgppix]),cmap=cmap,min=-250,max=250,lonra=[-20,20],latra=[-20,20],rot=[0,-90,0],remove_mono=True,title='WMAP V: SGP $\pm 10 \deg$',unit='$\mu K$')
savefig('/global/u1/p/peterm/plots/map_comparisons/sgp_v.png')
hp.cartview(m30-np.mean(m30[sgppix]),cmap=cmap,min=-250,max=250,lonra=[-20,20],latra=[-20,20],rot=[0,-90,0],remove_mono=True,title='Planck 30 GHz: SGP $\pm 10 \deg$',unit='$\mu K$')
savefig('/global/u1/p/peterm/plots/map_comparisons/sgp_30.png')
hp.cartview(m44-np.mean(m44[sgppix]),cmap=cmap,min=-250,max=250,lonra=[-20,20],latra=[-20,20],rot=[0,-90,0],remove_mono=True,title='Planck 44 GHz: SGP $\pm 10 \deg$',unit='$\mu K$')
savefig('/global/u1/p/peterm/plots/map_comparisons/sgp_44.png')
hp.cartview(m70-np.mean(m70[sgppix]),cmap=cmap,min=-250,max=250,lonra=[-20,20],latra=[-20,20],rot=[0,-90,0],remove_mono=True,title='Planck 70 GHz: SGP $\pm 10 \deg$',unit='$\mu K$')
savefig('/global/u1/p/peterm/plots/map_comparisons/sgp_70.png')
hp.cartview(m100-np.mean(m100[sgppix]),cmap=cmap,min=-250,max=250,lonra=[-20,20],latra=[-20,20],rot=[0,-90,0],remove_mono=True,title='Planck 100 GHz: SGP $\pm 10 \deg$',unit='$\mu K$')
savefig('/global/u1/p/peterm/plots/map_comparisons/sgp_100.png')
hp.cartview(m143-np.mean(m143[sgppix]),cmap=cmap,min=-250,max=250,lonra=[-20,20],latra=[-20,20],rot=[0,-90,0],remove_mono=True,title='Planck 143 GHz: SGP $\pm 10 \deg$',unit='$\mu K$')
savefig('/global/u1/p/peterm/plots/map_comparisons/sgp_143.png')
hp.cartview(m217-np.mean(m217[sgppix]),cmap=cmap,min=-250,max=250,lonra=[-20,20],latra=[-20,20],rot=[0,-90,0],remove_mono=True,title='Planck 217 GHz: SGP $\pm 10 \deg$',unit='$\mu K$')
savefig('/global/u1/p/peterm/plots/map_comparisons/sgp_217.png')
Ejemplo n.º 39
0
def main(argv):
    '''
    Main function: Takes input parameters, read observability map, 
    select best areas, and show and/or save areas at an output file. 
    Run program with -h for help. 
    '''    

    parser = OptionParser()

    parser.add_option("-i",'--input',
                      help="Input file with masked healpy observability map (output of selectArea.py).",type="string")
    parser.add_option("-m",'--mask',
                      help="Extra mask to be readed (field 0 of output from selectArea.py).",type="string")
    parser.add_option("-f",'--field',default=0,
                      help="Field to be readed from input file. May be 0, 1 or 2, see selectArea.py for info.",type="int")
    parser.add_option("--phi_min",
                      help="Inferior limit on phi as spacial cut (default = 0 graus).",type="float",default=0.)
    parser.add_option("--phi_max",
                      help="Superior limit on phi as spacial cut (default = 180 graus).",type="float",default=180.)
    parser.add_option("--theta_min",
                      help="Inferior limit on theta as spacial cut (default = 0 graus).",type="float",default=-180)
    parser.add_option("--theta_max",
                      help="Superior limit on theta as spacial cut (default = 360).",type="float",default=360.)
    parser.add_option("-o",'--output',
                      help="Output file. ",type="string")
    parser.add_option('--save_mapped',
                      help="Output file for the masked map. Will store a healpy fits file with 1.0 for the marked areas and 0.0 otherwise.",type="string")
    parser.add_option("-s", '--show',action="store_true", default=False,
                      help="Show map before quiting. If no output file is given, then consider show=True.")
    parser.add_option("-c",'--coordinates',
                      help="Coordinates to use on spacial cut. Can be either 'G' (Galactic) or 'E' (Ecliptic). Default is 'G'.",type="string",default='G')
    parser.add_option("-v", '--verbose',action="store_true", dest="verbose", default=False,
                      help="Don't print status messages to stdout")
    
    opt,arg = parser.parse_args(argv)

    if opt.input:
        if opt.verbose:
            print '(M):\n(M): Reading input file {0} ...\n(M):'.format(opt.input)
        obsMap = H.read_map(opt.input,field=opt.field)
    else:
        print '(E):\n(E): Input map not given.\n(E):'
        return -1

    emask = np.zeros(len(obsMap)) == 0
    if opt.mask:
        emask = H.read_map(opt.mask) == 1.
        if opt.verbose:
            print '''(R):
(R): Reading extra mask from {0} (assuming field = 0)... 
(R):'''.format(opt.mask)
        

    nside = H.npix2nside(len(obsMap))

    phi,theta = H.pix2ang(nside,np.arange(len(obsMap)))

    if opt.coordinates == 'E':
        print '''(R):
(R): Using ecliptic coordinates (J2000.). Convertion is made 
(R): elementwise and may take some time.
(R):''',
        sys.stdout.flush()
#        rate = 0.
#        sys.stdout.write('\r(R): {0:8.1f} %'.format(rate*10))
#        sys.stdout.flush()
        phi *= -180./np.pi
        phi += 90.
        theta *= 180./np.pi

        for i in range(len(phi)):
#            if rate != np.floor(i * 10. / len(phi)):
#                rate = np.floor(i * 10. / len(phi))
#                sys.stdout.write('\r(R): {0:8.1f} %'.format(rate*10))
#                sys.stdout.flush()
            phi[i],theta[i] = _skysub.gal2radec(theta[i],phi[i],2000.)

        mask_phi = np.bitwise_and(phi > opt.phi_min , phi < opt.phi_max)
        mask_theta = np.bitwise_and(theta > opt.theta_min ,theta < opt.theta_max )
        print

    else:
        print '''(R):
(R): Using galactic coordinates.
(R):'''
        mask_phi = np.bitwise_and(phi > opt.phi_min * np.pi / 180. , phi < opt.phi_max * np.pi / 180. )
        mask_theta = np.bitwise_and(theta > opt.theta_min * np.pi / 180. ,theta < opt.theta_max * np.pi / 180. )

#    print 'phi_min = {0}\nphi_max = {1}\ntheta_min = {2}\ntheta_max = {3}\n'.format(phi.min(),phi.max(),theta.min(),theta.max())

#    mask = np.bitwise_and(np.bitwise_and(mask_phi,mask_theta),obsMap > 0.)
    mask = np.bitwise_and(np.bitwise_and(mask_phi,mask_theta),emask)

    print '''(R):
(R): Npix_select = {npixs}
(R): Npix_s/Npix_tot = {rnpix}
(R): selected Area = {sarea} square-degree
(R): pixel Area = {parea} square-degree
(R): Avg Observability = {avgobs}
(R):'''.format(npixs = len(obsMap[mask]),
               sarea = len(obsMap[mask])*H.nside2pixarea(nside) * (180. / np.pi)**2.,
               avgobs = np.mean(obsMap[mask]), 
               rnpix = len(obsMap[mask]) * 1.0 / len(obsMap),
               parea = H.nside2pixarea(nside) * (180. / np.pi)**2. )

    obsMap[np.bitwise_not(mask)] = 0.

    if opt.output:

        amask = np.bitwise_and(np.bitwise_and(mask,obsMap == 0.),emask)
        fp = open(opt.output,'a')
        fp.write('{avgtime} {avgarea} {avgobs}\n'.format(avgtime = (opt.phi_max+opt.phi_min) * 0.5,
                                                         avgarea = len(obsMap[amask])*H.nside2pixarea(nside) * (180. / np.pi)**2.,
                                                         avgobs  = np.sum(obsMap[mask]) ) )
        fp.close()

    if opt.save_mapped:
        
        
        H.write_map(opt.save_mapped,obsMap,fits_IDL=False)

    if opt.show:
        #
        #H.cartview(phi,sub=(2,1,1),coord=['G','E'])

        
        amask = np.bitwise_and(mask,emask)
        obsMap[np.bitwise_not(amask)] = 0.
        #obsMap[emask] = 1.
        H.mollview(obsMap,sub=(2,1,1))
        H.cartview(obsMap,coord=['G','E'],sub=(2,1,2))

        py.show()
Ejemplo n.º 40
0
    def superimpose_hpxmap(self, hpx_map, label, color='red', coord_in='C',
                           cbar=True):
        '''Superimpose a Healpix map on the background map.

        Parameters
        ----------
        hpx_map : array-like
            The hpx_map to superimpose upon the background.

        label : string
            The label to put on the colorbar for this footprint.

        color : string or array-like with shape (3,)
            The color to use when overlaying the survey footprint. Either a
            string or rgb triplet.

        coord_in : 'C', 'G', or 'E'
            The coordinate system of the input healpix map.

        Notes
        -----
        The input healpix map will have zeros replaced with NaNs to make
        those points completely transparent.
        '''

        idx_nan = (hpx_map == 0)
        hpx_map /= np.max(hpx_map)
        hpx_map[idx_nan] = np.NaN

        cm1 = util.get_color_map(color)

        coord = [coord_in, self.coord_plot]

        if self.partialmap:
            # Colorbar is added to this and then deleted to make sure there is
            # room at the bottom of the map for the labels. Margins are to make
            # sure the title is not partially off the figure for a square map
            sub = (1, 1, 1)
            margins = (0.01, 0.025, 0.01, 0.03)
            map_tmp = H.cartview(hpx_map, title='',
                                 coord=coord, fig=self.fig.number, cmap=cm1,
                                 notext=True, flip='astro', sub=sub,
                                 margins=margins, return_projected_map=True,
                                 **self.kwds)
            idx = np.isfinite(map_tmp)
            cbar = len(map_tmp[idx]) > 0
        else:
            self.mapview(hpx_map, title='', coord=coord,
                         cbar=True, fig=self.fig.number, cmap=cm1,
                         notext=True, flip='astro', **self.kwds)
        self.fig.delaxes(self.fig.axes[-1])

        if cbar:
            # First add the new colorbar axis to the figure
            im0 = self.fig.axes[-1].get_images()[0]
            box = self.fig.axes[0].get_position()
            ax_color = pl.axes([len(self.cbs), box.y0-0.1, 0.05, 0.05])
            self.fig.colorbar(im0, cax=ax_color, orientation='horizontal',
                              label=label, values=[1, 1])

            self.cbs.append(ax_color)

            # Read just the location of every colorbar
            ncb = len(self.cbs)

            left = 1.0 / (2.0*ncb) - 0.025
            for ax_tmp in self.cbs:
                ax_tmp.set_position([left, box.y0-0.1, 0.05, 0.05])
                left += 1.0 / ncb
Ejemplo n.º 41
0
def make_figure(moll=True, ecliptic=False, footprint=True, idr2=True, cmap='Greys', title='test', highlight=False, highlight_survey='HYDRA', highlight_tile='HYDRA-0011', path='./'):

    alpha = 0.3
    lw = 2

    dust_map = 'data/lambda_sfd_ebv.fits'
    bgmap = H.read_map(os.path.join(path, dust_map))

    if highlight:
        title = highlight_survey + '/' + highlight_tile

    # plot the map projection
    cmap = cm.get_cmap(cmap)
    vmin = np.log10(np.percentile(bgmap, 20))
    vmax = 1+np.log10(np.percentile(bgmap, 99))
    cmap.set_under('w') # Set the color for low out-of-range values when norm.clip = False to white
    if moll:
        cart = H.mollview(np.log10(bgmap), coord=['G', 'C'], cmap=cmap, cbar=False, notext=False, title=title, min=vmin, max=vmax)

        add_numbers_on_axes = 1
        if add_numbers_on_axes == 1:
            dra = -2
            ddec = +1
            H.projtext(  0+dra, 2+ddec,'0h', coord='C', lonlat=True)
            H.projtext( 30+dra, 2+ddec,'2h', coord='C', lonlat=True)
            H.projtext( 60+dra, 2+ddec,'4h', coord='C', lonlat=True)
            H.projtext( 90+dra, 2+ddec,'6h', coord='C', lonlat=True)
            H.projtext(120+dra, 2+ddec,'8h', coord='C', lonlat=True)
            H.projtext(150+dra, 2+ddec,'10h', coord='C', lonlat=True)
            H.projtext(210+dra, 2+ddec,'14h', coord='C', lonlat=True)
            H.projtext(240+dra, 2+ddec,'16h', coord='C', lonlat=True)
            H.projtext(270+dra, 2+ddec,'18h', coord='C', lonlat=True)
            H.projtext(300+dra, 2+ddec,'20h', coord='C', lonlat=True)
            H.projtext(330+dra, 2+ddec,'22h', coord='C', lonlat=True)
            H.projtext(  0+dra,30+ddec,'30', coord='C', lonlat=True)
            H.projtext(  0+dra,60+ddec,'60', coord='C', lonlat=True)
    else:
        cart = H.cartview(np.log10(bgmap), coord=['G', 'C'], cmap=cmap, cbar=False, notext=True, title=title, min=vmin, max=vmax)

    # draw the ecliptic
    if ecliptic:
        ra = np.linspace(-np.pi,np.pi,100)
        dec = np.zeros(100)+(90+23.5*np.sin(ra))*np.pi/180.
        H.projplot(dec,ra,'--', color='k', lw=2.)

    # draw the S-PLUS footprint
    if footprint:
        # read SPLUS pointings file
        splus_tiles_file = os.path.join(path,'data/all_pointings.csv')
        splus_tiles = Table.read(splus_tiles_file, format="csv")
        splus_tiles['obs'] = 0 # add an extra column to mark if the pointing has been observed or not
        tilesize = 1.4 # degrees
        tilecol = ['b','g','r','m']
        color_the_surveys = False
        surveys = ['SPLUS', 'STRIPE82', 'HYDRA', 'MC']
        for s in range(0,len(surveys)):
            if color_the_surveys:
                col = tilecol[s]
            else:
                col = '0.5'
            idx = np.where(splus_tiles['PID'] == surveys[s])
            tiledata = splus_tiles[idx]
            ntiles = len(tiledata)
            coords = SkyCoord(ra=tiledata['RA'], dec=tiledata['DEC'], unit=(u.hourangle,u.degree))
            for j in range(0,ntiles):
                plotEqTile([coords[j].ra.value,coords[j].dec.value],tilesize,col,Tile=True,CenterPoints=False,CornerPoints=False,lw=1)
 
        if highlight:
            idx = (splus_tiles['PID'] == highlight_survey) & (splus_tiles['NAME'] == highlight_tile)
            tiledata = splus_tiles[idx]
            coords = SkyCoord(ra=tiledata['RA'], dec=tiledata['DEC'], unit=(u.hourangle,u.degree))
            lon = coords[0].ra.value
            lat = coords[0].dec.value
            plotEqTile([lon,lat],tilesize,'r',Tile=True,CenterPoints=True,CornerPoints=False,lw=1)

    # draw the observed idr2 footprint
    if idr2:
        # read SPLUS pointings file
        splus_tiles_file = os.path.join(path,'data/all_pointings.csv')
        splus_tiles = Table.read(splus_tiles_file, format="csv")
        splus_tiles_names = np.array(splus_tiles['NAME'])
        # read IDR2 pointings file
        idr2_tiles_file = os.path.join(path,'data/idr2_pointings.csv')
        idr2_tiles = Table.read(idr2_tiles_file, format="csv")
        idr2_tiles_names = np.array(idr2_tiles['FIELD'])
        tilesize = 1.4 # degrees
        for tile in range(0,len(splus_tiles)):
            sel = (idr2_tiles_names == splus_tiles_names[tile])
            if np.sum(sel) > 0:
                tiledata = splus_tiles[tile]
                coords = SkyCoord(ra=tiledata['RA'], dec=tiledata['DEC'], unit=(u.hourangle,u.degree))
                plotEqTile([coords.ra.value,coords.dec.value],tilesize,'g',Tile=True,CenterPoints=False,CornerPoints=False,lw=1)

    H.graticule()   # draw the coordinate system axes

    return 0
Ejemplo n.º 42
0
def almPlots(path, outDir, bundle,
             nside=128, lmax=500, filterband='i',
             raRange=[-50,50], decRange=[-65,5],
             subsetsToConsider=[[130,165], [240, 300]],
             showPlots=True):
    """

    Plot the skymaps/cartview plots corresponding to alms with specified l-ranges. 
    Automatically creates the output directories and saves the plots.

    Required Parameters
    -------------------
      * path: str: path to the main directory where output directory is saved
      * outDir: str: name of the main output directory
      * bundle: metricBundle object.
    
    Optional Parameters
    -------------------
      * nside: int: HEALpix resolution parameter. Default: 128
      * lmax: int: upper limit on the multipole. Default: 500
      * filterBand: str: any one of 'u', 'g', 'r', 'i', 'z', 'y'. Default: 'i'
      * raRange: float array: range of right ascention (in degrees) to consider in cartview plot; only useful when 
                              cartview= True. Default: [-50,50]
      * decRange: float array: range of declination (in degrees) to consider in cartview plot; only useful when 
                               cartview= True. Default: [-65,5]
      * subsetsToConsider: array of int arrays: l-ranges to consider, e.g. use [[50, 100]] to consider 50<l<100.
                                                Currently built to handle five subsets (= number of colors built in).
                                                Default: [[130,165], [240, 300]]
      * showPlots: boolean: set to True if want to show figures. Default: True

    """
    # set up the output directory
    outDir2 = 'almAnalysisPlots_%s<RA<%s_%s<Dec<%s'%(raRange[0], raRange[1], decRange[0], decRange[1])
    if not os.path.exists('%s%s/%s'%(path, outDir, outDir2)):
        os.makedirs('%s%s/%s'%(path, outDir, outDir2))
    
    outDir3 = 'almSkymaps'
    if not os.path.exists('%s%s/%s/%s'%(path, outDir, outDir2, outDir3)):
        os.makedirs('%s%s/%s/%s'%(path, outDir, outDir2, outDir3))
        
    outDir4 = 'almCartviewMaps'
    if not os.path.exists('%s%s/%s/%s'%(path, outDir, outDir2, outDir4)):
        os.makedirs('%s%s/%s/%s'%(path, outDir, outDir2, outDir4))

    # ------------------------------------------------------------------------
    # In order to consider the out-of-survey area as with data=0,  assign the masked region of the
    # skymaps the median of the in-survey data, and then subtract the median off the entire survey.
    # Add the median back later. This gets rid of the massive fake monopole and allows reconstructing
    # the full skymap from components.
    surveyMedianDict = {}
    surveyStdDict = {}
    for dither in bundle:
        inSurvey = np.where(bundle[dither].metricValues.mask == False)[0]
        outSurvey = np.where(bundle[dither].metricValues.mask == True)[0]
        bundle[dither].metricValues.mask[outSurvey] = False
        # data pixels
        surveyMedian = np.median(bundle[dither].metricValues.data[inSurvey])
        surveyStd = np.std(bundle[dither].metricValues.data[inSurvey])
        # assign data[outOfSurvey]= medianData[inSurvey]
        bundle[dither].metricValues.data[outSurvey] = surveyMedian
        # subtract median off
        bundle[dither].metricValues.data[:] = bundle[dither].metricValues.data[:]-surveyMedian 
        # save median for later use
        surveyMedianDict[dither] = surveyMedian
        surveyStdDict[dither] = surveyStd

    # ------------------------------------------------------------------------
    # now find the alms correponding to the map.
    for dither in bundle: 
        array = hp.anafast(bundle[dither].metricValues.filled(bundle[dither].slicer.badval), alm=True, lmax=500)
        cl = array[0]
        alm = array[1]
        l = np.arange(len(cl))

        lsubsets = {}
        colorArray = ['y', 'r', 'g', 'm', 'c']
        color = {}
        for case in range(len(subsetsToConsider)):
            lsubsets[case] = ((l>subsetsToConsider[case][0]) & (l<subsetsToConsider[case][1]))
            color[case] = colorArray[case]

        # ------------------------------------------------------------------------
        # plot things out
        plt.clf()
        plt.plot(l, (cl*l*(l+1))/(2.0*np.pi), color='b')
        for key in list(lsubsets.keys()):
            plt.plot(l[lsubsets[key]], (cl[lsubsets[key]]*l[lsubsets[key]]*(l[lsubsets[key]]+1))/(2.0*np.pi),
                     color=color[key])
        plt.title(dither)
        plt.xlabel('$\ell$')
        plt.ylabel(r'$\ell(\ell+1)C_\ell/(2\pi)$')
        filename = 'cls_%s.png'%(dither)
        plt.savefig('%s%s/%s/%s'%(path, outDir, outDir2, filename), format='png', bbox_inches='tight')

        if showPlots:
            plt.show()
        else:
            plt.close()
            
        surveyMedian = surveyMedianDict[dither]
        surveyStd = surveyStdDict[dither]

        # ------------------------------------------------------------------------
        # plot full-sky-alm plots first
        nTicks = 5
        colorMin = surveyMedian-1.5*surveyStd
        colorMax = surveyMedian+1.5*surveyStd
        increment = (colorMax-colorMin)/float(nTicks)
        ticks = np.arange(colorMin+increment, colorMax, increment)

        # full skymap
        hp.mollview(hp.alm2map(alm, nside=nside, lmax=lmax)+surveyMedian, flip='astro', rot=(0,0,0),
                    min=colorMin, max=colorMax,  title='', cbar=False)
        hp.graticule(dpar=20, dmer=20, verbose=False)
        plt.title('Full Map')
        
        ax = plt.gca()
        im = ax.get_images()[0]

        fig = plt.gcf()
        cbaxes = fig.add_axes([0.1, 0.015, 0.8, 0.04]) # [left, bottom, width, height]
        cb = plt.colorbar(im, orientation='horizontal', format='%.2f',
                          ticks=ticks, cax=cbaxes)
        cb.set_label('$%s$-band Coadded Depth'%filterband)
        filename = 'alm_FullMap_%s.png'%(dither)
        plt.savefig('%s%s/%s/%s/%s'%(path, outDir, outDir2, outDir3, filename),
                    format='png', bbox_inches='tight')

        # full cartview
        hp.cartview(hp.alm2map(alm, nside=nside, lmax=lmax)+surveyMedian,
                    lonra=raRange, latra=decRange, flip='astro',
                    min=colorMin, max=colorMax,  title='', cbar=False)
        hp.graticule(dpar=20, dmer=20, verbose=False)
        plt.title('Full Map')
        ax = plt.gca()
        im = ax.get_images()[0]
        fig= plt.gcf()
        cbaxes = fig.add_axes([0.1, -0.05, 0.8, 0.04]) # [left, bottom, width, height]
        cb = plt.colorbar(im,  orientation='horizontal', format='%.2f',
                          ticks=ticks, cax=cbaxes)
        cb.set_label('$%s$-band Coadded Depth'%filterband)
        filename = 'alm_Cartview_FullMap_%s.png'%(dither)
        plt.savefig('%s%s/%s/%s/%s'%(path, outDir, outDir2, outDir4, filename),
                    format='png', bbox_inches='tight')

        # prepare for the skymaps for l-range subsets
        colorMin = surveyMedian-0.1*surveyStd
        colorMax = surveyMedian+0.1*surveyStd
        increment = (colorMax-colorMin)/float(nTicks)
        increment = 1.15*increment
        ticks = np.arange(colorMin+increment, colorMax, increment)

        # ------------------------------------------------------------------------
        # consider each l-range
        for case in list(lsubsets.keys()):
            index = []
            lowLim = subsetsToConsider[case][0]
            upLim = subsetsToConsider[case][1]
            for ll in np.arange(lowLim, upLim+1):
                for mm in np.arange(0,ll+1):
                    index.append(hp.Alm.getidx(lmax=lmax, l=ll, m=mm))
            alms1 = alm.copy()
            alms1.fill(0)
            alms1[index] = alm[index]     # an unmasked array

            # plot the skymap
            hp.mollview(hp.alm2map(alms1, nside=nside, lmax=lmax)+surveyMedian,
                        flip='astro', rot=(0,0,0), 
                        min=colorMin, max=colorMax, title='', cbar=False)
            hp.graticule(dpar=20, dmer=20, verbose=False)
            plt.title('%s<$\ell$<%s'%(lowLim, upLim))
            ax = plt.gca()
            im = ax.get_images()[0]
            fig= plt.gcf()
            cbaxes = fig.add_axes([0.1, 0.015, 0.8, 0.04]) # [left, bottom, width, height]
            cb = plt.colorbar(im,  orientation='horizontal',format='%.3f',
                              ticks=ticks, cax = cbaxes)             
            cb.set_label('$%s$-band Coadded Depth'%filterband)
            filename = 'almSkymap_%s<l<%s_%s.png'%(lowLim, upLim, dither)
            plt.savefig('%s%s/%s/%s/%s'%(path, outDir, outDir2, outDir3, filename),
                        format='png', bbox_inches='tight')

            # plot cartview
            hp.cartview(hp.alm2map(alms1, nside=nside, lmax=lmax)+surveyMedian,
                        lonra=raRange, latra=decRange, flip='astro',
                        min=colorMin, max=colorMax,  title='',cbar=False)
            hp.graticule(dpar=20, dmer=20, verbose=False)
            plt.title('%s<$\ell$<%s'%(lowLim, upLim))

            ax = plt.gca()
            im = ax.get_images()[0]
            fig= plt.gcf()
            cbaxes = fig.add_axes([0.1, -0.05, 0.8, 0.04]) # [left, bottom, width, height]
            cb = plt.colorbar(im,  orientation='horizontal',format='%.3f',
                              ticks=ticks, cax=cbaxes)
            cb.set_label('$%s$-band Coadded Depth'%filterband)
            filename = 'almCartview_%s<l<%s_%s.png'%(lowLim, upLim, dither)
            plt.savefig('%s%s/%s/%s/%s'%(path, outDir, outDir2, outDir4, filename),
                        format='png', bbox_inches='tight')

        if showPlots:
            plt.show()
        else:
            plt.close('all')
Ejemplo n.º 43
0
def main():
    p = argparse.ArgumentParser(
        description="Plot map with Mercator projection")
    p.add_argument("fitsfile",
                   nargs="*",
                   help="Input HEALPix FITS file. "
                   "To plot the weighted sum of multiple files, put a list of "
                   "file weight file weight pairs.")
    p.add_argument("-a",
                   "--abthresh",
                   default=None,
                   type=float,
                   help="Apply an absolute (lower/upper) threshold to the map")
    p.add_argument("-c",
                   "--coords",
                   default="C",
                   help="C=equatorial (default), G=galactic")
    p.add_argument("-C",
                   "--column",
                   dest="col",
                   default=0,
                   type=int,
                   help="FITS column in which healpix map resides")
    p.add_argument(
        "--file-diff",
        dest="diff",
        default="",
        type=str,
        help=
        "FITS File to take the difference from (optional) otherwise uses positional argument"
    )
    p.add_argument("-D",
                   "--coldiff",
                   default=-1,
                   type=int,
                   help="FITS column in which healpix map to be subtracted "
                   "(if any) resides")
    p.add_argument(
        "--mjd",
        default=None,
        type=float,
        help=
        "MJD of the map. Will be plotted in J2000. Supersedes info in header")
    p.add_argument("-l",
                   "--threshold",
                   type=float,
                   default=None,
                   help="Apply a lower threshold to the plot.")
    p.add_argument(
        "--norm-sqdeg",
        dest="sqdeg",
        action="store_true",
        default=False,
        help="Normalize values to square degree, according to nSides"
        " (makes sense only certain kinds of maps)")
    p.add_argument("--milagro",
                   action="store_true",
                   help="Use Milagro color scale")
    p.add_argument(
        "--contours",
        dest="contours",
        type=float,
        nargs='*',
        default=None,
        help="plot contours. If --contourmap is provided, it will be"
        " used instead of plotted map. If no contours are"
        " provided, it will plot confidence intervals"
        " (1, 2, 3 sigma CI). Else, absolute sigmas are used,"
        " e.g. --contours 1 2 3 4 [sigma] --contours")
    p.add_argument("--contourscolor",
                   nargs='*',
                   default=None,
                   help="Draw options for contours")
    p.add_argument("--contoursstyle",
                   nargs='*',
                   default=None,
                   help="Draw options for contours")
    p.add_argument("--contourswidth",
                   type=float,
                   nargs='*',
                   default=None,
                   help="Draw options for contours")
    p.add_argument("--contourfile",
                   nargs='*',
                   default=None,
                   help="Draw contours from file with RA/Dec pairs")
    p.add_argument("--gamma",
                   action="store_true",
                   help="Use GeV/TeV gamma-ray color scale")
    p.add_argument("-L", "--label", default=None, help="Color bar label")
    p.add_argument("--cross",
                   action="store_true",
                   help="Plot a cross at the center of the plot")
    p.add_argument("--moon",
                   action="store_true",
                   dest="isMoon",
                   help="is in moon centered coordinates")
    p.add_argument("-m",
                   "--min",
                   type=float,
                   default=None,
                   help="Plot minimum value")
    p.add_argument("-M",
                   "--max",
                   type=float,
                   default=None,
                   help="Plot maximum value")
    p.add_argument("-n",
                   "--ncolors",
                   type=int,
                   default=256,
                   help="Number of contours to use in the colormap")
    p.add_argument("--nocolorbar",
                   dest="colorbar",
                   action="store_false",
                   help="Do not draw color bar.")
    p.add_argument("--nofill",
                   action="store_true",
                   help="Do not draw fill plot with colors. "
                   "Useful for contours.")
    p.add_argument(
        "-o",
        "--output",
        default=None,
        help="Output file name (optional). "
        "If file name ends in .fits or .fit, save as a healpix map with the pixels outside the plot area set to hp.UNSEEN."
    )
    p.add_argument("-s",
                   "--scale",
                   type=float,
                   default=1.,
                   help="scale up or down values in map")
    p.add_argument("--sun",
                   action="store_true",
                   dest="isSun",
                   help="is in Sun centered coordinates")
    p.add_argument("--dpar",
                   type=float,
                   default=1.,
                   help="Interval in degrees between parallels")
    p.add_argument("--dmer",
                   type=float,
                   default=1.,
                   help="Interval in degrees between meridians.")
    p.add_argument('--sexagesimal',
                   action='store_true',
                   help='Display RA in hh:mm.')
    p.add_argument("--nogrid",
                   action="store_true",
                   help="Do not plot gridlines.")
    p.add_argument("--interpolation",
                   action='store_true',
                   help="Uses bilinear interpolation in data map.")
    p.add_argument("--xsize",
                   type=int,
                   default=1000,
                   help="Number of X pixels, Y will be scaled acordingly.")
    p.add_argument("-t",
                   "--ticks",
                   nargs="+",
                   type=float,
                   help="List of ticks for color bar, space-separated")
    p.add_argument("-T", "--title", help="title of map")
    p.add_argument("--squareaspect",
                   action='store_true',
                   help="Better Mercator X/Y ratio.")
    p.add_argument("--dpi",
                   type=int,
                   default=300,
                   help="Change the dpi of the output")
    p.add_argument("--preliminary",
                   action="store_true",
                   help="Add a watermark indicating the plot as preliminary")
    p.add_argument("--onlystats",
                   action="store_true",
                   help="Exits after returning min, max and value at center. "
                   "If map is called 'flux', it will give the error if there "
                   "is a map called 'flux_error'")

    # Mutually exclusive option to specify plot xy range OR center + WxH
    argRange = p.add_mutually_exclusive_group(required=False)
    argRange.add_argument("--xyrange",
                          type=float,
                          nargs=4,
                          help="Xmin Xmax Ymin Ymax plot range [degree]")
    argRange.add_argument(
        "--origin",
        type=float,
        nargs=4,
        help="Central (x,y) coords + width + height [degree]")

    # Plot P-Value instead of sigma, expects location and scale of
    # a right-skewed Gumble distribution
    p.add_argument("--gumbel",
                   type=float,
                   nargs=2,
                   help="Plot P-Value instead of significance. "
                   "Arguments: location and scale of right-skewed "
                   "Gumble distribution.")

    # Download/plotting options for Fermi catalog sources
    p.add_argument(
        "--download-fermi",
        dest="dfermi",
        default=None,
        help="Download Fermi FITS data from NASA and exit. Enter version number"
    )
    p.add_argument("--fermicat",
                   default=None,
                   help="Fermi xFGL catalog FITS file name")
    p.add_argument("--fermicat-labels",
                   dest="fermicatLabels",
                   action="store_true",
                   help="Draw Fermi sources with labels.")

    # plotting options for Fermi Healpix file
    p.add_argument("--contourmap",
                   default=None,
                   help="Healpix map from which to grab contours.")
    p.add_argument(
        "--contourmapcoord",
        default="G",
        help=
        "Coordinate system of contourmap. C=equatorial, G=galactic (default)")

    # Download/plotting options for TeVCat sources
    p.add_argument("--download-tevcat",
                   dest="dtevcat",
                   action="store_true",
                   help="Download data from tevcat.uchicago.edu and exit")
    p.add_argument("--tevcat",
                   default=None,
                   help="Draw TeVCat sources using TeVCat ASCII file")
    p.add_argument("--tevcat-labels",
                   dest="tevcatLabels",
                   action="store_true",
                   help="Draw TeVCat sources with labels.")
    p.add_argument("--cat-labels-angle",
                   dest="catLabelsAngle",
                   default=90,
                   help="Oriantation of catalog labels.")
    p.add_argument("--cat-labels-size",
                   dest="catLabelsSize",
                   default=8,
                   help="Size of catalog labels.")

    # Highlight hotspots listed in an ASCII file
    p.add_argument("--hotspots",
                   default=None,
                   help="Hotspot coordinates in an ASCII file")
    p.add_argument("--hotspot-labels",
                   dest="hotspotLabels",
                   action="store_true",
                   help="Draw hotspots sources with labels.")
    # Plot 2D Gaussian fit result listed in an ASCII file from fitMap.py
    p.add_argument("--gaussfit",
                   default=None,
                   help="2D-Gaussian fit result in an ASCII file")

    args = p.parse_args()

    #Sanity checks
    if (args.mjd is not None) and (not canPrecess):
        print("Missing necessary packages to make precession")
        raise SystemExit

    if args.nofill:
        # If we don't fill with colors, we don't plot the colorbar either
        args.colorbar = False

    # Download TeVCat
    if args.dtevcat:
        if haveTeVCat:
            print("Fetching data from tevcat.uchicago.edu.")
            tevcat = TeVCat.TeVCat()
            return None
        else:
            print("Sorry, AERIE TeVCat python module is not available.")
            raise SystemExit

    # Downlaod Fermi catalog
    if args.dfermi:
        if haveFermi:
            print("Fetching 2FGL catalog, version %s" % args.dfermi)
            FGLCatalog.fetch_catalog(args.dfermi)
            return None
        else:
            print("Sorry, AERIE Fermi python module is not available.")
            raise SystemExit

    # Start normal processing
    fitsfile = args.fitsfile
    if fitsfile == []:
        print("Please specify an FITS file to plot.")
        raise SystemExit

    # Fill 2D array
    xmin = -180.
    xmax = 180.
    ymax = 90
    ymin = -90

    if (args.xyrange):
        xmin, xmax, ymin, ymax = args.xyrange
        xC = (xmin + xmax) / 2.
        yC = (ymin + ymax) / 2.
    elif (args.origin):
        xC, yC, w, h = args.origin
        xmin = xC - 0.5 * w
        xmax = xC + 0.5 * w
        ymin = yC - 0.5 * h
        ymax = yC + 0.5 * h
    else:
        print("Using default zoom window. "
              "To customize the zoom window you must specify either "
              "(xyrange) or (origin and width and height).")

    if args.isMoon or args.isSun:
        xmin += 180.
        xmax += 180.

    # Move to range expected by healpy
    while xmin < -180:
        xmin += 360
    while xmin > 180:
        xmin -= 360
    while xmax < -180:
        xmax += 360
    while xmax > 180:
        xmax -= 360

    if xmax < xmin:
        tmax = xmax
        tmin = xmin
        xmin = tmax
        xmax = tmin

    cxmin = xmin
    cxmax = xmax
    frot = 0.
    if xmax > 90. and xmin < -90.:
        frot = 180.
        cxmin = xmax - 180.
        cxmax = xmin + 180.

    if args.origin:
        while xC > 180:
            xC -= 360

    # Read in the skymap and mask out empty pixels
    skymap, skymapHeader = hp.read_map(fitsfile[0], args.col, h=True)
    if len(fitsfile) > 1:
        skymap *= float(fitsfile[1])
    # If fitsfile has more parameters, they should be "mapfile weight" pairs
    for i in range(2, len(fitsfile), 2):
        skymap2 = hp.read_map(fitsfile[i], args.col)
        skymap2 *= float(fitsfile[i + 1])
        skymap += skymap2
    # remove naughty values
    skymap[np.isnan(skymap)] = hp.UNSEEN
    skymap *= args.scale
    nside1 = hp.get_nside(skymap)
    npix = hp.nside2npix(nside1)

    if args.coldiff > -1:
        if os.path.isfile(args.diff):
            print("Taking difference with {0}".format(args.diff))
            skymap2 = hp.read_map(args.diff, args.coldiff)
        else:
            print("No extra file provided, using same file as input")
            skymap2 = hp.read_map(fitsfile[0], args.coldiff)
            if len(fitsfile) > 1:
                skymap2 *= float(fitsfile[1])

        print("Subtracting column {0} from skymap...".format(args.coldiff))
        skymap -= skymap2
        # If fitsfile has more parameters, they should be "mapfile weight" pairs
        for i in range(2, len(fitsfile), 2):
            skymap2 = hp.read_map(fitsfile[i], args.coldiff)
            skymap2 *= float(fitsfile[i + 1])
            skymap -= skymap2

    if (args.gumbel):
        assert haveGumbel
        gumbel_location, gumbel_scale = args.gumbel
        gumbel = gumbel_r(loc=gumbel_location, scale=gumbel_scale)
        skymap = gumbel.logsf(skymap) / log(10)

        def inf_suppressor(x):
            return x if np.isfinite(x) else 0.

        inf_suppressor = np.vectorize(inf_suppressor)
        skymap = inf_suppressor(skymap)

    # Normalize value to square degree
    if args.sqdeg:
        pixsizestr = 4 * np.pi / (12 * nside1**2)
        str2sqdeg = (180 / np.pi)**2
        pixsizesqdeg = pixsizestr * str2sqdeg
        skymap /= pixsizesqdeg

    # I did not find header handler, thats all I came up with...
    toFind = 'TTYPE' + str(args.col + 1)
    #print type(skymapHeader), type(skymapHeader[0]), skymapHeader, toFind, dict(skymapHeader)[toFind]
    skymapName = dict(skymapHeader)[toFind]

    #Check if it is flux
    isFlux = False
    hasFluxError = False
    if skymapName == 'flux':
        isFlux = True

        keyname = dict((v, n) for n, v in skymapHeader).get("flux_error")

        if keyname is not None:
            if keyname.find('TTYPE') == 0 and len(keyname) == 6:
                hasFluxError = True
                fluxerrmap = hp.read_map(fitsfile[0], int(keyname[5]) - 1)

        if not hasFluxError:
            print("Map called 'flux_error' not present, will not print errors")

    isFluxError = False
    if skymapName == "flux_error":
        isFluxError = True

    # Find FOV
    pxls = np.arange(skymap.size)
    nZeroPix = pxls[(skymap != 0)]
    pxTh, pxPh = hp.pix2ang(nside1, pxls)

    # Mask outside FOV
    values = np.ma.masked_where((pxTh > pxTh[nZeroPix].max())
                                | (pxTh < pxTh[nZeroPix].min())
                                | (skymap == hp.UNSEEN)
                                | (skymap == 1e20), skymap)

    # Plot the skymap as an image, setting up the color palette on the way
    mpl.rc("font", size=14, family="serif")
    faspect = abs(cxmax - cxmin) / abs(ymax - ymin)
    fysize = 4
    # Set up the figure frame and coordinate rotation angle
    coords = ["C", "C"]
    gratcoord = "C"
    if args.coords == "G":
        coords = ["C", "G"]
        gratcoord = "G"

    if args.mjd is not None:
        rotMap = precess.mjd2J2000ang(mjd=args.mjd, coord=coords, rot=frot)
        rotVertex = precess.mjd2J2000ang(mjd=args.mjd, coord=coords)
    elif not (args.isMoon or args.isSun):
        mjd = False
        if havePyfits:
            hdulist = pf.open(fitsfile[0])
            header = hdulist[0].header
            if 'EPOCH' in header:
                epoch = header['EPOCH']
                if epoch == 'J2000':
                    pass
                elif epoch == 'current':
                    if 'STARTMJD' in header and 'STOPMJD' in header:
                        startmjd = header['STARTMJD']
                        stopmjd = header['STOPMJD']
                        if (startmjd > 0
                                and stopmjd > 0) or startmjd > stopmjd:
                            mjd = (stopmjd + startmjd) / 2
                        else:
                            print(
                                "STARTMJD/STOPMJD are not well-definned, will not attempt to precess!"
                            )
                    else:
                        print(
                            "STARTMJD or STOPMJD not present in header, will not attempt to precess!"
                        )
                else:
                    print(
                        "Currently EPOCH can be J2000 or current. Will not attempt to precess"
                    )
            else:
                print("Key EPOCH not in header, will not attempt to precess!")

        else:
            print(
                "Pyfits not available -> Can't check map epoch -> Will not attempt to precess!"
            )

        if mjd:
            print(
                "Current epoch detected in header, will precess from MJD%g to J2000"
                % mjd)
            rotMap = precess.mjd2J2000ang(mjd=mjd, coord=coords, rot=frot)
            rotVertex = precess.mjd2J2000ang(mjd=mjd, coord=coords)
        else:
            rotMap = frot
            rotVertex = 0
    else:
        rotMap = frot
        rotVertex = 0

    # Get extrema
    angverts = [[xmin,ymin],[xmax,ymin],\
                [xmax,ymax],[xmin,ymax]]
    vertlist = []
    cRot = hp.Rotator(coord=coords, rot=rotVertex)
    for x, y in angverts:
        ctht, cph = np.deg2rad((y, x))
        ctht = 0.5 * np.pi - ctht
        if cph < 0:
            cph = 2. * np.pi + cph
        vertlist.append(cRot.I(hp.ang2vec(ctht, cph)))

    # Get pixels in image
    imgpix = hp.query_polygon(nside1, vertlist, inclusive=True)

    seenpix = imgpix[values[imgpix] > hp.UNSEEN]

    #if output is fits file: clip input healpy map by setting all pixels outside the plotted area to UNSEEN,
    #then save the result.
    if args.output and (args.output.endswith(".fits")
                        or args.output.endswith(".fit")):
        pix = np.ones(npix, dtype=bool)
        pix[seenpix] = False
        values[pix] = hp.UNSEEN
        print("Saving clipped healpy map to %s" % args.output)
        hp.write_map(args.output,
                     values,
                     partial=True,
                     column_names=[skymapName])
        exit()

    #Get stats
    precRot = hp.Rotator(coord=coords, rot=rotVertex)

    pixMin, pixMax = seenpix[[
        np.argmin(values[seenpix]),
        np.argmax(values[seenpix])
    ]]
    dMin, dMax = values[[pixMin, pixMax]]
    [[thMin, thMax],
     [phMin, phMax]] = np.rad2deg(precRot(hp.pix2ang(nside1,
                                                     [pixMin, pixMax])))

    if args.coords == 'C':
        while phMin < 0:
            phMin += 360

        while phMax < 0:
            phMax += 360

    th0, ph0 = precRot.I((90. - yC) * degree, xC * degree)
    pix0 = hp.ang2pix(nside1, th0, ph0)

    if isFlux:
        if hasFluxError:
            fluxerrMin, fluxerrMax, fluxerr0 = fluxerrmap[[
                pixMin, pixMax, pix0
            ]]
        else:
            fluxerrMin, fluxerrMax, fluxerr0 = [0, 0, 0]

        print("Flux units: TeV^-1 cm^-2 s^-1")
        print("Coord units: deg")
        print("Min:                 %11.2e +/- %11.2e (%6.2f, %5.2f)" %
              (dMin, fluxerrMin, phMin, 90 - thMin))
        print("Max:                 %11.2e +/- %11.2e (%6.2f, %5.2f)" %
              (dMax, fluxerrMax, phMax, 90 - thMax))
        print("Map value at origin: %11.2e +/- %11.2e" %
              (skymap[pix0], fluxerr0))

    elif isFluxError:
        print("Min:                 %5.4e (%6.2f, %5.2f)" %
              (dMin, phMin, 90 - thMin))
        print("Max:                 %5.4e (%6.2f, %5.2f)" %
              (dMax, phMax, 90 - thMax))
        print("Map value at origin: %5.4e" % skymap[pix0])
    else:
        print("Min:                 %5.2f (%6.2f, %5.2f)" %
              (dMin, phMin, 90 - thMin))
        print("Max:                 %5.2f (%6.2f, %5.2f)" %
              (dMax, phMax, 90 - thMax))
        print("Map value at origin: %5.2f" % skymap[pix0])

    if args.onlystats:
        return 0

    figsize = (fysize * faspect + 2, fysize + 2.75)
    fig = plt.figure(num=1, figsize=figsize)

    # Set  min/max value of map
    if args.min is not None:
        dMin = args.min
        values[(skymap < dMin) & (values > hp.UNSEEN)] = dMin
    if args.max is not None:
        dMax = args.max
        values[(skymap > dMax) & (values > hp.UNSEEN)] = dMax

    textcolor, colormap = MapPalette.setupDefaultColormap(args.ncolors)

    # Use the Fermi/HESS/VERITAS purply-red-yellow color map
    if args.gamma:
        textcolor, colormap = MapPalette.setupGammaColormap(args.ncolors)

    # Use the Milagro color map
    if args.milagro:
        dMin = -5
        dMax = 15
        dMin = args.min if args.min != None else -5
        dMax = args.max if args.max != None else 15
        thresh = args.threshold if args.threshold != None else 2.
        textcolor, colormap = \
            MapPalette.setupMilagroColormap(dMin, dMax, thresh, args.ncolors)
        print("Milagro", dMin, dMax, thresh)
    # Use a thresholded grayscale map with colors for extreme values
    else:
        if args.threshold != None:
            textcolor, colormap = \
                MapPalette.setupThresholdColormap(dMin, dMax, args.threshold,
                                                args.ncolors)
        elif args.abthresh != None:
            textcolor, colormap = \
                MapPalette.setupAbsThresholdColormap(dMin, dMax, args.abthresh,
                                                    args.ncolors)

    if args.interpolation:
        cRot = hp.Rotator(rot=rotMap, coord=coords)
        phi = np.linspace(np.deg2rad(xmax), np.deg2rad(xmin), args.xsize)
        if xmin < 0 and xmax > 0 and (xmax - xmin) > 180.:
            phi = np.linspace(
                np.deg2rad(xmin) + 2. * np.pi, np.deg2rad(xmax), args.xsize)
            phi[(phi > 2. * np.pi)] -= 2. * np.pi
        theta = 0.5 * np.pi - np.linspace(np.deg2rad(ymin), np.deg2rad(ymax),
                                          args.xsize / faspect)
        Phi, Theta = np.meshgrid(phi, theta)
        rTheta,rPhi = cRot.I(Theta.reshape(phi.size*theta.size),\
                           Phi.reshape(phi.size*theta.size))
        rotimg = hp.get_interp_val(values, rTheta.reshape(Phi.shape),\
                                           rPhi.reshape(Theta.shape))
    else:
        tfig = plt.figure(num=2, figsize=figsize)
        rotimg = hp.cartview(values, fig=2,coord=coords,title="",\
                            cmap=colormap, cbar=False,\
                            lonra=[cxmin,cxmax],latra=[ymin,ymax],rot=rotMap,
                            notext=True, xsize=args.xsize,
                            return_projected_map=True)
        plt.close(tfig)

    ax = fig.add_subplot(111)
    ax.set_aspect(1.)

    # if plotting contours
    if args.contours != None:
        if args.contourmap:
            contourmap = args.contourmap
            contourmapcoord = args.contourmapcoord
        else:
            contourmap = fitsfile[0]
            contourmapcoord = 'C'

        contourSkyMap, contourSkyMapHeader = hp.read_map(contourmap, h=True)
        fnside1 = hp.get_nside(contourSkyMap)
        ftoFind = 'TTYPE' + str(1)
        contourSkyMapName = dict(contourSkyMapHeader)[ftoFind]
        #<<<<<<< .mine
        #        fvalues = contourSkyMap #np.ma.masked_where(contourSkyMap == 0, contourSkyMap)
        #=======
        #>>>>>>> .r38901
        if args.interpolation:
            cRot = hp.Rotator(rot=rotMap, coord=[contourmapcoord, coords[-1]])
            phi = np.linspace(np.deg2rad(xmax), np.deg2rad(xmin), args.xsize)
            if xmin < 0 and xmax > 0 and (xmax - xmin) > 180.:
                phi = np.linspace(
                    np.deg2rad(xmin) + 2. * np.pi, np.deg2rad(xmax),
                    args.xsize)
                phi[(phi > 2. * np.pi)] -= 2. * np.pi
            theta = 0.5 * np.pi - np.linspace(
                np.deg2rad(ymin), np.deg2rad(ymax), args.xsize / faspect)
            Phi, Theta = np.meshgrid(phi, theta)
            rTheta,rPhi = cRot.I(Theta.reshape(phi.size*theta.size),\
                                Phi.reshape(phi.size*theta.size))
            frotimg = hp.get_interp_val(contourSkyMap,rTheta.reshape(Phi.shape),\
                                        rPhi.reshape(Theta.shape))
        else:
            tfig = plt.figure(num=3, figsize=figsize)
            frotimg = hp.cartview(contourSkyMap,
                                  fig=3,
                                  coord=[contourmapcoord, coords[-1]],
                                  title="",
                                  cmap=colormap,
                                  cbar=False,
                                  lonra=[xmin, xmax],
                                  latra=[ymin, ymax],
                                  rot=rotMap,
                                  notext=True,
                                  xsize=1000,
                                  min=dMin,
                                  max=dMax,
                                  return_projected_map=True)
            plt.close(tfig)

        if args.contours == []:
            rMaxSig2 = (contourSkyMap[imgpix].max())**2
            if rMaxSig2 < 11.83:
                print(
                    "No spot detected with at least a 3sigma confidence contour"
                )
                contours = [-float("inf")]
            else:
                contours = [
                    sqrt(rMaxSig2 - 2.30),
                    sqrt(rMaxSig2 - 6.18),
                    sqrt(rMaxSig2 - 11.83)
                ]
        else:
            contours = args.contours

        ccolor = args.contourscolor or 'g'
        cstyle = args.contoursstyle or '-'
        cwidth = args.contourswidth or 2.
        print('Contours style: ', ccolor, cstyle, cwidth)

        contp = ax.contour(frotimg,
                           levels=np.sort(contours),
                           colors=ccolor,
                           linestyles=cstyle,
                           linewidths=cwidth,
                           origin='upper',
                           extent=[cxmax, cxmin, ymax, ymin])

    rotimg[(rotimg > dMax)] = dMax
    rotimg[(rotimg < dMin)] = dMin
    if not args.nofill:
        imgp = ax.imshow(rotimg,extent=[cxmax, cxmin, ymax, ymin],\
                         vmin=dMin,vmax=dMax,cmap=colormap)

        imgp.get_cmap().set_under('w', alpha=0.)
        imgp.get_cmap().set_over('w', alpha=0.)

    #User defined contour
    if args.contourfile is not None:

        ccolor = args.contourscolor or ['g']
        cstyle = args.contoursstyle or ['-']
        cwidth = args.contourswidth or [2.]

        if len(ccolor) == 1:
            ccolor = np.repeat(ccolor[0], len(args.contourfile))

        if len(cstyle) == 1:
            cstyle = np.repeat(cstyle[0], len(args.contourfile))

        if len(cwidth) == 1:
            cwidth = np.repeat(cwidth[0], len(args.contourfile))

        for i, f in enumerate(args.contourfile):

            ra, dec = np.loadtxt(f, unpack=True)

            if xmax > 90. and xmin < -90.:
                #Map at the discontinuity boundary
                ra -= 180

            ra[ra > 180] -= 360
            ra[ra < -180] += 360

            ax.plot(ra,
                    dec,
                    color=ccolor[i],
                    linestyle=cstyle[i],
                    linewidth=cwidth[i])

    # Draw grid lines
    xts = np.arange(np.floor(xmin), np.ceil(xmax + args.dmer), args.dmer)[1:-1]
    xtlbs = [
        '%g' % (xt + 360) if args.coords == 'C' and xt < 0 else '%g' % xt
        for xt in xts
    ]
    if xmin < 0. and xmax > 0. and (xmax - xmin) > 180.:
        xts = np.arange(np.floor(cxmin), np.ceil(cxmax + args.dmer),
                        args.dmer)[1:-1]
        xtlbs = []
        for xt in xts:
            cval = xt - 180.
            if xt < 0:
                cval = 180. + xt
            if cval == -180:
                cval = 180
            if args.isMoon or args.isSun:
                cval -= 180.
                if cval < -180.:
                    cval += 360.
            elif args.coords == 'C' and cval < 0:
                cval += 360

            xtlbs.append('%g' % (cval))
    yts = np.arange(np.floor(ymin), np.ceil(ymax + args.dpar), args.dpar)[1:-1]

    if args.nogrid == False:
        ax.grid(color=textcolor)
        ax.xaxis.set_ticks(xts)
        ax.xaxis.set_ticklabels(xtlbs)
        ax.yaxis.set_ticks(yts)

    if args.preliminary:
        plt.text((xmin + xmax) / 2.,
                 ymin + 0.85 * (ymax - ymin),
                 "PRELIMINARY",
                 color=textcolor,
                 alpha=0.8,
                 fontdict={
                     "family": "sans-serif",
                     "weight": "bold",
                     "size": 28
                 },
                 horizontalalignment='center')

    # If TeVCat data are available, plot them
    if args.tevcat or args.tevcatLabels:
        if haveTeVCat:
            try:
                if args.tevcat:
                    tevcat = TeVCat.TeVCat(args.tevcat)
                elif args.tevcatLabels:
                    tevcat = TeVCat.TeVCat(args.tevcatLabels)
            except IOError as e:
                print(e)
                print("Downloading data from tevcat.uchicago.edu")
                tevcat = TeVCat.TeVCat()
            except:
                print("Why caught here?")
                print("Downloading data from tevcat.uchicago.edu")
                tevcat = TeVCat.TeVCat()

            cRot = hp.Rotator(coord=["C", coords[-1]])
            tnside = 512
            fpix = np.zeros(hp.nside2npix(tnside))
            for cId in (1, 2):
                catalog = tevcat.GetCatalog(cId)
                ra = catalog.GetRA()
                dec = catalog.GetDec()
                assoc = catalog.GetCanonicalName()
                cut = (assoc != 'Crab Pulsar')
                ra = ra[cut]
                dec = dec[cut]
                assoc = assoc[cut]
                cpix = hp.ang2pix(tnside, np.pi * 0.5 - dec, ra)
                slpx = []
                for sx, px in enumerate(cpix):
                    fpix[px] += 1
                    if fpix[px] != 1:
                        print("%s is a duplicate" % (assoc[sx]))
                        slpx.append(sx)

                ra = np.delete(ra, slpx)
                dec = np.delete(dec, slpx)
                assoc = np.delete(assoc, slpx)
                y, x = cRot(np.pi * 0.5 - dec, ra)
                x = np.rad2deg(x) + frot
                x[(x > 180.)] -= 360.
                y = 90. - np.rad2deg(y)
                cut = (x > xmin) & (x < xmax) & (y > ymin) & (y < ymax)
                x = x[cut]
                y = y[cut]
                assoc = assoc[cut]
                ax.scatter(x,
                           y,
                           color=textcolor,
                           facecolors="none",
                           marker="s")

                if args.tevcatLabels:
                    for r, d, s in zip(x, y, assoc):
                        print(r, d, s)
                        ax.text(r,
                                d,
                                s + '   .',
                                color=textcolor,
                                rotation=args.catLabelsAngle,
                                fontdict={
                                    'family': 'sans-serif',
                                    'size': args.catLabelsSize,
                                    'weight': 'bold'
                                })
        else:
            print("Sorry, TeVCat could not be loaded.")

    # If Fermi data are available, plot them
    if args.fermicat:
        if haveFermi:
            fcat = None
            try:
                fcat = FGLCatalog.FGLCatalog(args.fermicat)
                aflag = fcat.GetAnalysisFlags()
                acut = (aflag == 0)  # cut analysis errors

                flux = fcat.GetFlux1000()  # 1-100 GeV flux
                dflx = fcat.GetFlux1000Error()  # flux uncertainty
                fcut = dflx / flux < 0.5  # cut poorly measured srcs

                cuts = np.logical_and(acut, fcut)
                print('Using FGL')
            except:
                try:
                    fcat = FHLCatalog.FHLCatalog(args.fermicat)
                    cuts = (fcat.GetFlux() > 0.)  # Dummy cut
                    print('Using FHL')
                except:
                    print('Fermi catalog could not be loaded!')
        if fcat != None:
            # Don't show TeV associations if plotting from TeVCat
            if args.tevcat or args.tevcatLabels:
                tcfg = fcat.GetTeVCatFlag()
                tcut = (tcfg == "N") | (tcfg == "C")
                cuts = np.logical_and(cuts, tcut)
            ra = fcat.GetRA()[cuts]
            dec = fcat.GetDec()[cuts]
            assoc = fcat.GetSourceName()[cuts]
            catnms = fcat.GetCatalogName()[cuts]
            for i in xrange(len(assoc)):
                if assoc[i] == '':
                    assoc[i] = catnms[i]

            cRot = hp.Rotator(coord=["C", coords[-1]])
            y, x = cRot(np.pi * 0.5 - dec, ra)
            x = np.rad2deg(x) + frot
            x[(x > 180.)] -= 360.
            y = 90. - np.rad2deg(y)
            cut = (x > xmin) & (x < xmax) & (y > ymin) & (y < ymax)
            x = x[cut]
            y = y[cut]
            assoc = assoc[cut]
            ax.scatter(x, y, color=textcolor, facecolors="none", marker="o")

            if args.fermicatLabels:
                for r, d, s in zip(x, y, assoc):
                    ax.text(r,
                            d,
                            s,
                            color=textcolor,
                            rotation=args.catLabelsAngle,
                            fontdict={
                                'family': 'sans-serif',
                                'size': args.catLabelsSize,
                                'weight': 'bold'
                            })
        else:
            print("Sorry, the Fermi xFGL catalog could not be loaded.")

    # If a hotspot list is given, plot it
    if args.hotspots:
        fhot = open(args.hotspots, "r")
        ra = []
        dec = []
        assoc = []
        for line in fhot:
            if line.startswith("#"):
                continue
            larr = line.strip().split()
            ra.append(float(larr[1]))
            dec.append(float(larr[2]))
            assoc.append(larr[4])

        ra = np.deg2rad(ra)
        dec = np.deg2rad(dec)
        assoc = np.array(assoc)
        cRot = hp.Rotator(coord=["C", coords[-1]])
        y, x = cRot(np.pi * 0.5 - dec, ra)
        x = np.rad2deg(x) + frot
        x[(x > 180.)] -= 360.
        y = 90. - np.rad2deg(y)
        cut = (x > xmin) & (x < xmax) & (y > ymin) & (y < ymax)
        x = x[cut]
        y = y[cut]
        assoc = assoc[cut]
        ax.scatter(x, y, color=textcolor, facecolors="none", marker="o")
        if args.hotspotLabels:
            for r, d, s in zip(x, y, assoc):
                print(r, d, s)
                ax.text(r,
                        d,
                        s + '   .',
                        color=textcolor,
                        rotation=90,
                        fontdict={
                            'family': 'sans-serif',
                            'size': 8,
                            'weight': 'bold'
                        })

    # If a gaussian fit file is given, plot it
    if args.gaussfit:
        gfit = open(args.gaussfit, "r")
        gfit.next()
        gfit.next()
        ra, raErr = [float(i) for i in gfit.next().strip().split()]
        dec, decErr = [float(i) for i in gfit.next().strip().split()]
        raW, raWErr = [float(i) for i in gfit.next().strip().split()]
        decW, decWErr = [float(i) for i in gfit.next().strip().split()]
        gfit.close()

        mrot = -180. if args.isMoon or args.isSun else 0.

        cRot = hp.Rotator(coord=["C", coords[-1]])
        y, x = cRot(np.pi * 0.5 - np.deg2rad(dec), np.deg2rad(ra + mrot))
        x = np.rad2deg(x) + frot
        x = x - 360. if x > 180. else x
        y = 90. - np.rad2deg(y)
        ellip0 = Ellipse((x, y),
                         width=2 * raW,
                         height=2 * decW,
                         edgecolor='black',
                         facecolor='None')
        ax.add_patch(ellip0)
        ax.scatter(x, y, s=20, color='black', facecolors="black", marker="o")

        print(x, y, xmin, xmax, ymin, ymax)
        ax.text(
            x - 1,
            y + 1,
            "%s=%.02f$\pm$%.02f\n$\Delta\delta$=%.02f$\pm$%.02f\n%s=%.02f$\pm$%.02f\n$\sigma_\delta$=%.02f$\pm$%.02f"
            % (r"$\Delta\alpha$", ra, raErr, dec, decErr, r"$\sigma_\alpha$",
               raW, raWErr, decW, decWErr),
            color=textcolor,
            rotation=0,
            fontdict={"size": 12})

    # Set up the color bar
    # Setup color tick marks
    if args.colorbar:
        cticks = args.ticks
        if args.ticks == None:
            if (dMax - dMin) > 3:
                clrmin = np.floor(dMin)
                clrmax = np.ceil(dMax)
                ctspc = np.round((clrmax - clrmin) / 10.)
                if ctspc == 0.:
                    ctspc = 1.
                if clrmin < 0 and clrmax > 0:
                    cticks = -np.arange(0, -clrmin, ctspc)
                    cticks = np.sort(
                        np.unique(
                            np.append(cticks, np.arange(0, clrmax, ctspc))))
                else:
                    cticks = np.arange(clrmin, clrmax + ctspc, ctspc)
            else:
                cticks = None

        cb = fig.colorbar(
            imgp,
            orientation="horizontal",
            shrink=0.85,
            fraction=0.1,
            #aspect=25,
            pad=0.1,
            ax=ax,
            ticks=cticks)

    if args.label:
        skymapName = args.label
    else:
        if re.match("significance", skymapName):
            skymapName = r"significance [$\sigma$]"
    if args.gumbel:
        skymapName = "log10(P-Value)"

    if args.colorbar:
        cb.set_label(skymapName)

    xUnit = " [$^\circ$]"
    if args.sexagesimal:
        xUnit = ""
    yUnit = " [$^\circ$]"

    xlabel = r"$\alpha$%s" % xUnit
    ylabel = r"$\delta$%s" % yUnit

    # Set up the color bar and tick axis
    if args.coords == "G":
        xlabel = r"$l$%s" % xUnit
        ylabel = r"$b$%s" % yUnit
    if args.isMoon or args.isSun:
        xlabel = r"$\Delta\alpha$%s" % xUnit
        ylabel = r"$\Delta\delta$%s" % yUnit

    # X axis label
    ax.set_xlabel(xlabel, color='k')
    # Y axis label
    ax.set_ylabel(ylabel, color='k')

    if args.sexagesimal:
        if haveAstropy:
            # Display RA with hh:mm nonsense.
            ticksLocationsRA = plt.xticks()[0]

            def degrees_to_hhmmss(ra):
                return Angle(ra, u.degree).to_string(unit=u.hour, fields=2)

            ticksLabelsRA = degrees_to_hhmmss(ticksLocationsRA)
            plt.xticks(ticksLocationsRA, ticksLabelsRA)
            # The same with DEC coordinates. Actually no, we never plot less than 1 degree...
            if False:
                ticksLocationsDEC = plt.yticks()[0]

                def degrees_to_ddmmss(dec):
                    return Angle(dec, u.degree).to_string(unit=u.degree,
                                                          fields=2)

                ticksLabelsDEC = degrees_to_ddmmss(ticksLocationsDEC)
                plt.yticks(ticksLocationsDEC, ticksLabelsDEC)
        else:
            print('Error: "--sexagesimal" ignored (needs astropy module)')

    # Title
    if args.title != None:
        ax.set_title(r"{0}".format(args.title.replace("\\n", "\n")), color='k')

    if args.cross:
        # Indicate the center of the plot with a thick black cross
        ax.scatter(xC,
                   yC,
                   s=20**2,
                   marker="+",
                   facecolor="#000000",
                   color="#000000")

    ax.set_ylim(ymin, ymax)
    ax.set_xlim(cxmax, cxmin)
    if args.squareaspect:
        plt.axes().set_aspect(1. / cos((ymax + ymin) / 2 * pi / 180))

    # Either output the image to a file and quit or plot it in a window
    if args.output:
        if not args.nofill:
            fig.savefig(args.output, dpi=args.dpi)
        else:
            fig.savefig(args.output, dpi=args.dpi, transparent=True)
        print("File %s created" % args.output)
    else:
        plt.show()
def Healpix2CartesianMerge(basedir, fname):                        
    # Read from hdf5 file
    f = h5py.File(fname,'r')
    

    output = { 'pi0_brem':['pi0','brem'],
               'ics_all':['ics_cmb','ics_opt','ics_fir'] }



    for k, v in output.items():
        print "Writing", k, v
        
        

        # Get the cartesian maps for each energy
        hpixcube=None
        for t in v:
            print 'Adding template:', t 
            if hpixcube is None:
                hpixcube = f['templates/'+t][()]
            else: 
                hpixcube += f['templates/'+t][()]
        
        cartcube = np.zeros((hpixcube.shape[0], 721,1440), dtype=np.float32)
        for i in range(hpixcube.shape[0]):
            cartcube[i] = healpy.cartview(hpixcube[i], hold=True, return_projected_map=True,
                                                  xsize=1440, lonra=[-179.875, 179.875],flip='geo')
            plt.gcf()
        
        # Generate new hdu object
        hdu_new = pyfits.PrimaryHDU(cartcube.astype(np.float32))
        
        # Copy galdef into header
        galdef = dict(f['/galdef'].attrs.items())
        hdu_new.header.add_comment("Diffuse model generated by Eric Carlson ([email protected])")
        for key, val in galdef.items():
            hdu_new.header.add_comment(key + "=" +val)
        
        hdu_new.header['CRVAL1'] = 0.0
        hdu_new.header['CRPIX1'] = 720
        hdu_new.header['CDELT1'] = 0.25
        hdu_new.header['CUNIT1']= 'deg'
        hdu_new.header['CTYPE1']= 'GLON-CAR'
        hdu_new.header['CRVAL2'] = 0
        hdu_new.header['CRPIX2'] = 361
        hdu_new.header['CDELT2'] = 0.25
        hdu_new.header['CUNIT2']= 'deg'
        hdu_new.header['CTYPE2']= 'GLAT-CAR'
        hdu_new.header['CRVAL3'] = float(galdef['E_gamma_min'])
        hdu_new.header['CRPIX3'] = 0
        hdu_new.header['CDELT3'] = np.log10(float(galdef['E_gamma_factor']))
        hdu_new.header['CTYPE3']= 'Energy'
        hdu_new.header['CUNIT3']= 'MeV'
        hdu_new.header['EXTEND']=True
        hdu_new.header['CREATOR'] = ('Eric Carlson ([email protected])', '')

        # Write energy extension table
        energies = np.array([float(galdef['E_gamma_min'])*float(galdef['E_gamma_factor'])**i for i in range(cartcube.shape[0])])
        tbhdu = pyfits.BinTableHDU.from_columns([
                pyfits.Column(name='Energy', format='D', array=energies),])
        tbhdu.header['EXTNAME']="ENERGIES"
        
        hdulist = pyfits.HDUList([hdu_new,tbhdu])
    
        fname_out = fname.split('.')[0]+"_"+k+"_mapcube.fits"
        hdulist.writeto(basedir+'/'+fname_out,clobber=True)

        # For some reason on my platform, pyfits gzip compression was writing corrupt files.
        p = subprocess.Popen(['gzip -f ' + basedir+'/' +fname_out ,], shell=True)

        print 'File written to ', fname_out
    zgrid[goodind] = NP.sqrt(1.0 - (xgrid[goodind]**2 + ygrid[goodind]**2))

    xvect = xgrid.ravel()
    yvect = ygrid.ravel()
    zvect = zgrid.ravel()
    xyzvect = NP.hstack((xvect.reshape(-1,1), yvect.reshape(-1,1), zvect.reshape(-1,1)))

if use_DSM or use_GSM:
    dsm_file = '/data3/t_nithyanandan/project_MWA/foregrounds/gsmdata_{0:.1f}_MHz_nside_{1:0d}.fits'.format(freq/1e6,nside)
    hdulist = fits.open(dsm_file)
    dsm_table = hdulist[1].data
    ra_deg = dsm_table['RA']
    dec_deg = dsm_table['DEC']
    temperatures = dsm_table['T_{0:.0f}'.format(freq/1e6)]
    fluxes = temperatures
    backdrop = HP.cartview(temperatures.ravel(), coord=['G','E'], rot=[0,0,0], xsize=backdrop_xsize, return_projected_map=True)
elif use_GLEAM or use_SUMSS or use_NVSS or use_CSM:
    if use_GLEAM:
        catalog_file = '/data3/t_nithyanandan/project_MWA/foregrounds/mwacs_b1_131016.csv' # GLEAM catalog
        catdata = ascii.read(catalog_file, data_start=1, delimiter=',')
        dec_deg = catdata['DEJ2000']
        ra_deg = catdata['RAJ2000']
        fpeak = catdata['S150_fit']
        ferr = catdata['e_S150_fit']
        freq_catalog = 1.4 # GHz
        spindex = -0.83 + NP.zeros(fpeak.size)
        fluxes = fpeak * (freq_catalog * 1e9 / freq)**spindex
    elif use_SUMSS:
        SUMSS_file = '/data3/t_nithyanandan/project_MWA/foregrounds/sumsscat.Mar-11-2008.txt'
        catalog = NP.loadtxt(SUMSS_file, usecols=(0,1,2,3,4,5,10,12,13,14,15,16))
        ra_deg = 15.0 * (catalog[:,0] + catalog[:,1]/60.0 + catalog[:,2]/3.6e3)
Ejemplo n.º 46
0
def plotBundleMaps(path,
                   outDir,
                   bundle,
                   dataLabel,
                   filterBand,
                   dataName=None,
                   skymap=True,
                   powerSpectrum=True,
                   cartview=False,
                   raRange=[-180, 180],
                   decRange=[-70, 10],
                   showPlots=True,
                   saveFigs=False,
                   outDirNameForSavedFigs='',
                   lmax=500,
                   nTicks=5,
                   numFormat='%.2f',
                   colorMin=None,
                   colorMax=None):
    """

    Plot maps for the data in a metricBundle object without using MAF routines.

    Required Parameters
    -------------------
      * path: str: path to the main directory where output directory is saved
      * outDir: str: name of the main output directory
      * bundle: metricBundle object.
      * dataLabel: str: data type, e.g. 'counts', 'NumGal'. Will be the label for the colorbar in
                        in skymaps/cartview plots.
      * filterBand: str: filter to consider, e.g. 'r'
    
    Optional Parameters
    -------------------
      * dataName: str: dataLabel analog for filename. e.g. say for datalabel='c$_l$', a good dataName is 'cl'
                       Default: None 
      * skymap: boolean: set to True if want to plot skymaps. Default: True
      * powerSpectrum: boolean: set to True if want to plot powerspectra; dipole is removed. Default: True

      * cartview: boolean: set to True if want to plot cartview plots. Default: Fase
      * raRange: float array: range of right ascention (in degrees) to consider in cartview plot; only useful when 
                              cartview=True. Default: [-180,180]
      * decRange: float array: range of declination (in degrees) to consider in cartview plot; only useful when 
                               cartview=True. Default: [-70,10]

      * showPlots: boolean: set to True if want to show figures. Default: True
      * saveFigs: boolean: set to True if want to save figures. Default: False
      * outDirNameForSavedFigs: str: name for the output directory if saveFigs=True. Default: ''
      * lmax: int: upper limit on the multipole. Default: 500
      * nTicks: int: (number of ticks - 1) on the skymap colorbar. Default: 5
      * numFormat: str: number format for the labels on the colorbar. Default: '%.2f'
      * colorMin: float: lower limit on the colorscale for skymaps. Default: None
      * colorMax: float: upper limit on the colorscale for skymaps. Default: None

    """
    if dataName is None:
        dataName = dataLabel

    if saveFigs:
        # set up the subdirectory
        outDirNew = outDirNameForSavedFigs
        if not os.path.exists('%s%s/%s' % (path, outDir, outDirNew)):
            os.makedirs('%s%s/%s' % (path, outDir, outDirNew))

    if powerSpectrum:
        # plot out the power spectrum
        for dither in bundle:
            plt.clf()
            cl = hp.anafast(hp.remove_dipole(
                bundle[dither].metricValues.filled(
                    bundle[dither].slicer.badval)),
                            lmax=lmax)
            ell = np.arange(len(cl))
            plt.plot(ell, (cl * ell * (ell + 1)) / 2.0 / np.pi)
            plt.title('%s: %s' % (dataLabel, dither))
            plt.xlabel(r'$\ell$')
            plt.ylabel(r'$\ell(\ell+1)C_\ell/(2\pi)$')
            plt.xlim(0, lmax)

            if saveFigs:
                # save power spectrum
                filename = '%s_powerSpectrum_%s.png' % (dataName, dither)
                plt.savefig('%s%s/%s/%s' % (path, outDir, outDirNew, filename),
                            bbox_inches='tight',
                            format='png')
            if showPlots:
                plt.show()
            else:
                plt.close('all')
    if skymap:
        # plot out the skymaps
        for dither in bundle:
            inSurveyIndex = np.where(
                bundle[dither].metricValues.mask == False)[0]
            median = np.median(bundle[dither].metricValues.data[inSurveyIndex])
            stddev = np.std(bundle[dither].metricValues.data[inSurveyIndex])

            if (colorMin == None):
                colorMin = median - 1.5 * stddev
            if (colorMax == None):
                colorMax = median + 1.5 * stddev

            increment = (colorMax - colorMin) / float(nTicks)
            ticks = np.arange(colorMin + increment, colorMax, increment)

            hp.mollview(bundle[dither].metricValues.filled(
                bundle[dither].slicer.badval),
                        flip='astro',
                        rot=(0, 0, 0),
                        min=colorMin,
                        max=colorMax,
                        title='',
                        cbar=False)
            hp.graticule(dpar=20, dmer=20, verbose=False)
            plt.title(dither)
            ax = plt.gca()
            im = ax.get_images()[0]
            fig = plt.gcf()
            cbaxes = fig.add_axes([0.1, 0.03, 0.8,
                                   0.04])  # [left, bottom, width, height]
            cb = plt.colorbar(im,
                              orientation='horizontal',
                              ticks=ticks,
                              format=numFormat,
                              cax=cbaxes)
            cb.set_label(dataLabel)

            if saveFigs:
                # save skymap
                filename = '%s_skymap_%s.png' % (dataName, dither)
                plt.savefig('%s%s/%s/%s' % (path, outDir, outDirNew, filename),
                            bbox_inches='tight',
                            format='png')
            if showPlots:
                plt.show()
            else:
                plt.close('all')

    if cartview:
        # plot out the cartview plots
        for dither in bundle:
            inSurveyIndex = np.where(
                bundle[dither].metricValues.mask == False)[0]
            median = np.median(bundle[dither].metricValues.data[inSurveyIndex])
            stddev = np.std(bundle[dither].metricValues.data[inSurveyIndex])

            if (colorMin == None):
                colorMin = median - 1.5 * stddev
            if (colorMax == None):
                colorMax = median + 1.5 * stddev

            increment = (colorMax - colorMin) / float(nTicks)
            ticks = np.arange(colorMin + increment, colorMax, increment)

            hp.cartview(bundle[dither].metricValues.filled(
                bundle[dither].slicer.badval),
                        flip='astro',
                        rot=(0, 0, 0),
                        lonra=raRange,
                        latra=decRange,
                        min=colorMin,
                        max=colorMax,
                        title='',
                        cbar=False)
            hp.graticule(dpar=20, dmer=20, verbose=False)
            plt.title(dither)
            ax = plt.gca()
            im = ax.get_images()[0]
            fig = plt.gcf()
            cbaxes = fig.add_axes([0.1, 0.25, 0.8,
                                   0.04])  # [left, bottom, width, height]
            cb = plt.colorbar(im,
                              orientation='horizontal',
                              ticks=ticks,
                              format=numFormat,
                              cax=cbaxes)
            cb.set_label(dataLabel)

            if saveFigs:
                # save cartview plot
                filename = '%s_cartview_%s.png' % (dataName, dither)
                plt.savefig('%s%s/%s/%s' % (path, outDir, outDirNew, filename),
                            bbox_inches='tight',
                            format='png')
            if showPlots:
                plt.show()
            else:
                plt.close('all')
Ejemplo n.º 47
0
    moll_array = moll_array / (np.max(moll_array)) * 255.0
    return moll_array


#######

# changing data
t_start = time.time()
for num, path_ in enumerate(all_images):
    if not os.path.exists(destinationPath_data + 'msim_' + tag +
                          '%04i_data.tif' % num) or overwrite:
        image_data = hp.read_map(path_)
        image_data = np.array(image_data, np.float32)
        moll_array = hp.cartview(image_data,
                                 title=None,
                                 xsize=x_size,
                                 ysize=y_size,
                                 return_projected_map=True)
        if mod:
            moll_array = modification(moll_array)
        if norm:
            moll_array = normalization(moll_array)
        if rgb:
            moll_array = toRGB(moll_array)
        moll_image = Image.fromarray(moll_array)
        print('Saving to ' + destinationPath_data + 'msim_' + tag +
              '%04i_data.tif' % num)
        moll_image.save(destinationPath_data + 'msim_' + tag +
                        '%04i_data.tif' % num)

print('Total elapsed time:', time.time() - t_start, 's')
Ejemplo n.º 48
0
plt.grid()
plt.show()

l  = 51.641648
b  = -9.6750019

# Plot cartview a/o mollview #
ll = l
if (l>180):
	ll = ll-360.

offset = 1.
lonr = [51.25, 52.0]
latr = [-10., -9.35]
hp.cartview(ci_map, title='XXX', coord='G', unit='mag', min=0.1,max=0.4,
		norm=None, xsize=800, lonra=lonr, latra=latr, #lonra=[ll-offset,ll+offset], latra=[b-offset,b+offset], min=0, max=0.4,
		return_projected_map=True)

# hp.mollview(tau_map, title=info['src'][i]+'('+str(info['l'][i])+','+str(info['b'][i])+') - '+map_file,
# 	coord='G', unit='', rot=[l,b,0], norm='hist', min=1e-7,max=1e-3, xsize=800)

# Cal. #
hp.projplot(ll, b, 'bo', lonlat=True, coord='G')
hp.projtext(ll, b, ' (' + str(round(ll,2)) + ',' + str(round(b,2)) + ')', lonlat=True, coord='G', fontsize=18, weight='bold')

# theta = (90.0-b)*deg2rad
# phi   = l*deg2rad
# pix   = hp.ang2pix(nside, theta, phi, nest=False)

# for x in pl.frange(l-offset, l+offset, dd):
# 	for y in pl.frange(b-offset, b+offset, dd):
Ejemplo n.º 49
0
    def __init__(self, background, nside=None, fignum=None,
                 projection='mollweide', coord_bg='G', coord_plot='C',
                 partialmap=False, config='footprint.cfg',
                 map_path=None, download_config=False,
                 title='Survey Footprints', cbar=None, min=1.0,
                 max=5000.0, log=True, unit='', **kwds):

        self.fig = pl.figure(fignum)
        self.coord_plot = coord_plot
        self.partialmap = partialmap

        self.kwds = kwds
        self.cbs = []

        if projection == 'mollweide':
            self.mapview = H.mollview
            self.mapcontour = vf.mollcontour
        elif projection == 'cartesian':
            self.mapview = H.cartview
            self.mapcontour = vf.cartcontour
        elif projection == 'orthographic':
            self.mapview = H.orthview
            self.mapcontour = vf.orthcontour
        elif projection == 'gnomonic':
            self.mapview = H.gnomview
            self.mapcontour = vf.gnomcontour

        if map_path is None:
            full_path = inspect.getfile(inspect.currentframe())
            abs_path = os.path.split(full_path)[0]
            map_path = os.path.join(abs_path, 'maps/')

        self.config = ConfigHandler(config, map_path, nside=nside,
                                    download_config=download_config)

        # Could also just call load_survey which will call get_background
        if isinstance(background, str):
            bgmap, coord_bg, unit2 = self.config.load_survey(background,
                                                             get_unit=True)
            background = bgmap[0]
            if unit2 is not None:
                unit = unit2

        if nside is None:
            nside = H.npix2nside(len(background))

        self.nside = nside

        coord = [coord_bg, coord_plot]

        cm.Greys.set_under(alpha=0.0)

        if log:
            min = np.log(min)
            max = np.log(max)
            unit = r'$\log($' + unit + r'$)$'
            background = np.log(background)

        if self.partialmap:
            sub = (1, 1, 1)
            margins = (0.01, 0.025, 0.01, 0.03)
            H.cartview(background, title=title, coord=coord,
                       fig=self.fig.number, cmap=cm.Greys,
                       notext=True, flip='astro', min=min, max=max,
                       sub=sub, margins=margins, **kwds)
            self.fig.delaxes(self.fig.axes[-1])
        else:
            self.mapview(background, title=title,
                         coord=coord, fig=self.fig.number, cmap=cm.Greys,
                         min=min, max=max, notext=True,
                         cbar=True, flip='astro', unit=unit, **kwds)
            if not cbar:
                self.fig.delaxes(self.fig.axes[-1])

        H.graticule(dpar=30.0, dmer=30.0, coord='C', verbose=False)
weightsA = hp.fitsfunc.read_map(
    "/Volumes/DataDavy/Foregrounds/RHT_mask_Equ_ch16_to_24_w75_s15_t70_galfapixcorr_UPSIDEDOWN_plusbgt30cut_plusstarmask_plusHFI_Mask_PointSrc_2048_R2.00_TempPol_allfreqs_RING_apodFWHM15arcmin_zerod.fits"
)

plotmaps = [Q353map, q_bamp1, q_bamp0p01, q_bamp0]
plotmaps = [U353map, u_bamp1, u_bamp0p01, u_bamp0]
plottitles = ["353 raw", "Z=1", "Z=1E-2", "Z=0"]
subnums = [221, 222, 223, 224]

fig = plt.figure()
for i, (plotmap, subnum,
        plottitle) in enumerate(zip(plotmaps, subnums, plottitles)):
    plotmap[weightsA < 0.5] = None
    hp.cartview(plotmap,
                latra=(5, 90),
                lonra=(-30, 110),
                sub=subnum,
                title=plottitle)
# hp.mollview(plotmap, sub=subnum, title=plottitle)

RHT_TQU_Gal_fn = "../data/TQU_RHT_Planck_pol_ang_GALFA_HI_allsky_coadd_chS1004_1043_w75_s15_t70_Gal.fits"
RHT_T_Gal, QRHT, URHT = hp.fitsfunc.read_map(RHT_TQU_Gal_fn, field=(0, 1, 2))

psi_planck_flatprior_fn = maproot + "/psiMB_DR2_SC_241_353GHz_adaptivep0_True_new.fits"
psi_planck_flatprior = hp.fitsfunc.read_map(psi_planck_flatprior_fn)
psi_planck_flatprior_mask = copy.copy(psi_planck_flatprior)
psi_planck_flatprior_mask[weightsA < 0.5] = None

plotmaps = [thetarhtgal_mask, thet353_mask, thet1mmax]
subnums = [131, 132, 133]
plottitles = [r'$\psi_{RHT}$', r'$\psi_{353}$', r'1-R($\psi$) prior']
Ejemplo n.º 51
0
src = info['src']
for i in range(len(src)):
	if( (src[i] != '3C409') ):
		continue

	l  = info['l'][i]
	b  = info['b'][i]

	# Plot cartview a/o mollview #
	ll = l
	if (l>180):
		ll = ll-360.

	hp.cartview(tau_map, title=src[i], coord='G', unit='',
			norm=None, xsize=800, lonra=[ll-offset-0.1*offset,ll+offset+0.1*offset], latra=[b-offset-0.1*offset,b+offset+0.1*offset],
			return_projected_map=True)

	hp.projplot(ll, b, 'bo', lonlat=True, coord='G')
	hp.projtext(ll, b, ' (' + str(round(ll,2)) + ',' + str(round(b,2)) + ')', lonlat=True, coord='G', fontsize=18, weight='bold', color='b')

	# hp.mollview(tau_map, title=info['src'][i]+'('+str(info['l'][i])+','+str(info['b'][i])+') - '+map_file,
	# 	coord='G', unit='', rot=[l,b,0], norm='hist', min=1e-7,max=1e-3, xsize=800)

	# Cal. #
	theta = (90.0-b)*deg2rad
	phi   = l*deg2rad
	pix   = hp.ang2pix(nside, theta, phi, nest=False)

	for x in pl.frange(l-offset, l+offset, dd):
		for y in pl.frange(b-offset, b+offset, dd):
Ejemplo n.º 52
0
def main():
    _path = os.path.dirname(os.path.abspath(__file__))

    file_area = ['data/dcorr_smpas_obstime_15.fits', 'data/lambda_sfd_ebv.fits']

    splus_tilles = os.path.join(_path,'data/splus_tiles.txt')
    sn_tiles_file = os.path.expanduser('~/OneDrive/Documents/Documents/t80s/s-plus/sn2.txt')
    #
    # Reading data
    #

    map_area = np.array([H.read_map(os.path.join(_path, file_area[1])), ])
    pt_splus = np.loadtxt(splus_tilles, unpack=True, usecols=(1, 2))
    sn_tiles = np.loadtxt(sn_tiles_file, unpack=True)

    for i in range(1, len(file_area)):
        map_area = np.append(map_area, np.array([H.read_map(os.path.join(_path, file_area[i])), ]), axis=0)

    #
    # Plotting graph
    #

    # H.cartview(map_area[0], coord=['G', 'E'], cmap=cm.gray_r, cbar=False, notext=True,
    #            title='S-PLUS Survey Area', max=1)

    H.cartview(map_area[0], coord=['G', 'C'], cmap=cm.gray_r, cbar=False, notext=True,
               title='S-PLUS Survey Area', max=1)

    ####################################################################################################################
    # START S-PLUS

    #
    # S-PLUS Southern part
    #

    # for line in np.arange(-5, 1, 0.25):
    #     # dec = np.zeros(100)+(90+20*np.sin(line))*np.pi/180.
    #     H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(35, -35, 100)) * np.pi / 180., '-',
    #                color='b', lw=1, alpha=0.2)
    for line in np.arange(15, 45, 0.25):
        # H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(1, -35, 100)) * np.pi / 180., '-',
        #            color='m', lw=1) #, alpha=0.2)
        H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(60., -60, 100)) * np.pi / 180., '-',
                   color='r', lw=1, alpha=1)

    for line in np.arange(45, 70, 0.25):
        # H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(1, -35, 100)) * np.pi / 180., '-',
        #            color='m', lw=1) #, alpha=0.2)
        H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(70., -70, 100)) * np.pi / 180., '-',
                   color='r', lw=1, alpha=1)

    for line in np.arange(70, 75, 0.25):
        # H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(1, -35, 100)) * np.pi / 180., '-',
        #            color='m', lw=1) #, alpha=0.2)
        H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(70., -90, 100)) * np.pi / 180., '-',
                   color='r', lw=1, alpha=1)

    ######
    # for line in np.arange(15, 35, 0.25):
    #     # H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(1, -35, 100)) * np.pi / 180., '-',
    #     #            color='m', lw=1) #, alpha=0.2)
    #     H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(0., -30, 100)) * np.pi / 180., '-',
    #                color='r', lw=1, alpha=0.2)
    # for line in np.arange(35, 55, 0.25):
    #     # H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(1, -35, 100)) * np.pi / 180., '-',
    #     #            color='m', lw=1) #, alpha=0.2)
    #     H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(0., -60, 100)) * np.pi / 180., '-',
    #                color='r', lw=1, alpha=0.2)
    # for line in np.arange(20, 55, 0.25):
    #     # H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(1, -35, 100)) * np.pi / 180., '-',
    #     #            color='m', lw=1) #, alpha=0.2)
    #     H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(0., 22.5, 100)) * np.pi / 180., '-',
    #                color='r', lw=1, alpha=0.2)
    # for line in np.arange(20, 60, 0.25):
    #     # H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(1, -35, 100)) * np.pi / 180., '-',
    #     #            color='m', lw=1) #, alpha=0.2)
    #     H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(22.5, 60, 100)) * np.pi / 180., '-',
    #                color='r', lw=1, alpha=0.2)
    ######

    # for line in np.arange(15, 60, 0.25):
    #     H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(45, -75, 100)) * np.pi / 180., '-',
    #                color='r', lw=1, alpha=0.2)

    # for line in np.arange(30, 60, 0.25):
    #     H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(40, -60, 100)) * np.pi / 180., '-',
    #                color='r', lw=1, alpha=0.2)

    # for line in np.arange(60, 80, 0.25):
    #     H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(80, -80, 100)) * np.pi / 180., '-',
    #                color='r', lw=1, alpha=0.2)

    # ra = np.linspace(-180*np.pi/180.,-150*np.pi/180.,100.)
    # dec = np.zeros(100)+(90+20*np.sin(ra))*np.pi/180.
    # for line in np.arange(-4.,4.,0.25):
    #     H.projplot(dec+line * np.pi/180.,ra,'-',color='m',lw=2.)
    #
    # ra = np.linspace(150*np.pi/180.,180*np.pi/180.,100.)
    # dec = np.zeros(100)+(90+20*np.sin(ra))*np.pi/180.
    # for line in np.arange(-4.,4.,0.25):
    #     H.projplot(dec+line * np.pi/180.,ra,'-',color='m',lw=2.)

    # for ra in np.linspace(-35 * np.pi / 180.,35 * np.pi / 180.,30.):
    #     dec = (90+20*np.sin(ra))*np.pi/180.
    #     H.projplot(np.array([dec, dec]) - 10. * np.pi / 180. ,[ra, -35 * np.pi /180.]  ,'-',color='r',lw=2.,alpha=0.2)
    # for line in np.arange(dec[0], dec[-1] , 0.25):
    #     H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(-35, 35, 100)) * np.pi / 180., '-',
    #                color='r', lw=1, alpha=0.2)

    # for line in np.arange(30, 45, 0.5):
    #     H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(-60, 91, 100)) * np.pi / 180., '-',
    #                color='r', lw=2, alpha=0.9)
    # for line in np.arange(45, 80, 0.5):
    #     H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(-90, 90, 100)) * np.pi / 180., '-',
    #                color='r', lw=2, alpha=0.9)

    #
    # S-PLUS Northern part
    #
    for line in np.arange(-10, 40, 0.5):
        H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(150, 180, 100)) * np.pi / 180., '-',
                   color='r', lw=2, alpha=1)
        # H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(-157.5, -180, 100)) * np.pi / 180., '-',
        #            color='r', lw=2, alpha=0.2)
    # for line in np.arange(-15, 0, 0.5):
    #     H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(157.5,180, 100)) * np.pi / 180., '-',
    #                color='r', lw=2, alpha=0.9)

    # for line in np.arange(-5., 0, 0.5):
    #     H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(-120,-160, 100)) * np.pi / 180., '-',
    #                color='r', lw=2, alpha=0.2)

    for line in np.arange(-10., 40, 0.5):
        H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(-142.5,-180, 100)) * np.pi / 180., '-',
                   color='r', lw=2, alpha=1)

    # for line in np.arange(30., 40, 0.5):
    #     H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(-165,-120., 100)) * np.pi / 180., '-',
    #                color='r', lw=2, alpha=0.2)

    l_start = [-12,210]
    l_end = [12,260]

    #
    # # brange = [0.5,2,5,8,10,12]
    brange = np.arange(-10, 10)
    #
    for b in brange:
        for il in range(len(l_start)):
            H.projplot(np.zeros(100) + (90.-b) * np.pi / 180.,
                       np.linspace(l_start[il] * np.pi / 180., l_end[il] * np.pi / 180., 100),
                       'g-',lw=2,alpha=1.,coord=['G','E'])

        # H.projplot(np.zeros(100) + (90.-b) * np.pi / 180.,
        #            np.linspace(l_start[0] * np.pi / 180., l_end[0] * np.pi / 180., 100),
        #            'r-',lw=1,alpha=0.8,coord=['G','E'])
        #
        # H.projplot(np.zeros(100) + (90.+b) * np.pi / 180.,
        #            np.linspace(l_start[0] * np.pi / 180., l_end[0] * np.pi / 180., 100),
        #            'r-',lw=1,alpha=0.8,coord=['G','E'])
        #
        # H.projplot(np.zeros(100) + (90.-b) * np.pi / 180.,
        #            np.linspace(l_start[1] * np.pi / 180., l_end[1] * np.pi / 180., 100),
        #            'r-',lw=1,alpha=0.8,coord=['G','E'])
        #
        # H.projplot(np.zeros(100) + (90.+b) * np.pi / 180.,
        #            np.linspace(l_start[1] * np.pi / 180., l_end[1] * np.pi / 180., 100),
        #            'r-',lw=1,alpha=0.8,coord=['G','E'])

    # H.projplot(np.zeros(100) + 85. * np.pi / 180.,
    #            np.linspace(-10. * np.pi / 180., -30. * np.pi / 180., 100),
    #            'r-',lw=2,alpha=0.2,coord=['G','E'])
    #
    # H.projplot(np.zeros(100) + 95. * np.pi / 180.,
    #            np.linspace(-10. * np.pi / 180., -30. * np.pi / 180., 100),
    #            'r-',lw=2,alpha=0.2,coord=['G','E'])
    #
    # H.projplot(np.zeros(100) + 82. * np.pi / 180.,
    #            np.linspace(-10. * np.pi / 180., -30. * np.pi / 180., 100),
    #            'r-',lw=2,alpha=0.2,coord=['G','E'])
    #
    # H.projplot(np.zeros(100) + 98. * np.pi / 180.,
    #            np.linspace(-10. * np.pi / 180., -30. * np.pi / 180., 100),
    #            'r-',lw=2,alpha=0.2,coord=['G','E'])
    #
    # H.projplot(np.zeros(100) + 90. * np.pi / 180.,
    #            np.linspace(210. * np.pi / 180., 230. * np.pi / 180., 100),
    #            'r-',lw=2,alpha=0.2,coord=['G','E'])

    # H.projplot(np.zeros(100) + 92. * np.pi / 180.,
    #            np.linspace(170. * np.pi / 180., 150. * np.pi / 180., 100),
    #            'r-',lw=2,alpha=0.2,coord=['G','E'])

    # H.projplot((90 - sn_tiles[1]) * np.pi / 180., sn_tiles[0] * np.pi / 180., 's', color='r', alpha=0.8,
    #            coord='E')  #,coord=['E','G'])

    H.graticule()
    # py.show()
    #
    # return 0

    # END S-PLUS
    ####################################################################################################################
    # ATLAS

    # for line in np.arange(10, 40, 1.5):
    #     H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(-37.5, 60, 100)) * np.pi / 180., ':',
    #                color='g', lw=2, alpha=0.9)
    # H.projplot((90 - np.zeros(100) + 42) * np.pi / 180., (np.linspace(-37.5, 61, 100)) * np.pi / 180., '-', color='g',
    #            lw=3)
    # H.projplot((90 - np.zeros(100) + 10) * np.pi / 180., (np.linspace(-37.5, 61, 100)) * np.pi / 180., '-', color='g',
    #            lw=2)
    # H.projplot((90 - np.linspace(-40, -10, 100)) * np.pi / 180., (np.zeros(100) + 62) * np.pi / 180., '-', color='g',
    #            lw=3)
    # H.projplot((90 - np.linspace(-40, -10, 100)) * np.pi / 180., (np.zeros(100) - 37.5) * np.pi / 180., '-', color='g',
    #            lw=2)
    #
    # for line in np.arange(2, 29, 1.5):
    #     H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(150, 180, 100)) * np.pi / 180., ':',
    #                color='g', lw=2, alpha=0.9)
    #     if line < 20:
    #         H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(-180, -127.5, 100)) * np.pi / 180., ':',
    #                    color='g', lw=2, alpha=0.9)
    #     else:
    #         H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(-180, -135, 100)) * np.pi / 180., ':',
    #                    color='g', lw=2, alpha=0.9)
    #
    # H.projplot((90 - np.zeros(100) + 29) * np.pi / 180., (np.linspace(150, 180, 100)) * np.pi / 180., '-', color='g',
    #            lw=2)
    # H.projplot((90 - np.zeros(100) + 20) * np.pi / 180., (np.linspace(-135, -127.5, 100)) * np.pi / 180., '-',
    #            color='g', lw=2)
    # H.projplot((90 - np.zeros(100) + 29) * np.pi / 180., (np.linspace(-180, -135., 100)) * np.pi / 180., '-', color='g',
    #            lw=2)
    #
    # H.projplot((90 - np.zeros(100) + 2) * np.pi / 180., (np.linspace(150, 180, 100)) * np.pi / 180., '-', color='g',
    #            lw=2)
    # H.projplot((90 - np.zeros(100) + 2) * np.pi / 180., (np.linspace(-180, -127.5, 100)) * np.pi / 180., '-', color='g',
    #            lw=2)
    #
    # H.projplot((90 - np.linspace(-29, -2, 100)) * np.pi / 180., (np.zeros(100) + 150) * np.pi / 180., '-', color='g',
    #            lw=2)
    # H.projplot((90 - np.linspace(-20, -2, 100)) * np.pi / 180., (np.zeros(100) - 127.5) * np.pi / 180., '-', color='g',
    #            lw=2)
    # H.projplot((90 - np.linspace(-29, -20, 100)) * np.pi / 180., (np.zeros(100) - 135) * np.pi / 180., '-', color='g',
    #            lw=2)
    #
    # # H.projplot((90 - pt_splus[1]) * np.pi / 180., pt_splus[0] * np.pi / 180., 's', color='r', alpha=0.8,
    # #            coord='E')  #,coord=['E','G'])
    #
    # ra = np.linspace(-np.pi,np.pi,100.)
    # dec = np.zeros(100)+(90+20*np.sin(ra))*np.pi/180.
    # H.projplot(dec,ra,'-',color='w',lw=2.)
    # H.projplot(dec,ra,'--',color='k',lw=2.)
    #
    # H.graticule()
    # #
    # # py.savefig(os.path.expanduser('~/Desktop/figure_01.pdf'))
    # #
    # # py.savefig(os.path.expanduser('~/Desktop/figure_01.pdf'))
    # # py.show()
    # #
    # # return 0
    #
    # ####################################################################################################################
    # # Vista
    # #
    # ## VVV Bulge
    # #
    #
    # b = np.append(np.append(np.append(np.linspace(80. * np.pi / 180., 95. * np.pi / 180., 100),
    #                                   np.zeros(100) + 80. * np.pi / 180.),
    #                         np.linspace(80. * np.pi / 180., 95. * np.pi / 180., 100)),
    #               np.zeros(100) + 96. * np.pi / 180.)
    #
    # l = np.append(np.append(np.append(np.zeros(100) + 10. * np.pi / 180.,
    #                                   np.linspace(-10. * np.pi / 180., 10. * np.pi / 180., 100)),
    #                         np.zeros(100) - 10. * np.pi / 180.),
    #               np.linspace(-10. * np.pi / 180., 10. * np.pi / 180., 100))
    # H.projplot(b,l,'-',color="0.5",lw=2,coord=['G','E'])
    #
    # #
    # ## VVV Disk
    # #
    #
    # b = np.append(np.append(np.append(np.linspace(88. * np.pi / 180., 92. * np.pi / 180., 100),
    #                                   np.zeros(100) + 88. * np.pi / 180.),
    #                         np.linspace(88. * np.pi / 180., 92. * np.pi / 180., 100)),
    #               np.zeros(100) + 92. * np.pi / 180.)
    #
    # l = np.append(np.append(np.append(np.zeros(100) - 10. * np.pi / 180.,
    #                                   np.linspace(-10. * np.pi / 180., -65. * np.pi / 180., 100)),
    #                         np.zeros(100) - 65. * np.pi / 180.),
    #               np.linspace(-65. * np.pi / 180., -10. * np.pi / 180., 100))
    # H.projplot(b,l,'-',color="0.5",lw=2,coord=['G','E'])
    #
    #
    # ##################################
    # # VPHAS
    #
    # vb = np.append(np.append(np.append(np.linspace(80. * np.pi / 180., 100. * np.pi / 180., 100),
    #                                   np.zeros(100) + 80. * np.pi / 180.),
    #                         np.linspace(80. * np.pi / 180., 100. * np.pi / 180., 100)),
    #               np.zeros(100) + 100. * np.pi / 180.)
    #
    # vl = np.append(np.append(np.append(np.zeros(100) + 10. * np.pi / 180.,
    #                                   np.linspace(-10. * np.pi / 180., 10. * np.pi / 180., 100)),
    #                         np.zeros(100) - 10. * np.pi / 180.),
    #               np.linspace(-10. * np.pi / 180., 10. * np.pi / 180., 100))
    # # H.projplot(vb,vl,'r-',lw=2,coord=['G','E'])
    #
    # #
    # ## VPHAS Disk
    # #
    #
    # vb = np.append(np.append(np.append(np.linspace(85. * np.pi / 180., 95. * np.pi / 180., 100),
    #                                   np.zeros(100) + 85. * np.pi / 180.),
    #                         np.linspace(85. * np.pi / 180., 95. * np.pi / 180., 100)),
    #               np.zeros(100) + 95. * np.pi / 180.)
    #
    # vl = np.append(np.append(np.append(np.zeros(100) + 40. * np.pi / 180.,
    #                                   np.linspace(40. * np.pi / 180., -160. * np.pi / 180., 100)),
    #                         np.zeros(100) - 160. * np.pi / 180.),
    #               np.linspace(-160. * np.pi / 180., 40. * np.pi / 180., 100))
    # H.projplot(vb,vl,'m-',lw=2,coord=['G','E'])
    #
    # ##################################
    # # Avoiding region
    # vb = np.zeros(100) + 120. * np.pi / 180.
    # vl = np.linspace(0. * np.pi / 180., 360. * np.pi / 180., 100)
    # H.projplot(vb,vl,'w--',lw=2,coord=['G','E'])
    #
    # #
    # ## DECAL
    # #
    # for line in np.arange(-30, 10, 0.5):
    #     H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(120, 240, 100)) * np.pi / 180., ':',
    #                color='k', lw=2, alpha=0.9)
    #
    # for line in np.arange(-30, -15, 0.5):
    #     H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(-30, 40, 100)) * np.pi / 180., ':',
    #                color='k', lw=2, alpha=0.9)
    #
    # for line in np.arange(-15, -1, 0.5):
    #     H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(-45, 40, 100)) * np.pi / 180., ':',
    #                color='k', lw=2, alpha=0.9)
    #
    # for line in np.arange(-10, 10, 0.5):
    #     H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(40, 60, 100)) * np.pi / 180., ':',
    #                color='k', lw=2, alpha=0.9)
    #
    # for line in np.arange(1, 10, 0.5):
    #     H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(-0, -45, 100)) * np.pi / 180., ':',
    #                color='k', lw=2, alpha=0.9)
    #
    # ##
    #
    # a = [0,0,5,5]
    # d = [-3,+3,+3,-3]
    # for d in np.arange(-3,3,0.5):
    #     H.projplot((90 - np.zeros(100) + d) * np.pi / 180., (np.linspace(0, 5, 100)) * np.pi / 180., '-', color='c',
    #            lw=2)
    #
    # # H.projplot((90 + np.linspace(10, 30, 100)) * np.pi / 180., (np.zeros(100) + 61) * np.pi / 180., '-', color='r',
    # #            lw=2)
    # # H.projplot((90 - np.zeros(100) + 30) * np.pi / 180., (np.linspace(60, 90, 100)) * np.pi / 180., '-', color='r',
    # #            lw=2)
    # # H.projplot((90 + np.linspace(30, 80, 100)) * np.pi / 180., (np.zeros(100) + 90) * np.pi / 180., '-', color='r',
    # #            lw=2)
    # # H.projplot((90 - np.zeros(100) + 80) * np.pi / 180., (np.linspace(-90, 90, 100)) * np.pi / 180., '-', color='r',
    # #            lw=2)
    # # H.projplot((90 + np.linspace(45, 80, 100)) * np.pi / 180., (np.zeros(100) - 90) * np.pi / 180., '-', color='r',
    # #            lw=2)
    # # H.projplot((90 - np.zeros(100) + 45) * np.pi / 180., (np.linspace(-90, -60, 100)) * np.pi / 180., '-', color='r',
    # #            lw=2)
    # # H.projplot((90 + np.linspace(10, 45, 100)) * np.pi / 180., (np.zeros(100) -60) * np.pi / 180., '-', color='r',
    # #            lw=2)
    #
    # #
    # # H.projplot((90 - nna_pt[1]) * np.pi / 180., nna_pt[0] * np.pi / 180., '.', color='r', alpha=0.2,
    # #            coord='E')  #,coord=['E','G'])
    # # H.projplot((90 - nsa_pt[1]) * np.pi / 180., nsa_pt[0] * np.pi / 180., '.', color='r', alpha=0.2,
    # #            coord='E')  #,coord=['E','G'])
    # #
    # # H.projplot( (90-pt_kepler[1]) * np.pi/180. , pt_kepler[0] * np.pi /180., '-', color='c', alpha=1.0,
    # #            coord='E',lw=2)  #,coord=['E','G'])
    #
    #
    # # H.projplot((90 - pt_smaps_sul[1]) * np.pi / 180., pt_smaps_sul[0] * np.pi / 180., '.', color='r', alpha=0.2,
    # #            coord='E')  #,coord=['E','G'])
    # # H.projplot((90 - pt_smaps_nor[1]) * np.pi / 180., pt_smaps_nor[0] * np.pi / 180., '.', color='r', alpha=0.8,
    # #            coord='E')  #,coord=['E','G'])
    #
    # # H.projplot((90 - pt_spp[1]) * np.pi / 180., pt_spp[0] * np.pi / 180., 'o',
    # #            color='b', coord='E')  #,coord=['E','G'])
    #
    # #H.projplot((90-pt_smaps_lmc[1])*np.pi/180.,pt_smaps_lmc[0]*np.pi/180.,'.',color='k',alpha=1,coord='E')#,coord=['E','G'])
    # #H.projplot((90-pt_smaps_smc[1])*np.pi/180.,pt_smaps_smc[0]*np.pi/180.,'.',color='k',alpha=1,coord='E')#,coord=['E','G'])
    #
    # H.graticule()
    #
    # # py.show()
    # #
    # # return 0
    #
    # # SPT
    #
    # H.projplot((90 - np.zeros(100) + 65) * np.pi / 180., (np.linspace(-60, 105, 100)) * np.pi / 180., '-', color='b',
    #            lw=2)
    #
    # # for line in np.arange(40, 65, 0.5):
    # #     H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(-60, 105, 100)) * np.pi / 180., '-',
    # #                color='b', lw=2, alpha=0.5)
    # H.projplot((90 - np.zeros(100) + 40) * np.pi / 180., (np.linspace(-60, 105, 100)) * np.pi / 180., '-', color='b',
    #            lw=2)
    # # H.projplot((90 - np.zeros(100) + 40) * np.pi / 180., (np.linspace(-30, 105, 100)) * np.pi / 180., '--', color='b',
    # #            lw=2)
    # # H.projplot((90 - np.zeros(100) + 40) * np.pi / 180., (np.linspace(+60, 105, 100)) * np.pi / 180., '-', color='b',
    # #            lw=2)
    #
    # H.projplot((90 - np.linspace(-65, -40, 100)) * np.pi / 180., (np.zeros(100) - 60) * np.pi / 180., '-', color='b',
    #            lw=2)
    # H.projplot((90 - np.linspace(-65, -40, 100)) * np.pi / 180., (np.zeros(100) + 105) * np.pi / 180., '-', color='b',
    #            lw=2)
    #
    # # VIKING
    # # for line in np.arange(25, 40, 0.5):
    # #     H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(-30, 60, 100)) * np.pi / 180., '-',
    # #                color='b', lw=2, alpha=0.5)
    # H.projplot((90 - np.linspace(-40, -25, 100)) * np.pi / 180., (np.zeros(100) - 30) * np.pi / 180., '-', color='b',
    #            lw=2)
    # H.projplot((90 - np.linspace(-40, -25, 100)) * np.pi / 180., (np.zeros(100) + 60) * np.pi / 180., '-', color='b',
    #            lw=2)
    # H.projplot((90 - np.zeros(100) + 25) * np.pi / 180., (np.linspace(-30, 60, 100)) * np.pi / 180., '-', color='b',
    #            lw=2)
    #
    # # ROUND 82
    # # for line in np.arange(-3, 45, 0.5):
    # #     H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(-25, 3, 100)) * np.pi / 180., '-',
    # #                color='b', lw=2, alpha=0.5)
    # # H.projplot((90 - np.linspace(3, -45, 100)) * np.pi / 180., (np.zeros(100) - 25) * np.pi / 180., '-', color='b',
    # #            lw=2)
    # # H.projplot((90 - np.linspace(3, -45, 100)) * np.pi / 180., (np.zeros(100) + 3) * np.pi / 180., '-', color='b', lw=2)
    # # H.projplot((90 - np.zeros(100) + 45) * np.pi / 180., (np.linspace(-25, 3, 100)) * np.pi / 180., '-', color='b',
    # #            lw=2)
    # # H.projplot((90 - np.zeros(100) - 3) * np.pi / 180., (np.linspace(-25, 3, 100)) * np.pi / 180., '-', color='b', lw=2)
    #
    # H.projplot((90 - np.linspace(3, -25, 100)) * np.pi / 180., (np.zeros(100) + 45) * np.pi / 180., '-', color='b',
    #            lw=2)
    # H.projplot((90 - np.linspace(3, -25, 100)) * np.pi / 180., (np.zeros(100) - 3) * np.pi / 180., '-', color='b', lw=2)
    # H.projplot((90 - np.zeros(100) + 25) * np.pi / 180., (np.linspace(+45, -3, 100)) * np.pi / 180., '-', color='b',
    #            lw=2)
    # H.projplot((90 - np.zeros(100) - 3) * np.pi / 180., (np.linspace(+45, -3, 100)) * np.pi / 180., '-', color='b', lw=2)
    #
    # # STRIPE 82
    # H.projplot((90 - np.linspace(-1, +1, 100)) * np.pi / 180., (np.zeros(100) + 3) * np.pi / 180., '-', color='b', lw=2)
    # H.projplot((90 - np.linspace(-1, +1, 100)) * np.pi / 180., (np.zeros(100) + 43) * np.pi / 180., '-', color='b',
    #            lw=2)
    # H.projplot((90 - np.zeros(100) + 1) * np.pi / 180., (np.linspace(-3, -43, 100)) * np.pi / 180., '-', color='b',
    #            lw=2)
    # H.projplot((90 - np.zeros(100) - 1) * np.pi / 180., (np.linspace(-3, -43, 100)) * np.pi / 180., '-', color='b',
    #            lw=2)
    #
    # # KIDS
    #
    # H.projplot((90 - np.linspace(-5, +5, 100)) * np.pi / 180., (np.zeros(100) - 120) * np.pi / 180., '-', color='y',
    #            lw=2)
    # H.projplot((90 - np.linspace(-5, +5, 100)) * np.pi / 180., (np.zeros(100) - 202.5) * np.pi / 180., '-', color='y',
    #            lw=2)
    #
    # for line in np.arange(-5, 5, 0.5):
    #     H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(-120, -180, 100)) * np.pi / 180., '-',
    #                color='y', lw=2, alpha=0.5)
    #     H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(157, 180, 100)) * np.pi / 180., '-',
    #                color='y', lw=2, alpha=0.5)
    # H.projplot((90 - np.zeros(100) - 5) * np.pi / 180., (np.linspace(157, 180, 100)) * np.pi / 180., '-', color='y',
    #            lw=2)
    # H.projplot((90 - np.zeros(100) + 5) * np.pi / 180., (np.linspace(157, 180, 100)) * np.pi / 180., '-', color='y',
    #            lw=2)
    #
    # H.projplot((90 - np.zeros(100) - 5) * np.pi / 180., (np.linspace(-120, -180, 100)) * np.pi / 180., '-', color='y',
    #            lw=2)
    # H.projplot((90 - np.zeros(100) + 5) * np.pi / 180., (np.linspace(-120, -180, 100)) * np.pi / 180., '-', color='y',
    #            lw=2)
    #
    # H.projplot((90 - np.linspace(-30, -25, 100)) * np.pi / 180., (np.zeros(100) - 30) * np.pi / 180., '-', color='y',
    #            lw=2)
    # H.projplot((90 - np.linspace(-30, -25, 100)) * np.pi / 180., (np.zeros(100) + 53.5) * np.pi / 180., '-', color='y',
    #            lw=2)
    #
    # for line in np.arange(-30, -25, 0.5):
    #     H.projplot((90 - np.zeros(100) - line) * np.pi / 180., (np.linspace(-30.5, 53.5, 100)) * np.pi / 180., '-',
    #                color='y', lw=2, alpha=0.5)
    #
    # H.projplot((90 - np.zeros(100) + 30) * np.pi / 180., (np.linspace(-30, 30, 100)) * np.pi / 180., '-', color='y',
    #            lw=2)
    # H.projplot((90 - np.zeros(100) + 25) * np.pi / 180., (np.linspace(-30, 30, 100)) * np.pi / 180., '-', color='y',
    #            lw=2)
    #
    # #
    # ## GAMMA
    # #
    # # G02  30.2 :  38.8 / -10.25 :  -3.72
    # # G09 129.0 : 141.0 /  -2    :  +3
    # # G12 174.0 : 186.0 /  -3    :  +2
    # # G15 211.5 : 223.5 /  -2    :  +3
    # # G23 339.0 : 351.0 / -35    : -30
    #
    # for line in np.arange(3.72, 10.25, 0.5):
    #     H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(30.2, 38.8, 100)) * np.pi / 180., '-',
    #                color='#66FF33', lw=2, alpha=0.9)
    # for line in np.arange(-3, 2, 0.5):
    #     H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(129., 141., 100)) * np.pi / 180., '-',
    #                color='#66FF33', lw=2, alpha=0.9)
    # for line in np.arange(-2, 3, 0.5):
    #     H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(174, 186, 100)) * np.pi / 180., '-',
    #                color='#66FF33', lw=2, alpha=0.9)
    # for line in np.arange(-3, -2, 0.5):
    #     H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(211.5, 223.5, 100)) * np.pi / 180., '-',
    #                color='#66FF33', lw=2, alpha=0.9)
    # for line in np.arange(30, 35, 0.5):
    #     H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(339, 351, 100)) * np.pi / 180., '-',
    #                color='#66FF33', lw=2, alpha=0.9)
    #
    # #
    # ## VIKING
    # #
    #
    # #SGP:        22h00 < RA < 03h30 ,     -36 < Dec < -26 deg.
    # # H.projplot((90 - np.zeros(100) + 45.) * np.pi / 180., (np.linspace(-36, -26, 100)) * np.pi / 180., '-', color='k',
    # #            lw=2)
    # # H.projplot((90 - np.linspace(-45, 30, 100)) * np.pi / 180., (np.zeros(100) - 36) * np.pi / 180., '-', color='k',
    # #            lw=2)
    # # H.projplot((90 - np.zeros(100) - 30.) * np.pi / 180., (np.linspace(-36, -26, 100)) * np.pi / 180., '-', color='k',
    # #            lw=2)
    # # H.projplot((90 - np.linspace(-45, 30, 100)) * np.pi / 180., (np.zeros(100) - 26) * np.pi / 180., '-', color='k',
    # #            lw=2)
    # # # for line in np.arange(-45, 30, 0.5):
    # # #     H.projplot((90 - np.zeros(100) - line) * np.pi / 180., (np.linspace(-36, -26, 100)) * np.pi / 180., '-',
    # # #                color='k', lw=2, alpha=0.5)
    # # #NGP:        10h00 < RA < 15h30,      -5 < Dec < +4 deg
    # # H.projplot((90 - np.zeros(100) + 150.) * np.pi / 180., (np.linspace(-5, 4, 100)) * np.pi / 180., '-', color='k',
    # #            lw=2)
    # # H.projplot((90 - np.linspace(-150, -232.5, 100)) * np.pi / 180., (np.zeros(100) + 4) * np.pi / 180., '-', color='k',
    # #            lw=2)
    # # H.projplot((90 - np.zeros(100) + 232.5) * np.pi / 180., (np.linspace(-5, +4, 100)) * np.pi / 180., '-', color='k',
    # #            lw=2)
    # # H.projplot((90 - np.linspace(-150, -232.5, 100)) * np.pi / 180., (np.zeros(100) - 5) * np.pi / 180., '-', color='k',
    # #            lw=2)
    # # for line in np.arange(150, 232.5, 0.5):
    # #     H.projplot((90 - np.zeros(100) + line) * np.pi / 180., (np.linspace(-5, +4, 100)) * np.pi / 180., '-',
    # #                color='k', lw=2, alpha=0.5)
    #
    # ####################################################################################################################
    # # Ecliptic
    # #
    #
    # # ra = np.linspace(-np.pi,np.pi,100.)
    # # dec = np.zeros(100)+(90+20*np.sin(ra))*np.pi/180.
    # # H.projplot(dec,ra,'-',color='w',lw=2.)
    # # H.projplot(dec,ra,'--',color='k',lw=2.)

    H.graticule()

    py.savefig(os.path.expanduser('~/Desktop/figure_01.pdf'))

    py.show()
Ejemplo n.º 53
0
def healpy_cartview(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.cartview(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.cartview(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.cartview(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.cartview(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.º 54
0
    def __call__(self, metricValueIn, slicer, userPlotDict, fignum=None, ):

        """
        Plot the sky map of metricValue using healpy cartview plots in thin strips.
        raMin: Minimum RA to plot (deg)
        raMax: Max RA to plot (deg).  Note raMin/raMax define the centers that will be plotted.
        raLen:  Length of the plotted strips in degrees
        decMin: minimum dec value to plot
        decMax: max dec value to plot
        metricValueIn: metric values
        """

        fig = plt.figure(fignum)
        plotDict = {}
        plotDict.update(self.defaultPlotDict)
        plotDict.update(userPlotDict)

        norm = None
        if plotDict['logScale']:
            norm = 'log'
        if plotDict['cmap'] is None:
            cmap = cm.cubehelix
        else:
            cmap = plotDict['cmap']
        if type(cmap) == str:
            cmap = getattr(cm, cmap)
        # Make colormap compatible with healpy
        cmap = colors.LinearSegmentedColormap('cmap', cmap._segmentdata, cmap.N)
        cmap.set_over(cmap(1.0))
        cmap.set_under('w')
        cmap.set_bad('gray')
        if plotDict['zp'] is not None:
            metricValue = metricValueIn - plotDict['zp']
        elif plotDict['normVal'] is not None:
            metricValue = metricValueIn / plotDict['normVal']
        else:
            metricValue = metricValueIn

        if plotDict['percentileClip'] is not None:
            pcMin, pcMax = percentileClipping(metricValue.compressed(),
                                              percentile=plotDict['percentileClip'])
            if plotDict['colorMin'] is None:
                plotDict['colorMin'] = pcMin
            if plotDict['colorMax'] is None:
                plotDict['colorMax'] = pcMax
        if (plotDict['colorMin'] is not None) or (plotDict['colorMax'] is not None):
            clims = [plotDict['colorMin'], plotDict['colorMax']]
        else:
            clims = None

        # Make sure there is some range on the colorbar
        if clims is None:
            if metricValue.compressed().size > 0:
                clims = [metricValue.compressed().min(), metricValue.compressed().max()]
            else:
                clims = [-1, 1]
            if clims[0] == clims[1]:
                clims[0] = clims[0] - 1
                clims[1] = clims[1] + 1
        racenters = np.arange(plotDict['raMin'], plotDict['raMax'], plotDict['raLen'])
        nframes = racenters.size
        for i, racenter in enumerate(racenters):
            if i == 0:
                useTitle = plotDict['title'] + ' /n' + '%i < RA < %i' % (racenter - plotDict['raLen'],
                                                                         racenter + plotDict['raLen'])
            else:
                useTitle = '%i < RA < %i' % (racenter - plotDict['raLen'], racenter + plotDict['raLen'])
            hp.cartview(metricValue.filled(slicer.badval), title=useTitle, cbar=False,
                        min=clims[0], max=clims[1], flip='astro', rot=(racenter, 0, 0),
                        cmap=cmap, norm=norm, lonra=[-plotDict['raLen'], plotDict['raLen']],
                        latra=[plotDict['decMin'], plotDict['decMax']], sub=(nframes + 1, 1, i + 1), fig=fig)
            hp.graticule(dpar=20, dmer=20, verbose=False)
        # Add colorbar (not using healpy default colorbar because want more tickmarks).
        fig = plt.gcf()
        ax1 = fig.add_axes([0.1, .15, .8, .075])  # left, bottom, width, height
        # Add label.
        if plotDict['label'] is not None:
            plt.figtext(0.8, 0.9, '%s' % plotDict['label'])
        # Make the colorbar as a seperate figure,
        # from http: //matplotlib.org/examples/api/colorbar_only.html
        cnorm = colors.Normalize(vmin=clims[0], vmax=clims[1])
        # supress silly colorbar warnings
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            cb1 = mpl.colorbar.ColorbarBase(ax1, cmap=cmap, norm=cnorm,
                                            orientation='horizontal', format=plotDict['cbarFormat'])
            cb1.set_label(plotDict['xlabel'])
            cb1.ax.tick_params(labelsize=plotDict['labelsize'])
        # If outputing to PDF, this fixes the colorbar white stripes
        if plotDict['cbar_edge']:
            cb1.solids.set_edgecolor("face")
        fig = plt.gcf()
        return fig.number
Ejemplo n.º 55
0
plt.grid()
plt.show()

l  = 51.641648
b  = -9.6750019

# Plot cartview a/o mollview #
ll = l
if (l>180):
	ll = ll-360.

offset = 1.
lonr = [51.25, 52.0]
latr = [-10., -9.35]
m    = hp.cartview(ir_map, title='IRIS 100micron', coord='G', unit='MJy/sr', min=0.,max=26.,
		norm=None, xsize=800, lonra=lonr, latra=latr, #lonra=[ll-offset,ll+offset], latra=[b-offset,b+offset],
		return_projected_map=True)

# hp.mollview(tau_map, title=info['src'][i]+'('+str(info['l'][i])+','+str(info['b'][i])+') - '+map_file,
# 	coord='G', unit='', rot=[l,b,0], norm='hist', min=1e-7,max=1e-3, xsize=800)

# Cal. #
hp.projplot(ll, b, 'bo', lonlat=True, coord='G')
hp.projtext(ll, b, ' (' + str(round(ll,2)) + ',' + str(round(b,2)) + ')', lonlat=True, coord='G', fontsize=18, weight='bold')

# theta = (90.0-b)*deg2rad
# phi   = l*deg2rad
# pix   = hp.ang2pix(nside, theta, phi, nest=False)

# for x in pl.frange(l-offset, l+offset, dd):
# 	for y in pl.frange(b-offset, b+offset, dd):
Ejemplo n.º 56
0
    def plotSkyMap(self, metricValueIn, xlabel=None, title='', raMin=-90, raMax=90,
                   raLen=45., decMin=-2., decMax=2.,
                   logScale=False, cbarFormat='%.2f', cmap=cm.jet,
                   percentileClip=None, colorMin=None, colorMax=None,
                   plotMaskedValues=False, zp=None, normVal=None,
                   cbar_edge=True, label=None, fignum=None, **kwargs):
        """
        Plot the sky map of metricValue using healpy cartview plots in thin strips.
        raMin: Minimum RA to plot (deg)
        raMax: Max RA to plot (deg).  Note raMin/raMax define the centers that will be plotted.
        raLen:  Length of the plotted strips in degrees
        decMin: minimum dec value to plot
        decMax: max dec value to plot

        metricValueIn: metric values
        xlabel: units for metric color-bar label
        title: title for plot
        cbarFormat: format for color bar numerals (i.e. '%.2g', etc) (default to matplotlib default)
        plotMaskedValues: ignored, here to be consistent with OpsimFieldSlicer."""
        if fignum:
            fig = plt.figue(fignum)
        else:
            fig=plt.figure()
        norm = None
        if logScale:
            norm = 'log'
        if cmap is None:
            cmap = cm.jet
        if type(cmap) == str:
            cmap = getattr(cm,cmap)
        # Make colormap compatible with healpy
        cmap = colors.LinearSegmentedColormap('cmap', cmap._segmentdata, cmap.N)
        cmap.set_over(cmap(1.0))
        cmap.set_under('w')
        cmap.set_bad('gray')
        if zp:
            metricValue = metricValueIn - zp
        elif normVal:
            metricValue = metricValueIn/normVal
        else:
            metricValue = metricValueIn

        if percentileClip:
            pcMin, pcMax = percentileClipping(metricValue.compressed(), percentile=percentileClip)
        if colorMin is None and percentileClip:
            colorMin = pcMin
        if colorMax is None and percentileClip:
            colorMax = pcMax
        if (colorMin is not None) or (colorMax is not None):
            clims = [colorMin, colorMax]
        else:
            clims = None

        # Make sure there is some range on the colorbar
        if clims is None:
            if metricValue.compressed().size > 0:
                clims=[metricValue.compressed().min(), metricValue.compressed().max()]
            else:
                clims = [-1,1]
            if clims[0] == clims[1]:
                clims[0] =  clims[0]-1
                clims[1] =  clims[1]+1
        racenters=np.arange(raMin,raMax,raLen)
        nframes = racenters.size
        for i, racenter in enumerate(racenters):
            if i == 0:
                useTitle = title +' /n'+'%i < RA < %i'%(racenter-raLen, racenter+raLen)
            else:
                useTitle = '%i < RA < %i'%(racenter-raLen, racenter+raLen)
            hp.cartview(metricValue.filled(self.badval), title=useTitle, cbar=False,
                        min=clims[0], max=clims[1], flip='astro', rot=(racenter,0,0),
                        cmap=cmap, norm=norm, lonra=[-raLen,raLen],
                        latra=[decMin,decMax], sub=(nframes+1,1,i+1), fig=fig)
            hp.graticule(dpar=20, dmer=20, verbose=False)
        # Add colorbar (not using healpy default colorbar because want more tickmarks).
        fig = plt.gcf()
        ax1 = fig.add_axes([0.1, .15,.8,.075]) #left, bottom, width, height
        # Add label.
        if label is not None:
            plt.figtext(0.8, 0.9, '%s' %label)
        # Make the colorbar as a seperate figure,
        # from http://matplotlib.org/examples/api/colorbar_only.html
        cnorm = colors.Normalize(vmin=clims[0], vmax=clims[1])
        # supress silly colorbar warnings
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            cb1 = mpl.colorbar.ColorbarBase(ax1, cmap=cmap, norm=cnorm, orientation='horizontal', format=cbarFormat)
            cb1.set_label(xlabel)
        # If outputing to PDF, this fixes the colorbar white stripes
        if cbar_edge:
            cb1.solids.set_edgecolor("face")
        fig = plt.gcf()
        return fig.number
Ejemplo n.º 57
0
def almPlots(path,
             outDir,
             bundle,
             nside=128,
             lmax=500,
             filterband='i',
             raRange=[-50, 50],
             decRange=[-65, 5],
             subsetsToConsider=[[130, 165], [240, 300]],
             showPlots=True):
    """

    Plot the skymaps/cartview plots corresponding to alms with specified l-ranges. 
    Automatically creates the output directories and saves the plots.

    Required Parameters
    -------------------
      * path: str: path to the main directory where output directory is saved
      * outDir: str: name of the main output directory
      * bundle: metricBundle object.
    
    Optional Parameters
    -------------------
      * nside: int: HEALpix resolution parameter. Default: 128
      * lmax: int: upper limit on the multipole. Default: 500
      * filterBand: str: any one of 'u', 'g', 'r', 'i', 'z', 'y'. Default: 'i'
      * raRange: float array: range of right ascention (in degrees) to consider in cartview plot; only useful when 
                              cartview= True. Default: [-50,50]
      * decRange: float array: range of declination (in degrees) to consider in cartview plot; only useful when 
                               cartview= True. Default: [-65,5]
      * subsetsToConsider: array of int arrays: l-ranges to consider, e.g. use [[50, 100]] to consider 50<l<100.
                                                Currently built to handle five subsets (= number of colors built in).
                                                Default: [[130,165], [240, 300]]
      * showPlots: boolean: set to True if want to show figures. Default: True

    """
    # set up the output directory
    outDir2 = 'almAnalysisPlots_%s<RA<%s_%s<Dec<%s' % (
        raRange[0], raRange[1], decRange[0], decRange[1])
    if not os.path.exists('%s%s/%s' % (path, outDir, outDir2)):
        os.makedirs('%s%s/%s' % (path, outDir, outDir2))

    outDir3 = 'almSkymaps'
    if not os.path.exists('%s%s/%s/%s' % (path, outDir, outDir2, outDir3)):
        os.makedirs('%s%s/%s/%s' % (path, outDir, outDir2, outDir3))

    outDir4 = 'almCartviewMaps'
    if not os.path.exists('%s%s/%s/%s' % (path, outDir, outDir2, outDir4)):
        os.makedirs('%s%s/%s/%s' % (path, outDir, outDir2, outDir4))

    # ------------------------------------------------------------------------
    # In order to consider the out-of-survey area as with data=0,  assign the masked region of the
    # skymaps the median of the in-survey data, and then subtract the median off the entire survey.
    # Add the median back later. This gets rid of the massive fake monopole and allows reconstructing
    # the full skymap from components.
    surveyMedianDict = {}
    surveyStdDict = {}
    for dither in bundle:
        inSurvey = np.where(bundle[dither].metricValues.mask == False)[0]
        outSurvey = np.where(bundle[dither].metricValues.mask == True)[0]
        bundle[dither].metricValues.mask[outSurvey] = False
        # data pixels
        surveyMedian = np.median(bundle[dither].metricValues.data[inSurvey])
        surveyStd = np.std(bundle[dither].metricValues.data[inSurvey])
        # assign data[outOfSurvey]= medianData[inSurvey]
        bundle[dither].metricValues.data[outSurvey] = surveyMedian
        # subtract median off
        bundle[dither].metricValues.data[:] = bundle[
            dither].metricValues.data[:] - surveyMedian
        # save median for later use
        surveyMedianDict[dither] = surveyMedian
        surveyStdDict[dither] = surveyStd

    # ------------------------------------------------------------------------
    # now find the alms correponding to the map.
    for dither in bundle:
        array = hp.anafast(bundle[dither].metricValues.filled(
            bundle[dither].slicer.badval),
                           alm=True,
                           lmax=500)
        cl = array[0]
        alm = array[1]
        l = np.arange(len(cl))

        lsubsets = {}
        colorArray = ['y', 'r', 'g', 'm', 'c']
        color = {}
        for case in range(len(subsetsToConsider)):
            lsubsets[case] = ((l > subsetsToConsider[case][0]) &
                              (l < subsetsToConsider[case][1]))
            color[case] = colorArray[case]

        # ------------------------------------------------------------------------
        # plot things out
        plt.clf()
        plt.plot(l, (cl * l * (l + 1)) / (2.0 * np.pi), color='b')
        for key in list(lsubsets.keys()):
            plt.plot(l[lsubsets[key]],
                     (cl[lsubsets[key]] * l[lsubsets[key]] *
                      (l[lsubsets[key]] + 1)) / (2.0 * np.pi),
                     color=color[key])
        plt.title(dither)
        plt.xlabel('$\ell$')
        plt.ylabel(r'$\ell(\ell+1)C_\ell/(2\pi)$')
        filename = 'cls_%s.png' % (dither)
        plt.savefig('%s%s/%s/%s' % (path, outDir, outDir2, filename),
                    format='png',
                    bbox_inches='tight')

        if showPlots:
            plt.show()
        else:
            plt.close()

        surveyMedian = surveyMedianDict[dither]
        surveyStd = surveyStdDict[dither]

        # ------------------------------------------------------------------------
        # plot full-sky-alm plots first
        nTicks = 5
        colorMin = surveyMedian - 1.5 * surveyStd
        colorMax = surveyMedian + 1.5 * surveyStd
        increment = (colorMax - colorMin) / float(nTicks)
        ticks = np.arange(colorMin + increment, colorMax, increment)

        # full skymap
        hp.mollview(hp.alm2map(alm, nside=nside, lmax=lmax) + surveyMedian,
                    flip='astro',
                    rot=(0, 0, 0),
                    min=colorMin,
                    max=colorMax,
                    title='',
                    cbar=False)
        hp.graticule(dpar=20, dmer=20, verbose=False)
        plt.title('Full Map')

        ax = plt.gca()
        im = ax.get_images()[0]

        fig = plt.gcf()
        cbaxes = fig.add_axes([0.1, 0.015, 0.8,
                               0.04])  # [left, bottom, width, height]
        cb = plt.colorbar(im,
                          orientation='horizontal',
                          format='%.2f',
                          ticks=ticks,
                          cax=cbaxes)
        cb.set_label('$%s$-band Coadded Depth' % filterband)
        filename = 'alm_FullMap_%s.png' % (dither)
        plt.savefig('%s%s/%s/%s/%s' %
                    (path, outDir, outDir2, outDir3, filename),
                    format='png',
                    bbox_inches='tight')

        # full cartview
        hp.cartview(hp.alm2map(alm, nside=nside, lmax=lmax) + surveyMedian,
                    lonra=raRange,
                    latra=decRange,
                    flip='astro',
                    min=colorMin,
                    max=colorMax,
                    title='',
                    cbar=False)
        hp.graticule(dpar=20, dmer=20, verbose=False)
        plt.title('Full Map')
        ax = plt.gca()
        im = ax.get_images()[0]
        fig = plt.gcf()
        cbaxes = fig.add_axes([0.1, -0.05, 0.8,
                               0.04])  # [left, bottom, width, height]
        cb = plt.colorbar(im,
                          orientation='horizontal',
                          format='%.2f',
                          ticks=ticks,
                          cax=cbaxes)
        cb.set_label('$%s$-band Coadded Depth' % filterband)
        filename = 'alm_Cartview_FullMap_%s.png' % (dither)
        plt.savefig('%s%s/%s/%s/%s' %
                    (path, outDir, outDir2, outDir4, filename),
                    format='png',
                    bbox_inches='tight')

        # prepare for the skymaps for l-range subsets
        colorMin = surveyMedian - 0.1 * surveyStd
        colorMax = surveyMedian + 0.1 * surveyStd
        increment = (colorMax - colorMin) / float(nTicks)
        increment = 1.15 * increment
        ticks = np.arange(colorMin + increment, colorMax, increment)

        # ------------------------------------------------------------------------
        # consider each l-range
        for case in list(lsubsets.keys()):
            index = []
            lowLim = subsetsToConsider[case][0]
            upLim = subsetsToConsider[case][1]
            for ll in np.arange(lowLim, upLim + 1):
                for mm in np.arange(0, ll + 1):
                    index.append(hp.Alm.getidx(lmax=lmax, l=ll, m=mm))
            alms1 = alm.copy()
            alms1.fill(0)
            alms1[index] = alm[index]  # an unmasked array

            # plot the skymap
            hp.mollview(hp.alm2map(alms1, nside=nside, lmax=lmax) +
                        surveyMedian,
                        flip='astro',
                        rot=(0, 0, 0),
                        min=colorMin,
                        max=colorMax,
                        title='',
                        cbar=False)
            hp.graticule(dpar=20, dmer=20, verbose=False)
            plt.title('%s<$\ell$<%s' % (lowLim, upLim))
            ax = plt.gca()
            im = ax.get_images()[0]
            fig = plt.gcf()
            cbaxes = fig.add_axes([0.1, 0.015, 0.8,
                                   0.04])  # [left, bottom, width, height]
            cb = plt.colorbar(im,
                              orientation='horizontal',
                              format='%.3f',
                              ticks=ticks,
                              cax=cbaxes)
            cb.set_label('$%s$-band Coadded Depth' % filterband)
            filename = 'almSkymap_%s<l<%s_%s.png' % (lowLim, upLim, dither)
            plt.savefig('%s%s/%s/%s/%s' %
                        (path, outDir, outDir2, outDir3, filename),
                        format='png',
                        bbox_inches='tight')

            # plot cartview
            hp.cartview(hp.alm2map(alms1, nside=nside, lmax=lmax) +
                        surveyMedian,
                        lonra=raRange,
                        latra=decRange,
                        flip='astro',
                        min=colorMin,
                        max=colorMax,
                        title='',
                        cbar=False)
            hp.graticule(dpar=20, dmer=20, verbose=False)
            plt.title('%s<$\ell$<%s' % (lowLim, upLim))

            ax = plt.gca()
            im = ax.get_images()[0]
            fig = plt.gcf()
            cbaxes = fig.add_axes([0.1, -0.05, 0.8,
                                   0.04])  # [left, bottom, width, height]
            cb = plt.colorbar(im,
                              orientation='horizontal',
                              format='%.3f',
                              ticks=ticks,
                              cax=cbaxes)
            cb.set_label('$%s$-band Coadded Depth' % filterband)
            filename = 'almCartview_%s<l<%s_%s.png' % (lowLim, upLim, dither)
            plt.savefig('%s%s/%s/%s/%s' %
                        (path, outDir, outDir2, outDir4, filename),
                        format='png',
                        bbox_inches='tight')

        if showPlots:
            plt.show()
        else:
            plt.close('all')
def plot_Total_Sky_Halos_Surface_Brightness(Halo_data,Input_Para,Output_Para):

    from XCat_Objects               import DtoR, RtoD
    rc('font',family='serif')
    fdir  = './Output/plots/HEALPixSurfaceBrightness/'

    nside = Output_Para.nside

    Sl_n  = len(Halo_data)

    from XCat_Objects               import Halo_Brightness_Surface_Sample_Object

    for k in range(Sl_n):

      pix     = zeros(12*nside**2)

      if (len(Halo_data[k].RA[:]) == 0):
         pass 
      else:
         for halo_n in range(len(Halo_data[k].RA[:])):
            Halo_Sample     = Halo_Brightness_Surface_Sample_Object(Halo_data[k],Input_Para,Output_Para,halo_n)
            for i in range(len(Halo_Sample.sRA[:])):
               j    = hp.ang2pix(nside,DtoR*(90.0-Halo_Sample.sDEC[i]),DtoR*(Halo_Sample.sRA[i]))
               pix[j] += Halo_Sample.sSB[i]
         if (Output_Para.log_scale):
            pix_min = max(pix[:])/10.0**4
            pix = log10((pix+pix_min)*4.0*pi/(12.0*nside**2))
         else:
            pix = pix/(12.0*nside**2)
         plt.clf()
         if (Output_Para.HEALpix_cart):
            hp.cartview(pix, fig = 1)           
         else:
            hp.mollview(pix, fig = 1)
         if (Output_Para.HEALpix_grat):
            hp.graticule()
         plt.show()
         plt.close()

         save_ques = Read_YN_Input("Do you want to save the plot (please enter Y, y, N, or n)? ")
         if save_ques :
           rc('text',usetex=True)
           plt.clf()
           if (Output_Para.HEALpix_cart):
              hp.cartview(pix, fig = 1)           
           else:
              hp.mollview(pix, fig = 1)
           if (Output_Para.HEALpix_grat):
              hp.graticule()
           if (Output_Para.log_scale):
              fname = 'Full_Sky_Surface_Brightness_Profile_log_%i_%i.pdf'%(nside,(k+1))
           else:
              fname = 'Full_Sky_Surface_Brightness_Profile_%i_%i.pdf'%(nside,(k+1))
           plt.title(r'Surface Brightness Profile at redshift between %0.3f and %0.3f'%(Halo_data[k].z_min,Halo_data[k].z_max),fontsize = 20)
           print 'Saving plot', fname
#         savefig(fdir+fname,bbox_inches='tight')
           plt.savefig(fdir+fname)
           rc('text',usetex=False)
           plt.close()

         save_ques = Read_YN_Input("Do you want to save the map data (please enter Y, y, N, or n)? ")
         if save_ques :
           if (Output_Para.log_scale):
              fname = 'Full_Sky_Surface_Brightness_Profile_log_HEALPix_map_%i_%i.txt'%(nside,(k+1))
           else:
              fname = 'Full_Sky_Surface_Brightness_Profile_HEALPix_map_%i_%i.txt'%(nside,(k+1))
           print 'Saving data', fname
           f = open(fdir+fname,'w')
           f.write("#   Pix_Value \n")
           savetxt(f, array([pix]).T)
           f.close()