Beispiel #1
0
 def do_plot(fig, file):
     img = ctx.open_file(file)
     ax = fig.subplots()
     if align:
         ctx.align(img)
     if preprocess:
         ctx.pre_process(img)
     prj = ctx.get_projection(img)
     plotutils.imshow_image(ax, img, projection=prj, **kwargs)
     if not align:
         core_offset = ctx.get_core_offset()
         if core_offset is not None:
             x, y = core_offset.get(img.get_epoch())
             x, y = prj.s2p([x, y])
             # print core_offset, x, y
             ax.scatter(x, y, marker='*', s=40, c=plotutils.black)
     # if not preprocess:
     #     bg_mask = imgutils.Image(np.zeros_like(img.data, dtype=np.int8))
     #     bg = ctx.get_bg(bg_mask)
     #     if bg is not None and isinstance(bg, np.ndarray):
     #         bg.fill(1)
     if ctx.get_mask() is not None and show_mask is True:
         mask = ctx.get_mask()
         ctx.pre_process(mask)
         ax.contour(mask.data, [0.5])
     for region in show_regions:
         plotutils.plot_region(ax, region, prj, text=True)
Beispiel #2
0
def plot_displacements(ax, features1, features2, delta_info, num=False, projection=None, mode='com',
                bg=None, beam=True, cmap=None, **kwargs):
    """Display displacements of features on a map.
    
    If bg is not set and features1 and features2 are both SegmentedImage, a two color map,
    one color for the segments of each SegmentedImage, will be used as bg.
    
    Parameters
    ----------
    ax : :class:`matplotlib.axes.Axes`
    features1 : :class:`wise.features.FeaturesGroup`
        The features of the first epoch.
    features2 : :class:`wise.features.FeaturesGroup`
        The features of the second epoch.
    delta_info : :class:`wise.features.DeltaInformation`
        An object containing the displacements information.
    num : bool, optional
        Whatever to optionally annotate the segments with there ids.
    projection : :class:`libwise.imgutils.Projection`, optional
    mode : str, optional
        Coord mode for the location of the features: 'lm', 'com' or 'cos'.
    bg : :class:`libwise.imgutils.Image`, optional
        The image to be used as background map.
    beam : bool, optional
        Whatever to optionally display the beam of the image. Default is True.
    cmap : :class:`matplotlib.cm.ColorMap` or str, optional
        A color map for the background map.
    **kwargs: 
        Additional arguments to be passed to :func:`plot_displacement_vector`

    
    .. _tags: plt_matching
    """
    alpha = 0.8

    if isinstance(features1, wds.SegmentedImages):
        projection = plotutils.get_projection(features1.get_img(), projection)
        if bg is None:
            data = ((features1.get_labels() > 1) * 2 + (features2.get_labels() > 1) * 4).astype(np.int8)
            bg = imgutils.Image.from_image(features1.get_img(), data)
            alpha = 0.5
    else:
        assert bg is not None
        assert projection is not None
        contour = False

    cmap = plotutils.get_cmap(cmap)
    plotutils.imshow_image(ax, bg, projection=projection, beam=beam, title=False,
                           alpha=0.8, cmap=cmap)

    if num:
        plot_segmentid(ax, features1)

    plot_features(ax, features1, mode=mode, c=plotutils.blue, alpha=0.8)
    plot_features(ax, features2, mode=mode, c=plotutils.orange, alpha=0.8)

    plot_displacement_vector(ax, delta_info, mode=mode, fc='k', ec='k', **kwargs)

    plot_segments_contour(ax, features1, colors=plotutils.dblue)
    plot_segments_contour(ax, features2, colors=plotutils.red)
Beispiel #3
0
    def do_plot(fig):
        ax = fig.subplots()

        plotutils.imshow_image(ax, stack_img, projection=ctx.get_projection(stack_img), 
                               intensity_colorbar=intensity_colorbar, **kwargs)
        if ctx.get_mask() is not None and show_mask is True:
            ax.contour(ctx.get_mask().data, [0.5])
        for region in show_regions:
            plotutils.plot_region(ax, region, ctx.get_projection(stack_img), text=False, fill=True)
    def after_update(self, result):
        self.ax1.clear()
        self.ax2.clear()
        scale = int(self.scale.get())
        plotutils.imshow_image(self.ax1, self.img.get(), title=False, norm=plotutils.Normalize())
        self.ax1.set_title('Original')
        plotutils.imshow_image(self.ax2, result[scale - 1], title=False, norm=plotutils.Normalize())
        self.ax2.set_title('Scale %s' % scale)

        self.view.draw()
Beispiel #5
0
def plot_ms_set_map(ax, img, ms_set, projection, mode='com', color_style='date', colorbar_setting=None, 
                    map_cmap='jet', **kwargs):
    """Display all features of ms_set on a map.
    
    Parameters
    ----------
    ax : :class:`matplotlib.axes.Axes`
    img : Image
        An image to be used as background map.
    ms_set : :class:`wise.wds.MultiScaleImageSet`
        An object containing all the features to be displayed.
    projection : :class:`libwise.imgutils.Projection`
    mode : str, optional
        Coord mode for the location of the features: 'lm', 'com' or 'cos'.
    color_style : str, optional
        'scale': display one color per scale. 'date': color correspond to the epoch.
    colorbar_setting : :class:`libwise.ColorbarSetting, optional
        Settings for the color bar if color_style is 'date'.
    map_cmap : :class:`matplotlib.cm.ColorMap` or str, optional
    **kwargs : 
        Additional arguments to be passed to :func:`libwise.plotutils.imshow_image`.

    
    .. _tags: plt_detection
    """
    if colorbar_setting is None and color_style == 'date':
        colorbar_setting = plotutils.ColorbarSetting(ticks_locator=mdates.AutoDateLocator(),
                                                     ticks_formatter=mdates.DateFormatter('%m/%y'))
    
    epochs = ms_set.get_epochs()
    intensities = [k.get_intensity() for k in ms_set.features_iter()]
    int_norm = plotutils.Normalize(min(intensities), max(intensities))
    marker_select = plotutils.MarkerSelector()

    epochs_map = plotutils.build_epochs_mappable(epochs, colorbar_setting.get_cmap())

    if img is not None:
        plotutils.imshow_image(ax, img, projection=projection, title=False, cmap=plotutils.get_cmap(map_cmap), **kwargs)

    color_fct = None
    if color_style == 'date':
        color_fct = lambda f: epochs_map.to_rgba(f.get_epoch())
        colorbar_setting.add_colorbar(epochs_map, ax)
    elif color_style is 'scale':
        pass

    for ms_segments in ms_set:
        for segments in ms_segments:
            # if segments.get_scale() != 2:
            #     continue
            s = 10 * segments.get_scale()
            marker = marker_select.get(segments.get_scale())
            # s = 500 * int_norm(segments.get_intensities())
            # s = 200
            plot_features(ax, segments, mode=mode, color_fct=color_fct, s=s, alpha=0.7, marker=marker)
    def after_update(self, result):
        self.ax1.clear()
        self.ax2.clear()
        scale = int(self.scale.get())
        plotutils.imshow_image(self.ax1,
                               self.img.get(),
                               title=False,
                               norm=plotutils.Normalize())
        self.ax1.set_title('Original')
        plotutils.imshow_image(self.ax2,
                               result[scale - 1],
                               title=False,
                               norm=plotutils.Normalize())
        self.ax2.set_title('Scale %s' % scale)

        self.view.draw()
Beispiel #7
0
    def do_plot(fig):
        ax_all = fig.subplots()

        plotutils.imshow_image(ax_all, ref_img, projection=projection, **img_kargs)

        if region_list is not None:
            for region, gdata in data.df.groupby('region'):
                features = wds.DatedFeaturesGroupScale(0, features=gdata.features.values)

                wiseutils.plot_features(ax_all, features, mode='com', c=region.get_color(), label=region.get_name())
                plotutils.plot_region(ax_all, region, projection=projection, text=False, 
                                      color=region.get_color(), fill=True)
        else:
            features = wds.DatedFeaturesGroupScale(0, features=data.df.features.values)
            wiseutils.plot_features(ax_all, features, mode='com')

        if legend:
            ax_all.legend(loc='best')
Beispiel #8
0
    def after_update(self, result):
        print "Start update"
        img, noisy, denoised = result

        for ax in [self.ax1, self.ax2, self.ax3]:
            ax.clear()

        plotutils.imshow_image(self.ax1,
                               img,
                               title=False,
                               norm=plotutils.Normalize())
        self.ax1.set_title('Original')
        plotutils.imshow_image(self.ax2,
                               noisy,
                               title=False,
                               norm=plotutils.Normalize())
        self.ax2.set_title('Original + noise')
        plotutils.imshow_image(self.ax3,
                               denoised,
                               title=False,
                               norm=plotutils.Normalize())
        self.ax3.set_title('Denoised')

        self.view.figure.tight_layout()
        self.view.draw()
        print "Done update"
Beispiel #9
0
def imshow_segmented_image(ax, segmented_image, projection=None, title=True, beam=True, num=False,
                           bg=None, mode='com', **kwargs):
    """Display the segmented image on the axes.
    
    Parameters
    ----------
    ax : :class:`matplotlib.axes.Axes`
    segmented_image : :class:`wise.wds.SegmentedImages`
    projection : :class:`libwise.imgutils.Projection`, optional
    title : bool, optional
        Whatever to optionally display a title. Default is True.
    beam : bool, optional
        Whatever to optionally display the beam of the image. Default is True.
    num : bool, optional
        Whatever to optionally annotate the segments with there ids. Default is False.
    bg : :class:`libwise.imgutils.Image`, optional
        Diplay bg as background image instead of the on from segmented_image.
    mode : str, optional
        Coord mode for the location of the features: 'lm', 'com' or 'cos'.
    **kwargs :
        Additional arguments to be passed to :func:`libwise.plotutils.imshow_image`.

    
    .. _tags: plt_detection
    """
    if bg is None:
        bg = segmented_image.get_img()

    prj = plotutils.imshow_image(ax, bg, projection=projection, title=False, beam=beam, **kwargs)

    if title is True:
        title = "Segmented image"
        if isinstance(segmented_image, wds.AbstractScale):
            title += " at scale %s" % prj.get_sky(segmented_image.get_scale())
        if len(segmented_image.get_img().get_title()) > 0:
            title += "\n%s" % segmented_image.get_img().get_title()
        ax.set_title(title)

    plot_segments_contour(ax, segmented_image)

    plot_features(ax, segmented_image, num=num, c=plotutils.orange, mode=mode)
Beispiel #10
0
def preview_detection_stack(ctx, stack_detection_name, count_threshold=0, ms_set=None, 
                            date_filter=None, show_regions=[]):
    ''' Plot detection in stack'''
    stack = plotutils.FigureStack()

    stack_img, img_snr, img_count = load_detection_stack_image(ctx, stack_detection_name, preprocess=True)

    img_snr.data[img_count.data < count_threshold] = 0
    img_count.data[img_count.data < count_threshold] = 0

    prj = ctx.get_projection(stack_img)

    fig, ax = stack.add_subplots("Stack image")
    plotutils.imshow_image(ax, stack_img, projection=prj)
    for region in show_regions:
        plotutils.plot_region(ax, region, prj, text=True)

    fig, ax1 = stack.add_subplots("Stack detection SNR")
    plotutils.imshow_image(ax1, img_snr, projection=prj, cmap=plotutils.get_cmap('jet'))
    for region in show_regions:
        plotutils.plot_region(ax1, region, prj, text=True)

    fig, ax2 = stack.add_subplots("Stack detection count")
    plotutils.imshow_image(ax2, img_count, projection=prj, cmap=plotutils.get_cmap('jet'))
    for region in show_regions:
        plotutils.plot_region(ax2, region, prj, text=True)

    if ms_set is not None:
        colorbar_setting = plotutils.ColorbarSetting(cmap='jet', ticks_locator=mdates.AutoDateLocator(),
                                                     ticks_formatter=mdates.DateFormatter('%m/%y'))

        def feature_filter(feature):
            if img_snr.data[tuple(feature.get_coord())] == 0:
                return False
            if date_filter is not None and not date_filter(feature.get_epoch()):
                return False
            return True

        ms_set = wds.MultiScaleImageSet.from_file(os.path.join(ctx.get_data_dir(), j),
                                                  feature_filter=feature_filter)
        plot_ms_set_map(ax1, None, ms_set, prj, colorbar_setting=colorbar_setting)
        plot_ms_set_map(ax2, None, ms_set, prj, colorbar_setting=colorbar_setting)

        add_features_tooltip(stack, ax1, ms_set.features_iter(), projection=prj, epoch=True, tol=1)
        add_features_tooltip(stack, ax2, ms_set.features_iter(), projection=prj, epoch=True, tol=1)

    stack.show()
Beispiel #11
0
    def after_update(self, result):
        print "Start update"
        img, noisy, denoised = result

        for ax in [self.ax1, self.ax2, self.ax3]:
            ax.clear()

        plotutils.imshow_image(self.ax1, img, title=False, norm=plotutils.Normalize())
        self.ax1.set_title('Original')
        plotutils.imshow_image(self.ax2, noisy, title=False, norm=plotutils.Normalize())
        self.ax2.set_title('Original + noise')
        plotutils.imshow_image(self.ax3, denoised, title=False, norm=plotutils.Normalize())
        self.ax3.set_title('Denoised')

        self.view.figure.tight_layout()
        self.view.draw()
        print "Done update"
Beispiel #12
0
    def __init__(self, img, prj=None, max_ds=10, current_folder=None):
        self.max_ds = max_ds
        self.showverts = True
        self.current_folder = current_folder

        uiutils.UI.__init__(self, 750, 600, "PolyRegion Editor")

        vbox = QtGui.QVBoxLayout()
        self.setLayout(vbox)

        canva_box = QtGui.QHBoxLayout()
        vbox.addLayout(canva_box)

        self.canvas = plotutils.BaseCustomCanvas()
        canva_box.addWidget(self.canvas)

        ctl = QtGui.QHBoxLayout()
        vbox.addLayout(ctl)

        ctl.addWidget(plotutils.NavigationToolbar(self.canvas, self))

        self.title_entry = uiutils.EntryDescription("Title")
        ctl.addWidget(self.title_entry)

        self.color_entry = uiutils.EntryDescription("Color")
        ctl.addWidget(self.color_entry)

        save_bn = QtGui.QPushButton("Save")
        save_bn.clicked.connect(self.on_save_clicked)
        ctl.addWidget(save_bn)

        load_bn = QtGui.QPushButton("Load")
        load_bn.clicked.connect(self.on_load_clicked)
        ctl.addWidget(load_bn)

        save_bn = QtGui.QPushButton("New")
        save_bn.clicked.connect(self.on_new_clicked)
        ctl.addWidget(save_bn)

        self.ax = self.canvas.figure.subplots()

        if prj is None:
            prj = img.get_projection()

        self.prj = prj
        self.img = img

        plotutils.imshow_image(self.ax, self.img, projection=self.prj, title=False)

        self.poly = Polygon([[0, 0]], animated=True,
                    fc='b', ec='none', alpha=0.4)

        self.ax.add_patch(self.poly)
        self.ax.set_clip_on(False)
        self.ax.set_title("Click and drag a point to move it; "
                     "'i' to insert; 'd' to delete.")

        x, y = zip(*self.poly.xy)
        self.line = plt.Line2D(x, y, color='none', marker='o', mfc='r',
                               alpha=0.8, animated=True, lw=2, markersize=self.max_ds)
        self._update_line()
        self.ax.add_line(self.line)

        self.poly.add_callback(self.poly_changed)
        self._ind = None # the active vert

        canvas = self.poly.figure.canvas
        canvas.mpl_connect('draw_event', self.draw_callback)
        canvas.mpl_connect('button_press_event', self.button_press_callback)
        canvas.mpl_connect('button_release_event', self.button_release_callback)
        canvas.mpl_connect('key_press_event', self.key_press_callback)
        canvas.mpl_connect('motion_notify_event', self.motion_notify_callback)
        self.canvas = canvas

        self.load_default()

        self.canvas.setFocus()
Beispiel #13
0
def plot_links_map(ax, img, projection, links, color_style='link', mode='com', colorbar_setting=None,
                     map_cmap='jet', vector_width=4, link_id_label=False, num_bbox=None, 
                     ang_vel_arrows=False, ang_vel_unit=u.mas / u.year, pix_per_ang_vel_unit=1, **kwargs):
    """Display features links on a map.
    
    Parameters
    ----------
    ax : :class:`matplotlib.axes.Axes`
    img : Image
        An image to be used as background map.
    projection : :class:`libwise.imgutils.Projection`
    links : a list of :class:`wise.matcher.FeaturesLink`
    color_style : str, optional
        'link': one color per link. 
        'date': map the features epochs to a color.
        any color string: use one color for each displacements vectors.
        function: a function that take a feature as argument and return a color.
    mode : str, optional
        Coord mode for the location of the features: 'lm', 'com' or 'cos'.
    colorbar_setting : ColorBar, optional
        Settings for the color bar if color_style is 'date'.
    map_cmap : :class:`matplotlib.cm.ColorMap` or str, optional
    vector_width : int, optional
        Width of the displacements vector arrows. Default is 4.
    link_id_label : bool, optional
        Annotate the links with there ids.
    num_bbox : dict, optional
    **kwargs: 
        Additional arguments to be passed to :func:`libwise.plotutils.imshow_image`.

    
    .. _tags: plt_matching
    """
    color_fct = None
    if color_style == 'date':
        all_epochs = matcher.get_all_epochs(links)
        epochs_map = plotutils.build_epochs_mappable(all_epochs, colorbar_setting.get_cmap())
        if colorbar_setting is None:
            colorbar_setting = plotutils.ColorbarSetting(ticks_locator=mdates.AutoDateLocator(),
                                                         ticks_formatter=mdates.DateFormatter('%m/%y'))
        colorbar_setting.add_colorbar(epochs_map, ax)
        color_fct = lambda f: epochs_map.to_rgba(f.get_epoch())
    elif color_style is not 'link' and isinstance(color_style, str):
        color_fct = lambda f: color_style
    elif nputils.is_callable(color_style):
        color_fct = color_style

    plotutils.imshow_image(ax, img, projection=projection, title=False, cmap=plotutils.get_cmap(map_cmap), **kwargs)

    for link in links:
        delta_info = link.get_delta_info(measured_delta=False)

        if ang_vel_arrows:
            plot_velocity_vector(ax, delta_info, projection, ang_vel_unit, pix_per_ang_vel_unit, 
                                 color_fct=color_fct, mode=mode, lw=0.5,
                                 fc=link.get_color(), ec='k', alpha=0.9, zorder=link.size(), width=vector_width)
        else:
            plot_displacement_vector(ax, delta_info, color_fct=color_fct, mode=mode, lw=0.5,
                                 fc=link.get_color(), ec='k', alpha=0.9, zorder=link.size(), width=vector_width)
        # y, x = link.get_features()[int(np.random.normal(s / 2, s / 4))].get_coord()
        if link_id_label:
            y, x = link.last().get_coord()
            if num_bbox is None:
                props = dict(boxstyle='round', facecolor='wheat', alpha=0.7, edgecolor=link.get_color(), lw=1.5)
            ax.text(x, y, link.get_id(), bbox=num_bbox, zorder=200, size='small')
Beispiel #14
0
    def __init__(self, img, prj=None, max_ds=10, current_folder=None):
        self.max_ds = max_ds
        self.showverts = True
        self.current_folder = current_folder

        uiutils.UI.__init__(self, 750, 600, "PolyRegion Editor")

        vbox = QtGui.QVBoxLayout()
        self.setLayout(vbox)

        canva_box = QtGui.QHBoxLayout()
        vbox.addLayout(canva_box)

        self.canvas = plotutils.BaseCustomCanvas()
        canva_box.addWidget(self.canvas)

        ctl = QtGui.QHBoxLayout()
        vbox.addLayout(ctl)

        ctl.addWidget(plotutils.NavigationToolbar(self.canvas, self))

        self.title_entry = uiutils.EntryDescription("Title")
        ctl.addWidget(self.title_entry)

        self.color_entry = uiutils.EntryDescription("Color")
        ctl.addWidget(self.color_entry)

        save_bn = QtGui.QPushButton("Save")
        save_bn.clicked.connect(self.on_save_clicked)
        ctl.addWidget(save_bn)

        load_bn = QtGui.QPushButton("Load")
        load_bn.clicked.connect(self.on_load_clicked)
        ctl.addWidget(load_bn)

        save_bn = QtGui.QPushButton("New")
        save_bn.clicked.connect(self.on_new_clicked)
        ctl.addWidget(save_bn)

        self.ax = self.canvas.figure.subplots()

        if prj is None:
            prj = img.get_projection()

        self.prj = prj
        self.img = img

        plotutils.imshow_image(self.ax, self.img, projection=self.prj, title=False)

        self.poly = Polygon([[0, 0]], animated=True,
                            fc='b', ec='none', alpha=0.4)

        self.ax.add_patch(self.poly)
        self.ax.set_clip_on(False)
        self.ax.set_title("Click and drag a point to move it; "
                          "'i' to insert; 'd' to delete.")

        x, y = zip(*self.poly.xy)
        self.line = plt.Line2D(x, y, color='none', marker='o', mfc='r',
                               alpha=0.8, animated=True, lw=2, markersize=self.max_ds)
        self._update_line()
        self.ax.add_line(self.line)

        self.poly.add_callback(self.poly_changed)
        self._ind = None  # the active vert

        canvas = self.poly.figure.canvas
        canvas.mpl_connect('draw_event', self.draw_callback)
        canvas.mpl_connect('button_press_event', self.button_press_callback)
        canvas.mpl_connect('button_release_event', self.button_release_callback)
        canvas.mpl_connect('key_press_event', self.key_press_callback)
        canvas.mpl_connect('motion_notify_event', self.motion_notify_callback)
        self.canvas = canvas

        self.load_default()

        self.canvas.setFocus()