Esempio n. 1
0
 def draw_inset_colorbar(self, *args, **kwargs):
     defaults = dict(loc=3,
                     width="30%",
                     height="4%",
                     bbox_to_anchor=(0, 0.05, 1, 1))
     setdefaults(kwargs, defaults)
     super(DESSkymapMcBryde, self).draw_inset_colorbar(*args, **kwargs)
Esempio n. 2
0
    def draw_inset_colorbar(self,
                            format=None,
                            label=None,
                            ticks=None,
                            fontsize=11,
                            **kwargs):
        defaults = dict(width="25%",
                        height="5%",
                        loc=7,
                        bbox_to_anchor=(0., -0.04, 1, 1))
        setdefaults(kwargs, defaults)

        ax = plt.gca()
        im = plt.gci()
        cax = inset_axes(ax, bbox_transform=ax.transAxes, **kwargs)
        cmin, cmax = im.get_clim()

        if (ticks is None) and (cmin is not None) and (cmax is not None):
            cmed = (cmax + cmin) / 2.
            delta = (cmax - cmin) / 10.
            ticks = np.array([cmin + delta, cmed, cmax - delta])

        tmin = np.min(np.abs(ticks[0]))
        tmax = np.max(np.abs(ticks[1]))

        if format is None:
            if (tmin < 1e-2) or (tmax > 1e3):
                format = '$%.1e$'
            elif (tmin > 0.1) and (tmax < 100):
                format = '$%.1f$'
            elif (tmax > 100):
                format = '$%i$'
            else:
                format = '$%.2g$'
                #format = '%.2f'

        kwargs = dict(format=format, ticks=ticks, orientation='horizontal')

        if format == 'custom':
            ticks = np.array([cmin, 0.85 * cmax])
            kwargs.update(format='$%.0e$', ticks=ticks)

        cbar = plt.colorbar(cax=cax, **kwargs)
        cax.xaxis.set_ticks_position('top')
        cax.tick_params(axis='x', labelsize=fontsize)

        if format == 'custom':
            ticklabels = cax.get_xticklabels()
            for i, l in enumerate(ticklabels):
                val, exp = ticklabels[i].get_text().split('e')
                ticklabels[i].set_text(r'$%s \times 10^{%i}$' %
                                       (val, int(exp)))
            cax.set_xticklabels(ticklabels)

        if label is not None:
            cbar.set_label(label, size=fontsize)
            cax.xaxis.set_label_position('top')

        plt.sca(ax)
        return cbar, cax
Esempio n. 3
0
    def draw_polygon(self, filename, **kwargs):
        """ Draw a polygon footprint. """
        defaults = dict(color='k', lw=2)
        setdefaults(kwargs, defaults)

        poly = np.loadtxt(filename, dtype=[('ra', float), ('dec', float)])
        return self.draw_polygon_radec(poly['ra'], poly['dec'], **kwargs)
Esempio n. 4
0
    def draw_bliss(self,**kwargs):
        """Draw the BLISS footprint"""
        defaults=dict(color='magenta', lw=2)
        setdefaults(kwargs,defaults)

        filename = os.path.join(get_datadir(),'bliss-poly.txt')
        self.draw_polygons(filename,**kwargs)
Esempio n. 5
0
    def draw_des19(self,**kwargs):
        """ Draw the DES footprint. """
        defaults=dict(color='blue', lw=2)
        setdefaults(kwargs,defaults)

        filename = os.path.join(get_datadir(),'des-round19-poly.txt')
        return self.draw_polygon(filename,**kwargs)
Esempio n. 6
0
    def draw_maglites(self,**kwargs):
        """Draw the MagLiteS footprint"""
        defaults=dict(color='blue', lw=2)
        setdefaults(kwargs,defaults)

        filename = os.path.join(get_datadir(),'maglites-poly.txt')
        self.draw_polygon(filename,**kwargs)
Esempio n. 7
0
    def __init__(self, *args, **kwargs):
        self.set_observer(kwargs.pop('observer', None))
        self.set_date(kwargs.pop('date', None))

        setdefaults(kwargs, self.defaults)
        parallels = kwargs.pop('parallels', True)
        meridians = kwargs.pop('meridians', True)
        super(Skymap, self).__init__(*args, **kwargs)

        if parallels:
            self.draw_parallels()
        if meridians:
            self.draw_meridians()

        # Coordinate formatter
        # This is creating an axes (which we really don't want)
        # Better to stick in set_axes_limits
        ax = self._check_ax()

        def format_coord(x, y):
            return 'lon=%1.4f, lat=%1.4f' % self(x, y, inverse=True)

        plt.gca().format_coord = format_coord

        self.wrap_angle = np.mod(kwargs['lon_0'] + 180, 360)

        self.resolution = 'c'
Esempio n. 8
0
    def draw_planet9(self,**kwargs):
        from scipy.interpolate import interp1d
        from scipy.interpolate import UnivariateSpline
        defaults=dict(color='b',lw=3)
        setdefaults(kwargs,defaults)
        datadir = '/home/s1/kadrlica/projects/bliss/v0/data/'
        datadir = '/Users/kadrlica/bliss/observing/data/'
        ra_lo,dec_lo=np.genfromtxt(datadir+'p9_lo.txt',usecols=(0,1)).T
        ra_lo,dec_lo = self.roll(ra_lo,dec_lo)
        ra_lo += -360*(ra_lo > 180)
        ra_lo,dec_lo = ra_lo[::-1],dec_lo[::-1]
        ra_hi,dec_hi=np.genfromtxt(datadir+'p9_hi.txt',usecols=(0,1)).T
        ra_hi,dec_hi = self.roll(ra_hi,dec_hi)
        ra_hi += -360*(ra_hi > 180)
        ra_hi,dec_hi = ra_hi[::-1],dec_hi[::-1]

        spl_lo = UnivariateSpline(ra_lo,dec_lo)
        ra_lo_smooth = np.linspace(ra_lo[0],ra_lo[-1],360)
        dec_lo_smooth = spl_lo(ra_lo_smooth)

        spl_hi = UnivariateSpline(ra_hi,dec_hi)
        ra_hi_smooth = np.linspace(ra_hi[0],ra_hi[-1],360)
        dec_hi_smooth = spl_hi(ra_hi_smooth)

        #self.plot(ra_lo,dec_lo,latlon=True,**kwargs)
        #self.plot(ra_hi,dec_hi,latlon=True,**kwargs)
        self.plot(ra_lo_smooth,dec_lo_smooth,latlon=True,**kwargs)
        self.plot(ra_hi_smooth,dec_hi_smooth,latlon=True,**kwargs)

        orb = pd.read_csv(datadir+'P9_orbit_Cassini.csv').to_records(index=False)[::7]
        kwargs = dict(marker='o',s=40,edgecolor='none',cmap='jet_r')
        self.scatter(*self.proj(orb['ra'],orb['dec']),c=orb['cassini'],**kwargs)
Esempio n. 9
0
    def __init__(self, *args, **kwargs):
        defaults = dict(projection='laea',lon_0=120,lat_0=-90,
                        llcrnrlon=-110,llcrnrlat=8,
                        urcrnrlon=60,urcrnrlat=-15,
                        round=False,celestial=False)

        setdefaults(kwargs,defaults)
        super(SurveySkymap,self).__init__(*args, **kwargs)
Esempio n. 10
0
    def draw_hpxmap_rgb(self, r, g, b, xsize=800, **kwargs):
        hpxmap = healpix.masked_array(np.array([r, g, b]))

        vmin, vmax = np.percentile(hpxmap.compressed(), [0.1, 99.9])

        defaults = dict(latlon=True, rasterized=True, vmin=vmin, vmax=vmax)
        setdefaults(kwargs, defaults)

        #ax = plt.gca()
        #lonra = [-180.,180.]
        #latra = [-90.,90]

        #lon = np.linspace(lonra[0], lonra[1], xsize)
        #lat = np.linspace(latra[0], latra[1], xsize*self.aspect)
        #lon, lat = np.meshgrid(lon, lat)

        #nside = hp.get_nside(hpxmap.data)
        #try:
        #    pix = hp.ang2pix(nside,lon,lat,lonlat=True)
        #except TypeError:
        #    pix = hp.ang2pix(nside,np.radians(90-lat),np.radians(lon))

        lonra, latra = self.get_map_range(r)

        lon, lat, R = self.hpx2xy(r, lonra=lonra, latra=latra, xsize=xsize)
        _, _, G = self.hpx2xy(g, lonra=lonra, latra=latra, xsize=xsize)
        _, _, B = self.hpx2xy(b, lonra=lonra, latra=latra, xsize=xsize)

        # Colors are all normalized to R... probably not desired...
        #norm = np.nanmax(R)
        #r = self.set_scale(R,norm=norm)
        #g = self.set_scale(G,norm=norm)
        #b = self.set_scale(B,norm=norm)

        # Better?
        norm = np.percentile(R[~np.isnan(R)], 97.5)
        kw = dict(log=False, sigma=0.5, norm=norm)
        r = self.set_scale(R, **kw)
        g = self.set_scale(G, **kw)
        b = self.set_scale(B, **kw)

        #rgb = np.array([r,g,b]).T
        color_tuples = np.array([
            r[:-1, :-1].filled(np.nan).flatten(),
            g[:-1, :-1].filled(np.nan).flatten(),
            b[:-1, :-1].filled(np.nan).flatten()
        ]).T
        color_tuples[np.where(np.isnan(color_tuples))] = 0.0
        setdefaults(kwargs, {'color': color_tuples})

        if self.projection is 'ortho':
            im = self.pcolor(lon, lat, r, **kwargs)
        else:
            im = self.pcolormesh(lon, lat, r, **kwargs)
        plt.gca().set_facecolor((0, 0, 0))
        plt.draw()

        return im, lon, lat, r, color_tuples
Esempio n. 11
0
    def draw_smash(self,**kwargs):
        """ Draw the SMASH fields. """
        defaults=dict(facecolor='none',color='k')
        setdefaults(kwargs,defaults)

        filename = os.path.join(get_datadir(),'smash_fields_final.txt')
        smash=np.genfromtxt(filename,dtype=[('ra',float),('dec',float)],usecols=[4,5])
        xy = self.proj(smash['ra'],smash['dec'])
        self.scatter(*xy,**kwargs)
Esempio n. 12
0
 def __init__(self, *args, **kwargs):
     defaults = dict(projection='splaea',
                     lon_0=60,
                     boundinglat=-20,
                     round=True,
                     celestial=True,
                     parallels=True)
     setdefaults(kwargs, defaults)
     super(SurveySkymap, self).__init__(*args, **kwargs)
Esempio n. 13
0
    def draw_sfd(self, **kwargs):
        defaults = dict(rasterized=True, cmap=plt.cm.binary)
        setdefaults(kwargs, defaults)
        dirname = get_datadir()
        filename = 'lambda_sfd_ebv.fits'

        galhpx = hp.read_map(os.path.join(dirname, filename))
        celhpx = obztak.utils.projector.hpx_gal2cel(galhpx)
        return self.draw_hpxmap(np.log10(celhpx), **kwargs)
Esempio n. 14
0
    def draw_parallels(self,*args,**kwargs):
        defaults = dict(labels=[0,0,0,0])
        setdefaults(kwargs,defaults)
        ret =  super(DESLambert,self).draw_parallels(*args,**kwargs)

        ax = plt.gca()
        for l in ret.keys():
            ax.annotate(r"$%+d{}^{\circ}$"%(l), self(0,l),xycoords='data',
                        xytext=(+5,+5),textcoords='offset points',
                        va='top',ha='left',fontsize=12)
        return ret
Esempio n. 15
0
    def draw_sfd(self,filename=None,**kwargs):
        import healpy as hp
        defaults = dict(rasterized=True,cmap=plt.cm.binary)
        setdefaults(kwargs,defaults)
        if not filename:
            datadir  = '/Users/kadrlica/bliss/observing/data/'
            filename = datadir+'lambda_sfd_ebv.fits'

        galhpx = hp.read_map(filename)
        celhpx = hpx_gal2cel(galhpx)
        return self.draw_hpxmap(np.log10(celhpx),**kwargs)
Esempio n. 16
0
 def draw_parallels(self, *args, **kwargs):
     defaults = dict(labels=[1, 0, 0, 1],
                     labelstyle='+/-',
                     dashes=(2, 3),
                     color='gray',
                     linewidth=0.75)
     if not args:
         defaults.update(circles=np.arange(-60, 90, 30))
     if self.projection in ['ortho', 'geos', 'nsper', 'aeqd', 'vandg']:
         defaults.update(labels=[0, 0, 0, 0])
     setdefaults(kwargs, defaults)
     return self.drawparallels(*args, **kwargs)
Esempio n. 17
0
 def draw_meridians(self,*args,**kwargs):
     defaults = dict(labels=[1,1,1,1],fontsize=14,labelstyle='+/-')
     setdefaults(kwargs,defaults)
     cardinal = kwargs.pop('cardinal',False)
     meridict = super(OrthoSkymap,self).draw_meridians(*args,**kwargs)
     # We've switched to celestial, need to update meridian text
     for k,v in meridict.items():
         text = v[1][0].get_text()
         if text.startswith('-'):   text = text.replace('-','+')
         elif text.startswith('+'): text = text.replace('+','-')
         v[1][0].set_text(text)
     return meridict
Esempio n. 18
0
    def draw_decals(self, **kwargs):
        defaults = dict(color='red', lw=2)
        setdefaults(kwargs, defaults)

        filename = os.path.join(get_datadir(), 'decals-perimeter.txt')
        decals = np.genfromtxt(filename, names=['poly', 'ra', 'dec'])
        poly1 = decals[decals['poly'] == 1]
        poly2 = decals[decals['poly'] == 2]
        #self.draw_polygon_radec(poly1['ra'],poly1['dec'],**kwargs)
        #self.draw_polygon_radec(poly2['ra'],poly2['dec'],**kwargs)
        self.scatter(*self.proj(poly1['ra'], poly1['dec']))
        self.scatter(*self.proj(poly2['ra'], poly2['dec']))
Esempio n. 19
0
    def draw_magellanic_stream(self, **kwargs):
        import fitsio
        defaults = dict(xsize=800,
                        vmin=17.,
                        vmax=25.0,
                        rasterized=True,
                        cmap=plt.cm.binary)
        setdefaults(kwargs, defaults)

        dirname = get_datadir()
        filename = 'allms_coldens_gal_nside_1024.fits'
        galhpx = fitsio.read(os.path.join(dirname, filename))['coldens']
        celhpx = obztak.utils.projector.hpx_gal2cel(galhpx)
        return self.draw_hpxmap(celhpx, **kwargs)
Esempio n. 20
0
 def draw_smc(self, **kwargs):
     from skymap.constants import RA_SMC, DEC_SMC, RADIUS_SMC
     defaults = dict(npts=100, fc='0.7', ec='0.5')
     setdefaults(kwargs, defaults)
     proj = self.proj(RA_SMC, DEC_SMC)
     self.tissot(RA_SMC, DEC_SMC, RADIUS_SMC, **kwargs)
     plt.text(proj[0],
              proj[1],
              'SMC',
              weight='bold',
              fontsize=8,
              ha='center',
              va='center',
              color='k')
Esempio n. 21
0
    def draw_zenith(self, radius=1.0, **kwargs):
        """
        Plot a to-scale representation of the zenith.
        """
        defaults = dict(color='green', alpha=0.75, lw=1.5)
        setdefaults(kwargs, defaults)

        # RA and Dec of zenith
        zra, zdec = np.degrees(self.observer.radec_of(0, '90'))
        xy = self.proj(zra, zdec)

        self.plot(*xy, marker='+', ms=10, mew=1.5, **kwargs)
        if radius:
            self.tissot(zra, zdec, radius, npts=100, fc='none', **kwargs)
Esempio n. 22
0
 def draw_meridians(self, *args, **kwargs):
     defaults = dict(labels=[1, 0, 0, 1],
                     labelstyle='+/-',
                     dashes=(2, 3),
                     color='gray',
                     linewidth=0.75)
     if self.projection in [
             'ortho', 'geos', 'nsper', 'aeqd', 'vandg', 'sinu', 'hammer'
     ]:
         defaults.update(labels=[0, 0, 0, 0])
     if not args:
         #defaults.update(meridians=np.arange(0,420,60))
         defaults.update(meridians=np.arange(0, 360, 60))
     setdefaults(kwargs, defaults)
     return self.drawmeridians(*args, **kwargs)
Esempio n. 23
0
    def draw_airmass(self, airmass=1.4, npts=360, **kwargs):
        defaults = dict(color='green', lw=2)
        setdefaults(kwargs, defaults)

        altitude_radians = (0.5 * np.pi) - np.arccos(1. / airmass)
        ra_contour = np.zeros(npts)
        dec_contour = np.zeros(npts)
        for ii, azimuth in enumerate(np.linspace(0., 2. * np.pi, npts)):
            ra_radians, dec_radians = self.observer.radec_of(
                azimuth, '%.2f' % (np.degrees(altitude_radians)))
            ra_contour[ii] = np.degrees(ra_radians)
            dec_contour[ii] = np.degrees(dec_radians)
        xy = self.proj(ra_contour, dec_contour)
        self.plot(*xy, **kwargs)

        self.draw_zenith(**kwargs)
Esempio n. 24
0
 def draw_macho(self, ra, dec, **kwargs):
     from skymap.instrument.macho import MachoFocalPlane
     defaults = dict(alpha=0.2, color='gray', edgecolors='none', lw=0)
     setdefaults(kwargs, defaults)
     ra, dec = np.atleast_1d(ra, dec)
     if len(ra) != len(dec):
         msg = "Dimensions of 'ra' and 'dec' do not match"
         raise ValueError(msg)
     camera = MachoFocalPlane()
     # Should make sure axis exists....
     ax = plt.gca()
     for _ra, _dec in zip(ra, dec):
         corners = camera.project(self, _ra, _dec)
         collection = matplotlib.collections.PolyCollection(
             corners, **kwargs)
         ax.add_collection(collection)
     plt.draw()
Esempio n. 25
0
    def draw_fields(self, fields, **kwargs):
        # Scatter point size is figsize dependent...
        defaults = dict(edgecolor='none', s=15)
        # case insensitive without changing input array
        names = dict([(n.lower(), n) for n in fields.dtype.names])

        if self.projection == 'ortho': defaults.update(s=50)
        if 'filter' in names:
            colors = [self.COLORS[b] for b in fields[names['filter']]]
            defaults.update(c=colors)
        elif 'band' in names:
            colors = [self.COLORS[b] for b in fields[names['band']]]
            defaults.update(c=colors)

        setdefaults(kwargs, defaults)
        ra, dec = fields[names['ra']], fields[names['dec']]
        self.scatter(*self.proj(ra, dec), **kwargs)
Esempio n. 26
0
    def draw_milky_way(self, width=10, **kwargs):
        """ Draw the Milky Way galaxy. """
        defaults = dict(color='k', lw=1.5, ls='-')
        setdefaults(kwargs, defaults)

        glon = np.linspace(0, 360, 500)
        glat = np.zeros_like(glon)
        ra, dec = self.roll(*gal2cel(glon, glat), wrap=self.wrap_angle)
        ra -= 360 * (ra > 180)

        self.draw_polygon_radec(ra, dec, **kwargs)

        if width:
            kwargs.update(dict(ls='--', lw=1))
            for delta in [+width, -width]:
                ra, dec = self.roll(*gal2cel(glon, glat + delta))
                ra -= 360 * (ra > 180)
                self.draw_polygon_radec(ra, dec, **kwargs)
Esempio n. 27
0
    def draw_meridians(self, *args, **kwargs):
        def lon2str(deg):
            # This is a function just to remove some weird string formatting
            deg -= 360. * (deg >= 180)
            if (np.abs(deg) == 0):
                return r"$%d{}^{\circ}$" % (deg)
            elif (np.abs(deg) == 180):
                return r"$%+d{}^{\circ}$" % (np.abs(deg))
            else:
                return r"$%+d{}^{\circ}$" % (deg)

        #defaults = dict(labels=[1,1,1,1],labelstyle='+/-',
        #                fontsize=14,fmt=lon2str)
        defaults = dict(fmt=lon2str, labels=[1, 1, 1, 1], fontsize=14)
        if not args:
            defaults.update(meridians=np.arange(0, 360, 60))
        setdefaults(kwargs, defaults)

        #return self.drawmeridians(*args,**kwargs)
        return super(DESLambert, self).draw_meridians(*args, **kwargs)
Esempio n. 28
0
    def draw_constellations(self, **kwargs):
        defaults = dict(color='k', alpha=1.0)
        setdefaults(kwargs, defaults)
        ax = plt.gca()

        shapes, stars, boundaries, centers = self.read_constellations()

        ### add constellations
        for shape in shapes:
            self.plot(*self.proj(*shape.T), lw=0.5, **kwargs)

        ### add stars FIXME: hard coded...bad?
        mag = stars[:, -1]
        size = 7 * np.max([np.ones_like(mag), 5 - mag], axis=0)
        self.scatter(*self.proj(stars[:, 0], stars[:, 1]),
                     s=size,
                     marker='o',
                     edgecolor='none',
                     **kwargs)

        ### add constellation boundaries
        # Use the safe projection
        bound = [np.array(self.proj(*b)).T for b in boundaries]
        collect = LineCollection(bound,
                                 linestyle='--',
                                 linewidth=0.5,
                                 **kwargs)
        ax.add_collection(collect)

        ### add constellation centers
        for (name, (x, y)) in centers.items():
            ax.text(*self(x, y),
                    s=name,
                    ha='center',
                    va='center',
                    fontsize=8,
                    **kwargs)
Esempio n. 29
0
 def __init__(self, *args, **kwargs):
     setdefaults(kwargs, self.defaults)
     super(OrthoSkymap, self).__init__(*args, **kwargs)
Esempio n. 30
0
 def __init__(self, *args, **kwargs):
     setdefaults(kwargs, self.defaults)
     if np.abs(kwargs['lon_0']) > 180:
         raise Exception("Basemap requires: -180 < lon_0 < 180")
     super(McBrydeSkymap, self).__init__(*args, **kwargs)