Exemple #1
0
    def create_spt_area(self):
        
        num_ra = 1000
        num_dec = 200

        ra = np.arange(num_ra, dtype=np.float32)/num_ra * (360.0+105 - 300) + 300.0
        ip = np.where(ra > 360.0)
        ra[ip] = ra[ip] - 360.00

        dec = 90.0 - (np.arange(num_dec, dtype=np.float32)/num_dec * (65.0 - 40.00) - 65.0)

        ra[:] = ra[:] * np.pi/180.0
        dec[:] = dec[:] * np.pi/180.0

        ra_list = []
        dec_list = []
        for i in np.arange(num_ra):
            ra_list.append( ra[i] )
            dec_list.append( dec[0] )

        for i in np.arange(num_dec):
            ra_list.append( ra[num_ra-1] )
            dec_list.append( dec[i] )

        for i in np.arange(num_ra):
            ra_list.append( ra[num_ra-1-i] )
            dec_list.append( dec[num_dec-1] )

        for i in np.arange(num_dec):
            ra_list.append( ra[0] )
            dec_list.append( dec[num_dec-1-i] )

        hp.projplot(dec_list, ra_list, 'k')
Exemple #2
0
def plotArea(area_x,area_y):
    for i in range(len(area_x)):
        if len(area_x[i]) > 1:
            x1 = np.linspace(area_x[i][0],area_x[i][1], 100) #np.arange(-100,110,10)
        else:
            x1 = np.zeros(100)+area_x[i]

        if len(area_y[i]) > 1:
            y1 = np.linspace(area_y[i][0],area_y[i][1], 100) #np.arange(-100,110,10)
        else:
            y1 = np.zeros(100)+area_y[i]

        H.projplot((90.-x1)*np.pi/180.,y1*np.pi/180.,'g',lw=2.)#,rot=(0,-90,90),coord=['G','E'])
Exemple #3
0
def main(argv):

    _path = os.path.expanduser('~/Develop/SMAPs/')
    nna_file = os.path.expanduser('~/Documents/SMAPs/norpointT80.dat')
    nsa_file = os.path.expanduser('~/Documents/SMAPs/surpointT80.dat')

    sna_file = os.path.expanduser('~/Develop/SMAPs/coordinatesystemandtiling/smaps_pointT80norte.dat')
    ssa_file = os.path.expanduser('~/Develop/SMAPs/coordinatesystemandtiling/smaps_pointsulT80.dat')

    nna_pt = np.loadtxt(nna_file,unpack=True,usecols=(4,5))
    nsa_pt = np.loadtxt(nsa_file,unpack=True,usecols=(4,5))

    sna_pt = np.loadtxt(sna_file,unpack=True,usecols=(4,5))
    ssa_pt = np.loadtxt(ssa_file,unpack=True,usecols=(4,5))
		
    file1 = 'lambda_sfd_ebv.fits' 
    file2 = 'smpas_obstime_2.fits'
    file3 = 'smpas_obstime_15.fits'
    extMapFile = 'extintion_at3800.fits'
    
    map1 = H.read_map(os.path.join(_path,file1))
    map2 = H.read_map(os.path.join(_path,file2))
    map3 = H.read_map(os.path.join(_path,file3))    
    extMap = H.read_map(os.path.join(_path,extMapFile))
    
    H.mollview(map1,fig=1,coord=['G','E'],max=1.0,title='',sub=(2,2,3),cbar=False,notext=True)#,unit='hours z < 1.3')

    H.projplot((90-nna_pt[1])*np.pi/180.,nna_pt[0]*np.pi/180.,'r.')#,coord=['E','G'])
    H.projplot((90-nsa_pt[1])*np.pi/180.,nsa_pt[0]*np.pi/180.,'r.')#,coord=['E','G'])

    H.projplot((90-sna_pt[1])*np.pi/180.,sna_pt[0]*np.pi/180.,'w.')#,coord=['E','G'])
    H.projplot((90-ssa_pt[1])*np.pi/180.,ssa_pt[0]*np.pi/180.,'w.')#,coord=['E','G'])

    H.graticule()

    H.mollview(map2,fig=1,coord=['G','E'],title='',sub=(2,2,1),cbar=False,notext=True,max=1800)
	#,unit='hours z < 1.3')

    H.graticule()

    H.mollview(map3,fig=1,coord='G',title='',sub=(2,2,2),cbar=False,notext=True,max=1800)#,unit='hours z < 1.3')

    H.graticule()

    H.mollview(map2*10**(-extMap),fig=1,coord='G',title='',sub=(2,2,4),cbar=False,notext=True)#,unit='hours z < 1.3')

    H.graticule()

    py.savefig(os.path.join(_path,'Figures/fig1.png'))

    py.show()
Exemple #4
0
    def create_graticule(self, lat, lon):

        for la in lat:
            theta = np.zeros(1000)
            theta[:] = la * np.pi/180
            phi = np.linspace(0,np.pi*2,num=1000)
            hp.projplot(theta, phi, 'gray', linewidth=0.3)
            hp.projplot(theta, phi, 'k', linewidth=1, linestyle='dotted')
        for lo in lon:
            theta = np.linspace(0,np.pi,num=1000)
            phi = np.zeros(1000)
            phi[:] = lo * np.pi/180
            hp.projplot(theta, phi, 'gray', linewidth=0.3)
            hp.projplot(theta, phi, 'k', linewidth=1, linestyle='dotted')
Exemple #5
0
    def create_spt_area(self):
        
        num_ra = 1000
        num_dec = 200

        ra = np.arange(num_ra, dtype=np.float32)/num_ra * (360.0+105 - 300) + 300.0
        ip = np.where(ra > 360.0)
        ra[ip] = ra[ip] - 360.00

        dec = 90.0 - (np.arange(num_dec, dtype=np.float32)/num_dec * (65.0 - 40.00) - 65.0)

        ra[:] = ra[:] * np.pi/180.0
        dec[:] = dec[:] * np.pi/180.0

        ra_list = []
        dec_list = []
        for i in np.arange(num_ra):
            ra_list.append( ra[i] )
            dec_list.append( dec[0] )

        for i in np.arange(num_dec):
            ra_list.append( ra[num_ra-1] )
            dec_list.append( dec[i] )

        for i in np.arange(num_ra):
            ra_list.append( ra[num_ra-1-i] )
            dec_list.append( dec[num_dec-1] )

        for i in np.arange(num_dec):
            ra_list.append( ra[0] )
            dec_list.append( dec[num_dec-1-i] )

        rot = hp.Rotator(coord=['C','G'])
        theta, phi = rot(dec_list, ra_list)

        lines1 = hp.projplot(theta, phi, 'white')
        
        return lines1
Exemple #6
0
 def plot_dot(self, el, az):
     theta, phi = elaz2hp(el, az)
     hp.projplot(theta, phi, "k.", rot=(0, 90, 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()
Exemple #8
0
result10 = np.where(boolArr10)
boolArr50 = (credible_levels <=.5)
result50 = np.where(boolArr50)
boolArr90 = (credible_levels <=.9)
result90 = np.where(boolArr90)


theta, phi = hp.pix2ang(nside, result50[0])
ra = np.rad2deg(phi)
dec = np.rad2deg(0.5 * np.pi - theta)
print(ra, dec)




## https://healpy.readthedocs.io/en/latest/healpy_visu.html#tracing-lines-or-points
fig, ax = plt.subplots(figsize=(5, 3), dpi=80, facecolor='w', edgecolor='k')
#fig, ax = plt.subplots()
## Plotting a Mollweide-projection all-sky map:
hp.mollview(hpx)
hp.projplot(theta, phi, 'bo')  # plot 'o' in blue at coord (theta, phi)
fig.savefig("test.png")
plt.show()


#fig, (ax1, ax2) = plt.subplots(ncols=2)
#plt.axes(ax1)
#hp.mollview(np.random.random(hp.nside2npix(32)), hold=True)
#plt.axes(ax2)
#hp.mollview(np.arange(hp.nside2npix(32)), hold=True)
    def superimpose_polygon_outline(self, vertices, label, color='red',
                                    coord_in='C', cbar=True):
        '''Superimpose an outline of a survey given input vertices

        Parameters
        ----------
        vertices: array-like (nvtxs, 2)
            The vertices of the polygon

        label : string
            The label for the survey

        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', 'E', or 'G'
            The coordinate system for the input vertices

        cbar : boolean
            Whether to add a colorbar corresponding to this polygon or not
        '''

        lons = vertices[:, 0]
        lats = vertices[:, 1]

        if np.abs(lons[-1] - 180.0) > 0.01:
            lons = np.append(lons, lons[0])
            lats = np.append(lats, lats[0])

        #Convert coordinate system for the outline to the one used in the
        #plot
        r = H.rotator.Rotator(coord=[coord_in, self.coord_plot])
        r = H.rotator.Rotator(coord=[coord_in, coord_in])
        lonsp = []
        latsp = []
        for lon, lat in zip(lons, lats):
            theta = np.radians(90 - lat)
            phi = np.radians(lon)
            thetap, phip = r(theta, phi)
            lonsp.append(np.degrees(phip))
            latsp.append(90 - np.degrees(thetap))

        lons = lonsp
        lats = latsp

        nvertices = len(lons)

        # Loop over all vertices and generate lines between adjacent vertices
        # in list. This is to ensure the lines are drawn.
        linelon = np.array([])
        linelat = np.array([])
        for i in range(nvertices-1):
            tmplon = np.linspace(lons[i], lons[i+1], num=1000)
            tmplat = np.linspace(lats[i], lats[i+1], num=1000)
            linelon = np.append(linelon, tmplon)
            linelat = np.append(linelat, tmplat)

        H.projplot(linelon, linelat, lonlat=True, markersize=1,
                   color=color, coord=coord_in)

        if cbar:
            # Temporary axis with a Healpix map so I can get the correct color
            # for the colorbar
            cm1 = util.get_color_map(color)
            coord = [coord_in, self.coord_plot]
            hpx_map = np.ones(12*32**2)
            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])

            # 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)

            # Delete the temporary map
            self.fig.delaxes(self.fig.axes[-2])

            # Readjust 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
deltatheta = 15.
deltatheta2 = 20.
deltatheta3 = 25.
racirc, deccirc = circ_around_radec([racenter, deccenter], deltatheta)
racirc2, deccirc2 = circ_around_radec([racenter, deccenter], deltatheta2)
racirc3, deccirc3 = circ_around_radec([racenter, deccenter], deltatheta3)

# Initial dust map 
clf()
l,b = equ2gal(racenter, deccenter)
vv = hp.ang2vec(np.radians(90-b), np.radians(l))
pixels = hp.query_disc(hp.npix2nside(len(mapdust)), vv, np.radians(15))
mm = np.min(mapdust[pixels])
#hp.gnomview(mapdust-mm, coord='GE', title='Planck Dust Map', rot=[racenter,deccenter], fig=1, reso=25,min=0,max=1e-4)
hp.mollview(mapdust-mm, coord='GE', title='Planck Dust Map', rot=[racenter,deccenter], fig=2, min=0,max=1e-4)
hp.projplot(pi/2-np.radians(deccenter), np.radians(racenter), 'kx')
hp.projplot(pi/2-np.radians(deccirc), np.radians(racirc), 'k')
hp.projplot(pi/2-np.radians(deccirc2), np.radians(racirc2), 'k')
hp.projplot(pi/2-np.radians(deccirc3), np.radians(racirc3), 'k')
hp.projplot(pi/2-np.radians(-45), np.radians(4*15+40/60+12/3600), 'ko')
hp.projplot(pi/2-np.radians(-30/60), np.radians(11*15+453/60+0/3600), 'ko')
hp.projplot(pi/2 - np.radians(-32-48/60), np.radians(23*15+1/60+48/3600), 'ko')
bicepalpha = np.ravel([np.zeros(10)-60, np.linspace(-60, 60, 10), np.zeros(10)+60, np.linspace(60, -60, 10)])
bicepdelta = np.ravel([np.linspace(-70, -45, 10),np.zeros(10)-45, np.linspace(-45, -70, 10),np.zeros(10)-70])
hp.projplot(pi/2-np.radians(bicepdelta), np.radians(bicepalpha), 'k--')

# Initial 143 GHz map 
clf()
hp.gnomview(init143, coord='GE', title='Planck 143 GHz Map', rot=[racenter,deccenter], fig=2, reso=25,min=-5e-4,max=5e-4)
hp.projplot(pi/2-np.radians(deccenter), np.radians(racenter), 'kx')
hp.projplot(pi/2-np.radians(deccirc), np.radians(racirc), 'k')
Exemple #11
0
def plot(data, showdisks=False, unit='stars/deg^2'):
    _fontsize = rcParams['font.size']
    _fontweight = rcParams['font.weight']

    rcParams['font.size'] = 14
    rcParams['font.weight'] = 'normal'

    # Draw the map
    healpy.mollview(map=data, rot=[0, 180],
                    cmap=cm.gist_stern_r, title='', 
                    unit=unit)
    healpy.graticule(dpar=30.0, dmer=45.0, local=True)

    # Handle colorbar labels
    try:
        fig = py.gcf()
        cbar = fig.axes[-1]
        
        cbarLabels = cbar.xaxis.get_ticklabels()
        for cc in range(len(cbarLabels)):
            cbarLabels[cc] = '%.5f' % float(cbarLabels[cc].get_text())
    
        cbar.xaxis.set_ticklabels(cbarLabels, fontweight='bold', fontsize=14)
    except UnicodeEncodeError:
        pass
    
    # Draw contours for the old disk positions
    if showdisks:
        incl = [124.0, 30.0]
        incl_err = [2.0, 4.0]
        incl_thick = [7.0, 9.5]
        Om = [100.0, 167.0]
        Om_err = [3.0, 9.0]
        Om_thick = [7.0, 9.5]

        for jj in range(len(incl)):
            x1, y1 = ellipseOutline(incl[jj], Om[jj], 
                                  incl_err[jj], Om_err[jj])
            x2, y2 = ellipseOutline(incl[jj], Om[jj], 
                                  incl_thick[jj], Om_thick[jj])
            healpy.projplot(x1, y1, lonlat=True, color='k', 
                            linestyle='-', linewidth=2)
            healpy.projplot(x2, y2, lonlat=True, color='k',
                            linestyle='--', linewidth=2)


    # Flip so that the axes go in the right direction
    foo = py.axis()
    py.xlim(2.01, -2.01)

    # Make axis labels.
    healpy.projtext(178, 90, '0', lonlat=True)
    healpy.projtext(178, 60, '30', lonlat=True)
    healpy.projtext(178, 30, '60', lonlat=True)
    healpy.projtext(178, 0, '90', lonlat=True)
    healpy.projtext(178, -30, '120', lonlat=True)
    healpy.projtext(178, -60, '150', lonlat=True)
    healpy.projtext(178, -90, 'i = 180', lonlat=True,
                    horizontalalignment='center')

    healpy.projtext(92, 1, 'S', lonlat=True,
                    horizontalalignment='right', verticalalignment='top')
    healpy.projtext(182, 1, 'W', lonlat=True, 
                    horizontalalignment='right', verticalalignment='top')
    healpy.projtext(272, 1, 'N', lonlat=True, 
                    horizontalalignment='right', verticalalignment='top')
    healpy.projtext(362, 1, 'E', lonlat=True, 
                    horizontalalignment='right', verticalalignment='top')

    rcParams['font.size'] = _fontsize
    rcParams['font.weight'] = _fontweight
Exemple #12
0
 def display(self, marker, color):
     healpy.projplot(*self.coords(), marker+color, \
                     markersize=6, \
                     label=self.label)
Exemple #13
0
def maximum_info(maxima, n, mapp, nmax=None):
    '''Show a plot with a maximum and some information about it.
    
    Utility function to easily view the basic propierties of a specific maximum.
    
    Parameters
    ----------
    maxima : pd.DataFrame
        Pandas DataFrame with the information of the maxima. Has to contain at least the columns 'Pixel number' and 'Intensity'.
        If it contains 'pvalue', it will use it. Otherwise, the p-value will be set to ``np.nan``.
    n : int
        Row of the ``maxima`` with the information of the maximum to be shown.
    mapp : np.ndarray
        Healpix map to be shown in the image.
    nmax : int or None, optional
        Total number of maxima detected in the map. If ``None`` is introduced, it uses the length of the ``maxima`` table. Since this
        can affect the results (if ``maxima`` does not contain all the maxima), the lines affected are colored grey and the function 
        raises a warning.
    
    Returns
    -------
    matplotlib.figure.Figure
        Figure containing the information about the maximum.
    '''
    pixn = maxima['Pixel number'].iloc[n]
    intensity = maxima['Intensity'].iloc[n]
    try:
        pval = maxima['pvalue'].iloc[n]
    except KeyError:
        pval = np.nan
    nrows = 1
    nside = hp.get_nside(mapp)
    (lon, lat) = hp.pix2ang(ipix=pixn, nside=nside, lonlat=True)

    fig, axs = plt.subplots(nrows, 3, figsize=(15, 6 * nrows), squeeze=False)
    for ax in axs.flatten():
        ax.axis('off')
    _set_text(fig, f"Pixel number: {pixn}", 0.1 / nrows)
    _set_text(fig, f"Intensity: {intensity:.2f}", 0.2 / nrows)
    _set_text(fig, f"Longitude [deg]: {lon:.3f}", 0.3 / nrows)
    _set_text(fig, f"Latitude [deg]: {lat:.3f}", 0.4 / nrows)

    _set_text(fig, f"Index: {n+1}", 0.52 / nrows)
    _set_text(fig, f"pvalue: {pval:.2}", 0.62 / nrows)
    if nmax != None:
        _set_text(fig, f"Expected number: {pval*nmax:.2}", 0.72 / nrows)
    else:
        _set_text(fig,
                  f"Expected number: {pval*maxima.shape[0]:.2}",
                  0.72 / nrows,
                  alpha=0.5)
        warnings.warn(
            'The number of maxima nmax has not been introduced. Using the size of maxima instead. If this table does not cointain all the maxima in the map, the result of "Expected number" is not reliable.'
        )

    _set_text(fig, f"Intensity in the map: {mapp[pixn]:.2f}", 0.85 / nrows)
    _set_text(fig, f"Std of the map: {np.std(mapp):.2f}", 0.95 / nrows)

    hp.mollview(mapp, sub=[nrows, 3, 3], margins=(0, 0.12 / nrows, 0.01, 0))
    hp.projplot(lon,
                lat,
                'o',
                color='orange',
                lonlat=True,
                fillstyle='none',
                markersize=8)
    hp.gnomview(mapp,
                rot=(lon, lat),
                sub=[nrows, 3, 2],
                margins=(0.02, 0.02 / nrows, 0.02, 0.02 / nrows))

    return (fig, axs)
Exemple #14
0
def generateConesNoExtClock(slope,intercept,plane1Dets,plane2Dets,plane1Times,plane2Times,plane1NeutronPulseADC,plane2NeutronPulseADC,tic):
    import csv
    import numpy as np
    import math
    import matplotlib.pyplot as plt
    import matplotlib
    import pylab as pl
    import time
    import healpy as hp
    from mpl_toolkits.mplot3d import Axes3D
    from PIL import Image
    planeSeparation = 0.6096 #meters
    detectorSeparation = 0.0889 #meters
    u = detectorSeparation #meters
    D = planeSeparation #meters
    clockSpeed = 250*10**6 #Hz
    timeScale = 1/clockSpeed #seconds
    distance = []
    x1 = []
    x2 = []
    plane1Local = np.array([[0,0,0],[0,u,0],[0,2*u,0],[u,0,0],[u,u,0],[u,2*u,0],[2*u,0,0],[2*u,u,0],[2*u,2*u,0],[3*u,0,0],[3*u,u,0],[3*u,2*u,0]],dtype='float')
    plane2Local = np.array([[0,0,D],[0,u,D],[0,2*u,D],[u,0,D],[u,u,D],[u,2*u,D],[2*u,0,D],[2*u,u,D],[2*u,2*u,D],[3*u,0,D],[3*u,u,D],[3*u,2*u,D]],dtype='float')
    area = ((plane2Local[0,2] - plane1Local[0,2])*10**2)*(plane2Local[11,0]-plane1Local[0,0])*10**2 #cm2
    neutronEnergyTOF = []
    neutronEnergyADC = []
    neutronEnergy = []
    coneAngles = []
    coneVector = []
    mu = []
    weights = []
    coneVector1 = []
    mu1 = []
    weights1 = []
    coneVector2 = []
    mu2 = []
    weights2 = []
    coneVector3 = []
    mu3 = []
    weights3 = []
#    cones = []
    b = 0
    time1 = []
#    radii = 0
    sigma = 0.045
    iteration = 0
    area = (plane1Local[2,1]-plane1Local[0,1])*(plane1Local[10,0]-plane1Local[0,0])

    data1Mat = np.column_stack((tuple(plane1Dets),tuple(plane1Times),tuple(plane1NeutronPulseADC)))
    data1MatSort = data1Mat[data1Mat[:,0].argsort()[::1]]
    np.savetxt("data1MatSort.csv", data1MatSort, delimiter=",")
    plane1Dets = [column[0] for column in data1MatSort]
    plane1Times = [column[1] for column in data1MatSort]
    plane1NeutronPulseADC = [column[2] for column in data1MatSort]
    data2Mat = np.column_stack((tuple(plane2Dets),tuple(plane2Times),tuple(plane2NeutronPulseADC)))
    data2MatSort = data2Mat[data2Mat[:,0].argsort()[::1]]
    plane2Dets = [column[0] for column in data2MatSort]
    plane2Times = [column[1] for column in data2MatSort]
    plane2NeutronPulseADC = [column[2] for column in data2MatSort]
    plane1Dets = np.array(plane1Dets,dtype='int')
    plane1Dets = np.array(plane1Dets,dtype='int')
    plane2Dets = np.array(plane2Dets,dtype='int')
    plane2Dets = np.array(plane2Dets,dtype='int')
    plane2DetScale = []
    
    for i in range(0,len(plane2Dets)):
        if plane2Dets[i] == 12:
            plane2DetScale += [0]
        if plane2Dets[i] == 13:
            plane2DetScale += [1]
        if plane2Dets[i] == 14:
            plane2DetScale += [2]
        if plane2Dets[i] == 15:
            plane2DetScale += [3]
        if plane2Dets[i] == 16:
            plane2DetScale += [4]
        if plane2Dets[i] == 17:
            plane2DetScale += [5]
        if plane2Dets[i] == 18:
            plane2DetScale += [6]
        if plane2Dets[i] == 19:
            plane2DetScale += [7]
        if plane2Dets[i] == 20:
            plane2DetScale +=[8]
        if plane2Dets[i] == 21:
            plane2DetScale += [9]
        if plane2Dets[i] == 22:
            plane2DetScale += [10]
        if plane2Dets[i] == 23:
            plane2DetScale += [11]
    
    plane2DetScale = np.array(plane2DetScale,dtype = 'int')
    

#### Calculate neutron energy from time of flight between the 2 planes ####
    #tic = time.time()
    if len(plane1Times)>len(plane2Times):
        iteration = len(plane2Times)
    else:
        iteration = len(plane1Times)
        
    keepTrack = 0
    for i in range(0,iteration): #range(0,len(plane1Times))
        if i > 200 and i < iteration-101:
            for n in range(i-100,i+100):
                if plane2Times[n] - plane1Times[i] <= 1000000 and plane2Times[n] - plane1Times[i] > 0:
                    #temp = keepTrack
                    if 0 <= plane1Dets[i] <= 3 and 20 <= plane2Dets[n] <= 23:
                        #print('calculating TOF')
                        x1 = plane1Local[plane1Dets[i]]
                        x2 = plane2Local[plane2DetScale[n]]
                        dist = np.sqrt((x2[0]-x1[0])**2 + (x2[1]-x1[1])**2 + (x2[2])**2)
                        distance += [dist]
                        timeSeparation = (plane2Times[n]-plane1Times[i])*timeScale
                        #print('time separation = ',timeSeparation)
                        #print('distance = ',dist)
                        u = dist/timeSeparation
                        #print('velocity = ',u)
                        energy = (1/(1.602*10**(-16)))*0.5*(1.675*10**(-27))*(dist/timeSeparation)**2 #keV
                        energyADC = slope*plane1NeutronPulseADC[i] + intercept
                        #energyNeutronFirstScatter = (10**3)*(-0.1410 + math.sqrt(0.1410**2 + 4*0.035*plane1NeutronPulseADC[i]))/(2*0.035) #keV
                        energyNeutronFirstScatter = energyADC*((0.99*(plane1NeutronPulseADC[i]+0.0685))/(0.23*(plane1NeutronPulseADC[i]-0.008)))
                        energyTotal = energyNeutronFirstScatter + energy
                        neutronEnergyTOF += [energy] #keV
                        neutronEnergyADC += [energyNeutronFirstScatter] #keV
                        neutronEnergy += [energyTotal] #keV
                        #print('Direct ADC = ',energyADC)
                        #print('Converted ADC = ', energyNeutronFirstScatter)
                        #print('angle = ',np.deg2rad(math.sqrt((slope*plane1NeutronPulseADC[i] + intercept)/energyTotal)))
                        coneAngles += [math.atan(np.deg2rad(math.sqrt((slope*plane1NeutronPulseADC[i] + intercept)/energyTotal)))]
                        mu += [np.cos(math.atan(np.deg2rad(math.sqrt((slope*plane1NeutronPulseADC[i] + intercept)/energyTotal))))]
                        weights += [1/dist**2]
                        coneVector += [x1-x2]
                        #if keepTrack == 0:
                        time1 += [plane1Times[i]*timeScale]
                        time1 += [plane2Times[n]*timeScale]
                        coneVector += [x1-x2]
                        mu1 += [np.cos(math.atan(np.deg2rad(math.sqrt((slope*plane1NeutronPulseADC[i] + intercept)/energyTotal))))]
                        weights1 += [1/dist**2]
                        coneVector1 += [x1-x2]
                        #keepTrack += 1
                        #if keepTrack > temp:
                        #    time2 = plane1Times[keepTrack]*timeScale
                        break
                    elif 8 <= plane1Dets[i] <= 11 and 12 <= plane2Dets[n] <= 15:
                        x1 = plane1Local[plane1Dets[i]]
                        x2 = plane2Local[plane2DetScale[n]]
                        dist = np.sqrt((x2[0]-x1[0])**2 + (x2[1]-x1[1])**2 + (x2[2])**2)
                        distance += [dist]
                        timeSeparation = (plane2Times[n]-plane1Times[i])*timeScale
                        energy = (1/(1.602*10**(-16)))*0.5*(1.675*10**(-27))*(dist/timeSeparation)**2 #keV
                        energyADC = slope*plane1NeutronPulseADC[i] + intercept
                        energyTotal = energyADC + energy
                        neutronEnergyTOF += [energy] #keV
                        neutronEnergyADC += [energyADC] #keV
                        neutronEnergy += [energyTotal] #keV
                        #print('angle = ',np.deg2rad(math.sqrt((slope*plane1NeutronPulseADC[i] + intercept)/energyTotal)))
                        coneAngles += [math.atan(np.deg2rad(math.sqrt((slope*plane1NeutronPulseADC[i] + intercept)/energyTotal)))]
                        mu += [np.cos(math.atan(np.deg2rad(math.sqrt((slope*plane1NeutronPulseADC[i] + intercept)/energyTotal))))]
                        weights += [1/dist**2]
                        coneVector += [x1-x2]
                        print('in deterctor 2 space')
                        mu2 += [np.cos(math.atan(np.deg2rad(math.sqrt((slope*plane1NeutronPulseADC[i] + intercept)/energyTotal))))]
                        weights2 += [1/dist**2]
                        coneVector2 += [x1-x2]
                        break
                    elif 4 <= plane1Dets[i] <= 7 and 16 <= plane2Dets[n] <= 19:
                        x1 = plane1Local[plane1Dets[i]]
                        x2 = plane2Local[plane2DetScale[n]]
                        dist = np.sqrt((x2[0]-x1[0])**2 + (x2[1]-x1[1])**2 + (x2[2])**2)
                        distance += [dist]
                        timeSeparation = (plane2Times[n]-plane1Times[i])*timeScale
                        energy = (1/(1.602*10**(-16)))*0.5*(1.675*10**(-27))*(dist/timeSeparation)**2 #keV
                        energyADC = slope*plane1NeutronPulseADC[i] + intercept
                        energyTotal = energyADC + energy
                        neutronEnergyTOF += [energy] #keV
                        neutronEnergyADC += [energyADC] #keV
                        neutronEnergy += [energyTotal] #keV
                        #print('angle = ',np.deg2rad(math.sqrt((slope*plane1NeutronPulseADC[i] + intercept)/energyTotal)))
                        coneAngles += [math.atan(np.deg2rad(math.sqrt((slope*plane1NeutronPulseADC[i] + intercept)/energyTotal)))]
                        mu += [np.cos(math.atan(np.deg2rad(math.sqrt((slope*plane1NeutronPulseADC[i] + intercept)/energyTotal))))]
                        weights += [1/dist**2]
                        coneVector += [x1-x2]
                        print('in deterctor 3 space')
                        mu3 += [np.cos(math.atan(np.deg2rad(math.sqrt((slope*plane1NeutronPulseADC[i] + intercept)/energyTotal))))]
                        weights3 += [1/dist**2]
                        coneVector3 += [x1-x2]
                        break
                neutronEnergyTOF += [0] #keV
                neutronEnergyADC += [slope*plane1NeutronPulseADC[i] + intercept]
                    
        elif i<=200:
            for n in range(0,i+200):
#            if n%10000 == 0:
#                print('n = ',n)
                if plane2Times[n] - plane1Times[i] <= 1000000 and plane2Times[n] - plane1Times[i] > 0:
                    if 0 <= plane1Dets[i] <= 3 and 20 <= plane2Dets[n] <= 23:
                        x1 = plane1Local[plane1Dets[i]]
                        x2 = plane2Local[plane2DetScale[n]]
                        dist = np.sqrt((x2[0]-x1[0])**2 + (x2[1]-x1[1])**2 + (x2[2])**2)
                        distance += [dist]
                        timeSeparation = (plane2Times[n]-plane1Times[i])#*timeScale
                        energy = (1/(1.602*10**(-16)))*0.5*(1.675*10**(-27))*(dist/timeSeparation)**2 #keV
                        energyADC = slope*plane1NeutronPulseADC[i] + intercept
                        #energyTotal = energyADC + energy
                        neutronEnergyTOF += [energy] #keV
                        energyNeutronFirstScatter = energyADC*((0.99*(plane1NeutronPulseADC[i]+0.0685))/(0.23*(plane1NeutronPulseADC[i]-0.008)))
                        energyTotal = energyNeutronFirstScatter + energy
                        neutronEnergy += [energyTotal] #keV
                        #print('angle = ',np.deg2rad(math.sqrt((slope*plane1NeutronPulseADC[i] + intercept)/energyTotal)))
                        coneAngles += [math.atan(np.deg2rad(math.sqrt((slope*plane1NeutronPulseADC[i] + intercept)/energyTotal)))]
                        mu += [np.cos(math.atan(np.deg2rad(math.sqrt((slope*plane1NeutronPulseADC[i] + intercept)/energyTotal))))]
                        weights += [1/dist**2]
                        #if keepTrack == 0:
                        time1 += [plane1Times[i]*timeScale]
                        time1 += [plane2Times[n]*timeScale]
                        #keepTrack += 1
                        coneVector += [x1-x2]
                        mu1 += [np.cos(math.atan(np.deg2rad(math.sqrt((slope*plane1NeutronPulseADC[i] + intercept)/energyTotal))))]
                        weights1 += [1/dist**2]
                        coneVector1 += [x1-x2]
                        break
                    elif 8 <= plane1Dets[i] <= 11 and 12 <= plane2Dets[n] <= 15:
                        x1 = plane1Local[plane1Dets[i]]
                        x2 = plane2Local[plane2DetScale[n]]
                        dist = np.sqrt((x2[0]-x1[0])**2 + (x2[1]-x1[1])**2 + (x2[2])**2)
                        distance += [dist]
                        timeSeparation = (plane2Times[n]-plane1Times[i])*timeScale
                        energy = (1/(1.602*10**(-16)))*0.5*(1.675*10**(-27))*(dist/timeSeparation)**2 #keV
                        energyADC = slope*plane1NeutronPulseADC[i] + intercept
                        #energyTotal = energyADC + energy
                        neutronEnergyTOF += [energy] #keV
                        energyNeutronFirstScatter = energyADC*((0.99*(plane1NeutronPulseADC[i]+0.0685))/(0.23*(plane1NeutronPulseADC[i]-0.008)))
                        energyTotal = energyNeutronFirstScatter + energy
                        neutronEnergy += [energyTotal] #keV
                        #print('angle = ',np.deg2rad(math.sqrt((slope*plane1NeutronPulseADC[i] + intercept)/energyTotal)))
                        coneAngles += [math.atan(np.deg2rad(math.sqrt((slope*plane1NeutronPulseADC[i] + intercept)/energyTotal)))]
                        mu += [np.cos(math.atan(np.deg2rad(math.sqrt((slope*plane1NeutronPulseADC[i] + intercept)/energyTotal))))]
                        weights += [1/dist**2]
                        coneVector += [x1-x2]
                        print('in deterctor 2 space')
                        mu2 += [np.cos(math.atan(np.deg2rad(math.sqrt((slope*plane1NeutronPulseADC[i] + intercept)/energyTotal))))]
                        weights2 += [1/dist**2]
                        coneVector2 += [x1-x2]
                        break
                    elif 4 <= plane1Dets[i] <= 7 and 16 <= plane2Dets[n] <= 19:
                        x1 = plane1Local[plane1Dets[i]]
                        x2 = plane2Local[plane2DetScale[n]]
                        dist = np.sqrt((x2[0]-x1[0])**2 + (x2[1]-x1[1])**2 + (x2[2])**2)
                        distance += [dist]
                        timeSeparation = (plane2Times[n]-plane1Times[i])*timeScale
                        energy = (1/(1.602*10**(-16)))*0.5*(1.675*10**(-27))*(dist/timeSeparation)**2 #keV
                        energyADC = slope*plane1NeutronPulseADC[i] + intercept
                        energyTotal = energyADC + energy
                        neutronEnergyTOF += [energy] #keV
                        neutronEnergyADC += [energyADC] #keV
                        neutronEnergy += [energyTotal] #keV
                        #print('angle = ',np.deg2rad(math.sqrt((slope*plane1NeutronPulseADC[i] + intercept)/energyTotal)))
                        coneAngles += [math.atan(np.deg2rad(math.sqrt((slope*plane1NeutronPulseADC[i] + intercept)/energyTotal)))]
                        mu += [np.cos(math.atan(np.deg2rad(math.sqrt((slope*plane1NeutronPulseADC[i] + intercept)/energyTotal))))]
                        weights += [1/dist**2]
                        coneVector += [x1-x2]
                        print('in deterctor 3 space')
                        mu3 += [np.cos(math.atan(np.deg2rad(math.sqrt((slope*plane1NeutronPulseADC[i] + intercept)/energyTotal))))]
                        weights3 += [1/dist**2]
                        coneVector3 += [x1-x2]
                        break
                neutronEnergyTOF += [0] #keV
                neutronEnergyADC += [slope*plane1NeutronPulseADC[i] + intercept]
                neutronEnergy += [slope*plane1NeutronPulseADC[i] + intercept] #keV
        if i%10000 == 0:
            toc = time.time()
            print('i = ',i)
            print('elapsed time = ',toc-tic, 's')

######################################################################################
####                  make lists into numpy arrays                                ####  
######################################################################################
    distance = np.array(distance)
    neutronEnergyTOF = np.array(neutronEnergyTOF,dtype = 'float')
    #neutronEnergyTOF = neutronEnergyTOF*10**3 #keV
    neutronEnergyADC = np.array(neutronEnergyADC, dtype = 'float')
    neutronEnergy = np.array(neutronEnergy, dtype = 'float') #neutronEnergyTOF + neutronEnergyADC
    coneVector = np.array(coneVector,dtype = 'float')
    mu = np.array(mu)
    coneAngles = np.array(coneAngles)
    weights = np.array(weights)
    coneVector1 = np.array(coneVector1,dtype = 'float')
    mu1 = np.array(mu1)
    weights1 = np.array(weights1)
    coneVector2 = np.array(coneVector2,dtype = 'float')
    mu2 = np.array(mu2)
    weights2 = np.array(weights2)
    coneVector3 = np.array(coneVector3,dtype = 'float')
    mu3 = np.array(mu3)
    weights3 = np.array(weights3)
    #neutronEnergy = np.array(neutronEnergy,dtype='float')
    time1 = np.array(time1,dtype = 'float')
    time1.sort()
    np.savetxt('adcEnergy.csv',neutronEnergyADC)
    np.savetxt('neutronEnergy.csv',neutronEnergy)
    ### Checking max TOF and ADC Energies ###
    tofMaxArg = neutronEnergyTOF.argmax()
    print('Max TOF Energy = ', neutronEnergyTOF[tofMaxArg])
    adcMaxArg = neutronEnergyADC.argmax()
    print('Max ADC Energy = ', neutronEnergyADC[adcMaxArg])
    nEMax = neutronEnergy.argmax()
    print('Max Total Energy = ',neutronEnergy[nEMax])
#######################################################################################
####              create unit vector for cones                                     ####  
#######################################################################################
    unitNorm = 0
    unitVector = []
    for i in range(0,len(coneVector[:,0])):
        temp = coneVector[i,:]
        unitNorm = np.linalg.norm(temp)
        unitVector += [temp/unitNorm]

    unitVector = np.array(unitVector, dtype = 'float')

    unitNorm = 0
    unitVector1 = []
    for i in range(0,len(coneVector1[:,0])):
        temp = coneVector1[i,:]
        unitNorm = np.linalg.norm(temp)
        unitVector1 += [temp/unitNorm]

    unitVector1 = np.array(unitVector1, dtype = 'float')
    

    
    if coneVector2 != 0:
        unitNorm = 0
        unitVector2 = []
        for i in range(0,len(coneVector2[:,0])):
            temp = coneVector2[i,:]
            unitNorm = np.linalg.norm(temp)
            unitVector2 += [temp/unitNorm]
        unitVector2 = np.array(unitVector2, dtype = 'float')
    
    if coneVector3 != 0:
        unitNorm = 0
        unitVector3 = []
        for i in range(0,len(coneVector3[:,0])):
            temp = coneVector3[i,:]
            unitNorm = np.linalg.norm(temp)
            unitVector3 += [temp/unitNorm]
        unitVector3 = np.array(unitVector3, dtype = 'float')


#######################################################################################
####                    plot energy spectrum                                       ####  
#######################################################################################
    print('nEnergy.size() = ', np.size(neutronEnergy))
    neutronEnergyAdj = [i for i in neutronEnergy if  0 < i <= 500000]
    neutronEnergyAdj = np.array(neutronEnergyAdj, dtype = 'float')
    #print(neutronEnergy)
    nEMax = neutronEnergyAdj.argmax()
    print('max n energy = ',neutronEnergyAdj[nEMax])
    energyHist = np.histogram(neutronEnergyAdj,1000)#len(neutronEnergy))
    a = energyHist[0]
    b1 = energyHist[1]
    #print('a = ',a)
    #print('a.size = ',np.size(a))
    #print('b1 = ',b1)
    #print('b1.size = ',np.size(b1))
    
    c = b1[1:1001]
    print('max E taken = ',c[len(c)-1])
    print('max counts = ', max(a))
    for i in range(0,len(a)-1):
        if a[i] == 0:
            a[i]=1
            
    plt.figure(2)
    plt.plot(c,np.log10(a),'b-')
    plt.xlabel('Neutron Energy [keV]')
    plt.ylabel('Log10(Counts)')
    plt.title('Neutron Spectrum')
    plt.autoscale(enable=True,axis='x',tight=True)
    pl.xticks(rotation=45)
    #plt.legend(loc='upper right')
    #plt.plot(d,f)
    plt.show()

#######################################################################################
####                    plot flux spectrum                                         ####  
#######################################################################################
    print('flux time = ',time1[len(time1)-1]-time1[0])
    plt.figure()
    flux = np.exp(a)/(area*(time1[len(time1)-1]-time1[0]))
    plt.figure(3)
    plt.plot(c,flux,'b-')
    plt.xlabel('Neutron Energy [keV]')
    plt.ylabel('Flux [Counts/cm^2s]')
    plt.title('Neutron Flux Spectrum')
    plt.autoscale(enable=True,axis='x',tight=True)
    pl.xticks(rotation=45)
    #plt.legend(loc='upper right')
    #plt.plot(d,f)
    plt.show()
########################################################################################
####         generate and plot neutron dose spectrum                                ####  
########################################################################################
    doseConversion = np.array([[260],[240],[220],[230],[240],[270],[280],[48],[14],[8.5],[7.0],[6.8],[6.8],[6.5],[6.1],[5.1],[3.6],[2.2],[1.6],[1.4]], dtype = 'float')
    energyVals = np.array([[2.5*10**(-6)],[1*10**(-5)],[1*10**(-4)],[1*10**(-3)],[1*10**(-2)],[1*10**(-1)],[1*10**(0)],[1*10**1],[5*10],[1*10**2],[2*10**2],[5*10**2],[10*10**2],[20*10**2],[50*10**2],[10**4],[2*10**4],[5*10**4],[1*10**5],[2*10**5],[3*10**3]],dtype = 'float')
    neutronDose = []
    for i in range(0,len(c)):
        for n in range(0,len(energyVals)-1):
            if energyVals[n+1] > c[i] > energyVals[n]:
                conv = doseConversion[n] + (c[i]-energyVals[n])*((doseConversion[n+1]-doseConversion[n])/(energyVals[n+1]-energyVals[n]))
                neutronDose += [0.01*flux[i]/conv]
            elif energyVals[n] == c[i]:
                neutronDose += [0.01*flux[i]/doseConversion[n]]
            
            
    neutronDose = np.array(neutronDose,dtype = 'float')
    plt.figure(4)
    plt.plot(c,neutronDose,'b-')
    plt.xlabel('Neutron Energy [keV]')
    plt.ylabel('Dose [mSv/hr]')
    plt.title('Neutron Dose Rate for PuBe Source')
    plt.autoscale(enable=True,axis='x',tight=True)
    pl.xticks(rotation=45)
    plt.show()

########################################################################################
####             define neutron dose and flux rates                                 ####  
########################################################################################
    maxFluxRate = max(flux)
    maxDoseRate = max(neutronDose)
    totalDose = sum(neutronDose)
########################################################################################
###                      Generate image of neutron data                              ###
########################################################################################
    np.savetxt("muValsSinTheta.csv", mu, delimiter=",")
    np.savetxt("coneVectors.csv",coneVector,delimiter = ",")
    np.savetxt("weights.csv",weights,delimiter = ",")
    np.savetxt("neutronDose.csv",neutronDose,delimiter = ",")
    np.savetxt("neutronEnergy.csv",c,delimiter = ",")
    print('Generating Neutron Image')
    hpindex = 912
    theta,phi = np.asarray(hp.pix2ang(16,hpindex-1)) * (180./np.pi)
    if phi > 180: phi = -(360. - phi)
    nside = 64
    [x_,y_,z_] = hp.pix2vec(nside,range(12*nside*nside))#201))
    k = np.array(list(zip(x_,y_,z_)))
    cmap_ = plt.cm.jet
    cmap_.set_under("w")
    pixels = np.zeros(12*nside*nside)
    #angunc = 3.
    print(len(k))
    print(len(weights))
    b = 0
    for i in range(len(mu)):
        b += (weights[i] / (sigma * np.sqrt(2.*np.pi))) * np.exp(-(np.dot(k,unitVector[i,:]) - mu[i])**2/(2. * sigma**2))
        b[b < 1e-5] = 0
        pixels += b
        #print('elapsed = ',time.time()-tic, 's')

    pixels1 = np.zeros(12*nside*nside)
    #angunc = 3.
    #print(len(k))
    #print(len(weights))
    b = 0
    for i in range(len(mu1)):
        b += (weights1[i] / (sigma * np.sqrt(2.*np.pi))) * np.exp(-(np.dot(k,unitVector1[i,:]) - mu1[i])**2/(2. * sigma**2))
        b[b < 1e-5] = 0
        pixels1 += b
        #print('elapsed = ',time.time()-tic, 's')
    pixels2 = np.zeros(12*nside*nside)
    #angunc = 3.
    print(len(k))
    print(len(weights2))
    b = 0
    for i in range(len(mu2)):
        b += (weights2[i] / (sigma * np.sqrt(2.*np.pi))) * np.exp(-(np.dot(k,unitVector2[i,:]) - mu2[i])**2/(2. * sigma**2))
        b[b < 1e-5] = 0
        pixels2 += b
        #print('elapsed = ',time.time()-tic, 's')
    pixels3 = np.zeros(12*nside*nside)
    #angunc = 3.
    print(len(k))
    print(len(weights3))
    b = 0
    for i in range(len(mu3)):
        b += (weights3[i] / (sigma * np.sqrt(2.*np.pi))) * np.exp(-(np.dot(k,unitVector3[i,:]) - mu3[i])**2/(2. * sigma**2))
        b[b < 1e-5] = 0
        pixels3 += b
        #print('elapsed = ',time.time()-tic, 's')

    pixels = pixels/max(pixels)
    pixels = np.ravel(pixels)
    normPix = pixels-min(pixels[:])
    newPix = normPix/max(normPix)
    #print(res)
    newPix = newPix.reshape(12*nside*nside)#*maxDose

    pixels1 = pixels1/max(pixels1)
    pixels1 = np.ravel(pixels1)
    normPix1 = pixels1-min(pixels1[:])
    newPix1 = normPix1/max(normPix1)
    #print(res)
    newPix1 = newPix1.reshape(12*nside*nside)#*maxDose
    
    pixels2 = pixels2/max(pixels2)
    pixels2 = np.ravel(pixels2)
    normPix2 = pixels2-min(pixels2[:])
    newPix2 = normPix2/max(normPix2)
    #print(res)
    newPix2 = newPix2.reshape(12*nside*nside)#*maxDose
    
    pixels3 = pixels3/max(pixels3)
    pixels3 = np.ravel(pixels3)
    normPix3 = pixels-min(pixels3[:])
    newPix3 = normPix3/max(normPix3)
    #print(res)
    newPix3 = newPix3.reshape(12*nside*nside)#*maxDose
    
    latra = [-90,90]
    lonra = [-180,180]
    p = hp.cartview(newPix, rot=(90,-90), lonra=lonra,latra=latra, return_projected_map=True)
    hp.projplot(hp.pix2ang(16,hpindex-1), 'k*', markersize = 8)
    a = len(p[0,:])
    b = len(p[:,0])
    maxR = 0
    maxC = 0
    histRow = []
    histCol = []
    count = 0
    rowArg = 0
    for row in p:
        count += 1
        if max(row) > maxR: #row.mean() > maxR:
            histRow = row
            maxR = row.mean()
            rowArg = count

    count = 0
    colArg = 0
    for column in p:
        count += 1
        if max(column) > maxC: #column.mean() > maxC:
            histCol = column
            maxC = column.mean()
            colArg = count

    radAng = np.linspace(-180,180,a)
    azAng = np.linspace(-90,90,a)
    #print(radAng)
    #print(histCol)
    #print(np.size(histCol))
    #unitRow = np.linalg.norm(histRow)
    histRow = histRow/max(histRow)#(histRow - np.mean(histRow))/np.std(histRow)
    #unitCol = np.linalg.norm(histCol)
    histCol = histCol/max(histCol)
        
    #res = np.histogram(newPix,100)
    print(rowArg)
    print(colArg)
    #hp.graticule()
    plt.close("all")
    plt.figure()
    p = plt.imshow(p, cmap=cmap_, origin='lower', interpolation='nearest', extent=(lonra[1],lonra[0],latra[0],latra[1]))
    #plt.scatter(phi, 90-theta, marker='x')
    plt.xlim(lonra[0], lonra[1]); plt.ylim(latra[0], latra[1])
    plt.colorbar(p, fraction=0.046, pad=0.04)
    plt.title('Neutron Image of PuBe Source')
    plt.xlabel('Radial Angle [degrees]')
    plt.ylabel('Azimuthal Angle [degrees]')
    plt.xticks([-180,-135,-90,-45,0,45,90,135,180])
    plt.yticks([-90,-45,0,45,90])
    plt.plot([rowArg, rowArg], [0, len(histCol)], 'k-', lw=4)
    plt.plot([colArg, colArg], [0, len(histRow)], 'k-', lw=2)
    #plt.xticks([-270,-225,-180,-135,-90,-45,0,45,90])
    #plt.yticks([0,45,90,135,180])
    plt.show()

#    p1 = hp.cartview(newPix1, rot=(90,-90), lonra=lonra,latra=latra, return_projected_map=True)
#    hp.projplot(hp.pix2ang(16,hpindex-1), 'k*', markersize = 8)
#    p1 = hp.cartview(p1, rot=(90,-90), lonra=lonra,latra=latra, return_projected_map=True)
#    plt.close("all")
#    plt.figure()
#    p1 = plt.imshow(p1, cmap=cmap_, origin='lower', interpolation='nearest', extent=(lonra[1],lonra[0],latra[0],latra[1]))
        #plt.scatter(phi, 90-theta, marker='x')
#    plt.xlim(lonra[0], lonra[1]); plt.ylim(latra[0], latra[1])
#    plt.colorbar(p, fraction=0.046, pad=0.04)
#    plt.title('Neutron Image of PuBe Source - 3320 Card 1')
#    plt.xlabel('Radial Angle [degrees]')
#    plt.ylabel('Azimuthal Angle [degrees]')
#    plt.xticks([-180,-135,-90,-45,0,45,90,135,180])
#    plt.yticks([-90,-45,0,45,90])
#    plt.plot([rowArg, rowArg], [0, len(histCol)], 'k-', lw=4)
#    plt.plot([colArg, colArg], [0, len(histRow)], 'k-', lw=2)
    #plt.xticks([-270,-225,-180,-135,-90,-45,0,45,90])
    #plt.yticks([0,45,90,135,180])
    plt.show()
    if coneVector2 != 0:
        p2 = hp.cartview(newPix2, rot=(90,-90), lonra=lonra,latra=latra, return_projected_map=True)
        plt.close("all")
        plt.figure()
        p2 = plt.imshow(p2, cmap=cmap_, origin='lower', interpolation='nearest', extent=(lonra[1],lonra[0],latra[0],latra[1]))
        #plt.scatter(phi, 90-theta, marker='x')
        plt.xlim(lonra[0], lonra[1]); plt.ylim(latra[0], latra[1])
        plt.colorbar(p, fraction=0.046, pad=0.04)
        plt.title('Neutron Image of PuBe Source - 3320 Card 2')
        plt.xlabel('Radial Angle [degrees]')
        plt.ylabel('Azimuthal Angle [degrees]')
        plt.xticks([-180,-135,-90,-45,0,45,90,135,180])
        plt.yticks([-90,-45,0,45,90])
        plt.plot([rowArg, rowArg], [0, len(histCol)], 'k-', lw=4)
        plt.plot([colArg, colArg], [0, len(histRow)], 'k-', lw=2)
    #plt.xticks([-270,-225,-180,-135,-90,-45,0,45,90])
    #plt.yticks([0,45,90,135,180])
        plt.show()
    if coneVector3 != 0: 
        p3 = hp.cartview(newPix3, rot=(90,-90), lonra=lonra,latra=latra, return_projected_map=True)
        plt.close("all")
        plt.figure()
        p3 = plt.imshow(p3, cmap=cmap_, origin='lower', interpolation='nearest', extent=(lonra[1],lonra[0],latra[0],latra[1]))
        #plt.scatter(phi, 90-theta, marker='x')
        plt.xlim(lonra[0], lonra[1]); plt.ylim(latra[0], latra[1])
        plt.colorbar(p, fraction=0.046, pad=0.04)
        plt.title('Neutron Image of PuBe Source - 3320 Card 3')
        plt.xlabel('Radial Angle [degrees]')
        plt.ylabel('Azimuthal Angle [degrees]')
        plt.xticks([-180,-135,-90,-45,0,45,90,135,180])
        plt.yticks([-90,-45,0,45,90])
        plt.plot([rowArg, rowArg], [0, len(histCol)], 'k-', lw=4)
        plt.plot([colArg, colArg], [0, len(histRow)], 'k-', lw=2)
        #plt.xticks([-270,-225,-180,-135,-90,-45,0,45,90])
        #plt.yticks([0,45,90,135,180])
        plt.show()
    
    max_r = max(histRow)  # Find the maximum y value
    xr = [x for x in range(len(histRow)) if histRow[x] > max_r/2.0]
    print(min(xr), max(xr))
    azFWHM = radAng[max(xr)]-radAng[min(xr)]
    print('radAng1 = ',radAng[max(xr)])
    print('radAng2 = ', radAng[min(xr)])
    print('radFWHM = ', azFWHM)
    max_c = max(histCol)
    xc = [x for x in range(len(histCol)) if histCol[x] > max_c/2.0]
    radFWHM = azAng[max(xc)] - azAng[min(xr)]
    print('azFWHM = ', radFWHM)
    plt.figure()
    plt.title('Radial Resolution = %f degrees'%radFWHM)
    plt.xlabel('Radial Angle [degrees]')
    plt.plot(radAng,histCol)
    plt.show()
    print(len(histRow))
    print(len(azAng))
    plt.figure()
    plt.title('Azimuthal Resolution = %f degrees'%azFWHM)
    plt.xlabel('Azimuthal Angle [degrees]')
    plt.plot(azAng,histRow)
    return neutronEnergy
    
Exemple #15
0
    def plot_sky(self, showgrid=True, **kwargs):
        """plot: horizon, galactic plane, sun and moon

        Parameters
        ----------        
        Healpix graticule Parameters
        """
        kwargs = self.setkeys(kwargs)
        r = hp.Rotator(
            deg=True,
            rot=[kwargs['rot_theta'], kwargs['rot_phi'], kwargs['rot_psi']])

        # create figure
        fig = self._init_figure(**kwargs)
        if showgrid:
            self._grid(**kwargs)
            self.plot_coord(rot=[
                kwargs['rot_theta'], kwargs['rot_phi'], kwargs['rot_psi']
            ],
                            **kwargs)

        # plot the galactic plane
        ra = np.arange(0, 360, 10)
        dec = np.zeros(len(ra))

        thetal, phil = [], []
        for _ra, _dec in zip(ra, dec):

            # from galactic coordinates to equatorial
            _radecs = astropy.coordinates.SkyCoord(l=_ra * u.deg,
                                                   b=_dec * u.deg,
                                                   frame='galactic')

            # transform to theta phi
            _ra, _dec = _radecs.icrs.ra.deg, _radecs.icrs.dec.deg
            _theta, _phi = np.pi / 2. - np.radians(_dec), np.radians(_ra)
            thetal.append(_theta)
            phil.append(_phi)

        kwargs['color'] = 'k'
        kwargs['marker'] = 'x'
        kwargs['label'] = 'galactic plane'
        thetal, phil = r(thetal, phil)
        self.projplot(thetal, phil, **kwargs)

        if 'obstime' in self.__dict__:
            assert isinstance(self.obstime, astropy.time.Time)

            # plot the sun
            _sra,_sdec = astropy.coordinates.get_sun(self.obstime).ra.deg,\
                astropy.coordinates.get_sun(self.obstime).dec.deg
            _stheta, _sphi = np.pi / 2. - np.radians(_sdec), np.radians(_sra)

            # visualization
            kwargs['color'] = 'y'
            _stheta, _sphi = r(_stheta, _sphi)
            hp.projtext(_stheta,
                        _sphi,
                        '$\odot$',
                        lonlat=False,
                        **self.getkeys(kwargs, 'projtext'))

            # plot the moon
            for _nd in np.arange(0, 5, 1):
                _timeplus = _nd * 24
                timelater = self.obstime + astropy.time.TimeDelta(
                    _timeplus * 3600, format='sec')
                _mra,_mdec = astropy.coordinates.get_moon(timelater).ra.deg,\
                    astropy.coordinates.get_moon(timelater).dec.deg
                _mtheta, _mphi = np.pi / 2. - np.radians(_mdec), np.radians(
                    _mra)

                # visualization
                kwargs['color'] = 'b'
                _mtheta, _mphi = r(_mtheta, _mphi)
                hp.projtext(_mtheta,
                            _mphi,
                            '$\oplus$',
                            lonlat=False,
                            **self.getkeys(kwargs, 'projtext'))
                hp.projtext(_mtheta,
                            _mphi - .1,
                            '%id' % _nd,
                            lonlat=False,
                            **self.getkeys(kwargs, 'projtext'))

            # write labels
            xx, yy = -1.5, 1.
            plt.text(xx, .9, 'sun: $\odot$',fontsize=20,\
                     ha="center", va="center", color='y')
            plt.text(xx, 1., 'moon: $\oplus$',fontsize=20,\
                     ha="center", va="center", color='b')

        # plot the horizon for each observatories
        if not 'observatories' in self.__dict__: return
        for obs in self.observatories:

            for tel in self.observatories[obs]:

                name, lat, lon, alt = tel.name, tel.conf['lat'], tel.conf[
                    'lon'], tel.conf['alt']
                # define observatory
                observatory = astropy.coordinates.EarthLocation(
                    lat=lat * u.deg, lon=lon * u.deg, height=alt * u.m)
                _smlabel = True
                for _timedelta in np.arange(0, 360, 1):
                    AltAzcoordiantes = astropy.coordinates.SkyCoord(
                        alt=0 * u.deg,
                        az=0 * u.deg + _timedelta * u.deg,
                        obstime=obstime,
                        frame='altaz',
                        location=observatory)
                    ra, dec = AltAzcoordiantes.icrs.ra.deg, AltAzcoordiantes.icrs.dec.deg
                    theta, phi = np.pi / 2. - np.radians(dec), np.radians(ra)
                    if _smlabel:
                        hp.projplot(theta,phi,'.', color = _colorlist[nt], \
                                    coord=coord, ms = 2, label='%s horizon now'%name)
                        _smlabel = False
                    else:
                        hp.projplot(theta,phi,'.', color = _colorlist[nt], \
                                    coord=coord, ms = 2)
Exemple #16
0
def coverage(params, map_struct, coverage_struct, catalog_struct=None):

    unit = 'Gravitational-wave probability'
    cbar = False

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        if patch == []:
            continue

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

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

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

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

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

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

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

                if patch == []:
                    continue

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

        moviefiles = os.path.join(moviedir, "coverage-%04d.png")
        filename = os.path.join(params["outputDir"], "coverage.mpg")
        ffmpeg_command = 'ffmpeg -an -y -r 20 -i %s -b:v %s %s' % (
            moviefiles, '5000k', filename)
        os.system(ffmpeg_command)
        filename = os.path.join(params["outputDir"], "coverage.gif")
        ffmpeg_command = 'ffmpeg -an -y -r 20 -i %s -b:v %s %s' % (
            moviefiles, '5000k', filename)
        os.system(ffmpeg_command)
        rm_command = "rm %s/*.png" % (moviedir)
        os.system(rm_command)
                unit='Stars per sq. arcmin.',
                cbar=True,
                nest=nest,
                title='',
                coord=coordsys,
                notext=False,
                cmap=cm,
                flip='astro',
                nlocs=4)

# borders
lw = 3
pi = np.pi
dtor = pi / 180.
theta = np.arange(0, 181) * dtor
hp.projplot(theta, theta * 0 - pi, '-k', lw=lw, direct=True)
hp.projplot(theta, theta * 0 + 0.9999 * pi, '-k', lw=lw, direct=True)
phi = np.arange(-180, 180) * dtor
hp.projplot(phi * 0 + 1.e-10, phi, '-k', lw=lw, direct=True)
hp.projplot(phi * 0 + pi - 1.e-10, phi, '-k', lw=lw, direct=True)

# galaxy
for gallat in [15, 0, -15]:
    theta = np.arange(0., 360, 0.036)
    phi = gallat * np.ones_like(theta)
    hp.projplot(theta, phi, 'w-', coord=['G'], lonlat=True, lw=2)

# ecliptic
for ecllat in zip([0, -30, 30], [2, 1, 1]):
    theta = np.arange(0., 360, 0.036)
    phi = gallat * np.ones_like(theta)
Exemple #18
0
def main(argv):

    _path = os.path.expanduser('~/Develop/SMAPs/')

    file_area = [  'dcorr_smpas_obstime_2_area12.fits'
                  ,'dcorr_smpas_obstime_2_area18.fits'
                  ,'dcorr_smpas_obstime_2_area6.fits']
    
    nna_file = os.path.expanduser('~/Develop/SMAPs/coordinatesystemandtiling/norpointT80.dat')
    nsa_file = os.path.expanduser('~/Develop/SMAPs/coordinatesystemandtiling/surpointT80.dat')
	
    smaps_sul = os.path.expanduser('~/Develop/SMAPs/smaps_pointsulT80.dat')
    smaps_nor = os.path.expanduser('~/Develop/SMAPs/smaps_pointT80norte.dat')


    #
    # Reading data
    #

    map_area = np.array([H.read_map(os.path.join(_path,file_area[0])),])

    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
    #


    ##
    ## This is best area cut observability
    ##

    plmap = np.zeros(map_area.shape[1])

    #for i in range(3):
    #    plmap += map_area[i]
    #
    #H.mollview(plmap,fig=1,title='secz < 1.5',coord=['G','E'],sub=(1,2,4),cbar=False,notext=True,max=3.5)
    #
    #plmap = np.zeros(map_area.shape[1])

    for i in range(len(map_area)):
        plmap += map_area[i]
    
    # make a color map of fixed colors
    cmap = colors.ListedColormap(['grey', 'blue', 'green', 'red'])

    H.mollview(plmap,coord=['G','E'],cmap=cmap,cbar=False,notext=True,title='S-MAPS Survey Area Selection')#,rot=(0,-90,90))#, norm=norm)
    #H.cartview(plmap,coord='G',cmap=cmap,cbar=False,notext=True,title='S-MAPS Survey Area Selection')#, norm=norm)
    H.graticule()

    nna_pt = np.loadtxt(nna_file,unpack=True,usecols=(4,5))
    nsa_pt = np.loadtxt(nsa_file,unpack=True,usecols=(4,5))

    pt_smaps_sul = np.loadtxt(smaps_sul,unpack=True,usecols=(4,5))
    pt_smaps_nor = np.loadtxt(smaps_nor,unpack=True,usecols=(4,5))

	
    #myPatches=[]

    #for i in range(len(nna_pt[0])):
    #    r2 = patches.RegularPolygon(((90-nna_pt[1][i])*np.pi/180.,nna_pt[0][i]*np.pi/180.),4,0.573*np.pi,orientation=45*np.pi/180.)
    #    myPatches.append(r2)
	

	#collection = PatchCollection(myPatches,alpha=0.5)
	#H.add_collection(collection)

    H.projplot((90-nna_pt[1])*np.pi/180.,nna_pt[0]*np.pi/180.,'.',color='w',alpha=0.5)#,coord=['E','G'])
    H.projplot((90-nsa_pt[1])*np.pi/180.,nsa_pt[0]*np.pi/180.,'.',color='w',alpha=0.5)#,coord=['E','G'])

    H.projplot((90-pt_smaps_sul[1])*np.pi/180.,pt_smaps_sul[0]*np.pi/180.,'.',color='k',alpha=0.5)#,coord=['E','G'])
    H.projplot((90-pt_smaps_nor[1])*np.pi/180.,pt_smaps_nor[0]*np.pi/180.,'.',color='k',alpha=0.5)#,coord=['E','G'])

    #
    # Area 1 - SGH
    #
    #sgh_x = [ [135,180] , [135, 120] , [ 120 , 105] , [ 105 ,  80] , [80 , 105] , [105]       , [105 , 180] ]
    #sgh_y = [ [100]     , [100 , 40] , [ 40 ]       , [ 40  , -55] , [-55, -60] , [-60 , -85] , [-85 ]
	    
    sgh_x = [ [135,180] , [135, 120] , [ 120 , 113.] , [ 113. ,  100] , [100 , 112] , [112]       , [112 , 180] ]
    sgh_y = [ [85]     , [85 , 25] , [ 25 ]       , [ 25  , -40] , [ -40] , [-40 , -65] , [-65 ]      ]
    
    #plotArea(sgh_x,sgh_y)
    
    #ngh_x1 = [ [135, 125] , [125,100] , [55,100]]
    #ngh_y1 = [ [180,130] , [130, 110] , [179,110]]

    ngh_x1 = [ [115] , [115,80] , [80]]
    ngh_y1 = [ [180,160] , [160] , [179.9,160]]

    #plotArea(ngh_x1,ngh_y1)

	#ngh_x2 = [ [135, 115]  , [115,55] , [55]]
    #ngh_y2 = [ [-180,-130] , [-130, -115] , [-115,-180]]

    ngh_x2 = [ [115] , [90,115] , [90]  , [90,65] , [65]]
    ngh_y2 = [ [-165,-180] , [-165] , [-165,-150] , [-150] , [-150,-180]]

	#plotArea(ngh_x2,ngh_y2)
	
    x1 = np.zeros(100)+np.pi/2. #np.linspace(0,np.pi/2.,100)
    y1 = np.linspace(-np.pi,np.pi,100)
    H.projplot(x1,y1,'w',lw=2.,coord=['G','E'])#,rot=(0,-90,90),coord=['G','E'])
    #H.projplot([0],[np.pi/2.],'ko',lw=2.,coord=['G','E'])#,rot=(0,-90,90),coord=['G','E'])
    H.projplot([192.859508],[27.128336],'ko',lw=2.,coord=['E'],lonlat=True)#,rot=(0,-90,90),coord=['G','E'])
    H.projplot([192.859508-180],[-27.128336],'wo',lw=2.,coord=['E'],lonlat=True)#,rot=(0,-90,90),coord=['G','E'])
    #H.projplot([-np.pi],[np.pi/2.],'wo',lw=2.,coord=['G','E'])#,rot=(0,-90,90),coord=['G','E'])
    #H.projplot([-np.pi],[0],'wo',lw=2.,coord=['G','E'])#,rot=(0,-90,90),coord=['G','E'])
#    ngh_x2 = [ [135, 115]  , [90, 115], [90,55] , [55]]
#    ngh_y2 = [ [-180,-120] , [-140, -120 ], [-140, -115] , [-115,-180]]
	
#    plotArea(ngh_x2,ngh_y2)
    py.savefig(os.path.join(_path,'Figures/areaSelection.pdf'))

    py.show()
Exemple #19
0
fig, (ax1, ax2) = plt.subplots(ncols=2)

plt.axes(ax1)
hp.mollview(np.random.random(hp.nside2npix(32)), hold=True)

plt.axes(ax2)
hp.mollview(np.arange(hp.nside2npix(32)), hold=True)

'''
'''
https://stackoverflow.com/questions/57560428/aitoff-projections-using-healpy-and-projplot/57561507#57561507
'''

import healpy as hp
import numpy as np

nside = 64
npix = hp.nside2npix(nside)
arr = np.random.randn(npix)

# Draw a circle
r = np.full(100, 20.)
phi = np.linspace(0., 2 * np.pi, 100)
x = np.cos(phi) * r
y = np.sin(phi) * r

# Plot the map and the circle
hp.mollview(arr)
hp.projplot(x, y, c='r', lonlat=True)
Exemple #20
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()
Exemple #21
0
def plot_zoom_from_map(skymap,
                       ind,
                       reso=1.,
                       cmap=None,
                       draw_contour=True,
                       ax=None,
                       col_label=r'$\log_{10}$(prob.)'):
    """Plot skymap of an alert event
    
    Args:
        skymap (arr): healpy array
        index (int): Alert event index 
    """
    s, header = hp.read_map(skymap_files[ind], h=True, verbose=False)
    header = {name: val for name, val in header}
    nside = hp.get_nside(s)
    area = np.count_nonzero(
        s < 64.2) * hp.nside2pixarea(nside) * 180.**2. / (np.pi**2.)
    reso *= int(np.sqrt(area))
    reso = np.max([reso, 1.])
    original_LLH = s
    ra = np.radians(header['RA'])
    dec = np.radians(header['DEC'])
    title = skymap_files[ind][l_ind:r_ind].replace('Run', 'Run ').replace(
        '_', ', Event ')
    if cmap is None:
        pdf_palette = sns.color_palette("Blues", 500)
        cmap = mpl.colors.ListedColormap(pdf_palette)
    if np.count_nonzero(skymap > 0.0) > 1:
        max_color = np.max(skymap)
        min_color = 0.
    else:
        max_color = -1.8  #5 #max(skymap)
        min_color = -5.  #0.

    hp.gnomview(skymap,
                rot=(np.degrees(ra), np.degrees(dec), 0),
                cmap=cmap,
                max=max_color,
                min=min_color,
                reso=reso,
                title=title,
                notext=True,
                cbar=False
                #unit=r""
                )

    plt.plot(4.95 / 3. * reso * np.radians([-1, 1, 1, -1, -1]),
             4.95 / 3. * reso * np.radians([1, 1, -1, -1, 1]),
             color="k",
             ls="-",
             lw=3)
    hp.graticule(verbose=False)
    steady_sensitivity_fits.plot_labels(dec, ra, reso)
    con_nside = 256 if area < 5. else 128
    if draw_contour:
        contours = steady_sensitivity_fits.plot_contours(None,
                                                         original_LLH,
                                                         levels=[22.2, 64.2],
                                                         nside=con_nside)
        for contour in np.array(contours).T:
            hp.projplot(contour[0], contour[1], linewidth=1.5, c='k')
    steady_sensitivity_fits.plot_color_bar(cmap=cmap,
                                           labels=[min_color, max_color],
                                           col_label=col_label)
Exemple #22
0
def plot_gwmap(lvc_healpix_file, levels=[0.5, 0.9]):
    """Plot the GW map with the DESI footprint.
    
    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.
    
    Returns
    -------
    fig : matplotlib.Figure
        Figure object for accessing or saving a plot.
    """
    # Read metadata from FITS.
    hdus = fits.open(lvc_healpix_file)
    header = hdus[1].header

    # instruments = header['INSTRUME']
    distmean = header['DISTMEAN']
    diststd = header['DISTSTD']
    origin = header['ORIGIN']
    date = header['DATE']

    # Read HEALPix map.
    gwmap = hp.read_map(lvc_healpix_file)

    # Compute GW contours.
    prob64 = hp.pixelfunc.ud_grade(gwmap, 64)  #reduce nside to make it faster
    prob64 = prob64 / np.sum(prob64)
    pixels = np.arange(prob64.size)
    ra_contour, dec_contour = compute_contours(levels, prob64)

    cmap = mpl.cm.OrRd
    cmap.set_under('w')

    # Access DESI contours.
    nside = hp.pixelfunc.get_nside(gwmap)
    desi_mask = hp.read_map('desi_mask_nside{:04d}.fits'.format(nside))
    probs = np.copy(gwmap)
    probs[desi_mask == 0] = hp.UNSEEN

    hp.mollview(probs,
                cbar=True,
                unit=r'probability',
                title='{} {}'.format(origin, date),
                min=0,
                max=2e-4,
                flip='astro',
                rot=180,
                cmap=cmap)
    hp.graticule(ls=':', alpha=0.5, dpar=30, dmer=45)

    ramin, ramax = 1e99, -1e99
    decmin, decmax = 1e99, -1e99
    for i, (rc, dc) in enumerate(zip(ra_contour, dec_contour)):
        ramin = np.minimum(ramin, np.min(rc))
        ramax = np.maximum(ramax, np.max(rc))
        decmin = np.minimum(decmin, np.min(dc))
        decmax = np.maximum(decmax, np.max(dc))
        hp.projplot(rc, dc, lonlat=True, linewidth=1, c='k')

    logging.info(
        'RA_min={:.1f}, RA_max={:.1f}, Dec_min={:.1f}, Dec_max={:.1f}'.format(
            ramin, ramax, decmin, decmax))

    ax = plt.gca()

    # Label latitude lines.
    ax.text(2.00, 0.10, r'$0^\circ$', horizontalalignment='left')
    ax.text(1.80, 0.45, r'$30^\circ$', horizontalalignment='left')
    ax.text(1.30, 0.80, r'$60^\circ$', horizontalalignment='left')
    ax.text(1.83, -0.45, r'$-30^\circ$', horizontalalignment='left')
    ax.text(1.33, -0.80, r'$-60^\circ$', horizontalalignment='left')
    ax.text(-2.00, 0.10, r'$0^\circ$', horizontalalignment='right')
    ax.text(-1.80, 0.45, r'$30^\circ$', horizontalalignment='right')
    ax.text(-1.30, 0.80, r'$60^\circ$', horizontalalignment='right')
    ax.text(-1.85, -0.45, r'$-30^\circ$', horizontalalignment='right')
    ax.text(-1.35, -0.80, r'$-60^\circ$', horizontalalignment='right')

    # Label longitude lines.
    ax.text(2.0, -0.15, r'0$^\mathrm{h}$', horizontalalignment='center')
    ax.text(1.5, -0.15, r'3$^\mathrm{h}$', horizontalalignment='center')
    ax.text(1.0, -0.15, r'6$^\mathrm{h}$', horizontalalignment='center')
    ax.text(0.5, -0.15, r'9$^\mathrm{h}$', horizontalalignment='center')
    ax.text(0.0, -0.15, r'12$^\mathrm{h}$', horizontalalignment='center')
    ax.text(-0.5, -0.15, r'15$^\mathrm{h}$', horizontalalignment='center')
    ax.text(-1.0, -0.15, r'18$^\mathrm{h}$', horizontalalignment='center')
    ax.text(-1.5, -0.15, r'21$^\mathrm{h}$', horizontalalignment='center')
    ax.text(-2.0, -0.15, r'24$^\mathrm{h}$', horizontalalignment='center')

    fig = plt.gcf()
    return fig
Exemple #23
0
def plotseqmap(
        A,
        frames,
        tag="map",
        title=None,
        zero=True,
        vmin=None,
        vmax=None,
        cmap=plt.cm.pink,
        Earth=False,
        boundary_data="/home/kawahara/exomap/sot/data/earth_boundary.npz",
        color="#66CC99",
        png=True,
        pdf=True,
        show=False):
    if Earth:
        thetaE, phiE = bound_earth(boundary_data)

    if title is None or len(title) != len(frames):
        print("No title or mismatch")
        title = []
        for i in frames:
            title.append("")
    if zero:
        A[A == 0.0] = None
    if np.shape(np.shape(A))[0] == 2:
        j = 0
        for i in tqdm(frames):
            if vmin is None:
                hp.mollview(A[i, :], title=title[j], flip="geo", cmap=cmap)
                if Earth:
                    hp.projplot(thetaE, phiE, ".", c=color)

            else:
                hp.mollview(A[i, :],
                            title=title[j],
                            flip="geo",
                            cmap=cmap,
                            min=vmin,
                            max=vmax)
                if Earth:
                    hp.projplot(thetaE, phiE, ".", c=color, alpha=0.5)
            if png:
                plt.savefig("png/" + tag + str(i) + ".png")
            if pdf:
                plt.savefig("pdf/" + tag + str(i) + ".pdf")
            if show:
                plt.show()
            plt.close()
            j = j + 1

    elif np.shape(np.shape(A))[0] == 3:
        import plotmap
        Nk = np.shape(A)[2]
        j = 0
        for i in tqdm(frames):
            tagc = tag + "c" + str(i)
            plotmap.classmap_color(A[i, :, :],
                                   title=title[j],
                                   theme="3c",
                                   pdfname="pdf/" + tagc + ".pdf",
                                   pngname="png/" + tagc + ".png")
            for k in range(0, Nk):
                if vmin is None:
                    hp.mollview(A[i, :, k],
                                title=title[j],
                                flip="geo",
                                cmap=cmap)
                else:
                    hp.mollview(A[i, :, k],
                                title=title[j],
                                flip="geo",
                                cmap=cmap,
                                min=vmin,
                                max=vmax)
                if png:
                    plt.savefig("png/" + tag + str(i) + "_" + str(k) + ".png")
                if pdf:
                    plt.savefig("pdf/" + tag + str(i) + "_" + str(k) + ".pdf")
                if show:
                    plt.show()

                plt.close()
            j = j + 1
    else:
        print("It's not dynamic map! shape=", np.shape(np.shape(A))[0])
Exemple #24
0
def main():

	_path = os.path.expanduser('~/Develop/SMAPs/')

	file_area = [  'lambda_sfd_ebv.fits' ]

	nna_file = os.path.expanduser('~/Develop/SMAPs/coordinatesystemandtiling/norpointT80.dat')
	nsa_file = os.path.expanduser('~/Develop/SMAPs/coordinatesystemandtiling/surpointT80.dat')

	smaps_sul = os.path.expanduser('~/Develop/SMAPs/smaps_pointsulT80.dat')
	smaps_nor = os.path.expanduser('~/Develop/SMAPs/smaps_pointT80norte.dat')
	smaps_lmc = os.path.expanduser('~/Develop/SMAPs/coordinatesystemandtiling/foo3')
	smaps_smc = os.path.expanduser('~/Develop/SMAPs/coordinatesystemandtiling/foo')
	
	allnovae = os.path.expanduser('~/Develop/SMAPs/coordinatesystemandtiling/allnovae.txt')
	spp = os.path.expanduser('~/Develop/SMAPs/splus_varregions.dat')
	#
	# Reading data
	#

	map_area = np.array([H.read_map(os.path.join(_path,file_area[0])),])

	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
	#


	##
	## This is best area cut observability
	##

	plmap = np.zeros(map_area.shape[1])

	cmap = colors.ListedColormap(['gray', 'blue', 'white', 'red'])

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

	# LMC
	#81.2102 -75.2561
	#H.projplot([(90+80.75)*np.pi/180.],[-69.5*np.pi/180.],'ko')
	#H.projplot([(90+81.2102)*np.pi/180.],[-75.2561*np.pi/180.],'ko')

	# SMC
	#302.8084 -44.3277
	#H.projplot([(90+13.0)*np.pi/180.],[-72.5*np.pi/180.],'ko')
	#H.projplot([302.8*np.pi/180.],[44.3*np.pi/180.],'wo')#,coord=['G','E'])
	
	#
	# 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)+95.*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,'w-',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,'w-',lw=2,coord=['G','E'])

	#GAMA09:  08h36 < RA < 09h24,      -2 < Dec < +3 deg.
	
	
	nna_pt = np.loadtxt(nna_file,unpack=True,usecols=(4,5))
	nsa_pt = np.loadtxt(nsa_file,unpack=True,usecols=(4,5))

	pt_smaps_sul = np.loadtxt(smaps_sul,unpack=True,usecols=(4,5))
	pt_smaps_nor = np.loadtxt(smaps_nor,unpack=True,usecols=(4,5))
	pt_allnovae = np.loadtxt(allnovae,unpack=True)
	pt_spp = np.loadtxt(spp,unpack=True,usecols=(4,5))
	#pt_smaps_smc = np.loadtxt(smaps_smc,unpack=True)

	#myPatches=[]

	#for i in range(len(nna_pt[0])):
	#    r2 = patches.RegularPolygon(((90-nna_pt[1][i])*np.pi/180.,nna_pt[0][i]*np.pi/180.),4,0.573*np.pi,orientation=45*np.pi/180.)
	#    myPatches.append(r2)


	#collection = PatchCollection(myPatches,alpha=0.5)
	#H.add_collection(collection)

	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_allnovae[1])*np.pi/180.,pt_allnovae[0]*np.pi/180.,'o',color='r',alpha=1,coord='E')#,coord=['E','G'])

	H.projplot((90-pt_smaps_sul[1])*np.pi/180.,pt_smaps_sul[0]*np.pi/180.,'.',color='r',alpha=0.8,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
	# ATLAS

	for line in np.arange(10,40,0.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.5)
	H.projplot((90-np.zeros(100)+40)*np.pi/180.,(np.linspace(-37.5,60,100))*np.pi/180.,'-',color='g',lw=2)
	H.projplot((90-np.zeros(100)+10)*np.pi/180.,(np.linspace(-37.5,60,100))*np.pi/180.,'-',color='g',lw=2)
	H.projplot((90-np.linspace(-40,-10,100))*np.pi/180.,(np.zeros(100)+60)*np.pi/180.,'-',color='g',lw=2)
	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,0.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.5)
		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.5)
		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.5)
		
	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)

	# 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,-30,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)

	# 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)+30)*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,30,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)

	#
	## 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)


	H.graticule()
	
	py.show()
Exemple #25
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()
def main():

    # Load the map input files
    spt3g_map = hp.read_map(spt3g_infile)
    spt3g_map[np.logical_not(np.isfinite(spt3g_map))] = 0.0
    spt3g_map /= np.max(spt3g_map)

    bk_map = hp.read_map(bk_infile)
    bk_map[np.logical_not(np.isfinite(bk_map))] = 0.0
    bk_map /= np.max(bk_map)

    ba_map = hp.read_map(ba_infile)
    ba_map[np.logical_not(np.isfinite(ba_map))] = 0.0
    ba_map /= np.max(ba_map)

    planck_map = hp.read_map(planck_353)

    # Put the planck map in celestial coords like everything else
    rotate = hp.Rotator(coord='CG')
    pixnums = np.arange(planck_map.shape[0])
    t, p = hp.pix2ang(hp.npix2nside(planck_map.shape[0]), pixnums)
    trot, prot = rotate(t, p)
    reordering = hp.pixelfunc.ang2pix(hp.npix2nside(planck_map.shape[0]), trot,
                                      prot)
    planck_map = planck_map[reordering]

    square_deg_sphere = 4 * np.pi * (180.0 / np.pi)**2

    # Now let's compute fsky numbers, all in square degrees
    bk_signal = weight_to_fsky(bk_map, mode='signal') * square_deg_sphere
    bk_noise = weight_to_fsky(bk_map, mode='noise') * square_deg_sphere
    bk_clem = weight_to_fsky(bk_map, mode='clem') * square_deg_sphere
    print('BK apodization mask fsky numbers %s / %s / %s S/N/C' %
          (bk_signal, bk_noise, bk_clem))

    ba_signal = weight_to_fsky(ba_map, mode='signal') * square_deg_sphere
    ba_noise = weight_to_fsky(ba_map, mode='noise') * square_deg_sphere
    ba_clem = weight_to_fsky(ba_map, mode='clem') * square_deg_sphere
    print('BA apodization mask fsky numbers %s / %s / %s S/N/C' %
          (ba_signal, ba_noise, ba_clem))

    spt3g_signal = weight_to_fsky(spt3g_map, mode='signal') * square_deg_sphere
    spt3g_noise = weight_to_fsky(spt3g_map, mode='noise') * square_deg_sphere
    spt3g_clem = weight_to_fsky(spt3g_map, mode='clem') * square_deg_sphere
    print('BA apodization mask fsky numbers %s / %s / %s S/N/C' %
          (spt3g_signal, spt3g_noise, spt3g_clem))

    # Now let's turn this fsky into fractions of the apodization mask using the signal definition
    bk_thresh = (np.sort(bk_map)[::-1])[int(bk_clem / square_deg_sphere *
                                            float(bk_map.shape[0]))]
    ba_thresh = (np.sort(ba_map)[::-1])[int(ba_clem / square_deg_sphere *
                                            float(ba_map.shape[0]))]
    spt3g_thresh = (np.sort(spt3g_map)[::-1])[int(
        spt3g_signal / square_deg_sphere * float(spt3g_map.shape[0]))]
    print('Weight thresholds %f %f %f' % (bk_thresh, ba_thresh, spt3g_thresh))

    # Now, let's plot things
    hp.mollview(-1.0 * planck_map, norm='hist', rot=None, cmap=cm.gray)
    # Compute contours
    spt3g_boundary = compute_contours([spt3g_thresh], spt3g_map)
    bk_boundary = compute_contours([bk_thresh], bk_map)
    ba_boundary = compute_contours([ba_thresh], ba_map)

    np.savetxt('bicep_array_footprint.txt',
               np.transpose([ba_boundary[0], ba_boundary[1]]))

    # Plot contours
    hp.projplot(
        bk_boundary[0],
        bk_boundary[1],
        linewidth=2.0,
        color='r',
        linestyle='-.',
        coord='C',
        rot=None,
    )
    hp.projplot(
        ba_boundary[0],
        ba_boundary[1],
        linewidth=2.0,
        color='g',
        linestyle='--',
        coord='C',
        rot=None,
    )
    hp.projplot(
        spt3g_boundary[0],
        spt3g_boundary[1],
        linewidth=2.0,
        color='b',
        linestyle='-',
        coord='C',
        rot=None,
    )
    hp.graticule(True)
    title('Patch footprints')
    show()
Exemple #27
0
    def plot_skymap_zoom(self, with_contour=False, contour_files=None):
        r'''Make a zoomed in portion of a skymap with
        all neutrino events within a certain range
        '''
        events = self.llh.exp
        events = events[(events['time'] < self.stop) & (events['time'] > self.start)]

        col_num = 5000
        seq_palette = sns.color_palette("icefire", col_num)
        lscmap = mpl.colors.ListedColormap(seq_palette)

        rel_t = np.array((events['time'] - self.start) * col_num / (self.stop - self.start), dtype = int)
        cols = np.array([seq_palette[j] for j in rel_t])

        if self.skymap is not None:
            skymap = self.skymap
            ra = self.skymap_fit_ra
            dec = self.skymap_fit_dec
            label_str = "Scan Hot Spot"
            cmap = None
        else:
            skymap = np.zeros(hp.nside2npix(self._nside))
            ra = self.ra
            dec = self.dec
            label_str = self.name
            cmap = mpl.colors.ListedColormap([(1.,1.,1.)] * 50)

        plotting_utils.plot_zoom(skymap, ra, dec, "", range = [0,10], reso=3., cmap = cmap)

        if self.skipped is not None:
            try:
                msk = events['run'] == int(self.skipped[0][0])
                msk *= events['event'] == int(self.skipped[0][1])
                plotting_utils.plot_events(self.skipped_event['dec'], self.skipped_event['ra'], 
                    self.skipped_event['sigma']*self._angScale, 
                    ra, dec, 2*6, sigma_scale=1.0, constant_sigma=False, 
                    same_marker=True, energy_size=True, col = 'grey', 
                    with_dash=True)
                events = events[~msk]
                cols = cols[~msk]
            except:
                print("Removed event not in GFU")

        if (self.stop - self.start) <= 21.:
            plotting_utils.plot_events(events['dec'], events['ra'], events['sigma']*self._angScale, ra, dec, 2*6, sigma_scale=1.0,
                    constant_sigma=False, same_marker=True, energy_size=True, col = cols)
        else:
            #Long time windows means don't plot contours
            plotting_utils.plot_events(events['dec'], events['ra'], events['sigma']*self._angScale, ra, dec, 2*6, sigma_scale=None,
                    constant_sigma=False, same_marker=True, energy_size=True, col = cols)

        if contour_files is not None:
            cont_ls = ['solid', 'dashed']
            contour_counter = 0
            for c_file in contour_files:
                cont = np.loadtxt(c_file, skiprows=1)
                cont_ra = cont.T[0]
                cont_dec = cont.T[1]
                label = 'Millipede 50\%, 90\% (160427A syst.)' \
                    if contour_counter == 0 else ''
                hp.projplot(np.pi/2. - cont_dec, cont_ra, linewidth=3., 
                    color='k', linestyle=cont_ls[contour_counter], coord='C', 
                    label=label)
                contour_counter += 1
        
        if with_contour:
            probs = hp.pixelfunc.ud_grade(self.skymap, 64)
            probs = probs/np.sum(probs)
            ### plot 90% containment contour of PDF
            levels = [0.9]
            theta, phi = plotting_utils.plot_contours(levels, probs)
            hp.projplot(theta[0], phi[0], linewidth=2., c='k')
            for i in range(1, len(theta)):
                hp.projplot(theta[i], phi[i], linewidth=2., c='k', label=None)

        plt.scatter(0,0, marker='*', c = 'k', s = 130, label = label_str) 

        plt.legend(loc = 2, ncol=1, mode = 'expand', fontsize = 18.5, framealpha = 0.95)
        plotting_utils.plot_color_bar(range=[0,6], cmap=lscmap, col_label=r"IceCube Event Time",
                    offset=-50, labels = [r'-$\Delta T \Bigg/ 2$', r'+$\Delta T \Bigg/ 2$'])
        plt.savefig(self.analysispath + '/' + self.analysisid + 'unblinded_skymap_zoom.png',bbox_inches='tight')
        plt.savefig(self.analysispath + '/' + self.analysisid + 'unblinded_skymap_zoom.pdf',bbox_inches='tight', dpi=300)
        plt.close()
Exemple #28
0
def make_skyplot(moll=True,
                 ecliptic=False,
                 footprint=True,
                 idr2=True,
                 cmap='Greys',
                 title='test',
                 highlight=False,
                 highlight_survey='HYDRA',
                 highlight_tile='HYDRA_0011',
                 path='./',
                 bgmap='none'):
    # NOTES:
    # C = Celestial (Equatorial), G = Galactic, E = Ecliptic
    # if lonlat=True, then coords should be given in (lon,lat) with both in degrees

    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 = +3
            ra_positions = [
                0, 30, 60, 90, 120, 150, 210, 240, 270, 300, 330, 0, 0
            ]
            dec_positions = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 30, 60]
            labels = [
                '0h', '2h', '4h', '6h', '8h', '10h', '14h', '16h', '18h',
                '20h', '22h', '30', '60'
            ]
            for l in range(0, len(labels)):
                H.projtext(ra_positions[l] + dra,
                           dec_positions[l] + ddec,
                           labels[l],
                           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):
                add_skyplot_tile([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
            add_skyplot_tile([lon, lat],
                             tilesize,
                             'r',
                             Tile=True,
                             CenterPoints=False,
                             CornerPoints=False,
                             lw=2,
                             zorder=100)

    # 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))
                add_skyplot_tile([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
Exemple #29
0
    def plot_skymap(self, with_contour=False, contour_files=None):
        r''' Make skymap with event localization and all
        neutrino events on the sky within the given time window
        '''

        events = self.llh.exp
        events = events[(events['time'] < self.stop) & (events['time'] > self.start)]

        col_num = 5000
        seq_palette = sns.color_palette("icefire", col_num)
        lscmap = mpl.colors.ListedColormap(seq_palette)

        rel_t = np.array((events['time'] - self.start) * col_num / (self.stop - self.start), dtype = int)
        cols = [seq_palette[j] for j in rel_t]

        # Set color map and plot skymap
        pdf_palette = sns.color_palette("Blues", 500)
        cmap = mpl.colors.ListedColormap(pdf_palette)
        cmap.set_under("w")

        if self.skymap is None:
            skymap = np.zeros(hp.nside2npix(self._nside))
            max_val = 1.
            cmap = mpl.colors.ListedColormap([(1.,1.,1.)] * 50)
        else:
            skymap = self.skymap
            max_val = max(skymap)
        moll_cbar = True if self.skymap is not None else None
        hp.mollview(skymap, coord='C', cmap=cmap, cbar=moll_cbar)
        hp.graticule(verbose=False)

        theta=np.pi/2 - events['dec']
        phi = events['ra']

        #plot 90% containment errors
        sigma_90 = events['sigma']*self._angScale

        # plot events on sky with error contours
        hp.projscatter(theta,phi,c=cols,marker='x',label='GFU Event',coord='C', zorder=5)

        if (self.stop - self.start) <= 0.5:        #Only plot contours if less than 2 days
            for i in range(events['ra'].size):
                my_contour = plotting_utils.contour(events['ra'][i], 
                                    events['dec'][i],sigma_90[i], self._nside)
                hp.projplot(my_contour[0], my_contour[1], linewidth=2., 
                                    color=cols[i], linestyle="solid",coord='C', zorder=5)

        if self.skymap is None:
            src_theta = np.pi/2. - self.dec
            src_phi = self.ra
            hp.projscatter(src_theta, src_phi, c = 'k', marker = '*',
                                label = self.name, coord='C', s=350)

        if contour_files is not None:
            cont_ls = ['solid', 'dashed']
            contour_counter = 0
            for c_file in contour_files:
                cont = np.loadtxt(c_file, skiprows=1)
                cont_ra = cont.T[0]
                cont_dec = cont.T[1]
                hp.projplot(np.pi/2. - cont_dec, cont_ra, linewidth=3., 
                    color='k', linestyle=cont_ls[contour_counter], coord='C')
                contour_counter += 1

        if with_contour and self.skymap is not None:
            probs = hp.pixelfunc.ud_grade(self.skymap, 64)
            probs = probs/np.sum(probs)
            ### plot 90% containment contour of PDF
            levels = [0.9]
            theta, phi = plotting_utils.plot_contours(levels, probs)
            hp.projplot(theta[0], phi[0], linewidth=2., c='k', label='Skymap (90\% cont.)')
            for i in range(1, len(theta)):
                hp.projplot(theta[i], phi[i], linewidth=2., c='k')

        # plt.title('Fast Response Skymap')
        plt.title(self.name.replace('_', ' '))
        plt.legend(loc=1)
        plt.savefig(self.analysispath + '/' + self.analysisid + 'unblinded_skymap.png',bbox_inches='tight')
        plt.close()
Exemple #30
0
 def plot_x(self, plt, el, az):
     theta, phi = elaz2hp(el, az)
     hp.projplot(theta, phi, "ro", rot=(0, 90, 180))  #
dec = rot_theta
h = datetime.timedelta(minutes=int(1000))
ref_time = datetime.datetime(2013, 6, 1, 23, 0, 0)

gal_x = []
for i in range(len(rot_phi)):
    l_g, b_g = gal_sys(rot_phi[i], rot_theta[i], ref_time)
    b_g = 90. - b_g  #colatitude (galactic)
    gal_x.append(np.array([l_g * rad, b_g * rad]))

gal_x = np.transpose(gal_x)

#reference point for the rotation
ref_time1 = datetime.datetime(2013, 6, 1, 23, 0, 0)
phi_g, theta_g = gal_sys(glon, glat, ref_time1)
phi_g = phi_g * rad
theta_g = (theta_g) * rad
datos1, datos2 = np.loadtxt('cosa_d.txt', unpack=True)

nside = 512 / 16
pix = hp.ang2pix(nside, gal_x[1, :], gal_x[0, :])
#pix2 = hp.ang2pix(nside, RA, dec)

bmap = np.zeros(hp.nside2npix(nside), dtype=np.double)
bmap[pix] = temp
hp.mollview(bmap,
            coord=['G', 'C'],
            rot=(datos1[0] / rad, 90. - (datos2[0] / rad)))
hp.projplot(datos1, datos2, '.k', lonlat=False, coord='C')
plt.show()
Exemple #32
0
fact     = 1.42144524614e-05 
filename = 'data/HFI_CompMap_ThermalDustModel_2048_R1.20.fits'
filename = 'data/HFI_SkyMap_353_2048_R2.02_full.fits'

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

#hp.mollview(test_map)
#hp.cartview(test_map, title=filename, coord='G', rot=[0,0], unit='K', norm='hist', min=-1375,max=2687, xsize=800, lonra=[-1,1], latra=[-1,1])
#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)

equateur_lon = [10.,0.]
equateur_lat = [10.,0.]
hp.projplot(equateur_lon, equateur_lat, lonlat=True, coord='G')

# plt.loglog(hp.anafast(test_map))
# plt.grid()
# plt.xlabel("$\ell$")
# plt.ylabel("$C_\ell$")

plt.grid()
plt.show()
Exemple #33
0
        val4 = cmap[nei[0]]
        if np.sum(val4) == 4:
            cmapx[i] = 0

zmap = np.zeros(len(cmap))
for i in range(0, npix):
    if cmapx[i] > 0:
        nni = hp.pixelfunc.get_all_neighbours(nside, i)
        val8 = cmap[nni]
        if np.sum(val8) > 0:
            zmap[i] = 1

#hp.mollview(zmap, title="",flip="geo",cmap=plt.cm.bone)#,min=0.0,max=1.0)
#plt.show()

mask = zmap == 1
pix = np.array(range(npix))
np.savez("earth_boundary", nside, pix[mask])

#test
dat = np.load("earth_boundary.npz")
nside = dat["arr_0"]
nbound = dat["arr_1"]

zzmap = np.zeros(len(cmap))
hp.mollview(zzmap, title="", flip="geo", cmap=plt.cm.bone)  #,min=0.0,max=1.0)
theta, phi = hp.pixelfunc.pix2ang(nside, nbound)

hp.projplot(theta, phi, ".", c="white", alpha=0.5)
plt.show()
Exemple #34
0
    thetaE, phiE = plotdymap.bound_earth(
        "/home/kawahara/exomap/sot/data/earth_boundary.npz")
    year = 2016
    month = 5
    day = 11
    hdffile, month, day = modisfile(month, day, year=year)
    hdfdir = "/home/kawahara/exomap/data/modis/MYD08"

    hdffile = os.path.join(hdfdir, hdffile)
    a = read_cloud(hdffile, N=1)
    hmap = to_healpix(a, nside=16)
    hp.mollview(hmap,
                title=str(year) + "-" + str(month) + "-" + str(day),
                flip="geo",
                cmap=plt.cm.pink,
                min=0.5,
                max=1.0)
    hp.projplot(thetaE, phiE, ".", c="#66CC99")
    hp.projtext(-60,
                -25,
                "A",
                coord="G",
                lonlat=True,
                color="cyan",
                fontsize=26)  #amazon
    #    hp.projtext(-130,30,"B",coord="G",lonlat=True,color="cyan",fontsize=26) #north america

    plt.savefig("cf" + str(year) + "_" + str(month) + "_" + str(day) + ".pdf")
    plt.show()
def plot(data, showdisks=False, unit='stars/deg^2'):
    _fontsize = rcParams['font.size']
    _fontweight = rcParams['font.weight']

    rcParams['font.size'] = 14
    rcParams['font.weight'] = 'normal'

    # Draw the map
    healpy.mollview(map=data,
                    rot=[0, 180],
                    cmap=cm.gist_stern_r,
                    title='',
                    unit=unit)
    healpy.graticule(dpar=30.0, dmer=45.0, local=True)

    # Handle colorbar labels
    try:
        fig = py.gcf()
        cbar = fig.axes[-1]

        cbarLabels = cbar.xaxis.get_ticklabels()
        for cc in range(len(cbarLabels)):
            cbarLabels[cc] = '%.5f' % float(cbarLabels[cc].get_text())

        cbar.xaxis.set_ticklabels(cbarLabels, fontweight='bold', fontsize=14)
    except UnicodeEncodeError:
        pass

    # Draw contours for the old disk positions
    if showdisks:
        incl = [124.0, 30.0]
        incl_err = [2.0, 4.0]
        incl_thick = [7.0, 9.5]
        Om = [100.0, 167.0]
        Om_err = [3.0, 9.0]
        Om_thick = [7.0, 9.5]

        for jj in range(len(incl)):
            x1, y1 = ellipseOutline(incl[jj], Om[jj], incl_err[jj], Om_err[jj])
            x2, y2 = ellipseOutline(incl[jj], Om[jj], incl_thick[jj],
                                    Om_thick[jj])
            healpy.projplot(x1,
                            y1,
                            lonlat=True,
                            color='k',
                            linestyle='-',
                            linewidth=2)
            healpy.projplot(x2,
                            y2,
                            lonlat=True,
                            color='k',
                            linestyle='--',
                            linewidth=2)

    # Flip so that the axes go in the right direction
    foo = py.axis()
    py.xlim(2.01, -2.01)

    # Make axis labels.
    healpy.projtext(178, 90, '0', lonlat=True)
    healpy.projtext(178, 60, '30', lonlat=True)
    healpy.projtext(178, 30, '60', lonlat=True)
    healpy.projtext(178, 0, '90', lonlat=True)
    healpy.projtext(178, -30, '120', lonlat=True)
    healpy.projtext(178, -60, '150', lonlat=True)
    healpy.projtext(178,
                    -90,
                    'i = 180',
                    lonlat=True,
                    horizontalalignment='center')

    healpy.projtext(92,
                    1,
                    'S',
                    lonlat=True,
                    horizontalalignment='right',
                    verticalalignment='top')
    healpy.projtext(182,
                    1,
                    'W',
                    lonlat=True,
                    horizontalalignment='right',
                    verticalalignment='top')
    healpy.projtext(272,
                    1,
                    'N',
                    lonlat=True,
                    horizontalalignment='right',
                    verticalalignment='top')
    healpy.projtext(362,
                    1,
                    'E',
                    lonlat=True,
                    horizontalalignment='right',
                    verticalalignment='top')

    rcParams['font.size'] = _fontsize
    rcParams['font.weight'] = _fontweight
Exemple #36
0
    def superimpose_polygon_outline(self,
                                    vertices,
                                    label,
                                    color='red',
                                    coord_in='C',
                                    cbar=True):
        '''Superimpose an outline of a survey given input vertices

        Parameters
        ----------
        vertices: array-like (nvtxs, 2)
            The vertices of the polygon

        label : string
            The label for the survey

        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', 'E', or 'G'
            The coordinate system for the input vertices

        cbar : boolean
            Whether to add a colorbar corresponding to this polygon or not
        '''

        lons = vertices[:, 0]
        lats = vertices[:, 1]

        if np.abs(lons[-1] - 180.0) > 0.01:
            lons = np.append(lons, lons[0])
            lats = np.append(lats, lats[0])

        #Convert coordinate system for the outline to the one used in the
        #plot
        r = H.rotator.Rotator(coord=[coord_in, self.coord_plot])
        r = H.rotator.Rotator(coord=[coord_in, coord_in])
        lonsp = []
        latsp = []
        for lon, lat in zip(lons, lats):
            theta = np.radians(90 - lat)
            phi = np.radians(lon)
            thetap, phip = r(theta, phi)
            lonsp.append(np.degrees(phip))
            latsp.append(90 - np.degrees(thetap))

        lons = lonsp
        lats = latsp

        nvertices = len(lons)

        # Loop over all vertices and generate lines between adjacent vertices
        # in list. This is to ensure the lines are drawn.
        linelon = np.array([])
        linelat = np.array([])
        for i in range(nvertices - 1):
            tmplon = np.linspace(lons[i], lons[i + 1], num=1000)
            tmplat = np.linspace(lats[i], lats[i + 1], num=1000)
            linelon = np.append(linelon, tmplon)
            linelat = np.append(linelat, tmplat)

        H.projplot(linelon,
                   linelat,
                   lonlat=True,
                   markersize=1,
                   color=color,
                   coord=coord_in)

        if cbar:
            # Temporary axis with a Healpix map so I can get the correct color
            # for the colorbar
            cm1 = util.get_color_map(color)
            coord = [coord_in, self.coord_plot]
            hpx_map = np.ones(12 * 32**2)
            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])

            # 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)

            # Delete the temporary map
            self.fig.delaxes(self.fig.axes[-2])

            # Readjust 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
Exemple #37
0
def coverage(params, map_struct, coverage_struct):

    unit = 'Gravitational-wave probability'
    cbar = False

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

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

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

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

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

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

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

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

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

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

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

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

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

        moviefiles = os.path.join(moviedir, "coverage-%04d.png")
        filename = os.path.join(params["outputDir"], "coverage.mpg")
        ffmpeg_command = 'ffmpeg -an -y -r 20 -i %s -b:v %s %s' % (
            moviefiles, '5000k', filename)
        os.system(ffmpeg_command)
        filename = os.path.join(params["outputDir"], "coverage.gif")
        ffmpeg_command = 'ffmpeg -an -y -r 20 -i %s -b:v %s %s' % (
            moviefiles, '5000k', filename)
        os.system(ffmpeg_command)
        rm_command = "rm %s/*.png" % (moviedir)
        os.system(rm_command)
	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):
			cosb = np.cos(b*deg2rad)
			cosy = np.cos(y*deg2rad)
			if ( (((x-l)**2 + (y-b)**2) <= offset**2) ):
## Define constants #
deg2rad = np.pi/180.
pi      = 2.0*np.arccos(0.)

## Read infor of 26 no-CO sources
info    = read_info_no_co('26src_no_co_info.dat')

## g35+g45+g56 Mask
map_file = 'data/mask_g35g45g56.fits' #
msk      = hp.read_map(map_file, field = 0, h=False)
title    = map_file

nside    = hp.get_nside(msk)
# resol    = hp.nside2resol(nside, arcmin=False)
# print nside, resol*180./pi

cmap = plt.cm.get_cmap('cool')
hp.mollview(msk, title=map_file, coord='G', unit='', rot=[0,0,0], norm=None, xsize=800, cmap=cmap)

for i in range(0,26):
	src   = info['src'][i]
	l     = info['l'][i]
	b     = info['b'][i]

	op,er = get_dust_opacity(msk, l, b)
	hp.projplot(l, b, 'kx', lonlat=True, coord='G')
	# hp.projtext(l, b, src+','+str(l)+','+str(b), lonlat=True, coord='G')
	hp.projtext(l, b, src+', '+str(op)+', '+str(er), lonlat=True, coord='G')

hp.graticule()
plt.show()
Exemple #40
0
hp.projtext(275, 2, '270', lonlat=True, fontweight='bold')
hp.projtext(8, 2, '0', lonlat=True, fontweight='bold')
hp.projtext(359, 2, '360', lonlat=True, fontweight='bold')
hp.projtext(193, -8, 'RA (deg)', lonlat=True, fontweight='bold')
hp.projtext(350, 30, '30', lonlat=True, fontweight='bold')
hp.projtext(340, 60, '60', lonlat=True, fontweight='bold')
#hp.projtext(5, -5, 'Dec (deg)', lonlat=True)
hp.projtext(358, -33.5, '-30', lonlat=True, fontweight='bold')
hp.projtext(358, -63.5, '-60', lonlat=True, fontweight='bold')
ra_gplane = np.arange(0., 361., 1.)
dec_gplane = np.zeros(len(ra_gplane))

hp.projplot(ra_gplane,
            dec_gplane,
            coord='G',
            lonlat=True,
            color='DimGrey',
            linewidth=2.,
            alpha=0.5)

py.savefig('/data/user/brelethford/AGN_Core/Plots/wrongdec_eq.png')

#Galactic plane requires no rotation to put it in the form we want.
hp.mollview(title='Galactic Map of SwiftBAT AGNs',
            cbar=False,
            cmap=None,
            notext='True',
            coord='G')
hp.graticule(coord='G', color='DimGrey')
py.title(r"wrongdec - Galactic", fontsize=25, fontweight='bold')
#hp.projscatter(0,0,coord='G',lonlat=True) # This one used to test GC
Exemple #41
0
def make_airmass_map(obs_time, airmass_limit, dust, stars):
    solar_coordinates = astropy.coordinates.get_sun(obs_time)
    lunar_coordinates = astropy.coordinates.get_moon(obs_time)
    airmass_limit_coords = compute_airmass_limit_coords(
        obs_time, airmass_limit)
    twilight_coords = compute_twilight_limit_coords(obs_time, 90 + 12)
    ecliptic_coords = compute_ecliptic(obs_time)

    truncated_blue_cmap = mpl.colors.LinearSegmentedColormap.from_list(
        "truncated_blues",
        plt.get_cmap("Blues")(np.linspace(0, 0.3, 100)))

    healpy.azeqview(
        dust,
        norm="log",
        min=0.1,
        max=0.3,
        lamb=True,
        rot=(0, -90, 0),
        cbar=False,
        flip="astro",
        reso=18,
        cmap=truncated_blue_cmap,
        title=f"{str(obs_time)[:16]}",
    )
    for vmag in np.arange(4):
        mag_stars = stars.query(f'Vmag<{vmag} and decl<40')
        healpy.projplot(
            mag_stars.ra,
            mag_stars.decl,
            coord="E",
            lonlat=True,
            linestyle="",
            marker="*",
            color="black",
            alpha=0.2 * vmag / 4.0,
            markersize=(4 - vmag),
        )
    healpy.projplot(
        solar_coordinates.ra.deg,
        solar_coordinates.dec.deg,
        coord="E",
        lonlat=True,
        linestyle="",
        marker="*",
        color="green",
        markersize=10,
    )
    healpy.projplot(
        ecliptic_coords.ra.deg,
        ecliptic_coords.dec.deg,
        coord="E",
        lonlat=True,
        alpha=0.5,
        color="green",
    )
    healpy.projplot(
        lunar_coordinates.ra.deg,
        lunar_coordinates.dec.deg,
        coord="E",
        lonlat=True,
        linestyle="",
        marker="o",
        color="orange",
        markersize=10,
    )
    healpy.projplot(
        airmass_limit_coords.ra,
        airmass_limit_coords.decl,
        coord="E",
        lonlat=True,
        color="darkblue",
    )
    healpy.projplot(
        twilight_coords.ra,
        twilight_coords.decl,
        coord="E",
        lonlat=True,
        color="orange",
    )
    healpy.graticule(coord="E")

    fig = plt.gcf()
    return fig
Exemple #42
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()
Exemple #43
0
#                   coord=coords,
#                   color='black',
#                   rotation=0,
#                   fontdict={"family":"sans-serif", "weight":"bold", "size":12})
        descr = "HAWC Field of View\n(Moving Left)" if coords == "C" else "HAWC Field of View" 
        hp.projtext( U.halfpi - locale.latitude + 55*U.degree, lst,
                   descr,
                   coord=coords,
                   color='black',
                   rotation=0,
                   fontdict={"family":"sans-serif", "weight":"bold", "size":12})
        # plot error circle
        if args.errorCirc:
                hp.projplot( 
                             [ np.arange(0,360, 1.), np.ones(360)*(90-args.errorCirc)], 
                             lonlat=True, color='mediumorchid', coord=coords,
                             linestyle="-", linewidth=1.5,
                             rot= (ra,dec,0)
                           )
              
#              for axM in fig.get_axes():
#                  if type(axM) is hp.projaxes.HpxMollweideAxes:
#                      axM.fill_between( 
#                                np.arange(0,360, 1.),np.ones(360)*(90-args.errorCirc), np.ones(360)*(90-args.errorCirc)*.001, 
#                               #lonlat=True, color='mediumorchid', coord="C",
#                               #linestyle="-", linewidth=1,
#                               #rot= (ra,dec,0)
#                                  )
      
    time = []
    zen  = []
    for delhr in np.arange(-1.0*args.tmax, args.tmax+0.1, 0.1):
Exemple #44
0
    # Plot GW skymap in Mollweide projection
    hp.mollview(probs,
                cbar=True,
                unit=r'probability',
                min=0,
                max=3e-5,
                rot=180,
                cmap=cmap)
    hp.graticule(ls=':', alpha=0.5, dpar=30, dmer=45)  # Set grid lines

    # Draw containment contour around GW skymap
    nregion = len(theta_contour) // len(levels)
    # ls = ['-', '--', '-.']
    # label = ''
    for i, (tc, pc) in enumerate(zip(theta_contour, phi_contour)):
        hp.projplot(tc, pc, linewidth=1, c='k')
    #     j = i // nregion
    #     print(len(theta_contour), nregion, i, j)
    #     newlabel = '{:g}% credible region'.format(100*levels[j])
    #     if newlabel == label:
    #         hp.projplot(tc, pc, linewidth=1, c='k', linestyle=ls[j])
    #     else:
    #         hp.projplot(tc, pc, linewidth=1, c='k', linestyle=ls[j], label=newlabel)
    #         label = newlabel

    ax = plt.gca()

    # Label latitude lines.
    ax.text(2.00, 0.10, r'$0^\circ$', horizontalalignment='left')
    ax.text(1.80, 0.45, r'$30^\circ$', horizontalalignment='left')
    ax.text(1.30, 0.80, r'$60^\circ$', horizontalalignment='left')
    ]
    color_list = ['b', 'g', 'r', 'olive', 'm', 'indigo', 'orange', 'cyan']
    text_offset = np.array([[-0.05, -0.15], [-0.05, -0.15], [-0.05, -0.15],
                            [-0.00, 0.10], [-0.40, 0.00], [0.04, -0.10],
                            [-0.05, -0.15], [-0.05, -0.15]])
    # Plot regions
    plt.plot(np.pi, np.pi / 2, c='w', label='Training sets')
    for index, name in enumerate(image_name_list):
        if index == 3:
            plt.plot(np.pi, np.pi / 2, c='w', label='Test sets')
        image = pyfits.getdata(name)
        header = pyfits.getheader(name)
        w = wcs.WCS(header)
        indices_tuple = np.where(~np.isnan(image))
        pixel_coords = np.transpose(
            np.array([indices_tuple[0], indices_tuple[1]]))
        world_coords = w.wcs_pix2world(pixel_coords, 1)
        gala_coords = equatorial2galactic(world_coords)
        print("{1}, {0}".format(name, gala_coords[0]))
        hp.projplot(gala_coords[:, 0],
                    gala_coords[:, 1],
                    lonlat=True,
                    c=color_list[index],
                    label=region_name_list[index])
    plt.legend()
    fig.savefig('Locations_of_our_datasets_in_whole_sky_map.png', dpi=300)
    #-----------------------------------
    # Measure time
    elapsed_time = time.time() - start_time
    print("Exiting Main Program, spending ", elapsed_time, "seconds.")
Exemple #46
0
def plot_objects(ra,dec,markersize,color,symbol):

    coords = SkyCoord(ra=ra, dec=dec, unit=(u.degree,u.degree))
    for k in range(0,len(coords)):
        H.projplot(coords[k].ra.value,coords[k].dec.value,symbol,lonlat=True,color=color,coord=['C'],markersize=markersize)
def main():
    p = argparse.ArgumentParser(
        description="Plot maps in Mollweide projection")
    p.add_argument("fitsfile", nargs="?", help="Input HEALPix FITS file")
    p.add_argument("-c",
                   "--coords",
                   default="C",
                   help="C=equatorial, G=galactic, E=ecliptic")
    p.add_argument("-C",
                   "--column",
                   dest="fitscol",
                   type=int,
                   default=0,
                   help="FITS file column number of HEALPix map")
    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(
        "--file-diff",
        dest="diff",
        default="",
        type=str,
        help=
        "FITS File to take the difference from (optional) otherwise uses positional argument"
    )
    p.add_argument("--decMin",
                   type=float,
                   default=None,
                   help="Plot minimum declination value")
    p.add_argument("--decMax",
                   type=float,
                   default=None,
                   help="Plot maximum declination value")
    p.add_argument("--mjd",
                   default=None,
                   type=float,
                   help="MJD of the map. Will be plotted J2000")
    p.add_argument(
        "--norm-sqdeg",
        dest="sqdeg",
        action="store_true",
        help="Normalize values to square degree, according to nSides "
        "(makes sense only certain dinds of maps)")
    p.add_argument("-L", "--label", default=None, help="Color bar label")
    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 colors to use in the color map")
    p.add_argument("-o",
                   "--output",
                   default=None,
                   help="Output image file (.png preferred)")
    p.add_argument("-s",
                   "--scale",
                   type=float,
                   default=1.0,
                   help="Scale the map after input by some value")
    p.add_argument(
        "-S",
        "--size",
        dest="xsize",
        type=int,
        default=1600,
        help="Map x-axis pixel number; increase for high resolution")
    p.add_argument("-t",
                   "--ticks",
                   nargs="+",
                   type=float,
                   help="List of ticks for color bar, space-separated")
    p.add_argument("-T", "--title", default="", help="Plot title")
    p.add_argument("-x",
                   "--threshold",
                   dest="thresh",
                   default=None,
                   type=float,
                   help="Apply a (lower) threshold to the map")
    p.add_argument("-X",
                   "--abthresh",
                   dest="athresh",
                   default=None,
                   type=float,
                   help="Apply an absolute (lower/upper) threshold to the map")

    p.add_argument("--gamma",
                   action="store_true",
                   help="Use Fermi/HESS/VERITAS gamma-ray color scale")
    p.add_argument("--milagro",
                   action="store_true",
                   dest="milagro",
                   help="Use Milagro color scale")

    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.")
    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 w/ TeVCat ASCII file")

    # Highlight hotspots listed in an ASCII file
    p.add_argument(
        "--hotspots",
        default=None,
        help=
        "Hotspot coordinates in an ASCII file( Format:   source name, ra, dec   )"
    )
    p.add_argument("--hotspot-labels",
                   dest="hotspotLabels",
                   action="store_true",
                   help="Draw hotspots sources with labels.")

    p.add_argument("--glines",
                   action="store_true",
                   help="Draw galactic lines of latitude (celestial only)")
    p.add_argument("--gridlines", action="store_true", help="Draw gridlines")
    p.add_argument("--gplane",
                   action="store_true",
                   help="Draw the galactic plane and galactic center")
    p.add_argument("--nomask",
                   action="store_false",
                   dest="mask",
                   default=True,
                   help="Mask part of the sky")
    p.add_argument("--preliminary",
                   action="store_true",
                   help="Add a watermark indicating the plot as preliminary")
    p.add_argument("--alpha",
                   type=float,
                   default=0.7,
                   help="Alpha used for drawn Galactic lines.")
    p.add_argument("--logz",
                   action="store_true",
                   help="Set color scale in log.")

    # 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.")

    args = p.parse_args()

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

    # 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

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

    znorm = None
    if (args.logz):
        znorm = 'log'

    skymap, skymapHeader = hp.read_map(args.fitsfile, args.fitscol, h=True)
    nside1 = hp.get_nside(skymap)
    # remove naughty values
    skymap[np.isnan(skymap)] = hp.UNSEEN

    if args.decMax:
        imin = hp.ang2pix(nside1, 90 * degree - args.decMax * degree, 0)
        skymap[0:imin] = hp.UNSEEN
    if args.decMin:
        imax = hp.ang2pix(nside1, 90 * degree - args.decMin * degree, 0)
        skymap[imax:] = hp.UNSEEN

    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(args.fitsfile, args.coldiff)

        print("Subtracting column {0} from skymap...".format(args.coldiff))
        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)

    if args.sqdeg:
        # Normalize value to square degree
        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.fitscol + 1)
    skymapName = dict(skymapHeader)[toFind]
    skymap[skymap != hp.UNSEEN] *= args.scale

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

    # Mask outside FOV
    if args.mask:
        skymap = maskHAWC(skymap)

    print("Trials: %d" % skymap[skymap != hp.UNSEEN].size)
    print("Counts: %g" % skymap[skymap != hp.UNSEEN].sum())

    # Set up the map minimum and maximum values
    notMask = skymap[skymap > hp.UNSEEN]
    dMin, dMax = (notMask[np.argmin(notMask)], notMask[np.argmax(notMask)])
    print(dMin, dMax)
    if args.min is not None:
        dMin = args.min
        skymap[(skymap < dMin) & (skymap > hp.UNSEEN)] = dMin
    if args.max is not None:
        dMax = args.max
        skymap[(skymap > dMax) & (skymap > hp.UNSEEN)] = dMax

    mpl.rc("font", family="serif", size=14)

    # Set up the color map for plotting
    textcolor, colmap = MapPalette.setupDefaultColormap(args.ncolors)

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

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

    # Set up the figure frame and coordinate rotation angle
    if args.coords == "C":
        fig = plt.figure(1, figsize=((11.75, 6.5)), dpi=100)
        rotation = 180.
        coords = "C"
    elif args.coords == "G":
        fig = plt.figure(1, figsize=(9.5, 6), dpi=100)
        coords = "CG"
        rotation = 0.
    else:
        fig = plt.figure(1, figsize=(9.5, 6), dpi=100)
        coords = "CE"
        rotation = 180.

    if args.mjd is None:
        rotMap = rotation
    else:
        rotMap = precess.mjd2J2000ang(mjd=args.mjd, coord=coords, rot=rotation)
        rotPrec = hp.rotator.Rotator(rot=precess.mjd2J2000ang(mjd=args.mjd))

    hp.mollview(skymap,
                fig=1,
                xsize=args.xsize,
                coord=coords,
                min=dMin,
                max=dMax,
                rot=rotMap,
                title=args.title.replace("\\n", "\n"),
                cmap=colmap,
                cbar=False,
                notext=True,
                norm=znorm)
    if args.gridlines:
        hp.graticule()

    if args.preliminary:
        hp.projtext(95 * degree,
                    240 * degree,
                    "PRELIMINARY",
                    coord=coords,
                    color=textcolor,
                    alpha=0.5,
                    rotation=0,
                    fontdict={
                        "family": "sans-serif",
                        "weight": "bold",
                        "size": 42
                    })

    # If TeVCat data are available, plot them
    if args.tevcat:
        if haveTeVCat:
            try:
                tevcat = TeVCat.TeVCat(args.tevcat)
            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()

            for cId in (1, 2):
                catalog = tevcat.GetCatalog(cId)
                ra = catalog.GetRA()
                dec = catalog.GetDec()
                assoc = catalog.GetCanonicalName()

                if args.mask:
                    cut = np.logical_and(dec < 64 * degree, dec > -26 * degree)
                    dec = dec[cut]
                    ra = ra[cut]
                    assoc = assoc[cut]

                if args.mjd is None:
                    theta, phi = (90 * degree - dec, ra)
                else:
                    theta, phi = rotPrec.I(90 * degree - dec, ra)

                hp.projscatter(theta,
                               phi,
                               coord=coords,
                               color=textcolor,
                               facecolors="none",
                               marker="s")
                if args.tevcatLabels:
                    for th, ph, s in zip(theta, phi, assoc):
                        hp.projtext(th,
                                    ph,
                                    s,
                                    coord=coords,
                                    color=textcolor,
                                    rotation=10,
                                    fontdict={"size": 14})
                # Print significance for TeVCat sources above 3 sigma
                sThr = 3.
                if cId == 1:
                    print("TeVCat sources above %.2f sigma:" % sThr)
                for r, d, s in zip(ra, dec, assoc):
                    valueTeVCat = hp.get_interp_val(skymap, 90 * degree - d, r)
                    if valueTeVCat > sThr:
                        print(" - %s: %.2f sigma" % (s, valueTeVCat))
        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]

            if args.mjd is None:
                theta, phi = (90 * degree - dec, ra)
            else:
                theta, phi = rotPrec.I(90 * degree - dec, ra)

            for i in xrange(len(assoc)):
                if assoc[i] == '':
                    assoc[i] = catnms[i]

            if args.mask:
                cut = np.logical_and(dec < 64 * degree, dec > -26 * degree)
                dec = dec[cut]
                ra = ra[cut]
                assoc = assoc[cut]
            hp.projscatter(theta,
                           phi,
                           coord=coords,
                           color=textcolor,
                           facecolors="none",
                           marker="o")
            if args.fermicatLabels:
                for th, ph, s in zip(theta, phi, assoc):
                    hp.projtext(th,
                                ph,
                                s,
                                coord=coords,
                                color=textcolor,
                                rotation=10,
                                fontdict={"size": 14})
        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
            r, d = [float(t) * degree for t in line.strip().split(",")[1:3]]
            ra.append(r)
            dec.append(d)
            assoc.append(line.strip().split(",")[0].strip())
        ra = np.array(ra)
        dec = np.array(dec)
        assoc = np.array(assoc)

        if args.mjd is None:
            theta, phi = (90 * degree - dec, ra)
        else:
            theta, phi = rotPrec.I(90 * degree - dec, ra)

        if args.mask:
            cut = np.logical_and(dec < 64 * degree, dec > -26 * degree)
            dec = dec[cut]
            ra = ra[cut]
            assoc = assoc[cut]
            theta = theta[cut]
            phi = phi[cut]
        hp.projscatter(theta,
                       phi,
                       coord=coords,
                       color='darkorchid',
                       facecolors="none",
                       marker="o",
                       s=40)
        if args.hotspotLabels:
            for th, ph, r, d, s in zip(theta, phi, ra, dec, assoc):
                print(r, d, s)
                hp.projtext(th,
                            ph,
                            s + '  .',
                            coord=coords,
                            color='darkorchid',
                            rotation=4,
                            fontdict={
                                'family': 'sans-serif',
                                'size': 10,
                                'weight': 'bold'
                            })

    # Adjust plot so that empty southern hemisphere is cut out
    ax = fig.gca()
    # Hide not used space of image
    imgp = ax.get_images()[0]
    imgp.get_cmap().set_under('w', alpha=0.)
    imgp.get_cmap().set_over('w', alpha=0.)
    imgp.get_cmap().set_bad('w', alpha=0.)

    if args.coords == "C":
        ax.set_ylim([-0.5, 1])

    # Draw the galactic plane, latitude lines, and the galactic center
    # (only if underlying grid is celestial)
    if args.glines and args.coords == "C":
        for b in np.arange(-90., 90.1, 30):
            raGP = []
            decGP = []
            if b == 0:
                ls = "-"
                lw = 2
            else:
                ls = "--"
                lw = 1
            for l in np.arange(0., 360., 1.):
                r, d = gal2equ(l, b)
                raGP.append(r)
                decGP.append(d)

            if args.mjd is not None:
                raGP, decGP = rotPrec.I(raGP, decGP, lonlat=True)

            hp.projplot([raGP, decGP],
                        lonlat=True,
                        color=textcolor,
                        coord="C",
                        alpha=args.alpha,
                        linestyle=ls,
                        linewidth=lw)

        galCenter = gal2equ(0., 0.)
        if args.mjd is not None:
            galCenter = rotPrec.I(galCenter, lonlat=True)

        hp.projscatter(gal2equ(0., 0.),
                       lonlat=True,
                       color=textcolor,
                       alpha=args.alpha,
                       s=50,
                       marker='o',
                       coord="C")

        # Label the galactic latitude lines
        marks = [-60, -30, 0, 30, 0, -30, -60]
        xposn = [-1.56, -1.20, -0.79, 0.10, 0.60, 0.97, 1.33]
        for m, x in zip(marks, xposn):
            ax.annotate("%d$^\circ$" % m,
                        xy=(x, -0.475),
                        size="small",
                        fontweight="bold",
                        color=textcolor)
    # Draw lines above/below galactic plane, and the galactic center
    # (only if underlying grid is celestial)
    elif args.gplane and args.coords == "C":
        #for b in np.arange(-90., 90.1, 30):
        for b in [-5, 5]:
            raGP = []
            decGP = []
            if b == 0:
                ls = "-"
                lw = 2
            else:
                ls = "--"
                lw = 1
            for l in np.arange(0., 360., 1.):
                r, d = gal2equ(l, b)
                raGP.append(r)
                decGP.append(d)

            if args.mjd is not None:
                raGP, decGP = rotPrec.I(raGP, decGP, lonlat=True)

            hp.projplot([raGP, decGP],
                        lonlat=True,
                        color=textcolor,
                        coord="C",
                        linestyle=ls,
                        linewidth=lw,
                        alpha=args.alpha)

        galCenter = gal2equ(0., 0.)
        if args.mjd is not None:
            galCenter = rotPrec.I(galCenter, lonlat=True)

        hp.projscatter(galCenter,
                       lonlat=True,
                       color=textcolor,
                       s=50,
                       marker='o',
                       alpha=args.alpha,
                       coord="C")

        # Label the galactic latitude lines
        marks = [-5, 5, 5, -5]
        xposn = [-1.05, -0.7, 0.4, 0.7]
        for m, x in zip(marks, xposn):
            ax.annotate("%d$^\circ$" % m,
                        xy=(x, -0.475),
                        size="small",
                        fontweight="bold",
                        color=textcolor)

    # Set up the color bar and tick axis
    if args.label:
        paletteLabel = args.label
    else:
        if re.match("significance", skymapName):
            paletteLabel = r"significance [$\sigma$]"
        else:
            paletteLabel = skymapName
    if args.gumbel:
        paletteLabel = "log10(P-Value)"

    # Clean up automatic tick definitions
    cticks = args.ticks
    if args.ticks == None:
        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)

    setupColorbar(fig, title=paletteLabel, ticks=cticks, coord=args.coords)

    if args.output:
        fig.savefig(args.output, dpi=400)
        print("File %s created" % args.output)
    else:
        plt.show()
Exemple #48
0
#====== For Plotting ======#
# hp.mollview(np.log10(ir_map), title=r'$I_{100}$', coord='G', unit='MJy/sr', norm=None) #, min=0.,max=452)
hp.mollview(ir_map, title=r'$I_{100}$', coord='G', unit='MJy/sr', norm=None) #, min=0.,max=452)

for i in range(0,26):
	src   = info['src'][i]
	l     = info['l'][i]
	b     = info['b'][i]

	theta = (90.0 - b)*deg2rad
	phi   = l*deg2rad
	pix   = hp.ang2pix(nside, theta, phi, nest=False)
	val   = ir_map[pix]
	print src, l,b,pix, val
	hp.projplot(l, b, 'bo', lonlat=True, coord='G')
	# hp.projtext(l, b, src+','+str(l)+','+str(b), lonlat=True, coord='G')
	if (b<60):
		hp.projtext(l, b, src, lonlat=True, coord='G', fontsize=13, weight='bold')
	else:
		hp.projtext(l, b, src, lonlat=True, coord='G', fontsize=13, color='r', weight='bold')

	if(src == '3C109'):
		hp.projtext(l, b, src, lonlat=True, coord='G', fontsize=13, color='b', weight='bold')

mpl.rcParams.update({'font.size':30})
hp.graticule()
plt.grid()
plt.show()

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

	hp.cartview(tau_map, title=src[i], coord='G', unit='Unitless', norm=None, xsize=800, lonra=[ll-dg,ll+dg], latra=[b-dg,b+dg] )
	# min=7.03e-6, max=1.24e-5 )

	# 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='y')

	# 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):
			cosb = np.cos(b*deg2rad)
			cosy = np.cos(y*deg2rad)
			# if ( (((x-l)**2 + (y-b)**2) <= offset**2) ):
			if ( (((x-l)**2 + (y-b)**2) <= offset**2) and (((x-l)**2 + (y-b)**2) >= (offset-offset*0.05)**2) ):
				# hp.projtext(x, y, '.', lonlat=True, coord='G')
				hp.projplot(x, y, 'mx', lonlat=True, coord='G', ms=1, mew=2)

	mpl.rcParams.update({'font.size':30})
	plt.show()