Exemple #1
0
def show_residuals(cut, model, imshow_kwargs={}, plot_kwargs={}):
    imshow_kwargs = dict(cmap = "inferno",**imshow_kwargs)
    plot_kwargs = dict(color="blueviolet",**plot_kwargs)

    x, y = np.indices(cut.shape)
    
    plt.subplot(131)
    plt.imshow(utils.z_scale(cut), alpha=1, **imshow_kwargs)
    plt.xlabel("x (pixels)")
    plt.ylabel("y (pixels)")
    plt.title("PSF", loc="left")

    plt.subplot(132)
    plt.imshow(utils.z_scale(model), alpha=1, **imshow_kwargs)
    plt.xlabel("x (pixels)")
    plt.ylabel("y (pixels)")
    plt.title("PSF model", loc="left")
    
    residuals = cut-model
    plt.subplot(133)
    im =plt.imshow(residuals, alpha=1, **imshow_kwargs)
    plt.xlabel("x (pixels)")
    plt.ylabel("y (pixels)")
    plt.title("Residuals", loc="left")
    viz.add_colorbar(im)
Exemple #2
0
 def plot_masters(self):
     plt.figure(figsize=(40, 10))
     plt.subplot(131)
     plt.title("Master bias")
     im = plt.imshow(utils.z_scale(self.master_bias), cmap="Greys_r")
     viz.add_colorbar(im)
     plt.subplot(132)
     plt.title("Master dark")
     im = plt.imshow(utils.z_scale(self.master_dark), cmap="Greys_r")
     viz.add_colorbar(im)
     plt.subplot(133)
     plt.title("Master flat")
     im = plt.imshow(utils.z_scale(self.master_flat), cmap="Greys_r")
     viz.add_colorbar(im)
Exemple #3
0
def gif_image_array(image, factor=0.25):
    return (utils.z_scale(
        resize(
            image,
            np.array(np.shape(image)).astype(int) * factor,
            anti_aliasing=True,
        )) * 255).astype("uint8")
Exemple #4
0
def plot_all_cuts(cuts, W=10, cmap="magma", stars=None, stars_in=None):
    H = np.ceil(len(cuts) / W).astype(int)

    fig, axes = plt.subplots(
        H,
        W,
        figsize=(W * 2, H * 2),
        subplot_kw={"xticks": [], "yticks": []},
        gridspec_kw=dict(hspace=0.1, wspace=0.1),
    )
    for i, ax in enumerate(axes.flat):
        if i < len(cuts):
            ax.imshow(utils.z_scale(cuts[i]), cmap=cmap)
            ax.annotate(
                str(i),
                (0, 0),
                xycoords="axes fraction",
                xytext=(5, 5),
                textcoords="offset points",
                ha="left",
                va="bottom",
                fontsize=12,
                color="w",
            )

            if stars is not None:
                for j, s in enumerate(stars_in[i][0]):
                    ax.plot(*stars_in[i][1][j], "x", c="C0")
        else:
            ax.axis('off')
Exemple #5
0
def plot_marginal_model(data, model, cmap="inferno", c="blueviolet"):
    x, y = np.indices(data.shape)

    plt.subplot(131)
    plt.imshow(utils.z_scale(data), alpha=1, cmap=cmap)
    plt.contour(model, colors="w", alpha=0.7)
    plt.xlabel("x (pixels)")
    plt.ylabel("y (pixels)")
    plt.title("PSF", loc="left")

    plt.subplot(132)
    plt.plot(y[0], np.mean(data, axis=0), c=c)
    plt.plot(y[0], np.mean(model, axis=0), "--", c="k")
    plt.xlabel("x (pixels)")
    plt.ylim(data.min() * 0.98, np.mean(data, axis=0).max() * 1.02)
    plt.title("PSF x-axis projected", loc="left")
    plt.grid(color="whitesmoke")

    plt.subplot(133)
    plt.plot(y[0], np.mean(data, axis=1), c=c)
    plt.plot(y[0], np.mean(model, axis=1), "--", c="k")
    plt.xlabel("y")
    plt.ylim(data.min() * 0.98, np.mean(data, axis=1).max() * 1.02)
    plt.title("PSF y-axis projected", loc="left")
    plt.grid(color="whitesmoke")
    plt.tight_layout()
Exemple #6
0
def fancy_gif_image_array(image, median_psf, factor=0.25):

    fig = plt.figure(frameon=False)
    canvas = FigureCanvas(fig)
    ax = fig.add_axes([0, 0, 1, 1])
    ax.axis('off')
    gif_im = utils.z_scale(
        resize(
            image,
            np.array(np.shape(image)).astype(int) * factor,
            anti_aliasing=True,
        ))
    ax.imshow(gif_im, cmap="Greys_r")
    axins = inset_axes(ax, width=1, height=1, loc=3)
    axins.axis('off')
    axins.imshow(median_psf)
    canvas.draw()
    width, height = (fig.get_size_inches() * fig.get_dpi()).astype(int)
    return np.fromstring(canvas.tostring_rgb(), dtype='uint8').reshape(height, width, 3)
Exemple #7
0
def fancy_show_stars(
        image,
        stars,
        ref_stars=None,
        target=None,
        size=15,
        pixel_scale=None,
        contrast=0.05,
        aperture=None,
        marker_color=np.array([131, 220, 255]) / 255,
        proper_motion=False,
        n_stars=None,
        flip=False,
        view="all",
        zoom=True,
        options={},
):
    """
    Plot stack image and detected stars

    Parameters
    ----------
    size: float (optional)
        pyplot figure (size, size)
    image: int (optional)
        index of image to plot in light files. Default is None, which show stack image
    contrast: float
        contrast within [0, 1] (zscale is applied here)
    marker_color: [r, g, b]
    proper_motion: bool
        whether to display proper motion on the image
    n_stars: int
        max number of stars to show
    flip: bool
        flip image
    view: 'all', 'reference'
        - ``reference`` : only highlight target and comparison stars
        - ``all`` : all stars are shown
    zoom: bool
        whether to include a zoom view
    options: dict
        style options:
            - to do

    Examples
    --------

    .. code-block:: python3

        from specphot.observations import Photometry

        phot = Photometry("your_path")
        phot.plot_stars(view="reference")

    .. image:: /user_guide/gallery/plot_stars.png
       :align: center
    """
    _options = {
        "aperture_color": "seagreen",
        "aperture_ls": "--"
    }
    _options.update(options)

    marker_size = 9

    if isinstance(image, str):
        image = fits.getdata(image)

    image_size = np.array(np.shape(image))[::-1]

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

    if flip:
        image = utils.z_scale(image, c=contrast)[::-1, ::-1]
        stars = np.array(image_size) - stars
    else:
        image = utils.z_scale(image, c=contrast)

    ax = fig.add_subplot(111)
    ax.imshow(image, cmap="Greys_r")
    plt.title("Stack image", loc="left")

    size_factor = size / 15
    fontsize = min(size_factor, 1) * 15
    label_yoffset = min(size_factor, 1) * 30

    if view == "all":

        for i, coord in enumerate(stars):
            circle = mpatches.Circle(coord, marker_size, fill=None, ec=marker_color, )
            ax = plt.gca()
            ax.add_artist(circle)
            plt.annotate(str(i),
                         xy=[coord[0], coord[1] + marker_size+1],
                         color=marker_color,
                         ha='center', fontsize=12, va='top')

    if ref_stars is not None:
        circle = mpatches.Circle(stars[target, :], marker_size, fill=None, ec=marker_color, label="target")
        ax = plt.gca()
        ax.add_artist(circle)
        plt.annotate(target, xy=[stars[target][0], stars[target][1] + marker_size+1],
                     color=marker_color, ha='center', fontsize=12, va='top')

        plt.imshow(image, cmap="Greys_r")

        for i in ref_stars:
            circle = mpatches.Circle(stars[i, :], marker_size, fill=None, ec="yellow", label="comparison")
            ax.add_artist(circle)
            plt.annotate(str(i), xy=[stars[i][0], stars[i][1] + marker_size+1], color="yellow",
                         fontsize=12,
                         ha='center',
                         va='top')

        other_stars = np.arange(len(stars))

        other_stars = np.setdiff1d(other_stars, target)
        other_stars = np.setdiff1d(other_stars, ref_stars)

        for i in other_stars:
            circle = mpatches.Circle(stars[i, :], marker_size, fill=None, ec=marker_color, label="comparison",
                                     alpha=0.4)
            ax.add_artist(circle)

    plt.tight_layout()

    if pixel_scale is not None:
        ob = AnchoredHScaleBar(size=60 / pixel_scale, label="1'", loc=4, frameon=False, extent=0,
                               pad=0.6, sep=4, linekw=dict(color="white", linewidth=0.8))
        ax.add_artist(ob)

    if target is not None and zoom:
        with plt.rc_context({
            'axes.edgecolor': "white",
            'xtick.color': "white",
            'ytick.color': "white"
        }):
            x, y = stars[target]
            rect = patches.Rectangle(
                (x - 80, y - 80),
                160, 160, linewidth=1,
                edgecolor='white',
                facecolor='none',
                alpha=0.3)

            ax.add_patch(rect)
            axins = zoomed_inset_axes(ax, 2.5, loc=1)
            axins.imshow(image, cmap="Greys_r", origin="upper")
            if aperture is not None:
                ap = aperture / 2
                aperture = patches.Circle(
                    (x, y),
                    ap, linewidth=1,
                    ls=_options["aperture_ls"],
                    edgecolor=_options["aperture_color"],
                    facecolor='none',
                    alpha=1)
                axins.add_patch(aperture)
            axins.set_xlim([x - 80, x + 80])
            axins.set_ylim([y + 80, y - 80])

            if pixel_scale is not None:
                obin = AnchoredHScaleBar(size=15 / pixel_scale, label="15\"", loc=4,
                                         frameon=False, extent=0, pad=0.6, sep=4,
                                         linekw=dict(color="white", linewidth=0.8))
                axins.add_artist(obin)

    return fig
Exemple #8
0
def show_stars(image, stars=None, highlight=None, size=15, options={}, flip=None, color=None, contrast=0.05):

    if color is None:
        color = np.array([131, 220, 255]) / 255

    _options = {
        "aperture_color": "seagreen",
        "aperture_ls": "--"
    }
    _options.update(options)

    if isinstance(image, str):
        image = fits.getdata(image)

    image_size = np.array(np.shape(image))[::-1]

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

    if flip:
        image = utils.z_scale(image, c=contrast)[::-1, ::-1]
        if stars is not None:
            stars = np.array(image_size) - stars
    else:
        image = utils.z_scale(image, c=contrast)

    ax = fig.add_subplot(111)
    ax.imshow(image, cmap="Greys_r")
    plt.title("Stack image", loc="left")

    size_factor = size/7
    fontsize = min(size_factor, 1)*15
    label_yoffset = min(size_factor, 1)*15

    if stars is not None:
        if highlight is not None:

            plt.plot(
                stars[highlight, 0],
                stars[highlight, 1],
                "o",
                markersize=14*size_factor,
                markeredgecolor=color,
                markerfacecolor="none",
                label="target",
            )
            plt.annotate(
                highlight, xy=[stars[highlight][0], stars[highlight][1] + label_yoffset],
                color=color, fontsize=fontsize, ha='center', va='top'
            )

        else:
            highlight = -1

        other_stars = np.arange(len(stars))

        other_stars = np.setdiff1d(other_stars, highlight)

        plt.plot(
            stars[other_stars, 0],
            stars[other_stars, 1],
            "o",
            markersize=14*size_factor,
            markeredgecolor=color,
            markerfacecolor="none",
            alpha=0.4 if highlight >= 0 else 1
        )

        plt.tight_layout()

    return fig
Exemple #9
0
    def show(self, size=15):
        marker_size = 12
        marker_color = np.array([131, 220, 255]) / 255
        image = fits.getdata(self.phot.stack_fits)
        image_size = np.array(np.shape(image))[::-1]

        fig = plt.figure(figsize=(size, size))
        image = utils.z_scale(image, c=0.05)

        search_radius = 60 * self.radius / self.phot.telescope.pixel_scale
        target_coord = self.phot.stars[self.phot.target_id]
        circle = mpatches.Circle(target_coord,
                                 search_radius,
                                 fill=None,
                                 ec="white",
                                 alpha=0.6)

        plt.imshow(image, cmap="Greys_r")
        plt.title("Stack image", loc="left")

        ax = plt.gca()
        ax.add_artist(circle)
        plt.annotate(
            "radius {}'".format(self.radius),
            xy=[target_coord[0], target_coord[1] - search_radius - 15],
            color="white",
            ha='center',
            fontsize=12,
            va='bottom',
            alpha=0.6)

        for coord in self.phot.stars:
            circle = mpatches.Circle(coord,
                                     marker_size,
                                     fill=None,
                                     ec=marker_color,
                                     alpha=0.4)
            ax = plt.gca()
            ax.add_artist(circle)

        for i, coord in enumerate(self.phot.stars[self.nearby_ids]):
            if self.nearby_ids[i] == self.phot.target_id:
                color = marker_color
            else:
                color = self.color(i)
            circle = mpatches.Circle(coord, marker_size, fill=None, ec=color)
            ax = plt.gca()
            ax.add_artist(circle)
            plt.annotate(str(self.nearby_ids[i]),
                         xy=[coord[0], coord[1] - marker_size - 6],
                         color=color,
                         ha='center',
                         fontsize=12,
                         va='bottom')

        plt.tight_layout()
        ax = plt.gca()

        if self.phot.telescope.pixel_scale is not None:
            ob = viz.AnchoredHScaleBar(size=60 /
                                       self.phot.telescope.pixel_scale,
                                       label="1'",
                                       loc=4,
                                       frameon=False,
                                       extent=0,
                                       pad=0.6,
                                       sep=4,
                                       linekw=dict(color="white",
                                                   linewidth=0.8))
            ax.add_artist(ob)

        plt.ylim(target_coord[1] + search_radius + 100,
                 target_coord[1] - search_radius - 100)
        plt.xlim(target_coord[0] - search_radius - 100,
                 target_coord[0] + search_radius + 100)
Exemple #10
0
from photutils import DAOStarFinder
from astropy.stats import sigma_clipped_stats
from prose.pipeline_methods.alignment import clean_stars_positions
from prose import PhotProducts
import matplotlib.pyplot as plt
from prose import utils
from astropy.io import fits

data = fits.getdata(phot.stack_fits)
threshold = 1.3 * np.median(data)
regions = regionprops(label(data > threshold), data)
coordinates = np.array([region.weighted_centroid[::-1] for region in regions])

plt.figure(figsize=(10, 5))
plt.subplot(121)
plt.imshow(utils.z_scale(data), cmap='Greys_r')
plt.xlim(950, 1150)
plt.ylim(950, 1150)
plt.title("original image", loc="left")
plt.subplot(122)
plt.imshow(utils.z_scale(data), cmap='Greys_r')
for i, region in enumerate(regions):
    im = region.filled_image
    plt.imshow(np.ma.masked_where(im == 0, im),
               extent=(
                   region.bbox[1],
                   region.bbox[3],
                   region.bbox[0],
                   region.bbox[2],
               ),
               cmap="viridis_r",