def bsens_cleanest_diff(finaliter_prefix_b3, finaliter_prefix_b6,
                        cutoutregion, fignum=1,
                        finaliter_prefix_b3_bsens=None,
                        finaliter_prefix_b6_bsens=None,
                        normpars_b3=None,
                        normpars_b6=None,
                        basepath='/home/adam/work/alma-imf/reduction/', ):
    image_b3 = SpectralCube.read(f'{finaliter_prefix_b3}.image.tt0', format='casa_image').subcube_from_ds9region(cutoutregion)
    if finaliter_prefix_b3_bsens is None:
        finaliter_prefix_b3_bsens = finaliter_prefix_b3.replace("cleanest","bsens").replace("merged_12M","merged_bsens_12M")
    bsens_b3 = SpectralCube.read(f'{finaliter_prefix_b3_bsens}.image.tt0', format='casa_image').subcube_from_ds9region(cutoutregion)
    image_b6 = SpectralCube.read(f'{finaliter_prefix_b6}.image.tt0', format='casa_image').subcube_from_ds9region(cutoutregion)
    if finaliter_prefix_b6_bsens is None:
        finaliter_prefix_b6_bsens = finaliter_prefix_b6.replace("cleanest","bsens").replace("merged_12M","merged_bsens_12M")
    bsens_b6 = SpectralCube.read(f'{finaliter_prefix_b6_bsens}.image.tt0', format='casa_image').subcube_from_ds9region(cutoutregion)

    # image_b3 = image_b3 * u.beam / image_b3.beam.sr
    # image_b6 = image_b6 * u.beam / image_b6.beam.sr
    # bsens_b3 = bsens_b3 * u.beam / bsens_b3.beam.sr
    # bsens_b6 = bsens_b6 * u.beam / bsens_b6.beam.sr

    fieldname = os.path.basename(finaliter_prefix_b6).split("_")[0]
    print(fieldname)

    diff_b3 = bsens_b3 - image_b3
    diff_b6 = bsens_b6 - image_b6

    normpars_b3_default = dict(min_percent=0.1, max_percent=99.9, stretch='linear')
    normpars_b6_default = dict(min_percent=0.1, max_percent=99.9, stretch='linear')

    if normpars_b3 is not None:
        normpars_b3_default.update(normpars_b3)
    normpars_b3 = normpars_b3_default

    if normpars_b6 is not None:
        normpars_b6_default.update(normpars_b6)
    normpars_b6 = normpars_b6_default


    fig = pl.figure(num=fignum, figsize=(6,6))
    fig.clf()
    ax = pl.subplot(1,1,1,label='B3', projection=diff_b3[0].wcs)
    ax.imshow(diff_b3[0].value, norm=simple_norm(diff_b3[0].value, **normpars_b3), cmap='gray')
    ax.set_xlabel('Right Ascension')
    ax.set_ylabel('Declination')

    fig2 = pl.figure(num=fignum+1, figsize=(6,6))
    ax2 = pl.subplot(1,1,1,label='B6', projection=diff_b6[0].wcs)
    ax2.imshow(diff_b6[0].value, norm=simple_norm(diff_b6[0].value, **normpars_b6), cmap='gray')
    ax2.set_xlabel('Right Ascension')
    ax2.set_ylabel('Declination')

    # ax2.set_yticklabels([])
    # ax2.set_ylabel("")
    # lat = ax2.coords['dec']
    # lat.set_ticklabel_position('r')
    # lat.set_axislabel_position('r')
    # lat.set_axislabel('Declination')

    return fig,fig2
Exemple #2
0
def plot_model(image,model_morph):  
  ny, nx = image.shape
  imy, imx = np.mgrid[0:ny, 0:nx]


  sersic_model = models.Sersic2D(
    amplitude=model_morph.sersic_amplitude,
    r_eff=model_morph.sersic_rhalf,
    n=model_morph.sersic_n,
    x_0=model_morph.sersic_xc,
    y_0=model_morph.sersic_yc,
    ellip=model_morph.sersic_ellip,
    theta=model_morph.sersic_theta)
    
  fitted_model = sersic_model(imx, imy)
  plt.subplot(121)
  plt.imshow(image, cmap='rainbow', origin='lower',
           norm=simple_norm(image, stretch='log', log_a=10000))
  plt.subplot(122)
  plt.imshow(fitted_model, cmap='rainbow', origin='lower',
           norm=simple_norm(image, stretch='log', log_a=10000))
  plt.show()

  plt.imshow(image-fitted_model, cmap='rainbow', origin='lower')
  plt.colorbar()
  plt.show()
  plt.hist((image-fitted_model).flatten(),bins=25)
  plt.show()
Exemple #3
0
def plot_psf_fit(image, residual_image):
    plt.subplot(1, 2, 1)
    norm = simple_norm(image, 'log', percent=99.)
    plt.imshow(image, norm=norm, origin='lower', cmap='viridis')
#    plt.imshow(image, cmap='viridis', aspect=1, interpolation='nearest',origin='lower')
    plt.title('Data')
    plt.colorbar(orientation='horizontal', fraction=0.046, pad=0.04)
    plt.subplot(1, 2, 2)
    norm = simple_norm(residual_image, 'log', percent=99.)
    plt.imshow(residual_image, norm=norm, origin='lower', cmap='viridis')
#    plt.imshow(residual_image, cmap='viridis', aspect=1,interpolation='nearest', origin='lower')
    plt.title('Residual')
    plt.colorbar(orientation='horizontal', fraction=0.046, pad=0.04)
    plt.show()
    return
Exemple #4
0
def w51north_plot():
    fig = pl.figure(figsize=(9, 9))
    ax = pl.subplot(projection=ww)
    im = ax.imshow(fh[0].data,
                   cmap='gray',
                   norm=visualization.simple_norm(fh[0].data,
                                                  stretch='log',
                                                  max_percent=100.00))
    cb = pl.colorbar(mappable=im)
    cb.set_label(f"$S_\\nu$ [{fh[0].header['BUNIT']}]", fontsize=16)
    # cb.set_ticks([np.nanmin(fh[0].data), -0.005, 0.00 ,0.005, 0.01, 0.015, 0.020, 0.025])
    ax.axis([6750, 7750, 6750, 7750])

    radesys = ww.wcs.radesys

    _ = ax.set_xlabel(f"Right Ascension {ww.wcs.radesys}")
    _ = ax.set_ylabel(f"Declination {ww.wcs.radesys}")

    tick_fontsize = 14
    fontsize = 16
    ra = ax.coords['ra']
    ra.set_major_formatter('hh:mm:ss.s')
    dec = ax.coords['dec']
    ra.set_axislabel(f"RA ({radesys})", fontsize=fontsize)
    dec.set_axislabel(f"Dec ({radesys})", fontsize=fontsize, minpad=0.0)
    ra.ticklabels.set_fontsize(tick_fontsize)
    ra.set_ticklabel(exclude_overlapping=True)
    dec.ticklabels.set_fontsize(tick_fontsize)
    dec.set_ticklabel(exclude_overlapping=True)

    return ax
Exemple #5
0
def plot_sky_with_detected_stars(data, wcs, positions, filename=None):
    '''plot line map with detected sources
    
    Parameters
    ----------

    data : 2d array
        numpy array that contains the image data

    wcs : 
        wcs information for the projection

    positions : array or tuple
        (n,2) shaped array with positions. Can also be a tuple of
        multiple such arrays.

    filename : Path
        if given, a PDF of the plot is saved to filename
    '''

    apertures = []
    if isinstance(positions, tuple) or isinstance(positions, list):
        for position in positions:
            apertures.append(CircularAperture(position, r=5))
    else:
        apertures.append(CircularAperture(positions, r=5))

    #fig = figure(figsize=(6.974,6.974))
    fig = figure(figsize=(3.321, 3.321))

    ax = fig.add_subplot(111, projection=wcs)
    vmax = np.nanpercentile(data, 95)
    norm = simple_norm(data[~np.isnan(data)],
                       'log',
                       max_percent=95.,
                       clip=False)
    cmap = plt.cm.Blues_r
    cmap.set_bad('w')

    plt.imshow(
        data,
        origin='lower',
        cmap=cmap,
        #norm=norm,
        #interpolation='none',
        vmax=vmax)

    colors = ['tab:red', 'yellow', 'orange', 'green']
    for i, aperture in enumerate(apertures):
        aperture.plot(color=colors[i], lw=.8, alpha=1)

    ax.set_xlabel(r'RA (J2000)')
    ax.set_ylabel(r'Dec (J2000)')

    plt.tight_layout()

    if filename:
        if not isinstance(filename, Path):
            filename = Path(filename)
        savefig(filename, bbox_inches='tight')
Exemple #6
0
def ndarray_to_png(x, min_percent=20, max_percent=99.5):
    shape = np.array(x.shape)
    # Reverse order for reasons I do not understand...
    shape = shape[::-1]
    if len(shape) != 2:
        return

    width = 600  # pixels
    downsample = (shape[0] // width) + 1

    if downsample > 1:
        x = block_reduce(x,
                         block_size=(downsample, downsample))

    norm = simple_norm(x,
                       min_percent=min_percent,
                       max_percent=max_percent,
                       clip=True)

    x = norm(x)
    # Replace NaNs with black pixels
    x = np.nan_to_num(x)
    img_buffer = BytesIO()
    mimg.imsave(img_buffer, x, format='png', cmap='gray')
    return img_buffer.getvalue()
Exemple #7
0
 def show_psf(self):
     norm = simple_norm(self.epsf.data, 'log', percent=99.)
     plt.figure()
     plt.imshow(self.epsf.data, norm=norm, origin='lower', cmap='viridis')
     plt.colorbar()
     #plt.show()
     plt.savefig('plots/' + self.basename + '-psf.png')
Exemple #8
0
def single_cutout(ax,position,image,mask1=None,mask2=None,points=None,label=None,size=6*u.arcsec):
    
    cutout_image = Cutout2D(image.data,position,size=size,wcs=image.wcs)
    norm = simple_norm(cutout_image.data,clip=False,stretch='linear',percent=99.5)

    ax.imshow(cutout_image.data,origin='lower',norm=norm,cmap=plt.cm.gray_r)

    # plot the nebulae catalogue
    cutout_mask, _  = reproject_interp(mask1,output_projection=cutout_image.wcs,shape_out=cutout_image.shape,order='nearest-neighbor')    
    region_ID = np.unique(cutout_mask[~np.isnan(cutout_mask)])

    contours = []
    for i in region_ID:
        blank_mask = np.zeros_like(cutout_mask)
        blank_mask[cutout_mask==i] = 1
        contours += find_contours(blank_mask, 0.5)

    for coords in contours:
        ax.plot(coords[:,1],coords[:,0],color='tab:red',lw=1,label='HII-region')


    mask = np.zeros((*cutout_mask.shape,4))
    mask[~np.isnan(cutout_mask.data),:] = (0.84, 0.15, 0.16,0.1)
    ax.imshow(mask,origin='lower')

    # plot the association catalogue
    if mask2:
        cutout_mask, _  = reproject_interp(mask2,output_projection=cutout_image.wcs,shape_out=cutout_image.shape,order='nearest-neighbor')    
        region_ID = np.unique(cutout_mask[~np.isnan(cutout_mask)])

        contours = []
        for i in region_ID:
            blank_mask = np.zeros_like(cutout_mask)
            blank_mask[cutout_mask==i] = 1
            contours += find_contours(blank_mask, 0.5)

        for coords in contours:
            ax.plot(coords[:,1],coords[:,0],color='tab:blue',lw=1,label='association')

        mask = np.zeros((*cutout_mask.shape,4))
        mask[~np.isnan(cutout_mask.data),:] = (0.12,0.47,0.71,0.1)
        ax.imshow(mask,origin='lower')

    # mark the position of the clusters within the cutout
    if points:
        region = RectangleSkyRegion(position,0.9*size,0.9*size)
        in_frame = points[region.contains(points['SkyCoord'],cutout_image.wcs)]
        for row in in_frame:
            x,y = row['SkyCoord'].to_pixel(cutout_image.wcs)
            if 5<x<cutout_image.data.shape[0]-5 and 5<y<cutout_image.data.shape[1]-5:
                ax.scatter(x,y,marker='o',facecolors='none',s=20,lw=0.4,color='tab:blue',label='cluster')

    if label:
        t = ax.text(0.07,0.875,label, transform=ax.transAxes,color='black',fontsize=8)
        t.set_bbox(dict(facecolor='white', alpha=1, ec='white'))

    ax.set_xticks([])
    ax.set_yticks([])
    
    return ax
Exemple #9
0
def show_fov_on_spitzer(finaliter_prefix_b3,
                        finaliter_prefix_b6,
                        fieldid,
                        spitzerpath='spitzer_datapath',
                        spitzer_display_args=dict(stretch='log',
                                                  min_percent=1,
                                                  max_percent=99.99,
                                                  clip=True),
                        contour_level={
                            'B3': [0.01],
                            'B6': [0.01]
                        }):
    image_b3 = SpectralCube.read(f'{finaliter_prefix_b3}.image.tt0.fits',
                                 use_dask=False,
                                 format='fits')
    image_b6 = SpectralCube.read(f'{finaliter_prefix_b6}.image.tt0.fits',
                                 use_dask=False,
                                 format='fits')

    spitzfn = f'{spitzerpath}/{fieldid}_spitzer_images.fits'
    spitz = fits.open(spitzfn)[0]

    ww = wcs.WCS(spitz.header)

    fig = pl.figure(1, figsize=(10, 10))
    fig.clf()
    ax = fig.add_subplot(projection=ww.celestial)

    spitz_data = np.array(
        [simple_norm(x, **spitzer_display_args)(x) for x in spitz.data])

    ax.imshow(spitz_data.T.swapaxes(0, 1))

    lims = ax.axis()

    ax.contour(image_b3.mask.include()[0],
               transform=ax.get_transform(image_b3.wcs.celestial),
               levels=[0.5],
               colors=['orange'])
    ax.contour(image_b6.mask.include()[0],
               transform=ax.get_transform(image_b6.wcs.celestial),
               levels=[0.5],
               colors=['cyan'])
    ax.contour(image_b3[0].value,
               transform=ax.get_transform(image_b3.wcs.celestial),
               levels=contour_level['B3'],
               colors=['wheat'],
               linewidths=[0.5])
    ax.contour(image_b6[0].value,
               transform=ax.get_transform(image_b6.wcs.celestial),
               levels=contour_level['B6'],
               colors=['lightblue'],
               linewidths=[0.5])

    ax.axis(lims)
    ax.set_xlabel('Galactic Longitude')
    ax.set_ylabel('Galactic Latitude')

    #pl.figure(2).gca().imshow(image_b6.mask.include()[0])
    return fig
Exemple #10
0
def showimage(imagename, title=None, stretch='asinh', mask=None, **kwargs):
    if isinstance(imagename, str):
        ia.open(imagename)
        data = ia.getchunk().squeeze()
        ia.close()
    else:
        data = imagename

    if 'percentiles' in kwargs:
        min_percent, max_percent = kwargs.pop('percentiles')
        kwargs['min_percent'] = min_percent
        kwargs['max_percent'] = max_percent

    if mask is not None:
        data = data.squeeze().T * mask.T,
    else:
        data = data.squeeze().T

    im = pl.imshow(
        data,
        norm=simple_norm(data, stretch=stretch, **kwargs),
        origin='lower',
        interpolation='none',
    )

    if title is not None:
        pl.title(title)
    pl.gca().set_xticklabels([])
    pl.gca().set_yticklabels([])
    pl.colorbar()

    return im
Exemple #11
0
def OldPlotCube(cube, tdisplay, timebin):
    """
    Plot the image of the cube at tdisplay, as well as the cube projected lightcurve, with a dshed line at tdisplay
    """
    Tsize = np.shape(cube)[2]
    print("No elements =", Tsize)

    time = np.arange(0, Tsize) * timebin  # timebin is real time of exposure

    im_t = cube[:, :, tdisplay].astype(float)  # Create image at tdisplay
    LC = np.sum(cube, axis=(0, 1))  # Project the curbe on the time dimension

    fig = plt.figure(figsize=(10, 5))
    # Image at tdisplay from the cube
    left, bottom, width, height = 0.05, 0., 0.45, 1
    ax1 = fig.add_axes([left, bottom, width, height])
    ax1.grid(False)
    stretch = 'sqrt'
    p1 = ax1.imshow(im_t, norm=simple_norm(im_t, stretch), vmax=np.max(cube))
    cbar = plt.colorbar(p1, fraction=0.045, ax=ax1)

    # Lightcurve from the cube
    left, bottom, width, height = 0.65, 0.13, 0.5, 0.8
    ax2 = fig.add_axes([left, bottom, width, height])
    ax2.axvline(tdisplay * timebin, color='blue', ls=':')
    ax2.set_xlabel('Time (sec)', fontsize=15)
    ax2.set_ylabel('Counts', fontsize=15)
    ax2.plot(time, LC)

    plt.show()

    return
Exemple #12
0
def _data_stretch(image, vmin=None, vmax=None, pmin=0.25, pmax=99.75,
                  stretch='linear', vmid=None, exponent=2):

    if vmin is None or vmax is None:
        interval = AsymmetricPercentileInterval(pmin, pmax, n_samples=10000)
        try:
            vmin_auto, vmax_auto = interval.get_limits(image)
        except IndexError:  # no valid values
            vmin_auto = vmax_auto = 0

    if vmin is None:
        log.info("vmin = %10.3e (auto)" % vmin_auto)
        vmin = vmin_auto
    else:
        log.info("vmin = %10.3e" % vmin)

    if vmax is None:
        log.info("vmax = %10.3e (auto)" % vmax_auto)
        vmax = vmax_auto
    else:
        log.info("vmax = %10.3e" % vmax)

    if stretch == 'arcsinh':
        stretch = 'asinh'

    normalizer = simple_norm(image, stretch=stretch, power=exponent,
                             asinh_a=vmid, min_cut=vmin, max_cut=vmax, clip=False)

    data = normalizer(image, clip=True).filled(0)
    data = np.nan_to_num(data)
    data = np.clip(data * 255., 0., 255.)

    return data.astype(np.uint8)
Exemple #13
0
def norm_imshow(ax,
                data,
                stretch='linear',
                power=1.0,
                asinh_a=0.1,
                min_cut=None,
                max_cut=None,
                min_percent=None,
                max_percent=None,
                percent=None,
                clip=True,
                log_a=1000,
                **kwargs):
    """ Do normalization and do imshow
    """
    norm = simple_norm(data,
                       stretch=stretch,
                       power=power,
                       asinh_a=asinh_a,
                       min_cut=min_cut,
                       max_cut=max_cut,
                       min_percent=min_percent,
                       max_percent=max_percent,
                       percent=percent,
                       clip=clip,
                       log_a=log_a)
    im = ax.imshow(data, norm=norm, origin='lower', **kwargs)
    return im
Exemple #14
0
def run_test_dectecion():
    nrows = 2
    ncols = 4
    fig, ax = plt.subplots(nrows=nrows,
                           ncols=ncols,
                           figsize=(20, 10),
                           squeeze=True)
    ax = ax.ravel()

    amplitude_lst = [40, 200]
    sigma_lst = [2., 4.]
    StarFinder_lst = [DAOStarFinder, IRAFStarFinder]

    settings = []
    for f in StarFinder_lst:
        for s in sigma_lst:
            for a in amplitude_lst:
                settings.append((f, s, a))

    for i in range(nrows * ncols):
        f, s, a = settings[i]
        img, ap, sc, string = test_detection(f, s, a, PSF_size=1)

        norm = simple_norm(img, 'log', percent=99.)
        ax[i].imshow(img, norm=norm, origin='lower', cmap='viridis')
        ap.plot(color='red', lw=1., alpha=0.9, ax=ax[i])
        ax[i].scatter(sc['x_mean'], sc['y_mean'], color='red', s=1)
        ax[i].set_title(string)

    plt.show()
Exemple #15
0
def _data_stretch(image, vmin=None, vmax=None, pmin=0.25, pmax=99.75,
                  stretch='linear', vmid=None, exponent=2):

    if vmin is None or vmax is None:
        interval = AsymmetricPercentileInterval(pmin, pmax, n_samples=10000)
        try:
            vmin_auto, vmax_auto = interval.get_limits(image)
        except IndexError:  # no valid values
            vmin_auto = vmax_auto = 0

    if vmin is None:
        vmin = vmin_auto

    if vmax is None:
        vmax = vmax_auto


    normalizer = simple_norm(image, stretch=stretch, power=exponent,
                             asinh_a=vmid, min_cut=vmin, max_cut=vmax, clip=False)

    data = normalizer(image, clip=True).filled(0)
    data = np.nan_to_num(data)
    data = np.clip(data * 255., 0., 255.)

    return data.astype(np.uint8)
Exemple #16
0
    def create_example_frame(self, plot=True, figsize=(13, 13)):
        fits_files = list(self.datadir.glob('MCT*fits'))
        assert len(fits_files) > 0, 'No example frame fits-files found.'
        f = fits_files[0]
        f1 = pf.open(f)
        f2 = pf.open(f.with_suffix('.wcs'))
        h1 = f1[0].header.copy()
        h1.append(('COMMENT', '*********************'))
        h1.append(('COMMENT', '  WCS '))
        h1.append(('COMMENT', '*********************'))
        h1.extend(f2[0].header, unique=True, bottom=True)
        f1[0].header = h1
        filter = h1['filter']
        f1.writeto(self._dres.joinpath(
            f'{self.ticname}_20{self.date}_MuSCAT2_{filter}_frame.fits'),
                   overwrite=True)

        if plot:
            wcs = WCS(f1[0].header)
            data = f1[0].data.astype('d')
            norm = simple_norm(data, stretch='log')
            fig = figure(figsize=figsize, constrained_layout=True)
            ax = fig.add_subplot(111, projection=wcs)
            ax.imshow(data, origin='image', norm=norm, cmap=cm.gray_r)
            apts = SkyCircularAperture(
                self.phs[0].centroids_sky,
                float(self.phs[0]._flux.aperture[self.lpf.aid]) * u.pixel)
            apts.to_pixel(wcs).plot(color='w')
Exemple #17
0
        def _plot_interactive(index, stretch, ax=None, fig=None):
            if self.geom.is_image:
                raise TypeError('Use .plot() for 2D Maps')

            if fig is None:
                fig = plt.gcf()

            if ax is None:
                ax = fig.add_subplot(1, 1, 1, projection=self.geom.wcs)

            axes = self.geom.get_axis_by_name(self.geom.axes_names[0])

            data = self.get_image_by_idx([index]).data
            norm = simple_norm(data[np.isfinite(data)], stretch)

            caxes = ax.imshow(data, norm=norm, **kwargs)
            fig.colorbar(caxes, ax=ax)
            ax.set_title('{:.2f}-{:.2f} {} '.format(
                axes.edges[index],
                axes.edges[index + 1],
                self.geom.axes[0].unit.name,
            ))

            try:
                ax.coords['glon'].set_axislabel('Galactic Longitude')
                ax.coords['glat'].set_axislabel('Galactic Latitude')
            except KeyError:
                ax.coords['ra'].set_axislabel('Right Ascension')
                ax.coords['dec'].set_axislabel('Declination')
            except AttributeError:
                log.info(
                    "Can't set coordinate axes. No WCS information available.")

            plt.show()
def scale_and_downsample(data, downsample=4, min_percent=20, max_percent=99.5):

    norm = simple_norm(data, min_percent=min_percent, max_percent=max_percent)
    scaled_data = norm(data)
    if downsample > 1:
        scaled_data = block_reduce(scaled_data,
                                   block_size=(downsample, downsample))
    return scaled_data
Exemple #19
0
def plot_epsf(epsf):

    norm = simple_norm(epsf.data, 'log', percent=99.)
    plt.figure()
    plt.imshow(epsf.data, norm=norm, origin='lowerleft', cmap='viridis')
    plt.colorbar()
    plt.show()

    return
Exemple #20
0
def plot_sky_with_detected_stars(data, wcs, positions, filename=None):
    '''plot line map with detected sources
    
    Parameters
    ----------

    data : 2d array
        numpy array that contains the image data

    wcs : 
        wcs information for the projection

    positions : array or tuple
        (n,2) shaped array with positions. Can also be a tuple of
        multiple such arrays.

    filename : Path
        if given, a PDF of the plot is saved to filename
    '''

    apertures = []
    if isinstance(positions, tuple) or isinstance(positions, list):
        for position in positions:
            apertures.append(CircularAperture(position, r=8))
    else:
        apertures.append(CircularAperture(positions, r=8))

    fig = figure(figsize=(6.974, 6.974 / 2))
    ax = fig.add_subplot(111, projection=wcs)
    norm = simple_norm(data,
                       'asinh',
                       clip=False,
                       min_percent=1,
                       max_percent=99.5)
    cmap = plt.cm.hot
    cmap.set_bad('w')

    plt.imshow(
        data,
        origin='lower',
        cmap=cmap,
        norm=norm,
        #interpolation='none',
        #vmax=vmax
    )

    for aperture in apertures:
        aperture.plot(color='blue', lw=.5, alpha=1)

    ax.set_xlabel('RA')
    ax.set_ylabel('Dec')

    if filename:
        if not isinstance(filename, Path):
            filename = Path(filename)

        plt.savefig(filename, dpi=600)
def plot_spatial(image,
                 plotfname='spatial.pdf',
                 coords1='None',
                 coords2='None',
                 stars='None',
                 mags='False',
                 annotate='no',
                 interactive=False):
    fig, axes = plt.subplots(figsize=(14, 14))
    norm = simple_norm(image, 'sqrt', percent=90.)
    axes.imshow(image, aspect=1, origin='lower', cmap='Greys', norm=norm)

    if coords1 != 'None':
        coords1_x, coords1_y = coords1[0], coords1[1]
        for i in range(len(coords1_x)):
            e = Circle(xy=(coords1_x[i], coords1_y[i]), radius=4)
            e.set_facecolor('none')
            e.set_edgecolor('deeppink')
            axes.add_artist(e)

    if coords2 != 'None':
        coords2_x, coords2_y = coords2[0], coords2[1]
        for j in range(len(coords2_x)):
            e = Circle(xy=(coords2_x[j], coords2_y[j]), radius=3)
            e.set_facecolor('none')
            e.set_edgecolor('blue')
            axes.add_artist(e)

    if ((stars != 'None') & (mags == 'False')):
        for star in stars:
            e = Circle(xy=(star.xcoord, star.ycoord), radius=3)
            e.set_facecolor('none')
            e.set_edgecolor('deeppink')
            if annotate == 'yes':
                axes.annotate(str(star.star_id), (star.xcoord, star.ycoord),
                              (5, 5),
                              textcoords='offset points',
                              color='deeppink')
            axes.add_artist(e)
    if ((stars != 'None') & (mags == 'True')):
        for star in stars:
            e = Circle(xy=(star.xcoord, star.ycoord),
                       radius=(18 - star.ir_mag) * 2)
            e.set_facecolor('none')
            e.set_edgecolor('C1')
            axes.annotate(str(star.star_id), (star.xcoord, star.ycoord),
                          (5, 5),
                          textcoords='offset points',
                          color='C1')
            axes.add_artist(e)
    axes.set_xlabel('x coordinate [px]')
    axes.set_ylabel('y coordinate [px]')

    fig.savefig(plotfname, bbox_inches='tight')

    if interactive:
        plt.show()
 def update_image(self, ax, img, gamma):
     try: 
         R = self.img[:,:,0]; G = self.img[:,:,1]; B = self.img[:,:,2]
         Rg = np.clip(np.power(R, gamma), 0, 1)
         Gg = np.clip(np.power(G, gamma), 0, 1)
         Bg = np.clip(np.power(B, gamma), 0, 1)
        
         img_gamma = np.min([Rg, Gg, Bg], axis=0)
         img.set_data(img_gamma)
     except IndexError:
         img.norm = simple_norm(self.img, 'sqrt')
Exemple #23
0
def gshow(data, ax=None):

    if (ax == None):
        f, ax = plt.subtplos(1, 1)

    norm = simple_norm(data, 'sqrt', percent=99.9)
    cs = ax.imshow(data, norm=norm, cmap='gist_gray_r')

    if (ax == None):
        f.colorbar(cs)

    return ax
def scale_and_downsample(data, downsample=4, min_percent=20, max_percent=99.5):

    scaled_data = data

    if downsample > 1:
        scaled_data = block_reduce(scaled_data,
                                   block_size=(downsample, downsample))
    norm = simple_norm(scaled_data,
                       min_percent=min_percent,
                       max_percent=max_percent,
                       clip=True)

    return norm(scaled_data)
Exemple #25
0
    def get_wise_image_old(self):
        '''
        GOAL: Get the unWISE image from the unWISE catalog

        INPUT: nsaid used to grab unwise image information

        OUTPUT: Name of file to retrieve from

        '''

        baseurl = 'http://unwise.me/cutout_fits?version=allwise'
        imsize = self.radius * 2
        imurl = baseurl + '&ra=%.5f&dec=%.5f&size=%s&bands=%s' % (
            self.ra, self.dec, imsize, self.band)
        wisetar = wget.download(imurl)
        tartemp = tarfile.open(wisetar, mode='r:gz')  #mode='r:gz'
        wnames = tartemp.getnames()
        self.wnames = wnames
        print(wnames)
        # check for multiple pointings - means galaxy is split between images
        self.multiframe = False
        if len(wnames) > 4:
            self.multiframe = True
            os.remove(wisetar)
            return

        wmembers = tartemp.getmembers()
        tartemp.extractall()
        for fname in wnames:
            t = fname.split('-')
            self.rename = self.galname + '-' + t[0] + '-' + t[2] + '-' + t[
                3] + '-' + t[4]

            #print self.rename
            if os.path.exists(
                    self.rename
            ):  # this should only occur if multiple images are returned from wise
                os.remove(self.rename)
            os.rename(fname, self.rename)
            if self.rename.find('.gz') > -1:
                os.system('gunzip ' + self.rename)
            if fname.find('img') > -1:
                self.inputimage = self.rename
        os.remove(wisetar)
        print('self.rename = ', self.rename)

        ##### DISPLAY IMAGE
        im = fits.getdata(self.rename)
        norm = simple_norm(im, stretch='asinh', percent=99)
        plt.imshow(im, norm=norm)
        plt.show()
Exemple #26
0
def extract_radio_properties(hdu, survey_name, rms=None, savedir=False):

    fig = plt.figure(figsize=(18, 18))
    imdata, w = hdu[0].data, wcs.WCS(hdu[0].header, naxis=2)
    norm = simple_norm(imdata, percent=99.5)
    ax0 = fig.add_axes([0.1, 0.1, 0.85, 0.85], projection=w)
    ax0.imshow(imdata, cmap='inferno', norm=norm)
    if rms:
        ax0.contour(imdata, levels=[3, 5] * rms, colors='white', lw=1)
    polypick = PolyPick(ax0)
    if savedir == True:
        for ext in ['.pdf', '.png']:
            fig.savefig('{0}/{1}_LLS_plot{2}'.format(savedir, survey_name,
                                                     ext))
    plt.show()
    if len(polypick.las.x):
        LAS_points = Coords()
        LAS_points.x, LAS_points.y = w.wcs_pix2world(polypick.las.x,
                                                     polypick.las.y, 0)
        las = (compute_angular_separation(LAS_points.x[0], LAS_points.y[0],
                                          LAS_points.x[1],
                                          LAS_points.y[1])).arcsecond
        las = float('%.4g' % las)
        print('Measured a largest angular size of {0}'
              ' from {1}'.format(las, survey_name))
    else:
        print('No angular size measured.')
        las = np.nan
    if len(polypick.ucore.x):
        core_coords = Coords()
        core_coords.x, core_coords.y = w.wcs_pix2world(
            (polypick.ucore.x)[len(polypick.ucore.x) - 1],
            (polypick.ucore.y)[len(polypick.ucore.x) - 1], 0)
        ra_core, dec_core = core_coords.x, core_coords.y
        core_type = 'unresolved'
        print(
            'Unresolved {0} radio core measured at RA = {1}, Dec = {2}'.format(
                las, ra_core, dec_core))
    elif len(polypick.ecore.x):
        core_coords = Coords()
        core_coords.x, core_coords.y = w.wcs_pix2world(
            (polypick.ecore.x)[len(polypick.ecore.x) - 1],
            (polypick.ecore.y)[len(polypick.ecore.x) - 1], 0)
        ra_core, dec_core = core_coords.x, core_coords.y
        core_type = 'resolved'
        print('Resolved {0} radio core measured at RA = {1}, Dec = {2}'.format(
            las, ra_core, dec_core))
    else:
        print('No radio core measured.')
        ra_core, dec_core, core_type = np.nan, np.nan, 0
    return (las, ra_core, dec_core, core_type)
Exemple #27
0
    def plot(self,line):
        '''plot a single emission line'''

        if not hasattr(self,line):
            raise AttributeError(f'Object has no map {line}')
        
        data = getattr(self,line)

        fig = plt.figure(figsize=(two_column,two_column/1.618))
        ax  = fig.add_subplot(projection=self.wcs)

        norm = simple_norm(data,clip=False,percent=99)
        ax.imshow(data,norm=norm)
        plt.show()
def scale_and_downsample(data, downsample=4,
                         min_percent=20,
                         max_percent=99.5):

    scaled_data = data

    if downsample > 1:
        scaled_data = block_reduce(scaled_data,
                                   block_size=(downsample, downsample))
    norm = simple_norm(scaled_data,
                       min_percent=min_percent,
                       max_percent=max_percent)

    return norm(scaled_data)
def make_anim_single(imname, suffix, nselfcaliter=7, stretch='asinh', min_percent=1, max_percent=99.00):
    # base imname: W51-E_B6_uid___A001_X1296_X213_continuum_merged_12M_robust0

    fig, ax = pl.subplots(ncols=1, figsize=(8,8))
    fig.set_tight_layout(True)

    dpi = fig.get_dpi()
    size_inches = fig.get_size_inches()

    print(f"Figure size={size_inches} dpi={dpi}")

    ax.set_xticklabels([])
    ax.set_yticklabels([])

    cube_before = SpectralCube.read(f'{imname}_preselfcal.{suffix}.tt0', format='casa_image')
    data = cube_before[0].value
    norm = visualization.simple_norm(data=data, stretch=stretch,
                                     min_percent=min_percent,
                                     max_percent=max_percent)
    im1 = ax.imshow(data, norm=norm)
    title = pl.title("Before selfcal")

    def update(ii):

        try:
            if os.path.exists(f'{imname}_selfcal{ii}_finaliter.{suffix}.tt0'):
                cube = SpectralCube.read(f'{imname}_selfcal{ii}_finaliter.{suffix}.tt0', format='casa_image')
                im1.set_data(cube[0].value)

                title.set_text(f"Selfcal iteration {ii} (final clean)")

                return im1, ax
            if ii == 0:
                im1.set_data(data)
                title.set_text(f"Before selfcal")
                return im1, ax
            else:
                cube = SpectralCube.read(f'{imname}_selfcal{ii}.{suffix}.tt0', format='casa_image')
                im1.set_data(cube[0].value)

                title.set_text(f"Selfcal iteration {ii}")

                return im1, ax
        except Exception as ex:
            print(ex)

    anim = FuncAnimation(fig, update, frames=range(0, nselfcaliter), interval=400)
    anim.save(f'{imname}_{suffix}_selfcal_anim.gif', dpi=dpi, writer='imagemagick')

    return anim
Exemple #30
0
def norm_imshow(ax,
                data,
                origin="lower",
                stretch="linear",
                power=1.0,
                asinh_a=0.1,
                min_cut=None,
                max_cut=None,
                min_percent=None,
                max_percent=None,
                percent=None,
                clip=True,
                log_a=1000,
                invalid=-1.0,
                zscale=False,
                vmin=None,
                vmax=None,
                **kwargs):
    """Do normalization and do imshow"""
    if vmin is not None and min_cut is not None:
        warn("vmin will override min_cut.")

    if vmax is not None and max_cut is not None:
        warn("vmax will override max_cut.")

    if zscale:
        zs = ImageNormalize(data, interval=ZScaleInterval())
        min_cut = vmin = zs.vmin
        max_cut = vmax = zs.vmax

    if vmin is not None or vmax is not None:
        im = ax.imshow(data, origin=origin, vmin=vmin, vmax=vmax, **kwargs)
    else:
        im = ax.imshow(data,
                       origin=origin,
                       norm=simple_norm(data=data,
                                        stretch=stretch,
                                        power=power,
                                        asinh_a=asinh_a,
                                        min_cut=min_cut,
                                        max_cut=max_cut,
                                        min_percent=min_percent,
                                        max_percent=max_percent,
                                        percent=percent,
                                        clip=clip,
                                        log_a=log_a,
                                        invalid=invalid),
                       **kwargs)
    return im
Exemple #31
0
def sample_cutouts(data,peaks_tbl,wcs,nrows=10,ncols=10,filename=None):
    '''create cutouts of the detected sources and plot them
    
    
    '''
    
    # exclude stars that are too close to the border
    size = 16
    hsize = (size - 1) / 2
    x = peaks_tbl['x']  
    y = peaks_tbl['y']  
    mask = ((x > hsize) & (x < (data.shape[1] -1 - hsize)) &
           (y > hsize) & (y < (data.shape[0] -1 - hsize)))  

    stars_tbl = Table()
    stars_tbl['x'] = x[mask]  
    stars_tbl['y'] = y[mask]  

    # extract_stars does not include wcs information
    #nddata = NDData(data=data,wcs=self.wcs)  
    #stars = extract_stars(nddata, stars_tbl, size=size)  

    # defien the size of the cutout region
    size = u.Quantity((size, size), u.pixel)

    stars = []
    for row in stars_tbl:
        stars.append(Cutout2D(data, (row['x'],row['y']), size,wcs=wcs))
    
    #fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=(20, 20),squeeze=True)
    #ax = ax.ravel()
    
    fig = figure(figsize=(100,100))
    
    # get an index idx from 0 to nrows*ncols and a random index i from 0 to len(stars)
    for idx,i in enumerate(random.sample(range(len(stars)), nrows*ncols)):
        ax = fig.add_subplot(nrows,ncols,idx+1,projection=stars[i].wcs)

        if np.any(np.isnan(stars[i].data)):
            print('this should not be')

        norm = simple_norm(stars[i].data, 'log', percent=99.)
        ax.imshow(stars[i].data, norm=norm, origin='lower', cmap='Blues_r')

    if filename:
        if not isinstance(filename,Path):
            filename = Path(filename)
            
        plt.savefig(filename)
Exemple #32
0
def PlotCube(cube, time, tdisplay):
    """
    Plot the image of the cube at tdisplay, as well as the cube projected lightcurve, with a dshed line at tdisplay
    """
    #Tsize=np.shape(cube)[-1]
    #print("No elements =",Tsize)
    #time = np.arange(0,Tsize)*timebin # timebin is real time of exposure

    im_t = cube[:, :, np.where(time == tdisplay)[0][0]].astype(
        float)  # Create image at tdisplay
    LC = CubeLC(cube)

    fig = plt.figure(figsize=(10, 5))
    # Image at tdisplay from the cube
    left, bottom, width, height = 0.05, 0., 0.45, 1
    ax1 = fig.add_axes([left, bottom, width, height])
    ax1.grid(False)
    stretch = 'sqrt'

    if np.isnan(cube).any():
        new_im_t = np.ma.array(im_t,
                               mask=np.isnan(im_t))  # Array with masked values
        cmap = plt.cm.jet
        cmap.set_bad('white', 1.)
        p1 = ax1.imshow(new_im_t,
                        cmap=cmap,
                        vmax=np.max(cube[~np.isnan(cube)]))

    else:
        p1 = ax1.imshow(im_t,
                        norm=simple_norm(im_t, stretch),
                        vmax=np.max(cube))

    cbar = plt.colorbar(p1, fraction=0.045, ax=ax1)
    ax1.set_xlabel('x (px)')
    ax1.set_ylabel('y (px)')

    # Lightcurve from the cube
    left, bottom, width, height = 0.65, 0.13, 0.5, 0.8
    ax2 = fig.add_axes([left, bottom, width, height])
    ax2.axvline(tdisplay, color='blue', ls=':')
    ax2.set_xlabel('Time (sec)', fontsize=15)
    ax2.set_ylabel('Counts', fontsize=15)
    ax2.plot(time, LC)

    plt.show()

    return
Exemple #33
0
def ndarray_to_png(x, min_percent=20, max_percent=99.5):
    shape = np.array(x.shape)
    # Reverse order for reasons I do not understand...
    shape = shape[::-1]
    if len(shape) != 2:
        return

    width = 600  # pixels
    downsample = (shape[0] // width) + 1

    if downsample > 1:
        x = block_reduce(x,
                         block_size=(downsample, downsample))

    norm = simple_norm(x,
                       min_percent=min_percent,
                       max_percent=max_percent)
    img_buffer = BytesIO()
    mimg.imsave(img_buffer, norm(x), format='png', cmap='gray')
    return img_buffer.getvalue()
Exemple #34
0
    def plot(self, ax=None, fig=None, add_cbar=False, stretch="linear", **kwargs):
        """
        Plot image on matplotlib WCS axes.

        Parameters
        ----------
        ax : `~astropy.visualization.wcsaxes.WCSAxes`, optional
            WCS axis object to plot on.
        fig : `~matplotlib.figure.Figure`
            Figure object.
        add_cbar : bool
            Add color bar?
        stretch : str
            Passed to `astropy.visualization.simple_norm`.
        **kwargs : dict
            Keyword arguments passed to `~matplotlib.pyplot.imshow`.

        Returns
        -------
        fig : `~matplotlib.figure.Figure`
            Figure object.
        ax : `~astropy.visualization.wcsaxes.WCSAxes`
            WCS axis object
        cbar : `~matplotlib.colorbar.Colorbar` or None
            Colorbar object.
        """
        import matplotlib.pyplot as plt
        from astropy.visualization import simple_norm
        from astropy.visualization.wcsaxes.frame import EllipticalFrame

        if not self.geom.is_image:
            raise TypeError("Use .plot_interactive() for Map dimension > 2")

        if fig is None:
            fig = plt.gcf()

        if ax is None:
            if self.geom.is_allsky:
                ax = fig.add_subplot(
                    1, 1, 1, projection=self.geom.wcs, frame_class=EllipticalFrame
                )
            else:
                ax = fig.add_subplot(1, 1, 1, projection=self.geom.wcs)

        data = self.data.astype(float)

        kwargs.setdefault("interpolation", "nearest")
        kwargs.setdefault("origin", "lower")
        kwargs.setdefault("cmap", "afmhot")
        norm = simple_norm(data[np.isfinite(data)], stretch)
        kwargs.setdefault("norm", norm)

        caxes = ax.imshow(data, **kwargs)
        cbar = fig.colorbar(caxes, ax=ax, label=str(self.unit)) if add_cbar else None

        if self.geom.is_allsky:
            ax = self._plot_format_allsky(ax)
        else:
            ax = self._plot_format(ax)

        # without this the axis limits are changed when calling scatter
        ax.autoscale(enable=False)
        return fig, ax, cbar
Exemple #35
0
def main(argv=None):
    """Process command line"""

    import argparse
    import json

    import matplotlib.pyplot as plt
    import astropy.io.fits as fits
    from astropy.wcs import WCS
    from astropy.visualization import simple_norm
    import matplotlib.transforms as mtransforms

    import megaradrp.datamodel as dm
    from megaradrp.processing.wcs import update_wcs_from_ipa, compute_pa_from_ipa

    try:
        from megaradrp.processing.cube import create_cube_from_rss
        has_contours = True
    except ImportError:
        create_cube_from_rss = None
        has_contours = False

    parser = argparse.ArgumentParser(description='Display MEGARA RSS images')
    parser.add_argument('--wcs-grid', action='store_true',
                        help='Display WCS grid')
    parser.add_argument('--wcs-pa-from-header', action='store_true',
                        help="Use PA angle from PC keys", dest='pa_from_header')
    parser.add_argument('--average-region', nargs=2, default=[1000, 3000],
                        type=int, help='Region of the RSS averaged on display')
    parser.add_argument('--extname', '-e', default='PRIMARY',
                        help='Name of the extension used')
    parser.add_argument('--column', '-c', type=int,
                        help='Column of the RSS on display')
    parser.add_argument('--continuum-region', nargs=2,
                        type=int,
                        help='Region of the RSS used for continuum subtraction')
    parser.add_argument('--coordinate-type', choices=['pixel', 'wcs'],
                        default='pixel',
                        help='Types of coordinates used')
    parser.add_argument('--colormap', type=plt.get_cmap,
                        help='Name of a valid matplotlib colormap')
    parser.add_argument('--plot-sky', action='store_true',
                        help='Plot SKY bundles')
    parser.add_argument('--plot-nominal-config', action='store_true',
                        help='Plot nominal configuration, do not use the header')
    parser.add_argument('--hide-values', action='store_true',
                        help='Do not show values out of range')
    parser.add_argument('--title', help='Title of the plot')
    parser.add_argument('--label', help='Legend of the colorbar')
    parser.add_argument('--hex-size', type=float,
                        help='Size of the hexagons (default is {})'.format(SCALE),
                        default=SCALE)
    parser.add_argument('--hex-rel-size', type=float,
                        help='Scale the size of hexagons by a factor',
                        default=1.0)
    parser.add_argument('--min-cut', type=float,
                        help='Inferior cut level')
    parser.add_argument('--max-cut', type=float,
                        help='Superior cut level')
    parser.add_argument('--percent', type=float,
                        help='Compute cuts using percentiles')
    parser.add_argument('--stretch',
                        choices=['linear', 'sqrt', 'power', 'log', 'asinh'],
                        default='linear',
                        help='Name of the strech method used for display'
                        )
    if has_contours:
        parser.set_defaults(has_contours=True)
        group_c = parser.add_argument_group('contouring')
        group_c.add_argument('--contour-pixel-size', type=float, default=0.4,
                             help="Pixel size in arc seconds for image reconstruction")
        group_c.add_argument('--contour-levels',
                             help="Contour levels")
        group_c.add_argument('--contour', action='store_true',
                             help="Draw contours")
        group_c.add_argument('--contour-image',
                             help="Image for computing contours")
        group_c.add_argument('--contour-image-column', type=int,
                             help='Column of image used for contouring')
        group_c.add_argument('--contour-image-save',
                             help='Save image used for contouring')
        group_c.add_argument('--contour-image-region', nargs=2, default=[1000, 3000],
                             type=int, help='Region of the image used for contouring')
        group_c.add_argument('--contour-is-density', action='store_true',
                             help='The data is a magnitude that does not require scaling')

    else:
        parser.set_defaults(has_contours=False)

    parser.add_argument('rss', metavar='RSS', nargs='+',
                        help='RSS images to process')

    args = parser.parse_args(args=argv)

    for fname in args.rss:
        with fits.open(fname) as img:

            datamodel = dm.MegaraDataModel()
            if args.plot_nominal_config:
                insmode = img['FIBERS'].header['INSMODE']
                fiberconf = datamodel.get_fiberconf_default(insmode)
            else:
                fiberconf = datamodel.get_fiberconf(img)
            plot_mask = np.ones((fiberconf.nfibers,), dtype=np.bool)
            if not args.plot_sky:
                skyfibers = fiberconf.sky_fibers()
                skyfibers.sort()
                skyfibers_idx = [(fibid - 1) for fibid in skyfibers]
                plot_mask[skyfibers_idx] = False

            x = np.empty((fiberconf.nfibers,))
            y = np.empty((fiberconf.nfibers,))
            # Key is fibid
            for _, fiber in sorted(fiberconf.fibers.items()):
                idx = fiber.fibid - 1
                x[idx] = fiber.x
                y[idx] = fiber.y

            extname = args.extname
            if args.coordinate_type == 'wcs':
                # read WCS from extname
                wcs_wl = WCS(img[extname].header)
            else:
                wcs_wl = WCS(naxis=len(img[extname].shape))

            rssdata = np.squeeze(img[extname].data)

            zval = extract_zval(rssdata,
                                wcs_wl,
                                args.coordinate_type,
                                args.column,
                                args.average_region,
                                args.continuum_region
                                )
            fig = plt.figure()
            
            x = x[plot_mask]
            y = y[plot_mask]
            zval = zval[plot_mask]
            projection = None

            if args.wcs_grid:
                print('display wcs grid')
                if not args.pa_from_header:
                    print('compute PA from IPA')
                    ipa = img[extname].header['IPA']
                    pa = compute_pa_from_ipa(ipa)
                    print('IPA is', ipa, ' PA is', pa)
                    hdr_fibers = update_wcs_from_ipa(img['FIBERS'].header, pa)
                else:
                    hdr_fibers = img['FIBERS'].header

                projection = WCS(hdr_fibers)

            # plt.subplots_adjust(hspace=0.5)
            ax = fig.add_axes([0.15, 0.1, 0.8, 0.8], projection=projection)

#            ax.set_xlim([-6.5, 6.5])
#            ax.set_ylim([-6, 6])

            if args.wcs_grid:
                ax.coords.grid(color='black', alpha=1.0, linestyle='solid')

            norm = simple_norm(zval, args.stretch,
                               min_cut=args.min_cut,
                               max_cut=args.max_cut,
                               percent=args.percent
                               )

            if args.hide_values:
                zdisp = zval.copy()
                if norm.vmin is not None:
                    zdisp[zval < norm.vmin] = np.nan
                if norm.vmax is not None:
                    zdisp[zval > norm.vmax] = np.nan
            else:
                zdisp = zval
            scale = args.hex_rel_size * args.hex_size
            col = hexplot(ax, x, y, zdisp, scale=scale, cmap=args.colormap, norm=norm)

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

            cb = fig.colorbar(col)
            if args.label is not None:
                cb.set_label(args.label)

            if args.has_contours and args.contour:
                target_scale_arcsec = args.contour_pixel_size

                if args.contour_image is not None:
                    with fits.open(args.contour_image) as hdu_con:
                        extname = args.extname

                        if args.coordinate_type == 'wcs':
                            # read WCS from extname
                            wcs_wl_c = WCS(hdu_con[extname].header)
                        else:
                            wcs_wl_c = WCS(naxis=len(hdu_con[extname].shape))

                        rssdata_con = np.squeeze(hdu_con[extname].data)

                        zval_c = extract_zval(rssdata_con,
                                              wcs_wl_c,
                                              args.coordinate_type,
                                              column=args.contour_image_column,
                                              average_region=args.contour_image_region,
                                              continuum_region=None)
                else:
                    zval_c = zval

                # Build synthetic rss... for reconstruction
                primary = fits.PrimaryHDU(data=zval_c[:, np.newaxis], header=img[extname].header)
                synt = fits.HDUList([primary, img['FIBERS']])

                if args.contour_image_save is not None:
                    synt.writeto(args.contour_image_save)

                conserve_flux = not args.contour_is_density
                s_cube = create_cube_from_rss(synt, target_scale_arcsec, conserve_flux=conserve_flux)
                cube_wcs = WCS(s_cube[0].header).celestial
                px, py = cube_wcs.wcs.crpix
                interp = np.squeeze(s_cube[0].data)
                td = mtransforms.Affine2D().translate(-px, -py).scale(target_scale_arcsec, target_scale_arcsec)
                tt_d = td + ax.transData
                # im = ax.imshow(interp, alpha=0.9, cmap='jet', transform=tt_d)
                # im = ax.imshow(interp, alpha=0.9, cmap='jet', transform=ax.get_transform(cube_wcs))
                if args.contour_levels is not None:
                    levels = json.loads(args.contour_levels)
                    mm = ax.contour(interp, levels, transform=tt_d)
                else:
                    mm = ax.contour(interp, transform=tt_d)
                print('contour levels', mm.levels)

            plt.show()
Exemple #36
0
    def plot(self, ax=None, fig=None, add_cbar=False, stretch='linear', **kwargs):
        """
        Plot image on matplotlib WCS axes.

        Parameters
        ----------
        ax : `~astropy.visualization.wcsaxes.WCSAxes`, optional
            WCS axis object to plot on.
        fig : `~matplotlib.figure.Figure`, optional
            Figure
        stretch : str, optional
            Scaling for image ('linear', 'sqrt', 'log').
            Similar to normalize and stretch functions in ds9.
            See http://docs.astropy.org/en/stable/visualization/normalization.html
        Returns
        -------
        fig : `~matplotlib.figure.Figure`, optional
            Figure
        ax : `~astropy.visualization.wcsaxes.WCSAxes`, optional
            WCS axis object
        cbar : ?
            Colorbar object (if ``add_cbar=True`` was set)
        Examples
        --------
        >>> from astropy.visualization import simple_norm
        >>> from gammapy.image import SkyImage
        >>> filename = '$GAMMAPY_EXTRA/datasets/fermi_2fhl/fermi_2fhl_vela.fits.gz'
        >>> image = SkyImage.read(filename, hdu=2)
        >>> norm = simple_norm(image, 'sqrt')
        >>> plt.imshow(image, norm = norm)
        >>> plt.show()
        >>> #Equivalent to :
        >>> image.plot(stretch='sqrt')
        """
        import matplotlib.pyplot as plt
        from astropy.visualization import simple_norm

        # TODO: make skyimage.data a quantity
        try:
            data = self.data.value
        except AttributeError:
            data = self.data

        if fig is None:
            fig = plt.gcf()

        if ax is None:
            ax = fig.add_subplot(1, 1, 1, projection=self.wcs)

        kwargs['origin'] = kwargs.get('origin', 'lower')
        kwargs['cmap'] = kwargs.get('cmap', 'afmhot')
        kwargs['interpolation'] = kwargs.get('interpolation', 'None')
        norm = simple_norm(data[np.isfinite(data)], stretch)
        kwargs.setdefault('norm', norm)

        caxes = ax.imshow(data, **kwargs)

        if add_cbar:
            unit = self.unit or 'A.U.'
            label = self.name or 'None'
            cbar = fig.colorbar(caxes, ax=ax, label='{} ({})'.format(label.title(), unit))
        else:
            cbar = None

        try:
            ax.coords['glon'].set_axislabel('Galactic Longitude')
            ax.coords['glat'].set_axislabel('Galactic Latitude')
        except KeyError:
            ax.coords['ra'].set_axislabel('Right Ascension')
            ax.coords['dec'].set_axislabel('Declination')
        except AttributeError:
            log.info("Can't set coordinate axes. No WCS information available.")

        # without this the axis limits are changed when calling scatter
        ax.autoscale(enable=False)
        return fig, ax, cbar