Beispiel #1
0
def make_plot(cb_coord, psr_coord, hpbw):
    """
    Create a plot of the CB pattern with pulsar locations

    :param list cb_coord: List of SkyCoord objects with CB pointings
    :param list psr_coord: List of (name, SkyCoord) tuples with pulsar names and positions
    :param Quantity hpbw: half-power beam width of the CBs
    """
    fig, ax = plt.subplots()
    # CB positions
    for cb_idx, cb_pos in enumerate(cb_coord):
        ax.text(cb_pos.ra.deg,
                cb_pos.dec.deg,
                f'{cb_idx:02d}',
                ha='center',
                va='center',
                alpha=.5)
        patch = SphericalCircle((cb_pos.ra, cb_pos.dec),
                                hpbw,
                                ec='k',
                                fc='none',
                                ls='-',
                                alpha=.5)
        ax.add_patch(patch)
    # pulsar positions
    for name, coord in psr_coord:
        ax.plot(coord.ra.deg, coord.dec.deg, marker='o', color='red')
        ax.text(coord.ra.deg + .1, coord.dec.deg, name, va='center', ha='left')
    ax.set_xlabel('RA (deg)')
    ax.set_ylabel('Dec (deg)')
    plt.show()
Beispiel #2
0
def simple_finder_astro(myfile, findername, searchrad=28. / 3600):

    hdulist = pf.open(myfile)[0]
    img = hdulist.data * 1.

    name = fitsutils.get_par(myfile, "NAME")
    filter = fitsutils.get_par(myfile, "FILTER")

    ra, dec = coordinates_conversor.hour2deg(
        fitsutils.get_par(myfile, "OBJRA"),
        fitsutils.get_par(myfile, "OBJDEC"))

    wcs = WCS(hdulist.header)

    target_pix = wcs.wcs_world2pix([(np.array([ra, dec], np.float_))], 1)[0]
    corner_pix = wcs.wcs_world2pix(
        [(np.array([ra + searchrad, dec + searchrad], np.float_))], 1)[0]
    X = int(target_pix[0])
    Y = int(target_pix[1])
    #Size of the finder in pixels

    dx = int(np.abs(np.ceil(corner_pix[0] - target_pix[0])))
    dy = int(np.abs(np.ceil(corner_pix[1] - target_pix[1])))

    #size = int( (searchrad/0.394)/2)

    #zmin, zmax = zscale.zscale()
    newimg = img[X - dx:X + dx, Y - dy:Y + dy]

    zmin = np.percentile(newimg.flatten(), 5)
    zmax = np.percentile(newimg.flatten(), 98.5)

    print("X %d Y %d Size %d, %d zmin=%.2f zmax=%.2f. Size = %s" %
          (X, Y, dx, dy, zmin, zmax, newimg.shape))

    from astropy.visualization.wcsaxes import SphericalCircle

    plt.figure(figsize=(10, 9))
    ax = plt.subplot(projection=wcs)
    ax.imshow(np.flip(newimg, axis=0), \
        origin="lower", cmap=plt.get_cmap('gray'), vmin=zmin, vmax=zmax)
    r = SphericalCircle((ra * u.deg, dec * u.deg),
                        5. / 3600 * u.degree,
                        edgecolor='red',
                        facecolor='none',
                        transform=ax.get_transform('fk5'))
    ax.add_patch(r)

    #ax = plt.gca()
    #ax.scatter(ra, dec, transform=ax.get_transform('fk5'), s=20,
    #       edgecolor='red', facecolor='none')

    #plt.plot(dy, dx, "+", color="r", ms=20, mfc=None, mew=2)
    #plt.plot(Y, X, "+", color="r", ms=20, mfc=None, mew=2)
    #plt.xlim(Y-dy, Y+dy, X-dx, X+dx)

    plt.savefig(findername)

    print("Created ", findername)
Beispiel #3
0
    def mark_inset_circle(self, ax, center, radius, *args, **kwargs):
        """Outline a circle in this and another Axes to create a loupe.

        Parameters
        ----------
        ax : `astropy.visualization.wcsaxes.WCSAxes`
            The other axes.
        coord : `astropy.coordinates.SkyCoord`
            The center of the circle.
        radius : `astropy.units.Quantity`
            The radius of the circle in units that are compatible with degrees.

        Other parameters
        ----------------
        args :
            Extra arguments for `matplotlib.patches.PathPatch`
        kwargs :
            Extra keyword arguments for `matplotlib.patches.PathPatch`

        Returns
        -------
        patch1 : `matplotlib.patches.PathPatch`
            The outline of the circle in these Axes.
        patch2 : `matplotlib.patches.PathPatch`
            The outline of the circle in the other Axes.
        """
        center = SkyCoord(
            center, representation_type=UnitSphericalRepresentation).icrs
        radius = u.Quantity(radius)
        args = ((center.ra, center.dec), radius, *args)
        kwargs = {'facecolor': 'none',
                  'edgecolor': rcParams['axes.edgecolor'],
                  'linewidth': rcParams['axes.linewidth'],
                  **kwargs}
        for ax in (self, ax):
            ax.add_patch(SphericalCircle(*args, **kwargs,
                                         transform=ax.get_transform('world')))
Beispiel #4
0
###############################################################################
# Let's crop the image with Venus at it's center.
fov = 100 * u.arcsec
top_right = SkyCoord(venus_hpc.Tx + fov,
                     venus_hpc.Ty + fov,
                     frame=aiamap.coordinate_frame)
bottom_left = SkyCoord(venus_hpc.Tx - fov,
                       venus_hpc.Ty - fov,
                       frame=aiamap.coordinate_frame)
smap = aiamap.submap(top_right, bottom_left)

###############################################################################
# Let's plot the results.
ax = plt.subplot(111, projection=smap)
smap.plot()
smap.draw_limb()
ax.grid(False)
ax.plot_coord(venus_hpc, "x", color="deepskyblue", label="Venus")

r = SphericalCircle(
    (venus_hpc.Tx, venus_hpc.Ty),
    venus_angular_extent,
    edgecolor="deepskyblue",
    facecolor="none",
    transform=ax.get_transform("world"),
)
ax.add_patch(r)
plt.legend()
plt.savefig("fig_venus_transit.pdf", dpi=200)
plt.close()
Beispiel #5
0
def generate(image,
             wcs,
             title,
             log_stretch=False,
             cutout=None,
             primary_coord=None,
             secondary_coord=None,
             third_coord=None,
             vmnx=None,
             outfile=None):
    """
    Basic method to generate a Finder chart figure

    Args:
        image (np.ndarray):
          Image for the finder
        wcs (astropy.wcs.WCS):
          WCS solution
        title (str):
          TItle; typically the name of the primry source
        log_stretch (bool, optional):
            Use a log stretch for the image display
        cutout (tuple, optional):
            SkyCoord (center coordinate) and Quantity (image angular size)
            for a cutout from the input image.
        primary_coord (astropy.coordinates.SkyCoord, optional):
          If provided, place a mark in red at this coordinate
        secondary_coord (astropy.coordinates.SkyCoord, optional):
          If provided, place a mark in cyan at this coordinate
          Assume it is an offset star (i.e. calculate offsets)
        third_coord (astropy.coordinates.SkyCoord, optional):
          If provided, place a mark in yellow at this coordinate
        vmnx (tuple, optional):
          Used for scaling the image.  Otherwise, the image
          is analyzed for these values.
        outfile (str, optional):
          Filename for the figure.  File type will be according
          to the extension

    Returns:
        matplotlib.pyplot.figure, matplotlib.pyplot.Axis

    """

    utils.set_mplrc()

    plt.clf()
    fig = plt.figure(dpi=600)
    fig.set_size_inches(7.5, 10.5)

    # Cutout?
    if cutout is not None:
        cutout_img = Cutout2D(image, cutout[0], cutout[1], wcs=wcs)
        # Overwrite
        wcs = cutout_img.wcs
        image = cutout_img.data

    # Axis
    ax = fig.add_axes([0.10, 0.20, 0.80, 0.5], projection=wcs)

    # Show
    if log_stretch:
        norm = mplnorm.ImageNormalize(stretch=LogStretch())
    else:
        norm = None
    cimg = ax.imshow(image, cmap='Greys', norm=norm)

    # Flip so RA increases to the left
    ax.invert_xaxis()

    # N/E
    overlay = ax.get_coords_overlay('icrs')

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

    overlay['ra'].set_axislabel('Right Ascension')
    overlay['dec'].set_axislabel('Declination')

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

    # Contrast
    if vmnx is None:
        mean, median, stddev = sigma_clipped_stats(
            image
        )  # Also set clipping level and number of iterations here if necessary
        #
        vmnx = (median - stddev, median + 2 * stddev
                )  # sky level - 1 sigma and +2 sigma above sky level
        print("Using vmnx = {} based on the image stats".format(vmnx))
    cimg.set_clim(vmnx[0], vmnx[1])

    # Add Primary
    if primary_coord is not None:
        c = SphericalCircle((primary_coord.ra, primary_coord.dec),
                            2 * units.arcsec,
                            transform=ax.get_transform('icrs'),
                            edgecolor='red',
                            facecolor='none')
        ax.add_patch(c)
        # Text
        jname = ltu.name_from_coord(primary_coord)
        ax.text(0.5,
                1.34,
                jname,
                fontsize=28,
                horizontalalignment='center',
                transform=ax.transAxes)

    # Secondary
    if secondary_coord is not None:
        c_S1 = SphericalCircle((secondary_coord.ra, secondary_coord.dec),
                               2 * units.arcsec,
                               transform=ax.get_transform('icrs'),
                               edgecolor='cyan',
                               facecolor='none')
        ax.add_patch(c_S1)
        # Text
        jname = ltu.name_from_coord(secondary_coord)
        ax.text(0.5,
                1.24,
                jname,
                fontsize=22,
                color='blue',
                horizontalalignment='center',
                transform=ax.transAxes)
        # Print offsets
        if primary_coord is not None:
            sep = primary_coord.separation(secondary_coord).to('arcsec')
            PA = primary_coord.position_angle(secondary_coord)
            # RA/DEC
            dec_off = np.cos(PA) * sep  # arcsec
            ra_off = np.sin(PA) * sep  # arcsec (East is *higher* RA)
            ax.text(0.5,
                    1.14,
                    'RA(to targ) = {:.2f}  DEC(to targ) = {:.2f}'.format(
                        -1 * ra_off.to('arcsec'), -1 * dec_off.to('arcsec')),
                    fontsize=18,
                    horizontalalignment='center',
                    transform=ax.transAxes)
    # Add tertiary
    if third_coord is not None:
        c = SphericalCircle((third_coord.ra, third_coord.dec),
                            2 * units.arcsec,
                            transform=ax.get_transform('icrs'),
                            edgecolor='yellow',
                            facecolor='none')
        ax.add_patch(c)
    # Slit?
    '''
    if slit is not None:
        r = Rectangle((primary_coord.ra.value, primary_coord.dec.value),
                      slit[0]/3600., slit[1]/3600., angle=360-slit[2],
                      transform=ax.get_transform('icrs'),
                      facecolor='none', edgecolor='red')
        ax.add_patch(r)
    '''
    # Title
    ax.text(0.5,
            1.44,
            title,
            fontsize=32,
            horizontalalignment='center',
            transform=ax.transAxes)

    # Sources
    # Labels
    #ax.set_xlabel(r'\textbf{DEC (EAST direction)}')
    #ax.set_ylabel(r'\textbf{RA (SOUTH direction)}')

    if outfile is not None:
        plt.savefig(outfile)
        plt.close()
    else:
        plt.show()

    # Return
    return fig, ax
def produce_postage_stamps_new(row_dict, askap_data, askap_wcs, mos_data, mos_wcs, askap_extractions, cat_extractions, askap_pre_convolve_catalog, radius=13./60., contrast=0.2,
                            convolve=False, askap_nonconv_data=None, askap_nonconv_wcs=None, basecat="sumss"):
    #For now support one ASKAP image at a time so can just take this from the first entry.

    #First initialise the figure and set up the askap panel with the image.
    radius = Angle(radius * u.arcmin)
    if convolve:
        total_panels = 3
    else:
        total_panels = 2
    panels={}
    other={"sumss":"nvss", "nvss":"sumss"}
    fig = plt.figure(figsize=(18, 8))
    thissurvey = row_dict["survey_used"].upper()

    target = SkyCoord(row_dict["master_ra"]*u.degree, row_dict["master_dec"]*u.degree)
    askap_cutout = Cutout2D(askap_data, position=target, size=radius, wcs=askap_wcs, mode='partial')
    mos_cutout = Cutout2D(mos_data, position=target, size=radius, wcs=mos_wcs, mode='partial')
    if convolve:
        askap_nonconv_cutout = Cutout2D(askap_nonconv_data, position=target, size=radius, wcs=askap_nonconv_wcs, mode='partial')

    askap_norm = ImageNormalize(askap_cutout.data, interval=ZScaleInterval(contrast=contrast))
    mos_norm = ImageNormalize(mos_cutout.data, interval=ZScaleInterval(contrast=contrast))
    if convolve:
        askap_nonconv_norm = ImageNormalize(askap_nonconv_cutout.data, interval=ZScaleInterval(contrast=contrast))

    panels[1] = fig.add_subplot(1,total_panels,1, projection=mos_cutout.wcs)
    panels[2] = fig.add_subplot(1,total_panels,2, projection=askap_cutout.wcs)
    if convolve:
        panels[3] = fig.add_subplot(1,total_panels,3, projection=askap_nonconv_cutout.wcs)

    panels[1].imshow(mos_cutout.data,norm=mos_norm,cmap='gray_r')
    panels[2].imshow(askap_cutout.data,norm=askap_norm,cmap='gray_r')
    if convolve:
        panels[3].imshow(askap_nonconv_cutout.data,norm=askap_nonconv_norm,cmap='gray_r')

    asp = np.diff(panels[1].get_xlim())[0] / np.diff(panels[1].get_ylim())[0]

    asp /= np.abs(np.diff(panels[2].get_xlim())[0] / np.diff(panels[2].get_ylim())[0])

    panels[1].set_aspect(asp)

    # if convolve:
        # panels[3].set_aspect(asp)

    for i in panels:
        panels[i].set_autoscale_on(False)

    askap_collection = create_ellipses(askap_extractions, askap_cutout.wcs, "#1f77b4")

    if convolve:
        askap_nonconv_collection = create_ellipses(askap_pre_convolve_catalog, askap_cutout.wcs, "#11BA1C")
        askap_nonconv_collection_2 = create_ellipses(askap_pre_convolve_catalog, askap_cutout.wcs, "#11BA1C")
        askap_collection_2 = create_ellipses(askap_extractions, askap_cutout.wcs, "#1f77b4")
    else:
        askap_nonconv_collection = None
        askap_nonconv_collection_2 = None
        askap_collection_2 = None

    askap_catalog_collection = create_ellipses(cat_extractions, askap_cutout.wcs, "#d62728")

    catalog_askap_collection = create_ellipses(askap_extractions, mos_cutout.wcs, "#1f77b4")

    if convolve:
        catalog_askap_nonconv_collection = create_ellipses(askap_pre_convolve_catalog, mos_cutout.wcs, "#11BA1C")
        askap_catalog_collection_2 = create_ellipses(cat_extractions, askap_cutout.wcs, "#d62728")
    else:
        catalog_askap_nonconv_collection = None
        catalog_askap_nonconv_collection_2 = None
        askap_catalog_collection_2 = None

    catalog_collection = create_ellipses(cat_extractions, mos_cutout.wcs, "#d62728")

    #Ellipes loading
    panels[1].add_collection(catalog_collection, autolim=False)
    panels[1].add_collection(catalog_askap_collection, autolim=False)

    panels[2].add_collection(askap_collection, autolim=False)
    panels[2].add_collection(askap_catalog_collection, autolim=False)

    if convolve:
        panels[1].add_collection(catalog_askap_nonconv_collection, autolim=False)
        panels[2].add_collection(askap_nonconv_collection, autolim=False)
        panels[3].add_collection(askap_catalog_collection_2, autolim=False)
        panels[3].add_collection(askap_collection_2, autolim=False)
        panels[3].add_collection(askap_nonconv_collection_2, autolim=False)


    bbox_dict=dict(boxstyle="round", ec="white", fc="white", alpha=0.8)

    # if not pd.isna(filtered_cross_matches.iloc[0]["master_catalog_Mosaic_rms"]):
    #     image_rms = filtered_cross_matches.iloc[0]["master_catalog_Mosaic_rms"]
    # else:
    #     image_rms = filtered_cross_matches.iloc[0]["catalog_Mosaic_rms"]

    #Now begin the main loop per source
    # debug_num=0
    if row_dict["type"] == "match":
        askap_title = "RACS "+row_dict["askap_name"]
        if np.isnan(row_dict["aegean_convolved_int_flux"]) and convolve:
            askap_title_2 = "RACS "+row_dict["askap_non_conv_name"]
        else:
            askap_title_2 = "RACS" + row_dict["askap_name"]
        sumss_title = "{} {}".format(thissurvey, row_dict["master_name"])
        recentre_ra=row_dict["master_ra"]
        recentre_dec=row_dict["master_dec"]

    elif row_dict["type"] == "noaskapmatch":
        askap_title = "RACS (Convolved)"
        askap_title_2 = "RACS (Non-Convolved)"
        sumss_title = "{} {}".format(thissurvey, row_dict["master_name"])
        recentre_ra=row_dict["master_ra"]
        recentre_dec=row_dict["master_dec"]
    elif row_dict["type"] == "nocatalogmatch":
        askap_title = "RACS "+row_dict["askap_name"]
        if convolve:
            askap_title_2 = "RACS "+row_dict["askap_non_conv_name"]
        sumss_title = "{} ({})".format(thissurvey, row_dict["master_catalog_mosaic"])
        recentre_ra=row_dict["askap_ra"]
        recentre_dec=row_dict["askap_dec"]

    panels[1].set_title(sumss_title)
    panels[2].set_title(askap_title)
    if convolve:
        panels[3].set_title(askap_title_2)

    #Centre each image on the ASKAP coordinates for clarity
    if convolve:
        pos_x_1 = 0.41
        pos_y_1 = 0.68
        pos_x_2 = 0.14
        pos_y_2 = 0.27
        pos_x_3 = 0.07
        pos_y_3 = 0.12
        pos_x_4 = 0.65
        pos_x_5 = 0.68
        pos_y_5 = 0.27
        size=15
        boxsize = 10
    else:
        pos_x_1 = 0.57
        pos_y_1 = 0.75
        pos_x_2 = 0.14
        pos_y_2 = 0.14
        pos_x_3 = 0.02
        pos_y_3 = 0.02
        pos_x_4 = 0.8
        size = 18
        boxsize = 14


    for i in panels:
        lon = panels[i].coords[0]
        lat = panels[i].coords[1]
        if i==1:
            lon.set_axislabel('RA', size=size)
            lat.set_axislabel('Dec.', size=size)
            lon.set_ticklabel(size=12)
            lat.set_ticklabel(size=12)
        else:
            lon.set_ticklabel_visible(False)
            lat.set_ticklabel_visible(False)
            lon.set_axislabel('')
            lat.set_axislabel('')

    image_rms = row_dict["master_catalog_Mosaic_rms"]
    snr_col = "{0}_{0}_snr".format(thissurvey.lower())

    if row_dict["type"] == "match":
        for p in panels:
            r = SphericalCircle((target.ra, target.dec), 1. * u.arcmin, edgecolor='C9', facecolor='none', transform=panels[p].get_transform('fk5'), linewidth=3)
            panels[p].add_patch(r)
            askap_target = SkyCoord(row_dict["askap_ra"]*u.degree, row_dict["askap_dec"]*u.degree)
            r = SphericalCircle((askap_target.ra, askap_target.dec), 1. * u.arcmin, edgecolor='C1', facecolor='none', transform=panels[p].get_transform('fk5'), linewidth=3)
            panels[p].add_patch(r)
            if p==2:
                sep_text=plt.text(pos_x_3, pos_y_3, "Distance Separation = {:.2f} arcsec".format(row_dict["d2d"]), transform=fig.transFigure, size=size)
                ratio_text=plt.text(pos_x_4, pos_y_3, "Scaled Int. Flux Ratio = {:.2f} +/- {:.2f}".format(row_dict["master_ratio"], row_dict["master_ratio_err"]), transform=fig.transFigure, size=size)
                askap_snr_text=plt.text(pos_x_1, pos_y_2, "ASKAP Int. Flux = {:.2f} +/- {:.2f} mJy\nASKAP Image RMS ~ {:.2f} mJy\nASKAP Local RMS ~ {:.2f} mJy".format(row_dict["askap_flux_to_use"]*1.e3,
                    row_dict["askap_flux_to_use_err"]*1.e3, row_dict["askap_rms"]*1.e3, row_dict["measured_askap_local_rms"]*1.e3), transform=fig.transFigure, bbox=bbox_dict, size=boxsize)
                sumss_snr_text=plt.text(pos_x_2, pos_y_2, "{0} Int. Flux = {1:.2f} +/- {2:.2f} mJy\n{0} RMS ~ {3:.2f} mJy\n{0} SNR = {4:.2f}".format(thissurvey,
                    row_dict["catalog_flux_to_use"]*1.e3,row_dict["catalog_flux_to_use_err"]*1.e3,image_rms*1.e3, row_dict[snr_col]), transform=fig.transFigure, bbox=bbox_dict, size=boxsize)
                if convolve:
                    askap_snr_text_preconv=plt.text(pos_x_5, pos_y_2, "ASKAP Int. Flux = {:.2f} +/- {:.2f} mJy\nASKAP Image RMS ~ {:.2f} mJy\nASKAP Local RMS ~ {:.2f} mJy".format(row_dict["askap_flux_to_use_2"]*1.e3,
                        row_dict["askap_flux_to_use_2_err"]*1.e3, row_dict["askap_rms_preconv"]*1.e3, row_dict["measured_preconv_askap_local_rms"]*1.e3), transform=fig.transFigure, bbox=bbox_dict, size=boxsize)
                    custom_lines = [Line2D([0], [0], color="w", marker="o", fillstyle="none", lw=2, markeredgecolor='#1f77b4', linestyle="none"),
                                    Line2D([0], [0], color="w", marker="o", fillstyle="none", lw=2, markeredgecolor='#d62728', linestyle="none"),
                                    Line2D([0], [0], color="w", markeredgecolor='#11BA1C', marker="o", fillstyle="none", lw=2, linestyle="none"),
                                    Line2D([0], [0], color="w", markeredgecolor='C9', marker="o", fillstyle="none", lw=2, linestyle="none"),
                                    Line2D([0], [0], color='C1'),
                                    Line2D([0], [0], color='C9')
                                ]
                    labels = ["ASKAP Sources", "{} Sources".format(basecat.upper()), "Non-conv ASKAP sources", "Extracted Flux", "ASKAP Source Position", thissurvey+" Source Position"]
                else:
                    custom_lines = [Line2D([0], [0], color="w", marker="o", fillstyle="none", lw=2, markeredgecolor='#1f77b4', linestyle="none"),
                                    Line2D([0], [0], color="w", marker="o", fillstyle="none", lw=2, markeredgecolor='#d62728', linestyle="none"),
                                    Line2D([0], [0], color="w", markeredgecolor='C9', marker="o", fillstyle="none", lw=2, linestyle="none"),
                                    Line2D([0], [0], color='C1'),
                                    Line2D([0], [0], color='C9')
                                ]
                    labels = ["ASKAP Sources", "{} Sources".format(basecat.upper()), "Extracted Flux", "ASKAP Source Position", thissurvey+" Source Position"]

    elif row_dict["type"] == "noaskapmatch":
        for p in panels:
            r = SphericalCircle((target.ra, target.dec), 1. * u.arcmin, edgecolor='C9', facecolor='none', transform=panels[p].get_transform('fk5'), linewidth=3)
            panels[p].add_patch(r)
            if p==1:
                ratio_text=plt.text(pos_x_4, pos_y_3, "Scaled Int. Flux Ratio = {:.2f} +/- {:.2f}".format(row_dict["master_ratio"], row_dict["master_ratio_err"]), transform=fig.transFigure, size=size)
            if convolve:
                if p==2:
                    r = SphericalCircle((target.ra, target.dec), 22.5 * u.arcsec, edgecolor='C1', facecolor='none', transform=panels[p].get_transform('fk5'), linewidth=1)
                    panels[p].add_patch(r)
                if p==3:
                    r = SphericalCircle((target.ra, target.dec), 7. * u.arcsec, edgecolor='C1', facecolor='none', transform=panels[p].get_transform('fk5'), linewidth=1)
                    panels[p].add_patch(r)
                if p==1:
                    askap_snr_text=plt.text(pos_x_1, pos_y_2, "ASKAP Measured Int. Flux = {:.2f} mJy +/- {:.2f} \nASKAP Image RMS ~ {:.2f} mJy\nASKAP Local RMS ~ {:.2f} mJy".format(row_dict["askap_flux_to_use"]*1.e3,
                        row_dict["askap_flux_to_use_err"]*1.e3, row_dict["askap_rms"]*1.e3, row_dict["measured_askap_local_rms"]*1.e3), transform=fig.transFigure, bbox=bbox_dict, size=boxsize)
                    askap_snr_text_preconv=plt.text(pos_x_5, pos_y_2, "ASKAP Measured Int. Flux = {:.2f} +/- {:.2f} mJy\nASKAP Image RMS ~ {:.2f} mJy\nASKAP Local RMS ~ {:.2f} mJy".format(row_dict["askap_flux_to_use_2"]*1.e3,
                        row_dict["askap_flux_to_use_2_err"]*1.e3, row_dict["askap_rms_preconv"]*1.e3, row_dict["measured_preconv_askap_local_rms"]*1.e3), transform=fig.transFigure, bbox=bbox_dict, size=boxsize)
                    custom_lines = [Line2D([0], [0], color="w", marker="o", fillstyle="none", lw=2, markeredgecolor='#1f77b4'),
                                    Line2D([0], [0], color="w", marker="o", fillstyle="none", lw=2, markeredgecolor='#d62728'),
                                    Line2D([0], [0], color="w", markeredgecolor='#11BA1C', marker="o", fillstyle="none", lw=2),
                                    Line2D([0], [0], color="w", markeredgecolor='C9', marker="o", fillstyle="none", lw=2),
                                    Line2D([0], [0], color='C1')
                                ]
                    labels = ["ASKAP Sources", "{} Sources".format(thissurvey), "Non-conv ASKAP sources", "Extracted Flux", thissurvey+" Source Position"]
            else:
                if p==2:
                    r = SphericalCircle((target.ra, target.dec), 7. * u.arcsec, edgecolor='C1', facecolor='none', transform=panels[p].get_transform('fk5'), linewidth=1)
                    panels[p].add_patch(r)
                if p==1:
                    askap_snr_text=plt.text(pos_x_1, pos_y_2, "ASKAP Measured Int. Flux = {:.2f} +/- {:.2f} mJy\nASKAP Image RMS ~ {:.2f} mJy\nASKAP Local RMS ~ {:.2f} mJy".format(row_dict["askap_flux_to_use"]*1.e3,
                        row_dict["askap_flux_to_use_err"]*1.e3, row_dict["askap_rms"]*1.e3, row_dict["measured_askap_local_rms"]*1.e3), transform=fig.transFigure, bbox=bbox_dict, size=boxsize)
                    custom_lines = [Line2D([0], [0], color="w", marker="o", fillstyle="none", lw=2, markeredgecolor='#1f77b4'),
                                    Line2D([0], [0], color="w", marker="o", fillstyle="none", lw=2, markeredgecolor='#d62728'),
                                    Line2D([0], [0], color="w", markeredgecolor='C9', marker="o", fillstyle="none", lw=2),
                                    Line2D([0], [0], color='C1')
                                ]
                    labels = ["ASKAP Sources", "{} Sources".format(thissurvey), "Extracted Flux", thissurvey+" Source Position"]
            if p==1:
                sumss_snr_text=plt.text(pos_x_2, pos_y_2, "{0} Int. Flux = {1:.2f} +/- {2:.2f} mJy\n{0} RMS ~ {3:.2f} mJy\n{0} SNR = {4:.2f}".format(thissurvey,
                    row_dict["catalog_flux_to_use"]*1.e3, row_dict["catalog_flux_to_use_err"]*1.e3,image_rms*1.e3, row_dict[snr_col]), transform=fig.transFigure, bbox=bbox_dict, size=boxsize)
        #Rectangle on extracted flux on ASKAP images
        # x_size,y_size=_get_extracted_rectangle_size(panels[1], recentre_ra, recentre_dec, 10)
        # panels[1].show_rectangles([recentre_ra], [recentre_dec], x_size, y_size, color='C1', linewidth=1, label="Extracted Flux", layer="Extracted Flux")
        # if convolve:
        #     x_size,y_size=_get_extracted_rectangle_size(panels[2], recentre_ra, recentre_dec, 10)
        #     panels[2].show_rectangles([recentre_ra], [recentre_dec], x_size, y_size, color='C1', linewidth=1, label="Extracted Flux", layer="Extracted Flux")

    elif row_dict["type"] == "nocatalogmatch":
        for p in panels:
            r = SphericalCircle((target.ra, target.dec), 1. * u.arcmin, edgecolor='C1', facecolor='none', transform=panels[p].get_transform('fk5'), linewidth=3)
            panels[p].add_patch(r)
            if p==1:
                ratio_text=plt.text(pos_x_4, pos_y_3, "Scaled Int. Flux Ratio = {:.2f} +/- {:.2f}".format(row_dict["master_ratio"], row_dict["master_ratio_err"]), transform=fig.transFigure, size=size)
                #Put a rectangle to show extracted peak flux measurement
                # x_size,y_size=_get_extracted_rectangle_size(panels[0], recentre_ra, recentre_dec, 5)
                r = SphericalCircle((target.ra, target.dec), 22.5 * u.arcsec, edgecolor='C9', facecolor='none', transform=panels[p].get_transform('fk5'), linewidth=1)
                panels[p].add_patch(r)
                askap_snr_text=plt.text(pos_x_1, pos_y_2, "ASKAP Int. Flux = {:.2f} +/- {:.2f} mJy\nASKAP Image RMS ~ {:.2f} mJy\nASKAP Local RMS ~ {:.2f} mJy".format(row_dict["askap_flux_to_use"]*1.e3,
                    row_dict["askap_flux_to_use_err"]*1.e3,row_dict["askap_rms"]*1.e3, row_dict["measured_askap_local_rms"]*1.e3), transform=fig.transFigure, bbox=bbox_dict, size=boxsize)
                if convolve:
                    askap_snr_text_preconv=plt.text(pos_x_5, pos_y_2, "ASKAP Int. Flux = {:.2f} +/- {:.2f} mJy\nASKAP Image RMS ~ {:.2f} mJy\nASKAP Local RMS ~ {:.2f} mJy".format(row_dict["askap_flux_to_use_2"]*1.e3,
                        row_dict["askap_flux_to_use_2_err"]*1.e3,row_dict["askap_rms_preconv"]*1.e3, row_dict["measured_preconv_askap_local_rms"]*1.e3), transform=fig.transFigure, bbox=bbox_dict, size=boxsize)
                    custom_lines = [Line2D([0], [0], color="w", marker="o", fillstyle="none", lw=2, markeredgecolor='#1f77b4'),
                                    Line2D([0], [0], color="w", marker="o", fillstyle="none", lw=2, markeredgecolor='#d62728'),
                                    Line2D([0], [0], color="w", markeredgecolor='#11BA1C', marker="o", fillstyle="none", lw=2),
                                    Line2D([0], [0], color="w", markeredgecolor='C9', marker="o", fillstyle="none", lw=2),
                                    Line2D([0], [0], color='C9')
                                ]
                    labels = ["ASKAP Sources", "{} Sources".format(basecat.upper()), "Non-conv ASKAP sources", "Extracted Flux", "ASKAP Source Position"]
                else:
                    custom_lines = [Line2D([0], [0], color="w", marker="o", fillstyle="none", lw=2, markeredgecolor='#1f77b4'),
                                    Line2D([0], [0], color="w", marker="o", fillstyle="none", lw=2, markeredgecolor='#d62728'),
                                    Line2D([0], [0], color="w", markeredgecolor='C9', marker="o", fillstyle="none", lw=2),
                                    Line2D([0], [0], color='C9')
                                ]
                    labels = ["ASKAP Sources", "{} Sources".format(basecat.upper()), "Extracted Flux", "ASKAP Source Position"]
                sumss_snr_text=plt.text(pos_x_2, pos_y_2, "Measured {0} Int. Flux = {1:.2f} +/- {2:.2f} mJy\n{0} RMS ~ {3:.2f} mJy\n{0} SNR = {4:.2f}".format(thissurvey,
                    row_dict["catalog_flux_to_use"]*1.e3,row_dict["catalog_flux_to_use_err"]*1.e3,image_rms*1.e3, row_dict["catalog_flux_to_use"]/image_rms), transform=fig.transFigure, bbox=bbox_dict, size=boxsize)
            # panels[0].show_rectangles([recentre_ra], [recentre_dec], x_size, y_size, color='C1', linewidth=1, label="Extracted Flux", layer="Extracted Flux")
    #         #
    #         # if skip:
    #         #     continue
            #
    figname = "source_{}_postagestamps.jpg".format(row_dict["master_name"])

    if convolve:
        panels[3].legend(custom_lines,  labels, fontsize=10, loc=1)
    else:
        panels[2].legend(custom_lines, labels, fontsize=14, loc=1)



    plt.savefig(figname, bbox_inches="tight")
    fig.clf()
    #plt.show()
    plt.close(fig)
    return
def image_plot(inputfile, d_range, imsize, outputfile):
    """Takes a scaled image in the form of a numpy array and plots it along with coordinates and a colorbar"""

    block = import_fits(inputfile, d_range)
    data = block[0]
    hrd = block[1]
    wcs = WCS(hrd)
    if hrd['TELESCOP'] != 'Spitzer':
        beam = Beam.from_fits_header(hrd)

    print(np.shape(data))
    norm = ImageNormalize(data,
                          interval=MinMaxInterval(),
                          stretch=SqrtStretch())

    figure = plt.figure(num=1)
    if wcs.pixel_n_dim == 4:
        ax = figure.add_subplot(111, projection=wcs, slices=('x', 'y', 0, 0))
    elif wcs.pixel_n_dim == 2:
        ax = figure.add_subplot(111, projection=wcs, slices=('x', 'y'))

    main_image = ax.imshow(X=data,
                           cmap='plasma',
                           origin='lower',
                           norm=norm,
                           vmax=np.max(data),
                           vmin=np.min(data))
    cbar = figure.colorbar(main_image)

    if hrd['TELESCOP'] == 'Spitzer':
        ax.invert_xaxis()
        ax.invert_yaxis()

    #position=SkyCoord('23h20m48s', '+61d12m06s', frame='icrs')
    #centre=wcs.world_to_pixel(position)
    dims = np.shape(data)
    centre = (dims[0] / 2., dims[1] / 2.)
    ax.set_xlim(centre[0] - imsize, centre[0] + imsize)
    ax.set_ylim(centre[1] - imsize, centre[1] + imsize)

    ax.set_xlabel('Right Ascension J2000', fontdict=font)
    ax.set_ylabel('Declination J2000', fontdict=font)
    cbar.set_label('Surface Brigthness (MJy/Sr)', fontdict=font)
    ra = ax.coords[0]
    ra.set_format_unit('degree', decimal=True)

    dec = ax.coords[1]
    dec.set_format_unit('degree', decimal=True)

    #ax.set_title('Spitzer 24\u03BCm', fontdict=font)
    ax.set_title('8-12 GHz, 5\u03C3 mask', fontdict=font)

    if hrd['TELESCOP'] != 'Spitzer':
        beam = Beam.from_fits_header(hrd)
        c = SphericalCircle((350.34, 61.13) * u.degree,
                            beam.major,
                            edgecolor='black',
                            facecolor='none',
                            transform=ax.get_transform('fk5'))
        ax.add_patch(c)

    if outputfile != False:
        plt.savefig(os.getcwd() + '/thesis_figs/' + outputfile)
    plt.show()
def make_plot(conf_ints,
              X,
              Y,
              title,
              conf_int,
              mode='radec',
              sigma_max=3,
              freq=1370 * u.MHz,
              t_arr=None,
              loc=None,
              cb_pos=None,
              src_pos=None):
    """
    Create plot of localisation area

    :param conf_ints: confidence interval grid
    :param X: RA or Az
    :param Y: Dec or Alt
    :param title: plot title
    :param conf_int: confidence interval to plot
    :param mode: radec or altaz (default radec)
    :param sigma_max: used to determine maximum value for colors in plot (default 3)
    :param freq: central frequency (default 1370 MHz)
    :param t_arr: burst arrival time (only required if mode is altaz)
    :param loc: legend location (optional)
    :param cb_pos: cb pointing (optional, tuple or list of tuples)
    :param src_pos: source position (tuple)
    :return: figure
    """
    if mode == 'altaz' and t_arr is None:
        logger.info("t_arr is required in AltAz mode")
    X = X.to(u.deg).value
    Y = Y.to(u.deg).value

    # best pos = point with lowest confidence interval
    ind = np.unravel_index(np.argmin(conf_ints), conf_ints.shape)
    best_x = X[ind]
    best_y = Y[ind]

    # init figure
    fig, ax = plt.subplots()

    # plot confidence interval
    img = ax.pcolormesh(X, Y, conf_ints, vmin=0, vmax=1, shading='nearest')
    cbar = fig.colorbar(img, ax=ax)
    cbar.set_label('Confidence interval', rotation=270, labelpad=15)

    # add contours
    ax.contour(X,
               Y,
               conf_ints, [conf_int],
               colors=['#FF0000', '#C00000', '#800000'])

    # add best position
    ax.plot(best_x,
            best_y,
            c='r',
            marker='.',
            ls='',
            ms=10,
            label='Best position')
    # add source position if available
    if src_pos is not None:
        if mode == 'altaz':
            ha_src, dec_src = tools.radec_to_hadec(*src_pos, t_arr)
            y_src, x_src = tools.hadec_to_altaz(ha_src, dec_src)
        else:
            x_src, y_src = src_pos
        ax.plot(x_src.to(u.deg).value,
                y_src.to(u.deg).value,
                c='cyan',
                marker='+',
                ls='',
                ms=10,
                label='Source position')
    # add CB position and circle if available
    if cb_pos is not None:
        if not isinstance(cb_pos, list):
            cb_pos = [cb_pos]
        for i, pos in enumerate(cb_pos):
            if mode == 'altaz':
                ha_cb, dec_cb = tools.radec_to_hadec(pos.ra, pos.dec, t_arr)
                y_cb, x_cb = tools.hadec_to_altaz(ha_cb, dec_cb)
            else:
                x_cb = pos.ra
                y_cb = pos.dec
            if i == 0:
                label = 'CB center'
            else:
                label = ''
            ax.plot(x_cb.to(u.deg).value,
                    y_cb.to(u.deg).value,
                    c='w',
                    marker='x',
                    ls='',
                    ms=10,
                    label=label)
            # add CB
            cb_radius = (CB_HPBW * REF_FREQ / freq / 2)
            patch = SphericalCircle((x_cb, y_cb),
                                    cb_radius,
                                    ec='k',
                                    fc='none',
                                    ls='-',
                                    alpha=.5)
            ax.add_patch(patch)

    # limit to localisation region
    ax.set_xlim(X[0, 0], X[-1, -1])
    ax.set_ylim(Y[0, 0], Y[-1, -1])

    # add labels
    if mode == 'altaz':
        ax.set_xlabel('Az (deg)')
        ax.set_ylabel('Alt (deg)')
    elif mode == 'radec':
        ax.set_xlabel('RA (deg)')
        ax.set_ylabel('Dec (deg)')
    ax.legend(loc=loc)
    ax.set_title(title)

    return fig
Beispiel #9
0
            transform=ax.get_transform('world'),
            s=20,
            label='Phase centres')
 ax.scatter(master_table[RA_column],
            master_table[Dec_column],
            transform=ax.get_transform('world'),
            s=2,
            label='Source positions')
 leg1 = ax.legend(loc='upper left', bbox_to_anchor=(1.01, 0.6))
 #ax.plot(df['RA'],df['DEC'],'-',transform=ax.get_transform('world'))
 #ax.set_xlim(pixels/-2.,pixels/2.)
 #ax.set_ylim(pixels/-2.,pixels/2.)
 for i in range(len(df['RA'])):
     r = SphericalCircle((df['RA'][i] * u.deg, df['DEC'][i] * u.deg),
                         phs_centre_fov * u.arcmin,
                         edgecolor='k',
                         facecolor='none',
                         transform=ax.get_transform('world'))
     ax.add_patch(r)
 if len(PB_plots) != 0:
     lst = cycle(['r', 'b', 'k', 'g'])
     ls2 = cycle(['--', '-.', ':'])
     custom_lines = []
     handles = []
     for i, j in enumerate(PB_plots):
         iter1 = next(lst)
         iter2 = next(ls2)
         PB_fov = ((c.c / freq) / j) * (180. / np.pi)
         print(PB_fov)
         r = SphericalCircle((float(pointing_centre[0]) * u.deg,
                              float(pointing_centre[1]) * u.deg),
Beispiel #10
0
def do_plot(ax,
            RA,
            DEC,
            dchi2,
            dof,
            cb_ra,
            cb_dec,
            freq,
            CONF_INT=.90,
            sigma_max=3,
            title=None,
            src_ra=None,
            src_dec=None,
            contour_ax=None):
    # best pos = point with lowest (delta)chi2
    ind = np.unravel_index(np.argmin(dchi2), dchi2.shape)
    best_ra = RA[ind]
    best_dec = DEC[ind]

    # convert CONF_INT to dchi2 value
    dchi2_contour_value = stats.chi2.ppf(CONF_INT, dof)

    # convert sigma_max to dchi2 value
    conf_int_max = stats.chi2.cdf(sigma_max**2, 1)
    dchi2_value_max = stats.chi2.ppf(conf_int_max, dof)

    # plot data with colorbar
    img = ax.pcolormesh(RA,
                        DEC,
                        dchi2,
                        vmax=min(dchi2.max(), dchi2_value_max),
                        shading='nearest')
    divider = make_axes_locatable(ax)
    cax = divider.append_axes('right', size='5%', pad=0.05)
    fig.colorbar(img, cax)

    # add contour
    c = ax.contour(RA, DEC, dchi2, [dchi2_contour_value], colors='r')
    # get points of contour
    try:
        points = np.concatenate(c.allsegs[0])
    except ValueError:
        points = None
    if contour_ax:
        # plot contour is this axis too
        contour_ax.contour(RA,
                           DEC,
                           dchi2, [dchi2_contour_value],
                           c=colormap,
                           label=title)
        next(cmap_list)

    # add best position
    ax.plot(best_ra,
            best_dec,
            c='r',
            marker='.',
            ls='',
            ms=10,
            label='Best position')

    # add source position
    if src_ra is not None and src_dec is not None:
        ax.plot(src_ra,
                src_dec,
                c='cyan',
                marker='+',
                ls='',
                ms=10,
                label='Source position')

    # add cb position(s)
    cb_radius = .5 * CB_HPBW * REF_FREQ / freq
    if isinstance(cb_ra, float):
        cb_pos = np.array([[cb_ra, cb_dec]])
    else:
        cb_pos = np.transpose([cb_ra, cb_dec])

    for i, (ra, dec) in enumerate(cb_pos):
        # set label once
        if i == 0:
            label = 'CB center'
        else:
            label = ''
        ax.plot(ra, dec, c='k', marker='x', ls='', ms=10, label=label)

        # add CB size
        patch = SphericalCircle((ra * u.deg, dec * u.deg),
                                cb_radius,
                                ec='k',
                                fc='none',
                                ls='-',
                                alpha=.5)
        ax.add_patch(patch)

    # labels
    ax.set_xlabel('Right Ascension (deg)')
    ax.set_ylabel('Declination (deg)')
    ax.set_title(title)
    # ax.legend()

    return points
Beispiel #11
0
    def do_plot(ha0=0 * u.deg, dec0=0 * u.deg, parang=0 * u.deg):
        # store coordinates of CB00
        ra0 = lst - ha0
        alt0, az0 = tools.hadec_to_altaz(ha0, dec0)
        # plot CBs
        for cb, (dra, ddec) in enumerate(cb_pos):
            # RADec
            # pointing of this CB
            ra, dec = tools.offset_to_coord(ra0, dec0, dra, ddec)

            _ra = ra.to(u.deg).value
            _dec = dec.to(u.deg).value

            # plot
            patch = SphericalCircle((ra, dec), cb_radius,
                                    ec='k', fc='none', ls='-', alpha=.5)
            ax.add_patch(patch)
            ax.text(_ra, _dec, f'CB{cb:02d}', va='center', ha='center',
                    fontdict=font, clip_on=True)

            # AltAz
            ha = lst - ra
            alt, az = tools.hadec_to_altaz(ha, dec)
            dalt = alt - alt0
            daz = az - az0

            _alt = alt.to(u.deg).value
            _az = az.to(u.deg).value

            # plot
            patch = SphericalCircle((az, alt), cb_radius,
                                    ec='k', fc='none', ls='-', alpha=.5)
            ax2.add_patch(patch)
            ax2.text(_az, _alt, f'CB{cb:02d}', va='center', ha='center',
                     fontdict=font, clip_on=True)

        # plot SBs
        for cb in beams.keys():
            cb_dra, cb_ddec = cb_offsets[cb] * 60  # to arcmin
            for sb in beams[cb]:
                # SB increases towards higher RA
                sb_offset = (sb - 35) * sb_separation

                # draw line from (x, -y) to (x, y)
                # but the apply rotation by parallactic angle
                # in altaz:
                # x = +/-sb_offset, depending on azimuth:
                # higher SB = higher RA = East = either lower or higher Az
                # assume we are pointing above NCP if North
                if az0 > 270 * u.deg or az0 < 90 * u.deg:
                    sgn = 1
                else:
                    sgn = -1

                # alt az of this cb
                cb_shift_az = 0
                cb_shift_alt = 0

                # y = +/- length of line a sb_offset from center of CB
                dy = np.sqrt(cb_radius ** 2 - sb_offset ** 2)
                # alt start and end point
                alts = alt0 + dy + cb_shift_alt
                alte = alt0 - dy + cb_shift_alt
                # az start and end point
                azs = az0 + sgn * sb_offset / np.cos(alts) + cb_shift_az
                aze = az0 + sgn * sb_offset / np.cos(alte) + cb_shift_az

                # convert to HA, Dec
                has, decs = tools.altaz_to_hadec(alts, azs)
                hae, dece = tools.altaz_to_hadec(alte, aze)
                # convert HA to RA
                ras = lst - has
                rae = lst - hae

                # plot in RADec
                x = [ras.to(u.deg).value, rae.to(u.deg).value]
                y = [decs.to(u.deg).value, dece.to(u.deg).value]

                ax.plot(x, y, c='b')
                # add text above lines
                ax.text(np.mean(x), np.mean(y), f"SB{sb:02d}", va='center', ha='center')

                # plot in AltAz
                x = [azs.to(u.deg).value, aze.to(u.deg).value]
                y = [alts.to(u.deg).value, alte.to(u.deg).value]

                ax2.plot(x, y, c='b')
                # add text above lines
                ax2.text(np.mean(x), np.mean(y), f"SB{sb:02d}", va='center', ha='center')

                # polar
                # theta_start = np.arctan2(dy, sb_offset)
                # theta_end = np.arctan2(-dy, sb_offset)

                # apply parallactic angle rotation
                # works positive in HA space, but negative in RA space
                # theta_start -= parang.to(u.radian).value
                # theta_end -= parang.to(u.radian).value

                # start and end in cartesian coordinates
                # shift to correct CB and position
                # xstart = cb_radius * np.cos(theta_start) + cb_dra
                # ystart = cb_radius * np.sin(theta_start) + cb_ddec
                # xend = cb_radius * np.cos(theta_end) + cb_dra
                # yend = cb_radius * np.sin(theta_end) + cb_ddec

                # plot RA Dec
                # ax.plot((xstart, xend), (ystart, yend), c='b')
                # add text above lines
                # ax.text(np.mean([xstart, xend]), np.mean([ystart, yend]),  "SB{:02d}".format(sb),  va='center', ha='center')

                # continue
                # plot Alt Az
                # ystart, xstart = tools.hadec_to_altaz(ha0-xstart*u.arcmin, dec0+ystart*u.arcmin)
                # yend, xend = tools.hadec_to_altaz(ha0-xend*u.arcmin, dec0+yend*u.arcmin)
                # subtract center and remove cosine correction
                # #xstart = (xstart - az0).to(u.arcmin).value
                # #xend = (xend - az0).to(u.arcmin).value
                # #ystart = (ystart - alt0).to(u.arcmin).value
                # #yend = (yend - alt0).to(u.arcmin).value
                # xstart = xstart.to(u.arcmin).value
                # xend = xend.to(u.arcmin).value
                # ystart = ystart.to(u.arcmin).value
                # yend = yend.to(u.arcmin).value

        # set limits
        x = ra0.to(u.deg).value
        y = dec0.to(u.deg).value
        ax.set_xlim(x - 130 / 60., x + 130 / 60.)
        ax.set_ylim(y - 100 / 60., y + 100 / 60.)
        ax.set_xlabel('RA (deg)')
        ax.set_ylabel('Dec (deg)')
        ax.set_title('RA - Dec')

        x = az0.to(u.deg).value
        y = alt0.to(u.deg).value
        ax2.set_xlim(x - 130 / 60., x + 130 / 60.)
        ax2.set_ylim(y - 100 / 60., y + 100 / 60.)
        ax2.set_xlabel('Az (deg)')
        ax2.set_ylabel('Alt (deg)')
        ax2.set_title('Alt - Az')
Beispiel #12
0
def sub_image(fig, hdu, FRB, img_center=None,
              imsize=30*units.arcsec, vmnx = (None,None),
              xyaxis=(0.15, 0.15, 0.8, 0.8), fsz=15.,
              tick_spacing=None, invert=False,
              cmap='Blues', cclr='red'):
    """

    Args:
        fig:
        hdu:
        FRB:
        img_center:
        imsize:
        vmnx:
        xyaxis:
        fsz:
        tick_spacing:
        invert:
        cmap:
        cclr:

    Returns:

    """

    header = hdu[0].header
    hst_uvis = hdu[0].data

    size = units.Quantity((imsize, imsize), units.arcsec)
    if img_center is None:
        img_center = FRB.coord

    cutout = Cutout2D(hst_uvis, img_center, size, wcs=WCS(header))

    axIMG = fig.add_axes(xyaxis, projection=cutout.wcs)

    lon = axIMG.coords[0]
    lat = axIMG.coords[1]
    #lon.set_ticks(exclude_overlapping=True)
    lon.set_major_formatter('hh:mm:ss.s')
    if tick_spacing is not None:
        lon.set_ticks(spacing=tick_spacing)
        lat.set_ticks(spacing=tick_spacing)
    lon.display_minor_ticks(True)
    lat.display_minor_ticks(True)
    #
    blues = plt.get_cmap(cmap)
    d = axIMG.imshow(cutout.data, cmap=blues, vmin=vmnx[0], vmax=vmnx[1])
    plt.grid(color='gray', ls='dashed')
    axIMG.set_xlabel(r'\textbf{Right Ascension (J2000)}', fontsize=fsz)
    axIMG.set_ylabel(r'\textbf{Declination (J2000)}', fontsize=fsz, labelpad=-1.)
    if invert:
        axIMG.invert_xaxis()

    c = SphericalCircle((FRB.coord.ra, FRB.coord.dec),
                        FRB.eellipse['a']*units.arcsec, transform=axIMG.get_transform('icrs'),
                        edgecolor=cclr, facecolor='none')
    axIMG.add_patch(c)

    '''
    ylbl = 0.05
    axHST.text(0.05, ylbl, r'\textbf{HST/UVIS}', transform=axIMG.transAxes,
               fontsize=isz, ha='left', color='black')
    '''
    utils.set_fontsize(axIMG, 15.)

    return cutout, axIMG
Beispiel #13
0
w = generate_central_wcs([c.ra.deg, c.dec.deg], [1 / 60, 1 / 60], [1, 1])

fig = plt.figure(1, figsize=(9, 9))
ax = fig.add_subplot(111, projection=w)
ax.scatter(df['RA'],
           df['DEC'],
           c='k',
           s=2,
           transform=ax.get_transform('world'))
#ax.scatter(t['RA'],t['DEC'],transform=ax.get_transform('world'),s=1)

for i, j in enumerate(df.RANGE):
    if i == 0:
        label = r'Phase centre ($10\%$ smearing)'
    else:
        label = ''
    r = SphericalCircle((df.RA[i] * u.deg, df.DEC[i] * u.deg),
                        j / 2. * u.degree,
                        edgecolor='k',
                        facecolor='none',
                        ls='--',
                        transform=ax.get_transform('world'),
                        label=label)
    ax.add_patch(r)
ax.set_ylabel('Declination (J2000)')
ax.set_xlabel('Right Ascension (J2000)')
fig.savefig('%s/mosaic_pointings.pdf' % inputs['output_path'])

# In[ ]:
Beispiel #14
0
    def plot(self,
             title='',
             cblabel='',
             sources=True,
             time=None,
             filename=None,
             circle=None,
             **kwargs):
        """
        """
        if 'cmap' not in kwargs.keys():
            kwargs['cmap'] = 'YlGnBu_r'
        if 'vmin' not in kwargs.keys():
            kwargs['vmin'] = self.image.min()
        if 'vmax' not in kwargs.keys():
            kwargs['vmax'] = self.image.max()

        cbar = True
        if 'cbar' in kwargs.keys():
            cbar = kwargs['cbar']
            del kwargs['cbar']

        import matplotlib.pyplot as plt
        from matplotlib.colorbar import ColorbarBase
        from matplotlib.ticker import LinearLocator
        from matplotlib.colors import Normalize
        from matplotlib.cm import get_cmap
        from mpl_toolkits.axes_grid1.inset_locator import inset_axes
        from astropy.visualization.wcsaxes import SphericalCircle

        fig = plt.figure(figsize=(7, 7))
        ax = plt.subplot(projection=self.wcs)
        im = ax.imshow(self.image,
                       origin='lower',
                       interpolation='nearest',
                       **kwargs)

        ax.coords.grid(True, color='white', ls='solid', alpha=0.5)
        axra = ax.coords[0]
        axdec = ax.coords[1]
        axra.set_axislabel('RA')
        axra.set_major_formatter('d')
        axra.set_ticks(number=10)
        axdec.set_axislabel('Dec')
        axdec.set_major_formatter('d')
        axdec.set_ticks(number=10)

        if cbar:
            cax = inset_axes(
                ax,
                width='5%',
                height='100%',
                loc='lower left',
                bbox_to_anchor=(1.05, 0., 1, 1),
                bbox_transform=ax.transAxes,
                borderpad=0,
            )
            cb = ColorbarBase(cax,
                              cmap=get_cmap(name='YlGnBu_r'),
                              orientation='vertical',
                              norm=Normalize(vmin=kwargs['vmin'],
                                             vmax=kwargs['vmax']),
                              ticks=LinearLocator())
            cb.solids.set_edgecolor('face')
            cb.set_label(cblabel)
            cb.formatter.set_powerlimits((0, 0))

        if sources:
            phase_center = radec(ra=self.center[0], dec=self.center[1])
            if time is None:
                time = Time.now()
            srcs = radio_sources(time=time)
            for k in srcs.keys():
                src = radec(ra=srcs[k][0], dec=srcs[k][1])
                if phase_center.separation(
                        src).deg > self.npix_x / 2 * self.resol:
                    # Source not in FoV
                    continue
                ax.text(src.ra.deg,
                        src.dec.deg,
                        k.title(),
                        transform=ax.get_transform('icrs'),
                        color='white')

        if circle is not None:
            r1 = SphericalCircle(center=(circle[0] * u.deg, circle[1] * u.deg),
                                 radius=circle[2] / 2 * u.deg,
                                 resolution=100,
                                 edgecolor='white',
                                 facecolor='none',
                                 transform=ax.get_transform('icrs'))
            ax.add_patch(r1)
            r2 = SphericalCircle(center=(circle[0] * u.deg, circle[1] * u.deg),
                                 radius=circle[2] * u.deg,
                                 resolution=100,
                                 edgecolor='white',
                                 linestyle=':',
                                 facecolor='none',
                                 transform=ax.get_transform('icrs'))
            ax.add_patch(r2)

        ax.set_title(title)
        # plt.tight_layout()

        if filename is None:
            plt.show()
        else:
            plt.savefig(filename, dpi=300)
        return
Beispiel #15
0
    ax.set_autoscale_on(False)

    lon = ax.coords[0]
    lat = ax.coords[1]

    lon.set_ticks_visible(False)
    lon.set_ticklabel_visible(False)
    lat.set_ticks_visible(False)
    lat.set_ticklabel_visible(False)
    lon.set_axislabel('')
    lat.set_axislabel('')

    ax.coords.frame.set_color('None')

    north_nuc = SphericalCircle((0.4245000045 * u.deg, 23.49619722 * u.deg), 0.0017047 * u.degree, \
        edgecolor='dodgerblue', facecolor='none', transform=ax.get_transform('fk5'), lw=1.5)
    south_nuc = SphericalCircle((0.4099666595 * u.deg, 23.48356417 * u.deg), 0.0017153 * u.degree, \
        edgecolor='dodgerblue', facecolor='none', transform=ax.get_transform('fk5'), lw=1.5)
    ax.add_patch(north_nuc)
    ax.add_patch(south_nuc)

    f = FontProperties()
    f.set_weight('bold')
    ax.text(0.26, 0.49, 'Bridge east', \
        verticalalignment='top', horizontalalignment='left', \
        transform=ax.transAxes, color='green', fontproperties=f)

    f1 = f.copy()
    f1.set_weight('normal')
    ax.text(0.26, 0.6, 'Bridge east', \
        verticalalignment='top', horizontalalignment='left', \
Beispiel #16
0
def generate(image,
             wcs,
             title,
             flip_ra=False,
             flip_dec=False,
             log_stretch=False,
             cutout=None,
             primary_coord=None,
             secondary_coord=None,
             third_coord=None,
             slit=None,
             vmnx=None,
             extra_text=None,
             outfile=None):
    """
    Basic method to generate a Finder chart figure

    Args:
        image (np.ndarray):
          Image for the finder
        wcs (astropy.wcs.WCS):
          WCS solution
        title (str):
          Title; typically the name of the primary source
        flip_ra (bool, default False):
            Flip the RA (x-axis). Useful for southern hemisphere finders.
        flip_dec (bool, default False):
            Flip the Dec (y-axis). Useful for southern hemisphere finders.
        log_stretch (bool, optional):
            Use a log stretch for the image display
        cutout (tuple, optional):
            SkyCoord (center coordinate) and Quantity (image angular size)
            for a cutout from the input image.
        primary_coord (astropy.coordinates.SkyCoord, optional):
          If provided, place a mark in red at this coordinate
        secondary_coord (astropy.coordinates.SkyCoord, optional):
          If provided, place a mark in cyan at this coordinate
          Assume it is an offset star (i.e. calculate offsets)
        third_coord (astropy.coordinates.SkyCoord, optional):
          If provided, place a mark in yellow at this coordinate
        slit (tuple, optional):
          If provided, places a rectangular slit with specified
          coordinates, width, length, and position angle on image (from North to East)
          [SkyCoords('21h44m25.255s',-40d54m00.1s', frame='icrs'), 1*u.arcsec, 10*u.arcsec, 20*u.deg]
        vmnx (tuple, optional):
          Used for scaling the image.  Otherwise, the image
          is analyzed for these values.
        extra_text : str
          Extra text to be added at the bottom of the Figure.
          e.g. `DSS r-filter`
        outfile (str, optional):
          Filename for the figure.  File type will be according
          to the extension

    Returns:
        matplotlib.pyplot.figure, matplotlib.pyplot.Axis

    """

    utils.set_mplrc()

    plt.clf()
    fig = plt.figure(figsize=(7, 8.5))
    # fig.set_size_inches(7.5,10.5)

    # Cutout?
    if cutout is not None:
        cutout_img = Cutout2D(image, cutout[0], cutout[1], wcs=wcs)
        # Overwrite
        wcs = cutout_img.wcs
        image = cutout_img.data

    # Axis
    ax = fig.add_axes([0.10, 0.20, 0.75, 0.5], projection=wcs)

    # Show
    if log_stretch:
        norm = mplnorm.ImageNormalize(stretch=LogStretch())
    else:
        norm = None
    cimg = ax.imshow(image, cmap='Greys', norm=norm)

    # Flip so RA increases to the left
    if flip_ra is True:
        ax.invert_xaxis()
    if flip_dec is True:
        ax.invert_yaxis()

    # N/E
    overlay = ax.get_coords_overlay('icrs')

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

    overlay['ra'].set_axislabel('Right Ascension')
    overlay['dec'].set_axislabel('Declination')

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

    # Contrast
    if vmnx is None:
        mean, median, stddev = sigma_clipped_stats(
            image
        )  # Also set clipping level and number of iterations here if necessary
        #
        vmnx = (median - stddev, median + 2 * stddev
                )  # sky level - 1 sigma and +2 sigma above sky level
        print("Using vmnx = {} based on the image stats".format(vmnx))
    cimg.set_clim(vmnx[0], vmnx[1])

    # Add Primary
    if primary_coord is not None:
        c = SphericalCircle((primary_coord.ra, primary_coord.dec),
                            2 * units.arcsec,
                            transform=ax.get_transform('icrs'),
                            edgecolor='red',
                            facecolor='none')
        ax.add_patch(c)
        # Text
        jname = ltu.name_from_coord(primary_coord)
        ax.text(0.5,
                1.34,
                jname,
                fontsize=28,
                horizontalalignment='center',
                transform=ax.transAxes)

    # Secondary
    if secondary_coord is not None:
        c_S1 = SphericalCircle((secondary_coord.ra, secondary_coord.dec),
                               2 * units.arcsec,
                               transform=ax.get_transform('icrs'),
                               edgecolor='cyan',
                               facecolor='none')
        ax.add_patch(c_S1)
        # Text
        jname = ltu.name_from_coord(secondary_coord)
        ax.text(0.5,
                1.24,
                jname,
                fontsize=22,
                color='blue',
                horizontalalignment='center',
                transform=ax.transAxes)
        # Print offsets
        if primary_coord is not None:
            sep = primary_coord.separation(secondary_coord).to('arcsec')
            PA = primary_coord.position_angle(secondary_coord)
            # RA/DEC
            dec_off = np.cos(PA) * sep  # arcsec
            ra_off = np.sin(PA) * sep  # arcsec (East is *higher* RA)
            ax.text(
                0.5,
                1.22,
                'Offset from Ref. Star (cyan) to Target (red):\nRA(to targ) = {:.2f}  DEC(to targ) = {:.2f}'
                .format(-1 * ra_off.to('arcsec'), -1 * dec_off.to('arcsec')),
                fontsize=15,
                horizontalalignment='center',
                transform=ax.transAxes,
                color='blue',
                va='top')
    # Add tertiary
    if third_coord is not None:
        c = SphericalCircle((third_coord.ra, third_coord.dec),
                            2 * units.arcsec,
                            transform=ax.get_transform('icrs'),
                            edgecolor='yellow',
                            facecolor='none')
        ax.add_patch(c)

    # Slit
    if ((slit is not None) and (flag_photu is True)):
        # List of values - [coodinates, width, length, PA],
        # e.g. [SkyCoords('21h44m25.255s',-40d54m00.1s', frame='icrs'), 1*u.arcsec, 10*u.arcsec, 20*u.deg]
        slit_coords, width, length, pa = slit

        pa_deg = pa.to('deg').value

        aper = SkyRectangularAperture(
            positions=slit_coords, w=length, h=width, theta=pa
        )  # For theta=0, width goes North-South, which is slit length

        apermap = aper.to_pixel(wcs)

        apermap.plot(color='purple', lw=1)

        plt.text(0.5,
                 -0.1,
                 'Slit PA={} deg'.format(pa_deg),
                 color='purple',
                 fontsize=15,
                 ha='center',
                 va='top',
                 transform=ax.transAxes)

    if ((slit is not None) and (flag_photu is False)):
        raise IOError('Slit cannot be placed without photutils package')

    # Title
    ax.text(0.5,
            1.44,
            title,
            fontsize=32,
            horizontalalignment='center',
            transform=ax.transAxes)

    # Extra text
    if extra_text is not None:
        ax.text(-0.1,
                -0.25,
                extra_text,
                fontsize=20,
                horizontalalignment='left',
                transform=ax.transAxes)
    # Sources

    # Labels
    #ax.set_xlabel(r'\textbf{DEC (EAST direction)}')
    #ax.set_ylabel(r'\textbf{RA (SOUTH direction)}')

    if outfile is not None:
        plt.savefig(outfile)
        plt.close()
    else:
        plt.show()

    # Return
    return fig, ax
def plot_fov(target_coord,res,fov_rad=60*u.arcsec,ang_dist=15*u.arcsec,
             survey='DSS',verbose=True,outdir=None,savefig=False):
    """Plot FOV indicating the query position (magenta reticle) and nearby HARPS
    target (colored triangle), query radius (green circle) and Gaia DR2 sources
    (red squares)

    Parameters
    ----------
    targ_coord : astropy.coordinates.SkyCoord
        targ_coord
    res : pandas.DataFrame
        masked dataframe from `query_target`
    fov_rad : astropy.unit
        field of view radius
    ang_dist : astropy.unit
        angular distance within which to find nearest HARPS object
    survey : str
        survey name of archival image
    outdir : str
        download directory location
    verbose : bool
        print texts
    savefig : bool
        save figure

    Returns
    -------
    res : pandas.DataFrame
        masked dataframe
    """
    if verbose:
        print('\nGenerating FOV ...\n')

    nearest_obj = res['Target'].values[0]
    tic = res['ticid'].values[0]
    if outdir is None:
        outdir = nearest_obj
    else:
        #save with folder name==ticid
        if len(res['ticid'].dropna())>0:
            outdir = join(outdir,'tic'+str(tic))
#         elif res['toi'] is not None:
#             outdir = join(outdir,str(res['toi']).split('.')[0])
        else:
            outdir = join(outdir,nearest_obj)
    if not isdir(outdir):
        makedirs(outdir)

    nearest_obj_ra,nearest_obj_dec =res[['RA_deg','DEC_deg']].values[0]
    nearest_obj_coord = SkyCoord(ra=nearest_obj_ra, dec=nearest_obj_dec, unit=u.deg)

    #indicate target location with magenta reticle
    ax,hdu=plot_finder_image(target_coord,fov_radius=fov_rad,reticle=True,
        survey=survey,reticle_style_kwargs={'label':'target'})
    c = SphericalCircle((nearest_obj_ra, nearest_obj_dec)*u.deg, ang_dist,
        edgecolor='C2', transform=ax.get_transform('icrs'),
        facecolor='none', label='query radius')
    ax.set_title('{} ({})'.format(survey,nearest_obj))
    ax.add_patch(c)

    #harps objects within angular distance
    coords = SkyCoord(ra=res['RA_deg'], dec=res['DEC_deg'], unit=u.deg)
    sep2d = target_coord.separation(coords)

    #get indices that satisfy the criterion
    idxs = sep2d < ang_dist
    colors = cm.rainbow(np.linspace(0, 1, idxs.sum()))

    if len(coords[idxs])>1:
        #plot each star match within search radius
        for n,(coord,color) in enumerate(zip(coords[idxs],colors)):
            ax.scatter(coord.ra.deg, coord.dec.deg, transform=ax.get_transform('icrs'), s=300,
               marker='^', edgecolor=color, facecolor='none',label=res.loc[idxs,'Target'].values[n])
    else:
        ax.scatter(coords.ra.deg, coords.dec.deg, transform=ax.get_transform('icrs'), s=300,
               marker='^', edgecolor='blue', facecolor='none',label=res['Target'].values[0])

    #gaia dr2 sources
    wcs = WCS(hdu.header)
    mx, my = hdu.data.shape

    #query gaia sources within region centered at target_coord
    gaia_sources = Catalogs.query_region(target_coord, radius=fov_rad,
                                         catalog="Gaia", version=2).to_pandas()
    for r,d in gaia_sources[['ra','dec']].values:
        pix = wcs.all_world2pix(np.c_[r,d],1)[0]
        ax.scatter(pix[0], pix[1], marker='s', s=50, edgecolor='C1',
            facecolor='none', label='gaia source')
    pl.setp(ax, xlim=(0,mx), ylim=(0,my))

    #remove redundant labels due to 4 reticles
    handles, labels = pl.gca().get_legend_handles_labels()
    by_label = OrderedDict(zip(labels, handles))
    pl.legend(by_label.values(), by_label.keys())
    if savefig:
        fp = join(outdir,'tic{}_{}_fov.png'.format(tic,nearest_obj))
        ax.figure.savefig(fp,bbox_inches='tight')
        print('Saved: {}'.format(fp))
    return None
Beispiel #18
0
    # with fits.open(work_dir + 'fits/stacked/' + clusters[k] + '_rsi.fits') as hdu_r:
    with fits.open(ab.work_dir + 'fits/best_single/' +
                   ab.short_sci_fn[k][2]) as hdu_r:
        plt.figure(figsize=(12, 12))
        wcs_out, shape_out = find_optimal_celestial_wcs(
            hdu_r[1:len(hdu_r)])  # has only CompImageHDU files
        array, footprint = reproject_and_coadd(
            hdu_r[1:len(hdu_r)],
            wcs_out,
            shape_out=shape_out,
            reproject_function=reproject_interp)

        ax = plt.gca(projection=wcs_out)
        plt.imshow(mm.jarrett(array - np.nanmedian(array), np.nanstd(array),
                              5),
                   cmap='gray_r')
        plt.xlabel('R.A.')
        plt.ylabel('Decl.')
        c = SphericalCircle(
            (ab.coords_cl_cen[k].ra.value, ab.coords_cl_cen[k].dec.value) *
            u.deg,
            0.8 * u.deg,
            edgecolor='gray',
            facecolor='none',
            linestyle='--',
            transform=ax.get_transform('fk5'))
        ax.add_patch(c)

        plt.savefig(ab.work_dir + 'plot/' + ab.clusters[k] +
                    '_short_mosaic_sub_n5.pdf')
        plt.show()
Beispiel #19
0
    # ------------------------ PLOT THE REGIONS ------------------------ #
    reg_file = open(taffy_extdir + 'rawspectra_for_paperplot/regions_for_line_profiles.reg')
    circ_size = 3.776 / 3600 

    for ln_count, ln in enumerate(reg_file.readlines()):
        if ln_count < 3:
            continue
        dec = float(ln.split(',')[1])
        ra = float(ln.split(',')[0].split('circle(')[1])

        reg_color = 'white'
        if 'color=blue' in ln:
            reg_color = 'k'  # Now coloring the bridge circles maroon to be consistent with teh BPT plots

        region = SphericalCircle((ra * u.deg, dec * u.deg), circ_size * u.degree, \
            edgecolor=reg_color, facecolor='none', transform=ax.get_transform('fk5'), lw=2.0)
        ax.add_patch(region)

    # ------------------------ PLOT THE SPECTRA ------------------------ #
    ax_n_1_blue, ax_n_1_red = plot_line_profiles(ax_n_1_blue, ax_n_1_red, north_majax_1_blue['wav'], north_majax_1_blue['flux'], north_majax_1_red['wav'], north_majax_1_red['flux'], 55,90, 40,175)
    ax_n_2_blue, ax_n_2_red = plot_line_profiles(ax_n_2_blue, ax_n_2_red, north_majax_2_blue['wav'], north_majax_2_blue['flux'], north_majax_2_red['wav'], north_majax_2_red['flux'], 40,80, 60,320)
    ax_n_3_blue, ax_n_3_red = plot_line_profiles(ax_n_3_blue, ax_n_3_red, north_majax_3_blue['wav'], north_majax_3_blue['flux'], north_majax_3_red['wav'], north_majax_3_red['flux'], 20,48, 20,235)
    ax_n_4_blue, ax_n_4_red = plot_line_profiles(ax_n_4_blue, ax_n_4_red, north_majax_4_blue['wav'], north_majax_4_blue['flux'], north_majax_4_red['wav'], north_majax_4_red['flux'], 15,50, 15,95)
    ax_n_5_blue, ax_n_5_red = plot_line_profiles(ax_n_5_blue, ax_n_5_red, north_majax_5_blue['wav'], north_majax_5_blue['flux'], north_majax_5_red['wav'], north_majax_5_red['flux'], 20,75, 0,175)

    ax_s_1_blue, ax_s_1_red = plot_line_profiles(ax_s_1_blue, ax_s_1_red, south_majax_1_blue['wav'], south_majax_1_blue['flux'], south_majax_1_red['wav'], south_majax_1_red['flux'], 24,56, 30,340)
    ax_s_2_blue, ax_s_2_red = plot_line_profiles(ax_s_2_blue, ax_s_2_red, south_majax_2_blue['wav'], south_majax_2_blue['flux'], south_majax_2_red['wav'], south_majax_2_red['flux'], 105,160, 140,260)
    ax_s_3_blue, ax_s_3_red = plot_line_profiles(ax_s_3_blue, ax_s_3_red, south_majax_3_blue['wav'], south_majax_3_blue['flux'], south_majax_3_red['wav'], south_majax_3_red['flux'], 25,63, 40,275)
    ax_s_4_blue, ax_s_4_red = plot_line_profiles(ax_s_4_blue, ax_s_4_red, south_majax_4_blue['wav'], south_majax_4_blue['flux'], south_majax_4_red['wav'], south_majax_4_red['flux'], 40,120, 40,340)
    ax_s_5_blue, ax_s_5_red = plot_line_profiles(ax_s_5_blue, ax_s_5_red, south_majax_5_blue['wav'], south_majax_5_blue['flux'], south_majax_5_red['wav'], south_majax_5_red['flux'], 25,75, 20,130)
Beispiel #20
0
    def plot(self, fig=None, ax=None):
        """Plot survey data and position overlay."""
        self.sign = self.kwargs.get('sign', 1)
        self._plot_setup(fig, ax)
        self.data *= self.sign
        absmax = max(self.data.max(), self.data.min(), key=abs)
        self.logger.debug(f"Max flux in cutout: {absmax:.2f} mJy.")
        rms = np.sqrt(np.mean(np.square(self.data)))
        self.logger.debug(f"RMS flux in cutout: {rms:.2f} mJy.")

        assert (sum((~np.isnan(self.data).flatten())) > 0 and sum(self.data.flatten()) != 0), \
            f"No data in {self.survey}"

        if self.kwargs.get('maxnorm'):
            self.norm = ImageNormalize(self.data,
                                       interval=ZScaleInterval(),
                                       vmax=self.data.max(),
                                       clip=True)
        else:
            self.norm = ImageNormalize(self.data,
                                       interval=ZScaleInterval(contrast=0.2),
                                       clip=True)

        self.im = self.ax.imshow(self.data, cmap=self.cmap, norm=self.norm)

        if self.kwargs.get('bar', True):
            try:
                self.fig.colorbar(self.im,
                                  label=r'Flux Density (mJy beam$^{-1}$)',
                                  ax=self.ax)
            except UnboundLocalError:
                self.logger.error(
                    "Colorbar failed. Upgrade to recent version of astropy ")

        if self.psf:
            try:
                self.bmaj = self.header['BMAJ'] * 3600
                self.bmin = self.header['BMIN'] * 3600
                self.bpa = self.header['BPA']
            except KeyError:
                self.logger.warning('Header did not contain PSF information.')
                try:
                    self.bmaj = self.psf[0]
                    self.bmin = self.psf[1]
                    self.bpa = 0
                    self.logger.warning(
                        'Using supplied BMAJ/BMin. Assuming BPA=0')
                except ValueError:
                    self.logger.error('No PSF information supplied.')

            rhs = self.wcs.wcs_pix2world(self.data.shape[0], 0, 1)
            lhs = self.wcs.wcs_pix2world(0, 0, 1)

            # Offset PSF marker by the major axis in pixel coordinates
            try:
                cdelt = self.header['CDELT1']
            except KeyError:
                cdelt = self.header['CD1_1']
            beamavg = (self.bmaj + self.bmin) / 2
            beamsize_pix = beamavg / abs(cdelt) / 3600
            ax_len_pix = abs(lhs[0] - rhs[0]) / abs(cdelt) / 3600
            beam = self.wcs.wcs_pix2world(beamsize_pix, beamsize_pix, 1)
            self.beamx = beam[0]
            self.beamy = beam[1]

            self.beam = Ellipse((self.beamx, self.beamy),
                                self.bmin / 3600,
                                self.bmaj / 3600,
                                -self.bpa,
                                facecolor='white',
                                edgecolor='k',
                                transform=self.ax.get_transform('world'),
                                zorder=10)
            self.ax.add_patch(self.beam)

            # Optionally plot square around the PSF
            # Set size to greater of 110% PSF size or 10% ax length
            if self.kwargs.get('beamsquare', False):
                boxsize = max(beamsize_pix * 1.15, ax_len_pix * .1)
                offset = beamsize_pix - boxsize / 2
                self.square = Rectangle(
                    (offset, offset),
                    boxsize,
                    boxsize,
                    facecolor='white',
                    edgecolor='k',
                    # transform=self.ax.get_transform('world'),
                    zorder=5)
                self.ax.add_patch(self.square)

        if self.plot_sources:
            if self.kwargs.get('corner'):
                self._add_cornermarker(
                    self.source.ra_deg_cont, self.source.dec_deg_cont,
                    self.kwargs.get('corner_span', 20 / 3600),
                    self.kwargs.get('corner_offset', 10 / 3600))
            else:
                self.sourcepos = Ellipse(
                    (self.source.ra_deg_cont, self.source.dec_deg_cont),
                    self.source.min_axis / 3600,
                    self.source.maj_axis / 3600,
                    -self.source.pos_ang,
                    facecolor='none',
                    edgecolor='r',
                    ls=':',
                    lw=2,
                    transform=self.ax.get_transform('world'))
                self.ax.add_patch(self.sourcepos)

        else:
            if self.kwargs.get('corner'):
                self._add_cornermarker(
                    self.ra, self.dec, self.kwargs.get('corner_span',
                                                       20 / 3600),
                    self.kwargs.get('corner_offset', 10 / 3600))
            else:
                self.bmin = 15
                self.bmaj = 15
                self.bpa = 0
                overlay = SphericalCircle(
                    (self.ra * u.deg, self.dec * u.deg),
                    self.bmaj * u.arcsec,
                    edgecolor='r',
                    linewidth=2,
                    facecolor='none',
                    transform=self.ax.get_transform('world'))
                self.ax.add_artist(overlay)

        if self.plot_neighbours:
            for idx, neighbour in self.neighbours.iterrows():
                n = Ellipse((neighbour.ra_deg_cont, neighbour.dec_deg_cont),
                            neighbour.min_axis / 3600,
                            neighbour.maj_axis / 3600,
                            -neighbour.pos_ang,
                            facecolor='none',
                            edgecolor='c',
                            ls=':',
                            lw=2,
                            transform=self.ax.get_transform('world'))
                self.ax.add_patch(n)
Beispiel #21
0
wcs = WCS(hdu.header)
#subplot(projection=wcs)
#grid(color='white', ls='solid')
#plot the data
N = len(ra)
print(N)
xn = len(xra)
xer = loadtxt("xerrors.txt")
ax = plt.subplot(projection=wcs)
#show everything- v min and v max define the end points of the color mapping
xsources = []
sources = []
for i in range(0, xn):
    r = SphericalCircle((xra[i] * u.deg, xdec[i] * u.deg),
                        xer[i] * u.arcsec,
                        edgecolor='purple',
                        facecolor='none',
                        transform=ax.get_transform('fk5'))
    xsources.append(r)
    text(xra[i],
         xdec[i],
         str(i + 1),
         color="red",
         transform=ax.get_transform('fk5'),
         fontsize=12)
#for i in range(0,N):
#    r = SphericalCircle((ra[i] * u.deg, dec[i] * u.deg), .5 * u.arcsec,
#        edgecolor='orange', facecolor='none',
#        transform=ax.get_transform('fk5'))
#    sources.append(r)
imshow(data, cmap='Greys', origin='lower', vmin=0, vmax=1)
def image_plot(inputfile, d_range, imsize, outputfile):
	"""Takes a scaled image in the form of a numpy array and plots it along with coordinates and a colorbar"""

	block = import_fits(inputfile, d_range)
	data = block[0]
	hrd = block[1]
	wcs = WCS(hrd, naxis=2)
	if hrd['TELESCOP'] != 'Spitzer':
		beam = Beam.from_fits_header(hrd)

	print(np.shape(data))
	norm = ImageNormalize(data, interval=MinMaxInterval(), stretch=SqrtStretch())

	figure=plt.figure(num=1)
	figure.subplots_adjust(
		top=0.924,
		bottom=0.208,
		left=0.042,
		right=0.958,
		hspace=0.125,
		wspace=0.2
	)

	if wcs.pixel_n_dim == 4:
		ax=figure.add_subplot(111, projection=wcs, slices=('x','y', 0, 0))
	elif wcs.pixel_n_dim ==2:
		ax=figure.add_subplot(111, projection=wcs, slices=('x','y'))


	main_image=ax.imshow(X=data, cmap='plasma', origin='lower', norm=norm, vmax=np.max(data) , vmin=np.min(data))
	cbar=figure.colorbar(main_image)
	star_index = wcs.world_to_pixel(star_coord)
	star=ax.scatter(star_index[0], star_index[1], marker='*', c='w')

	if hrd['TELESCOP'] == 'Spitzer':
		ax.invert_xaxis()
		ax.invert_yaxis()


	dims=np.shape(data)
	centre=(dims[0]/2., dims[1]/2.)
	ax.set_xlim(centre[0]-imsize, centre[0]+imsize)
	ax.set_ylim(centre[1]-imsize, centre[1]+imsize)



	ax.set_xlabel('Right Ascension J2000')
	ax.set_ylabel('Declination J2000')
	cbar.set_label('Surface Brigthness (MJy/Sr)')
	ra = ax.coords[0]
	ra.set_format_unit('degree', decimal=True)

	dec=ax.coords[1]
	dec.set_format_unit('degree', decimal=True)

	#ax.set_title('Spitzer 24\u03BCm', fontdict=font)
	ax.set_title('4-12 GH 5\u03C3 mask')

	if hrd['TELESCOP'] != 'Spitzer':
		beam = Beam.from_fits_header(hrd)
		c = SphericalCircle((350.32, 61.14)*u.degree, beam.major, edgecolor='black', facecolor='none',
	           				transform=ax.get_transform('fk5'))
		ax.add_patch(c)


	if outputfile != False:
		plt.savefig(os.getcwd()+'/thesis_figs/'+outputfile)
	plt.show()
Beispiel #23
0
    ax.add_patch(r)

    plt.text(float(region[0]),
             float(region[1]),
             labels[i],
             transform=ax.get_transform('fk5'),
             c='w')
    i += 1

ra = ax.coords[0]
ra.set_format_unit('degree', decimal=True)

dec = ax.coords[1]
dec.set_format_unit('degree', decimal=True)

dims = np.shape(SB_masked)
centre = (dims[0] / 2, dims[1] / 2)
size = 400
ax.set_xlim(centre[0] - size, centre[0] + size)
ax.set_ylim(centre[1] - size, centre[1] + size)

beam = Beam.from_fits_header(header)
c = SphericalCircle((350.34, 61.13) * u.degree,
                    beam.major,
                    edgecolor='white',
                    facecolor='none',
                    transform=ax.get_transform('fk5'))
ax.add_patch(c)

plt.show()
Beispiel #24
0
    lon.set_ticks_visible(False)
    lon.set_ticklabel_visible(False)
    lat.set_ticks_visible(False)
    lat.set_ticklabel_visible(False)
    lon.set_axislabel('')
    lat.set_axislabel('')

    ax.coords.frame.set_color('None')

    # ------------------------ PLOT THE REGIONS ------------------------ #
    # the format for the coordinates here is 
    # Rectangle((lower_left_x, lower_left_y), width, height, ....)
    # the -1 is to go from ds9 x,y to numpy row,col
    # i've translated the center coords that i got from ds9
    # to the coords of the lower left corner
    north_nuc = SphericalCircle((0.4245000045 * u.deg, 23.49619722 * u.deg), 0.0017047 * u.degree, \
        edgecolor='dodgerblue', facecolor='none', transform=ax.get_transform('fk5'), lw=1.5)
    south_nuc = SphericalCircle((0.4099666595 * u.deg, 23.48356417 * u.deg), 0.0017153 * u.degree, \
        edgecolor='dodgerblue', facecolor='none', transform=ax.get_transform('fk5'), lw=1.5)
    ax.add_patch(north_nuc)
    ax.add_patch(south_nuc)

    xgal_hii = SphericalCircle((0.4208500067 * u.deg, 23.49327528 * u.deg), 0.0020958 * u.degree, \
        edgecolor='green', facecolor='none', transform=ax.get_transform('fk5'), lw=1.5)
    ax.add_patch(xgal_hii)

    nw_patch = SphericalCircle((0.4192749977 * u.deg, 23.50056333 * u.deg), 0.0018061 * u.degree, \
        edgecolor='dodgerblue', facecolor='none', transform=ax.get_transform('fk5'), lw=1.5)
    ne_patch = SphericalCircle((0.4283333302 * u.deg, 23.49243528 * u.deg), 0.0018061 * u.degree, \
        edgecolor='dodgerblue', facecolor='none', transform=ax.get_transform('fk5'), lw=1.5)
    sw_patch = SphericalCircle((0.4066708406 * u.deg, 23.49171278 * u.deg), 0.0018061 * u.degree, \
        edgecolor='dodgerblue', facecolor='none', transform=ax.get_transform('fk5'), lw=1.5)
Beispiel #25
0
hide_ax(ax33)
ax33.text(0.1, 0.3, 'SUMSS 843 MHz', fontsize=18)

ax4 = fig.add_axes([0.38, 0.09, width, height], projection=w_atlbs_lr)
ax44 = fig.add_axes([0.4, 0.46, 0.8 * width, 0.1 * height])
hide_ax(ax44)
ax44.text(0.1, 0.3, 'ATLBS (high-res) 1.4 GHz', fontsize=18)

ax5 = fig.add_axes([0.7, 0.09, width - 0.02, height - 0.01])
norm = simple_norm(imdata_gleam, percent=99.5)
ax0.imshow(imdata_gleam, cmap='inferno', norm=norm)
norm = simple_norm(imdata_atlbs_lr, percent=99.5)
ax1.imshow(imdata_atlbs_lr, cmap='inferno', norm=norm)
r1 = SphericalCircle((8.4732939 * u.deg, -66.5745355 * u.deg),
                     216.381 * u.arcsecond,
                     ls='-.',
                     edgecolor='white',
                     facecolor='none',
                     transform=ax1.get_transform('fk5'))
r2 = SphericalCircle((8.5480254 * u.deg, -66.7383874 * u.deg),
                     216.381 * u.arcsecond,
                     ls='-.',
                     edgecolor='white',
                     facecolor='none',
                     transform=ax1.get_transform('fk5'))
ax1.add_patch(r2)
ax1.add_patch(r1)
ax1.text(8.33602,
         -66.5361,
         'Lobe (N)',
         transform=ax1.get_transform('fk5'),
         fontsize=13,