예제 #1
0
def get_feat_selection_lakeland(df,  max_lvl=9):
    """
    Gets the feature selection widget.
    :param df:
    :param max_lvl:
    :return:
    """
    start_level = widgets.IntSlider(value=0, min=0, max=max_lvl, step=1, description='Start Level:',
                                    disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d')
    end_level = widgets.IntSlider(value=0, min=0, max=max_lvl, step=1, description='End Level:',
                                  disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d')
    level_selection = widgets.GridBox([start_level, end_level])

    def change_start_level(change):
        end_level.min = start_level.value
        if end_level.value < start_level.value:
            end_level.value = start_level.value
    start_level.observe(change_start_level, names="value")

    lvl_feats = sorted(set([f[5:] for f in df.columns if f.startswith('lvl')]))
    sess_feats = sorted(
        set([f[5:] for f in df.columns if f.startswith('sess_')]))
    other_feats = sorted(set([f for f in df.columns if not f.startswith(
        'lvl') and not f.startswith('sess_')]))
    selection_widget = widgets.GridBox([multi_checkbox_widget(lvl_feats, 'lvl'),
                                        multi_checkbox_widget(
                                            sess_feats, 'sess'),
                                        multi_checkbox_widget(
                                            other_feats, 'other'),
                                        level_selection],
                                       layout=widgets.Layout(grid_template_columns=f"repeat(3, 500px)"))

    return selection_widget
예제 #2
0
def get_feat_selection(df, session_prefix, max_lvl, cc_prefix_max_list=None):
    """
    Gets the feature selection widget.
    :param df:
    :param max_lvl:
    :return:
    """

    cc_prefix_max_list = cc_prefix_max_list or []
    checkbox_widgets = []
    slider_widgets = []
    feats = set()

    for prefix, max_val in [('lvl', max_lvl)] + cc_prefix_max_list:
        start_val = widgets.IntSlider(value=0, min=0, max=max_val, step=1, description=f'Start {prefix}:',
                                      disabled=False, continuous_update=False, orientation='horizontal', readout=True,
                                      readout_format='d')
        end_val = widgets.IntSlider(value=0, min=0, max=max_val, step=1, description=f'End {prefix}:',
                                    disabled=False, continuous_update=False, orientation='horizontal', readout=True,
                                    readout_format='d')
        val_selection = widgets.GridBox([start_val, end_val])
        slider_widgets.append(val_selection)
        val_feats_set = set(['_'.join(f.split('_')[1:])
                             for f in df.columns if f.startswith(prefix)])
        feats = feats.union(
            [f'{prefix}{n}_{v}' for n in range(max_val+1) for v in val_feats_set])
        val_feats = sorted(val_feats_set)
        val_feats_checkbox = multi_checkbox_widget(val_feats, prefix)
        checkbox_widgets.append(val_feats_checkbox)

    other_feats = sorted(set(df.columns).difference(feats))
    selection_widget = widgets.GridBox(checkbox_widgets+slider_widgets+[multi_checkbox_widget(other_feats, 'other')],
                                       layout=widgets.Layout(grid_template_columns=f"repeat({len(slider_widgets)}, 500px)"))

    return selection_widget
예제 #3
0
 def _get_tasks_gridbox(grid_job):
     gridbox_children = [task_gridbox_children]
     task_details_list = []
     for task_name in grid_job.tasks.names:
         progress = grid_job.tasks.get(task_name).progress
         status = grid_job.tasks.get(task_name).status
         progress = widgets.IntProgress(value=progress, min=0, max=100)
         status_label = widgets.Label(status)
         task_name_label = widgets.Label(task_name)
         task_details = widgets.Output()
         logs = grid_job.tasks.get(task_name).logs
         details_button = _get_details_button(_toggle_info_display,
                                              task_details, task_name, logs)
         task_details_list.append(task_details)
         row_children = [
             task_name_label, progress, status_label, details_button
         ]
         row_box = widgets.GridBox(
             children=row_children,
             layout=widgets.Layout(grid_template_columns='43% 43% 9% 5%'))
         gridbox_children.append(row_box)
         gridbox_children.append(task_details)
     grid_box = widgets.GridBox(children=gridbox_children,
                                layout=widgets.Layout(width='100%'))
     return grid_box
예제 #4
0
 def welems(self, elements, e):
     elTitle = widgets.Label(value='Elements')
     elemtext = ['Element#', 'Nodei', 'Nodej', 't', 'Mat#']
     elem = [[] for i in range(self.e)]
     self.eitems = [[] for i in range(self.e)]
     self.ADDELEM = widgets.Button(description="Add Element",
                                   layout=widgets.Layout(
                                       border='solid 1px black',
                                       width='120px'))
     self.DELELEM = widgets.Button(description="Remove Element",
                                   layout=widgets.Layout(
                                       border='solid 1px black',
                                       width='120px'))
     elabel = widgets.GridBox(
         [widgets.Label(value=elemtext[j]) for j in range(5)],
         layout=widgets.Layout(
             grid_template_columns="repeat(5, 50px[col-start])"))
     for i in range(self.e):
         if (i < len(self.elements)):
             for j in range(5):
                 self.eitems[i].append(
                     widgets.FloatText(value=self.elements[i, j],
                                       layout=widgets.Layout(
                                           width='50px', height='22px')))
             elem[i] = widgets.HBox(self.eitems[i],
                                    layout=widgets.Layout(height='30px'))
         if (i >= len(self.elements)):
             for j in range(5):
                 if (j < 3):
                     self.eitems[i].append(
                         widgets.FloatText(
                             value=self.elements[i - 1, j] + 1,
                             layout=widgets.Layout(width='50px',
                                                   height='22px')))
                 if (j >= 3):
                     self.eitems[i].append(
                         widgets.FloatText(
                             value=self.elements[i - 1, j],
                             layout=widgets.Layout(width='50px',
                                                   height='22px')))
             elem[i] = widgets.GridBox(self.eitems[i],
                                       layout=widgets.Layout(height='30px'))
     elemr = widgets.VBox([elem[j] for j in range(e)])
     brow = widgets.HBox([self.ADDELEM, self.DELELEM],
                         layout=widgets.Layout(width='30%'))
     self.relem = widgets.VBox(
         [elTitle, elabel, elemr, brow],
         layout=widgets.Layout(border='solid 1px black'))
     return self.relem, self.ADDELEM, self.DELELEM, self.eitems
def layout_app(header, sidebar, main_, footer):
    header_area = widgets.HBox(
        children=header,
        layout=widgets.Layout(
            width="auto", grid_area="header", justify_content="center"
        ),
    )
    sidebar_area = widgets.HBox(
        children=sidebar, layout=widgets.Layout(width="auto", grid_area="sidebar")
    )
    main_area = widgets.HBox(
        children=main_, layout=widgets.Layout(width="auto", grid_area="main")
    )
    footer_area = widgets.HBox(
        children=footer,
        layout=widgets.Layout(
            width="auto", grid_area="footer", justify_content="center"
        ),
    )

    page = widgets.GridBox(
        children=[header_area, main_area, sidebar_area, footer_area],
        layout=widgets.Layout(
            width="95%",
            grid_template_rows="auto auto auto",
            grid_template_columns="25% 25% 25% 25%",
            grid_template_areas="""
                "header header header header"
                "sidebar main main main "
                "footer footer footer footer"
                """,
        ),
    )
    ip.display(page)
예제 #6
0
    def widget(self):
        box = widgets.GridBox(layout=widgets.Layout(
            grid_template_columns='25% 25% 25% 25%'))

        #box = widgets.VBox()
        self._update(box)
        return box
예제 #7
0
 def __init__(self, module, scheduler=None):
     self._module = module
     self.info_labels = {}
     lst = []
     for k, lab in self.info_keys.items():
         lst.append(ipw.Label(lab))
         lst.append(self._info_label(k))
     lst.append(ipw.Label("Rows"))
     self._rows_label = ipw.Label("0")
     lst.append(self._rows_label)
     self._module.after_run_proc = _refresh_info(self)
     gb = ipw.GridBox(
         lst, layout=ipw.Layout(grid_template_columns="repeat(2, 120px)"))
     if not module.hist:
         super().__init__(children=[gb])
     else:
         hlist = []
         for hmod in module.hist.values():
             hout = VegaWidget(spec=spec_no_data)
             hlist.append(hout)
             hmod.after_run_proc = _refresh_info_hist(hout, hmod)
         htab = ipw.Tab(hlist)
         for i, t in enumerate(module.hist.keys()):
             htab.set_title(i, t)
         super().__init__(children=[gb, htab])
예제 #8
0
def form(fields, label_position="left"):
    if label_position not in {"left", "top"}:
        raise ValueError("label_position")

    if label_position == "left":
        grid_template_columns = "auto 1fr"
        label_layout = widgets.Layout(display="flex",
                                      justify_content="flex-end")
        children = list(
            chain.from_iterable(
                (widgets.Label(label + ":", layout=label_layout), control)
                for label, control in fields))
    else:
        grid_template_columns = "max-content"
        children = [
            widgets.VBox([widgets.Label(label + ":"), control],
                         layout=widgets.Layout(margin="0"))
            for label, control in fields
        ]

    return widgets.GridBox(
        children=children,
        layout=widgets.Layout(
            grid_template_columns=grid_template_columns,
            grid_template_rows="max-content " * len(fields),
            grid_gap="8px",
        ),
    )
예제 #9
0
def labelled_input_generator(
    label: str,
    layout_class: Literal['HBox', 'VBox'],
    text_default_value: Optional[str] = None,
    layout: Optional[widgets.Layout] = None,
    text_class: Union[Type[widgets.Text],
                      Type[widgets.Textarea]] = widgets.Text
) -> widgets.Box:
    """Construct a labelled input field.
    :param label:  The label string of the field
    :param layout_class: The name of layout class
    :param text_default_value: The default value for the input.
    :param layout: The user-defined layout, which will override layout_class
    :param text_class: The text widget used for the user input.
    :return: An IPython widget containing a label and a text input field.
    """
    if layout is None:
        if layout_class == 'HBox':
            layout = widgets.Layout(grid_template_columns='1fr 3fr')
        else:
            layout = widgets.Layout(grid_template_columns='1fr')

    return widgets.GridBox(
        [widgets.Label(label),
         text_class(value=text_default_value)],
        layout=layout)
예제 #10
0
    def __init__(self, **kwargs):
        # Create description label
        self.description_label = widgets.Label(
            value=kwargs.get("description", ""))
        widgets.link((self.description_label, "value"), (self, "description"))

        # Create widgets
        value_trait = self.traits()["value"]
        ctx = kwargs["ctx"]
        self.widgets = ctx.create_widgets_for_model_cls(
            ctx.resolve(value_trait.klass))

        # Create box container for widgets
        self.widgets_container = widgets.GridBox(
            list(self.widgets.values()), layout={"flex_flow": "column"})
        self._links = []

        self._logger = ctx.logger

        shared_trait_names = self.class_traits().keys() & self.widgets.keys()
        if shared_trait_names:
            raise ValueError(
                f"Traits {shared_trait_names} clash with builtin widget trait names"
            )

        super().__init__(
            children=[
                self.description_label,
                self.widgets_container,
            ],
            **kwargs,
        )
예제 #11
0
def make_clear_button(watcher: "IBMDashboard") -> widgets.GridBox:
    """Makes the clear button.

    Args:
        watcher: The watcher widget instance.

    Returns:
        The clear button widget.
    """
    clear = widgets.Button(
        description="Clear",
        button_style="primary",
        layout=widgets.Layout(width="70px",
                              grid_area="right",
                              padding="0px 0px 0px 0px"),
    )

    def on_clear_button_clicked(_):
        """Clear finished jobs."""
        watcher.clear_done()

    clear.on_click(on_clear_button_clicked)

    clear_button = widgets.GridBox(
        children=[clear],
        layout=widgets.Layout(
            width="100%",
            grid_template_columns="20% 20% 20% 20% 20%",
            grid_template_areas="""
                                       ". . . . right "
                                        """,
        ),
    )
    return clear_button
예제 #12
0
    def _add_element_pane(self, element):
        header, field_values = self._unpack_element(element)

        if self.attempt_batch_prefetch:
            self._do_retrieve_batch(element, field_values)

        import html
        grid_content_boxes = []
        for field, value in field_values.items():
            field_display_name = self._to_field_display_name(element, field)
            if field_display_name and (value
                                       is not None) and not ([] == value):
                field_widget = widgets.HTML(
                    value="<b>{}</b>".format(html.escape(field_display_name)))
                field_box = widgets.Box(children=[field_widget],
                                        layout=self.field_box_layout)
                slot_widget_list = self._value_widget_list(
                    element, field, value)
                slot_box = widgets.Box(children=slot_widget_list,
                                       layout=self.slot_box_layout)
                grid_content_boxes.extend([field_box, slot_box])
        content = widgets.GridBox(layout=self.grid_container_layout,
                                  children=grid_content_boxes)

        self.accordion.children = list(self.accordion.children) + [content]
        self.accordion.set_title(len(self.element_list), header)
        self.element_id_to_index[self._to_hashable_identifier(element)] = len(
            self.element_list)
        self.element_list.append(element)
예제 #13
0
파일: settings_tab.py 프로젝트: pypm/ipypm
def get_parameters_tab(self):
    
    items = []
    par_name_list = list(self.model.parameters.keys())
    par_name_list.sort()
    for par_name in par_name_list:
        par = self.model.parameters[par_name]
        cb = widgets.Checkbox(
        value=not par.hidden,
        description=par_name,
        disabled=False)
        items.append(cb)
        
    def par_eventhandler(change):
        owner = change['owner']
        pop_name = owner.description
        new_val = change['new']
        pop = self.model.parameters[pop_name]
        pop.hidden = not new_val
    
    for item in items:
        item.observe(par_eventhandler, names='value')
        
    return widgets.GridBox(items,
        layout=widgets.Layout(grid_template_columns="repeat(3, 200px)"))
예제 #14
0
    def box_maker(name, widget, group):
        layout = widgets.Layout(grid_template_columns="1fr",
                                border='2px solid gray')
        b = widgets.GridBox(layout=layout)
        module = extract_module_name(widget, full=True)
        #print('    ', widget.__name__, module)
        if 'selection' in module:
            extra_args = dict(options=[1, 2, 3])
        elif 'progress' in widget.__name__.lower():
            extra_args = dict(value=50)
        elif 'gridspeclayout' in widget.__name__.lower():
            extra_args = dict(n_rows=3, n_columns=3)
        else:
            extra_args = {}

        wid = widget(description='A label!', **extra_args)

        try:
            short_description = wid.__doc__.split('\n')[0]
            if not short_description:
                short_description = wid.__doc__.split('\n')[1]
        except AttributeError:
            short_description = ''

        url = f'{help_url_base}#{name}'
        help_link = f'<h3><a href="{url}" rel="nofollow" target="_self" style="color:gray;">{name}</a></h3><p>{short_description}</p>'
        title = widgets.Output()
        title.append_display_data(HTML(help_link))
        title.layout.padding = '10px'
        b.layout.overflow_x = 'hidden'
        b.children = [title, wid]

        return b
예제 #15
0
def make_clear_button(watcher: 'IQXDashboard') -> widgets.GridBox:
    """Makes the clear button.

    Args:
        watcher: The watcher widget instance.

    Returns:
        The clear button widget.
    """
    clear = widgets.Button(description='Clear',
                           button_style='primary',
                           layout=widgets.Layout(width='70px',
                                                 grid_area='right',
                                                 padding="0px 0px 0px 0px"))

    def on_clear_button_clicked(_):
        """Clear finished jobs."""
        watcher.clear_done()

    clear.on_click(on_clear_button_clicked)

    clear_button = widgets.GridBox(
        children=[clear],
        layout=widgets.Layout(width='100%',
                              grid_template_columns='20% 20% 20% 20% 20%',
                              grid_template_areas='''
                                       ". . . . right "
                                        '''))
    return clear_button
예제 #16
0
def colorwidget(img, paramlist=None):
    """Display info to user on colorspace if paramlist is not empty."""
    if paramlist:
        seg = colorspace(paramlist=paramlist)
    else:
        seg = colorspace()

    print(f"seg.params = {seg.params}")
    widg = dict()
    widglist = []

    for ppp, ind in zip(seg.paramindexes, range(len(seg.paramindexes))):
        thislist = seg.params.ranges[ppp]
        name = ppp
        current_value = seg.params[ppp]
        if current_value not in thislist:
            # TODO: We should find the min distance between current_value and
            # this list and use that instead.
            current_value = thislist[0]

        thiswidg = widgets.SelectionSlider(
            options=tuple(thislist),
            disabled=False,
            description=name,
            value=current_value,
            continuous_update=False,
            orientation="horizontal",
            readout=True,
        )

        widglist.append(thiswidg)
        widg[ppp] = thiswidg

    def func(**kwargs):
        """Find mask and fitness for current algorithm. Show masked image."""
        for k in kwargs:
            seg.params[k] = kwargs[k]
        colorspace = seg.evaluate(img)

        # fit = Segmentors.FitnessFunction(mask, gmask)
        fig = showtwo(img, colorspace)
        showimage(
            img,
            ax=fig.gca(),
            color=seg.params["colorspace"],
            multichannel=seg.params["multichannel"],
            channel=seg.params["channel"],
        )
        # I like the idea of printing the sharepython but it should be below the figures.
        # print(seg.sharepython(img))

    #         plt.title('Fitness Value: ' + str(fit[0]))

    layout = widgets.Layout(grid_template_columns="1fr 1fr 1fr")
    u_i = widgets.GridBox(widglist, layout=layout)
    out = widgets.interactive_output(func, widg)
    display(u_i, out)

    return seg.params
예제 #17
0
파일: ui.py 프로젝트: libp2p/test-plans
def collapsible(title, params, expanded=False):
    grid = widgets.Layout(width='900px',
                          grid_template_columns="repeat(2, 400px)")
    inner = widgets.GridBox(params, layout=grid)
    a = widgets.Accordion(children=[inner])
    a.set_title(0, title)
    a.selected_index = 0 if expanded else None
    return a
예제 #18
0
    def __init__(self):
        super(MyControlWidget, self).__init__()

        # Load settings
        self.settings = QtCore.QSettings("Lev Corp.", "woerdle-zehla")

        self.input_widget = widgets.GridBox()
        self.source_file_input = None
        self.sample_size_box = None
        self.init_ui()
예제 #19
0
 def __init__(self, col):
     width = round(100.0 / col, 2)
     template = ""
     for i in range(col):
         template += str(width) + "% "
     self.grid = widgets.GridBox(
         children=[],
         layout=widgets.Layout(
             grid_template_columns=template
         )
     )
예제 #20
0
파일: module.py 프로젝트: nevermind78/Gauss
def wid(n, m):
    items = [
        widgets.Text(value='0',
                     placeholder='a',
                     description=indices(n, m)[i],
                     layout=Layout(width='75%', height='75%'),
                     disabled=False) for i in indices(n, m).keys()
    ]
    return widgets.GridBox(
        items,
        layout=widgets.Layout(
            grid_template_columns="repeat({}, 200px)".format(m)))
예제 #21
0
    def build_button_controls(self):

        self.labelled_sample_size_box = self.label_sample_size_box()
        self.sample_button = create_expanded_button('Sample', 'warning')
        self.calculate_button = create_expanded_button('Calculate', 'warning')

        return widgets.GridBox(
            [
                self.labelled_sample_size_box, self.sample_button,
                self.calculate_button
            ],
            layout=widgets.Layout(grid_template_columns="repeat(1, 99.5%)"))
예제 #22
0
파일: core.py 프로젝트: TMMV/classypandas
    def __init__(self, df, html_col, target, labels):
        self.df = df
        self.html_col = html_col
        self.target = target
        self.labels = labels

        # go to next unfilled row
        self.current_pos = self.df[target].isnull().idxmax()

        if self.current_pos is None or self.current_pos > len(self.df):
            self.current_pos = self.df.iloc[0].index

        self.progress = ipywidgets.widgets.HTML(grid_area='progress')
        self.update_progress()

        # create main section
        self.update_to_pos(self.current_pos)

        previous_button = ipywidgets.widgets.Button(tooltip='previous',
                                                    icon='arrow-left',
                                                    layout=ipywidgets.Layout(
                                                        height='auto',
                                                        width='auto'),
                                                    grid_area='prev')
        next_button = ipywidgets.widgets.Button(tooltip='next',
                                                icon='arrow-right',
                                                layout=ipywidgets.Layout(
                                                    height='auto',
                                                    width='auto'),
                                                grid_area='next')
        previous_button.on_click(lambda b: self.move_pos('prev'))
        next_button.on_click(lambda b: self.move_pos('next'))

        clear_button = ipywidgets.Button(description='Clear',
                                         layout=ipywidgets.Layout(
                                             height='50px', width='auto'),
                                         grid_area='clear')
        clear_button.on_click(lambda b: self.clear())

        self.set_button_labels()

        self.grid = ipywidgets.GridBox(children=[
            previous_button, self.html_section, next_button, clear_button,
            self.button_grid, self.progress
        ],
                                       layout=ipywidgets.Layout(
                                           max_width='1400px',
                                           grid_template_rows='auto auto auto',
                                           grid_template_columns='10% 80% 10%',
                                           grid_template_areas='''
                    "prev main next"
                    "clear button_grid progress"
                '''))
예제 #23
0
 def wprops(self, props, m):
     matTitle = widgets.Label(value='Material Properties')
     mattext = ['mat#', 'Ex', 'Ey', 'vx', 'vy', 'G']
     prop = [[] for i in range(self.m)]
     self.mitems = [[] for i in range(self.m)]
     self.ADDMAT = widgets.Button(
         description="Add Material",
         layout=widgets.Layout(border='solid 1px black'))
     self.DELMAT = widgets.Button(
         description="Remove Material",
         layout=widgets.Layout(border='solid 1px black'))
     matlabel = widgets.GridBox(
         [widgets.Label(value=mattext[j]) for j in range(6)],
         layout=widgets.Layout(
             grid_template_columns="repeat(6, 50px[col-start])"))
     for i in range(self.m):
         if (i < len(self.props)):
             for j in range(6):
                 self.mitems[i].append(
                     widgets.FloatText(value=self.props[i, j],
                                       layout=widgets.Layout(width='70px')))
             prop[i] = widgets.GridBox(
                 self.mitems[i],
                 layout=widgets.Layout(
                     grid_template_columns="repeat(6, 50px[col-start])"))
         if (i >= len(self.props)):
             for j in range(6):
                 self.mitems[i].append(
                     widgets.FloatText(value=self.props[i - 1, j],
                                       layout=widgets.Layout(width='70px')))
             prop[i] = widgets.GridBox(
                 self.mitems[i],
                 layout=widgets.Layout(
                     grid_template_columns="repeat(6, 50px[col-start])"))
     matr = widgets.VBox([prop[j] for j in range(m)])
     brow = widgets.HBox([self.ADDMAT, self.DELMAT])
     self.rowm = widgets.VBox([matTitle, matlabel, matr, brow],
                              layout=widgets.Layout(
                                  border='solid 1px black', width='35%'))
     return self.rowm, self.ADDMAT, self.DELMAT, self.mitems
예제 #24
0
    def __init__(self, input_box, plot_box, output_box):

        # File layout.
        self.file_box = wg.Box()

        # Help layout.
        self.help_box = wg.Box()

        # Input area.
        narrow_input_btn = self.autosize_button('🡐')
        narrow_input_btn.on_click(self.on_narrow_input)
        widen_input_btn = self.autosize_button('🡒')
        widen_input_btn.on_click(self.on_widen_input)
        input_header = wg.HBox(
            [wg.Label(value='Input'), narrow_input_btn, widen_input_btn])
        input_layout = wg.VBox([input_header, input_box],
                               layout=wg.Layout(width='auto',
                                                grid_area='input'))

        # Plot area.
        narrow_plot = self.autosize_button('🡑')
        narrow_plot.on_click(self.on_narrow_plot)
        widen_plot = self.autosize_button('🡓')
        widen_plot.on_click(self.on_widen_plot)
        plot_header = wg.HBox(
            [wg.Label(value='Plots'), narrow_plot, widen_plot])
        plot_layout = wg.VBox([plot_header, plot_box],
                              layout=wg.Layout(width='auto', grid_area='plot'))

        # Output area.
        output_header = wg.HBox([wg.Label(value='Output')])
        output_layout = wg.VBox([output_header, output_box],
                                layout=wg.Layout(width='auto',
                                                 grid_area='output'))

        self.calc_layout = wg.GridBox(
            children=[input_layout, plot_layout, output_layout],
            layout=wg.Layout(grid_template_rows='50% auto',
                             grid_template_columns='50% auto',
                             grid_template_areas='''
                                                       "input plot"
                                                       "input output"
                                                       '''))

        # Tabbed layout for overall app.
        self.main_view = wg.Tab()
        self.main_view.children = [
            self.calc_layout, self.help_box, self.file_box
        ]
        self.main_view.set_title(0, 'App')
        self.main_view.set_title(1, 'Help')
        self.main_view.set_title(2, 'File')
예제 #25
0
def segmentwidget(img, gmask, params=None, alg=None):
    """Generate GUI. Produce slider for each parameter for the current segmentor.
     Show both options for the masked image.

    Keyword arguments:
    img -- original image
    gmask -- ground truth segmentation mask for the image
    params -- list of parameter options
    alg -- algorithm to search parameters over

    """
    if params is None and alg is None:
        alg = 'FB'
        params = [alg, 0, 0.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,\
         (1, 1), 0, 'checkerboard', 'checkerboard', 0, 0, 0, 0, 0, 0]
    elif params is None and alg is not None:
        params = [alg, 0, 0.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,\
         (1, 1), 0, 'checkerboard', 'checkerboard', 0, 0, 0, 0, 0, 0]
    elif params is not None and alg is not None:
        params[0] = alg
    seg = Segmentors.algoFromParams(params)
    widg = dict()
    widglist = []

    for ppp in seg.paramindexes:
        thislist = eval(seg.params.ranges[ppp])
        thiswidg = widgets.SelectionSlider(options=tuple(thislist),
                                           disabled=False,
                                           description=ppp,
                                           value=seg.params[ppp],
                                           continuous_update=False,
                                           orientation='horizontal',
                                           readout=True)
        widglist.append(thiswidg)
        widg[ppp] = thiswidg

    def func(img=img, mask=gmask, **kwargs):
        """Find mask and fitness for current algorithm. Show masked image."""
        print(seg.params["algorithm"])
        for k in kwargs:
            seg.params[k] = kwargs[k]
        mask = seg.evaluate(img)
        fit = Segmentors.FitnessFunction(mask, gmask)
        fig = showtwo(img, mask)
        plt.title('Fitness Value: ' + str(fit[0]))

    layout = widgets.Layout(grid_template_columns='1fr 1fr 1fr')
    u_i = widgets.GridBox(widglist, layout=layout)

    out = widgets.interactive_output(func, widg)
    display(u_i, out)
    return seg.params
예제 #26
0
 def ui(self):
     """Return the input container."""
     wdg = []
     grid_layout = ipy.Layout(grid_template_columns=self._tpl,
                              grid_gap='5px 5px')
     lbl = ipy.HTML('{}'.format(self.label))
     hint = ipy.Label(self.hint)
     wdg = []
     wdg.append(lbl)
     wdg.append(self.input)
     wdg.append(hint)
     box = ipy.GridBox(wdg, layout=grid_layout)
     return box
예제 #27
0
    def __init__(self, graph, variables=[]):
        if not isinstance(graph, (networkx.Graph, networkx.DiGraph)):
            graph = graph.networkx()
        self._graph = graph
        self._variables = variables

        nodes = graph.vertices()
        self._rank = {v: i for i, v in enumerate(nodes)}

        try:
            # ignore a FutureWarning in numpy raised
            # by networkx's planar_layout
            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                layout = networkx.planar_layout(graph)
        except networkx.NetworkXException:
            layout = networkx.spring_layout(graph)
        xs = bqplot.LinearScale()
        ys = bqplot.LinearScale()
        cs = bqplot.ColorScale(scheme='Reds')
        x = [layout[node][0] for node in nodes]
        y = [layout[node][1] for node in nodes]

        fig_layout = ipywidgets.Layout(width='400px', height='400px')
        self._mark = mark = bqplot.marks.Graph(node_data=self.node_data(),
                                               link_type='line',
                                               directed=graph.is_directed(),
                                               scales={
                                                   'x': xs,
                                                   'y': ys,
                                                   'link_color': cs
                                               },
                                               x=x,
                                               y=y,
                                               charge=-600,
                                               colors=self.colors())

        fig = bqplot.Figure(marks=[mark], layout=fig_layout)

        self._variable_views = {}
        variables_boxes = []
        for v in variables:
            label = ipywidgets.Label(v['name'])
            output = ipywidgets.Output()
            self._variable_views[v['name']] = output
            variables_boxes.extend([label, output])
        variables_view = ipywidgets.GridBox(
            variables_boxes,
            layout=ipywidgets.Layout(grid_template_columns='1fr 1fr'))
        ipywidgets.VBox.__init__(self, [fig, variables_view])
        self.update()
예제 #28
0
    def start_experiment(self):
        # linking button and function together using a button's method
        [button.on_click(self.on_button_clicked) for button in self.buttons]

        return widgets.GridBox(children=self.buttons + [self.out] + [self.img],
                               layout=widgets.Layout(
                                   width='70%',
                                   grid_template_rows='auto auto',
                                   grid_template_columns='25% 25% 25% 25%',
                                   grid_template_areas='''
                           "instruct instruct instruct instruct"
                           "button0 button1 button2 button3"
                           "output output output output"
                           '''))
예제 #29
0
    def widget_layout(self, out):
        sliders = self.sliders
        layout = ipw.Layout(grid_template_columns='1fr 1fr')
        param_sliders_list = [sliders[py_var] for py_var in self.py_vars[1:]]
        t_slider = sliders['t']
        grid = ipw.GridBox(param_sliders_list, layout=layout)
        w_max_text = ipw.FloatText(value=self.w_max,
                                   description=r'w_max',
                                   disabled=False)
        out_w_max = ipw.interactive_output(self.set_w_max,
                                           {'w_max': w_max_text})

        hbox = ipw.HBox([t_slider, w_max_text])
        box = ipw.VBox([hbox, grid, out, out_w_max])
        display(box)
예제 #30
0
    def start_experiment(self):
        # linking button and function together using a button's method
        [button.on_click(self.on_button_clicked) for button in self.buttons]

        self.next_trial()

        return widgets.GridBox(children=self.buttons + [self.canvas],
                               layout=widgets.Layout(
                                   width='50%',
                                   justify_items='center',
                                   grid_template_rows='auto auto',
                                   grid_template_columns='10% 40% 40% 10%',
                                   grid_template_areas='''
                           ". canvas canvas ."
                           ". button0 button1 ."
                           "output output output output"
                           '''))