示例#1
0
def skyplot(crec, title='', axes=None, fignum=30, ait_kw={}, **kwargs):
    """ make an AIT skyplot of a HEALpix array
    crec : array
        must be sorted according to the HEALpix index
    title : string
        set the figure title
    ait_kw : dict
        to set kwargs for image.AIT, perhaps pixelsize
    
    Other args passed to imshow
    """
    n = len(crec)
    nside = int(np.sqrt(n/12))
    assert n==12*nside**2, 'wrong length to be healpix array'
    band = Band(nside)
    def skyplotfun(v):
        skydir = SkyDir(Hep3Vector(v[0],v[1],v[2]))
        index = band.index(skydir)
        return crec[index]
    if axes is None:
        plt.close(fignum)
        fig = plt.figure(fignum, figsize=(12,6))
    ait=image.AIT(PySkyFunction(skyplotfun) ,axes=axes, **ait_kw)
    ait.imshow(title=title, **kwargs)
    return ait
示例#2
0
    def plot(self, title='', axes=None, fignum=30, ait_kw={}, **kwargs):
        """ make an AIT skyplot from the array 
        title : string
            set the figure title
        ait_kw : dict
            to set kwargs for image.AIT, perhaps pixelsize
        
        Other args passed to imshow, for example norm: to make a log plot,
            from matplotlib.colors import LogNorm
            plot(norm=LogNorm(vmin=1,vmax=10))
        It returns a image.AIT object, which has a colorbar member that can be adjusted.
        """
        cbtext = kwargs.pop('cbtext', '')
        ait_kw.update(cbtext=cbtext)
        band = Band(self.nside)

        def skyplotfun(v):
            skydir = SkyDir(Hep3Vector(v[0], v[1], v[2]))
            return self(skydir)

        if axes is None:
            plt.close(fignum)
            fig = plt.figure(fignum, figsize=(12, 6))
            axes = plt.gca()
        ait = image.AIT(PySkyFunction(skyplotfun), axes=axes, **ait_kw)
        ait.imshow(title=title, **kwargs)
        return ait
示例#3
0
 def plot(self, title=None, axes=None, fignum=30, ait_kw={}, log=False, **kwargs):
     """ make an AIT skyplot from the array 
     title : string
         set the figure title. If None, use the name
     ait_kw : dict
         to set kwargs for image.AIT, perhaps pixelsize
     
     Other args passed to imshow, for example norm: to make a log plot,
         from matplotlib.colors import LogNorm
         plot(norm=LogNorm(vmin=1,vmax=10))
     It returns a image.AIT object, which has a colorbar member that can be adjusted.
     """
     cbtext = kwargs.pop('cbtext', '')
     if log:
         vmin=kwargs.pop('vmin', None)
         vmax=kwargs.pop('vmax', None)
         kwargs['norm']=LogNorm(vmin=vmin,vmax=vmax)
     ait_kw.update(cbtext=cbtext)
     band = Band(self.nside)
     def skyplotfun(v):
         skydir = SkyDir(Hep3Vector(v[0],v[1],v[2]))
         return self(skydir)
     if axes is None:
         plt.close(fignum)
         fig = plt.figure(fignum, figsize=(12,6))
         axes = plt.gca()
     else:
         fig = axes.figure
     ait=image.AIT(PySkyFunction(skyplotfun) ,axes=axes, **ait_kw)
     ait.imshow( **kwargs)
     axes.set_title(self.name if title is None else title, loc='left')
     fig.set_facecolor('white')
     return ait
示例#4
0
    def make_3panel(self,
                    center,
                    size=10,
                    pixelsize=0.02,
                    galactic=False,
                    scale=1,
                    label_1FGL=True,
                    labels=None,
                    separate_figures=False,
                    fignum_base=10):

        import pylab as P
        from matplotlib.colorbar import ColorbarBase
        from matplotlib.colors import Normalize
        from uw.utilities.image import ZEA

        cmap = P.cm.jet
        cmap.set_bad('white')

        if separate_figures:
            axes = []
            for i in xrange(1, 4):
                P.figure(i + fignum_base)
                axes += [P.gca()]
        else:
            axes = [P.subplot(1, 3, i) for i in xrange(1, 4)]
        zeas = [
            ZEA(center,
                size=size,
                pixelsize=pixelsize,
                galactic=galactic,
                axes=ax) for ax in axes
        ]
        mods = [1, 2, 0]
        for i in xrange(0, 3):
            self.set_mode(mods[i])
            zeas[i].fill(PySkyFunction(self))
            zeas[i].grid()
            axes[i].imshow(zeas[i].image**(0.5 if scale else 1), cmap=cmap)
        if label_1FGL:
            names, skydirs = self.get_1FGL_sources(zeas[0])
            for na, sd in zip(names, skydirs):
                for z in zeas:
                    z.plot_source(na, sd, color='white')
        if labels is not None:
            names, skydirs = labels
            for na, sd in zip(names, skydirs):
                for z in zeas:
                    z.plot_source(na, sd, color='white')
        if separate_figures:
            # basically a "show"
            for i in xrange(1, 4):
                P.figure(i + fignum_base)
                axes[i - 1].set_autoscale_on(True)
                cb = ColorbarBase(axes[i - 1],
                                  orientation='vertical',
                                  cmap=cmap)
                #P.colorbar()
        return axes, zeas
示例#5
0
def plot_tsmap(roi,
               name=None,
               center=None,
               size=0.5,
               pixelsize=None,
               outdir=None,
               which=0,
               catsig=99,
               axes=None,
               fignum=99,
               bandfits=True,
               galmap=True,
               galactic=False,
               assoc=None,
               notitle=False,
               nolegend=False,
               markercolor='blue',
               markersize=12,
               primary_markercolor='green',
               primary_markersize=14,
               **kwargs):
    """ create a TS map for the source. These are localization style
        TS maps (where the source is not in the background model) and
        are useful for source localization.

    roi: an ROIAnalsyis object

        Optional keyword arguments:

      =========   =======================================================
      Keyword     Description
      =========   =======================================================
      name        [None]  -- provide name for title, and to save figure if outdir set
      center      [None] -- center, default the roi center
      outdir       [None] if set, save sed into <outdir>/<source_name>_tsmap.png if outdir is a directory, save into filename=<outdir> if not.  
      catsig      [99]  -- if set and less than 1.0, draw cross with this size (degrees)
      size        [0.5]  -- width=height (deg)
      pixelsize   [None] -- if not set, will be 20 x20 pixels
      galmap      [True] -- if set, draw a galactic coordinate image with the source position shown
      galactic    [False] -- plot using galactic coordinates
      which       [0]    -- chose a different source in the ROI to plot 
                            can be an index for point sources, or a name to also get extended sources   
      assoc       [None] -- if set, a list of tuple of associated sources 
      notitle     [False] -- set to turn off (allows setting the current Axes object title)
      nolegend    [False]
      markersize  [12]   -- set 0 to not plot nearby sources in the model
      markercolor [blue]
      =========   =======================================================

    returns the image.TSplot object for plotting positions, for example
    """
    kwargs = {}  #fix later
    localizer = roi_localize.localizer(roi, which, bandfits=bandfits)

    tsm = PySkyFunction(localizer)

    sdir = center if center is not None else roi.roi_dir
    if axes is None:
        plt.figure(fignum, figsize=(5, 5))
        plt.clf()

    tsp = image.TSplot(tsm,
                       sdir,
                       size,
                       pixelsize=pixelsize if pixelsize is not None else size /
                       20.,
                       axes=axes,
                       galactic=galactic,
                       galmap=galmap,
                       **kwargs)
    if 'qform' in roi.__dict__ and roi.qform is not None:
        sigma = math.sqrt(roi.qform.par[3] *
                          roi.qform.par[4])  # why do I need this?
        qual = roi.qform.par[6]
        if sigma < 1 and qual < 50:
            tsp.overplot(roi.qform, sigma)
        else:
            print 'bad fit sigma %g, >1 or qual %.1f >50' % (sigma, qual)
    tsp.show(colorbar=False)
    if catsig < 1:
        tsp.cross(sdir, catsig, lw=2, color='grey')

    # plot the primary source, any nearby from the fit
    x, y = tsp.zea.pixel(sdir)
    tsp.zea.axes.plot([x], [y],
                      '*',
                      color=primary_markercolor,
                      label=name,
                      markersize=primary_markersize)
    marker = 'ov^<>1234sphH'
    i = k = 0
    if markersize != 0:
        for ps in roi.psm.point_sources:  # skip
            x, y = tsp.zea.pixel(ps.skydir)
            if ps.name == name or x < 0 or x > tsp.zea.nx or y < 0 or y > tsp.zea.ny:
                continue
            tsp.zea.axes.plot([x], [y],
                              marker[k % 12],
                              color=markercolor,
                              label=ps.name,
                              markersize=markersize)
            k += 1

    tsp.plot(tsp.tsmaxpos, symbol='+', color='k')  # at the maximum
    if not notitle: plt.title(name, fontsize=24)

    if assoc is not None:
        # eventually move this to image.TSplot
        last_loc, i = SkyDir(0, 90), 0
        for aname, loc, prob, catid in zip(assoc['name'], assoc['dir'],
                                           assoc['prob'], assoc['cat']):
            #print 'associate with %s, prob=%.2f' % (aname.strip(),prob)
            if catid in ('ibis', ):
                print '---skip gamma cat %s' % catid
                continue
            if i > 8:
                print '---skip because too many for display'
                continue
            x, y = tsp.zea.pixel(loc)
            diff = np.degrees(loc.difference(last_loc))
            last_loc = loc
            if diff > 1e-3: k += 1  # new marker only if changed place
            tsp.zea.axes.plot([x], [y],
                              marker=marker[k % 12],
                              color='green',
                              linestyle='None',
                              label='%s[%s] %.2f' %
                              (aname.strip(), catid, prob),
                              markersize=markersize)
            i += 1

    fs = plt.rcParams['font.size']
    plt.rcParams.update({'legend.fontsize': 7, 'font.size': 7})
    # put legend on left.
    if not nolegend:
        tsp.zea.axes.legend(loc=2, numpoints=1, bbox_to_anchor=(-0.15, 1.0))
    plt.rcParams['font.size'] = fs

    if outdir is not None:
        if os.path.isdir(outdir):
            plt.savefig(os.path.join(outdir, '%s_tsmap.png' % name.strip()))
        else:
            plt.savefig(outdir)
    return tsp
示例#6
0
 def get_pyskyfun(self):
     return PySkyFunction(self)
示例#7
0
 def make_zea(self, center, size=10, pixelsize=0.02, galactic=False):
     z = ZEA(center, size=size, pixelsize=pixelsize, galactic=galactic)
     z.fill(PySkyFunction(self))
     self.z = z
示例#8
0
    def make_map(self,
                 center,
                 size=10,
                 pixelsize=0.02,
                 galactic=False,
                 axes=None,
                 scale=1,
                 thresh_low=0,
                 thresh_high=np.inf,
                 label_1FGL=True,
                 mode=1,
                 cmap=None,
                 log_transform=False,
                 labels=None):
        """
            scale : 0 == linear, 1 == sqrt
        """
        import pylab as P
        from uw.utilities.image import ZEA
        from matplotlib.colorbar import ColorbarBase
        from matplotlib.colors import Normalize

        self.set_mode(mode)

        if axes is None: axes = P.gca()
        cmap = cmap or P.cm.jet
        cmap.set_bad('white')
        z = ZEA(center,
                size=size,
                pixelsize=pixelsize,
                galactic=galactic,
                axes=axes)
        z.fill(PySkyFunction(self))
        im = z.image.copy()
        print 'Max Value: %.2f' % (im.max())
        im[im < thresh_low] = np.nan
        im[im > thresh_high] = thresh_high
        z.grid()
        im = im**(0.5 if scale else 1)
        if log_transform:
            im[im < 1] = 1
            im = np.log10(im)
        P.imshow(im, cmap=cmap)
        #P.colorbar(ax=axes,cmap=cmap,orientation='horizontal')
        #P.contour(im,np.asarray([9,16,25,50,100,1000])**(0.5 if scale else 1))
        #P.contour(im,10)
        #contours = np.asarray([9,16,25,36,49,64,81,100,225,400,625,900,1225,1600])**(0.5 if scale else 1)
        #if log_transform: contours = np.log10(contours)
        #P.contour(im,contours)
        if label_1FGL:
            names, skydirs = self.get_1FGL_sources(z)
            for na, sd in zip(names, skydirs):
                z.plot_source(na,
                              sd,
                              color='gray' if thresh_low > 0 else 'white')
        if labels is not None:
            try:
                names, skydirs = labels
            except:
                skydirs = labels
                names = ['S%d' % (i) for i in xrange(len(labels))]
            for na, sd in zip(names, skydirs):
                z.plot_source(na,
                              sd,
                              color='gray' if thresh_low > 0 else 'white')
        return z
示例#9
0
 def make_zea(self, center, size=10, pixelsize=0.02, galactic=False):
     from uw.utilities.image import ZEA
     z = ZEA(center, size=size, pixelsize=pixelsize, galactic=galactic)
     z.fill(PySkyFunction(self))
     self.z = z