示例#1
0
    def __init__(self, host="localhost", *args, **kwargs):
        if "value" in kwargs:
            kwargs["index"] = kwargs["value"]
            del kwargs["value"]
        if kwargs["index"] is None:
            kwargs["index"] = tuple()
        if isinstance(kwargs["index"], int):
            kwargs["index"] = (kwargs["index"], )

        try:
            c = requests.get("http://{}:12345".format(host))
            assert c.status_code == 200
            SelectMultiple.__init__(
                self,
                *args,
                options=list("GPU {index} ({utilization}%)".format(
                    index=x["index"], utilization=x["utilization.gpu"])
                             for x in c.json()["gpus"]),
                **kwargs,
            )
        except Exception:
            SelectMultiple.__init__(
                self,
                *args,
                options=list(range(8)),  # default, just in case
                **kwargs,
            )
示例#2
0
    def __init__(self, *args) -> None:
        super().__init__(*args)

        training_path = Path(self.training_repo.value)  # type: ignore

        if not training_path.exists():
            raise RuntimeError("Path {} does not exist".format(training_path))

        if training_path.is_dir():

            self.train_labels = SelectMultiple(
                options=[],
                value=[],
                description="Training labels",
                disabled=False,
            )

            self.test_labels = SelectMultiple(
                options=[],
                value=[],
                description="Testing labels",
                disabled=False,
            )

            if not ',' in self.testing_repo.value:
                self.testing_repo.value = '[\'' + self.testing_repo.value + '\']'

            self.testing_repo.observe(  # type: ignore
                self.update_label_list, names="value")
            self.training_repo.observe(  # type: ignore
                self.update_label_list, names="value")

            self.train_labels.observe(self.update_train_dir_list,
                                      names="value")
            self.test_labels.observe(self.update_test_dir_list, names="value")
            self.file_list.observe(self.display_img, names="value")

        else:
            self.train_labels = Button(
                description=Path(self.training_repo.value).name  # type: ignore
            )
            if not ',' in self.testing_repo.value:
                self.testing_repo.value = '[\'' + self.testing_repo.value + '\']'
            self.test_labels = Button(description=Path(
                eval(self.testing_repo.value)[0]).name  # type: ignore
                                      )

            self.train_labels.on_click(self.update_train_file_list)
            self.test_labels.on_click(self.update_test_file_list)
            self.file_list.observe(self.display_img, names="value")

        self._img_explorer.children = [
            HBox([HBox([self.train_labels, self.test_labels])]),
            self.file_list,
            self.output,
        ]

        self.update_label_list(())
示例#3
0
 def setup_products_out_selector(self):
     self.selector_products_out = SelectMultiple(
         options=sorted(self.get_unique_products(self.rules)),
         value=[],
         rows=10,
         # description="Drop",
         disabled=False,
     )
     self.selector_products_out.observe(self.handler_products_out_filter, "value")
示例#4
0
    def __init__(self, *args, **kwargs):
        # Compute selected and unselected values
        options = kwargs.get('options', {})
        if isinstance(options, list):
            options = named_objs([(opt, opt) for opt in options])
        self._reverse_lookup = {v: k for k, v in options.items()}
        selected = [self._reverse_lookup[v] for v in kwargs.get('value', [])]
        unselected = [k for k in options if k not in selected]

        # Define whitelist and blacklist
        self._lists = {
            False: SelectMultiple(options=unselected),
            True: SelectMultiple(options=selected)
        }

        self._lists[False].observe(self._update_selection, 'value')
        self._lists[True].observe(self._update_selection, 'value')

        # Define buttons
        button_layout = Layout(width='50px')
        self._buttons = {
            False: Button(description='<<', layout=button_layout),
            True: Button(description='>>', layout=button_layout)
        }
        self._buttons[False].on_click(self._apply_selection)
        self._buttons[True].on_click(self._apply_selection)

        # Define search
        self._search = {
            False: Text(placeholder='Filter available options'),
            True: Text(placeholder='Filter selected options')
        }
        self._search[False].observe(self._filter_options, 'value')
        self._search[True].observe(self._filter_options, 'value')

        # Define Layout
        no_margin = Layout(margin='0')
        row_layout = Layout(margin='0',
                            display='flex',
                            justify_content='space-between')

        search_row = HBox([self._search[False], self._search[True]])
        search_row.layout = row_layout
        button_box = VBox([self._buttons[True], self._buttons[False]],
                          layout=Layout(margin='auto 0'))
        tab_row = HBox([self._lists[False], button_box, self._lists[True]])
        tab_row.layout = row_layout
        self._composite = VBox([search_row, tab_row], layout=no_margin)

        self.observe(self._update_options, 'options')
        self.observe(self._update_value, 'value')

        self._selected = {False: [], True: []}
        self._query = {False: '', True: ''}
        super(CrossSelect, self).__init__(*args, **dict(kwargs,
                                                        options=options))
示例#5
0
 def setup_products_in_selector(self):
     self.selector_products_in = SelectMultiple(
         options=sorted(self.get_unique_products(self.rules)),
         value=sorted(self.get_unique_products(self.rules)),
         rows=10,
         # description="Include",
         disabled=False,
     )
     self.products_to_in = sorted(self.get_unique_products(self.rules))
     self.selector_products_in.observe(self.handler_products_in_filter, "value")
示例#6
0
 def widget_plots(self):
     return interact(
         self.show_plots, 
         plots=SelectMultiple(options=self.ERROR_FUNCTION_NAMES, value=["mean", "max"], description="Plots"), 
         datasets=SelectMultiple(options=["raw", "image"], value=["image"], description="Datasets"),
         error_type=Dropdown(options={"Absolute": "absolute", "Relative": "relative"}, value="absolute", description='Error'),
         xmin=Text(value="", placeholder="Type a number or leave blank to disable", description='Min x'),
         xmax=Text(value="", placeholder="Type a number or leave blank to disable", description='Max x'),
         ymin=Text(value="", placeholder="Type a number or leave blank to disable", description='Min y'),
         ymax=Text(value="", placeholder="Type a number or leave blank to disable", description='Max y'),
         width=IntSlider(value=15, min=5, max=50, step=1, continuous_update=False, description="Subplot width"), 
         height=IntSlider(value=15, min=5, max=50, step=1, continuous_update=False, description="Subplot height")
     )
示例#7
0
    def __init__(self, signal_components: dict, _type=""):
        """
            Summary:
                
        """
        self.type = _type

        # Create the list of signals available
        # Include an empty option
        self.signals = ["", *list(signal_components)]

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

        # Components
        self.components = signal_components
        components = [""]
        for key in signal_components:
            components = [*components, *signal_components[key]]

        self.wsm_components = SelectMultipleOrdered(options=components,
                                                    value=[""],
                                                    description="Components:",
                                                    placeholder="Components",
                                                    disabled=False)

        def on_signal_change(change):
            components = [""]

            if "" in self.wsm_signals.value:
                for key in self.components:
                    components = [*components, *self.components[key]]
            else:
                for key in self.wsm_signals.value:
                    components = [*components, *self.components[key]]

            self.wsm_components.options = components

        self.wsm_signals.observe(on_signal_change, 'value')

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

        self.options = []
示例#8
0
def generate_pdp_grid(models: list) -> GridBox:
    children = []

    # Row 1
    children.append(
        Label(layout=Layout(width='auto', height='auto'),
              value='Choose a PDP method'))
    children.append(
        Label(layout=Layout(width='auto', height='auto'),
              value='Choose one or more model(s)'))

    # Row 2
    # if you change the description of this widget,
    # you have to also adjust it in the notebook function call.
    children.append(
        Select(description='Type',
               options=[elem.name for elem in PDPType],
               disabled=False))
    # if you change the description of this widget,
    # you have to also adjust it in the notebook function call.
    children.append(
        SelectMultiple(description='Model(s)',
                       options=[model.name for model in models],
                       disabled=False))

    return GridBox(children=children,
                   layout=Layout(width='auto',
                                 grid_template_columns="50% 50%",
                                 grid_template_rows='auto',
                                 align_items='center',
                                 grid_gap='3px 3px'))
示例#9
0
def replay(workplane, index=0, debug=False, cad_width=600, height=600):
    reset_replay()

    r = Replay(debug, cad_width, height)
    r.stack = r.to_array(workplane,
                         result_name=getattr(workplane, "name", None))
    r.indexes = [index]

    if r._debug:
        print("Dump of stack:")
        r.dump()

    r.select_box = SelectMultiple(options=[
        "[%02d] %s" % (i, code) for i, (code, obj) in enumerate(r.stack)
    ],
                                  index=r.indexes,
                                  rows=len(r.stack),
                                  description='',
                                  disabled=False,
                                  layout=Layout(width="600px"))
    r.select_box.add_class("monospace")
    r.select_box.observe(r.select_handler)
    display(HBox([r.select_box, r.debug_output]))

    r.select(r.indexes)
    return r
示例#10
0
 def interact_plot_model(self):
     Q=interact(
         self.plot_model,
         m_background=FloatSlider(
             min=-2, max=2, step=0.05, value=0., continuous_update=False, description="m$_{background}$",
         ),
         m1=FloatSlider(
             min=-2, max=2, step=0.05, value=1., continuous_update=False, description="m1",
         ),
         m2=FloatSlider(
             min=-2, max=2, step=0.05, value=2., continuous_update=False, description="m2",
         ),
         m1_center=FloatSlider(
             min=-2, max=2, step=0.05, value=0.2, continuous_update=False, description="m1$_{center}$",
         ),
         dm1 =FloatSlider(
             min=0, max=0.5, step=0.05, value=0.2, continuous_update=False, description="m1$_{width}$",
         ),
         m2_center=FloatSlider(
             min=-2, max=2, step=0.05, value=0.75, continuous_update=False, description="m2$_{center}$",
         ),
         sigma_2=FloatSlider(
             min=0.01, max=0.1, step=0.01, value=0.07, continuous_update=False, description="m2$_{sigma}$",
         ),
         option=SelectMultiple(
             options=["kernel", "model", "data"],
             value=["model"],
             description='option'
         ),
         percentage=FloatText(value=5),
         floor=FloatText(value=0.02),
     )
     return Q
示例#11
0
    def _make_affix_box(self, a_e):
        aff = getattr(self._rgx_mchr, a_e[0])
        err = getattr(self._rgx_mchr, a_e[1])
        dct = getattr(self._rgx_mchr, a_e[2])
        opt = getattr(self._rgx_mchr, a_e[3])

        form_item_layout = Layout(display='flex',
                                  flex_flow='column',
                                  align_items='stretch',
                                  display_content='center')
        ctrl = VBox([
            Checkbox(
                value=opt,
                description=a_e[0] + 'fix',
            ),
            Text(value=aff, ),
            IntSlider(
                value=err,
                min=0,
                max=6,
                readout=True,
            ),
            SelectMultiple(options=dct),
        ],
                    layout=form_item_layout)
        #ctrl.children[1].disabled = not ctrl.children[0].value
        link((self._rgx_mchr, a_e[0]), (ctrl.children[1], 'value'))
        link((self._rgx_mchr, a_e[1]), (ctrl.children[2], 'value'))
        link((self._rgx_mchr, a_e[3]), (ctrl.children[0], 'value'))
        return ctrl
示例#12
0
    def build_widget(self):

        # init interactive plot
        self.plot_output = Output(layout={'width': '600px'})

        self.text_output = Output()
        self.select = SelectMultiple(options=self.file_list,
                                     layout={'width': '400px'},
                                     rows=20)
        self.select.observe(self.update_plot)

        VB = VBox([self.select], layout={'align_self': 'center'})
        HB = HBox([VB, self.plot_output])
        widget = VBox([HB, self.text_output])

        return widget
示例#13
0
def replay(cad_obj, index=0, debug=False, cad_width=600, height=600):
    r = Replay(debug, cad_width, height)

    if isinstance(cad_obj, cq.Workplane):
        workplane = cad_obj
    elif is_cqparts_part(cad_obj):
        workplane = convert_cqparts(cad_obj, replay=True)
    else:
        print("Cannot replay", cad_obj)
        return None

    r.stack = r.format_steps(
        r.to_array(workplane, result_name=getattr(workplane, "name", None)))
    r.indexes = [index]

    r.select_box = SelectMultiple(options=[
        "[%02d] %s" % (i, code) for i, (code, obj) in enumerate(r.stack)
    ],
                                  index=r.indexes,
                                  rows=len(r.stack),
                                  description='',
                                  disabled=False,
                                  layout=Layout(width="600px"))
    r.select_box.add_class("monospace")
    r.select_box.observe(r.select_handler)
    display(HBox([r.select_box, r.debug_output]))

    r.select(r.indexes)
    return r
示例#14
0
    def _create_widget(self) -> SelectMultiple:

        _tokens = list(self.tokens.index)
        _layout = Layout(width="200px")
        self._tokens_widget = SelectMultiple(options=_tokens,
                                             value=[],
                                             rows=30)
        self._tokens_widget.layout = _layout
        self._tokens_widget.observe(self._on_selection_changed, "value")

        self._text_widget = Text(description="")
        self._text_widget.layout = _layout
        self._text_widget.observe(self._on_filter_changed, "value")

        _widget = VBox(
            [HTML("<b>Filter</b>"), self._text_widget, self._tokens_widget])

        return _widget
示例#15
0
def generate_local_interpretation_grid(models: list) -> GridBox:
    children = []

    # Row 1
    children.append(
        Label(layout=Layout(width='auto', height='auto'),
              value='Choose an interpretation method'))
    children.append(
        Label(layout=Layout(width='auto', height='auto'),
              value='Choose one or more model(s)'))

    # Row 2
    # if you change the description of this widget,
    # you have to also adjust it in the notebook function call.
    children.append(
        Select(description='Type',
               options=[elem.name for elem in LocalInterpreterType],
               disabled=False))
    # if you change the description of this widget,
    # you have to also adjust it in the notebook function call.
    children.append(
        SelectMultiple(description='Model(s)',
                       options=[model.name for model in models],
                       disabled=False))

    # Row 3
    # if you change the description of this widget,
    # you have to also adjust it in the notebook function call.
    children.append(
        RadioButtons(options=[elem.name for elem in ExampleType],
                     layout={'width': 'max-content'},
                     description='Example(s) type:',
                     disabled=False))

    # if you change the description of this widget,
    # you have to also adjust it in the notebook function call.
    children.append(
        IntSlider(
            value=1,
            min=1,
            max=10,
            step=1,
            description='Number of examples:',
            disabled=False,
            continuous_update=False,
            orientation='horizontal',
            readout=True,
            readout_format='d',
        ))

    return GridBox(children=children,
                   layout=Layout(width='auto',
                                 grid_template_columns="50% 50%",
                                 grid_template_rows='auto',
                                 align_items='center',
                                 grid_gap='3px 3px'))
示例#16
0
def replay(
    cad_obj,
    index=-1,
    quality=None,
    deviation=0.1,
    angular_tolerance=0.2,
    edge_accuracy=None,
    debug=False,
    cad_width=600,
    height=600,
):

    if not REPLAY:
        print(
            "Replay is not enabled. To do so call 'enable_replay()'. Falling back to 'show()'"
        )
        return show(cad_obj, cad_width=cad_width, height=height)
    else:
        print(
            "Use the multi select box below to select one or more steps you want to examine"
        )

    r = Replay(quality, deviation, angular_tolerance, edge_accuracy, debug,
               cad_width, height)

    if isinstance(cad_obj, cq.Workplane):
        workplane = cad_obj
    elif is_cqparts_part(cad_obj):
        workplane = convert_cqparts(cad_obj, replay=True)
    else:
        print("Cannot replay", cad_obj)
        return None

    r.stack = r.format_steps(
        r.to_array(workplane, result_name=getattr(workplane, "name", None)))
    if index == -1:
        r.indexes = [len(r.stack) - 1]
    else:
        r.indexes = [index]

    r.select_box = SelectMultiple(
        options=[
            "[%02d] %s" % (i, code) for i, (code, obj) in enumerate(r.stack)
        ],
        index=r.indexes,
        rows=len(r.stack),
        description="",
        disabled=False,
        layout=Layout(width="600px"),
    )
    r.select_box.add_class("monospace")
    r.select_box.observe(r.select_handler)
    display(HBox([r.select_box, r.debug_output]))

    r.select(r.indexes)
    return r
示例#17
0
    def _init_gui(self):

        close = Button(description=' Close', icon='trash', layout=_wlo)

        def _close(b):
            self.close()

        close.on_click(_close)

        frame = IntSlider(min=self._df.frame.astype(int).min(),
                          max=self._df.frame.astype(int).max(),
                          value=-1,
                          description='Frame',
                          layout=_wlo)

        cbut = Button(description=' Columns', icon='barcode')
        cols = self._df.columns.tolist()
        cols = SelectMultiple(options=cols, value=cols)

        def _cols(c):
            self.columns = c.new
            self._update_output()

        cols.observe(_cols, names='value')
        cfol = Folder(cbut, _ListDict([('cols', cols)]))

        rbut = Button(description=' Rows', icon='bars')
        rows = IntRangeSlider(min=self.indexes[0],
                              max=self.indexes[1],
                              value=[0, 50])

        def _rows(c):
            self.indexes = c.new
            print(self.indexes)
            self._update_output()

        rows.observe(_rows, names='value')

        rfol = Folder(rbut, _ListDict([('rows', rows)]))

        return _ListDict([('close', close), ('frame', frame), ('cols', cfol),
                          ('rows', rfol)])
示例#18
0
    def _init_gui(self):

        close = Button(description=' Close', icon='trash', layout=_wlo)
        def _close(b): self.close()
        close.on_click(_close)

        frame = IntSlider(min=self._df.frame.astype(int).min(),
                          max=self._df.frame.astype(int).max(),
                          value=-1, description='Frame', layout=_wlo)

        cbut = Button(description=' Columns', icon='barcode')
        cols = self._df.columns.tolist()
        cols = SelectMultiple(options=cols, value=cols)

        def _cols(c):
            self.columns = c.new
            self._update_output()
        cols.observe(_cols, names='value')
        cfol = Folder(cbut, _ListDict([('cols', cols)]))

        rbut = Button(description=' Rows', icon='bars')
        rows = IntRangeSlider(min=self.indexes[0],
                              max=self.indexes[1],
                              value=[0, 50])
        def _rows(c):
            self.indexes = c.new
            print(self.indexes)
            self._update_output()
        rows.observe(_rows, names='value')

        rfol = Folder(rbut, _ListDict([('rows', rows)]))

        return _ListDict([('close', close),
                          ('frame', frame),
                          ('cols', cfol),
                          ('rows', rfol)])
示例#19
0
def layer_select(m, design):

    layers_to_plot = m
    features_to_plot = {'features':[],'layer':[]}
    if len(layers_to_plot)>0:
        features_to_plot['features'] = [x for x in design.features if design.features[x].layer in layers_to_plot]
        features_to_plot['layers'] = [layers_to_plot.index(design.features[x].layer) for x in design.features if design.features[x].layer in layers_to_plot]

        if len(features_to_plot['features'])>0:
            #chk = [Checkbox(description=a) for a in features_to_plot]
            #interact(updatePlot, **{c.description: c.value for c in chk})
            sel_mult2 = SelectMultiple(options = features_to_plot['features'])
            interactive_plot2 = interactive(updatePlot, n=sel_mult2, 
                                            design = fixed(design), all_features = fixed(features_to_plot))
            display(interactive_plot2)
示例#20
0
    def interact_ft_vs_markers(self):
        """Interactor for plotting nuclei feature vs marker values."""
        def _interact_ft_vs_markers(feature, markers, sample=1.0):
            """Plot scatter plot of a marker vs a feature, allows plotting more than one marker at a time using different
            colors.

            The sample parameter is a float from 0.0 to 1.0 that defines how many nuclei to sample from the total number
            of nuclei available to plot - plotting a smaller number of points makes comparisons easier to see."""
            button, text = _create_button_text_display('feature_vs_markers.png')

            # check that both dataframes matche in CellID column
            if not np.all(self.markers_df.CellID == self.df_full.CellID):
                raise Exception('The cell id columns of both dataframe do not match, not running function')

            # subset the markers dataframe by only the markers of interest and concatenate horizontally
            markers = list(markers)
            df = concat([self.df_full, self.markers_df[markers]], axis=1)

            # sample the nuclei
            if sample < 1.0:
                df = df.sample(frac=sample, random_state=64)

            # create the figure canvas
            fig, ax = plt.subplots(figsize=(10, 10))

            # plot the scatter of the feature vs each marker
            for i, marker in enumerate(markers):
                df.plot.scatter(x=feature, y=marker, c=COLOR_NAMES[i], ax=ax, alpha=0.2)

            ax.set_ylabel('Marker value', fontsize=18)
            ax.set_xlabel(f'Feature: {feature}', fontsize=18)
            ax.legend(markers, fontsize=14)
            ax.set_title('Comparison of nuclei feature and marker value', fontsize=20)
            plt.show()

            button.on_click(partial(self.on_button_clicked, text_widget=text, fig_to_save=fig))
            display(widgets.HBox([text, button]))

        a = Dropdown(options=self.features, value=self.features[0], description='Feature:')
        b = SelectMultiple(options=self.markers, value=[self.markers[0]], style=DESC_STYLES,
                           layout=Layout(width='500px'),description='Select markers (hold control to select multiple):')
        c = FloatSlider(value=0.1, min=0.05, max=1.0, step=0.05, description='Frac. nuclei sampled:', style=DESC_STYLES,
                        continuous_update=False)
        row = widgets.HBox([a, b, c])

        out = widgets.interactive_output(_interact_ft_vs_markers, {'feature': a, 'markers': b, 'sample': c})

        display(row, out)
示例#21
0
    def build_knobs(self):
        # Dropdowns
        for name, (options, default) in self.dropdowns.items():
            if None not in options:
                options = options + [None]
            self.knobs[name] = Dropdown(options=options,
                                        description=name,
                                        value=default)

        # Selectors
        for name, options in self.selectors.items():
            self.knobs[name] = SelectMultiple(options=options,
                                              value=options,
                                              rows=len(options))

        self.knobs["xlog"] = Checkbox(description="xlog", value=False)
        self.knobs["ylog"] = Checkbox(description="ylog", value=False)
示例#22
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 = []
示例#23
0
def interact_with_plot_all_outputs(sa_dict, demo=False, manual=True):
    """
    This function adds the ability to interactively adjust all of the
    plotting.make_plot() arguments.

    Parameters
    ----------
    sa_dict : dict
              a dictionary with all the sensitivity analysis results.
    demo    : bool, optional
              plot only few outcomes for demo purpose.

    Returns
    -------
    Interactive widgets to control plot
    """
    min_val_box = BoundedFloatText(value=0.01,
                                   min=0,
                                   max=1,
                                   description='Min value:')
    top_box = IntText(value=20, description='Show top:')
    stacks = Checkbox(
        description='Show stacked plots:',
        value=True,
    )
    error_bars = Checkbox(description='Show error bars:', value=True)
    log_axis = Checkbox(description='Use log axis:', value=True)

    # get a list of all the parameter options
    key = sa_dict.keys()[0]
    param_options = list(sa_dict[key][0].Parameter.values)
    highlighted = SelectMultiple(description="Choose parameters to highlight",
                                 options=param_options,
                                 value=[])

    return interact(plot_all_outputs,
                    sa_dict=fixed(sa_dict),
                    demo=fixed(demo),
                    min_val=min_val_box,
                    top=top_box,
                    stacked=stacks,
                    error_bars=error_bars,
                    log_axis=log_axis,
                    highlighted_parameters=highlighted,
                    __manual=manual)
    def __fill_smoothing_method(self):
        """
        Fill smooth methods
        """
        smoothing_methods = ['smoothn',
                             'ExponentialSmoothing',
                             'SimpleExpSmoothing',
                             'Holt']

        self.smoothing_methods = SelectMultiple(
                options=tuple(smoothing_methods),
                value=tuple([smoothing_methods[0]]),
                rows=len(smoothing_methods),
                description='Smoothing methods',
                disabled=False,
                style = {'description_width': 'initial'},
                layout={'width': '330px'},
        )
示例#25
0
    def __fill_interpolation_method(self):
        """
        Fill interpolation methods
        """
        interpolation_methods = [
            'linear', 'nearest', 'slinear', 'quadratic', 'cubic', 'krog',
            'pchip', 'spline', 'akima'
        ]

        self.interpolation_methods = SelectMultiple(
            options=tuple(interpolation_methods),
            value=tuple([interpolation_methods[0]]),
            rows=len(interpolation_methods),
            description='Interpolation methods',
            disabled=False,
            style={'description_width': 'initial'},
            layout={'width': '220px'},
        )
示例#26
0
    def __init__(self):
        log.info("__init__")
        self.cl = int_field(settings.CACHE_LINES_VAL,
                            settings.CACHE_LINES_DESC)
        self.cb = int_field(settings.CACHE_BLOCK_VAL,
                            settings.CACHE_BLOCK_DESC)
        self.ml = int_field(settings.OUTPUT_LINES_VAL,
                            settings.OUTPUT_LINES_DESC)

        self.cwd = Combobox(placeholder=settings.CWD_PATH_DEF,
                            options=load_cwd_file(),
                            description=settings.CWD_PATH_DESC,
                            style=settings.WIDGET_DESC_PROP,
                            layout=settings.WIDGET_LAYOUT)

        self.ex = text_field(settings.EXEC_PATH_DEF, settings.EXEC_PATH_DESC)
        self.to = text_field(settings.TRACE_NAME_DEF, settings.TRACE_NAME_DESC)
        self.st = text_field(settings.START_FUN_DEF, settings.START_FUN_DESC)

        self.vh = v.Html(
            tag='style',
            children=[".v-input__slot .v-label{color: black!important}"])

        self.gt_in = VBox([
            self.cl, self.cb, self.ml, self.cwd, self.ex, self.to, self.st,
            self.vh
        ],
                          layout=Layout(width='100%'))

        self.gb = button(settings.GENERATE_DESC, color=settings.GENERATE_COLOR)
        self.lb = button(settings.LOAD_DESC, color=settings.LOAD_COLOR)
        self.db = button(settings.DELETE_DESC, color=settings.DELETE_COLOR)
        self.bs = HBox([self.gb, self.lb, self.db])

        self.sw = SelectMultiple(options=[],
                                 value=[],
                                 description=settings.SELECT_MULTIPLE_DESC,
                                 layout=settings.WIDGET_LAYOUT,
                                 rows=10)

        self.tw = HBox([self.gt_in, self.sw],
                       layout=Layout(justify_content="space-around"))
        self.widgets = VBox([self.tw, self.bs],
                            layout=Layout(justify_content="space-around"))
示例#27
0
    def __init__(self, *, default_folder: str, **defaults):
        """GUI base for PoS token count statistics."""
        super().__init__()
        self.default_folder: str = default_folder
        self.document_index: pd.DataFrame = None
        self.data: pd.DataFrame = None
        self.defaults: dict = defaults
        self.PoS_tag_groups: pd.DataFrame = pu.PD_PoS_tag_groups
        self._source_folder: FileChooserExt2 = None

        self._normalize: ToggleButton = ToggleButton(
            description="Normalize",
            icon='check',
            value=defaults.get('normalize', False),
            layout=Layout(width='140px'))
        self._smooth: ToggleButton = ToggleButton(description="Smooth",
                                                  icon='check',
                                                  value=defaults.get(
                                                      'smooth', False),
                                                  layout=Layout(width='140px'))
        self._temporal_key: Dropdown = Dropdown(
            options=TEMPORAL_GROUP_BY,
            value=defaults.get('temporal_key', 'decade'),
            description='',
            disabled=False,
            layout=Layout(width='90px'),
        )
        self._status: HTML = HTML(
            layout=Layout(width='50%', border="0px transparent white"))
        self._pos_groups: SelectMultiple = SelectMultiple(
            options=['Total'] + [
                x
                for x in self.PoS_tag_groups.index.tolist() if x != "Delimiter"
            ],
            value=['Total'],
            rows=10,
            layout=Layout(width='120px'),
        )

        self._tab: OutputsTabExt = OutputsTabExt(["Table", "Line", "Bar"],
                                                 layout={'width': '98%'})
        self._widgets_placeholder: HBox = HBox(children=[])
        self._sidebar_placeholder: HBox = HBox(children=[])
示例#28
0
    def new_dataset(self):
        """
        A handy widget for creating new `DataSets`.
        """
        samples = list(self.tier)
        option_map = {sample.name: sample for sample in samples}

        selection = SelectMultiple(options=option_map.keys(),
                                   description='Auto Add')

        def create(name, auto_add):
            with form.status:
                self.tier.setup_technique(name)
                if auto_add:
                    for sample in (option_map[name] for name in auto_add):
                        o = sample[name]
                        o.setup_files()
                        display(widgetify_html(o._repr_html_()))

        form = InputSequence(
            create, Text(description=f'Name:', placeholder='e.g. XRD'),
            selection)

        return form.as_widget()
示例#29
0
def view():
    info = Label("Select a parcel to display.")

    temppath = config.get_value(['paths', 'temp'])
    datapath = config.get_value(['paths', 'data'])

    method = ToggleButtons(options=[('From local storage', 0),
                                    ('Remote to memory', 1)],
                           value=0,
                           description='',
                           disabled=True,
                           button_style='info',
                           tooltips=[
                               'View data that are stored on the local drive.',
                               'View data from memory.'
                           ])

    paths = RadioButtons(options=[
        (f"Temporary folder: '{temppath}'.", temppath),
        (f"Personal data folder: '{datapath}'.", datapath)
    ],
                         layout={'width': 'max-content'},
                         value=temppath)

    paths_box = Box([Label(value="Select folder:"), paths])

    tables_first = [
        f for f in os.listdir(paths.value)
        if os.path.isdir(os.path.join(paths.value, f))
    ]

    select_table = Dropdown(
        options=[f for f in tables_first if not f.startswith('.')],
        value=None,
        description='Select tabe:',
        disabled=False,
    )

    select_option = RadioButtons(options=[(f"Single parcel selection.", 1),
                                          (f"Multiple parcels selection.", 2)],
                                 disabled=True,
                                 layout={'width': 'max-content'})

    button_refresh = Button(layout=Layout(width='35px'), icon='fa-refresh')

    select_option_box = HBox([
        select_table, button_refresh,
        Label(value="Selection method:"), select_option
    ])

    selection_single = Dropdown(
        options=[],
        value=None,
        description='Select parcel:',
        disabled=False,
    )

    selection_multi = SelectMultiple(
        options=[],
        value=[],
        description='Select parcels:',
        disabled=False,
    )

    view_method = ToggleButtons(
        options=[],
        value=None,
        description='',
        disabled=False,
        button_style='info',
        tooltips=[],
    )

    rm_parcel = Button(value=False,
                       disabled=False,
                       button_style='danger',
                       tooltip='Delete parcel data.',
                       icon='trash',
                       layout=Layout(width='35px'))

    code_info = Label()
    single_box = HBox([selection_single, rm_parcel])
    select_box = Box([single_box])

    method_0 = VBox([info, paths_box, select_option_box, select_box])
    method_1 = VBox([])
    view_box = Output(layout=Layout(border='1px solid black'))
    method_out = Output()
    with method_out:
        display(method_0)

    def method_options(obj):
        with method_out:
            method_out.clear_output()
            if obj['new'] == 0:
                display(method_0)
            elif obj['new'] == 1:
                display(method_1)

    method.observe(method_options, 'value')

    @button_refresh.on_click
    def button_refresh_on_click(b):
        view_box.clear_output()
        tables_first = [
            f for f in os.listdir(paths.value)
            if os.path.isdir(os.path.join(paths.value, f))
        ]
        select_table.options = [
            f for f in tables_first if not f.startswith('.')
        ]
        if select_table.value is not None:
            parcels = f"{paths.value}{select_table.value}"
            parcels_list = [
                f for f in os.listdir(parcels) if not f.startswith('.')
            ]
            selection_single.options = parcels_list
            selection_multi.options = parcels_list
        else:
            selection_single.options = []
            selection_single.value = None
            selection_multi.options = []
            selection_multi.value = []

    @rm_parcel.on_click
    def rm_parcel_on_click(b):
        try:
            parcel_to_rm = f"{paths.value}{select_table.value}/{selection_single.value}"
            try:
                shutil.rmtree(f'{parcel_to_rm}')
            except Exception:
                pass
            try:
                os.remove(f'{parcel_to_rm}')
            except Exception:
                pass
#             print(f"The parce: '{selection_single.value}' is deleted.")
            parcels = f"{paths.value}{select_table.value}"
            parcels_list = [
                f for f in os.listdir(parcels) if not f.startswith('.')
            ]
            selection_single.options = parcels_list
            view_box.clear_output()
        except Exception:
            pass

    def on_select_option_change(change):
        if select_option.value == 1:
            select_box.children = [single_box]
        else:
            select_box.children = [selection_multi]

    select_option.observe(on_select_option_change, 'value')

    def on_datapath_change(change):
        tables = [
            f for f in os.listdir(paths.value)
            if os.path.isdir(os.path.join(paths.value, f))
        ]
        tables = [f for f in tables if not f.startswith('.')]
        select_table.options = tables

    paths.observe(on_datapath_change, 'value')

    def on_table_change(change):
        if select_table.value is not None:
            parcels = f"{paths.value}{select_table.value}"
            parcels_list = [
                f for f in os.listdir(parcels) if not f.startswith('.')
            ]
            selection_single.options = parcels_list
            selection_multi.options = parcels_list
        else:
            selection_single.options = []
            selection_single.value = None
            selection_multi.options = []
            selection_multi.value = []
            view_method.options = []

    select_table.observe(on_table_change, 'value')

    def on_selection_change(obj):
        code_info.value = "Select how to view the dataset."
        options_list = [('Get example code', 1)]
        if obj['new'] is not None:
            parceldata = f"{paths.value}{select_table.value}/{selection_single.value}"
            data_list = [
                f for f in os.listdir(parceldata) if not f.startswith('.')
            ]
            if any("time_series" in s for s in data_list):
                options_list.append(('Plot time series', 2))
            if any("chip_images" in s for s in data_list):
                options_list.append(('View images', 3))
            options_list.append(("Show on map", 4))
            if select_option.value == 2:
                options_list.append(('Comparison', 5))
            view_method.options = options_list
            view_method.value = None

    selection_single.observe(on_selection_change, 'value')
    selection_multi.observe(on_selection_change, 'value')

    def method_options(obj):
        view_box.clear_output()
        with view_box:
            if selection_single.value is None:
                with view_box:
                    print("Please select a parcel")

            elif select_option.value == 1:
                data_path = f'{paths.value}{select_table.value}/{selection_single.value}/'
                if obj['new'] == 1:
                    from src.ipycbm.ui_view import view_code
                    display(view_code.code(data_path))
                elif obj['new'] == 2:
                    from src.ipycbm.ui_view import view_time_series
                    display(view_time_series.time_series(data_path))
                elif obj['new'] == 3:
                    from src.ipycbm.ui_view import view_calendar
                    display(view_calendar.calendar(data_path))
                elif obj['new'] == 4:
                    from src.ipycbm.ui_view import view_map
                    display(view_map.widget_box(data_path))

            elif select_option.value == 2 and len(selection_multi.value) > 0:
                data_path = f'{paths.value}{select_table.value}/'
                data_paths = [
                    f'{data_path}{s}/' for s in selection_multi.value
                ]
                if obj['new'] == 1:
                    from src.ipycbm.ui_view import view_code
                    display(view_code.code(data_paths[0]))
                    pass
                elif obj['new'] == 2:
                    from src.ipycbm.ui_view import view_time_series
                    # display(view_time_series.time_series(data_list[0]))
                    pass
                elif obj['new'] == 3:
                    from src.ipycbm.ui_view import view_calendar
                    # display(view_chip_images.calendar(data_path))
                    pass
                elif obj['new'] == 4:
                    from src.ipycbm.ui_view import view_maps
                    display(view_maps.with_polygons(data_paths))

    selection_single.observe(method_options, 'value')
    selection_multi.observe(method_options, 'value')
    view_method.observe(method_options, 'value')

    notes_info = Label("Add a note for the parcel")
    notes_bt = Button(value=False,
                      description='Add note',
                      disabled=False,
                      button_style='info',
                      tooltip='Add a note.',
                      icon='sticky-note')
    notes_box = VBox([])

    @notes_bt.on_click
    def notes_bt_on_click(b):
        if notes_box.children == ():
            notes_box.children = [
                view_notes.notes(f"{paths.value}{select_table.value}/",
                                 select_table.value,
                                 selection_single.value.replace('parcel_', ''))
            ]
        else:
            notes_box.children = []

    wbox = VBox([
        method_out, code_info, view_method, view_box,
        HBox([notes_info, notes_bt]), notes_box
    ])

    return wbox
示例#30
0
def plot_design(design):
    output_notebook()
    sel_mult = SelectMultiple(options = [x for x in design.layers])
    interactive_plot = interactive(layer_select, m=sel_mult, design=fixed(design))
    display(interactive_plot)
示例#31
0
    def __init__(self, signal_components: dict):
        """
            Summary:
                Object constructor.                
        
            This is a quite specific processor and has a dedicated constructor.
        """

        self.type = "band_filter"

        # Create the list of signals available
        # Include an empty option
        self.signals = list(signal_components.keys())

        # In this case, only one signal can be selected
        self.wdd_signals = Dropdown(options=self.signals,
                                    description="Signals:",
                                    placeholder="Signals",
                                    disabled=False)

        self.components = signal_components

        components = signal_components[self.wdd_signals.value]
        self.wdd_nir = Dropdown(options=components,
                                description="NIR:",
                                disabled=False)

        self.wdd_swir = Dropdown(options=components,
                                 description="SWIR:",
                                 disabled=False)

        self.wdd_red = Dropdown(options=components,
                                description="RED:",
                                disabled=False)

        self.nsr_bar = HBox([self.wdd_nir, self.wdd_swir, self.wdd_red])

        self.wsm_components = SelectMultiple(options=["", *components],
                                             value=[""],
                                             description="Components:",
                                             placeholder="Components",
                                             disabled=False)

        def on_signal_change(change):
            components = self.components[self.wdd_signals.value]
            self.wdd_nir.options = components
            self.wdd_swir.options = components
            self.wdd_red.options = components

            self.wsm_components.options = ["", *components]

        self.wdd_signals.observe(on_signal_change, 'value')

        super(type(self).__bases__[0],
              self).__init__([
                  HTML(value=f"<B>Processor type: {self.type}</B>"),
                  HBox([self.wdd_signals, self.wsm_components]), self.nsr_bar,
                  HTML(value="<B>Options :</B>")
              ],
                             layout=Layout(border='1px solid black'))

        self.options = []

        # Add specific options
        wsm_cat = SelectMultiple(
            description="excluded_categories:",
            options=red_nir_swir_processor_widget.class_labels,
            disabled=False)

        # "min_val": [1200, 800, 150],
        # "max_val": [5700, 4100, 2800]
        #         wt_minval = Text(
        #             description="min_val:",
        #             value = "1200, 800, 150",
        # 			disabled = False)

        #         wt_maxval = Text(
        #             description="max_val:",
        #             value = "5700, 4100, 2800",
        # 			disabled = False)

        #         wfc_trainingfile = FileChooser(
        #             description = "training_file:",
        #             disabled = False
        #         )

        # self.add_options([wsm_cat, wt_minval, wt_maxval, wfc_trainingfile])
        self.add_options([wsm_cat])