Ejemplo n.º 1
0
    def single_image_view_specifier(self, imgId):
        gt_segs, pd_segs = self.gt.img2seg[imgId], self.pd.img2seg[imgId]
        _gt_cats = {seg['category_id'] for seg in gt_segs.values()}
        _pd_cats = {seg['category_id'] for seg in pd_segs.values()}
        relevant_catIds = _gt_cats | _pd_cats
        tranche_map = self._tranche_filter(gt_segs, pd_segs)
        modes = ['bulk', 'walk']

        def logic(catIds, tranches, mode):
            # only for walk, not for bulk display
            seg_list = self._cat_filter_and_merge_tranche_map(
                tranche_map, catIds, tranches)
            if mode == modes[0]:
                self.single_image_bulk_display(seg_list)
            elif mode == modes[1]:
                self.walk_primary(seg_list)

        UI = interactive(logic,
                         mode=widgets.ToggleButtons(options=modes,
                                                    value=modes[0]),
                         catIds=self._category_roulette(
                             relevant_catIds,
                             multi_select=True,
                             default_cid=[self.global_state['catId']]),
                         tranches=widgets.SelectMultiple(
                             options=tranche_map.keys(),
                             value=[self.global_state['tranche']]))
        ipy_display(UI)
Ejemplo n.º 2
0
 def display(self, widget):
     if self._display == "cell" or SIDECAR is None:
         ipy_display(widget)
     else:
         SIDECAR.clear_output(True)
         with SIDECAR:
             ipy_display(widget)
Ejemplo n.º 3
0
    def walk_matched(self, ref_seg):
        """child of walk_primary"""
        ref_sid = ref_seg['sid']
        # note that matchings is {sid: IoU}
        matched_sids = list(ref_seg['matchings'].keys())
        matched_ious = list(ref_seg['matchings'].values())
        if len(matched_sids) == 0:
            matched_sids = (None, )
            matched_ious = (0, )

        def segid_to_catname(partition, sid):
            if sid is None:
                return 'NA'
            return self.gt.cats[partition.segs[sid]['category_id']]['name']

        def logic(inx):
            match_sid = matched_sids[inx]
            if ref_sid.startswith('gt/'):
                gt_sid, pd_sid, highlight = ref_sid, match_sid, 1
                imgId = self.gt.segs[ref_sid]['image_id']
            else:
                gt_sid, pd_sid, highlight = match_sid, ref_sid, 2
                imgId = self.pd.segs[ref_sid]['image_id']
            print('IoU: {:.3f}'.format(matched_ious[inx]))
            print('gt: {} vs pd: {}'.format(segid_to_catname(self.gt, gt_sid),
                                            segid_to_catname(self.pd, pd_sid)))
            self.single_image_plot(imgId, gt_sid, pd_sid, highlight)

        inx, txt = self._inx_txt_scroller_pair(matched_sids)
        UI = interactive(logic, inx=inx)
        print("Matched Segment:")
        ipy_display(txt)
        ipy_display(UI)
Ejemplo n.º 4
0
def display(obj, n=PD_DEFAULT_ROWS, ncol=10, *args, **kwargs):
    """
    extension of the display function, allows to
    specify the number of rows/cols for pandas.
    """
    from IPython.display import display as ipy_display
    with pd.option_context('display.max_rows', n, 'display.max_columns', ncol):
        ipy_display(obj)
Ejemplo n.º 5
0
 def logic(mode):
     # cache the widget later
     if mode == modes[0]:
         if self.global_walk is None:
             self.global_walk = self.global_walk_specifier()
         ipy_display(self.global_walk)
     elif mode == modes[1]:
         self.image_view = self.single_image_selector()
Ejemplo n.º 6
0
 def _display(self, game):
     if 'ipykernel' in sys.modules:
         source = self._render(game)
         ipy_display(HTML(source))
     else:
         print("Warning: since it's not in ipykernel, "
               "it will show the command line version.")
         super()._display(game)
Ejemplo n.º 7
0
 def display(self):
     """
     Display the display the ipywidgets controls or show the control figures
     """
     if self.use_ipywidgets:
         ipy_display(self.vbox)
     else:
         for fig in self.control_figures:
             if fig is not None:
                 fig.show()
Ejemplo n.º 8
0
    def single_image_selector(self):
        imgIds = self.imgIds
        inx, txt = self._inx_txt_scroller_pair(
            imgIds, default_txt=self.global_state['imgId'])

        def logic(inx):
            print("curr image {}/{}".format(inx, len(imgIds)))
            imgId = imgIds[inx]
            self.single_image_view_specifier(imgId)

        UI = interactive(logic, inx=inx)
        ipy_display(txt)
        ipy_display(UI)
Ejemplo n.º 9
0
def get_or_create_display(init=False, **kwargs):
    global DISPLAY

    def resize():
        t = kwargs.get("tree_width")
        w = kwargs.get("cad_width")
        h = kwargs.get("height")
        if w is not None or h is not None:
            DISPLAY.set_size(t, w, h)

    if kwargs.get("display",
                  get_default("display")) != "sidecar" or SIDECAR is None:
        d = CadqueryDisplay()
        widget = d.create(**kwargs)
        ipy_display(widget)
        set_css(get_default("theme"))
        return d

    if DISPLAY is None:
        DISPLAY = CadqueryDisplay()
        widget = DISPLAY.create(**kwargs)
        resize()
        SIDECAR.clear_output(True)
        with SIDECAR:
            ipy_display(widget)

        data = pickle.loads(base64.b64decode(LOGO_DATA))
        mesh_data = data["data"]
        config = data["config"]
        DISPLAY.init_progress(data.get("count", 1))
        create_args, add_shape_args = split_args(config)
        DISPLAY._update_settings(**create_args)
        DISPLAY.add_shapes(**mesh_data, **add_shape_args)
        DISPLAY.info.ready_msg(DISPLAY.cq_view.grid.step)
        DISPLAY.splash = True
        set_css(get_default("theme"), True)

    else:
        # Use the existing Cad Display, so set the defaults and parameters again
        DISPLAY._update_settings(**kwargs)
        resize()
        set_css(get_default("theme"))

    # Change latest settings
    # DISPLAY._update_settings(**kwargs)
    DISPLAY.cq_view.timeit = kwargs.get("timeit", get_default("timeit"))

    return DISPLAY
Ejemplo n.º 10
0
def gogogo_display(ipympl, use_ipywidgets, display, controls, fig):
    if use_ipywidgets:
        controls = widgets.VBox(controls)
        if display:
            if ipympl:
                ipy_display(widgets.VBox([controls, fig.canvas]))
            else:
                # for the case of using %matplotlib qt
                # but also want ipywidgets sliders
                # ie with force_ipywidgets = True
                ipy_display(controls)
                fig.show()
    else:
        if display:
            fig.show()
            controls[0].show()
    return controls
Ejemplo n.º 11
0
def show(expr, prefix: str = None, postfix: str = None) -> None:
    """
    Display latex math in Jupyter Notebook.txt

    Parameters
    ----------
    expr
        Sympy expression to display.
    prefix : str, optional
        Insert `prefix` before `expr`, by default None
    postfix : str, optional
        Insert `postfix` before `expr`, by default None
    
    """
    latex_str = sp.latex(expr)
    if prefix is not None:
        latex_str = prefix + latex_str
    if postfix is not None:
        latex_str = latex_str + postfix
    ipy_display(Math(latex_str))
Ejemplo n.º 12
0
def display(obj, backend=None):
    """Display given object on Jupyter notebook using given backend.

    This is largely for testing.
    """
    global _backend
    from IPython.display import HTML, display as ipy_display
    backend = _backend if backend is None else backend
    orig_backend = _backend
    _backend = backend
    html = _repr_html_(obj)
    _backend = orig_backend
    return ipy_display(HTML(html))
Ejemplo n.º 13
0
def glue(name, variable, display=True):
    """Glue an variable into the notebook's cell metadata.

    Parameters
    ----------
    name: string
        A unique name for the variable. You can use this name to refer to the variable
        later on.
    variable: python object
        A variable in Python for which you'd like to store its display value. This is
        not quite the same as storing the object itself - the stored information is
        what is *displayed* when you print or show the object in a Jupyter Notebook.
    display: bool
        Display the object you are gluing. This is helpful in sanity-checking the
        state of the object at glue-time.
    """
    mimebundle, metadata = IPython.core.formatters.format_display_data(variable)
    mime_prefix = "" if display else GLUE_PREFIX
    metadata["scrapbook"] = dict(name=name, mime_prefix=mime_prefix)
    ipy_display(
        {mime_prefix + k: v for k, v in mimebundle.items()}, raw=True, metadata=metadata
    )
Ejemplo n.º 14
0
def display(obj, backend=None):
    """Display given object on Jupyter notebook using given backend.

    This is largely for testing.
    """
    global _backend
    from IPython.display import HTML, display as ipy_display
    backend = _backend if backend is None else backend
    orig_backend = _backend
    _backend = backend
    html = _repr_html_(obj)
    _backend = orig_backend
    return ipy_display(HTML(html))
Ejemplo n.º 15
0
    def walk_primary(self, segs, is_global=False):
        """segs: a list of seg"""
        # the watching logic here is quite messy
        sids = [seg['sid'] for seg in segs]
        if len(sids) == 0:
            return 'no available segs'
        inx, txt = self._inx_txt_scroller_pair(
            sids,
            default_txt=self.global_state['segId'] if is_global else None)

        def logic(inx):
            seg = segs[inx]
            if is_global:
                self.global_state['segId'] = seg['sid']
                self.global_state['imgId'] = seg['image_id']
            print("Primary seg {}/{} matches with {} segments".format(
                inx, len(segs), len(seg['matchings'])))
            self.walk_matched(seg)

        UI = interactive(logic, inx=inx)
        print("Primary Segment:")
        ipy_display(txt)
        ipy_display(UI)
Ejemplo n.º 16
0
    def root_wdgt(self):
        """
        root widget delegates to either global or image
        """
        self.summarize()
        modes = ['Global', 'Single-Image']

        def logic(mode):
            # cache the widget later
            if mode == modes[0]:
                if self.global_walk is None:
                    self.global_walk = self.global_walk_specifier()
                ipy_display(self.global_walk)
            elif mode == modes[1]:
                self.image_view = self.single_image_selector()
                # if self.image_view is None:
                #     self.image_view = self.single_image_selector()
                # ipy_display(self.image_view)

        UI = interactive(logic,
                         mode=widgets.ToggleButtons(options=modes,
                                                    value=modes[0]))
        UI.children[-1].layout.height = '1000px'
        ipy_display(UI)
Ejemplo n.º 17
0
 def _ipython_display_(self):
     ipy_display(self.vbox)
Ejemplo n.º 18
0
Archivo: vis.py Proyecto: w-hc/pcv
 def display_stdout_and_err_in_curr_cell(self):
     """
     in JLab, stdout and stderr from widget callbacks
     must be displayed through a specialized output widget
     """
     ipy_display(self.output_widget)
Ejemplo n.º 19
0
    def add_shapes(self, shapes, mapping, tree, reset=True):
        def count_shapes(shapes):
            count = 0
            for shape in shapes["parts"]:
                if shape.get("parts") is None:
                    count += 1
                else:
                    count += count_shapes(shape)
            return count

        self.clear()
        self.states = {k: v["state"] for k, v in mapping.items()}
        self.paths = {k: v["path"] for k, v in mapping.items()}

        self.tree_view = Output()
        self.tree_clipping.children = [
            self.tree_view, self.tree_clipping.children[1]
        ]
        self.progress = Progress(count_shapes(shapes) + 3)
        with self.tree_view:
            ipy_display(self.progress.progress)

        add_shapes_timer = Timer(self.timeit, "add shapes")
        self.cq_view.add_shapes(shapes, self.progress, reset=reset)
        add_shapes_timer.stop()

        configure_display_timer = Timer(self.timeit, "configure display")

        def set_slider(i, s_min, s_max):
            s_min = -0.02 if abs(s_min) < 1e-4 else s_min * self.bb_factor
            s_max = 0.02 if abs(s_max) < 1e-4 else s_max * self.bb_factor
            self.clipping.sliders[
                i].max = 2**31  #  first increase max to avoid traitlet error that min > max
            self.clipping.sliders[
                i].min = s_min  # set min which now is always < max
            self.clipping.sliders[i].max = s_max  # correct max
            self.clipping.sliders[i].value = s_max

        bb = self.cq_view.bb
        set_slider(1, bb.xmin, bb.xmax)
        set_slider(3, bb.ymin, bb.ymax)
        set_slider(5, bb.zmin, bb.zmax)

        # Tree widget to change visibility
        self.tree_view = TreeView(
            image_paths=self.image_paths,
            tree=tree,
            state=self.states,
            layout=Layout(height="%dpx" % (self.height * 0.6 - 25),
                          width="%dpx" % (self.tree_width - 20)),
        )
        self.tree_view.add_class("view_tree")
        self.tree_view.add_class("scroll-area")
        if self.mac_scrollbar:
            self.tree_view.add_class("mac-scrollbar")

        self.tree_view.observe(self.cq_view.change_visibility(self.paths),
                               "state")
        self.tree_clipping.children = [
            self.tree_view, self.tree_clipping.children[1]
        ]

        # Set initial state

        for obj, vals in self.states.items():
            for i, val in enumerate(vals):
                self.cq_view.set_visibility(self.paths[obj], i, val)

        self.toggle_axes(self.axes)
        self.toggle_center(self.axes0)
        self.toggle_grid(self.grid)
        self.toggle_transparent(self.transparent)
        self.toggle_black_edges(self.black_edges)
        self.toggle_ortho(self.ortho)

        self.clean = False
        configure_display_timer.stop()
        if SIDECAR is not None:
            print("Done, using side car '%s'" % SIDECAR.title)