def integrated_map_axes_lv(fig, ax_limits, datacube, wcs_object, integration_limits,
                           aspect_in_units=5*(u.km/u.s)/u.deg, latitude_px_override=None,
                           cmap=dame_cmap):
    """ 
    Hackish way of exporting the above behavior to an ax object.

    """

    ax = WCSAxes(fig, ax_limits, wcs=wcs_object, 
                     slices=('x', 0, 'y'))
    fig.add_axes(ax)

    if latitude_px_override is None:
        min_b_px, max_b_px = latitude_world2pix(wcs_object, integration_limits)
        min_b_px, max_b_px = sanitize_integration_limits((min_b_px, max_b_px), datacube, axis=1)
    else:
        min_b_px, max_b_px = latitude_px_override
        
    array_lv = np.nansum(datacube[:,min_b_px:max_b_px,:], axis=1)
    array_lv[(array_lv < 0) | np.isinf(array_lv) | np.isnan(array_lv)] = 0

    ax.spatial_scale = np.abs(wcs_object.wcs.cdelt[0]) * u.deg
    ax.velocity_scale = np.abs(wcs_object.wcs.cdelt[2]) * u.km/u.s

    ax.aspect_px = (ax.velocity_scale/ax.spatial_scale)/aspect_in_units

    image_lv = ax.imshow(np.log10(array_lv+1), origin='lower', 
        interpolation='nearest', cmap=cmap, aspect=ax.aspect_px)

    return ax    
Пример #2
0
def make_left_plots(fig,main_dims,spec_dims,ra_main,dec_main):
	
	##A fits image header with which to create a wcs with
	header = { 'NAXIS'  : 2,             ##Number of data axis
    'NAXIS1' : 10,                  ##Length of X axis
    'CTYPE1' : 'RA---SIN',           ##Projection type of X axis
	'CRVAL1' : ra_main,        ##Central X world coord value
	'CRPIX1' : 5,                    ##Central X Pixel value
	'CUNIT1' : 'deg',                ##Unit of X axes
	'CDELT1' : -0.001*np.cos(dec_main*(np.pi/180.0)),              ##Size of pixel in world co-ord
	'NAXIS2' : 10,                  ##Length of X axis
	'CTYPE2' : 'DEC--SIN',           ##Projection along Y axis
	'CRVAL2' : dec_main,                   ##Central Y world coord value
	'CRPIX2' : 5,                    ##Central Y Pixel value
	'CUNIT2' : 'deg',                ##Unit of Y world coord
	'CDELT2' : +0.001      		     ##Size of pixel in deg
	} 
	
	##Create the ws, and the main axis based on that. Plot top left
	wcs = WCS(header=header)
	ax_main = WCSAxes(fig, main_dims, wcs=wcs)
	fig.add_axes(ax_main)
	tr_fk5 = ax_main.get_transform("fk5")
	
	#ax_main.set_title("All sources within 3'.0")
	ax_main.text(0.01,0.93,"All sources within search area",verticalalignment='bottom',horizontalalignment='left', transform=ax_main.transAxes,fontsize=16)
	
	##Create bottom left plot with log-log axes - set the error bars to plot
	##even if they go off the edge of the plot
	ax_spectral = fig.add_axes(spec_dims)
	ax_spectral.set_xscale("log",nonposx='clip')
	ax_spectral.set_yscale("log",nonposy='clip')
	
	return ax_main,ax_spectral,tr_fk5,wcs
def integrated_map_axes_lb(fig,
                           ax_limits,
                           datacube,
                           wcs_object,
                           integration_limits,
                           cmap=dame_cmap):
    """ 
    Hackish way of exporting the above behavior to an ax object.

    But it's actually on-the-sky.

    """

    ax = WCSAxes(fig, ax_limits, wcs=wcs_object, slices=('x', 'y', 0))
    fig.add_axes(ax)

    min_v_px, max_v_px = velocity_world2pix(wcs_object, integration_limits)
    min_v_px, max_v_px = sanitize_integration_limits((min_v_px, max_v_px),
                                                     datacube,
                                                     axis=0)

    array_lb = np.nansum(datacube[min_v_px:max_v_px, :, :], axis=0)
    array_lb[(array_lb < 0) | np.isinf(array_lb) | np.isnan(array_lb)] = 0

    ax.spatial_scale = np.abs(wcs_object.wcs.cdelt[0]) * u.deg
    ax.velocity_scale = np.abs(wcs_object.wcs.cdelt[2]) * u.km / u.s

    image_lb = ax.imshow(np.log10(array_lb + 1),
                         origin='lower',
                         interpolation='nearest',
                         cmap=cmap,
                         aspect=1)

    return ax
Пример #4
0
    def plot(self, ax=None, **kwargs):
        """Plot

        Parameters
        ----------
        ax : `~astropy.wcsaxes.WCSAxes`, optional
            WCS axis object

        Returns
        ----------
        ax : `~astropy.wcsaxes.WCSAxes`, optional
            WCS axis object
        """

        from matplotlib import colors
        import matplotlib.pyplot as plt
        from wcsaxes import WCSAxes

        if ax is None:
            fig = plt.figure()
            ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], wcs=self.wcs)
            fig.add_axes(ax) 

        if 'cmap' not in locals():
            cmap = colors.ListedColormap(['black', 'lightgrey'])

        ax.imshow(self.mask, cmap=cmap, origin='lower')

        return ax
Пример #5
0
    def test_direct_init(self, generate):

        s = DistanceToLonLat(R=6378.273)

        coord_meta = {}
        coord_meta['type'] = ('longitude', 'latitude')
        coord_meta['wrap'] = (360., None)
        coord_meta['unit'] = (u.deg, u.deg)
        coord_meta['name'] = 'lon', 'lat'
        fig = plt.figure(figsize=(4,4))

        ax = WCSAxes(fig, [0.15, 0.15, 0.7, 0.7], transform=s, coord_meta=coord_meta)
        fig.add_axes(ax)

        ax.coords['lon'].grid(color='red', linestyle='solid', alpha=0.3)
        ax.coords['lat'].grid(color='blue', linestyle='solid', alpha=0.3)

        ax.coords['lon'].set_ticklabel(size=7)
        ax.coords['lat'].set_ticklabel(size=7)

        ax.coords['lon'].set_ticklabel_position('brtl')
        ax.coords['lat'].set_ticklabel_position('brtl')

        ax.coords['lon'].set_ticks(spacing=10. * u.deg)
        ax.coords['lat'].set_ticks(spacing=10. * u.deg)

        ax.set_xlim(-400., 500.)
        ax.set_ylim(-300., 400.)

        self.generate_or_test(generate, fig, 'direct_init.png')
Пример #6
0
def query_time_series():

    data = np.loadtxt("dataserver_queries.csv",
                      comments='#',
                      delimiter=',',
                      usecols=(1, 2))

    dates = []
    with open('dataserver_queries.csv') as cvsfile:
        for row in csv.reader(cvsfile):
            if row[0][0] == "#":
                continue
            dates.append(datetime.datetime.strptime(row[0], "%Y-%m-%d"))

    FERMI_5YEAR_IMAGE = os.path.join(os.environ['GSSC_REFDATA'], \
                                 'Fermi_All_Sky_5year_GC.fits')

    fig = pt.figure(figsize=(10, 5))
    hdu = fits.open(fits_file)[0]

    # Setup the axes
    ax = WCSAxes(fig, [0.0, 0.0, 1.0, 1.0], wcs=WCS(hdu.header))
    fig.add_axes(ax)
    ax.set_xlim(-0.5, hdu.data.shape[1] - 0.5)
    ax.set_ylim(-0.5, hdu.data.shape[0] - 0.5)

    # Increase the default number of latitude grid lines.
    ax.coords[0].set_ticks(number=6)

    # Read in and scale the image.
    ax.imshow(hdu.data, origin='lower', cmap=pt.cm.CMRmap)

    # Add a coordinate grid.
    ax.grid(True, color='white', linestyle='solid', alpha=0.5)
def integrated_map_axes_lb(fig, ax_limits, datacube, wcs_object, integration_limits,
                           cmap=dame_cmap ):
    """ 
    Hackish way of exporting the above behavior to an ax object.

    But it's actually on-the-sky.

    """

    ax = WCSAxes(fig, ax_limits, wcs=wcs_object, 
                     slices=('x', 'y', 0))
    fig.add_axes(ax)

    min_v_px, max_v_px = velocity_world2pix(wcs_object, integration_limits)
    min_v_px, max_v_px = sanitize_integration_limits((min_v_px, max_v_px), datacube, axis=0)

    array_lb = np.nansum(datacube[min_v_px:max_v_px,:,:], axis=0)
    array_lb[(array_lb < 0) | np.isinf(array_lb) | np.isnan(array_lb)] = 0

    ax.spatial_scale = np.abs(wcs_object.wcs.cdelt[0]) * u.deg
    ax.velocity_scale = np.abs(wcs_object.wcs.cdelt[2]) * u.km/u.s    

    image_lb = ax.imshow(np.log10(array_lb+1), origin='lower', 
        interpolation='nearest', cmap=cmap, aspect=1)

    return ax
Пример #8
0
    def test_image_plot(self, generate):
        fig = plt.figure(figsize=(6, 6))
        ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], wcs=WCS(self.msx_header), aspect='equal')
        fig.add_axes(ax)
        ax.set_xlim(-0.5, 148.5)
        ax.set_ylim(-0.5, 148.5)
        ax.coords[0].set_ticks([-0.30, 0., 0.20] * u.degree, size=5, width=1)

        self.generate_or_test(generate, fig, 'image_plot.png')
Пример #9
0
def plot_overview(cube='../nro_maps/12CO_20161002_FOREST-BEARS_spheroidal_xyb_grid7.5_0.099kms.fits',
 region_file='../nro_maps/SouthShells.reg', mode='peak', plotname='12co_peak_shells.png',
 interactive=False, show_shells=False):
    """
    Show full image with all shells.
    
    Parameters
    ----------
    cube : str, optional
        Description
    region_file : str, optional
        Description
    mode : str, optional
        Description
    plotname : str, optional
        Description
    interactive : bool, optional
        Description
    show_shells : bool, optional
        Description
    
    """
    try:
        cube = SpectralCube.read(cube)
    except ValueError:
        pass

    if mode == "peak":
        image = cube.max(axis=0)

    fig = plt.figure()
    wcs = WCS(image.header)
    ax = WCSAxes(fig, [0.1,0.1,0.8,0.8], wcs=wcs) 
    fig.add_axes(ax)      
    imgplot = plt.imshow(image.data, cmap=cm.gray, origin='lower', interpolation='none',
        vmin=0., vmax=100)
    cb = plt.colorbar()
    cb.set_label(r'K [T$_{MB}$]')
    plt.title(r"$^{12}$CO Peak")

    if show_shells:
        r = pyregion.open(region_file).as_imagecoord(image.header)
        patch_list, artist_list = r.get_mpl_patches_texts()

        for p in patch_list:
            ax.add_patch(p)
        for t in artist_list:
            ax.add_artist(t)

        pass

    if interactive:
        plt.show()
    else:
        plt.savefig(plotname)
Пример #10
0
    def test_set_coord_type(self, generate):
        fig = plt.figure(figsize=(3, 3))
        ax = WCSAxes(fig, [0.2, 0.2, 0.6, 0.6], wcs=WCS(self.msx_header), aspect='equal')
        fig.add_axes(ax)
        ax.set_xlim(-0.5, 148.5)
        ax.set_ylim(-0.5, 148.5)
        ax.coords[0].set_coord_type('scalar')
        ax.coords[1].set_coord_type('scalar')
        ax.coords[0].set_major_formatter('x.xxx')
        ax.coords[1].set_major_formatter('x.xxx')

        self.generate_or_test(generate, fig, 'set_coord_type.png')
Пример #11
0
    def test_cube_slice_image(self, generate):
        w = WCS(self.cube_header)
        fig = plt.figure()
        ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], w, slices=(50, 'y', 'x'), aspect='equal')
        fig.add_axes(ax)
        ax.set_xlim(-0.5, 52.5)
        ax.set_ylim(-0.5, 106.5)
        ax.coords[2].set_axislabel('Velocity m/s')
        ax.coords[1].set_ticks(width=1)
        ax.coords[2].set_ticks(width=1)

        self.generate_or_test(generate, fig, 'cube_slice_image.png')
Пример #12
0
    def time_basic_plot(self):

        fig = Figure()
        canvas = FigureCanvas(fig)

        ax = WCSAxes(fig, [0.15, 0.15, 0.7, 0.7],
                     wcs=WCS(self.msx_header))
        fig.add_axes(ax)

        ax.set_xlim(-0.5, 148.5)
        ax.set_ylim(-0.5, 148.5)

        canvas.draw()
Пример #13
0
    def test_changed_axis_units(self, generate):
        w = WCS(self.cube_header)
        fig = plt.figure()
        ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], w, slices=(50, 'y', 'x'), aspect='equal')
        fig.add_axes(ax)
        ax.set_xlim(-0.5, 52.5)
        ax.set_ylim(-0.5, 106.5)
        ax.coords[2].set_major_formatter('x.xx')
        ax.coords[2].set_format_unit(u.km / u.s)
        ax.coords[2].set_axislabel('Velocity km/s')
        ax.coords[1].set_ticks(width=1)
        ax.coords[2].set_ticks(width=1)

        self.generate_or_test(generate, fig, 'changed_axis_units.png')
Пример #14
0
    def test_overlay_features_image(self, generate):
        fig = plt.figure(figsize=(6, 6))
        ax = WCSAxes(fig, [0.25, 0.25, 0.65, 0.65], wcs=WCS(self.msx_header), aspect='equal')
        fig.add_axes(ax)
        # Change the format of the ticks
        ax.coords[0].set_major_formatter('dd:mm:ss')
        ax.coords[1].set_major_formatter('dd:mm:ss.ssss')

        # Overlay grid on image
        ax.grid(color='red', alpha=1.0, lw=1, linestyle='dashed')

        # Set the spacing of ticks on the 'glon' axis to 4 arcsec
        ax.coords['glon'].set_ticks(spacing=4 * u.arcsec, size=5, width=1)
        # Set the number of ticks on the 'glat' axis to 9
        ax.coords['glat'].set_ticks(number=9, size=5, width=1)
        # Set labels on axes
        ax.coords['glon'].set_axislabel('Galactic Longitude', minpad=1.6)
        ax.coords['glat'].set_axislabel('Galactic Latitude', minpad=-0.75)

        self.generate_or_test(generate, fig, 'overlay_features_image.png')
Пример #15
0
    def test_ticks_labels(self, generate):
        fig = plt.figure(figsize=(6, 6))
        ax = WCSAxes(fig, [0.1, 0.1, 0.7, 0.7], wcs=None)
        fig.add_axes(ax)
        ax.set_xlim(-0.5, 2)
        ax.set_ylim(-0.5, 2)
        ax.coords[0].set_ticks(size=10, color='blue', alpha=0.2, width=1)
        ax.coords[1].set_ticks(size=20, color='red', alpha=0.9, width=1)
        ax.coords[0].set_ticks_position('all')
        ax.coords[1].set_ticks_position('all')
        ax.coords[0].set_axislabel('X-axis', size=20)
        ax.coords[1].set_axislabel('Y-axis', color='green', size=25, weight='regular', style='normal', family='monospace')
        ax.coords[0].set_axislabel_position('t')
        ax.coords[1].set_axislabel_position('r')
        ax.coords[0].set_ticklabel(color='purple', size=15, alpha=1, weight='light', style='normal', family='sans-serif')
        ax.coords[1].set_ticklabel(color='black', size=18, alpha=0.9, weight='bold', family='serif')
        ax.coords[0].set_ticklabel_position('all')
        ax.coords[1].set_ticklabel_position('r')

        self.generate_or_test(generate, fig, 'ticks_labels.png')
Пример #16
0
    def test_direct_init(self, generate):

        s = DistanceToLonLat(R=6378.273)

        coord_meta = {}
        coord_meta['type'] = ('longitude', 'latitude')
        coord_meta['wrap'] = (360., None)
        coord_meta['unit'] = (u.deg, u.deg)
        coord_meta['name'] = 'lon', 'lat'
        fig = plt.figure(figsize=(4, 4))

        ax = WCSAxes(fig, [0.15, 0.15, 0.7, 0.7],
                     transform=s,
                     coord_meta=coord_meta)
        fig.add_axes(ax)

        ax.coords['lon'].grid(color='red', linestyle='solid', alpha=0.3)
        ax.coords['lat'].grid(color='blue', linestyle='solid', alpha=0.3)

        ax.coords['lon'].set_ticklabel(size=7)
        ax.coords['lat'].set_ticklabel(size=7)

        ax.coords['lon'].set_ticklabel_position('brtl')
        ax.coords['lat'].set_ticklabel_position('brtl')

        ax.coords['lon'].set_ticks(spacing=10. * u.deg,
                                   exclude_overlapping=True)
        ax.coords['lat'].set_ticks(spacing=10. * u.deg,
                                   exclude_overlapping=True)

        ax.set_xlim(-400., 500.)
        ax.set_ylim(-300., 400.)

        self.generate_or_test(generate, fig, 'direct_init.png')
def plotimagewcs(fits_image,
                 fig,
                 location=[0, 1, 0, 1],
                 vmin=0,
                 vmax=4,
                 haflag=0):
    rfits = fits.open(fits_image)
    im = rfits[0].data.copy()
    wcs = WCS(rfits[0].header)
    rfits.close()

    ax = WCSAxes(fig, location, wcs=wcs)
    fig.add_axes(ax)
    axis('equal')
    if haflag:
        ny, nx = im.shape
        #imshow((im[int(.25*nx):int(.75*nx),int(.25*ny):int(.75*ny)]),interpolation='nearest',origin='upper',cmap='binary',vmin=vmin,vmax=vmax)
        ax.imshow((im),
                  interpolation='nearest',
                  cmap=cm.gray_r,
                  vmin=vmin,
                  vmax=vmax,
                  origin='lower')
    else:
        ax.imshow((im),
                  interpolation='nearest',
                  cmap=cm.gray_r,
                  vmin=vmin,
                  vmax=vmax,
                  origin='lower')
Пример #18
0
    def time_basic_plot_with_grid(self):

        fig = Figure()
        canvas = FigureCanvas(fig)

        ax = WCSAxes(fig, [0.15, 0.15, 0.7, 0.7], wcs=WCS(self.msx_header))
        fig.add_axes(ax)

        ax.grid(color='red', alpha=0.5, linestyle='solid')

        ax.set_xlim(-0.5, 148.5)
        ax.set_ylim(-0.5, 148.5)

        canvas.draw()
Пример #19
0
    def test_overlay_features_image(self, generate):
        fig = plt.figure(figsize=(6, 6))
        ax = WCSAxes(fig, [0.25, 0.25, 0.65, 0.65], wcs=WCS(self.msx_header), aspect='equal')
        fig.add_axes(ax)
        # Change the format of the ticks
        ax.coords[0].set_major_formatter('dd:mm:ss')
        ax.coords[1].set_major_formatter('dd:mm:ss.ssss')

        # Overlay grid on image
        ax.grid(color='red', alpha=1.0, lw=1, linestyle='dashed')

        # Set the spacing of ticks on the 'glon' axis to 4 arcsec
        ax.coords['glon'].set_ticks(spacing=4 * u.arcsec, size=5, width=1)
        # Set the number of ticks on the 'glat' axis to 9
        ax.coords['glat'].set_ticks(number=9, size=5, width=1)
        # Set labels on axes
        ax.coords['glon'].set_axislabel('Galactic Longitude', minpad=1.6)
        ax.coords['glat'].set_axislabel('Galactic Latitude', minpad=-0.75)
        # Change the frame linewidth and color
        ax.coords.frame.set_color('red')
        ax.coords.frame.set_linewidth(2)

        self.generate_or_test(generate, fig, 'overlay_features_image.png')
Пример #20
0
    def test_image_plot(self, generate):
        fig = plt.figure(figsize=(6, 6))
        ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], wcs=WCS(self.msx_header), aspect='equal')
        fig.add_axes(ax)
        ax.set_xlim(-0.5, 148.5)
        ax.set_ylim(-0.5, 148.5)
        ax.coords[0].set_ticks([-0.30, 0., 0.20] * u.degree, size=5, width=1)

        self.generate_or_test(generate, fig, 'image_plot.png')
Пример #21
0
 def test_tick_angles_non_square_axes(self, generate):
     w = WCS()
     w.wcs.ctype = ['RA---TAN', 'DEC--TAN']
     w.wcs.crval = [90, 70]
     w.wcs.cdelt = [16, 16]
     w.wcs.crpix = [1, 1]
     w.wcs.radesys = 'ICRS'
     w.wcs.equinox = 2000.0
     fig = plt.figure(figsize=(6, 3))
     ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], wcs=w)
     fig.add_axes(ax)
     ax.set_xlim(1, -1)
     ax.set_ylim(-1, 1)
     ax.grid(color='gray', alpha=0.5, linestyle='solid')
     ax.coords['ra'].set_ticks(color='red', size=20)
     ax.coords['dec'].set_ticks(color='red', size=20)
     self.generate_or_test(generate, fig, 'tick_angles_non_square_axes.png')
Пример #22
0
 def __init__(self, pw):
     from wcsaxes import WCSAxes
     if pw.oblique:
         raise NotImplementedError("WCS axes are not implemented for oblique plots.")
     if not hasattr(pw.ds, "wcs_2d"):
         raise NotImplementedError("WCS axes are not implemented for this dataset.")
     if pw.data_source.axis != pw.ds.spec_axis:
         raise NotImplementedError("WCS axes are not implemented for this axis.")
     self.plots = {}
     self.pw = pw
     for f in pw.plots:
         rect = pw.plots[f]._get_best_layout()[1]
         fig = pw.plots[f].figure
         ax = fig.axes[0]
         wcs_ax = WCSAxes(fig, rect, wcs=pw.ds.wcs_2d, frameon=False)
         fig.add_axes(wcs_ax)
         wcs = pw.ds.wcs_2d.wcs
         xax = pw.ds.coordinates.x_axis[pw.data_source.axis]
         yax = pw.ds.coordinates.y_axis[pw.data_source.axis]
         xlabel = "%s (%s)" % (wcs.ctype[xax].split("-")[0],
                               wcs.cunit[xax])
         ylabel = "%s (%s)" % (wcs.ctype[yax].split("-")[0],
                               wcs.cunit[yax])
         fp = pw._font_properties
         wcs_ax.coords[0].set_axislabel(xlabel, fontproperties=fp, minpad=0.5)
         wcs_ax.coords[1].set_axislabel(ylabel, fontproperties=fp, minpad=0.4)
         wcs_ax.coords[0].ticklabels.set_fontproperties(fp)
         wcs_ax.coords[1].ticklabels.set_fontproperties(fp)
         ax.xaxis.set_visible(False)
         ax.yaxis.set_visible(False)
         wcs_ax.set_xlim(pw.xlim[0].value, pw.xlim[1].value)
         wcs_ax.set_ylim(pw.ylim[0].value, pw.ylim[1].value)
         wcs_ax.coords.frame._update_cache = []
         ax.xaxis.set_visible(False)
         ax.yaxis.set_visible(False)
         self.plots[f] = fig
Пример #23
0
    def test_coords_overlay_auto_coord_meta(self, generate):

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

        ax = WCSAxes(fig, [0.15, 0.15, 0.7, 0.7], wcs=WCS(self.msx_header))
        fig.add_axes(ax)

        ax.grid(color='red', alpha=0.5, linestyle='solid')

        overlay = ax.get_coords_overlay('fk5')  # automatically sets coord_meta

        overlay.grid(color='black', alpha=0.5, linestyle='solid')

        overlay['ra'].set_ticks(color='black')
        overlay['dec'].set_ticks(color='black')

        ax.set_xlim(-0.5, 148.5)
        ax.set_ylim(-0.5, 148.5)

        self.generate_or_test(generate, fig,
                              'coords_overlay_auto_coord_meta.png')
Пример #24
0
    def __init__(self, pw):
        try:
            # Attempt import from the old WCSAxes package first
            from wcsaxes import WCSAxes

            issue_deprecation_warning("Support for the standalone 'wcsaxes' "
                                      "package is deprecated since its"
                                      "functionality has been merged into"
                                      "AstroPy, and will be removed in a "
                                      "future release. It is recommended to "
                                      "use the version bundled with AstroPy "
                                      ">= 1.3.")
        except ImportError:
            # Try to use the AstroPy version
            WCSAxes = _astropy.wcsaxes.WCSAxes

        if pw.oblique:
            raise NotImplementedError(
                "WCS axes are not implemented for oblique plots.")
        if not hasattr(pw.ds, "wcs_2d"):
            raise NotImplementedError(
                "WCS axes are not implemented for this dataset.")
        if pw.data_source.axis != pw.ds.spec_axis:
            raise NotImplementedError(
                "WCS axes are not implemented for this axis.")
        self.plots = {}
        self.pw = pw
        for f in pw.plots:
            rect = pw.plots[f]._get_best_layout()[1]
            fig = pw.plots[f].figure
            ax = fig.axes[0]
            wcs_ax = WCSAxes(fig, rect, wcs=pw.ds.wcs_2d, frameon=False)
            fig.add_axes(wcs_ax)
            wcs = pw.ds.wcs_2d.wcs
            xax = pw.ds.coordinates.x_axis[pw.data_source.axis]
            yax = pw.ds.coordinates.y_axis[pw.data_source.axis]
            xlabel = "%s (%s)" % (wcs.ctype[xax].split("-")[0], wcs.cunit[xax])
            ylabel = "%s (%s)" % (wcs.ctype[yax].split("-")[0], wcs.cunit[yax])
            fp = pw._font_properties
            wcs_ax.coords[0].set_axislabel(xlabel,
                                           fontproperties=fp,
                                           minpad=0.5)
            wcs_ax.coords[1].set_axislabel(ylabel,
                                           fontproperties=fp,
                                           minpad=0.4)
            wcs_ax.coords[0].ticklabels.set_fontproperties(fp)
            wcs_ax.coords[1].ticklabels.set_fontproperties(fp)
            ax.xaxis.set_visible(False)
            ax.yaxis.set_visible(False)
            wcs_ax.set_xlim(pw.xlim[0].value, pw.xlim[1].value)
            wcs_ax.set_ylim(pw.ylim[0].value, pw.ylim[1].value)
            wcs_ax.coords.frame._update_cache = []
            ax.xaxis.set_visible(False)
            ax.yaxis.set_visible(False)
            self.plots[f] = fig
Пример #25
0
 def test_rcparams(self, generate):
     with rc_context({
             'xtick.color': 'red',
             'xtick.major.size': 20,
             'xtick.major.width': 2,
             'grid.color': 'blue',
             'grid.linestle': ':.',
             'grid.linewidth': 1,
             'grid.alpha': 0.5}):
         fig = plt.figure(figsize=(6, 6))
         ax = WCSAxes(fig, [0.1, 0.1, 0.7, 0.7], wcs=None)
         fig.add_axes(ax)
         ax.set_xlim(-0.5, 2)
         ax.set_ylim(-0.5, 2)
         ax.grid()
         ax.coords[0].set_ticks(exclude_overlapping=True)
         ax.coords[1].set_ticks(exclude_overlapping=True)
         self.generate_or_test(generate, fig, 'rcparams.png')
Пример #26
0
    def time_basic_plot_with_grid(self):

        fig = Figure()
        canvas = FigureCanvas(fig)

        ax = WCSAxes(fig, [0.15, 0.15, 0.7, 0.7],
                     wcs=WCS(self.msx_header))
        fig.add_axes(ax)

        ax.grid(color='red', alpha=0.5, linestyle='solid')

        ax.set_xlim(-0.5, 148.5)
        ax.set_ylim(-0.5, 148.5)

        canvas.draw()
Пример #27
0
    def time_basic_plot(self):

        fig = Figure()
        canvas = FigureCanvas(fig)

        ax = WCSAxes(fig, [0.15, 0.15, 0.7, 0.7], wcs=WCS(self.msx_header))
        fig.add_axes(ax)

        ax.set_xlim(-0.5, 148.5)
        ax.set_ylim(-0.5, 148.5)

        canvas.draw()
Пример #28
0
 def test_rcparams(self, generate):
     with rc_context({
             'xtick.color': 'red',
             'xtick.major.size': 20,
             'xtick.major.width': 2,
             'grid.color': 'blue',
             'grid.linestle': ':.',
             'grid.linewidth': 1,
             'grid.alpha': 0.5}):
         fig = plt.figure(figsize=(6, 6))
         ax = WCSAxes(fig, [0.1, 0.1, 0.7, 0.7], wcs=None)
         fig.add_axes(ax)
         ax.set_xlim(-0.5, 2)
         ax.set_ylim(-0.5, 2)
         ax.grid()
         self.generate_or_test(generate, fig, 'rcparams.png')
Пример #29
0
    def test_coords_overlay_auto_coord_meta(self, generate):

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

        ax = WCSAxes(fig, [0.15, 0.15, 0.7, 0.7], wcs=WCS(self.msx_header))
        fig.add_axes(ax)

        ax.grid(color='red', alpha=0.5, linestyle='solid')

        overlay = ax.get_coords_overlay('fk5')  # automatically sets coord_meta

        overlay.grid(color='black', alpha=0.5, linestyle='solid')

        overlay['ra'].set_ticks(color='black')
        overlay['dec'].set_ticks(color='black')

        ax.set_xlim(-0.5, 148.5)
        ax.set_ylim(-0.5, 148.5)

        self.generate_or_test(generate, fig, 'coords_overlay_auto_coord_meta.png')
Пример #30
0
 def test_tick_angles_non_square_axes(self, generate):
     w = WCS()
     w.wcs.ctype = ['RA---TAN', 'DEC--TAN']
     w.wcs.crval = [90, 70]
     w.wcs.cdelt = [16, 16]
     w.wcs.crpix = [1, 1]
     w.wcs.radesys = 'ICRS'
     w.wcs.equinox = 2000.0
     fig = plt.figure(figsize=(6, 3))
     ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], wcs=w)
     fig.add_axes(ax)
     ax.set_xlim(1, -1)
     ax.set_ylim(-1, 1)
     ax.grid(color='gray', alpha=0.5, linestyle='solid')
     ax.coords['ra'].set_ticks(color='red', size=20)
     ax.coords['dec'].set_ticks(color='red', size=20)
     self.generate_or_test(generate, fig, 'tick_angles_non_square_axes.png')
Пример #31
0
    def test_coords_overlay(self, generate):

        # Set up a simple WCS that maps pixels to non-projected distances
        wcs = WCS(naxis=2)
        wcs.wcs.ctype = ['x', 'y']
        wcs.wcs.cunit = ['km', 'km']
        wcs.wcs.crpix = [614.5, 856.5]
        wcs.wcs.cdelt = [6.25, 6.25]
        wcs.wcs.crval = [0., 0.]

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

        ax = WCSAxes(fig, [0.15, 0.15, 0.7, 0.7], wcs=wcs)
        fig.add_axes(ax)

        s = DistanceToLonLat(R=6378.273)

        ax.coords['x'].set_ticklabel_position('')
        ax.coords['y'].set_ticklabel_position('')

        coord_meta = {}
        coord_meta['type'] = ('longitude', 'latitude')
        coord_meta['wrap'] = (360., None)
        coord_meta['unit'] = (u.deg, u.deg)
        coord_meta['name'] = 'lon', 'lat'

        overlay = ax.get_coords_overlay(s, coord_meta=coord_meta)

        overlay.grid(color='red')
        overlay['lon'].grid(color='red', linestyle='solid', alpha=0.3)
        overlay['lat'].grid(color='blue', linestyle='solid', alpha=0.3)

        overlay['lon'].set_ticklabel(size=7)
        overlay['lat'].set_ticklabel(size=7)

        overlay['lon'].set_ticklabel_position('brtl')
        overlay['lat'].set_ticklabel_position('brtl')

        overlay['lon'].set_ticks(spacing=10. * u.deg, exclude_overlapping=True)
        overlay['lat'].set_ticks(spacing=10. * u.deg, exclude_overlapping=True)

        ax.set_xlim(-0.5, 1215.5)
        ax.set_ylim(-0.5, 1791.5)

        self.generate_or_test(generate, fig, 'coords_overlay.png')
Пример #32
0
    def test_changed_axis_units(self, generate):
        w = WCS(self.cube_header)
        fig = plt.figure()
        ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], w, slices=(50, 'y', 'x'), aspect='equal')
        fig.add_axes(ax)
        ax.set_xlim(-0.5, 52.5)
        ax.set_ylim(-0.5, 106.5)
        ax.coords[2].set_major_formatter('x.xx')
        ax.coords[2].set_format_unit(u.km / u.s)
        ax.coords[2].set_axislabel('Velocity km/s')
        ax.coords[1].set_ticks(width=1, exclude_overlapping=True)
        ax.coords[2].set_ticks(width=1, exclude_overlapping=True)

        self.generate_or_test(generate, fig, 'changed_axis_units.png')
Пример #33
0
    def test_set_coord_type(self, generate):
        fig = plt.figure(figsize=(3, 3))
        ax = WCSAxes(fig, [0.2, 0.2, 0.6, 0.6], wcs=WCS(self.msx_header), aspect='equal')
        fig.add_axes(ax)
        ax.set_xlim(-0.5, 148.5)
        ax.set_ylim(-0.5, 148.5)
        ax.coords[0].set_coord_type('scalar')
        ax.coords[1].set_coord_type('scalar')
        ax.coords[0].set_major_formatter('x.xxx')
        ax.coords[1].set_major_formatter('x.xxx')
        ax.coords[0].set_ticks(exclude_overlapping=True)
        ax.coords[1].set_ticks(exclude_overlapping=True)

        self.generate_or_test(generate, fig, 'set_coord_type.png')
Пример #34
0
    def test_minor_ticks(self, generate):
        w = WCS(self.cube_header)
        fig = plt.figure()
        ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], w, slices=(50, 'y', 'x'), aspect='equal')
        fig.add_axes(ax)
        ax.set_xlim(-0.5, 52.5)
        ax.set_ylim(-0.5, 106.5)
        ax.coords[2].set_ticks(exclude_overlapping=True)
        ax.coords[1].set_ticks(exclude_overlapping=True)
        ax.coords[2].display_minor_ticks(True)
        ax.coords[1].display_minor_ticks(True)
        ax.coords[2].set_minor_frequency(3)
        ax.coords[1].set_minor_frequency(10)

        self.generate_or_test(generate, fig, 'minor_ticks_image.png')
Пример #35
0
    def test_coords_overlay(self, generate):

        # Set up a simple WCS that maps pixels to non-projected distances
        wcs = WCS(naxis=2)
        wcs.wcs.ctype = ['x', 'y']
        wcs.wcs.cunit = ['km', 'km']
        wcs.wcs.crpix = [614.5, 856.5]
        wcs.wcs.cdelt = [6.25, 6.25]
        wcs.wcs.crval = [0., 0.]

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

        ax = WCSAxes(fig, [0.15, 0.15, 0.7, 0.7], wcs=wcs)
        fig.add_axes(ax)

        s = DistanceToLonLat(R=6378.273)

        ax.coords['x'].set_ticklabel_position('')
        ax.coords['y'].set_ticklabel_position('')

        coord_meta = {}
        coord_meta['type'] = ('longitude', 'latitude')
        coord_meta['wrap'] = (360., None)
        coord_meta['unit'] = (u.deg, u.deg)
        coord_meta['name'] = 'lon', 'lat'

        overlay = ax.get_coords_overlay(s, coord_meta=coord_meta)

        overlay.grid(color='red')
        overlay['lon'].grid(color='red', linestyle='solid', alpha=0.3)
        overlay['lat'].grid(color='blue', linestyle='solid', alpha=0.3)

        overlay['lon'].set_ticklabel(size=7)
        overlay['lat'].set_ticklabel(size=7)

        overlay['lon'].set_ticklabel_position('brtl')
        overlay['lat'].set_ticklabel_position('brtl')

        overlay['lon'].set_ticks(spacing=10. * u.deg)
        overlay['lat'].set_ticks(spacing=10. * u.deg)

        ax.set_xlim(-0.5, 1215.5)
        ax.set_ylim(-0.5, 1791.5)

        self.generate_or_test(generate, fig, 'coords_overlay.png')
    def __init__(self,
                 datacube,
                 wcs_object,
                 aspect_in_units=5 * (u.km / u.s) / u.deg,
                 cmap=dame_cmap,
                 integration_limits=(-1, 1),
                 figsize=(10, 9),
                 vmin=None,
                 vmax=None):

        self.datacube = datacube
        self.wcs = wcs_object

        self.fig = plt.figure(figsize=figsize)
        self.cmap = cmap
        self.vmin = vmin
        self.vmax = vmax

        ax = WCSAxes(self.fig, [0.1, 0.1, 0.8, 0.8],
                     wcs=self.wcs,
                     slices=('x', 0, 'y'))
        self.ax = self.fig.add_axes(ax)

        min_b_px, max_b_px = latitude_world2pix(self.wcs, integration_limits)

        array_lv = np.nansum(self.datacube[:, min_b_px:max_b_px, :], axis=1)
        array_lv[(array_lv < 0) | np.isinf(array_lv) | np.isnan(array_lv)] = 0
        self.array_lv = array_lv

        self.spatial_scale = np.abs(self.wcs.wcs.cdelt[0]) * u.deg
        self.velocity_scale = np.abs(self.wcs.wcs.cdelt[2]) * u.km / u.s

        self.aspect_px = (self.velocity_scale /
                          self.spatial_scale) / aspect_in_units

        self._draw_plot()
Пример #37
0
    def test_ticks_labels(self, generate):
        fig = plt.figure(figsize=(6, 6))
        ax = WCSAxes(fig, [0.1, 0.1, 0.7, 0.7], wcs=None)
        fig.add_axes(ax)
        ax.set_xlim(-0.5, 2)
        ax.set_ylim(-0.5, 2)
        ax.coords[0].set_ticks(size=10, color='blue', alpha=0.2, width=1)
        ax.coords[1].set_ticks(size=20, color='red', alpha=0.9, width=1)
        ax.coords[0].set_ticks_position('all')
        ax.coords[1].set_ticks_position('all')
        ax.coords[0].set_axislabel('X-axis', size=20)
        ax.coords[1].set_axislabel('Y-axis', color='green', size=25, weight='regular', style='normal', family='monospace')
        ax.coords[0].set_axislabel_position('t')
        ax.coords[1].set_axislabel_position('r')
        ax.coords[0].set_ticklabel(color='purple', size=15, alpha=1, weight='light', style='normal', family='sans-serif')
        ax.coords[1].set_ticklabel(color='black', size=18, alpha=0.9, weight='bold', family='serif')
        ax.coords[0].set_ticklabel_position('all')
        ax.coords[1].set_ticklabel_position('r')

        self.generate_or_test(generate, fig, 'ticks_labels.png', bbox_inches='tight')
Пример #38
0
 def __init__(self, pw):
     from wcsaxes import WCSAxes
     if pw.oblique:
         raise NotImplementedError(
             "WCS axes are not implemented for oblique plots.")
     if not hasattr(pw.ds, "wcs_2d"):
         raise NotImplementedError(
             "WCS axes are not implemented for this dataset.")
     if pw.data_source.axis != pw.ds.spec_axis:
         raise NotImplementedError(
             "WCS axes are not implemented for this axis.")
     self.plots = {}
     self.pw = pw
     for f in pw.plots:
         rect = pw.plots[f]._get_best_layout()[1]
         fig = pw.plots[f].figure
         ax = fig.axes[0]
         wcs_ax = WCSAxes(fig, rect, wcs=pw.ds.wcs_2d, frameon=False)
         fig.add_axes(wcs_ax)
         wcs = pw.ds.wcs_2d.wcs
         xax = pw.ds.coordinates.x_axis[pw.data_source.axis]
         yax = pw.ds.coordinates.y_axis[pw.data_source.axis]
         xlabel = "%s (%s)" % (wcs.ctype[xax].split("-")[0], wcs.cunit[xax])
         ylabel = "%s (%s)" % (wcs.ctype[yax].split("-")[0], wcs.cunit[yax])
         fp = pw._font_properties
         wcs_ax.coords[0].set_axislabel(xlabel,
                                        fontproperties=fp,
                                        minpad=0.5)
         wcs_ax.coords[1].set_axislabel(ylabel,
                                        fontproperties=fp,
                                        minpad=0.4)
         wcs_ax.coords[0].ticklabels.set_fontproperties(fp)
         wcs_ax.coords[1].ticklabels.set_fontproperties(fp)
         ax.xaxis.set_visible(False)
         ax.yaxis.set_visible(False)
         wcs_ax.set_xlim(pw.xlim[0].value, pw.xlim[1].value)
         wcs_ax.set_ylim(pw.ylim[0].value, pw.ylim[1].value)
         wcs_ax.coords.frame._update_cache = []
         ax.xaxis.set_visible(False)
         ax.yaxis.set_visible(False)
         self.plots[f] = fig
def integrated_map_axes_lv(fig,
                           ax_limits,
                           datacube,
                           wcs_object,
                           integration_limits,
                           aspect_in_units=5 * (u.km / u.s) / u.deg,
                           latitude_px_override=None,
                           cmap=dame_cmap):
    """ 
    Hackish way of exporting the above behavior to an ax object.

    """

    ax = WCSAxes(fig, ax_limits, wcs=wcs_object, slices=('x', 0, 'y'))
    fig.add_axes(ax)

    if latitude_px_override is None:
        min_b_px, max_b_px = latitude_world2pix(wcs_object, integration_limits)
        min_b_px, max_b_px = sanitize_integration_limits((min_b_px, max_b_px),
                                                         datacube,
                                                         axis=1)
    else:
        min_b_px, max_b_px = latitude_px_override

    array_lv = np.nansum(datacube[:, min_b_px:max_b_px, :], axis=1)
    array_lv[(array_lv < 0) | np.isinf(array_lv) | np.isnan(array_lv)] = 0

    ax.spatial_scale = np.abs(wcs_object.wcs.cdelt[0]) * u.deg
    ax.velocity_scale = np.abs(wcs_object.wcs.cdelt[2]) * u.km / u.s

    ax.aspect_px = (ax.velocity_scale / ax.spatial_scale) / aspect_in_units

    image_lv = ax.imshow(np.log10(array_lv + 1),
                         origin='lower',
                         interpolation='nearest',
                         cmap=cmap,
                         aspect=ax.aspect_px)

    return ax
Пример #40
0
def plot(LSM, fileName=None, labelBy=None):
    """
    Shows a simple plot of the sky model.

    The circles in the plot are scaled with flux. If the sky model is grouped
    into patches, sources are colored by patch and the patch positions are
    indicated with stars.

    Parameters
    ----------
    LSM : SkyModel object
        Input sky model
    fileName : str, optional
        If given, the plot is saved to a file instead of displayed
    labelBy : str, optional
        One of 'source' or 'patch': label points using source names ('source') or
        patch names ('patch')

    Examples:
    ---------
    Plot and display to the screen::

        >>> LSM = lsmtool.load('sky.model')
        >>> plot(LSM)

    Plot and save to a PDF file::

        >>> plot(LSM, 'sky_plot.pdf')

    """
    try:
        import os
        if 'DISPLAY' not in os.environ:
            import matplotlib
            if matplotlib.get_backend() is not 'Agg':
                matplotlib.use("Agg")
        import matplotlib.pyplot as plt
        from matplotlib.ticker import FuncFormatter
    except Exception as e:
        raise ImportError('PyPlot could not be imported. Plotting is not '
            'available: {0}'.format(e.message))
    try:
        from wcsaxes import WCSAxes
        hasWCSaxes = True
    except:
        hasWCSaxes = False
    import numpy as np
    from ..operations_lib import radec2xy, makeWCS
    global midRA, midDec, ymin, xmin

    if len(LSM) == 0:
        log.error('Sky model is empty.')
        return

    fig = plt.figure(1,figsize=(7.66,7))
    plt.clf()
    x, y, midRA, midDec  = LSM._getXY()
    if hasWCSaxes:
        wcs = makeWCS(midRA, midDec)
        ax = WCSAxes(fig, [0.16, 0.1, 0.8, 0.8], wcs=wcs)
        fig.add_axes(ax)
    else:
        ax = plt.gca()
    if LSM.hasPatches:
        nsrc = len(LSM.getPatchNames())
    else:
        nsrc = len(LSM)
    sm = plt.cm.ScalarMappable(cmap=plt.cm.Set3, norm=plt.Normalize(vmin=0,
        vmax=nsrc))
    sm._A = []

    # Set symbol sizes by flux, making sure no symbol is smaller than 50 or
    # larger than 1000
    s = []
    fluxes = LSM.getColValues('I')
    if len(fluxes[fluxes > 0.0]) == 0:
        minflux = 0.0
    else:
        minflux = np.min(fluxes[fluxes > 0.0])
    for flux in LSM.getColValues('I'):
        if flux > 0.0:
            s.append(min(1000.0, (1.0+2.0*np.log10(flux/minflux))*50.0))
        else:
            s.append(50.0)

    # Color sources by patch if grouped
    c = [0]*len(LSM)
    cp = []
    if LSM.hasPatches:
        for p, patchName in enumerate(LSM.getPatchNames()):
            indices = LSM.getRowIndex(patchName)
            cp.append(sm.to_rgba(p))
            for ind in indices:
                c[ind] = sm.to_rgba(p)
    else:
        c = [sm.to_rgba(0)] * nsrc

    # Plot sources
    if hasWCSaxes:
        RA = LSM.getColValues('Ra')
        Dec = LSM.getColValues('Dec')
        ax.set_xlim(np.min(x)-20, np.max(x)+20)
        ax.set_ylim(np.min(y)-20, np.max(y)+20)
    plt.scatter(x, y, s=s, c=c)

    if LSM.hasPatches:
        RAp, Decp = LSM.getPatchPositions(asArray=True)
        goodInd = np.where( (RAp != 0.0) & (Decp != 0.0) )
        if len(goodInd[0]) < len(RAp):
            log.info('Some patch positions are unset. Run setPatchPositions() '
                'before plotting to see patch positions and patch names.')
        xp, yp = radec2xy(RAp[goodInd], Decp[goodInd], midRA, midDec)
        plt.scatter(xp, yp, s=100, c=cp, marker='*')

    # Set axis labels, etc.
    if hasWCSaxes:
        RAAxis = ax.coords['ra']
        RAAxis.set_axislabel('RA', minpad=0.75)
        RAAxis.set_major_formatter('hh:mm:ss')
        DecAxis = ax.coords['dec']
        DecAxis.set_axislabel('Dec', minpad=0.75)
        DecAxis.set_major_formatter('dd:mm:ss')
        ax.coords.grid(color='black', alpha=0.5, linestyle='solid')
    else:
        plt.xlabel("RA (arb. units)")
        plt.ylabel("Dec (arb. units)")

    if labelBy is not None:
        if labelBy.lower() == 'source':
            labels = LSM.getColValues('name')
            xls = x
            yls = y
        elif labelBy.lower() == 'patch':
            if LSM.hasPatches:
                labels = LSM.getPatchNames()
                xls = xp
                yls = yp
            else:
                labels = LSM.getColValues('name')
                xls = x
                yls = y
        else:
            raise ValueError("The lableBy parameter must be one of 'source' or "
                "'patch'.")
        for label, xl, yl in zip(labels, xls, yls):
            plt.annotate(label, xy = (xl, yl), xytext = (-2, 2), textcoords=
                'offset points', ha='right', va='bottom')

    # Define coodinate formater to show RA and Dec under mouse pointer
    RAformatter = FuncFormatter(RAtickformatter)
    ax.format_coord = formatCoord

    if fileName is not None:
        plt.savefig(fileName)
    else:
        plt.show()
    plt.close(fig)
Пример #41
0
    def test_curvilinear_grid_patches_image(self, generate):
        fig = plt.figure(figsize=(8, 8))
        ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], wcs=WCS(self.rosat_header), aspect='equal')
        fig.add_axes(ax)
        ax.set_xlim(-0.5, 479.5)
        ax.set_ylim(-0.5, 239.5)
        ax.grid(color='black', alpha=1.0, lw=1, linestyle='dashed')
        p = Circle((300, 100), radius=40, ec='yellow', fc='none')
        ax.add_patch(p)
        p = Circle((30., 20.), radius=20., ec='orange', fc='none', transform=ax.get_transform('world'))
        ax.add_patch(p)
        p = Circle((60., 50.), radius=20., ec='red', fc='none', transform=ax.get_transform('fk5'))
        ax.add_patch(p)
        p = Circle((40., 60.), radius=20., ec='green', fc='none', transform=ax.get_transform('galactic'))
        ax.add_patch(p)

        self.generate_or_test(generate, fig, 'curvlinear_grid_patches_image.png')
from __future__ import division

import os.path
import matplotlib.pyplot as plt

from astropy import wcs
from astropy.io.fits import getdata

from wcsaxes import WCSAxes
from demo import downsample_and_transpose_data_and_header

data_path = os.path.expanduser("~/Dropbox/College/Astro99/DATA/")

data_file = 'COGAL_local_mom.fits'

datacube, datacube_header = getdata(data_path+data_file, memmap=True,
    header=True)

datacube_dt, datacube_dt_header = \
    downsample_and_transpose_data_and_header(datacube, datacube_header, 1, (2,0,1), resample=False, recenter=True)
datacube_dt_wcs = wcs.wcs.WCS(datacube_dt_header)

datacube_dt_wcs.wcs.bounds_check(pix2world=False, world2pix=False)

fig = plt.figure(figsize=(13,3.5))
ax_image_limits = [0.1, 0.1, 0.8, 0.8]
ax_image = fig.add_axes(WCSAxes(fig, ax_image_limits, wcs=datacube_dt_wcs, slices=('x','y', 0)))

image = ax_image.imshow(datacube_dt[50, :,:], origin='lower', interpolation='nearest', cmap=plt.cm.gray)

fig.show()
Пример #43
0
    def test_contour_overlay(self, generate):
        hdu_msx = datasets.msx_hdu()
        wcs_msx = WCS(self.msx_header)

        fig = plt.figure(figsize=(6, 6))
        ax = WCSAxes(fig, [0.15, 0.15, 0.8, 0.8], wcs=WCS(self.twoMASS_k_header), aspect='equal')
        fig.add_axes(ax)
        ax.set_xlim(-0.5, 720.5)
        ax.set_ylim(-0.5, 720.5)
        # Overplot contour
        ax.contour(hdu_msx.data, transform=ax.get_transform(wcs_msx), colors='orange', levels=[2.5e-5, 5e-5, 1.e-4])
        ax.coords[0].set_ticks(size=5, width=1)
        ax.coords[1].set_ticks(size=5, width=1)
        ax.set_xlim(0., 720.)
        ax.set_ylim(0., 720.)

        self.generate_or_test(generate, fig, 'contour_overlay.png')
Пример #44
0
import matplotlib.pyplot as plt
import matplotlib.cm as cm

import pyregion
from astropy.io import fits

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

try:
    from astropy.wcs import WCS
    from wcsaxes import WCSAxes
    wcs = WCS(f_xray[0].header)
    fig = plt.figure()
    ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], wcs=wcs)
    fig.add_axes(ax)
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(f_xray[0].header)

patch_list, text_list = r.get_mpl_patches_texts()
for p in patch_list:
    ax.add_patch(p)
for t in text_list:
    ax.add_artist(t)
Пример #45
0
def plotFluxRatioSky(predFlux, measFlux, x, y, RA, Dec, midRA, midDec, labels,
    outDir, name1, name2, format):
    """
    Makes sky plot of measured-to-predicted flux ratio
    """
    import os
    import numpy as np
    from ..operations_lib import calculateSeparation, makeWCS
    try:
        from astropy.stats.funcs import sigma_clip
    except ImportError:
        from astropy.stats import sigma_clip
    try:
        import matplotlib
        if matplotlib.get_backend() is not 'Agg':
            matplotlib.use("Agg")
        import matplotlib.pyplot as plt
        import matplotlib.colors as colors
        from matplotlib.ticker import FuncFormatter
    except Exception as e:
        raise ImportError('PyPlot could not be imported. Plotting is not '
            'available: {0}'.format(e.message))
    try:
        from wcsaxes import WCSAxes
        hasWCSaxes = True
    except:
        hasWCSaxes = False

    if name1 is None:
        name1 = 'Model 1'
    if name2 is None:
        name2 = 'Model 2'

    ratio = measFlux / predFlux

    fig = plt.figure(figsize=(7.0, 5.0))
    if hasWCSaxes:
        wcs = makeWCS(midRA, midDec)
        ax1 = WCSAxes(fig, [0.12, 0.12, 0.8, 0.8], wcs=wcs)
        fig.add_axes(ax1)
    else:
        ax1 = plt.gca()
    plt.title('Flux Density Ratios ({0} / {1})'.format(name1, name2))

    # Set symbol color by ratio
    vmin = np.min(ratio) - 0.1
    vmax = np.max(ratio) + 0.1
    sm = plt.cm.ScalarMappable(cmap=plt.cm.jet,
        norm=colors.Normalize(vmin=vmin, vmax=vmax))
    sm.set_array(ratio)
    sm._A = []
    c = []
    for r in ratio:
        c.append(sm.to_rgba(r))

    if hasWCSaxes:
        ax1.set_xlim(np.min(x)-20, np.max(x)+20)
        ax1.set_ylim(np.min(y)-20, np.max(y)+20)
    plot = plt.scatter(x, y, c=c)
    cbar = plt.colorbar(sm)

    # Set axis labels, etc.
    if hasWCSaxes:
        RAAxis = ax1.coords['ra']
        DecAxis = ax1.coords['dec']
        RAAxis.set_axislabel('RA')
        DecAxis.set_axislabel('Dec')
        ax1.coords.grid(color='black', alpha=0.5, linestyle='solid')
    else:
        plt.xlabel("RA (arb. units)")
        plt.ylabel("Dec (arb. units)")

    if labels is not None:
        xls = x
        yls = y
        for label, xl, yl in zip(labels, xls, yls):
            plt.annotate(label, xy = (xl, yl), xytext = (-2, 2), textcoords=
                'offset points', ha='right', va='bottom')

    plt.savefig(outDir+'flux_ratio_sky.{}'.format(format), format=format)
Пример #46
0
def plotFluxRatioSky(predFlux, measFlux, x, y, RA, Dec, midRA, midDec, labels, outDir):
    """
    Makes sky plot of measured-to-predicted flux ratio
    """
    import os
    import numpy as np
    from ..operations_lib import calculateSeparation, makeWCS

    try:
        from astropy.stats.funcs import sigma_clip
    except ImportError:
        from astropy.stats import sigma_clip
    try:
        import matplotlib

        if matplotlib.get_backend() is not "Agg":
            matplotlib.use("Agg")
        import matplotlib.pyplot as plt
        from matplotlib.ticker import FuncFormatter
    except Exception as e:
        raise ImportError("PyPlot could not be imported. Plotting is not " "available: {0}".format(e.message))
    try:
        from wcsaxes import WCSAxes

        hasWCSaxes = True
    except:
        hasWCSaxes = False

    ratio = measFlux / predFlux

    fig = plt.figure(figsize=(7.0, 5.0))
    if hasWCSaxes:
        wcs = makeWCS(midRA, midDec)
        ax1 = WCSAxes(fig, [0.12, 0.12, 0.8, 0.8], wcs=wcs)
        fig.add_axes(ax1)
    else:
        ax1 = plt.gca()
    plt.title("Flux Ratios (Model 1 / Model 2)")

    # Set symbol color by ratio
    vmin = np.min(ratio) - 0.1
    vmax = np.max(ratio) + 0.1
    sm = plt.cm.ScalarMappable(cmap=plt.cm.jet, norm=plt.normalize(vmin=vmin, vmax=vmax))
    sm.set_array(ratio)
    sm._A = []
    c = []
    for r in ratio:
        c.append(sm.to_rgba(r))

    if hasWCSaxes:
        ax1.set_xlim(np.min(x) - 20, np.max(x) + 20)
        ax1.set_ylim(np.min(y) - 20, np.max(y) + 20)
    plot = plt.scatter(x, y, c=c)
    cbar = plt.colorbar(sm)

    # Set axis labels, etc.
    if hasWCSaxes:
        RAAxis = ax1.coords["ra"]
        DecAxis = ax1.coords["dec"]
        RAAxis.set_axislabel("RA")
        DecAxis.set_axislabel("Dec")
        ax1.coords.grid(color="black", alpha=0.5, linestyle="solid")
    else:
        plt.xlabel("RA (arb. units)")
        plt.ylabel("Dec (arb. units)")

    if labels is not None:
        xls = x
        yls = y
        for label, xl, yl in zip(labels, xls, yls):
            plt.annotate(label, xy=(xl, yl), xytext=(-2, 2), textcoords="offset points", ha="right", va="bottom")

    plt.savefig(outDir + "flux_ratio_sky.pdf", format="pdf")
    def __init__(self,
                 dendrogram,
                 hub,
                 alignment='latitude',
                 cmap=plt.cm.gray,
                 clip_velocity=None):

        if dendrogram.data.ndim != 3:
            raise ValueError("Only 3-dimensional arrays are supported")

        if not hasattr(hub, 'select_subtree'):
            raise NotImplementedError(
                "astrodendro does not have scatter_picker enabled")

        self.hub = hub

        self.datacube = dendrogram.data
        self.dendrogram = dendrogram
        self.wcs = dendrogram.wcs

        self.plotter = DendrogramPlotter(dendrogram)
        self.plotter.sort(reverse=True)

        # Get the lines as individual elements, and the mapping from line to structure
        self.lines = self.plotter.get_lines(edgecolor='k')

        self.selected_lines = {}
        self.selected_contours = {}  # selection_id -> (contour, contour) tuple

        if alignment == 'latitude':
            figsize = (15, 9)
            ax_integrated_limits = [0.025, 0.05, 0.6, 0.5]
            ax_cartoon_limits = [0.025, 0.55, 0.6, 0.5]

            slices = ('x', 'y', 0)
            self.sum_axis = 0
            self.overlay_cartoon = overlay_lb_cartoon
            self.aspect = 1
        elif alignment == 'velocity':
            figsize = (15, 9)
            ax_integrated_limits = [0.025, 0.05, 0.6, 0.5]
            ax_cartoon_limits = [0.025, 0.55, 0.6, 0.5]

            slices = ('x', 0, 'y')
            self.sum_axis = 1
            self.overlay_cartoon = overlay_lv_cartoon
            self.aspect = 2.5
        # elif alignment == 'pp' or alignment == 'lb':
        #     figsize = (10, 4)
        #     ax_integrated_limits = [0.1, 0.1, 0.8, 0.8]
        #     ax_cartoon_limits = [0,0,0.01,0.01]
        else:
            raise ValueError("`alignment` must be 'latitude' or 'velocity'")

        self.alignment = alignment

        self.fig = plt.figure(figsize=figsize)
        self.cmap = cmap

        if self.dendrogram.wcs is not None:
            ax_integrated = WCSAxes(self.fig,
                                    ax_integrated_limits,
                                    wcs=self.dendrogram.wcs,
                                    slices=slices)
            self.ax_integrated = self.fig.add_axes(ax_integrated)

            ax_cartoon = WCSAxes(self.fig,
                                 ax_cartoon_limits,
                                 wcs=self.dendrogram.wcs,
                                 slices=slices,
                                 sharex=ax_integrated,
                                 sharey=ax_integrated)
            self.ax_cartoon = self.fig.add_axes(ax_cartoon)
        else:
            self.ax_integrated = self.fig.add_axes(ax_integrated_limits)
            self.ax_cartoon = self.fig.add_axes(ax_cartoon_limits,
                                                sharex=ax_integrated,
                                                sharey=ax_integrated)

        array_summed = np.nansum(self.datacube, axis=self.sum_axis)
        array_summed[(array_summed < 0) | np.isinf(array_summed)
                     | np.isnan(array_summed)] = 0
        self.array_summed = array_summed

        # all stolen from astrodendro.viewer
        self.ax_dendrogram = self.fig.add_axes([0.65, 0.1, 0.35, 0.6])
        self.ax_dendrogram.add_collection(self.lines)

        self.selected_label = {}  # map selection IDs -> text objects
        self.selected_label[1] = self.fig.text(0.75,
                                               0.9,
                                               "No structure selected",
                                               fontsize=18,
                                               color=self.hub.colors[1])
        self.selected_label[2] = self.fig.text(0.75,
                                               0.85,
                                               "No structure selected",
                                               fontsize=18,
                                               color=self.hub.colors[2])
        self.selected_label[3] = self.fig.text(0.75,
                                               0.8,
                                               "No structure selected",
                                               fontsize=18,
                                               color=self.hub.colors[3])
        x = [p.vertices[:, 0] for p in self.lines.get_paths()]
        y = [p.vertices[:, 1] for p in self.lines.get_paths()]
        xmin = np.min(x)
        xmax = np.max(x)
        ymin = np.min(y)
        ymax = np.max(y)
        self.lines.set_picker(2.)
        self.lines.set_zorder(0)
        dx = xmax - xmin
        self.ax_dendrogram.set_xlim(xmin - dx * 0.1, xmax + dx * 0.1)
        self.ax_dendrogram.set_ylim(ymin * 0.5, ymax * 2.0)
        self.ax_dendrogram.set_yscale('log')

        self.fig.canvas.mpl_connect('pick_event', self.line_picker)

        # array_lv = np.nansum(self.datacube, axis=1)
        # array_lv[(array_lv < 0) | np.isinf(array_lv) | np.isnan(array_lv)] = 0
        # self.array_lv = array_lv

        # if clip_velocity is None:
        #     if np.shape(array_lv)[0]*2.5 > np.shape(array_lb)[0]:
        #         self.clip_velocity = True
        #     else:
        #         self.clip_velocity = False
        # else:
        #     self.clip_velocity = clip_velocity

        self._draw_plot()
        self.hub.add_callback(self.update_selection)
        self.hub.add_callback(self._update_lines)
        self.fig.canvas.mpl_connect('button_press_event', self.select_from_map)

        # If things are already selected in the hub, go select them!
        for selection_id in self.hub.selections:
            self.update_selection(selection_id)
Пример #48
0
    def __init__(self, dendrogram):

        if dendrogram.data.ndim not in [2, 3]:
            raise ValueError(
                "Only 2- and 3-dimensional arrays are supported at this time")

        self.hub = SelectionHub()
        self._connect_to_hub()

        self.array = dendrogram.data
        self.dendrogram = dendrogram
        self.plotter = DendrogramPlotter(dendrogram)
        self.plotter.sort(reverse=True)

        # Get the lines as individual elements, and the mapping from line to structure
        self.lines = self.plotter.get_lines(edgecolor='k')

        # Define the currently selected subtree
        self.selected_lines = {}
        self.selected_contour = {}
        # The keys in these dictionaries are event button IDs.

        # Initiate plot
        import matplotlib.pyplot as plt
        self.fig = plt.figure(figsize=(14, 8))

        ax_image_limits = [0.1, 0.1, 0.4, 0.7]

        try:
            from wcsaxes import WCSAxes
            __wcaxes_imported = True
        except ImportError:
            __wcaxes_imported = False
            if self.dendrogram.wcs is not None:
                warnings.warn(
                    "`WCSAxes` package required for wcs coordinate display.")

        if self.dendrogram.wcs is not None and __wcaxes_imported:

            if self.array.ndim == 2:
                slices = ('x', 'y')
            else:
                slices = ('x', 'y', 1)

            ax_image = WCSAxes(self.fig,
                               ax_image_limits,
                               wcs=self.dendrogram.wcs,
                               slices=slices)
            self.ax_image = self.fig.add_axes(ax_image)

        else:
            self.ax_image = self.fig.add_axes(ax_image_limits)

        from matplotlib.widgets import Slider

        self._clim = (np.min(self.array[~np.isnan(self.array)
                                        & ~np.isinf(self.array)]),
                      np.max(self.array[~np.isnan(self.array)
                                        & ~np.isinf(self.array)]))

        if self.array.ndim == 2:

            self.slice = None
            self.image = self.ax_image.imshow(self.array,
                                              origin='lower',
                                              interpolation='nearest',
                                              vmin=self._clim[0],
                                              vmax=self._clim[1],
                                              cmap=plt.cm.gray)

            self.slice_slider = None

        else:

            if self.array.shape[0] > 1:

                self.slice = int(round(self.array.shape[0] / 2.))

                self.slice_slider_ax = self.fig.add_axes(
                    [0.1, 0.95, 0.4, 0.03])
                self.slice_slider_ax.set_xticklabels("")
                self.slice_slider_ax.set_yticklabels("")
                self.slice_slider = Slider(self.slice_slider_ax,
                                           "3-d slice",
                                           0,
                                           self.array.shape[0],
                                           valinit=self.slice,
                                           valfmt="%i")
                self.slice_slider.on_changed(self.update_slice)
                self.slice_slider.drawon = False

            else:

                self.slice = 0
                self.slice_slider = None

            self.image = self.ax_image.imshow(self.array[self.slice, :, :],
                                              origin='lower',
                                              interpolation='nearest',
                                              vmin=self._clim[0],
                                              vmax=self._clim[1],
                                              cmap=plt.cm.gray)

        self.vmin_slider_ax = self.fig.add_axes([0.1, 0.90, 0.4, 0.03])
        self.vmin_slider_ax.set_xticklabels("")
        self.vmin_slider_ax.set_yticklabels("")
        self.vmin_slider = Slider(self.vmin_slider_ax,
                                  "vmin",
                                  self._clim[0],
                                  self._clim[1],
                                  valinit=self._clim[0])
        self.vmin_slider.on_changed(self.update_vmin)
        self.vmin_slider.drawon = False

        self.vmax_slider_ax = self.fig.add_axes([0.1, 0.85, 0.4, 0.03])
        self.vmax_slider_ax.set_xticklabels("")
        self.vmax_slider_ax.set_yticklabels("")
        self.vmax_slider = Slider(self.vmax_slider_ax,
                                  "vmax",
                                  self._clim[0],
                                  self._clim[1],
                                  valinit=self._clim[1])
        self.vmax_slider.on_changed(self.update_vmax)
        self.vmax_slider.drawon = False

        self.ax_dendrogram = self.fig.add_axes([0.6, 0.3, 0.35, 0.4])
        self.ax_dendrogram.add_collection(self.lines)

        self.selected_label = {}  # map selection IDs -> text objects
        self.selected_label[1] = self.fig.text(0.6,
                                               0.85,
                                               "No structure selected",
                                               fontsize=18,
                                               color=self.hub.colors[1])
        self.selected_label[2] = self.fig.text(0.6,
                                               0.8,
                                               "No structure selected",
                                               fontsize=18,
                                               color=self.hub.colors[2])
        self.selected_label[3] = self.fig.text(0.6,
                                               0.75,
                                               "No structure selected",
                                               fontsize=18,
                                               color=self.hub.colors[3])
        x = [p.vertices[:, 0] for p in self.lines.get_paths()]
        y = [p.vertices[:, 1] for p in self.lines.get_paths()]
        xmin = np.min(x)
        xmax = np.max(x)
        ymin = np.min(y)
        ymax = np.max(y)
        self.lines.set_picker(2.)
        self.lines.set_zorder(0)
        dx = xmax - xmin
        self.ax_dendrogram.set_xlim(xmin - dx * 0.1, xmax + dx * 0.1)
        self.ax_dendrogram.set_ylim(ymin * 0.5, ymax * 2.0)
        self.ax_dendrogram.set_yscale('log')

        self.fig.canvas.mpl_connect('pick_event', self.line_picker)
        self.fig.canvas.mpl_connect('button_press_event', self.select_from_map)
Пример #49
0
def plot_state(directions_list, trim_names=True):
    """
    Plots the facets of a run
    """
    global midRA, midDec, fig, at, selected_direction
    selected_direction = None

    # Set up coordinate system and figure
    points, midRA, midDec = factor.directions.getxy(directions_list)
    fig = plt.figure(1, figsize=(10,9))
    if hasWCSaxes:
        wcs = factor.directions.makeWCS(midRA, midDec)
        ax = WCSAxes(fig, [0.16, 0.1, 0.8, 0.8], wcs=wcs)
        fig.add_axes(ax)
    else:
        ax = plt.gca()

    field_x = min(points[0])
    field_y = max(points[1])
    adjust_xy = True
    while adjust_xy:
        adjust_xy = False
        for xy in points:
            dist = np.sqrt( (xy[0] - field_x)**2 + (xy[1] - field_y)**2 )
            if dist < 10.0:
                field_x -= 1
                field_y += 1
                adjust_xy = True
                break
    field_ra, field_dec = factor.directions.xy2radec([field_x], [field_y],
        refRA=midRA, refDec=midDec)
    field = Direction('field', field_ra[0], field_dec[0],
        factor_working_dir=directions_list[0].working_dir)
    directions_list.append(field)

    ax.set_title('Overview of FACTOR run in\n{}'.format(directions_list[0].working_dir))

    # Plot facets
    markers = []
    for direction in directions_list:
        if direction.name != 'field':
            vertices = read_vertices(direction.vertices_file)
            RAverts = vertices[0]
            Decverts = vertices[1]
            xverts, yverts = factor.directions.radec2xy(RAverts, Decverts,
                refRA=midRA, refDec=midDec)
            xyverts = [np.array([xp, yp]) for xp, yp in zip(xverts, yverts)]
            mpl_poly = Polygon(np.array(xyverts), edgecolor='#a9a9a9', facecolor='#F2F2F2',
                clip_box=ax.bbox, picker=3.0, linewidth=2)
        else:
            xverts = [field_x]
            yverts = [field_y]
            mpl_poly = Circle((field_x, field_y), radius=5.0, edgecolor='#a9a9a9', facecolor='#F2F2F2',
                clip_box=ax.bbox, picker=3.0, linewidth=2)
        mpl_poly.facet_name = direction.name
        mpl_poly.completed_ops = get_completed_ops(direction)
        mpl_poly.started_ops = get_started_ops(direction)
        mpl_poly.current_op = get_current_op(direction)
        set_patch_color(mpl_poly, direction)
        ax.add_patch(mpl_poly)

        # Add facet names
        if direction.name != 'field':
            poly_tuple = tuple([(xp, yp) for xp, yp in zip(xverts, yverts)])
            xmid = SPolygon(poly_tuple).centroid.x
            ymid = SPolygon(poly_tuple).centroid.y
        else:
            xmid = field_x
            ymid = field_y
        if trim_names:
            name = direction.name.split('_')[-1]
        else:
            name = direction.name
        marker = ax.text(xmid, ymid, name, color='k', clip_on=True,
            clip_box=ax.bbox, ha='center', va='bottom')
        marker.set_zorder(1001)
        markers.append(marker)

    # Add info box
    at = AnchoredText("Selected direction: None", prop=dict(size=12), frameon=True,
        loc=3)
    at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2")
    at.set_zorder(1002)
    ax.add_artist(at)

    ax.relim()
    ax.autoscale()
    ax.set_aspect('equal')

    if hasWCSaxes:
        RAAxis = ax.coords['ra']
        RAAxis.set_axislabel('RA', minpad=0.75)
        RAAxis.set_major_formatter('hh:mm:ss')
        DecAxis = ax.coords['dec']
        DecAxis.set_axislabel('Dec', minpad=0.75)
        DecAxis.set_major_formatter('dd:mm:ss')
        ax.coords.grid(color='black', alpha=0.5, linestyle='solid')
    else:
        plt.xlabel("RA (arb. units)")
        plt.ylabel("Dec (arb. units)")

    # Define coodinate formater to show RA and Dec under mouse pointer
    ax.format_coord = formatCoord

    # Show legend
    not_processed_patch = plt.Rectangle((0, 0), 1, 1, edgecolor='#a9a9a9',
        facecolor='#F2F2F2', linewidth=2)
    processing_patch = plt.Rectangle((0, 0), 1, 1, edgecolor='#a9a9a9',
        facecolor='#F2F5A9', linewidth=2)
    selfcal_ok_patch = plt.Rectangle((0, 0), 1, 1, edgecolor='#a9a9a9',
        facecolor='#A9F5A9', linewidth=2)
    selfcal_not_ok_patch =plt.Rectangle((0, 0), 1, 1, edgecolor='#a9a9a9',
        facecolor='#F5A9A9', linewidth=2)
    l = ax.legend([not_processed_patch, processing_patch, selfcal_ok_patch, selfcal_not_ok_patch],
              ['Unprocessed', 'Processing', 'Completed', 'Failed'])
    l.set_zorder(1002)

    # Add check for mouse clicks and key presses
    fig.canvas.mpl_connect('pick_event', on_pick)
    fig.canvas.mpl_connect('key_press_event', on_press)

    # Add timer to update the plot every 60 seconds
    timer = fig.canvas.new_timer(interval=60000)
    timer.add_callback(update_plot)
    timer.start()

    # Show plot
    plt.show()
    plt.close(fig)

    # Clean up any temp pyrap images
    if not hasaplpy:
        if os.path.exists('/tmp/tempimage'):
            try:
                shutil.rmtree('/tmp/tempimage')
            except OSError:
                pass
Пример #50
0
    def test_contour_overlay(self, generate):
        hdu_msx = datasets.msx_hdu()
        wcs_msx = WCS(self.msx_header)

        fig = plt.figure(figsize=(6, 6))
        ax = WCSAxes(fig, [0.15, 0.15, 0.8, 0.8], wcs=WCS(self.twoMASS_k_header), aspect='equal')
        fig.add_axes(ax)
        ax.set_xlim(-0.5, 720.5)
        ax.set_ylim(-0.5, 720.5)
        # Overplot contour
        ax.contour(hdu_msx.data, transform=ax.get_transform(wcs_msx), colors='orange', levels=[2.5e-5, 5e-5, 1.e-4])
        ax.coords[0].set_ticks(size=5, width=1)
        ax.coords[1].set_ticks(size=5, width=1)
        ax.set_xlim(0., 720.)
        ax.set_ylim(0., 720.)

        self.generate_or_test(generate, fig, 'contour_overlay.png')
Пример #51
0
def plot_state(directions_list, trim_names=True):
    """
    Plots the facets of a run
    """
    global midRA, midDec, fig, at, selected_direction
    selected_direction = None

    # Set up coordinate system and figure
    points, midRA, midDec = factor.directions.getxy(directions_list)
    fig = plt.figure(1, figsize=(10, 9))
    if hasWCSaxes:
        wcs = factor.directions.makeWCS(midRA, midDec)
        ax = WCSAxes(fig, [0.16, 0.1, 0.8, 0.8], wcs=wcs)
        fig.add_axes(ax)
    else:
        ax = plt.gca()

    field_x = min(points[0])
    field_y = max(points[1])
    adjust_xy = True
    while adjust_xy:
        adjust_xy = False
        for xy in points:
            dist = np.sqrt((xy[0] - field_x)**2 + (xy[1] - field_y)**2)
            if dist < 10.0:
                field_x -= 1
                field_y += 1
                adjust_xy = True
                break
    field_ra, field_dec = factor.directions.xy2radec([field_x], [field_y],
                                                     refRA=midRA,
                                                     refDec=midDec)
    field = Direction('field',
                      field_ra[0],
                      field_dec[0],
                      factor_working_dir=directions_list[0].working_dir)
    directions_list.append(field)

    ax.set_title('Overview of FACTOR run in\n{}'.format(
        directions_list[0].working_dir))

    # Plot facets
    markers = []
    for direction in directions_list:
        if direction.name != 'field':
            vertices = read_vertices(direction.vertices_file)
            RAverts = vertices[0]
            Decverts = vertices[1]
            xverts, yverts = factor.directions.radec2xy(RAverts,
                                                        Decverts,
                                                        refRA=midRA,
                                                        refDec=midDec)
            xyverts = [np.array([xp, yp]) for xp, yp in zip(xverts, yverts)]
            mpl_poly = Polygon(np.array(xyverts),
                               edgecolor='#a9a9a9',
                               facecolor='#F2F2F2',
                               clip_box=ax.bbox,
                               picker=3.0,
                               linewidth=2)
        else:
            xverts = [field_x]
            yverts = [field_y]
            mpl_poly = Circle((field_x, field_y),
                              radius=5.0,
                              edgecolor='#a9a9a9',
                              facecolor='#F2F2F2',
                              clip_box=ax.bbox,
                              picker=3.0,
                              linewidth=2)
        mpl_poly.facet_name = direction.name
        mpl_poly.completed_ops = get_completed_ops(direction)
        mpl_poly.started_ops = get_started_ops(direction)
        mpl_poly.current_op = get_current_op(direction)
        set_patch_color(mpl_poly, direction)
        ax.add_patch(mpl_poly)

        # Add facet names
        if direction.name != 'field':
            poly_tuple = tuple([(xp, yp) for xp, yp in zip(xverts, yverts)])
            xmid = SPolygon(poly_tuple).centroid.x
            ymid = SPolygon(poly_tuple).centroid.y
        else:
            xmid = field_x
            ymid = field_y
        if trim_names:
            name = direction.name.split('_')[-1]
        else:
            name = direction.name
        marker = ax.text(xmid,
                         ymid,
                         name,
                         color='k',
                         clip_on=True,
                         clip_box=ax.bbox,
                         ha='center',
                         va='bottom')
        marker.set_zorder(1001)
        markers.append(marker)

    # Add info box
    at = AnchoredText("Selected direction: None",
                      prop=dict(size=12),
                      frameon=True,
                      loc=3)
    at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2")
    at.set_zorder(1002)
    ax.add_artist(at)

    ax.relim()
    ax.autoscale()
    ax.set_aspect('equal')

    if hasWCSaxes:
        RAAxis = ax.coords['ra']
        RAAxis.set_axislabel('RA', minpad=0.75)
        RAAxis.set_major_formatter('hh:mm:ss')
        DecAxis = ax.coords['dec']
        DecAxis.set_axislabel('Dec', minpad=0.75)
        DecAxis.set_major_formatter('dd:mm:ss')
        ax.coords.grid(color='black', alpha=0.5, linestyle='solid')
    else:
        plt.xlabel("RA (arb. units)")
        plt.ylabel("Dec (arb. units)")

    # Define coodinate formater to show RA and Dec under mouse pointer
    ax.format_coord = formatCoord

    # Show legend
    not_processed_patch = plt.Rectangle((0, 0),
                                        1,
                                        1,
                                        edgecolor='#a9a9a9',
                                        facecolor='#F2F2F2',
                                        linewidth=2)
    processing_patch = plt.Rectangle((0, 0),
                                     1,
                                     1,
                                     edgecolor='#a9a9a9',
                                     facecolor='#F2F5A9',
                                     linewidth=2)
    selfcal_ok_patch = plt.Rectangle((0, 0),
                                     1,
                                     1,
                                     edgecolor='#a9a9a9',
                                     facecolor='#A9F5A9',
                                     linewidth=2)
    selfcal_not_ok_patch = plt.Rectangle((0, 0),
                                         1,
                                         1,
                                         edgecolor='#a9a9a9',
                                         facecolor='#F5A9A9',
                                         linewidth=2)
    l = ax.legend([
        not_processed_patch, processing_patch, selfcal_ok_patch,
        selfcal_not_ok_patch
    ], ['Unprocessed', 'Processing', 'Completed', 'Failed'])
    l.set_zorder(1002)

    # Add check for mouse clicks and key presses
    fig.canvas.mpl_connect('pick_event', on_pick)
    fig.canvas.mpl_connect('key_press_event', on_press)

    # Add timer to update the plot every 60 seconds
    timer = fig.canvas.new_timer(interval=60000)
    timer.add_callback(update_plot)
    timer.start()

    # Show plot
    plt.show()
    plt.close(fig)

    # Clean up any temp pyrap images
    if os.path.exists('/tmp/tempimage'):
        shutil.rmtree('/tmp/tempimage')
Пример #52
0
    def __init__(self, dendrogram, hub, alignment='horizontal', cmap=plt.cm.gray,
                 clip_velocity=None, aspect=2.5, linewidths=0.9, figsize=None):

        if dendrogram.data.ndim != 3:
            raise ValueError(
                "Only 3-dimensional arrays are supported")

        if not hasattr(hub, 'select_subtree'):
            raise NotImplementedError("astrodendro does not have scatter_picker enabled")

        self.hub = hub

        self.datacube = dendrogram.data
        self.dendrogram = dendrogram

        self.selected_contours = {} # selection_id -> (contour, contour) tuple

        if alignment == 'horizontal':
            figsize = figsize or (10, 4.4)
            ax_lb_limits = [0.1, 0.05, 0.8, 0.4]
            ax_lv_limits = [0.1, 0.5, 0.8, 0.5]
        elif alignment == 'vertical':
            figsize = figsize or (8, 6)
            ax_lb_limits = [0.1, 0.1, 0.375, 0.8]
            ax_lv_limits = [0.55, 0.1, 0.375, 0.8]
        elif alignment == 'pp' or alignment == 'lb':
            figsize = figsize or (10, 4)
            ax_lb_limits = [0.1, 0.1, 0.8, 0.8]
            ax_lv_limits = [0,0,0.01,0.01]
        elif alignment == 'pv' or alignment == 'lv':
            figsize = figsize or (10, 4)
            ax_lb_limits = [0.5, 0.5, 0.01, 0.01]
            ax_lv_limits = [0.1, 0.1, 0.8, 0.8]
        else:
            raise ValueError("`alignment` must be 'horizontal' or 'vertical'")

        self.fig = plt.figure(figsize=figsize)
        self.cmap = cmap

        if self.dendrogram.wcs is not None:
            ax_lb = WCSAxes(self.fig, ax_lb_limits, wcs=self.dendrogram.wcs, slices=('x', 'y', 0))
            self.ax_lb = self.fig.add_axes(ax_lb)

            ax_lv = WCSAxes(self.fig, ax_lv_limits, wcs=self.dendrogram.wcs, slices=('x', 0, 'y'))
            self.ax_lv = self.fig.add_axes(ax_lv)
        else:
            self.ax_lb = self.fig.add_axes(ax_lb_limits)
            self.ax_lv = self.fig.add_axes(ax_lv_limits)

        array_lb = np.nansum(self.datacube, axis=0)
        array_lb[(array_lb < 0) | np.isinf(array_lb) | np.isnan(array_lb)] = 0
        self.array_lb = array_lb

        array_lv = np.nansum(self.datacube, axis=1)
        array_lv[(array_lv < 0) | np.isinf(array_lv) | np.isnan(array_lv)] = 0
        self.array_lv = array_lv

        if clip_velocity is None:
            if np.shape(array_lv)[0]*2.5 > np.shape(array_lb)[0]:
                self.clip_velocity = True
            else:
                self.clip_velocity = False
        else:
            self.clip_velocity = clip_velocity

        self.aspect = aspect
        self.linewidths = linewidths

        self._draw_plot()
        self.hub.add_callback(self.update_selection)
        self.fig.canvas.mpl_connect('button_press_event', self.select_from_map)

        # If things are already selected in the hub, go select them!
        for selection_id in self.hub.selections:
            self.update_selection(selection_id)
Пример #53
0
from wcsaxes import WCSAxes

import pyregion

region_list = ["test_text.reg", "test_context.reg"]

# Create figure
fig = plt.figure(figsize=(8, 4))

# Parse WCS information
header = Header.fromtextfile('sample_fits01.header')
wcs = WCS(header)

# Create axes
ax1 = WCSAxes(fig, [0.1, 0.1, 0.4, 0.8], wcs=wcs)
fig.add_axes(ax1)
ax2 = WCSAxes(fig, [0.5, 0.1, 0.4, 0.8], wcs=wcs)
fig.add_axes(ax2)

# Hide labels on y axis
ax2.coords[1].set_ticklabel_position('')

for ax, reg_name in zip([ax1, ax2], region_list):

    ax.set_xlim(300, 1300)
    ax.set_ylim(300, 1300)
    ax.set_aspect(1)

    r = pyregion.open(reg_name).as_imagecoord(header)
Пример #54
0
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from astropy.io import fits
import pyregion

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

try:
    from astropy.wcs import WCS
    from wcsaxes import WCSAxes

    wcs = WCS(f_xray[0].header)
    fig = plt.figure()
    ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], wcs=wcs)
    fig.add_axes(ax)
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
import pyfits
import numpy as np

cluster_name = "blanckimage.fits"
image        = fits.open(cluster_name)

#cluster_name = sys.argv[1]
#output_image = sys.argv[2]

try:
    from astropy.wcs import WCS
    from wcsaxes import WCSAxes

    wcs = WCS(image[0].header)
    fig = plt.figure()
    ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], wcs=wcs)
    fig.add_axes(ax)
except ImportError:
    ax = plt.subplot(111)

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

reg_name  = "A2029fullregions.reg"
r         = pyregion.open(reg_name).as_imagecoord(header=image[0].header)
from pyregion.mpl_helper import properties_func_default

def fixed_color(shape, saved_attrs):
    attr_list, attr_dict  = saved_attrs
    attr_dict["color"]    = "red"
    kwargs                = properties_func_default(shape, (attr_list, attr_dict))
Пример #56
0
def plotFluxRatioSky(predFlux, measFlux, x, y, RA, Dec, midRA, midDec, labels,
                     outDir, name1, name2, format):
    """
    Makes sky plot of measured-to-predicted flux ratio
    """
    import os
    import numpy as np
    from ..operations_lib import calculateSeparation, makeWCS
    try:
        from astropy.stats.funcs import sigma_clip
    except ImportError:
        from astropy.stats import sigma_clip
    try:
        import matplotlib
        if matplotlib.get_backend() is not 'Agg':
            matplotlib.use("Agg")
        import matplotlib.pyplot as plt
        import matplotlib.colors as colors
        from matplotlib.ticker import FuncFormatter
    except Exception as e:
        raise ImportError('PyPlot could not be imported. Plotting is not '
                          'available: {0}'.format(e.message))
    try:
        from wcsaxes import WCSAxes
        hasWCSaxes = True
    except:
        hasWCSaxes = False

    if name1 is None:
        name1 = 'Model 1'
    if name2 is None:
        name2 = 'Model 2'

    ratio = measFlux / predFlux

    fig = plt.figure(figsize=(7.0, 5.0))
    if hasWCSaxes:
        wcs = makeWCS(midRA, midDec)
        ax1 = WCSAxes(fig, [0.12, 0.12, 0.8, 0.8], wcs=wcs)
        fig.add_axes(ax1)
    else:
        ax1 = plt.gca()
    plt.title('Flux Density Ratios ({0} / {1})'.format(name1, name2))

    # Set symbol color by ratio
    vmin = np.min(ratio) - 0.1
    vmax = np.max(ratio) + 0.1
    sm = plt.cm.ScalarMappable(cmap=plt.cm.jet,
                               norm=colors.Normalize(vmin=vmin, vmax=vmax))
    sm.set_array(ratio)
    sm._A = []
    c = []
    for r in ratio:
        c.append(sm.to_rgba(r))

    if hasWCSaxes:
        ax1.set_xlim(np.min(x) - 20, np.max(x) + 20)
        ax1.set_ylim(np.min(y) - 20, np.max(y) + 20)
    plot = plt.scatter(x, y, c=c)
    cbar = plt.colorbar(sm)

    # Set axis labels, etc.
    if hasWCSaxes:
        RAAxis = ax1.coords['ra']
        DecAxis = ax1.coords['dec']
        RAAxis.set_axislabel('RA')
        DecAxis.set_axislabel('Dec')
        ax1.coords.grid(color='black', alpha=0.5, linestyle='solid')
    else:
        plt.xlabel("RA (arb. units)")
        plt.ylabel("Dec (arb. units)")

    if labels is not None:
        xls = x
        yls = y
        for label, xl, yl in zip(labels, xls, yls):
            plt.annotate(label,
                         xy=(xl, yl),
                         xytext=(-2, 2),
                         textcoords='offset points',
                         ha='right',
                         va='bottom')

    plt.savefig(outDir + 'flux_ratio_sky.{}'.format(format), format=format)
Пример #57
0
    def test_cube_slice_image(self, generate):
        w = WCS(self.cube_header)
        fig = plt.figure()
        ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], w, slices=(50, 'y', 'x'), aspect='equal')
        fig.add_axes(ax)
        ax.grid(grid_type='contours')
        ax.set_xlim(-0.5, 52.5)
        ax.set_ylim(-0.5, 106.5)
        ax.coords[2].set_axislabel('Velocity m/s')
        ax.coords[1].set_ticks(width=1, exclude_overlapping=True)
        ax.coords[2].set_ticks(width=1, exclude_overlapping=True)
        ax.grid(grid_type='contours', color='red')
        ax.grid(grid_type='contours', linestyle='solid')

        self.generate_or_test(generate, fig, 'cube_slice_image.png')