Example #1
0
def parse_patches(args):
    # Parse the patch definitions

    patches = []
    total_weight = 0
    for patch_def in args.patch:
        parts = patch_def.split(',')
        name = parts[0]
        weight = float(parts[1])
        total_weight += weight
        print('Adding patch "{}" {} '.format(name, weight), end='')
        if len(parts[2:]) == 3:
            corners = parse_patch_center_and_width(args, parts)
        elif len(parts[2:]) == 4:
            corners = parse_patch_rectangular(args, parts)
        else:
            corners = parse_patch_explicit(args, parts)
        print('')
        patches.append([name, weight, corners])

    if args.debug:
        import matplotlib.pyplot as plt
        import healpy as hp
        plt.figure(figsize=[18, 12])
        for iplot, coord in enumerate('CEG'):
            hp.mollview(np.zeros(12),
                        coord=coord,
                        cbar=False,
                        title='Patch locations',
                        sub=[2, 2, 1 + iplot])
            hp.graticule(30)
            for name, weight, corners in patches:
                lon = [corner._ra / degree for corner in corners]
                lat = [corner._dec / degree for corner in corners]
                lon.append(lon[0])
                lat.append(lat[0])
                print('{} corners:\n lon = {}\n lat= {}'.format(
                    name, lon, lat),
                      flush=True)
                hp.projplot(lon,
                            lat,
                            'r-',
                            threshold=1,
                            lonlat=True,
                            coord='C',
                            lw=2)
                hp.projtext(lon[0],
                            lat[0],
                            name,
                            lonlat=True,
                            coord='C',
                            fontsize=14)
        plt.savefig('patches.png')
        plt.close()

    # Normalize the weights
    for i in range(len(patches)):
        patches[i][1] /= total_weight

    return patches
Example #2
0
    def plot_coord(self, rot=[0, 0, 0], bkgcolor='k', **kwargs):
        """show specific coordinates in skymap

        Parameters
        ----------        
        rot   :  list
           rotion scheme
        Healpix graticule Parameters
        """
        kwargs = self.getkeys(kwargs, 'projtext')
        kwargs['color'] = bkgcolor
        for _t in [60, 120, 180, 240, 300, 360]:
            # deg to hms
            c = astropy.coordinates.SkyCoord(ra=_t * u.degree,
                                             dec=0 * u.degree,
                                             frame='icrs')

            # visualization
            hp.projtext(_t - rot[0],
                        0 - rot[1],
                        '%ih' % c.ra.hms.h,
                        lonlat=True,
                        **kwargs)

        for _p in [30, 60, -30, -60]:

            # visualization
            hp.projtext(0 - rot[0],
                        _p - rot[1],
                        '%.f$^\circ$' % _p,
                        lonlat=True,
                        **kwargs)
Example #3
0
def add_edges():

    hp.graticule(verbose=False)
    plt.grid(True)
    lons = np.arange(-150.0, 180, 30.0)
    lats = np.zeros(lons.shape)
    for lon, lat in zip(lons, lats):
        hp.projtext(lon, lat, "%.0f" % lon, lonlat=True)
    lats = np.arange(-60.0, 90, 30.0)
    lons = np.zeros(lons.shape)
    for lon, lat in zip(lons, lats):
        hp.projtext(lon, lat, "%.0f" % lat, lonlat=True)
Example #4
0
    def _generatePlot(self, table):
        coords, proj = self.__getCoordinatesAndProjection()

        fignum = 1
        self.Plot.figure(num = fignum, tight_layout = True)

        pixels = self.__getPixelsData(table)
        #pixels = self.__getMaskedPixels(pixels)

        cmap = self.Plot.get_cmap(self.Configuration.getValueOf(ChartHealpixOptions.COLOURMAP, "jet"))
        cmap.set_under('w')

        healpy.mollview(pixels, fig = fignum, coord = [coords, proj], unit = 'mas', title = "",
                        min = self.__Min, max = self.__Max, flip = 'astro', cbar = False,
                        cmap = cmap, norm = self.__getNormalization(), nest = self.__nestedPixels())
        healpy.graticule(dpar = 30, dmer = 30, coord = proj, local = None, linestyle = ':',
                         color = 'white')

        healpy.projtext(0,  90,  "90", lonlat = True, coord = proj,
                        verticalalignment = 'bottom', horizontalalignment = 'center',
                        fontsize = 12)
        healpy.projtext(0, 270, "-90", lonlat = True, coord = proj,
                        verticalalignment = 'top', horizontalalignment = 'center',
                        linespacing = 2.0, fontsize = 12)
        healpy.projtext( 179, 0,  "180 ", lonlat = True, coord = proj,
                        verticalalignment = 'center', horizontalalignment = 'right',
                        fontsize = 12)
        healpy.projtext(-179, 0, " -180", lonlat = True, coord = proj,
                        verticalalignment = 'center', horizontalalignment = 'left',
                        fontsize = 12)
Example #5
0
def plotEq():
    hp.mollview(title="SwiftBAT 70 month Seyfert-0 Catalogue")
    hp.graticule(coord='C', color='DimGrey')
    hp.projscatter(ra, dec, coord='C')
    horizon = 90.
    hp.projtext(np.pi / 2, 0.15, s='0$^\circ$', color='DimGrey')
    hp.projtext(np.pi / 2, 2 * np.pi - 0.05, color='DimGrey', s='360$^\circ$')
    ras = np.arange(0., 361., 1.) * np.pi / 180.
    decls_1 = np.ones(len(ras)) * (180. - horizon) * np.pi / 180.
    hp.projplot(decls_1,
                ras,
                color='DimGrey',
                linewidth=1.,
                alpha=0.5,
                coord='G')
    hp.projscatter(0.0,
                   0.0,
                   color='DimGrey',
                   marker='s',
                   coord='G',
                   lonlat=True)
Example #6
0
    def true_image_overlay(self, location, utc_date):
        """Plot current sky.
        Theta is colatitude and measured from North pole. 0 .. pi
         (straight up) |  el:  pi/2   | theta 0
         (horizon)     |  el:  0      | theta pi/2
        Th = pi/2 - el

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

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

        hp.projtext(np.pi / 2, 0.0, "N", rot=(0, 90, 0), va="top", ha="center")
        hp.projtext(np.pi / 2, -np.pi / 2.0, "E", rot=(0, 90, 0), va="center")
        hp.projtext(np.pi / 2, -np.pi, "S", rot=(0, 90, 0), ha="center")
        hp.projtext(
            np.pi / 2, -np.pi * 3.0 / 2.0, "W", rot=(0, 90, 0), ha="right", va="center"
        )
Example #7
0
  def true_image_overlay(self, location, utc_date):
    '''Plot current sky.
    Theta is colatitude and measured from North pole. 0 .. pi
     (straight up) |  el:  pi/2   | theta 0
     (horizon)     |  el:  0      | theta pi/2
    Th = pi/2 - el

    flip : {'astro', 'geo''}, optional
    Defines the convention of projection : 'astro'' (default, east towards left, west towards right) or 'geo' (east towards right, west towards left)
    '''

    l_el, l_az, l_name = self.get_src_positions(location, utc_date)

    th = np.pi/2. - np.array(l_el)
    l_phi = -np.array(l_az)
    _ = [hp.projscatter(i, j, rot=(0,90,0), color='red', alpha=0.5, s=25) for i, j, n in zip(th, l_phi, l_name)]
    _ = [hp.projtext(i, j, n, rot=(0,90,0), color='red') for i, j, n in zip(th, l_phi, l_name)]

    hp.projtext(np.pi/2, 0., 'N', rot=(0,90,0))
    hp.projtext(np.pi/2, -np.pi/2., 'E', rot=(0,90,0))
    hp.projtext(np.pi/2, -np.pi, 'S', rot=(0,90,0))
    hp.projtext(np.pi/2, -np.pi*3./2., 'W', rot=(0,90,0))
Example #8
0
def get_map():
    # Get current time
    now = Time.now()
    T = datetime.utcnow() + timedelta(hours=0)
    T = Time(T, format="datetime")
    loc = astropy.coordinates.EarthLocation(lon=22.13303, lat=-31.58)

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

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

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

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

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

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

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

    count = 0
    for body in ssbodies:
        name = body
        body = astropy.coordinates.get_body(body, T)
        healpy.projscatter(
            body.ra, body.dec, lonlat=True, s=50, color=colors[count], label=name
        )
        healpy.projtext(body.ra, body.dec, lonlat=True, color="k", s=name)
        count += 1
Example #9
0
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
b  = -9.6750019

# Plot cartview a/o mollview #
Example #10
0
def plot_mollmap(lvc_healpix_file, levels=[0.5, 0.9], rot=255):
    """Plot the GW map with the DESI footprint in a Mollweide projection.
    
    Parameters
    ----------
    lvc_healpix_file : str
        Relative or absolute path to LIGO/Virgo HEALPix angular reconstruction file.
    levels : list
        List of credible interval thresholds, e.g., 0.5, 0.9, etc.
    rot : float
        Rotation angle (around z) for map projection, in degrees.
    
    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-OBS']

    # 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

    fig = plt.figure(num=1, figsize=(10, 6))
    hp.mollview(probs,
                fig=1,
                cbar=True,
                unit=r'$dp/d\Omega$ [deg$^{-2}$]',
                title='{} {}'.format(origin, date),
                min=0,
                max=2e-4,
                flip='astro',
                rot=rot,
                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.
    for _dec in [-60, -30, 0, 30, 60]:
        vert = 'top' if _dec < 0 else 'bottom' if _dec > 0 else 'center'
        hp.projtext(180 + rot,
                    _dec,
                    r'{0:+}$^\circ$'.format(_dec),
                    ha='left',
                    va=vert,
                    fontsize=12,
                    lonlat=True)

    # Label longitude lines.
    for _ra in np.arange(0, 360, 45):
        hp.projtext(_ra,
                    -40,
                    r'{:d}$^\circ$'.format(_ra),
                    horizontalalignment='center',
                    fontsize=12,
                    lonlat=True)


#    fig = plt.gcf()
    return fig
Example #11
0
def getObsWindow(date, obs_window):
    # ===================================
    # date is a string with the
    # Universal time, e.g. '2019/3/9 5:13'
    # obs_window is the radius(in degrees)
    # of the maximum deviation from the
    # Sun's antipodal point that HaloSat
    # is allowed to observe.
    # ===================================

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

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

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

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

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

    # Convert to Galactic coordinates
    # -------------------------------
    ap = ephem.Equatorial(win_ra, win_dec, epoch='2000')
    sp = ephem.Equatorial(sun.ra, sun.dec, epoch='2000')
    g = ephem.Galactic(ap)
    s = ephem.Galactic(sp)
    print(g.lon, g.lat)
    vec = hp.ang2vec(g.lon * 57.4, g.lat * 57.2958, lonlat=True)
    local = hp.query_disc(512, vec, cone_radius)
    map[local] = nan
    hp.mollview(map,
                max=6000,
                title='Date: ' + str(halosat.date) + ', Window Center: [RA ' +
                str(win_ra) + ', DEC ' + str(win_dec) + ']')
    hp.projtext(g.lon * 57.2958 + 20,
                g.lat * 57.2958,
                'Obs Window',
                lonlat=True,
                coord='G',
                fontsize=20)
    hp.projscatter(s.lon * 57.2958,
                   s.lat * 57.2958,
                   lonlat=True,
                   s=55,
                   coord='G',
                   color='yellow')
    hp.projtext(s.lon * 57.2958 - 5,
                s.lat * 57.2958,
                'Sun',
                lonlat=True,
                coord='G',
                fontsize=20)
Example #12
0
def makegrid() :
	H.graticule(coord='C',dpar=30,dmer=30,color="black")
	H.projtext(np.pi/2.+0.02,np.pi/3.,r'$60^\circ$',coord='C',color="black",fontsize=10,\
	rotation=0,horizontalalignment='center',verticalalignment='top')
	H.projtext(np.pi/2.+0.02,np.pi*2./3.,r'$120^\circ$',coord='C',color="black",fontsize=10,\
	rotation=0,horizontalalignment='center',verticalalignment='top')
	H.projtext(np.pi/2.+0.02,np.pi,r'$180^\circ$',coord='C',color="black",fontsize=10,\
	rotation=0,horizontalalignment='center',verticalalignment='top')
	H.projtext(np.pi/2.+0.02,-np.pi/3.,r'$300^\circ$',coord='C',color="black",fontsize=10,\
	rotation=0,horizontalalignment='center',verticalalignment='top')
	H.projtext(np.pi/2.+0.02,-np.pi*2./3.,r'$240^\circ$',coord='C',color="black",fontsize=10,\
	rotation=0,horizontalalignment='center',verticalalignment='top')
	H.projtext(np.pi/2.*1/3,0.2,r'$60^\circ$',coord='C',color="black",fontsize=10,\
	rotation=0,horizontalalignment='right',verticalalignment='center')
	H.projtext(np.pi/2.*2/3,0.05,r'$30^\circ$',coord='C',color="black",fontsize=10,\
	rotation=0,horizontalalignment='right',verticalalignment='center')
	H.projtext(np.pi/2.*4/3,0.02,r'$-30^\circ$',coord='C',color="black",fontsize=10,\
	rotation=0,horizontalalignment='right',verticalalignment='center')
	H.projtext(np.pi/2.*5/3,0.02,r'$-60^\circ$',coord='C',color="black",fontsize=10,\
	rotation=0,horizontalalignment='right',verticalalignment='center')
Example #13
0
                          amps=amps)
    response = response[0][0]
    beam_response[all_indexes] = response

    decibel_beam = 10 * log10(beam_response)

    normed_beam = decibel_beam - decibel_beam.max()

    fit_map, diff_map = do_fit_plot(AUT=AUT,
                                    normed_beam=normed_beam,
                                    plot_num=AUT_ind)
    fit_maps.append(fit_map)
    diff_maps.append(diff_map)

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

hp.projtext(80.0 * (pi / 180.0), (0.0 + rot[0]) * (pi / 180.0),
            "S",
            coord='E',
            color='w',
            verticalalignment='bottom',
            weight='bold')
hp.projtext(80.0 * (pi / 180.0), (90.0 + rot[0]) * (pi / 180.0),
            "W",
            coord='E',
            color='w',
            horizontalalignment='left',
            weight='bold')
Example #14
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()
Example #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)
Example #16
0
def myPlot(x, xerr, args):

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

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

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

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

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

    title = makeTitle(args)

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

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

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

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

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


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

    if not args.batch:
        plt.show()
Example #17
0
        plotOtherFOV( 28.757 , -17.887, 2200, 'darkgreen', mjd, args.j2000, astro, coords, upgoing=False)
    # Add HESS FOV Ring
    if args.hess:
        plotOtherFOV(  -23-16.28/60., 16+30./60., 1800, '#cc0000', mjd, args.j2000, astro, coords, upgoing=False)
    # Add IceCube FOV Ring
    if args.icecube:
        plotOtherFOV(  -89-59.5/60., -63, 750, 'lightblue', mjd, args.j2000, astro, coords, upgoing=True)
    # Add VERITASFOV Ring
    if args.veritas:
        plotOtherFOV(  31+40./60., -110-57./60., 1270, '#002699', mjd, args.j2000, astro, coords, upgoing=False)

    if args.preliminary:
        hp.projtext(95*U.degree, 240*U.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 or args.tevcatLabels:
        if haveTeVCat:
            try:
                if args.tevcat:
                    tevcat = TeVCat.TeVCat(args.tevcat)
                elif args.tevcatLabels:
                    tevcat = TeVCat.TeVCat(args.tevcatLabels)
            except IOError as e:
                print(e)
                print("Downloading data from tevcat.uchicago.edu")
Example #18
0
def plot_healpix(
    data_map=None,
    fig=None,
    sub=None,
    title=None,
    vmin=None,
    vmax=None,
    cmap=None,
    cbar=True,
):
    """Yeesh do some healpix magic to plot the thing

    :param data_map: Healpix input map to plot
    :param fig: Figure number to use
    :param sub: Matplotlib subplot syntax
    :param title: Plot title
    :param vmin: Colormap minimum
    :param vmax: Colormap maximum
    :param cmap: Matplotlib :class:`~matplotlib.colors.ListedColormap`
    :param cbar: If True, plot a colorbar

    :returns:
        - Plot of healpix map

    """

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

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

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

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

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

    # NSEW
    hp.projtext(
        80.0 * (np.pi / 180.0),
        000.0 * (np.pi / 180.0),
        r"$N  $",
        coord="E",
        color="w",
        fontweight="light",
        verticalalignment="top",
    )
    hp.projtext(
        80.0 * (np.pi / 180.0),
        090.0 * (np.pi / 180.0),
        r"$E  $",
        coord="E",
        color="w",
        fontweight="light",
        horizontalalignment="right",
    )
    hp.projtext(
        80.0 * (np.pi / 180.0),
        180.0 * (np.pi / 180.0),
        r"$S  $",
        coord="E",
        color="w",
        fontweight="light",
        verticalalignment="bottom",
    )
    hp.projtext(
        80.0 * (np.pi / 180.0),
        270.0 * (np.pi / 180.0),
        r"$W  $",
        coord="E",
        color="w",
        fontweight="light",
        horizontalalignment="left",
    )
## 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()
CenA_ra = 13.0 + (25.0 / 60) + (27.6 / 3600)
CenA_dec = -(43.0 + 1.0 / 60 + 9.0 / 3600)
CenA_target, CenA_phi, CenA_theta = findTarget(NSIDE, CenA_ra, CenA_dec,
                                               my_location)

#%%

x = np.array([TauA_theta, RCW38_theta, CenA_theta])
y = np.array([TauA_phi, RCW38_phi, CenA_phi])
names = ['Tau A', 'RCW38', 'Cen A']
hp.mollview(m, coord=['G', 'E'], norm='hist')
hp.projscatter(x, y, coord=['G'], color='red')
[
    hp.projtext(x[i],
                y[i] - 0.2,
                names[i],
                color='red',
                size='x-large',
                coord=['G', 'E']) for i in range(3)
]

hp.graticule()

#%%

TauA_pixels = hp.query_disc(NSIDE, hp.ang2vec(TauA_theta, TauA_phi),
                            np.pi / 90)
CenA_pixels = hp.query_disc(NSIDE, hp.ang2vec(CenA_theta, CenA_phi),
                            np.pi / 90)
RCW38_pixels = hp.query_disc(NSIDE, hp.ang2vec(RCW38_theta, RCW38_phi),
                             np.pi / 90)
plt.figure(2)
Example #21
0
from astropy.io import fits
hdr1 = fits.getheader(aligo_alert_data_file)


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

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

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

hp.graticule()

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


# In[28]:

# plot the banana map
fig = plt.figure(2, figsize=(10, 10))
Example #22
0
#============= For Mask ========= #
offset = 2.0 #degree

#====== For Plotting ======#
hp.mollview(tau353, title=r'${\tau}_{353}$', coord=['G','C'], unit='', norm=None, min=0.,max=2.0e-5)

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   = tau353[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()
Example #23
0
def prob_observable(m, header, time, plot=False):
    """
    Determine the integrated probability contained in a gravitational-wave
    sky map that is observable with HET at a particular time. Needs hetpix.dat,
    pixels and lonlat of HET pupil, in the directory.

    """

    # Determine resolution of sky map
    mplot = np.copy(m)
    npix = len(m)
    nside = hp.npix2nside(npix)
    # Get time now and Local Sidereal Time
    # time = astropy.time.Time.now()
    # Or at the time of the gravitational-wave event...
    # time = astropy.time.Time(header['MJD-OBS'], format='mjd')
    # Or at a particular time...
    # time = astropy.time.Time(time)

    # Geodetic coordinates of MacDonald Obs

    HET_loc = (-104.01472, 30.6814, 2025)
    hetpupil = np.loadtxt('hetpix.dat')
    hetfullpix = hp.query_strip(nside, minhetdec_rad, \
                            maxhetdec_rad)

    observatory = astropy.coordinates.EarthLocation(lat=HET_loc[1] * u.deg,
                                                    lon=HET_loc[0] * u.deg,
                                                    height=HET_loc[2] * u.m)

    # Find pixels of HET pupil in this time
    t = astropy.time.Time(time, scale='utc', location=HET_loc)
    LST = t.sidereal_time('mean').deg
    HETphi = ((hetpupil[:, 1] + LST) % 360) * np.pi / 180
    HETtheta = (90 - hetpupil[:, 2]) * np.pi / 180
    newpix = hp.ang2pix(nside, HETtheta, HETphi)
    newpixp = newpix

    # Alt/az reference frame at the observatory, in this time
    frame = astropy.coordinates.AltAz(obstime=t, location=observatory)

    # Look up (celestial) spherical polar coordinates of HEALPix grid.
    theta, phi = hp.pix2ang(nside, np.arange(npix))
    # Convert to RA, Dec.
    radecs = astropy.coordinates.SkyCoord(ra=phi * u.rad,
                                          dec=(0.5 * np.pi - theta) * u.rad)
    # Transform grid to alt/az coordinates at observatory, in this time
    altaz = radecs.transform_to(frame)

    #Get RA,DEC of the sun in this time
    sun = astropy.coordinates.get_sun(time)
    # Where is the sun in the Texas sky, in this time?
    sun_altaz = sun.transform_to(frame)

    delta_time = np.linspace(0, 24, 1000) * u.hour
    times24 = t + delta_time
    frames24 = astropy.coordinates.AltAz(obstime=times24, location=observatory)
    sunaltazs24 = astropy.coordinates.get_sun(times24).transform_to(frames24)
    timetilldark = 0 * u.hour
    timetillbright = 0 * u.hour

    nightstart = times24[sunaltazs24.alt < -18 * u.deg][0]
    nighttimemask = np.array((sunaltazs24.alt < -18 * u.deg)) * 1
    if (sun_altaz.alt > -18 * u.deg):
        nightend = times24[(np.roll(nighttimemask, 1) - nighttimemask) != 0][1]
    else:
        nightend = times24[(np.roll(nighttimemask, 1) - nighttimemask) != 0][0]
    nightime = nightend - nightstart
    nightime.format = 'sec'
    #Moving to start of the night if in daytime
    if (sun_altaz.alt > -18 * u.deg):
        timetilldark = (nightstart - t)
        timetilldark.format = 'sec'
        LST = nightstart.sidereal_time('mean').deg
        HETphi = ((hetpupil[:, 1] + LST) % 360) * np.pi / 180
        newpix = hp.ang2pix(nside, HETtheta, HETphi)
    else:
        timetillbright = (nightend - t)
        timetillbright.format = 'sec'

    # How likely is it that the (true, unknown) location of the source
    # is within the area that is visible, in this time and within 24 hours?
    # Demand that it falls in the HETDEX pupil, that the sun is at least 18
    # degrees below the horizon and that the airmass (secant of zenith angle
    # approximation) is at most 2.5.

    msortedpix = np.flipud(np.argsort(m))
    cumsum = np.cumsum(m[msortedpix])
    cls = np.empty_like(m)
    cls[msortedpix] = cumsum * 100
    p90i = np.where(cls <= 90)
    if plot:

        #SUN CIRCLE OF 18 DEGREES
        radius = 18
        phis = Angle(sun.ra).radian
        thetas = 0.5 * np.pi - Angle(sun.dec).radian
        radius = np.deg2rad(radius)
        xyz = hp.ang2vec(thetas, phis)
        ipix_sun = hp.query_disc(nside, xyz, radius)

        #Coloring the plot, order important here!
        mplot[:] = 1
        mplot[altaz.secz > 2.5] = 0.1
        mplot[altaz.alt < 0] = 0.99
        mplot[newpixp] = 0.2
        mplot[p90i] = 0.4
        mplot[ipix_sun] = 0.6
        hp.mollview(mplot,
                    coord='C',
                    cmap='nipy_spectral',
                    cbar=False,
                    max=1,
                    title='HET NOW')
        hp.graticule(local=True)
        ax1 = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24]
        for ii in ax1:
            hp.projtext(ii / 24. * 360 - 1, -5, str(ii) + 'h', lonlat=True)
        ax2 = [60, 30, 0, -30, -60]
        for ii in ax2:
            hp.projtext(360. / 2, ii, '   ' + str(ii) + '°', lonlat=True)
        plt.savefig('MOLL_GWHET_%s.png' % header['GraceID'])
        #plt.show()

        #from astropy.wcs import WCS

        #ax = plt.subplot(1,1,1, projection=WCS(target_header))
        #ax.imshow(array, vmin=0, vmax=1.e-8)
        #ax.coords.grid(color='white')
        #ax.coords.frame.set_color('none')
        #plt.show()
    theta90, phi90 = hp.pix2ang(nside, p90i)
    #mask skymap pixels by hetdex accesible region
    theta90HETi = (theta90 > minhetdec_rad) * (theta90 < maxhetdec_rad)
    print(theta90HETi.sum(), theta90.min(), theta90.max())
    theta90HET = theta90[theta90HETi]
    phi90HET = phi90[theta90HETi]
    timetill90 = 0
    #if the region doesn't intersect HET now
    if len(np.intersect1d(p90i, newpix)) == 0:
        #if the region doesn't intersect HET at all
        if len(np.intersect1d(p90i, hetfullpix)) == 0:
            return 0, 0, -99, 0
        hetedge = np.loadtxt('hetedge.dat')
        hetedgef = lambda x: np.interp(x, hetedge[:, 0], hetedge[:, 1])
        y = theta90HET * 180 / np.pi  #DEC SKYMAP
        x = (phi90HET * 180 / np.pi - LST) % 360  #RA SKYMAP ZEROING HET PUPIL
        wsecs = np.min(x - hetedgef(y)) * 3600 * 12 / 180
        if wsecs < 0:
            #it's inside the pupil...
            hetedgef2 = lambda x: np.interp(x, hetedge[:, 0], hetedge[:, 2])
            y = (hetedgef2(y) + 180) % 360 - 180
            x = (x + 180) % 360 - 180
            wsecs = np.min(x - y) * 3600 * 12 / 180

        if timetilldark == 0:
            if wsecs > timetillbright.value:
                return 0, 0, -99, 0
        else:
            if wsecs > nightime.value:
                return 0, 0, -99, 0
        timetill90 = (wsecs + timetilldark.value) / 3600
    elif timetilldark.value > 0:
        timetill90 = timetilldark.value / 3600

    mask_arraynow = np.zeros(len(m), dtype=int)
    mask_arraynow[newpixp] = 1
    mask_arraynow *= (altaz.secz <= 2.5) & (sun_altaz.alt <= -18 * u.deg)

    prob = m[mask_arraynow > 0].sum()
    probfull = m[np.intersect1d(p90i, hetfullpix)].sum()
    m[np.setdiff1d(np.arange(len(m)),
                   np.intersect1d(p90i, hetfullpix),
                   assume_unique=True)] = m.min()
    #hp.orthview(m)
    #plt.show()
    #plt.savefig('MOLL_GWHET_%s.pdf'%header['GraceID'])
    # Done!
    return prob, probfull, timetill90, m
Example #24
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
Example #25
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   = 3.5            # Beam = 3.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/10.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]

		sr = 15

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

		if (i == sr):
			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) and (i == sr) ):
					hp.projtext(x, y, '.', lonlat=True, coord='G')

	plt.show()
Example #26
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()
Example #27
0
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()
Example #28
0
def get_map():
    # Get current time
    now = Time.now()
    sidereal = now.sidereal_time("mean", longitude=22.13303)
    loc = astropy.coordinates.EarthLocation(lon=22.13303, lat=-31.58)
    T = Time(now, format="datetime", location=loc)
    # T = Time('2019-07-23 15:46:30', scale='utc', location = loc)
    print(T)

    ra = (now.sidereal_time("mean", longitude=22.13303)) / u.hourangle
    dec = -31.58
    rot = [-112.13, -31.06]

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

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

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

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

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

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

    count = 0
    for body in ssbodies:
        name = body
        body = astropy.coordinates.get_body(body, T)
        healpy.projscatter(body.ra,
                           body.dec,
                           lonlat=True,
                           s=50,
                           c=colors[count],
                           label=name)
        healpy.projtext(body.ra, body.dec, lonlat=True, c="k", s=name)
        count += 1
Example #29
0
def plot_healpix(data_map=None,
                 sub=None,
                 title=None,
                 vmin=None,
                 vmax=None,
                 cmap=None):
    if vmin == None:
        if cmap == None:
            hp.orthview(map=data_map,
                        coord='E',
                        half_sky=True,
                        xsize=400,
                        title=title,
                        rot=(0, 90, 0),
                        sub=sub)
        else:
            hp.orthview(map=data_map,
                        coord='E',
                        half_sky=True,
                        xsize=400,
                        title=title,
                        rot=(0, 90, 0),
                        sub=sub,
                        cmap=cmap)
    else:
        if cmap == None:
            hp.orthview(map=data_map,
                        coord='E',
                        half_sky=True,
                        xsize=400,
                        title=title,
                        rot=(0, 90, 0),
                        sub=sub,
                        min=vmin,
                        max=vmax)
        else:
            hp.orthview(map=data_map,
                        coord='E',
                        half_sky=True,
                        xsize=400,
                        title=title,
                        rot=(0, 90, 0),
                        sub=sub,
                        min=vmin,
                        max=vmax,
                        cmap=cmap)

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

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

    hp.projtext(90.0 * (pi / 180.0),
                0.0,
                r'$0^\circ$',
                coord='E',
                color='k',
                verticalalignment='top')
    hp.projtext(90.0 * (pi / 180.0),
                90.0 * (pi / 180.0),
                r'$90^\circ$',
                coord='E',
                color='k',
                horizontalalignment='right')
    hp.projtext(90.0 * (pi / 180.0),
                180.0 * (pi / 180.0),
                r'$180^\circ$',
                coord='E',
                color='k')
    hp.projtext(90.0 * (pi / 180.0),
                270.0 * (pi / 180.0),
                r'$270^\circ$',
                coord='E',
                color='k')
Example #30
0
beam    = 3.5
dbeam   = beam/120.0 # Beam = 3.5' -> dbeam = beam/60/2
dbeam   = 0.5
edge    = dbeam/40. # To plot a rectangle about the source
info    = read_info_no_co('../../co12/result/26src_no_co_with_sponge.dat')

## CO Dame Map, NSIDE = 512 ##
map_file = os.getenv("HOME")+'/hdata/co/lambda_wco_dht2001.fits'
co_map   = hp.read_map(map_file, field = 1, h=False)

## Color map ##
nside = 512
# cmap  = plt.cm.get_cmap('winter')
hp.mollview(co_map, title='Velocity Integrated CO Map', coord='G', unit='K km/sec', rot=[0,0,0], norm='hist', xsize=800)

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   = msk[pix]
	print src, l,b,pix, val
	hp.projplot(l, b, 'bx', lonlat=True, coord='G')
	# hp.projtext(l, b, src+','+str(l)+','+str(b), lonlat=True, coord='G')
	hp.projtext(l, b, src+','+str(val), lonlat=True, coord='G')

hp.graticule()
plt.show()
                        ysize=args.zoom,
                        sub=211,
                        cbar=False,
                        reso=1.0,
                        notext=True,
                        coord='C')
            pass

        hp.graticule()
        ax = plt.gca()
        if args.zoom is None:
            lat = 0
            for lon in lons:
                hp.projtext(lon,
                            lat,
                            '%d$^{\circ}$' % (lon),
                            lonlat=True,
                            size=ticks_size,
                            va='bottom')
            lon = 179.9 + 180
            for lat in lats:
                if lat == 0:
                    va = 'center'
                    continue
                elif lat > 0:
                    va = 'bottom'
                else:
                    va = 'top'
                    pass
                hp.projtext(lon,
                            lat,
                            r'%d$^{\circ}$ ' % (lat),
Example #32
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()
def plot_healpix(data_map=None,
                 sub=None,
                 title=None,
                 vmin=None,
                 vmax=None,
                 cmap=None,
                 labels=True):
    '''Y'know, plot healpix maps'''
    rot = (-45, 90, 0)

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

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

    if labels == True:

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

        hp.projtext(80.0 * (pi / 180.0), (0.0 + rot[0]) * (pi / 180.0),
                    "S",
                    coord='E',
                    color='w',
                    verticalalignment='bottom',
                    weight='bold')
        hp.projtext(80.0 * (pi / 180.0), (90.0 + rot[0]) * (pi / 180.0),
                    "W",
                    coord='E',
                    color='w',
                    horizontalalignment='left',
                    weight='bold')
        hp.projtext(80.0 * (pi / 180.0), (180.0 + rot[0]) * (pi / 180.0),
                    "N",
                    coord='E',
                    color='w',
                    verticalalignment='top',
                    weight='bold')
        hp.projtext(80.0 * (pi / 180.0), (270.0 + rot[0]) * (pi / 180.0),
                    'E',
                    coord='E',
                    color='w',
                    horizontalalignment='right',
                    weight='bold')
Example #34
0
def _plot_exampleSED(dictionary, center, nus_out, maskmaps, savefig = None):

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

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

	capsize=3
	plt.rc('font', size=16)

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

	fig,ax = plt.subplots(nrows=1,ncols=2,figsize=(14,5),)
	ax = ax.ravel()
	IPIXG = pixG[0]
	ax[1].plot(nus_out, maskmaps[:,IPIXG,0], 'o-', color='r')
	ax[1].set_ylabel(r'$I_\nu$ [$\mu$K]')
	ax[1].set_xlabel(r'$\nu$[GHz]')
	ax[0].cla()
	plt.axes(ax[0])
	hp.gnomview(maskmaps[-1,:,0], reso = 15,hold = True, title = ' ',unit = r'$\mu$K', notext =True,
				min = 0 ,
				max = 0.23 * np.max(maskmaps[-1,:,0]), rot = center)
	hp.projscatter(hp.pix2ang(dictionary['nside'], IPIXG), marker = '*', color = 'r',s = 180)
	dpar = 10
	dmer = 20
	#Watch out, the names are wrong (change it)
	mer_coordsG = [ center[0] - dmer,   center[0], center[0] + dmer]
	long_coordsG = [center[1] - 2*dpar, center[1] - dpar, center[1], 
					center[1] + dpar,   center[1] + 2 * dpar]
	#paralels
	for ilong in long_coordsG:
		plt.text(np.deg2rad(mer_coordsG[0] - 13), 1.1*np.deg2rad(ilong), 
				 r'{}$\degree$'.format(ilong))
	#meridians
	for imer in mer_coordsG:
		if imer < 0:
			jmer = imer + 360
			ip, dp = divmod(jmer/15,1)
		else:
			ip, dp = divmod(imer/15,1)
		if imer == 0:
			plt.text(-np.deg2rad(imer + 3), np.deg2rad(long_coordsG[-1] + 6), 
				 r'{}$\degree$'.format(int(ip) ))
		else:
			plt.text(-np.deg2rad(imer + 3), np.deg2rad(long_coordsG[-1] + 6), 
				 r'{}$\degree$'.format(imer))

	hp.projtext(mer_coordsG[1] + 2, long_coordsG[0] - 6, '$l$',  color = 'k', lonlat=True)
	hp.projtext(mer_coordsG[2] + 12.5, long_coordsG[2] - 1, '$b$', rotation = 90, color = 'k', lonlat=True)
	hp.graticule(dpar = dpar, dmer = dmer, alpha = 0.6, verbose = False)
	plt.tight_layout()
	if savefig != None:
		plt.savefig('true-sky.svg', format = 'svg',  bbox_inches='tight')
		plt.savefig('true-sky.pdf', format = 'pdf',  bbox_inches='tight')
		plt.savefig('true-sky',  bbox_inches='tight')
	plt.show()
Example #35
0
def make_figure(moll=True, ecliptic=False, footprint=True, idr2=True, cmap='Greys', title='test', highlight=False, highlight_survey='HYDRA', highlight_tile='HYDRA-0011', path='./'):

    alpha = 0.3
    lw = 2

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

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

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

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

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

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

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

    H.graticule()   # draw the coordinate system axes

    return 0
			 r'{}$\degree$'.format(ilong))
#meridians
for imer in mer_coordsG:
	if imer < 0:
		jmer = imer + 360
		ip, dp = divmod(jmer/15,1)
	else:
		ip, dp = divmod(imer/15,1)
	if imer == 0:
		plt.text(-np.deg2rad(imer + 3), np.deg2rad(long_coordsG[-1] + 6), 
			 r'{}$\degree$'.format(int(ip) ))
	else:
		plt.text(-np.deg2rad(imer + 3), np.deg2rad(long_coordsG[-1] + 6), 
			 r'{}$\degree$'.format(imer))
			 #r'{}h{}m'.format(int(ip), int(round(dp*60))))
hp.projtext(mer_coordsG[1] + 2, long_coordsG[0] - 6, '$l$',  color = 'k', lonlat=True)
hp.projtext(mer_coordsG[2] + 12.5, long_coordsG[2] - 1, '$b$', rotation = 90, color = 'k', lonlat=True)

ax[3].cla()
plt.axes(ax[3])
hp.gnomview(maps_ud[1, -1, :, 0], reso = 15, hold = True, 
			notext = True, title = ' ',
			unit = r'$\mu$K',
			min = 0,
			max = 0.4*np.max(maps_ud[1, -1, :, 0]), 
			rot = centerQ)
hp.projscatter(hp.pix2ang(nside_new, pixQ_ud),marker = '*', color = 'r', s = 180)

mer_coordsQ = [centers[1][0] - dmer, centers[0][0]+0, centers[0][0] + dmer]
long_coordsQ = [centers[0][1] - 2*dpar, centers[0][1] - dpar, centers[0][1], 
				centers[0][1] + dpar, centers[0][1] + 2 * dpar]
Example #37
0
ra_ctest=(265,265,255,255)
dec_ctest=(-35,-25,-35,-25)

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

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

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

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

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


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

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

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

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

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

	hp.projtext(mer_coordsG[1] + 2, long_coordsG[0] - 6, '$l$',  color = 'k', lonlat=True)
	hp.projtext(mer_coordsG[2] + 12.5, long_coordsG[2] - 1, '$b$', rotation = 90, color = 'k', lonlat=True)
	hp.graticule(dpar = dpar, dmer = dmer, alpha = 0.6, verbose = False)
	plt.tight_layout()
	if savefig:
		plt.savefig('SED-components.svg', format = 'svg',  bbox_inches='tight')
		plt.savefig('SED-components.pdf', format = 'pdf',  bbox_inches='tight')
		plt.savefig('SED-components',  bbox_inches='tight')
	plt.show()
def plot_healpix(
    data_map=None,
    fig=None,
    sub=None,
    title=None,
    vmin=None,
    vmax=None,
    cmap=None,
    cbar=True,
):
    """Yeesh do some healpix magic to plot the thing"""

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

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

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

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

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

    # NSEW
    hp.projtext(
        80.0 * (np.pi / 180.0),
        000.0 * (np.pi / 180.0),
        r"$N  $",
        coord="E",
        color="w",
        fontweight="light",
        verticalalignment="top",
    )
    hp.projtext(
        80.0 * (np.pi / 180.0),
        090.0 * (np.pi / 180.0),
        r"$E  $",
        coord="E",
        color="w",
        fontweight="light",
        horizontalalignment="right",
    )
    hp.projtext(
        80.0 * (np.pi / 180.0),
        180.0 * (np.pi / 180.0),
        r"$S  $",
        coord="E",
        color="w",
        fontweight="light",
        verticalalignment="bottom",
    )
    hp.projtext(
        80.0 * (np.pi / 180.0),
        270.0 * (np.pi / 180.0),
        r"$W  $",
        coord="E",
        color="w",
        fontweight="light",
        horizontalalignment="left",
    )
Example #40
0
def plot_healpix(data_map=None,
                 sub=None,
                 title=None,
                 vmin=None,
                 vmax=None,
                 cmap=None):
    '''Does some plotting what what'''
    if vmin == None:
        if cmap == None:
            half_sky = hp.orthview(map=data_map,
                                   coord='E',
                                   half_sky=True,
                                   xsize=400,
                                   title=title,
                                   rot=(0, 90, 0),
                                   sub=sub,
                                   notext=True,
                                   return_projected_map=True)
        else:
            half_sky = hp.orthview(map=data_map,
                                   coord='E',
                                   half_sky=True,
                                   xsize=400,
                                   title=title,
                                   rot=(0, 90, 0),
                                   sub=sub,
                                   cmap=cmap,
                                   notext=True,
                                   return_projected_map=True)
    else:
        if cmap == None:
            half_sky = hp.orthview(map=data_map,
                                   coord='E',
                                   half_sky=True,
                                   xsize=400,
                                   title=title,
                                   rot=(0, 90, 0),
                                   sub=sub,
                                   min=vmin,
                                   max=vmax,
                                   notext=True,
                                   return_projected_map=True)
        else:
            half_sky = hp.orthview(map=data_map,
                                   coord='E',
                                   half_sky=True,
                                   xsize=400,
                                   title=title,
                                   rot=(0, 90, 0),
                                   sub=sub,
                                   min=vmin,
                                   max=vmax,
                                   cmap=cmap,
                                   notext=True,
                                   return_projected_map=True)
    hp.graticule(dpar=10, coord='E', color='k', alpha=0.3, dmer=45)
    #print where(half_sky == nan)

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

    hp.projtext(90.0 * (pi / 180.0),
                0.0,
                r'$0^\circ$',
                coord='E',
                color='k',
                verticalalignment='top')
    hp.projtext(90.0 * (pi / 180.0),
                90.0 * (pi / 180.0),
                r'$90^\circ$',
                coord='E',
                color='k',
                horizontalalignment='right')
    hp.projtext(90.0 * (pi / 180.0),
                180.0 * (pi / 180.0),
                r'$180^\circ$',
                coord='E',
                color='k')
    hp.projtext(90.0 * (pi / 180.0),
                270.0 * (pi / 180.0),
                r'$270^\circ$',
                coord='E',
                color='k')
Example #41
0
def plot_gaia_density(
    positions: pd.DataFrame,
    path_gaia_density: Union[str, pathlib.Path],
    title: Optional[str] = None,
    save: Optional[Union[str, pathlib.Path]] = None,
):
    """Plot the RA/DEC Gaia density plot with a sample of objects over-plotted

    source: https://vlas.dev/post/gaia-dr2-hrd/

    """
    # plot the H-R diagram for 1 M stars within 200 pc from the Sun
    plt.rc("text", usetex=True)

    # load the data
    hdulist = fits.open(path_gaia_density)
    hist = hdulist[1].data["srcdens"][np.argsort(hdulist[1].data["hpx8"])]

    # make figure
    fig, ax = plt.subplots(figsize=(6, 6), dpi=200)
    if title is not None:
        fig.suptitle(title, fontsize=24)

    # background setup
    coordsys = ["C", "C"]
    nest = True

    # colormap
    cm = plt.cm.get_cmap("viridis")  # colorscale
    cm.set_under("w")
    cm.set_bad("w")

    # plot the data in healpy
    norm = "log"
    hp.mollview(
        hist,
        norm=norm,
        unit="Stars per sq. arcmin.",
        cbar=False,
        nest=nest,
        title="",
        coord=coordsys,
        notext=True,
        cmap=cm,
        flip="astro",
        nlocs=4,
        min=0.1,
        max=300,
    )
    ax = plt.gca()
    image = ax.get_images()[0]
    cbar = fig.colorbar(
        image,
        ax=ax,
        ticks=[0.1, 1, 10, 100],
        fraction=0.15,
        pad=0.05,
        location="bottom",
    )
    cbar.set_label("Stars per sq. arcmin.", size=12)
    cbar.ax.tick_params(labelsize=12)

    ax.tick_params(axis="both", which="major", labelsize=24)

    # borders
    lw = 3
    pi = np.pi
    dtor = pi / 180.0
    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.0e-10, phi, "-k", lw=lw, direct=True)
    hp.projplot(phi * 0 + pi - 1.0e-10, phi, "-k", lw=lw, direct=True)

    # ZTF
    theta = np.arange(0.0, 360, 0.036)
    phi = -30.0 * np.ones_like(theta)
    hp.projplot(theta, phi, "k--", coord=["C"], lonlat=True, lw=2)
    hp.projtext(170.0, -24.0, r"ZTF Limit", lonlat=True)

    # galaxy
    for gallat in [15, 0, -15]:
        theta = np.arange(0.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.0, 360, 0.036)
        phi = ecllat * np.ones_like(theta)
        hp.projplot(theta, phi, "w-", coord=["E"], lonlat=True, lw=2, ls=":")

    # graticule
    hp.graticule(ls="-", alpha=0.1, lw=0.5)

    # labels
    for lat in [60, 30, 0, -30, -60]:
        hp.projtext(360.0, lat, str(lat), lonlat=True)
    for lon in [0, 60, 120, 240, 300]:
        hp.projtext(lon, 0.0, str(lon), lonlat=True)

    # NWES
    plt.text(0.0, 0.5, r"E", ha="right", transform=ax.transAxes, weight="bold")
    plt.text(1.0, 0.5, r"W", ha="left", transform=ax.transAxes, weight="bold")
    plt.text(
        0.5,
        0.992,
        r"N",
        va="bottom",
        ha="center",
        transform=ax.transAxes,
        weight="bold",
    )
    plt.text(0.5,
             0.0,
             r"S",
             va="top",
             ha="center",
             transform=ax.transAxes,
             weight="bold")

    color = "k"
    lw = 10
    alpha = 0.75

    for pos in positions:
        hp.projplot(
            pos[0],
            pos[1],
            color=color,
            markersize=5,
            marker="o",
            coord=coordsys,
            lonlat=True,
            lw=lw,
            alpha=alpha,
            zorder=10,
        )

    if save is not None:
        fig.tight_layout()
        plt.savefig(save)
Example #42
0
def creat_map(mkffile, ra, dec, time, outfile):

    mkfdata = fits.getdata(mkffile, 1)

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

    plotfile = PdfPages(outfile)

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

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

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

    #Earth Occult

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

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

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

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

    plotfile.savefig()

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

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

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

    plotfile.savefig()

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

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

    plotfile.savefig()

    plotfile.close()

    return
Example #43
0
def plot_patches(src_num, info):
	# Define constants #
	deg2rad   = np.pi/180.
	# Define the width of area #
	beam   = 14.4           # Beam = 3.5'
	dbeam  = beam/60./2.     # Beam = 3.5' -> dbeam = beam/60/2 in degree
	offset = dbeam          # degree

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

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

		# if(i != 14): continue

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

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

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

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

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

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

		print proj
		print proj.shape

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

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

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

		plt.show()
Example #44
0
import healpy as hp
import numpy as np
import pylab as pl

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

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

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

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

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