def setup_axes(fig, header):
    from mpl_toolkits.axes_grid import make_axes_locatable

    ax0 = pywcsgrid2.subplot(111, wcs=header)
    divider = make_axes_locatable(ax0)

    gh1 = pywcsgrid2.GridHelperSimple(wcs=header, axis_nums=[0, 2])
    ax_v = divider.new_vertical(1.5, pad=0.1, sharex=ax0,
                                axes_class=pywcsgrid2.Axes,
                                grid_helper=gh1)
    fig.add_axes(ax_v)

    gh2 = pywcsgrid2.GridHelperSimple(wcs=header, axis_nums=[2, 1])
    ax_h = divider.new_horizontal(1.5, pad=0.1, sharey=ax0,
                                axes_class=pywcsgrid2.Axes,
                                grid_helper=gh2)

    fig.add_axes(ax_h)


    ax_h.axis["left"].toggle(label=False, ticklabels=False)
    ax_v.axis["bottom"].toggle(label=False, ticklabels=False)


    return ax0, ax_v, ax_h
Пример #2
0
def setup_axes():
    ax = pywcsgrid2.subplot(111, header=co_header)

    #add colorbar axes
    divider = make_axes_locatable(ax)
    cax = divider.new_horizontal("5%", pad=0.1, axes_class=Axes)
    fig.add_axes(cax)

    return ax, cax
Пример #3
0
def plot_map(image,coords,title='title',cm ='RdPu'):
    """
    Usage: plot_map(pixel_map,WCS_Coords)
    Input: 2D pixel Map, WCS object of the Map
    Output: Plot of The Image with a WCS Compass
    """
    ax1 = pywcsgrid2.subplot(111, wcs=coords)
    im = ax1.imshow(image,origin='low',cmap=cm)
    ax1.add_compass(loc=5,color='black')
    ax1.set_title(title)
    plt.colorbar(im)
Пример #4
0
    def show(self, filename=None):

        # taken from http://matplotlib.sourceforge.net/users/usetex.html
        import pywcsgrid2
        from matplotlib.gridspec import GridSpec

        self.imshow_args = dict(interpolation='nearest', origin='lower')

        self.counts_norm = mpl.colors.LogNorm(vmin=self.counts_min,
                                              vmax=self.counts_max)
        self.norm_res = mpl.colors.Normalize(vmin=-5, vmax=5)

        # first, divide the plot in 4x4
        self.fig = P.figure(self.fignum, self.figsize)
        P.clf()
        gs = GridSpec(4, 4)
        gs.update(wspace=1.5, hspace=1)
        self.ax_model = pywcsgrid2.subplot(gs[0:2, 0:2], header=self.h)
        self.ax_counts = pywcsgrid2.subplot(gs[0:2, 2:4], header=self.h)
        self.ax_res = pywcsgrid2.subplot(gs[2:4, 0:2], header=self.h)

        # then divide the 4th space in two.
        self.ax_pvals = P.subplot(gs[2, 2:4])
        self.ax_pvals.yaxis.set_major_locator(MaxNLocator(3))

        self.ax_resplot = P.subplot(gs[3, 2:4])
        self.ax_resplot.yaxis.set_major_locator(MaxNLocator(3))

        self.model_plot()
        self.counts_plot()
        self.resids_plot()
        self.hist_plot()

        for ax in [self.ax_model, self.ax_counts, self.ax_res]:
            ax.axis[:].set_zorder(100)
            ROIMapPlotter.overlay_region(self.roi, ax, self.h,
                                         **self.overlay_kwargs)
            if self.extra_overlay is not None: self.extra_overlay(ax)

        if self.title is not None: self.fig.suptitle(self.title)
        if filename is not None: P.savefig(filename)
Пример #5
0
def plot_skyreg(header, data, **kwargs):
    """ Plot sky region defined by header and data
    header : FITS header
    data   : Data array
    """
    kwargs.setdefault('cmap','binary')
    fig = plt.figure()
    ax = pywcsgrid2.subplot(111, header=header)
    ax.set_ticklabel_type("dms")
    im = ax.imshow(data, origin="center", **kwargs)
    ax.grid()
    ax.add_compass(loc=1,coord='fk5')
    ax.add_compass(loc=4,coord='gal')
    return ax, im
Пример #6
0
def plot_skyreg(header, data, **kwargs):
    """ Plot sky region defined by header and data
    header : FITS header
    data   : Data array
    """
    kwargs.setdefault('cmap', 'binary')
    fig = plt.figure()
    ax = pywcsgrid2.subplot(111, header=header)
    ax.set_ticklabel_type("dms")
    im = ax.imshow(data, origin="center", **kwargs)
    ax.grid()
    ax.add_compass(loc=1, coord='fk5')
    ax.add_compass(loc=4, coord='gal')
    return ax, im
Пример #7
0
    def show(self, filename=None, axes=None, cax=None):

        import pylab as P
        import pywcsgrid2
        from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable

        d = self.pf[0].data

        if axes is None:
            fig = P.figure(self.fignum, self.figsize)
            P.clf()
            axes = pywcsgrid2.subplot(111, header=self.header)
        else:
            fig = axes.get_figure()

        self.axes = ax = axes

        im = ax.imshow(d,
                       interpolation=self.interpolation,
                       origin="lower",
                       **self.imshow_kwargs())

        ax.axis[:].set_zorder(100)

        if self.show_colorbar:
            if cax is None:
                # add colorbar axes
                divider = make_axes_locatable(ax)
                self.cax = cax = divider.new_horizontal("5%",
                                                        pad="2%",
                                                        axes_class=Axes)
                fig.add_axes(cax)
                self.cbar = P.colorbar(im, cax=cax)
            else:
                # See comment for ROISmoothedSources's colobar code.
                self.cax = cax
                self.cbar = cax.colorbar(im)

        if self.title is not None:
            ax.set_title(self.title)

        ROIMapPlotter.overlay_region(self.roi, ax, self.header,
                                     **self.overlay_kwargs)

        self._additional_plotting()
        if self.extra_overlay is not None: self.extra_overlay(ax)

        tight_layout(fig)

        if filename is not None: P.savefig(filename)
Пример #8
0
def setup_sky(header, subplt=111, delta=100, title=None, **kwargs):
    '''Setup a nice sky plot that handles images'''
    import pywcsgrid2  # slow as shit
    ax = pywcsgrid2.subplot(subplt, header=header)
    fig = pylab.gcf()
    fig.add_axes(ax)
    ax.set_display_coord_system('fk5')
    ax.set_ticklabel_type('absdeg', 'absdeg')
    ax.set_aspect('equal')
    ax.locator_params(axis='x', nbins=4)
    ax.grid()
    ax.set_xlim(-delta, delta + header['naxis1'])
    ax.set_ylim(-delta, delta + header['naxis2'])
    if title is not None:
        pylab.title(title)
    return ax
Пример #9
0
def setup_sky(header, subplt=111, delta=100, title=None, **kwargs):
    '''Setup a nice sky plot that handles images'''
    import pywcsgrid2 # slow as shit
    ax = pywcsgrid2.subplot(subplt, header=header)
    fig = pylab.gcf()
    fig.add_axes(ax)
    ax.set_display_coord_system('fk5')
    ax.set_ticklabel_type('absdeg', 'absdeg')
    ax.set_aspect('equal')
    ax.locator_params(axis='x', nbins=4)
    ax.grid()
    ax.set_xlim(-delta,delta+header['naxis1'])
    ax.set_ylim(-delta,delta+header['naxis2'])
    if title is not None:
        pylab.title(title)
    return ax
Пример #10
0
def points_inside_reg(pyfits_obj, reg_name, ra_points, dec_points, plot=False):
    '''
    Takes an open fits file (pyfits_obj), a reg file (reg_name), ra and dec
    array, and returns the indices of the ra dec array inside each shape in
    the region file. Will also plot...
    inds - cumulative
    '''
    if plot == True:
        ax = pywcsgrid2.subplot(111, header=pyfits_obj[0].header)
        ax.grid()
        ax.imshow(pyfits_obj[0].data, cmap=cm.gray, origin="lower")

    # load projection, reg shapes, and get them in python
    proj = wcs.Projection(pyfits_obj[0].header)
    r = pyregion.open(reg_name).as_imagecoord(header=pyfits_obj[0].header)
    patch_list, artist_list = r.get_mpl_patches_texts()

    radec = np.column_stack((ra_points, dec_points))
    # get masks of ra,dec in each shape
    masks = []
    for p in patch_list[::-1]:
        if plot == True: ax.add_patch(p)
        verts_xy = p.get_xy()
        pixels = (verts_xy[:, 0], verts_xy[:, 1])
        ra_v, dec_v = proj.toworld(pixels)
        verts = np.column_stack((ra_v, dec_v))
        masks.append(nxutils.points_inside_poly(radec, verts))

    # subtract masks from outside to inside to not over count.
    inds = []
    for i in range(len(masks) - 1):
        isolated_mask = (masks[i] - masks[i + 1])
        if len(isolated_mask) > 0:
            within = np.nonzero(isolated_mask)[0]
            inds.append(within)
            if plot == True:
                ax["fk5"].plot(ra_points[within],
                               dec_points[within],
                               '.',
                               alpha=0.2,
                               label='%i' % i,
                               color=cols[i])
                for t in artist_list:
                    ax.add_artist(t)
                ax.add_compass(loc=1)
                ax.legend()
    return inds
Пример #11
0
def draw_cel(center, major_axes):

    header = equ_header(center, major_axes)

    l,b=center.l(),center.b()
    cel_ax=pywcsgrid2.subplot(122, header=header)
    cel_ax.set_ticklabel_type("absdeg")
    cel_ax.imshow(np.zeros((IMAGE_SIZE,IMAGE_SIZE)), origin="lower", cmap=plt.cm.gray_r)
    cel_ax.grid()


    # add floating galacitc axes on top of equatorial axes
    cel_ax.axis["l=%.2f" % l] = cel_ax["gal"].new_floating_axis(0, l)
    cel_ax.axis["b=%.2f" % b] = cel_ax["gal"].new_floating_axis(1, b)
    cel_ax.add_compass(loc=1)

    return cel_ax
Пример #12
0
def draw_gal(center, major_axes):
    ra,dec=center.ra(),center.dec()

    header=gal_header(center, major_axes)

    global gal_ax

    gal_ax=pywcsgrid2.subplot(121, header=header)
    gal_ax.set_ticklabel_type("absdeg")
    gal_ax.imshow(np.zeros((IMAGE_SIZE,IMAGE_SIZE)), origin="lower", cmap=plt.cm.gray_r)
    gal_ax.grid()

    # add floating equatorial axes on top of galactic axes
    gal_ax.axis["ra=%.2f" % ra] = gal_ax["fk5"].new_floating_axis(0, ra)
    gal_ax.axis["dec=%.2f" % dec] = gal_ax["fk5"].new_floating_axis(1, dec)
    gal_ax.add_compass(loc=1)

    return gal_ax
Пример #13
0
def setup_axes(fig, header):
    
    ax_t = pywcsgrid2.subplot(111, header=header)
    
    #gh = pywcsgrid2.GridHelper(wcs=header)
    #gh.locator_params(nbins=4)

    g = axes_grid.ImageGrid(fig, 111, 
            nrows_ncols=(ny,nx), 
            ngrids=None, direction='row', 
            axes_pad=0.0, 
            add_all=True, 
            share_all=True, 
            aspect=True, 
            label_mode='L', 
            cbar_mode=None) 

    return g, ax_t
Пример #14
0
def points_inside_reg(pyfits_obj,reg_name,ra_points,dec_points,plot=False):
    '''
    Takes an open fits file (pyfits_obj), a reg file (reg_name), ra and dec
    array, and returns the indices of the ra dec array inside each shape in
    the region file. Will also plot...
    inds - cumulative
    '''
    if plot == True:
        ax=pywcsgrid2.subplot(111, header=pyfits_obj[0].header)
        ax.grid()
        ax.imshow(pyfits_obj[0].data, cmap=cm.gray, origin="lower")
        
    # load projection, reg shapes, and get them in python
    proj = wcs.Projection(pyfits_obj[0].header)
    r = pyregion.open(reg_name).as_imagecoord(header=pyfits_obj[0].header)
    patch_list, artist_list = r.get_mpl_patches_texts()
    
    radec = np.column_stack((ra_points,dec_points))
    # get masks of ra,dec in each shape
    masks = []
    for p in patch_list[::-1]:
        if plot == True: ax.add_patch(p)
        verts_xy = p.get_xy()
        pixels = (verts_xy[:,0],verts_xy[:,1])
        ra_v,dec_v = proj.toworld(pixels)
        verts = np.column_stack((ra_v,dec_v))
        masks.append( nxutils.points_inside_poly(radec, verts))
        
    # subtract masks from outside to inside to not over count.
    inds = []
    for i in range(len(masks)-1):
        isolated_mask = (masks[i]-masks[i+1])
        if len(isolated_mask)>0:
            within = np.nonzero(isolated_mask)[0]
            inds.append(within)
            if plot == True: 
                ax["fk5"].plot(ra_points[within],dec_points[within],'.',alpha=0.2,label='%i'%i,color=cols[i])
                for t in artist_list:
                    ax.add_artist(t)
                ax.add_compass(loc=1)
                ax.legend()
    return inds
Пример #15
0
def plot_maps(coords,fn,cm='coolwarm',norm='log',fs=(20,10),**kwargs):
    """
    Usage: plot_maps(maps=[list_of_maps],titles=[list_of_titles],fn=filename(put f for not saving),norm='log',fs=figsize,coords=wcs,cm=colormap)
    Input: 2D pixel Maps, WCS object of the Maps
    Output: Plot all Subplots of The Images with WCS Compass
    """
    plt.rcParams['figure.figsize'] = fs
    nm=len(kwargs['maps'])
    a=[[]]*nm
    for i,m in enumerate(kwargs['maps']):
        vmax=m.max()
        a[i]=(pywcsgrid2.subplot(1,nm,i,wcs=coords))
        a[i].grid()
        if norm=='log':
            im=a[i].imshow(m,origin='low',cmap=cm,norm=LogNorm(),aspect=1.)
        else:
            im=a[i].imshow(m,origin='low',cmap=cm,aspect=1.)
        a[i].set_title(kwargs['titles'][i])
        a[i].add_compass(loc=5,color='black')
        ains = inset_axes(a[i], width='2%', height='37%', loc=1)
        cb=plt.colorbar(im,cax=ains)
        plt.tight_layout()
        if (fn !='f'):
            plt.savefig(fn,bbox_inches='tight')
Пример #16
0
pointing_pix_X = 4.096000000e03
pointing_pix_Y = 4.097000000e03
pointing_Dec = 1.96615555556e01
del_RA = -1.111111061e-07
del_Dec = 1.111111061e-07

core_A = [5427.45, 5624.77]
blobs_x_A = [core_A[0], 5420.59, 5385.71]
blobs_y_A = [core_A[1], 5619.15, 5626.8]
core_B = [3089.05, 2511.30]
jet_B = [3078.38, 2501.19]
blobs_x_B = [core_B[0], jet_B[0]]
blobs_y_B = [core_B[1], jet_B[1]]

fig2 = plt.figure(figsize=(15, 6))
axA = pywcsgrid2.subplot(121, header=h44, aspect=1, adjustable="box-forced")
cA38 = axA.contourf(d38, levels=levs38, colors=cols38)
cA44 = axA.contour(d44, levels=levs44, colors=cols44)
plt.xlim((core_A[0]-63.13, core_A[0]+12.63))
plt.ylim((core_A[1]-37.88, core_A[1]+37.88))
axA.set_title("Image A")
#plt.clabel(cA44, cA44.levels[::2])#, inline=True, fmt=fmt, fontsize=10)

axB = pywcsgrid2.subplot(122, header=h44, aspect=1, adjustable="box-forced")
cB38 = axB.contourf(d38, levels=levs38, colors=cols38)
cB44 = axB.contour(d44, levels=levs44, colors=cols44)
plt.xlim((core_B[0]-50.50, core_B[0]+25.25))
plt.ylim((core_B[1]-50.50, core_B[1]+25.25))
axB.add_beam_size(b44[0]/pxl_scl, b44[1]/pxl_scl, 0.02, loc=3, frameon=True)
axB.add_beam_size(b38[0]/pxl_scl, b38[1]/pxl_scl, -5.55, loc=2, frameon=True)
axB.add_size_bar(5./pxl_scl, label='5 mas', loc=1)
Пример #17
0
    # Get SDSS r image
    pix, hdr, im = None, None, None
    xid = SDSS.query_region(pos)
    if xid is not None:
        one_match = table.Table(xid[0])
        im = SDSS.get_images(matches=one_match, band='r')
        pix = im[0][0].data
        hdr = im[0][0].header

    # Plot K2 image
    # Set up the GridHelper to merge the axes
    grid_helper = pywcsgrid2.GridHelper(wcs=w2)

    # Plot the pixel stamp as usual, except with the WCS
    ax1 = pywcsgrid2.subplot(441,
                             grid_helper=grid_helper,
                             aspect=1,
                             adjustable="box-forced")
    ax1.matshow(coadd, origin="lower", cmap=cmap, norm=colors.LogNorm())
    if pix is not None:
        median = np.median(pix)
        stdev = np.std(pix)
        levels = np.linspace(median + stdev, np.max(pix), 20)
        #grey = plt.cm.Greys(0.3)
        ax1[hdr].contour(pix, cmap=plt.cm.Greys, levels=levels)

        # Plot the SDSS image rotated into the same frame as the pixel stamp
        ax2 = pywcsgrid2.subplot(445,
                                 grid_helper=grid_helper,
                                 aspect=1,
                                 adjustable="box-forced",
                                 sharex=ax1,
def plot_av_images(cloud_dict, title=None, boxes=False, savedir='./',
        filename=None, show=True, rh2_limits=None, hi_sd_limits=None):

    # Import external modules
    import matplotlib.pyplot as plt
    import matplotlib
    import numpy as np
    from mpl_toolkits.axes_grid1 import ImageGrid
    import pyfits as pf
    import matplotlib.pyplot as plt
    import pywcsgrid2
    import pywcs
    from pylab import cm # colormaps
    from matplotlib.patches import Polygon
    from matplotlib.gridspec import GridSpec

    # Set up plot aesthetics
    plt.clf()
    plt.rcdefaults()
    colormap = plt.cm.gist_ncar
    #color_cycle = [colormap(i) for i in np.linspace(0, 0.9, len(flux_list))]
    font_scale = 20
    params = {#'backend': .pdf',
              'axes.labelsize': font_scale,
              'axes.titlesize': font_scale,
              'text.fontsize': font_scale,
              'legend.fontsize': font_scale*3/4,
              'xtick.labelsize': font_scale,
              'ytick.labelsize': font_scale,
              'font.weight': 500,
              'axes.labelweight': 500,
              'text.usetex': True,
              'figure.figsize': (20, 10),
              'figure.titlesize': font_scale
              #'axes.color_cycle': color_cycle # colors of different plots
             }
    plt.rcParams.update(params)

    fig = pywcsgrid2.plt.figure()

    fig.subplots_adjust(hspace=0.1)

    gs1 = GridSpec(1, 2)
    #gs1.update(left=0.02, right=0.6, bottom=0.02, top=0.98, wspace=0.00,
    #        hspace=0.12)

    #grid_helper = pywcsgrid2.GridHelper(wcs=cloud_dict[cloud]['av_header'])

    grid_pos = 0
    cloud_list = []

    cloud_dict = {'taurus':cloud_dict['taurus'],
                  'california':cloud_dict['california']}

    for i, cloud in enumerate(cloud_dict):
        av_image = cloud_dict[cloud]['av_data']
        av_header = cloud_dict[cloud]['av_header']

        ax = pywcsgrid2.subplot(gs1[grid_pos],
                header=av_header)

        # create axes
        cmap = cm.pink # colormap
        cmap.set_bad(color='w')
        # show the image
        vmin, vmax = cloud_dict[cloud]['color_scale_limits']
        im = ax.imshow(av_image,
                interpolation='nearest',
                origin='lower',
                cmap=cmap,
                vmin=vmin,
                vmax=vmax,
                #norm=matplotlib.colors.LogNorm()
                )

        # Set limits
        limits = cloud_dict[cloud]['limit_pixels']
        ax.set_xlim([limits[0][0], limits[1][0]])
        ax.set_ylim([limits[0][1], limits[1][1]])

        # Asthetics
        ax.set_display_coord_system("fk5")
        ax.set_ticklabel_type("hms", "dms")

        if i != 0:
            ax.set_xlabel('')
        else:
            ax.set_xlabel('Right Ascension (J2000)',)
        ax.set_xlabel('Right Ascension (J2000)',)
        ax.set_ylabel('Declination (J2000)',)

        ax.annotate(cloud.capitalize(),
                xy=[0.02, 0.9],
                textcoords='axes fraction',
                xycoords='axes fraction',
                fontsize=font_scale * 1.5,
                color='w')

        # Convert sky to pix coordinates
        cores = cloud_dict[cloud]['cores']

        '''
        # Colorbar
        if cloud == 'perseus':
            cb = fig.colorbar(im, ax=ax)

            # Write label to colorbar
            cb.set_label(r'A$_V$ (Mag)',)
        else:
            cb = fig.colorbar(im, ax=ax)

            # Write label to colorbar
            cb.set_label(r'A$_V$ (Mag)',)
        '''

        for core in cores:
            if core in cloud_dict[cloud]['plot_cores']:
            	scale = 1.1
            	linewidth=3
            	linestyle='solid'
            else:
            	scale = 0.8
            	linewidth=1
            	linestyle='dashed'

            pix_coords = cores[core]['center_pixel']

            anno_color = (0.3, 0.5, 1)

            ax.scatter(pix_coords[0],pix_coords[1],
                    color=anno_color,
                    s=200,
                    marker='+',
                    linewidths=2)

            ax.annotate(core,
                    xy=[pix_coords[0], pix_coords[1]],
                    xytext=(5,10),
                    textcoords='offset points',
                    fontsize=font_scale*scale,
                    #arrowprops=dict(facecolor='w'),
                    color='w')

            if boxes:
                vertices = np.copy(cores[core]['box_vertices_rotated'])
                #[:, ::-1]
                rect = ax.add_patch(Polygon(
                        vertices[:, ::-1],
                        facecolor='none',
                        edgecolor=anno_color,
                        linewidth=linewidth,
                        linestyle=linestyle))

        cloud_list.append(cloud)
        grid_pos += 1

    #plt.tight_layout()

    if title is not None:
        fig.suptitle(title, fontsize=font_scale)
    if filename is not None:
        plt.savefig(savedir + filename, bbox_inches='tight')
    if show:
        fig.show()
Пример #19
0
def remove_field_overlaps(photfiles,drzs,footprints,base_fits=m31,plot=False,fake=False,matched_only=False,qc=True):
    '''
    This only works for field 3,4,5,9,10,11,15,16,17. It can be adapted for 
    all fields though, 3 is now the top left field, 9 and 15 are the left most
    fields on the next rows.

    footprints is a region file from exposure_coverage.csv
    pre-processing:
    1. grep UVIS exposure_coverage.csv > poop
    2. grep F336W poop > poop1
    3. grep 550 poop1 > poop2
    4. Then some hard coding in the file:
      I decided to update the exposure footprints file since full bricks are 
      on their way...
      the problem is that chip 1 vs chip 2 flip their orientation on fields 1,2,3
      from those of 4,5,6 such that chip 1 of field 3 overlaps with chip 1 of 
      field 4 while chip 2 of field 4 and 5 overlap with chip 1 of 5 and 6.
      I swapped the chip values of 1,2,3,7,8,9,13,14,15 so it's consistent with
      4,5,6,10,11,12,16,17,18. 
    5. Then I cut out all fields BUT 3,4,5,9,10,11,15,16,17

    Hacked adaptability for all.fake files. If .fake files are coming in, just
    say they are photfiles and set the fake kwarg to True.

    For all.fake: need to run twice (ug). Once with qc=True and once with qc=False.

    adding more fields? Check the if statements and the [i-*]s.
    '''
    clrs = discrete_colors(len(photfiles))
    if plot == True:
        ax=pywcsgrid2.subplot(111, header=f_header)
        ax.grid()
        ax.imshow(f_data, cmap=cm.gray, origin="lower")
    r = pyregion.open(footprints).as_imagecoord(header=f_header)
    # a is the left chip of the field (see # 4 in comment)
    r1a = pyregion.ShapeList([rr for rr in r if re.search('550-1',rr.attr[1].get("tag"))])
    # b is the right chip of the field (see # 4 in comment)
    r1b = pyregion.ShapeList([rr for rr in r if re.search('550-2',rr.attr[1].get("tag"))])

    patch_list1a, artist_list1a = r1a.get_mpl_patches_texts()
    patch_list1b, artist_list1b = r1b.get_mpl_patches_texts(fixed_color)
    if plot == True:
        for p in patch_list1a + patch_list1b:
            ax.add_patch(p)
    for i in range(len(photfiles)):
        inds1,inds2 = '',''
        print 'reading',photfiles[i]
        if fake==True: 
            if qc == False:
                x,y,mag1,mag2,xxx,yyy,qc_ind1,qc_ind2 = read_all_fake(photfiles[i])
            else:
                x,y,mag1,mag2,xxx,yyy,qc_ind1,qc_ind2 = read_all_fake(photfiles[i],mag1_cut=999.,mag2_cut=999.)
        else: x,y,mag1,mag2,qc_ind1,qc_ind2,matches = read_phot(photfiles[i])
        # HACK!!! This is to only use the phot stars found in both filters (with qc)
        if matched_only == True:
            qc_ind1 = matches
            qc_ind2 = matches
        d = pyfits.open(drzs[i])
        # get out of image coords
        ra,dec = XY2radec(d,x,y)
        # currect for chip gap and edges:
        within = in_chips(ra,dec,patch_list1a[i],patch_list1b[i])
        # field 3 is the chosen one to sit on top:
        if re.search('F03',photfiles[i]):
            inds1 = match_2inds(within,qc_ind1)
            inds2 = match_2inds(within,qc_ind2)
            if qc == False:
                inds1 = within
                inds2 = within
            Mag1 = mag1[inds1]
            Mag2 = mag2[inds2]
            Ra1 = ra[inds1]
            Dec1 = dec[inds1]
            Ra2 = ra[inds2]
            Dec2 = dec[inds2]
        # top row will only overlap with one to the right
        elif re.search('F0',photfiles[i]) or re.search('F05',photfiles[i]) or re.search('F06',photfiles[i]):
            not_overlapped = poly_over_under(ra,dec,patch_list1b[i-1],patch_list1a[i])
            inds1 = match_3inds(within,qc_ind1,not_overlapped)
            inds2 = match_3inds(within,qc_ind2,not_overlapped)
            if qc == False:
                inds1 = match_2inds(within,not_overlapped)
                inds2 = match_2inds(within,not_overlapped)
        # next two rows will overlap above and to the right
        else:
            # correct for overlap by field in above row
            #    by left chip
            top_a_a = poly_over_under(ra,dec,patch_list1a[i-4],patch_list1a[i])
            top_a_b = poly_over_under(ra,dec,patch_list1a[i-4],patch_list1b[i])
            top_b_b = poly_over_under(ra,dec,patch_list1b[i-4],patch_list1b[i])
            tops = list(set(top_a_a) & set(top_a_b) & set(top_b_b))
            # correct for overlap by field to the left, F09 is the left-most.
            if re.search('F09',photfiles[i]) or re.search('F15',photfiles[i]):
                inds1 = list(set(qc_ind1) & set(within) & set(tops))
                inds2 = list(set(qc_ind2) & set(within) & set(tops))
            else:
                top_left_b_a = poly_over_under(ra,dec,patch_list1b[i-5],patch_list1a[i])
                the_left = poly_over_under(ra,dec,patch_list1b[i-1],patch_list1a[i])
                inds1 = list(set(qc_ind1) & set(within) & set(tops) & set(top_left_b_a) & set(the_left))
                inds2 = list(set(qc_ind2) & set(within) & set(tops) & set(top_left_b_a) & set(the_left))
                if qc == False:
                    inds1 = list(set(within) & set(tops) & set(top_left_b_a) & set(the_left))
                    inds2 = list(set(within) & set(tops) & set(top_left_b_a) & set(the_left))
                    
        if plot==True: ax['fk5'].plot(ra[inds1],dec[inds1],'o',ms=4,mec=clrs[i],color=clrs[i])
        Mag1 = np.append(Mag1,mag1[inds1])
        Mag2 = np.append(Mag2,mag2[inds2])
        Ra1 = np.append(Ra1,ra[inds1])
        Dec1 = np.append(Dec1,dec[inds1])
        Ra2 = np.append(Ra2,ra[inds2])
        Dec2 = np.append(Dec2,dec[inds2])
        
    return Ra1,Dec1,Ra2,Dec2,Mag1,Mag2
Пример #20
0
import pyfits
import matplotlib.pyplot as plt


f = pyfits.open("data/lmc.fits")
d, h = f[0].data, f[0].header

plt.figure(1, [6,3.5])

plt.subplot(121)

plt.imshow(d, origin="low", vmin=0, vmax=2000,
           cmap=plt.cm.gray_r)

plt.title("Original MPL")

import pywcsgrid2

pywcsgrid2.subplot(122, header=h)

plt.imshow(d, origin="low", vmin=0, vmax=2000,
           cmap=plt.cm.gray_r)

plt.title("pywcsgrid2")

plt.subplots_adjust(left=0.1, right=0.95, top=0.95, wspace=0.5)

plt.show()

Пример #21
0
import matplotlib.pyplot as plt
import matplotlib.cm as cm

import pyregion
try:
    from astropy.io import fits as pyfits
except ImportError:
    import pyfits

# read in the image
cluster_name = "a383_mosaic_065mas_acs_wfc3ir_total_drz_20110825.fits"
f_cluster = pyfits.open(cluster_name)

try:
    import pywcsgrid2
    ax = pywcsgrid2.subplot(111, header=f_cluster[0].header)
except ImportError:
    ax = plt.subplot(111)

ax.imshow(f_cluster[0].data,
          cmap=cm.gray,
          vmin=0.,
          vmax=0.00038,
          origin="lower")

reg_name = "abell383_wfc3ir_outline.reg"
r = pyregion.open(reg_name).as_imagecoord(header=f_cluster[0].header)

from pyregion.mpl_helper import properties_func_default

def plot_av_images(cloud_dict,
                   title=None,
                   boxes=False,
                   savedir='./',
                   filename=None,
                   show=True,
                   rh2_limits=None,
                   hi_sd_limits=None):

    # Import external modules
    import matplotlib.pyplot as plt
    import matplotlib
    import numpy as np
    from mpl_toolkits.axes_grid1 import ImageGrid
    import pyfits as pf
    import matplotlib.pyplot as plt
    import pywcsgrid2
    import pywcs
    from pylab import cm  # colormaps
    from matplotlib.patches import Polygon
    from matplotlib.gridspec import GridSpec

    # Set up plot aesthetics
    plt.clf()
    plt.rcdefaults()
    colormap = plt.cm.gist_ncar
    #color_cycle = [colormap(i) for i in np.linspace(0, 0.9, len(flux_list))]
    font_scale = 20
    params = {  #'backend': .pdf',
        'axes.labelsize': font_scale,
        'axes.titlesize': font_scale,
        'text.fontsize': font_scale,
        'legend.fontsize': font_scale * 3 / 4,
        'xtick.labelsize': font_scale,
        'ytick.labelsize': font_scale,
        'font.weight': 500,
        'axes.labelweight': 500,
        'text.usetex': True,
        'figure.figsize': (19, 20),
        'figure.titlesize': font_scale
        #'axes.color_cycle': color_cycle # colors of different plots
    }
    plt.rcParams.update(params)

    fig = pywcsgrid2.plt.figure()

    fig.subplots_adjust(hspace=0.1)

    gs1 = GridSpec(3, 1)
    gs1.update(left=0.02,
               right=0.6,
               bottom=0.02,
               top=0.98,
               wspace=0.00,
               hspace=0.12)

    #grid_helper = pywcsgrid2.GridHelper(wcs=cloud_dict[cloud]['av_header'])

    grid_pos = 0
    cloud_list = []

    for i, cloud in enumerate(cloud_dict):
        av_image = cloud_dict[cloud]['av_data']
        av_header = cloud_dict[cloud]['av_header']

        ax = pywcsgrid2.subplot(gs1[grid_pos], header=av_header)

        # create axes
        cmap = cm.pink  # colormap
        cmap.set_bad(color='w')
        # show the image
        vmin, vmax = cloud_dict[cloud]['color_scale_limits']
        im = ax.imshow(
            av_image,
            interpolation='nearest',
            origin='lower',
            cmap=cmap,
            vmin=vmin,
            vmax=vmax,
            #norm=matplotlib.colors.LogNorm()
        )

        # Set limits
        limits = cloud_dict[cloud]['limit_pixels']
        ax.set_xlim([limits[0][0], limits[1][0]])
        ax.set_ylim([limits[0][1], limits[1][1]])

        # Asthetics
        ax.set_display_coord_system("fk5")
        ax.set_ticklabel_type("hms", "dms")

        if i != 0:
            ax.set_xlabel('')
        else:
            ax.set_xlabel('Right Ascension (J2000)', )
        ax.set_xlabel('Right Ascension (J2000)', )
        ax.set_ylabel('Declination (J2000)', )

        ax.annotate(cloud.capitalize(),
                    xy=[0.02, 0.9],
                    textcoords='axes fraction',
                    xycoords='axes fraction',
                    fontsize=font_scale * 1.5,
                    color='w')

        # Convert sky to pix coordinates
        cores = cloud_dict[cloud]['cores']

        # Colorbar
        if cloud == 'perseus':
            cb = fig.colorbar(im, ax=ax)

            # Write label to colorbar
            cb.set_label(r'A$_V$ (Mag)', )
        else:
            cb = fig.colorbar(im, ax=ax)

            # Write label to colorbar
            cb.set_label(r'A$_V$ (Mag)', )

        for core in cores:
            if core in cloud_dict[cloud]['plot_cores']:
                scale = 1.1
                linewidth = 3
                linestyle = 'solid'
            else:
                scale = 0.8
                linewidth = 1
                linestyle = 'dashed'

            pix_coords = cores[core]['center_pixel']

            anno_color = (0.3, 0.5, 1)

            ax.scatter(pix_coords[0],
                       pix_coords[1],
                       color=anno_color,
                       s=200,
                       marker='+',
                       linewidths=2)

            ax.annotate(
                core,
                xy=[pix_coords[0], pix_coords[1]],
                xytext=(5, 10),
                textcoords='offset points',
                fontsize=font_scale * scale,
                #arrowprops=dict(facecolor='w'),
                color='w')

            if boxes:
                vertices = np.copy(cores[core]['box_vertices_rotated'])
                #[:, ::-1]
                rect = ax.add_patch(
                    Polygon(vertices[:, ::-1],
                            facecolor='none',
                            edgecolor=anno_color,
                            linewidth=linewidth,
                            linestyle=linestyle))

        cloud_list.append(cloud)
        grid_pos += 1

    # Plot RH2 and HISD vs. HSD
    plot_rh2_hi_vs_h(cloud_dict,
                     fig,
                     font_scale=font_scale,
                     rh2_limits=rh2_limits,
                     cloud_list=cloud_list,
                     hi_sd_limits=hi_sd_limits)

    #plt.tight_layout()

    if title is not None:
        fig.suptitle(title, fontsize=font_scale)
    if filename is not None:
        plt.savefig(savedir + filename, bbox_inches='tight')
    if show:
        fig.show()
Пример #23
0
import matplotlib.pyplot as plt
import matplotlib.cm as cm

import pyregion
try:
    from astropy.io import fits as pyfits
except ImportError:
    import pyfits

# read in the image
xray_name= "pspc_skyview.fits"
f_xray = pyfits.open(xray_name)

try:
    import pywcsgrid2
    ax=pywcsgrid2.subplot(111, header=f_xray[0].header)
except ImportError:
    ax=plt.subplot(111)

ax.imshow(f_xray[0].data, cmap=cm.gray, vmin=0., vmax=0.00038, origin="lower")

reg_name = "test.reg"
r = pyregion.open(reg_name).as_imagecoord(header=f_xray[0].header)

from pyregion.mpl_helper import properties_func_default

# Use custom function for patch attribute
def fixed_color(shape, saved_attrs):

    attr_list, attr_dict = saved_attrs
    attr_dict["color"] = "red"
Пример #24
0
image = image[600:1400, 200:1400] * 60.

# Scale input image
bottom, top = 0., 150.
data = (((top - bottom) * (image - image.min())) / (image.max() - image.min())) + bottom

# Determine image size
tam = data.shape

# Define plot size
xsize = 15
ysize = xsize * tam[0] / tam[1]

# Setup plot and custom axes
fig = plt.figure(figsize=(ysize, xsize))
ax = pywcsgrid2.subplot(111, header=hdr)

# Select image colormap
cmap = cm.get_cmap('gray_r')

# Setup axes ticks and labels
ax.locator_params(axis='x', nbins=6)
ax.locator_params(axis='y', nbins=14)
ax.set_xlabel('RIGHT ASCENSION')
ax.set_ylabel('DECLINATION')

# Display background image
im = ax.imshow(data, cmap=cmap, vmax=7.)

# Calculate contours
contour_x = np.arange(tam[1])
Пример #25
0
 def setup_axes(fig):
   ax=pywcsgrid2.subplot(111,header=f[0].header)
   divider=make_axes_locatable(ax)  
   # cax=divider.new_horizontal('5%',pad=0.05,axes_class=Axes)
   # fig.add_axes(cax)
   return ax #,cax
Пример #26
0
def plot_four(epic, filename, coadd, maskmap, maskheader, init, coords, sources, ap=None, campaign=4):

    logging.info("Plot four %s", epic)
    logging.debug(base_path)

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

    hdu2 = fits.open(filename)
    dataheader = hdu2[1].header
    hdu2.close()
    keysel = np.empty(13, "S6")
    keysel[:] = "binary"
    w2 = WCS(dataheader, colsel=[5], keysel=keysel)

    # Plot DSS/SDSS image if available
    dssname = "{0}/ss_finders/{1}d/fc_{1}d_dssdss2red.fits".format(base_path, epic)
    sdssname = "{0}/ss_finders/{1}d/fc_{1}d_sdss (dr7)z.fits".format(base_path, epic)
    if os.path.exists(dssname):
        # Open image file
        hdu = fits.open(dssname)
        pix, hdr = hdu[0].data, hdu[0].header
        hdu.close()

    elif os.path.exists(sdssname):
        # Open image file
        hdu = fits.open(sdssname)
        pix, hdr = hdu[0].data, hdu[0].header
        hdu.close()

    else:
        pix = None

    # Set up the GridHelper to merge the axes
    grid_helper = pywcsgrid2.GridHelper(wcs=w2)

    # Plot the pixel stamp as usual, except with the WCS
    ax1 = pywcsgrid2.subplot(221, grid_helper=grid_helper, aspect=1, adjustable="box-forced")
    ax1.matshow(coadd, origin="lower", cmap="Greys", norm=colors.LogNorm())
    if ap is not None:
        ap_circle = plt.Circle(coords, ap, color="k", fill=False, linewidth=1.5)
        ax1.add_artist(ap_circle)
    # ax1.axis["bottom","left","top","right"].toggle(ticklabels=False)

    if pix is not None:
        median = np.median(pix)
        stdev = np.std(pix)
        levels = np.linspace(median + stdev, np.max(pix), 5)
        ax1[hdr].contour(pix, colors="r", levels=levels)
        #        ax1.set_ticklabel_type("delta","delta",
        #                               dict(offset=np.float64(dataheader["1CRVL5"]),
        #                                    latitude=np.float64(dataheader["2CRVL5"])))

        # Plot the DSS image rotated into the same frame as the pixel stamp
        ax2 = pywcsgrid2.subplot(
            222, grid_helper=grid_helper, aspect=1, adjustable="box-forced", sharex=ax1, sharey=ax1
        )
        ax2[hdr].imshow_affine(pix, origin="lower", cmap="Greys", norm=colors.LogNorm())
        median2 = np.median(coadd)
        stdev2 = np.std(coadd)
        levels2 = np.linspace(median, np.max(coadd), 5)
        # ax2[w2].contour(coadd,3, colors="r")
    #        ax2.set_ticklabel_type("delta","delta")
    #        ax2.axis["bottom","left","top","right"].toggle(ticklabels=False)

    # Then the pixel motion across the CCD
    ax3 = plt.subplot(223)
    divider3 = make_axes_locatable(ax3)
    cax3 = divider3.append_axes("bottom", size="5%", pad=0.35)

    stamp(coadd, maskmap, ax=ax3, cmap="gray")

    lcs = at.read("{}/lcs/ktwo{}-c0{}.csv".format(base_path, epic, campaign))

    ax3.set_xlim(np.floor(min(lcs["x"])), np.ceil(max(lcs["x"])))
    ax3.set_ylim(np.floor(min(lcs["y"])), np.ceil(max(lcs["y"])))

    xyt = ax3.scatter(
        lcs["x"],
        lcs["y"],
        c=lcs["t"],
        edgecolor="none",
        alpha=0.5,
        vmin=np.percentile(lcs["t"], 5),
        vmax=np.percentile(lcs["t"], 95),
        cmap="gnuplot",
    )
    cbar_ticks = np.asarray(np.percentile(lcs["t"], np.arange(10, 100, 40)), int)
    cbar1 = fig.colorbar(xyt, cax=cax3, ticks=cbar_ticks, orientation="horizontal")
    cbar1.set_label("Time (d)", fontsize="small")

    # Then sky coordinates with the object position overlaid
    ax4 = plt.subplot(224)
    plot_chips(ax4, campaign)
    setup_k2_axes(ax4)
    plt.plot(maskheader["RA_OBJ"], maskheader["DEC_OBJ"], "*", color="Purple", ms=25, alpha=0.8)
    plt.setp(ax4.get_xticklabels()[::2], visible=False)
    plt.setp(ax4.get_yticklabels()[::2], visible=False)

    plt.suptitle("EPIC {}".format(epic))  # , fontsize="large")
    # plt.tight_layout()
    plt.subplots_adjust(top=0.95, hspace=0.5, wspace=0.8)
Пример #27
0
    def plot(self,subplot=111,catalog=None,cmap='jet',**kwargs):

        from matplotlib.colors import NoNorm, LogNorm, Normalize

        kwargs_contour = { 'levels' : None, 'colors' : ['k'],
                           'linewidths' : None,
                           'origin' : 'lower' }
        
        kwargs_imshow = { 'interpolation' : 'nearest',
                          'origin' : 'lower','norm' : None,
                          'vmin' : None, 'vmax' : None }

        zscale = kwargs.get('zscale',None)
        gamma = kwargs.get('gamma',0.5)
        beam_size = kwargs.get('beam_size',None)
        
        if zscale == 'pow':
            kwargs_imshow['norm'] = PowerNorm(gamma=gamma)
        elif zscale == 'sqrt': 
            kwargs_imshow['norm'] = PowerNorm(gamma=0.5)
        elif zscale == 'log': kwargs_imshow['norm'] = LogNorm()
        else: kwargs_imshow['norm'] = Normalize()

#        ax = kwargs.get('ax',None)        
#        if ax is None:
        ax = pywcsgrid2.subplot(subplot, header=self._wcs.to_header())
#        ax = pywcsgrid2.axes(header=self._wcs.to_header())

        load_ds9_cmap()
        colormap = mpl.cm.get_cmap(cmap)
        colormap.set_under('white')

        counts = copy.copy(self._counts)
        
        if np.any(self._roi_msk):        
            kwargs_imshow['vmin'] = 0.8*np.min(self._counts[~self._roi_msk.T])
            counts[self._roi_msk.T] = -np.inf
        
#        vmax = np.max(self._counts[~self._roi_msk])
#        c = self._counts[~self._roi_msk]        
#        if logz: vmin = np.min(c[c>0])

        update_dict(kwargs_imshow,kwargs)
        update_dict(kwargs_contour,kwargs)
        
        im = ax.imshow(counts.T,**kwargs_imshow)
        im.set_cmap(colormap)

        if kwargs_contour['levels']:        
            cs = ax.contour(counts.T,**kwargs_contour)
        #        plt.clabel(cs, fontsize=5, inline=0)
        
#        im.set_clim(vmin=np.min(self._counts[~self._roi_msk]),
#                    vmax=np.max(self._counts[~self._roi_msk]))
        
        ax.set_ticklabel_type("d", "d")



        if self._axes[0]._coordsys == 'gal':
            ax.set_xlabel('GLON')
            ax.set_ylabel('GLAT')
        else:        
            ax.set_xlabel('RA')
            ax.set_ylabel('DEC')

        xlabel = kwargs.get('xlabel',None)
        ylabel = kwargs.get('ylabel',None)
        if xlabel is not None: ax.set_xlabel(xlabel)
        if ylabel is not None: ax.set_ylabel(ylabel)

#        plt.colorbar(im,orientation='horizontal',shrink=0.7,pad=0.15,
#                     fraction=0.05)
        ax.grid()

        if catalog:
            cat = Catalog.get(catalog)

            kwargs_cat = {'src_color' : 'k' }
            if cmap == 'ds9_b': kwargs_cat['src_color'] = 'w'

            cat.plot(self,ax=ax,**kwargs_cat)
        
#        ax.add_compass(loc=1)
#        ax.set_display_coord_system("gal")       
 #       ax.locator_params(axis="x", nbins=12)

        ax.add_size_bar(1./self._axes[0]._delta, # 30' in in pixel
                        r"$1^{\circ}$",loc=3,color='w')
            
        if beam_size is not None:
            ax.add_beam_size(2.0*beam_size[0]/self._axes[0]._delta,
                             2.0*beam_size[1]/self._axes[1]._delta,
                             beam_size[2],beam_size[3],
                             patch_props={'fc' : "none", 'ec' : "w"})
            
        self._ax = ax
        
        return im
Пример #28
0
import matplotlib.pyplot as plt
import matplotlib.cm as cm

import pyregion
try:
    from astropy.io import fits as pyfits
except ImportError:
    import pyfits

# read in the image
cluster_name="a383_mosaic_065mas_acs_wfc3ir_total_drz_20110825.fits"
f_cluster = pyfits.open(cluster_name)

try:
    import pywcsgrid2
    ax=pywcsgrid2.subplot(111, header=f_cluster[0].header)
except ImportError:
    ax=plt.subplot(111)

ax.imshow(f_cluster[0].data, cmap=cm.gray, vmin=0., vmax=0.00038, origin="lower")

reg_name = "abell383_wfc3ir_outline.reg"
r = pyregion.open(reg_name).as_imagecoord(header=f_cluster[0].header)

from pyregion.mpl_helper import properties_func_default

# Use custom function for patch attribute
def fixed_color(shape, saved_attrs):
    
    attr_list, attr_dict = saved_attrs
    attr_dict["color"] = "red"
Пример #29
0
from astropy.io import fits as pyfits

import matplotlib.pyplot as plt

f = pyfits.open("data/lmc.fits")
d, h = f[0].data, f[0].header

plt.figure(1, [6, 3.5])

plt.subplot(121)

plt.imshow(d, origin="low", vmin=0, vmax=2000, cmap=plt.cm.gray_r)

plt.title("Original MPL")

import pywcsgrid2

pywcsgrid2.subplot(122, header=h)

plt.imshow(d, origin="low", vmin=0, vmax=2000, cmap=plt.cm.gray_r)

plt.title("pywcsgrid2")

plt.subplots_adjust(left=0.1, right=0.95, top=0.95, wspace=0.5)

plt.show()
Пример #30
0
import matplotlib.pyplot as plt
import matplotlib.cm as cm

import pyregion
try:
    from astropy.io import fits as pyfits
except ImportError:
    import pyfits

# read in the image
xray_name = "pspc_skyview.fits"
f_xray = pyfits.open(xray_name)

try:
    import pywcsgrid2
    ax = pywcsgrid2.subplot(111, header=f_xray[0].header)
except ImportError:
    ax = plt.subplot(111)

ax.imshow(f_xray[0].data, cmap=cm.gray, vmin=0., vmax=0.00038, origin="lower")

reg_name = "test.reg"
r = pyregion.open(reg_name).as_imagecoord(header=f_xray[0].header)

from pyregion.mpl_helper import properties_func_default


# Use custom function for patch attribute
def fixed_color(shape, saved_attrs):

    attr_list, attr_dict = saved_attrs
Пример #31
0
        bs = bs38
        bpa = bpa38
        filename = 'jetmedian38'
    elif fitsfile == fitsfile44:
        bs = bs44
        bpa = bpa44
        filename = 'jetmedian44'
    fhdr, fdata, dmean, dstd, dmax, ddrng = read_stats(fitsfile)
    cl1 = dstd*8.
    n = np.arange(0, 10)
    levs = cl1*2.**n
    cmap = brewer2mpl.get_map('OrRd', 'sequential', 9, reverse=True)
    cols = np.array(cmap.mpl_colors)

    fig = plt.figure()
    axA = pywcsgrid2.subplot(121, aspect=1, header=fhdr)
    axB = pywcsgrid2.subplot(122, aspect=1, header=fhdr)

    core_A = [5427.45, 5624.77]
    core_B = [3089.05, 2511.30]

    if dataset == 8.4:
      imA = fdata
      imB = fdata
    elif dataset == 5:
      imA=fdata[core_A[1]-40:core_A[1]+40, core_A[0]-60:core_A[0]+40]
      imB=fdata[core_B[1]-30:core_B[1]+25, core_B[0]-30:core_B[0]+25]

    axA.contour(imA, levels=levs, orogin='lower', colors='k', alpha=0.5)
    c = ['#1f78b4', '#33a02c', '#fb9a99', '#e31a1c', '#fdbf6f', '#ff7f00', '#cab2d6', '#a6cee3', '#b2df8a', 'k']
    for l in range(1,2):
Пример #32
0
h = demo_header()
nx, ny = h["naxis1"], h["naxis2"],

labtypes = [
    ("hms", {}),
    ("h", {}),
    ("dms", {}),
    ("absdeg", {}),
    ("delta", dict(offset=h["crval1"], latitude=h["crval2"])),
    ("arcmin", dict(offset=h["crval1"], latitude=h["crval2"])),
    ("manual", dict(locs=[70, 65, 60], labels=["A", "B", "C"])),
]
n = len(labtypes)

plt.figure(figsize=(5, 1 * n))

for i, (labtyp1, labtyp1_kwargs) in enumerate(labtypes):
    ax = pywcsgrid2.subplot(n, 1, i + 1, header=h, frameon=False)
    ax.set_aspect(1.)
    ax.set_xlim(-0.5, nx - 0.5)
    ax.set_ylim(-0.5, 4.5)
    ax.axis["left", "right", "top"].set_visible(False)

    ax.annotate(labtyp1, (0., 0), (0, 2),
                xycoords="axes fraction",
                textcoords="offset points")
    ax.set_ticklabel1_type(labtyp1, **labtyp1_kwargs)
    ax.set_default_label(labtyp1, None)

plt.show()
Пример #33
0
gh2 = ax_h.get_grid_helper()
gh2.set_ticklabel1_type("absval", scale=0.001, nbins=5)

ax_h.axis["bottom"].label.set_text(r"$v_{\mathrm{LSR}}$ [km s$^{-1}$]")
ax_v.axis["left"].label.set_text(r"$v_{\mathrm{LSR}}$ [km s$^{-1}$]")

ax_h.set(xlim=(kcut1,kcut2+1))
ax_v.set(ylim=(kcut1,kcut2+1))

fname_o = "P-V_area.eps"
savefig(fname_o, bbox_inches='tight')

#
if 0:
    gh1 = pywcsgrid2.GridHelperSimple(wcs=co_header, axis_nums=[2, 0])
    gh2 = pywcsgrid2.GridHelperSimple(wcs=co_header, axis_nums=[2, 1])
    fig_n = figure(2)
    ax1 = pywcsgrid2.subplot(211, grid_helper=gh1)
    im1 = ax1.imshow(vv1.transpose(), origin='lower', aspect='auto')
    ax2 = pywcsgrid2.subplot(212, grid_helper=gh2)
    im2 = ax2.imshow(vv2, origin='lower', aspect='auto')
    fname_o_new = 'P-V_%f_%f.eps'%(pick_x,pick_y)
    ax1.set(xlim=(kcut1,kcut2+1))
    ax2.set(xlim=(kcut1,kcut2+1))
    cont1 = ax1.contour(vv1.transpose(), levels=arange(2.,6.,2.), colors='w',
            linewidths=0.5)
    cont2 = ax2.contour(vv2, levels=arange(2.,6.,2.), colors='w', 
            linewidths=0.5)
    savefig(fname_o_new, bbox_inches='tight')
Пример #34
0
h = demo_header()
nx, ny = h["naxis1"], h["naxis2"],

labtypes = [("hms", {}),
            ("h", {}),
            ("dms", {}),
            ("absdeg", {}),
            ("delta", dict(offset=h["crval1"], latitude=h["crval2"])),
            ("arcmin", dict(offset=h["crval1"], latitude=h["crval2"])),
            ("manual", dict(locs=[70, 65, 60], labels=["A","B","C"])),
            ]
n = len(labtypes)

plt.figure(figsize=(5, 1*n))

for i, (labtyp1, labtyp1_kwargs) in enumerate(labtypes):
    ax = pywcsgrid2.subplot(n, 1, i+1, header=h, frameon=False)
    ax.set_aspect(1.)
    ax.set_xlim(-0.5, nx-0.5)
    ax.set_ylim(-0.5, 4.5)
    ax.axis["left","right","top"].set_visible(False)

    ax.annotate(labtyp1, (0.,0), (0, 2),
                xycoords="axes fraction",
                textcoords="offset points")
    ax.set_ticklabel1_type(labtyp1, **labtyp1_kwargs)
    ax.set_default_label(labtyp1, None)
    

plt.show()
Пример #35
0
def remove_field_overlaps(photfiles,
                          drzs,
                          footprints,
                          base_fits=m31,
                          plot=False,
                          fake=False,
                          matched_only=False,
                          qc=True):
    '''
    This only works for field 3,4,5,9,10,11,15,16,17. It can be adapted for 
    all fields though, 3 is now the top left field, 9 and 15 are the left most
    fields on the next rows.

    footprints is a region file from exposure_coverage.csv
    pre-processing:
    1. grep UVIS exposure_coverage.csv > poop
    2. grep F336W poop > poop1
    3. grep 550 poop1 > poop2
    4. Then some hard coding in the file:
      I decided to update the exposure footprints file since full bricks are 
      on their way...
      the problem is that chip 1 vs chip 2 flip their orientation on fields 1,2,3
      from those of 4,5,6 such that chip 1 of field 3 overlaps with chip 1 of 
      field 4 while chip 2 of field 4 and 5 overlap with chip 1 of 5 and 6.
      I swapped the chip values of 1,2,3,7,8,9,13,14,15 so it's consistent with
      4,5,6,10,11,12,16,17,18. 
    5. Then I cut out all fields BUT 3,4,5,9,10,11,15,16,17

    Hacked adaptability for all.fake files. If .fake files are coming in, just
    say they are photfiles and set the fake kwarg to True.

    For all.fake: need to run twice (ug). Once with qc=True and once with qc=False.

    adding more fields? Check the if statements and the [i-*]s.
    '''
    clrs = discrete_colors(len(photfiles))
    if plot == True:
        ax = pywcsgrid2.subplot(111, header=f_header)
        ax.grid()
        ax.imshow(f_data, cmap=cm.gray, origin="lower")
    r = pyregion.open(footprints).as_imagecoord(header=f_header)
    # a is the left chip of the field (see # 4 in comment)
    r1a = pyregion.ShapeList(
        [rr for rr in r if re.search('550-1', rr.attr[1].get("tag"))])
    # b is the right chip of the field (see # 4 in comment)
    r1b = pyregion.ShapeList(
        [rr for rr in r if re.search('550-2', rr.attr[1].get("tag"))])

    patch_list1a, artist_list1a = r1a.get_mpl_patches_texts()
    patch_list1b, artist_list1b = r1b.get_mpl_patches_texts(fixed_color)
    if plot == True:
        for p in patch_list1a + patch_list1b:
            ax.add_patch(p)
    for i in range(len(photfiles)):
        inds1, inds2 = '', ''
        print 'reading', photfiles[i]
        if fake == True:
            if qc == False:
                x, y, mag1, mag2, xxx, yyy, qc_ind1, qc_ind2 = read_all_fake(
                    photfiles[i])
            else:
                x, y, mag1, mag2, xxx, yyy, qc_ind1, qc_ind2 = read_all_fake(
                    photfiles[i], mag1_cut=999., mag2_cut=999.)
        else:
            x, y, mag1, mag2, qc_ind1, qc_ind2, matches = read_phot(
                photfiles[i])
        # HACK!!! This is to only use the phot stars found in both filters (with qc)
        if matched_only == True:
            qc_ind1 = matches
            qc_ind2 = matches
        d = pyfits.open(drzs[i])
        # get out of image coords
        ra, dec = XY2radec(d, x, y)
        # currect for chip gap and edges:
        within = in_chips(ra, dec, patch_list1a[i], patch_list1b[i])
        # field 3 is the chosen one to sit on top:
        if re.search('F03', photfiles[i]):
            inds1 = match_2inds(within, qc_ind1)
            inds2 = match_2inds(within, qc_ind2)
            if qc == False:
                inds1 = within
                inds2 = within
            Mag1 = mag1[inds1]
            Mag2 = mag2[inds2]
            Ra1 = ra[inds1]
            Dec1 = dec[inds1]
            Ra2 = ra[inds2]
            Dec2 = dec[inds2]
        # top row will only overlap with one to the right
        elif re.search('F0', photfiles[i]) or re.search(
                'F05', photfiles[i]) or re.search('F06', photfiles[i]):
            not_overlapped = poly_over_under(ra, dec, patch_list1b[i - 1],
                                             patch_list1a[i])
            inds1 = match_3inds(within, qc_ind1, not_overlapped)
            inds2 = match_3inds(within, qc_ind2, not_overlapped)
            if qc == False:
                inds1 = match_2inds(within, not_overlapped)
                inds2 = match_2inds(within, not_overlapped)
        # next two rows will overlap above and to the right
        else:
            # correct for overlap by field in above row
            #    by left chip
            top_a_a = poly_over_under(ra, dec, patch_list1a[i - 4],
                                      patch_list1a[i])
            top_a_b = poly_over_under(ra, dec, patch_list1a[i - 4],
                                      patch_list1b[i])
            top_b_b = poly_over_under(ra, dec, patch_list1b[i - 4],
                                      patch_list1b[i])
            tops = list(set(top_a_a) & set(top_a_b) & set(top_b_b))
            # correct for overlap by field to the left, F09 is the left-most.
            if re.search('F09', photfiles[i]) or re.search(
                    'F15', photfiles[i]):
                inds1 = list(set(qc_ind1) & set(within) & set(tops))
                inds2 = list(set(qc_ind2) & set(within) & set(tops))
            else:
                top_left_b_a = poly_over_under(ra, dec, patch_list1b[i - 5],
                                               patch_list1a[i])
                the_left = poly_over_under(ra, dec, patch_list1b[i - 1],
                                           patch_list1a[i])
                inds1 = list(
                    set(qc_ind1) & set(within) & set(tops) & set(top_left_b_a)
                    & set(the_left))
                inds2 = list(
                    set(qc_ind2) & set(within) & set(tops) & set(top_left_b_a)
                    & set(the_left))
                if qc == False:
                    inds1 = list(
                        set(within) & set(tops) & set(top_left_b_a)
                        & set(the_left))
                    inds2 = list(
                        set(within) & set(tops) & set(top_left_b_a)
                        & set(the_left))

        if plot == True:
            ax['fk5'].plot(ra[inds1],
                           dec[inds1],
                           'o',
                           ms=4,
                           mec=clrs[i],
                           color=clrs[i])
        Mag1 = np.append(Mag1, mag1[inds1])
        Mag2 = np.append(Mag2, mag2[inds2])
        Ra1 = np.append(Ra1, ra[inds1])
        Dec1 = np.append(Dec1, dec[inds1])
        Ra2 = np.append(Ra2, ra[inds2])
        Dec2 = np.append(Dec2, dec[inds2])

    return Ra1, Dec1, Ra2, Dec2, Mag1, Mag2
Пример #36
0
    def _make_axis(self):
        if self.fig is None:
            self.fig = plt.figure()

        if self.cmap is None:
            self.cmap = plt.cm.gray_r

        if self.twin and not self.right:
            if self.gs:
                gs = self.gs
            else:
                gs = 121
            self.ax = pywcsgrid2.subplot(gs, wcs=self.h1, aspect=self.aspect,adjustable='box',)
            
        elif self.twin and self.right:
            if self.gs:
                gs = self.gs
            else:
                gs = 122
            self.ax = pywcsgrid2.subplot(gs, wcs=self.h1, aspect=self.aspect,adjustable='box')
            
        elif self.gs:
            if 'PACS' in self.filename:
                self.ax = plt.subplot(self.gs,projection=self.w0)
            else:
                self.ax = pywcsgrid2.subplot(self.gs, wcs=self.h1, aspect=self.aspect,adjustable='box')

            #if self.h0['CTYPE1'] == 'GLON-CAR':
            #    self.ax.set_display_coord_system('fk5')
        else:
            self.ax = pywcsgrid2.axes(wcs=self.h1, aspect=self.aspect) #aspect=1
        self.ax.set_xlim(-self.nx/4, 5*self.nx/4)
        self.ax.set_ylim(-self.ny/4, 5*self.ny/4)

        if self.interp is None:
            if 'PACS' in self.filename:
                self.im = self.ax.imshow(self.data,origin='lower',vmin=self.vmin,vmax=self.vmax,cmap=self.cmap,norm=self.norm)
            else:
                self.im = self.ax[self.h0].imshow_affine(self.data,origin='lower',vmin=self.vmin,vmax=self.vmax,cmap=self.cmap,norm=self.norm)
        else:
            self.im = self.ax[self.h0].imshow(self.data,origin='lower',vmin=self.vmin,vmax=self.vmax,cmap=self.cmap,interpolation=self.interp,norm=self.norm)

        if self.xlim:
            self.ax.set_xlim(self.xlim)
        if self.ylim:
            self.ax.set_ylim(self.ylim)

        self.ax.grid(color='black', alpha=0.2, linestyle='dashed')

        if self.right:
            self.ax.axis['left'].major_ticklabels.set_visible(False)
            #self.ax.axis['right'].major_ticklabels.set_visible(True)
            self.ax.axis['right'].label.set_text(r"$\delta_{2000}$")
            plt.setp(self.ax.axis['right'].label,fontsize=14)
            self.ax.axis['left'].label.set_text('')

        else:
            try:
                plt.setp(self.ax.axis['left'].label,fontsize=14)
            except TypeError:
                plt.setp(self.ax.yaxis.label,fontsize=14)
        try:
            plt.setp(self.ax.axis['bottom'].label,fontsize=14)
        except TypeError:
            plt.setp(self.ax.xaxis.label,fontsize=14)
            
        return self.ax
Пример #37
0
def plot_four(epic,
              filename,
              coadd,
              maskmap,
              maskheader,
              init,
              coords,
              sources,
              ap=None,
              campaign=4):

    logging.info("Plot four %s", epic)
    logging.debug(base_path)

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

    hdu2 = fits.open(filename)
    dataheader = hdu2[1].header
    hdu2.close()
    keysel = np.empty(13, "S6")
    keysel[:] = "binary"
    w2 = WCS(dataheader, colsel=[5], keysel=keysel)

    # Plot DSS/SDSS image if available
    dssname = "{0}/ss_finders/{1}d/fc_{1}d_dssdss2red.fits".format(
        base_path, epic)
    sdssname = "{0}/ss_finders/{1}d/fc_{1}d_sdss (dr7)z.fits".format(
        base_path, epic)
    if os.path.exists(dssname):
        # Open image file
        hdu = fits.open(dssname)
        pix, hdr = hdu[0].data, hdu[0].header
        hdu.close()

    elif os.path.exists(sdssname):
        # Open image file
        hdu = fits.open(sdssname)
        pix, hdr = hdu[0].data, hdu[0].header
        hdu.close()

    else:
        pix = None

    # Set up the GridHelper to merge the axes
    grid_helper = pywcsgrid2.GridHelper(wcs=w2)

    # Plot the pixel stamp as usual, except with the WCS
    ax1 = pywcsgrid2.subplot(221,
                             grid_helper=grid_helper,
                             aspect=1,
                             adjustable="box-forced")
    ax1.matshow(coadd, origin="lower", cmap='Greys', norm=colors.LogNorm())
    if ap is not None:
        ap_circle = plt.Circle(coords,
                               ap,
                               color="k",
                               fill=False,
                               linewidth=1.5)
        ax1.add_artist(ap_circle)
    #ax1.axis["bottom","left","top","right"].toggle(ticklabels=False)

    if pix is not None:
        median = np.median(pix)
        stdev = np.std(pix)
        levels = np.linspace(median + stdev, np.max(pix), 5)
        ax1[hdr].contour(pix, colors="r", levels=levels)
        #        ax1.set_ticklabel_type("delta","delta",
        #                               dict(offset=np.float64(dataheader["1CRVL5"]),
        #                                    latitude=np.float64(dataheader["2CRVL5"])))

        # Plot the DSS image rotated into the same frame as the pixel stamp
        ax2 = pywcsgrid2.subplot(222,
                                 grid_helper=grid_helper,
                                 aspect=1,
                                 adjustable="box-forced",
                                 sharex=ax1,
                                 sharey=ax1)
        ax2[hdr].imshow_affine(pix,
                               origin="lower",
                               cmap='Greys',
                               norm=colors.LogNorm())
        median2 = np.median(coadd)
        stdev2 = np.std(coadd)
        levels2 = np.linspace(median, np.max(coadd), 5)
        #ax2[w2].contour(coadd,3, colors="r")
#        ax2.set_ticklabel_type("delta","delta")
#        ax2.axis["bottom","left","top","right"].toggle(ticklabels=False)

# Then the pixel motion across the CCD
    ax3 = plt.subplot(223)
    divider3 = make_axes_locatable(ax3)
    cax3 = divider3.append_axes("bottom", size="5%", pad=0.35)

    stamp(coadd, maskmap, ax=ax3, cmap="gray")

    lcs = at.read("{}/lcs/ktwo{}-c0{}.csv".format(base_path, epic, campaign))

    ax3.set_xlim(np.floor(min(lcs["x"])), np.ceil(max(lcs["x"])))
    ax3.set_ylim(np.floor(min(lcs["y"])), np.ceil(max(lcs["y"])))

    xyt = ax3.scatter(lcs["x"],
                      lcs["y"],
                      c=lcs["t"],
                      edgecolor="none",
                      alpha=0.5,
                      vmin=np.percentile(lcs["t"], 5),
                      vmax=np.percentile(lcs["t"], 95),
                      cmap="gnuplot")
    cbar_ticks = np.asarray(np.percentile(lcs["t"], np.arange(10, 100, 40)),
                            int)
    cbar1 = fig.colorbar(xyt,
                         cax=cax3,
                         ticks=cbar_ticks,
                         orientation="horizontal")
    cbar1.set_label("Time (d)", fontsize="small")

    # Then sky coordinates with the object position overlaid
    ax4 = plt.subplot(224)
    plot_chips(ax4, campaign)
    setup_k2_axes(ax4)
    plt.plot(maskheader["RA_OBJ"],
             maskheader["DEC_OBJ"],
             '*',
             color="Purple",
             ms=25,
             alpha=0.8)
    plt.setp(ax4.get_xticklabels()[::2], visible=False)
    plt.setp(ax4.get_yticklabels()[::2], visible=False)

    plt.suptitle("EPIC {}".format(epic))  #, fontsize="large")
    #plt.tight_layout()
    plt.subplots_adjust(top=0.95, hspace=0.5, wspace=0.8)
Пример #38
0
def line_stages(sname, linename, fancyname=None,
                stampdir="Stamps", drange=None, sky=0,
                pmax=None, psmooth=None, doublet=False):
    """
    Plot all the stages in the reduction of a normal or doublet line
    """
    SINGLET_TABLE = [
        ["", 0, 231, "Original"],
        ["-nc", 0, 232, "Line"],
        ["-nc", "CONT", 235, "Continuum"],
        ["-nc", "PROP", 233, "Proplyd"],
        ["-nc", "NEB", 236, ["", "Sky + "][sky] + "Nebula"]]
    DOUBLET_TABLE = [
        ["", 0, 241, "Original"],
        ["-nc", 0, 242, "Line"],
        ["-nc", "CONT", 246, "Continuum"],
        ["-nc-dd", 0, 243, "Deconvolved"],
        ["-nc-dd", "PROP", 244, "Proplyd"],
        ["-nc-dd", "NEB", 248, "Nebula"]]

    if doublet:
        table = DOUBLET_TABLE
        ncolumns = 4
        outid = "-doublet"
    else:
        table = SINGLET_TABLE
        ncolumns = 3
        outid = "-line"

    stampname = os.path.join(stampdir,
                             "-".join([sname, linename, "stamp"]))
    fig = plt.figure(figsize=[4*ncolumns, 7])
    h = None

    for suff, index, win, title in table:
        hdu = pyfits.open(stampname + suff + ".fits")[index]
        if index != "CONT":
            h = hdu.header
        d = hdu.data
        ax = pywcsgrid2.subplot(win, header=h)
        im = ax.imshow(d, vmin=drange[0], vmax=drange[1],
                       origin="low", cmap=plt.cm.gray_r,
                       aspect="auto",
                       interpolation="nearest")
        if index == "PROP" and pmax is not None:
            if psmooth is None:
                pd = d
            else:
                pd = ni.gaussian_filter(d.astype("d"), psmooth/FWHM)
            cs = ax.contour(pd, pmax*2**(-0.5*np.arange(NPCONT)),
                            colors="r", alpha=0.5)
            plt.clabel(cs, cs.levels[::2],
                       inline=True, fmt="%.0d", inline_spacing=1, fontsize=6)
        ax.set_ticklabel2_type("arcsec", scale=1./3600, nbins=8)
        ax.set_ticklabel1_type("absval", scale=1./1000, nbins=7)
        ax.set_xlim(*kms2xpix(h, [-30.0, 60.0]))
        ax.set_title(title)
        ax.grid()
        ax.axis["bottom"].label.set_text(
            r"$V_{\mathrm{top}}\ \mathrm{(km\,s^{-1})}$")

    # Make a separate axis on the second row just for the line label
    # Use 10 times as many horizontal divisions
    ax = plt.subplot(2, 10*ncolumns, 10*ncolumns+1, frameon=False)
    ax.axis("off")
    ax.text(0.0, 0.5, fancyname or linename,
            fontsize="x-large",
            horizontalalignment='left',
            verticalalignment='center',
            transform=ax.transAxes)

    # And another one for the color bar
    cb_ax = plt.subplot(2, 10*ncolumns, 10*ncolumns+6)
    cb = plt.colorbar(im, cax=cb_ax, orientation="vertical")
    cb.set_label("Intensity")

    fig.subplots_adjust(bottom=0.08, top=0.95,
                        left=0.05, right=0.99,
                        wspace=0.25, hspace=0.4)
    fig.savefig(stampname + outid + "-stages.pdf")
    plt.close(fig)
import matplotlib.pyplot as plt
from matplotlib.patheffects import withStroke

import pywcsgrid2
import pyfits


f = pyfits.open("Hen_3-519.Ha.fits")

fig = plt.figure(figsize=(8,4))
ax = pywcsgrid2.subplot(121, wcs=f[0].header)
ax.set_default_path_effects([withStroke(foreground="w", linewidth=3)])

im = ax.imshow(f[0].data, origin="lower", cmap="gray_r")
im.set_clim(2941, 15000)

ax.set(xlim=(149.5, 290.5),
       ylim=(149.5, 295.5))

ax.axis[:].toggle(all=False)
it = ax.add_inner_title(r"(a) Hen 3-519 : H$\alpha$", loc=2)
it.patch.set_ec("none")

pixels_of_30_arcmin = 0.5/60./f[0].header["CD2_2"]
ax.add_size_bar(pixels_of_30_arcmin, r"$30^{\prime\prime}$", loc=8)
ax.add_compass(loc=4)



f2 = pyfits.open("G26.47+0.02.24um.fits")