예제 #1
0
    def __init__(self, path):
        self.db_view = SimpleDatabaseView()

        toolbar = ToolBar(['eye-slash', 'list', 'image'], exclusive=True, current=0)
        self.toolbar = toolbar
        self.hierarchy_bar = HierarchyBar(path, layout=Layout(width='70%'))
        self.length_label = RichLabel('[0]')
        self.header = HBox([toolbar,  HTML(layout=Layout(width='25px')),
                            self.hierarchy_bar, HTML(layout=Layout(width='40px')),
                            self.length_label], layout=Layout(align_content='flex-end'))

        self.offset_edit = BoundedIntText(description='offset: ', value=self.db_view.offset, min=0,
                                          layout=Layout(width='150px'))
        self.limit_edit = BoundedIntText(description='limit: ', value=self.db_view.limit, min=0, max=self.db_view.limit,
                                          layout=Layout(width='150px'))
        self.progress = TinyLoading(layout=Layout(width='150px'))
        self.foot = HBox([self.offset_edit, self.limit_edit, HSpace(), self.progress],
                         layout=Layout(align_items='center'))

        jsdlink((self.offset_edit, 'value'), (self.db_view, 'offset'))
        jsdlink((self.limit_edit, 'value'), (self.db_view, 'limit'))
        jsdlink((self.db_view, 'cache_progress'), (self.progress, 'value'))

        def toolbar_handling(button_id):
            self.db_view.visible = button_id != 0
            self.foot.layout.display = 'none' if button_id == 0 else 'flex'
        self.toolbar.on_button_clicked(toolbar_handling)
        toolbar_handling(0)

        super(DatabaseView, self).__init__([self.header, VSpace(), self.db_view, self.foot])
예제 #2
0
    def __init__(self, data, dimensions, **kwargs):
        GluePlotly.__init__(self, data, dimensions, **kwargs)
        self.DefaultLayoutTitles("", "", "")
        self.options['line_width'] = BoundedIntText(description='Lines width:',
                                                    value=1,
                                                    min=0,
                                                    max=10)
        self.options['line_width'].observe(
            lambda v: self.UpdateTraces({'line.width': v['new']}),
            names='value')
        self.options['marker_size'] = BoundedIntText(
            description='Markers size:', value=3, min=0, max=15)
        self.options['marker_size'].observe(
            lambda v: self.UpdateTraces({'marker.size': v['new']}),
            names='value')
        self.options['layout_type'] = Dropdown(description='Layout type:',
                                               value=self.default_layout_type,
                                               options=self.layout_options)
        self.options['layout_type'].observe(lambda v: self.updateRender(),
                                            names='value')
        self.options['layout_k'] = BoundedIntText(description='Layout k:',
                                                  value=5,
                                                  min=1,
                                                  max=10)
        self.options['layout_k'].observe(lambda v: self.updateRender(),
                                         names='value')
        self.options['layout_iter'] = BoundedIntText(
            description='Layout Iter:', value=100, min=20, max=250)
        self.options['layout_iter'].observe(lambda v: self.updateRender(),
                                            names='value')
        self.DefaultLegend('v', 1.02, 1.0)

        self.updateRender()
예제 #3
0
    def __init__(self, signal_components: dict, parent=None):
        """
        Summary:
            Object constructor.
        
        Arguments :
            signal_components - dictionary with the signal/components names
            parent - reference to the parent widget
        """
        super().__init__(signal_components, state_change_detector_widget._type,
                         parent)

        wbit_min_duration = BoundedIntText(description="min_duration:",
                                           value=7,
                                           min=0,
                                           step=1,
                                           disabled=False)

        wbit_to_state = BoundedIntText(description="to_state:",
                                       value=4,
                                       min=0,
                                       step=1,
                                       disable=False)

        self.add_options([wbit_min_duration, wbit_to_state])
예제 #4
0
 def __init__(self, data, dimensions, **kwargs):
     GluePlotly.__init__(self, data, dimensions, **kwargs)
     self.DefaultLayoutTitles("", 'I Component', 'J Component')
     self.DefaultLayoutScales("linear","linear");
     self.options['line_width'] = BoundedIntText(description = 'Lines width:', value = 1, min=0, max=10)
     self.options['line_width'].observe(lambda v:self.UpdateTraces({'line.width':v['new']}), names='value')        
     self.options['marker_size'] = BoundedIntText(description = 'Markers size:', value = 3, min=0, max=15)
     self.options['marker_size'].observe(lambda v:self.UpdateTraces({'marker.size':v['new']}), names='value')        
     self.options['pca_method'] = Dropdown(description = 'PCA Method:', value = 'PCA', options = ['PCA','KPCA','IPCA'])
     self.options['pca_method'].observe(lambda v:self.updateRender(), names='value')
     self.DefaultLegend('v', 1.02, 1.0);
     
     self.updateRender()
예제 #5
0
파일: shap.py 프로젝트: kiminh/expybox
    def build_options(self):
        options_map, options_grid = super().build_options()
        # remove unnecessary dropdown with plot selection
        options_map['plot_type'].layout.visibility = 'hidden'
        del options_map['plot_type']

        # and with class_to_explain (if it exists)
        if self.is_classification:
            # only the assignment triggers actual change of the widget (and only if it's not the original dict)
            options = options_map['class_to_explain'].options.copy()
            options['All'] = -1
            options_map['class_to_explain'].options = options
            options_map['class_to_explain'].value = -1

        # sample_size
        sample_size = BoundedIntText(
            min=1,
            max=self.X_train.shape[0],
            step=1,
            value=min(self.X_train.shape[0], 1000),
            description='Sample size:',
            description_tooltip=
            'Number of instances from train data to use for calculating mean shap value.',
            style={'description_width': '60%'})
        options_map['sample_size'] = sample_size
        options_grid[0, 0] = sample_size

        return options_map, options_grid
예제 #6
0
 def create_label_total(self):
     label_total = Label(value='/ {}'.format(len(self.objects)))
     self.text_index = BoundedIntText(value=1, min=1, max=len(self.objects))
     self.text_index.layout.width = '80px'
     self.text_index.layout.height = '35px'
     self.text_index.observe(self.selected_index)
     return label_total
예제 #7
0
    def intervals(self, intervals):
        self.intervals = intervals
        interval_widget = BoundedIntText(value=0,
                                         min=0,
                                         max=int(10) - 1,
                                         step=1,
                                         description='Interval number',
                                         disabled=False)
        btn_up = Button(description='Up',
                        disabled=False,
                        button_style='success')
        btn_down = Button(description='Down',
                          disabled=False,
                          button_style='warning')

        display_dropdown = Dropdown(
            options=['1', '2', '3', '4'],
            value='1',
            description='Display:',
            disabled=False,
            button_style='danger'  # 'success', 'info', 'warning', 'danger' or ''
        )

        def increase(t):
            interval_widget.value += 1

        def decrease(t):
            interval_widget.value -= 1

        display(btn_up)
        display(btn_down)
        btn_up.on_click(increase)
        btn_down.on_click(decrease)
        interact(self.plot, i=interval_widget, display=display_dropdown)
예제 #8
0
 def _init_ui(self) -> VBox:
     "Initialize the widget UI and return the UI."
     self._search_input = Text(placeholder="What images to search for?")
     self._count_input = BoundedIntText(placeholder="How many pics?",
                                        value=10,
                                        min=1,
                                        max=5000,
                                        step=1,
                                        layout=Layout(width='60px'))
     self._size_input = Dropdown(options=_img_sizes.keys(),
                                 value='>400*300',
                                 layout=Layout(width='120px'))
     self._download_button = Button(description="Search & Download",
                                    icon="download",
                                    layout=Layout(width='200px'))
     self._download_button.on_click(self.on_download_button_click)
     self._output = Output()
     self._controls_pane = HBox([
         self._search_input, self._count_input, self._size_input,
         self._download_button
     ],
                                layout=Layout(width='auto', height='40px'))
     self._heading = ""
     self._download_complete_heading = "<h3>Download complete. Here are a few images</h3>"
     self._preview_header = widgets.HTML(self._heading,
                                         layout=Layout(height='60px'))
     self._img_pane = Box(layout=Layout(display='inline'))
     return VBox(
         [self._controls_pane, self._preview_header, self._img_pane])
예제 #9
0
    def __init__(self, data, dimensions, **kwargs):
        GluePlotly.__init__(self, data, dimensions, **kwargs)
        self.options['title'] = Text(description='Title:', value="")
        self.options['title'].observe(
            lambda v: self.UpdateLayout({'title': v['new']}), names='value')
        self.options['xaxis'] = Text(description='Xaxis Title:',
                                     value=self.dimensions[0])
        self.options['xaxis'].observe(
            lambda v: self.UpdateLayout({'scene.xaxis.title': v['new']}),
            names='value')
        self.options['yaxis'] = Text(description='Yaxis Title:',
                                     value=self.dimensions[1])
        self.options['yaxis'].observe(
            lambda v: self.UpdateLayout({'scene.yaxis.title': v['new']}),
            names='value')
        self.options['zaxis'] = Text(description='Zaxis Title:',
                                     value=self.dimensions[2])
        self.options['zaxis'].observe(
            lambda v: self.UpdateLayout({'scene.zaxis.title': v['new']}),
            names='value')
        self.options['marker_size'] = BoundedIntText(
            description='Markers size:', value=3, min=0, max=15)
        self.options['marker_size'].observe(
            lambda v: self.UpdateTraces({'marker.size': v['new']}),
            names='value')
        self.DefaultLegend('v', 1.02, 1.0)

        self.updateRender()
예제 #10
0
    def __init__(self, algorithms: List[AbstractSolver],
                 puzzle_pack: SudokuPack):
        super().__init__()

        self.algorithms = algorithms
        self.puzzle_pack = puzzle_pack

        self.algorithm_dropdown = Dropdown(
            options={a.display_name(): a
                     for a in algorithms},
            description='Algorithm:',
        )

        self.puzzle_id_input = BoundedIntText(
            value=random.randrange(0, len(puzzle_pack)),
            min=0,
            max=len(puzzle_pack) - 1,
            description='Puzzle:',
        )

        self.random_btn = Button(description='Random')
        self.random_btn.on_click(self.random_puzzle)

        self.run_btn = Button(description='Run')
        self.run_btn.on_click(self.run)

        self.out = Output()
        self.result = None

        self.children = [
            self.algorithm_dropdown,
            HBox([self.puzzle_id_input, self.random_btn]),
            self.run_btn,
            self.out,
        ]
예제 #11
0
def my_text_box(value, mymin, mymax, step, description):
    return BoundedIntText(value=value,
                          min=mymin,
                          max=mymax,
                          step=step,
                          description=description,
                          style={'description_width': 'initial'})
예제 #12
0
    def app(self):
        self._out = Output(layout=Layout(width="{}px".format(self.width+2),
                                         height="{}px".format(self.height+2),
                                         border='1px solid black'))
        sld_frame = IntSlider(description="Frame",
                              min=0, max=self.num_frames-1,
                              step=1, value=self.active_frame,
                              layout=Layout(width="{}px".format(self.width)))
        btn_play = Play(description="Animate",
                        min=0, max=self.num_frames-1,
                        step=1, value=self.active_frame,
                        interval=200)
        btn_fwrd = Button(description="▶▶", layout=Layout(width="auto"))
        btn_revs = Button(description="◀◀", layout=Layout(width="auto"))
        drd_model = Dropdown(description="Model",
                             options=list(range(self.num_models)),
                             value=self.active_model)
        drd_style = Dropdown(description="Style",
                             options=['sticks', 'ballsticks', 'vanderwaals',
                                      'default'],
                             value='default')
        int_delay = IntText(description="Delay (ms)", value=100,
                            layout=Layout(max_width="150px"))
        int_step = BoundedIntText(description="Step", value=1,
                                  min=1, max=self.num_frames,
                                  layout=Layout(max_width="150px"))
        ui = VBox([HBox([drd_model, drd_style]),
                   self._out,
                   HBox([VBox([int_step, int_delay]),
                         VBox([sld_frame,
                               HBox([btn_revs, btn_play, btn_fwrd])],
                              layout=Layout(align_items='center'))])],
                  layout=Layout(align_items='center'))

        def frame_fwrd(btn):
            if (sld_frame.value < sld_frame.max):
                sld_frame.value += 1

        def frame_revs(btn):
            if (sld_frame.value > sld_frame.min):
                sld_frame.value -= 1

        def frame_change(model, frame, style):
            with self._out:
                self.update(model=model, frame=frame, style=style)

        btn_fwrd.on_click(frame_fwrd)
        btn_revs.on_click(frame_revs)
        jslink((btn_play, "value"), (sld_frame, "value"))
        jslink((int_delay, "value"), (btn_play, "interval"))
        jslink((int_step, "value"), (btn_play, "step"))
        interactive_output(frame_change, {'model': drd_model,
                                          'style': drd_style,
                                          'frame': sld_frame})

        IPython.display.display(ui)
예제 #13
0
 def __init__(self, data, dimensions, **kwargs):
     GluePlotly.__init__(self, data, dimensions, **kwargs)
     self.options['title'] = Text(description='Title:', value="")
     self.options['title'].observe(
         lambda v: self.UpdateLayout({'title': v['new']}), names='value')
     self.options['line_width'] = BoundedIntText(description='Lines width:',
                                                 value=1,
                                                 min=0,
                                                 max=10)
     self.options['line_width'].observe(
         lambda v: self.UpdateTraces({'line.width': v['new']}),
         names='value')
     self.options['marker_size'] = BoundedIntText(
         description='Markers size:', value=3, min=0, max=15)
     self.options['marker_size'].observe(
         lambda v: self.UpdateTraces({'marker.size': v['new']}),
         names='value')
     self.DefaultLegend('v', 0.6, 0.95)
     self.updateRender()
예제 #14
0
 def __init__(self, data, dimensions, **kwargs):
     GluePlotly.__init__(self, data, dimensions, **kwargs)
     self.DefaultLayoutTitles("", self.dimensions[0], ' '.join([self.dimensions[i] for i in range(1,len(self.dimensions))]))
     self.DefaultLayoutScales("linear","linear");
     self.options['marker_type'] = Dropdown( description = 'Marker type:', value = 'lines', options = ['lines','lines+markers','lines+text'])
     self.options['marker_type'].observe(lambda v:self.UpdateTraces({'mode':v['new']}), names='value')       
     self.options['line_width'] = BoundedIntText(description = 'Lines width:', value = 1, min=0, max=10)
     self.options['line_width'].observe(lambda v:self.UpdateTraces({'line.width':v['new']}), names='value')        
     self.DefaultLegend('v', 1.02, 1.0);                
     self.updateRender() 
예제 #15
0
    def __init__(self):
        self.mp4_zip_file = "cells_mp4.zip"
        self.mp4_file = "cells.mp4"

        self.instructions = Label("After a simulation completes, generate a video of cells (from SVG files). Does not work for cached results yet.")
        self.feedback = Label("                            ")
        # self.feedback.value = "Converting all svg to jpg..."

        self.gen_button = Button(
            description='Generate video',
            button_style='success',  # 'success', 'info', 'warning', 'danger' or ''
            tooltip='Generate a MP4 video of cells',
        )
        self.gen_button.disabled = True
        self.gen_button.on_click(self.gen_button_cb)

        fps_style = {'description_width': '35%'}
        fps_layout = {'width': '85px'}
        # tooltip='frames per sec',  -- tooltip not available for *Text !
        self.fps = BoundedIntText(description="fps=", value=5, min=1, max=30, step=1, 
          style=fps_style, layout=fps_layout)

        size_style = {'description_width': '50%'}
        size_layout = {'width': '150px'}
        self.size = BoundedIntText(description="w,h(pixels)=", value=500, min=250, max=1500, step=10, disabled=False, tooltip='width, height of video',
          style=size_style, layout=size_layout)

        self.video = HTML( value="",
            placeholder='',
            description='',
            layout= Layout(visibility='hidden')
        )

        if (hublib_flag):
            self.download_mp4_button = Download(self.mp4_zip_file, style='success', icon='cloud-download', 
                                                tooltip='Download mp4 (you need to allow pop-ups in your browser)')
            self.download_mp4_button.w.disabled = True

            self.tab = VBox([self.instructions, HBox([ self.gen_button, self.fps, self.size, self.feedback,
                self.download_mp4_button.w]), self.video])
        else:
            self.tab = VBox([self.instructions, HBox([self.gen_button, self.fps, self.size, self.feedback]), self.video])
예제 #16
0
def notes(path, ds=None, parcel=None):
    info = HTML(
        value="Add a note for the parcel",
        placeholder='Notes',
    )

    aoi = Text(value=ds,
               placeholder='MS or ragion',
               description='AOI:',
               disabled=False)
    try:
        y_ = int(ds[-4:])
    except:
        y_ = 2000
    year = BoundedIntText(value=y_,
                          min=1980,
                          max=2100,
                          step=1,
                          description='Year:',
                          disabled=False,
                          layout=Layout(width='180px'))
    pid = Text(value=parcel,
               placeholder='12345',
               description='Parcel ID:',
               disabled=False)
    note = Textarea(value=None,
                    placeholder='',
                    description='Note:',
                    disabled=False,
                    layout=Layout(width='60%'))
    save = Button(value=False,
                  disabled=False,
                  button_style='info',
                  tooltip='Save note to notes table.',
                  icon='save',
                  layout=Layout(width='35px'))
    new = HBox([aoi, year, pid])

    progress = Output()

    def outlog(*text):
        with progress:
            print(*text)

    @save.on_click
    def save_on_click(b):
        progress.clear_output()
        df = pd.DataFrame([[aoi.value, year.value, pid.value, note.value]])
        df.to_csv(f'{path}notes.csv', mode='a', header=False)
        outlog(f"The note is saved in {path}notes.csv")

    wbox = VBox([info, new, HBox([note, save]), progress])

    return wbox
예제 #17
0
파일: util.py 프로젝트: jmandreoli/IPYDEMO
    def __init__(self,
                 displayer: Callable[[Figure, Selection], Callable[[int, Any],
                                                                   None]],
                 resolution: int = None,
                 fig_kw={},
                 children=(),
                 toolbar=(),
                 **ka):
        from ipywidgets import BoundedIntText, IntText, Label

        def select(bounds_):
            i = self.level + 1
            w_level.active = False
            w_level.max = i
            w_level.value = i
            setlevel(i, (resolution, bounds_))
            w_level.active = True

        def show_running(b):
            w_running.icon = 'pause' if b else 'play'

        def show_precision(p):
            w_precision.value = p

        self.select = select
        self.show_precision = show_precision
        self.show_running = show_running

        def setlevel(i, new=None):
            self.level = i
            w_precision.value = display(i, new)
            board.canvas.draw_idle()

        # global design and widget definitions
        w_running = SimpleButton(icon='')
        w_level = BoundedIntText(0,
                                 min=0,
                                 max=0,
                                 layout=dict(width='1.6cm', padding='0cm'))
        w_level.active = True
        w_precision = IntText(0,
                              disabled=True,
                              layout=dict(width='1.6cm', padding='0cm'))
        super().__init__(children,
                         toolbar=(w_running, Label('level:'), w_level,
                                  Label('precision:'), w_precision, *toolbar))
        self.board = board = self.mpl_figure(**fig_kw)
        display = displayer(board, select)
        # callbacks
        w_running.on_click(lambda b: self.setrunning())
        w_level.observe(
            (lambda c: (setlevel(c.new) if w_level.active else None)), 'value')
        super(app, self).__init__(display, **ka)
예제 #18
0
    def __init__(self, data, dimensions, **kwargs):
        GluePlotly.__init__(self, data, dimensions, **kwargs)
        self.DefaultLayoutTitles("", self.dimensions[0], self.dimensions[1])
        z_id = self.dimensions[2]
        self.max_color = max(self.data[z_id].flatten())
        self.min_color = min(self.data[z_id].flatten())
        color_options = [
            'Greys', 'YlGnBu', 'Greens', 'YlOrRd', 'Bluered', 'RdBu', 'Reds',
            'Blues', 'Picnic', 'Rainbow', 'Portland', 'Jet', 'Hot',
            'Blackbody', 'Earth', 'Electric', 'Viridis', 'Cividis'
        ]
        self.options['line_width'] = BoundedIntText(description='Lines width:',
                                                    value=1,
                                                    min=0,
                                                    max=10)
        self.options['line_width'].observe(
            lambda v: self.UpdateTraces({'line.width': v['new']}),
            names='value')
        self.options['marker_size'] = BoundedIntText(
            description='Markers size:', value=3, min=0, max=15)
        self.options['marker_size'].observe(
            lambda v: self.UpdateTraces({'marker.size': v['new']}),
            names='value')
        self.options['color_range_min'] = FloatText(description='Color min:',
                                                    value=self.min_color)
        self.options['color_range_min'].observe(
            lambda v: self.UpdateTraces({'zmin': v['new']}), names='value')
        self.options['color_range_max'] = FloatText(description='Color max:',
                                                    value=self.max_color)
        self.options['color_range_max'].observe(
            lambda v: self.UpdateTraces({'zmax': v['new']}), names='value')
        self.options['color_scale'] = Dropdown(description='Color scale:',
                                               value='Greys',
                                               options=color_options)
        self.options['color_scale'].observe(
            lambda v: self.UpdateTraces({'colorscale': v['new']}),
            names='value')
        self.DefaultLegend('v', 1.02, 1.0)

        self.updateRender()
예제 #19
0
    def vis(self, oracle=False, oracle_res=4):
        """
        optionally save all predicted files through output writer
        """
        assert not self.mp_distributed
        from panoptic.vis import Visualizer
        from ipywidgets import interactive, BoundedIntText, BoundedFloatText
        from IPython.display import display

        model, loader = self.model, self.val_loader
        dset, pcv = loader.dataset, model.pcv
        vis_engine = Visualizer(cfg, dset.meta, pcv)
        vis_engine.display_stdout_and_err_in_curr_cell()

        def logic(inx, hmap_thresh):
            _, segments_info, img, pan_gt_mask = dset.pan_getitem(inx)
            if oracle:
                sem_pd, vote_pd = gt_tsr_res_reduction(
                    oracle_res, self.gt_prod_handle,
                    dset.meta, pcv, pan_gt_mask, segments_info
                )
            else:
                # sem_pd, _ = gt_tsr_res_reduction(
                #     oracle_res, self.gt_prod_handle,
                #     dset.meta, pcv, pan_gt_mask, segments_info
                # )
                sem_pd, vote_pd = model.infer(
                    dset[inx][0].unsqueeze(0).cuda(), softmax_normalize=True
                )

            # img = _downsample_PIL(img)  # rtchange
            if cfg.data.dataset.params['caffe_mode']:
                img = np.array(img)[:, :, ::-1]
            pan_gt_mask = _downsample_PIL(pan_gt_mask)
            vis_engine.vis(
                img, pan_gt_mask, segments_info, sem_pd, vote_pd,
                self.gt_prod_handle, model.criteria, hmap_thresh
            )

        wdgt = interactive(
            logic,
            inx=BoundedIntText(
                min=0, max=len(dset) - 1, step=1
            ),
            hmap_thresh=BoundedFloatText(
                value=cfg.pcv.hmap_thresh, min=0, max=1000.0, step=0.2,
                description='ws_thresh'
            )
        )
        wdgt.children[-1].layout.height = '1300px'
        display(wdgt)
        return vis_engine
예제 #20
0
    def __init__(self, mk_signals: list):

        # first call the base class constructor
        super().__init__(mk_signals)

        # add the "overlapping" box
        self.wt_overlap = BoundedIntText(value=7,
                                         min=0,
                                         step=1,
                                         description='Overlap:',
                                         disabled=False)

        self.children = [*self.children, self.wt_overlap]
 def __init__(self, label, width, init_value=0, min_value=0, max_value=100):
     '''
     Summary:
         A slider with a label on top. Only integers allowed in the slider.
     Args:
         label (str): the label on top of the slider.
         width (int): the width of the slider and the label.
         init_value (int): the initial value in the slider.
         min_value (int): the minimum value in the slider.
         max_value (int): the maximum value in the slider.
     '''
     self.label = Label(value=label, layout=Layout(width='{w}px'.format(w=width)))
     self.bi = BoundedIntText(value=init_value, min=min_value, max=max_value, layout=Layout(width='{w}px'.format(w=width)))
     super().__init__(children=[self.label, self.bi], layout=Layout(margin='0 0 10px 0'))
예제 #22
0
    def __init__(self, signal_components: dict, parent=None):
        """
        Summary:
            Object constructor.
        
        Arguments :
            signal_components - dictionary with the signal/components names
        """
        super().__init__(signal_components, peak_detector_widget._type, parent)

        # Add specific options
        wbit_aggregate = BoundedIntText(description="aggregate:",
                                        value=0,
                                        min=0,
                                        step=1,
                                        disabled=False)

        wcb_filter_by_angle = Checkbox(value=False,
                                       description='filter_by_angle:',
                                       disabled=False)

        wbit_min_duration = BoundedIntText(description="min_duration:",
                                           value=-1,
                                           min=-1,
                                           step=1,
                                           disabled=False)

        wbit_min_increase = BoundedFloatText(description="min_increase:",
                                             value=-1,
                                             min=-1,
                                             step=1,
                                             disabled=False)

        self.add_options([
            wbit_min_duration, wbit_min_increase, wcb_filter_by_angle,
            wbit_aggregate
        ])
예제 #23
0
 def __init__(self, data, dimensions, **kwargs):
     GluePlotly.__init__(self, data, dimensions, **kwargs)
     self.DefaultLayoutTitles(
         "", self.dimensions[0], ' '.join(
             [self.dimensions[i] for i in range(1, len(self.dimensions))]))
     self.options['line_width'] = BoundedIntText(description='Lines width:',
                                                 value=1,
                                                 min=0,
                                                 max=10)
     self.options['line_width'].observe(
         lambda v: self.UpdateTraces({'line.width': v['new']}),
         names='value')
     self.options['marker_size'] = BoundedIntText(
         description='Markers size:', value=3, min=0, max=15)
     self.options['marker_size'].observe(
         lambda v: self.UpdateTraces({'marker.size': v['new']}),
         names='value')
     degree = kwargs.get('degree', 2)
     self.options['fit_degree'] = BoundedIntText(
         description='Fitting degree:', value=degree, min=2, max=20)
     self.options['fit_degree'].observe(lambda v: self.updateRender(),
                                        names='value')
     self.DefaultLegend('v', 1.02, 1.0)
     self.updateRender()
예제 #24
0
    def __init__(self, signal_components: dict, md_type="", parent=None):
        self.type = md_type

        self.parent = parent

        if self.parent is not None:
            try:
                self.parent.set_title_from_widget(self)
            except:
                print("Unable to set the Tab title.")

        # Retain only the signals (at this stage a single component should be present)
        self.signals = list(signal_components.keys())

        self.wsm_signals = SelectMultiple(options=["", *self.signals],
                                          value=[""],
                                          description="Signals:",
                                          placeholder="Signals",
                                          disabled=False)

        # Components
        self.components = signal_components

        # start date
        wdp_start_date = DatePicker(description='Start date:', disabled=False)

        # stop date
        wdp_stop_date = DatePicker(description='Stop date:', disabled=False)

        self.whb_dates = HBox([wdp_start_date, wdp_stop_date])

        # Max number of markers to detect
        self.wit_max_num = BoundedIntText(value=0,
                                          min=0,
                                          step=1,
                                          description="Max Number of Markers:")

        # Initialize the
        super().__init__([
            HTML(value=f"<B>Processor type: {self.type}</B>"),
            self.wsm_signals, self.whb_dates,
            HTML(value="<B>Options :</B>")
        ],
                         layout=Layout(border='1px solid black'))

        self.options = []
예제 #25
0
    def __init__(self, signal_components: dict, parent=None):
        """
        Summary:
            Object constructor.
        
        Arguments :
            signal_components - dictionary with the signal/components names
        """
        super().__init__(signal_components, gap_detector_widget._type, parent)

        wbit_min_gap_len = BoundedIntText(description="min_gap_len:",
                                          value=20,
                                          min=0,
                                          step=1,
                                          disabled=False)

        self.add_options([wbit_min_gap_len])
예제 #26
0
def my_local_explainer(base_value, shap_values, classifier, features, X, label, decoder=dict()):
    
    df_shap_values = pd.DataFrame(shap_values, columns = X.columns) 
    decoded_X = copy.deepcopy(X)

    for feature in decoder:
        sum_shap = [0] * len(shap_values)

        for elem in decoder[feature]:
            for i in range(len(shap_values)):
                sum_shap[i] += df_shap_values[elem][i]
                
            df_shap_values = df_shap_values.drop([elem], axis=1)
            decoded_X = decoded_X.drop([elem], axis=1)
        
        df_shap_values[feature] = sum_shap
        decoded_X[feature] = features[feature] 

    df_shap_values = df_shap_values[features.columns]
    decoded_X = decoded_X[features.columns]

    shap_values = df_shap_values.to_numpy()

    textbox = BoundedIntText(value=0,
                             min=0,
                             max= len(X),
                             step=1,
                             description='Sample id:',
                             disabled=False,
                             layout=Layout(width='90%', 
                                  padding = "10px 640px 0px 420px",
                                  )
                            )

    menu = Dropdown(options=["forceplot", "output value box plots", "impact evaluation", "shap value range"],
                    value="forceplot",
                    description = "Mode:",
                    disabled=False,
                    layout=Layout(width='90%', 
                                  padding = "10px 640px 35px 420px",
                                  )
                   ) 
    
    
    interact(select_mode, base_value = fixed(base_value), shap_values = fixed(shap_values), classifier = fixed(classifier), features = fixed(features), X = fixed(decoded_X), 
            encoded_X = fixed(X), sample_id = textbox, label = fixed(label), mode = menu) 
예제 #27
0
    def __init__(self, signal_components: dict):
        """
            Summary:
                Object constructor.                
        """

        super().__init__(signal_components, "interp")

        wdd_method = Dropdown(options=["linear", "nearest"],
                              description="method:",
                              disabled=False)

        wit_sampling_int = BoundedIntText(value=1,
                                          min=0,
                                          step=1,
                                          description="Ts:")

        self.add_options([wdd_method, wit_sampling_int])
예제 #28
0
    def find_beam_shape_thresh(self):
        if self._beam_shape_fig is None:
            fig, ax = plt.subplots()
            self._beam_shape_fig = fig

        ax = self._beam_shape_fig.axes[0]

        thresh_sel = BoundedIntText(value=50, min=0, max=100,
                                    description="threshold")

        def update(change=None):
            if self._beam_shape_artist is not None:
                self._beam_shape_artist.remove()
            self._beam_shape_artist = ax.imshow(
                self.beam_shape * 100 > thresh_sel.value)
            self._beam_shape_fig.canvas.draw_idle()

        thresh_sel.observe(update, "value")
        update()

        return VBox([thresh_sel, self._beam_shape_fig.canvas])
예제 #29
0
 def _create_input(self) -> None:
     self._input["number_clusters"] = BoundedIntText(
         continuous_update=True,
         min=1,
         max=len(self._routes) - 1,
         layout={"width": "80px"},
     )
     self._buttons["cluster"] = Button(description="Cluster")
     self._buttons["cluster"].on_click(self._on_cluster_button_clicked)
     box = HBox([
         Label("Number of clusters to make"),
         self._input["number_clusters"],
         self._buttons["cluster"],
     ])
     display(box)
     help_out = Output()
     with help_out:
         print(
             "Optimization is carried out if the number of given clusters are less than 2"
         )
     display(help_out)
예제 #30
0
    def __init__(self,
                 twitter_client: TwitterClient,
                 sentiment_font_size=3,
                 full_contrast=True):
        self.full_contrast = full_contrast
        self.sentiment_font_size = sentiment_font_size
        self.twitter_client = twitter_client
        self.last_search = self.tweet_ids = self.tweets = None

        self.search_text = Text(
            value='@CogSys',
            placeholder='',
            description='Search:',
            disabled=False,
            layout=dict(width="60%"),
        )
        self.search_button = Button(
            description='Search Twitter',
            disabled=False,
            button_style=
            'success',  # 'success', 'info', 'warning', 'danger' or ''
            tooltip='',
            icon='',
            layout=dict(width="20%"),
        )
        self.description = VBox((
            Label(value="Type a search for Twitter."),
            Label(value=
                  "Use @ and # for searching for specific users or hashtags."),
        ),
                                layout=dict(width="70%"))
        self.n_results = BoundedIntText(
            value=15,
            min=1,
            max=50,
            step=1,
            description='Tweets:',
            disabled=False,
            layout=dict(width="23%"),
        )

        self.language = Dropdown(
            options=['en', 'da'],
            value='en',
            description='Language:',
            disabled=False,
        )
        self.emoticons = Checkbox(value=False,
                                  description='Emoticons',
                                  disabled=False)
        self.show_mean = Checkbox(value=False,
                                  description='Show Mean',
                                  disabled=False)

        box1 = HBox((self.description, self.n_results))
        box2 = HBox((self.search_text, self.search_button))
        box3 = HBox((self.language, self.emoticons, self.show_mean))
        self.dashboard = VBox((box1, box2, box3))
        # noinspection PyTypeChecker
        display(self.dashboard)

        # Observe
        self.search_button.on_click(self._run)