예제 #1
0
def get_color_switch_widget(colors_by_labels, colors_rgb, scatter_widget):
    w = None
    options = []
    if colors_by_labels is not None:
        options = ['labels']
        is_multilabels = isinstance(colors_by_labels, (list, tuple))
        if is_multilabels:
            options = [
                'labels_' + str(i) for i in range(len(colors_by_labels))
            ]
    if colors_rgb is not None:
        options += ['rgb']
    if len(options) > 1:
        value = options[-1]
        w = RadioButtons(options=options, description='colors', value=value)

        def on_switch_colors(e):
            value = e['new']
            if value.startswith('labels'):
                if is_multilabels:
                    ind = int(value.split('_')[1])
                    current_colors = colors_by_labels[ind]
                else:
                    current_colors = colors_by_labels
            else:
                current_colors = colors_rgb

            with scatter_widget.hold_trait_notifications():
                scatter_widget.color = current_colors

        w.observe(on_switch_colors, 'value')
    return w
예제 #2
0
 def _dock_add_radio_buttons(self, value, rng, callback, vertical=True,
                             layout=None):
     # XXX: vertical=False is not supported yet
     layout = self._dock_layout if layout is None else layout
     widget = RadioButtons(
         options=rng,
         value=value,
         disabled=False,
     )
     widget.observe(_generate_callback(callback), names='value')
     self._layout_add_widget(layout, widget)
     return _IpyWidgetList(widget)
예제 #3
0
    def create_check_radio_boxes(self):
        labels = dict()
        for k_name, v in self.properties_and_values.items():

            if len(v) == 3:
                label = v[2]
            elif MetaPropertiesType.TEXT.value == v[0].value and len(v) == 2:
                label = v[1]
            else:
                label = k_name

            labels[k_name] = label

            if MetaPropertiesType.UNIQUE.value == v[0].value:  # radiobutton
                self.radiobuttons[k_name] = RadioButtons(name=k_name, options=v[1],
                                                         disabled=False,
                                                         indent=False)
            elif MetaPropertiesType.COMPOUND.value == v[0].value:  # checkbox
                self.checkboxes[k_name] = [Checkbox(False, indent=False, name=k_name,
                                                    description=prop_name) for prop_name in v[1]]
            elif MetaPropertiesType.CONTINUE.value == v[0].value:
                self.bounded_text[k_name] = BoundedFloatText(value=v[1][0], min=v[1][0], max=v[1][1])

            elif MetaPropertiesType.TEXT.value == v[0].value:
                self.box_text[k_name] = Textarea(disabled=False)

        return labels
예제 #4
0
 def interact_plot_inversion(self, maxIter=30):
     interact(
         self.plot_inversion,
         mode=RadioButtons(
             description="mode", options=["Run", "Explore"], value="Run"
         ),
         maxIter=IntText(value=maxIter),
         m0=FloatSlider(
             min=-2, max=2, step=0.05, value=0.0, continuous_update=False
         ),
         mref=FloatSlider(
             min=-2, max=2, step=0.05, value=0.0, continuous_update=False
         ),
         percentage=FloatText(value=self.percentage),
         floor=FloatText(value=self.floor),
         chifact=FloatText(value=1.0),
         beta0_ratio=FloatText(value=100),
         coolingFactor=FloatSlider(
             min=0.1, max=10, step=1, value=2, continuous_update=False
         ),
         coolingRate=IntSlider(
             min=1, max=10, step=1, value=1, continuous_update=False
         ),
         alpha_s=FloatText(value=1e-10),
         alpha_x=FloatText(value=0),
         target=False,
         option=ToggleButtons(options=["misfit", "tikhonov"], value="misfit"),
         i_iteration=IntSlider(
             min=0, max=maxIter, step=1, value=0, continuous_update=False
         ),
     )
예제 #5
0
    def __init__(self):
        # initialize the base class
        super().__init__()

        # Add additional elements
        self.wt_signals = Text(placeholder='Signal Table',
                               description='Signal Table:',
                               disabled=False)

        self.wt_histtable = Text(placeholder='Hist. Table',
                                 description='Hist. Table:',
                                 disabled=False)

        self.wt_sm_table = Text(placeholder='Sen. Table',
                                description='Sen. Table:',
                                disabled=False)

        self.wrb_cloud = RadioButtons(
            options=['True', 'False'],
            value='True',  # Defaults to 'pineapple'
            description='Cloud Free:',
            disabled=False)

        self.wdp_start_date = DatePicker(description='Start date:',
                                         disabled=False)

        self.wdp_end_date = DatePicker(description='Stop date:',
                                       disabled=False)

        children = [*super().children, self.wt_signals, self.wt_histtable, \
                    self.wt_sm_table, self.wrb_cloud, self.wdp_start_date, \
                    self.wdp_end_date]

        self.children = children
예제 #6
0
    def _make_pag(self) -> VBox:
        self.pagtype_box = RadioButtons(
            options=["No Pagination", "offset", "seek", "page", "token"],
            layout={"width": "max-content"},  # If the items' names are long
            description="",
            style={"description_width": "initial"},
            disabled=False,
        )
        pag_label = HTML(
            value=
            ("""<h3 style="background-color:#E8E8E8; background-size: 100px; ">
                <span style="color: #ff0000">4.</span> Pagination</h3>"""),
            layout=self.label_layout,
        )

        self.pagparams_box = Textarea(
            placeholder=
            ("Please separate pagination key and corresponding value by ':' ;"
             " while each key-value pair needs to be separated by ',' "
             "(e.g. name:abcdefg, date:2019-12-12)"),
            layout=self.textarea_layout,
        )
        carousel_4 = Box(children=[self.pagparams_box], layout=self.box_layout)
        pag_box = VBox([pag_label, self.pagtype_box, carousel_4])
        return pag_box
예제 #7
0
def visualize_dos_with_matplotlib(
    df: pd.DataFrame,
    xmin: float,
    xmax: float,
    mag_order_list: List[str],
    update_function,
    dpi: int = 120,
    style: str = "k-",
):
    xmin: FloatText = FloatText(xmin, description="Energy minimum")
    xmax: FloatText = FloatText(xmax, description="Energy maximum")
    mag_order: RadioButtons = RadioButtons(
        options=mag_order_list,
        description="magnetic order",
    )

    interactive_window: interactive = interactive(
        update_function,
        df=fixed(df),
        xmin=xmin,
        xmax=xmax,
        mag_order=mag_order,
        dpi=dpi,
        style=style,
    )

    return interactive_window
예제 #8
0
    def _make_auth(self) -> VBox:
        self.authtype_box = RadioButtons(
            options=[
                "No Authorization", "OAuth2", "QueryParam", "Bearer", "Header"
            ],
            layout={"width": "max-content"},  # If the items' names are long
            description="",
            style={"description_width": "initial"},
            disabled=False,
        )

        auth_label = HTML(
            value=
            ("""<h3 style="background-color:#E8E8E8; background-size: 100px; ">"""
             """<span style="color: #ff0000">3.</span> Authorization """
             """<span style="font-size: 14px">"""
             """<i>(some APIs require authorization)</i> </span></span></h3>"""
             ),
            layout=self.label_layout,
        )

        self.authparams_box = Textarea(
            placeholder=
            ("Please separate authtication key and corresponding value by ':' ; "
             "while each key-value pair needs to be separated by ',' "
             "(e.g. name:abcdefg, date:2019-12-12)"),
            layout=self.textarea_layout,
        )

        carousel_3 = Box(children=[self.authparams_box],
                         layout=self.box_layout)
        auth_box = VBox([auth_label, self.authtype_box, carousel_3])
        return auth_box
예제 #9
0
 def interact_plot_inversion(self, n_beta=81):
     interact(
         self.plot_inversion,
         mode=RadioButtons(
             description="mode", options=["Run", "Explore"], value="Run"
         ),
         mref=FloatSlider(
             min=-2, max=2, step=0.05, value=0.0, continuous_update=False
         ),
         percentage=FloatText(value=self.percentage),
         floor=FloatText(value=self.floor),
         beta_min=FloatText(value=1e-3),
         beta_max=FloatText(value=1e5),
         n_beta=IntText(value=n_beta, min=10, max=100),
         alpha_s=FloatText(value=1.0),
         alpha_x=FloatText(value=0),
         option=ToggleButtons(options=["misfit", "tikhonov"], value="tikhonov"),
         data_option=ToggleButtons(
             options=["obs/pred", "misfit"], value="obs/pred", description="data"
         ),
         scale=ToggleButtons(options=["linear", "log"], value="log"),
         i_beta=IntSlider(
             min=0, max=n_beta - 1, step=1, value=0, continuous_update=False
         ),
         chifact=FloatText(value=1.0),
     )
예제 #10
0
 def __init__(self, num_options: int = 4) -> None:
     options = [
         str(option_number + 1) for option_number in range(num_options)
     ]
     layout = Layout(margin="0 0 0 20px")
     self._radiobuttons = RadioButtons(options=options,
                                       layout=layout,
                                       value=None)
예제 #11
0
def widget_box():

    source = int(config.get_value(['set', 'data_source']))

    sources = RadioButtons(
        options=[
            ("JRC RESTful API.", 0),
            ("Direct access to database and object storage.", 1)
        ],
        value=source,
        layout={'width': 'max-content'}
    )

    sources_box = Box([
        Label(value="Data sources:"),
        sources]
    )

    info_api = Label("RESTful API Settings.")
    info_direct = Label("Direct access settings")

    view_options = VBox([info_direct])

    if source == 0:
        view_options.children = [info_api, rest_api()]
    elif source == 1:
        view_options.children = [info_direct, direct()]

    def on_source_change(change):
        view_options.children = []
        if sources.value == 0:
            view_options.children = [info_api, rest_api()]
        elif sources.value == 1:
            view_options.children = [info_direct, direct()]
        config.update(['set', 'data_source'], str(sources.value))

    sources.observe(on_source_change, 'value')

    wbox_sources = VBox([sources_box, view_options],
                        layout=Layout(border='1px solid black'))

    info_general = Label(value="General settings:")

    wbox = VBox([wbox_sources, info_general, settings.widget_box()])

    return wbox
예제 #12
0
def widget_box():

    source = config.get_value(['set', 'data_source'])

    sources = RadioButtons(
        options=[
            ("DIAS API.", 'dias_api'),
            ("Direct access to database and object storage.", 'direct')
        ],
        layout={'width': 'max-content'}
    )

    sources_box = Box([
        Label(value="Available sources:"),
        sources]
    )

    info_api = Label("DIAS API Settings.")
    info_direct = Label("Direct access settings")

    view_options = VBox([info_direct])

    if source == 'direct':
        view_options.children = [info_direct]
    else:
        view_options.children = [info_api, dias_api()]

    def on_source_change(change):
        view_options.children = []
        if sources.value == 'dias_api':
            view_options.children = [info_api, dias_api()]
        elif sources.value == 'direct':
            view_options.children = [info_direct]
        config.update(['preferences', 'data_source'], str(sources.value))

    sources.observe(on_source_change, 'value')

    wbox_sources = VBox([sources_box, view_options],
                        layout=Layout(border='1px solid black'))

    info_general = Label(value="General settings:")

    wbox = VBox([wbox_sources, info_general, settings.widget_box()])

    return wbox
예제 #13
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'))
def InversionSampledDataWidget():

    i = interact(
        widget_fun_sampled_data,
        v0=FloatSlider(
            min=1.,
            max=5.,
            value=2.,
            step=0.25,
            continuous_update=False,
            readout_format='.2f',
            description="$v_0$ [m/s]",
        ),
        a=FloatSlider(
            min=0.1,
            max=1.,
            value=0.5,
            step=0.1,
            continuous_update=False,
            readout_format='.1f',
            description="$a$",
        ),
        T=FloatSlider(
            min=0.0002,
            max=0.005,
            value=0.001,
            step=0.0002,
            continuous_update=False,
            readout_format='.4f',
            description="T [s]",
        ),
        tmax=FloatSlider(
            min=0.001,
            max=0.01,
            value=0.005,
            step=0.001,
            continuous_update=False,
            readout_format='.3f',
            description="tmax [s]",
        ),
        n=IntSlider(
            min=1,
            max=50,
            value=6,
            step=1,
            continuous_update=False,
            description="n",
        ),
        interp_type=RadioButtons(options=['linear', 'quadratic', 'cubic'],
                                 value='quadratic',
                                 description='Interpolation:'),
    )

    return i
예제 #15
0
    def addRadioButtons(self, **kwargs):
        orientation = getValue(kwargs, 'orientation', EasyForm.VERTICAL)
        radio_buttons = RadioButtons(options=getValue(kwargs, 'options', []),
                                     description=getValue(kwargs, 'value', ""))

        if orientation == EasyForm.VERTICAL:
            self.children += (radio_buttons, )
        else:
            box = HBox()
            box.children += (radio_buttons, )
            self.children += (box, )

        return radio_buttons
예제 #16
0
def data_source():

    source = config.get_value(['set', 'data_source'])

    sources = RadioButtons(options=[
        ("RESTful API for CbM.", 'api'),
        ("Direct access to database and object storage.", 'direct')
    ],
                           value=source,
                           layout={'width': 'max-content'},
                           disabled=True)

    sources_box = Box([Label(value="Data sources:"), sources])

    info_api = Label("RESTful API Settings.")
    info_direct = Label("Direct access settings")

    view_options = VBox([info_direct])

    if source == 'api':
        view_options.children = [info_api, settings_ds.api()]
    elif source == 'direct':
        view_options.children = [info_direct, settings_ds.direct()]

    def on_source_change(change):
        view_options.children = []
        if sources.value == 'api':
            view_options.children = [info_api, settings_ds.api()]
        elif sources.value == 'direct':
            view_options.children = [info_direct, settings_ds.direct()]
        config.set_value(['set', 'data_source'], sources.value)

    sources.observe(on_source_change, 'value')

    wbox_sources = VBox([sources_box, view_options],
                        layout=Layout(border='1px solid black'))

    return wbox_sources
예제 #17
0
    def __init__(self):
        self.run_bt = Button(description='Demo_deprec', button_style='info')
        self.mod_add_bt = Button(description='Add model', button_style='info')
        self.mod_remove_bt = Button(description='Remove model',
                                    button_style='warning')
        # self.dts_selector = Dropdown(options=SUPPORTED_DATASETS,
        #                              value=SUPPORTED_DATASETS[0],
        #                              description='Dataset:')
        self.dts_selector = self.get_default_dts_selector()
        self.size_selector = RadioButtons(options=[1000, 2000, 5000, 10000],
                                          value=1000,
                                          description='Size')
        self.features_selector = IntRangeSlider(value=[30, 100],
                                                min=30,
                                                max=2000,
                                                step=1,
                                                layout=Layout(width='950px'))

        self.model_name_column = VBox([Label(value='Model')])
        self.sampler_name_column = VBox([Label(value='Sampler')])
        self.box_type_column = VBox([Label(value='Box Type')])
        self.n_estim_column = VBox([Label(value='Number Estimators')])
        self.pca_column = VBox([Label(value='PCA?')])

        self.models_bar = HBox([
            self.model_name_column,
            self.sampler_name_column,
            self.box_type_column,
            self.n_estim_column,
            self.pca_column,
        ],
                               layout=Layout(border='3px solid black'))

        self.gui = VBox([
            self.dts_selector,
            self.size_selector,
            self.mod_add_bt,
            self.mod_remove_bt,
            self.features_selector,
            self.models_bar,
            self.run_bt,
        ])
        self.mod_add_bt.on_click(self.insert_model_bar)
        self.mod_remove_bt.on_click(self.remove_model_bar)
        self.insert_model_bar()
        # self.box_type_changed()
        self.sampler_changed()
        super().__init__()
예제 #18
0
파일: ui.py 프로젝트: wanyun-yang/dataprep
    def _make_pag(self) -> VBox:
        self.pagtype_box = RadioButtons(
            options=["No Pagination", "offset", "seek", "page", "token"],
            layout={"width": "max-content"},  # If the items' names are long
            description="",
            style={"description_width": "initial"},
            disabled=False,
        )

        self.pagparams_box = Textarea(
            placeholder=(
                "Please separate pagination key and corresponding value by ':' ;"
                " while each key-value pair needs to be separated by ',' "
                "(e.g. name:abcdefg, date:2019-12-12)"
            ),
            layout={"width": "100%"},
        )
        carousel_4 = Box(children=[self.pagparams_box], layout=BOX_LAYOUT)
        pag_box = VBox([_make_header(4, "Pagination"), self.pagtype_box, carousel_4])
        return pag_box
예제 #19
0
파일: ui.py 프로젝트: wanyun-yang/dataprep
    def _make_auth(self) -> VBox:
        self.authtype_box = RadioButtons(
            options=["No Authorization", "OAuth2", "QueryParam", "Bearer", "Header"],
            layout={"width": "max-content"},  # If the items' names are long
            description="",
            style={"description_width": "initial"},
            disabled=False,
        )

        self.authparams_box = Textarea(
            placeholder=(
                "Please separate authtication key and corresponding value by ':' ; "
                "while each key-value pair needs to be separated by ',' "
                "(e.g. name:abcdefg, date:2019-12-12)"
            ),
            layout={"width": "100%"},
        )

        carousel_3 = Box(children=[self.authparams_box], layout=BOX_LAYOUT)
        auth_box = VBox([_make_header(3, "Authorization"), self.authtype_box, carousel_3])
        return auth_box
예제 #20
0
파일: utils.py 프로젝트: hpgem/nanomesh
    def __init__(
        self,
        data: np.ndarray,
        update_delay: int = 50,
        **kwargs,
    ):
        self.fig, self.ax = plt.subplots()
        self.data = data
        self.update_delay = update_delay / 1000

        self.max_vals = dict(zip('zyx', np.array(data.shape) - 1))
        self.labels = {
            'x': ('y', 'z'),
            'y': ('x', 'z'),
            'z': ('x', 'y'),
        }

        self.last_update = 0.0

        # Enable direct specification of slice, i.e. x=123
        for along in 'xyz':
            if along in kwargs:
                kwargs['along'] = along
                kwargs['index'] = kwargs[along]
                break

        along = kwargs.get('along', 'x')
        init_max_val = self.max_vals[along]
        init_val = kwargs.get('index', int(init_max_val / 2))

        self.int_slider = IntSlider(value=init_val, min=0, max=init_max_val)
        self.radio_buttons = RadioButtons(options=('x', 'y', 'z'), value=along)

        self.im = self.ax.imshow(data[0], interpolation=None)
        self.im.set_clim(vmin=data.min(), vmax=data.max())
        self.update(index=init_val, along=along)
예제 #21
0
def dias_cat():

    aoi_method = RadioButtons(
        #         options=[('Predefined MS polygons', 1), ('Get polygon from dataset extent', 2), ('Draw polygon on a map', 3)],
        options=[('Predefined MS polygons', 1),
                 ('Get polygon from dataset extent', 2)],
        value=2,
        description='AOI:',
        disabled=False,
    )

    mss = data_options.ms_polygons()
    ms = Dropdown(
        options=[(m, mss[m]) for m in mss],
        tooltip="AOI",
        description='AOI:',
    )
    tb = Dropdown(
        options=database.tables(),
        tooltip="Select table",
        description='Table:',
    )
    tb_refresh = Button(layout=Layout(width='35px'), icon='fa-refresh')

    aoi_box = VBox([HBox([tb, tb_refresh])])

    dias = Dropdown(
        options=data_options.dias_providers(),
        value='EOSC',
        description='DIAS Provider:',
        disabled=True,
    )

    start = DatePicker(description='Start date', disabled=False)
    end = DatePicker(description='End date', disabled=False)
    plevel = RadioButtons(
        options=['LEVEL2A', 'LEVEL2AP'],
        value='LEVEL2A',
        description='pLevel:',
        disabled=False,
    )
    ptype = RadioButtons(
        options=['CARD-COH6', 'CARD-BS'],
        description='pType:',
        disabled=False,
    )
    card_options = VBox([plevel])
    card = RadioButtons(
        options=[('Sentinel 1', 's1'), ('Sentinel 2', 's2')],
        value='s2',
        description='card:',
        disabled=False,
    )

    bt_card2db = Button(description='Add CARD to db',
                        value=False,
                        disabled=False,
                        button_style='info',
                        tooltip='Add CARD catalogue to database',
                        icon='database')

    progress = Output()

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

    def on_aoi_method_change(change):
        if aoi_method.value == 1:
            aoi_box.children = [ms]
        elif aoi_method.value == 2:
            aoi_box.children = [HBox([tb, tb_refresh])]
        elif aoi_method.value == 3:
            aoi_box.children = []

    aoi_method.observe(on_aoi_method_change, 'value')

    def on_card_change(change):
        if card.value == 's2':
            card_options.children = [plevel]
        else:
            card_options.children = [ptype]

    card.observe(on_card_change, 'value')

    @tb_refresh.on_click
    def tb_refresh_on_click(b):
        tb.options = database.tables()

    @bt_card2db.on_click
    def bt_card2db_on_click(b):
        progress.clear_output()
        try:
            with open(f"{config.get_value(['paths','temp'])}tb_prefix",
                      'r') as f:
                tb_prefix = f.read()
        except Exception:
            tb_prefix = ''

        dc_table = f'{tb_prefix}_dias_catalogue'
        if database.tb_exist(dc_table) is True:
            if aoi_method.value == 1:
                polygon = ms.value.replace(' ', '+')
            elif aoi_method.value == 2:
                polygon = database.tb_extent(tb.value)
            elif aoi_method.value == 3:
                polygon = ms.value.replace(' ', '+')

#             print(polygon)
            if card.value == 's2':
                option = plevel.value
            else:
                option = ptype.value

            outlog("Inserting CARD catalogue to database ...")
            with progress:
                meta2DB.dias_cat(tb_prefix, f"POLYGON(({polygon}))",
                                 start.value, end.value, card.value, option)
            outlog("Completed.")
        else:
            outlog(f"Table {dc_table} does not exist.")

    wbox = VBox([
        dias,
        HBox([aoi_method, aoi_box]),
        HBox([start, end]),
        HBox([card, card_options]), bt_card2db, progress
    ])

    return wbox
예제 #22
0
파일: base.py 프로젝트: faruk0509/gammapy
    def plot_interactive(self, rc_params=None, **kwargs):
        """
        Plot map with interactive widgets to explore the non spatial axes.

        Parameters
        ----------
        rc_params : dict
            Passed to ``matplotlib.rc_context(rc=rc_params)`` to style the plot.
        **kwargs : dict
            Keyword arguments passed to `WcsNDMap.plot`.

        Examples
        --------
        You can try this out e.g. using a Fermi-LAT diffuse model cube with an energy axis::

            from gammapy.maps import Map

            m = Map.read("$GAMMAPY_DATA/fermi_3fhl/gll_iem_v06_cutout.fits")
            m.plot_interactive(add_cbar=True, stretch="sqrt")

        If you would like to adjust the figure size you can use the ``rc_params`` argument::

            rc_params = {'figure.figsize': (12, 6), 'font.size': 12}
            m.plot_interactive(rc_params=rc_params)
        """
        import matplotlib as mpl
        import matplotlib.pyplot as plt
        from ipywidgets.widgets.interaction import interact, fixed
        from ipywidgets import SelectionSlider, RadioButtons

        if self.geom.is_image:
            raise TypeError("Use .plot() for 2D Maps")

        kwargs.setdefault("interpolation", "nearest")
        kwargs.setdefault("origin", "lower")
        kwargs.setdefault("cmap", "afmhot")

        rc_params = rc_params or {}
        stretch = kwargs.pop("stretch", "sqrt")

        interact_kwargs = {}

        for axis in self.geom.axes:
            if axis.node_type == "edges":
                options = [
                    "{:.2e} - {:.2e} {}".format(val_min, val_max, axis.unit)
                    for val_min, val_max in zip(axis.edges[:-1], axis.edges[1:])
                ]
            else:
                options = ["{:.2e} {}".format(val, axis.unit) for val in axis.center]

            interact_kwargs[axis.name] = SelectionSlider(
                options=options,
                description="Select {}:".format(axis.name),
                continuous_update=False,
                style={"description_width": "initial"},
                layout={"width": "50%"},
            )
            interact_kwargs[axis.name + "_options"] = fixed(options)

        interact_kwargs["stretch"] = RadioButtons(
            options=["linear", "sqrt", "log"],
            value=stretch,
            description="Select stretch:",
            style={"description_width": "initial"},
        )

        @interact(**interact_kwargs)
        def _plot_interactive(**ikwargs):
            idx = [
                ikwargs[ax.name + "_options"].index(ikwargs[ax.name])
                for ax in self.geom.axes
            ]
            img = self.get_image_by_idx(idx)
            stretch = ikwargs["stretch"]
            with mpl.rc_context(rc=rc_params):
                fig, ax, cbar = img.plot(stretch=stretch, **kwargs)
                plt.show()
예제 #23
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
예제 #24
0
파일: new_test.py 프로젝트: lliney/My_CV
    mean_vectorized, mean_plain = mean_execution_time(int(n), int(m))
    p1 = plt.bar([0], mean_vectorized, color='g')
    p2 = plt.bar([1], mean_plain, color='r')

    plt.ylabel("Time spent")
    plt.yticks(np.arange(0, mean_plain))

    plt.xticks(range(0, 1))
    plt.legend(("vectorized", "non - vectorized"))

    plt.show()


interact(plot_mean_execution_time,
         n=RadioButtons(options=["1", "10", "100"]),
         m=RadioButtons(options=["1", "10", "100"], separator=" "))


def plot_line(coefs):
    """
    рисует разделяющую прямую, соответствующую весам, переданным в coefs = (weights, bias),
    где weights - ndarray формы (2, 1), bias - число
    """
    w, bias = coefs
    a, b = -w[0][0] / w[1][0], -bias / w[1][0]
    xx = np.linspace(*plt.xlim())
    line.set_data(xx, a * xx + b)


def step_by_step_weights(p, input_matrix, y, max_steps=1e6):
예제 #25
0
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()

data_init = pickle.dumps(init_val)
conn.send(data_init)
print("init_data_sent")

#TuningGUI
out = VBox([HBox([w for w in items[i:i + 10]]) for i in range(0, 80, 10)])
display(out)

#Input Switch
switch_label = Label('Input Option')
switch = RadioButtons(options=['RC Input', 'Onboard'])
display(HBox([switch_label, switch]))

#Controller Switch
switch_label = Label('Controller Option')
switch = RadioButtons(options=['manual', '1-PID', '2-PID'])
display(HBox([switch_label, switch]))


def PIDLoop():

    t_start = time.time()
    prev_data = []

    while True:
        t_now = time.time()
예제 #26
0
파일: editor.py 프로젝트: Zeii2024/RL
    def init_widgets(self):
        # Debug checkbox - enable logging in the Output widget
        self.debug = ipywidgets.Checkbox(description="Debug")
        self.debug.observe(self.controller.set_debug, names="value")

        # Separate checkbox for mouse move events - they are very verbose
        self.debug_move = Checkbox(description="Debug mouse move")
        self.debug_move.observe(self.controller.set_debug_move, names="value")

        # This is like a cell widget where loggin goes
        self.output_generator = Output()

        # Filename textbox
        self.filename = Text(description="Filename")
        self.filename.value = self.model.env_filename
        self.filename.observe(self.controller.set_filename, names="value")

        # Size of environment when regenerating

        self.regen_width = IntSlider(
            value=10,
            min=5,
            max=100,
            step=5,
            description="Regen Size (Width)",
            tip="Click Regenerate after changing this")
        self.regen_width.observe(self.controller.set_regen_width,
                                 names="value")

        self.regen_height = IntSlider(
            value=10,
            min=5,
            max=100,
            step=5,
            description="Regen Size (Height)",
            tip="Click Regenerate after changing this")
        self.regen_height.observe(self.controller.set_regen_height,
                                  names="value")

        # Number of Agents when regenerating
        self.regen_n_agents = IntSlider(
            value=1,
            min=0,
            max=5,
            step=1,
            description="# Agents",
            tip="Click regenerate or reset after changing this")
        self.regen_method = RadioButtons(description="Regen\nMethod",
                                         options=["Empty", "Random Cell"])

        self.replace_agents = Checkbox(value=True,
                                       description="Replace Agents")

        self.wTab = Tab()
        tab_contents = ["Regen", "Observation"]
        for i, title in enumerate(tab_contents):
            self.wTab.set_title(i, title)
        self.wTab.children = [
            VBox([
                self.regen_width, self.regen_height, self.regen_n_agents,
                self.regen_method
            ])
        ]

        # abbreviated description of buttons and the methods they call
        ldButtons = [
            dict(name="Refresh",
                 method=self.controller.refresh,
                 tip="Redraw only"),
            dict(name="Rotate Agent",
                 method=self.controller.rotate_agent,
                 tip="Rotate selected agent"),
            dict(name="Restart Agents",
                 method=self.controller.restart_agents,
                 tip="Move agents back to start positions"),
            dict(
                name="Random",
                method=self.controller.reset,
                tip="Generate a randomized scene, including regen rail + agents"
            ),
            dict(name="Regenerate",
                 method=self.controller.regenerate,
                 tip="Regenerate the rails using the method selected below"),
            dict(name="Load", method=self.controller.load),
            dict(name="Save", method=self.controller.save),
            dict(name="Save as image", method=self.controller.save_image)
        ]

        self.lwButtons = []
        for dButton in ldButtons:
            wButton = ipywidgets.Button(description=dButton["name"],
                                        tooltip=dButton["tip"] if "tip"
                                        in dButton else dButton["name"])
            wButton.on_click(dButton["method"])
            self.lwButtons.append(wButton)

        self.wVbox_controls = VBox([self.filename, *self.lwButtons, self.wTab])

        self.wMain = HBox([self.wImage, self.wVbox_controls])
예제 #27
0
파일: foi_panel.py 프로젝트: mokasini/cbm
def foi():
    path_plug = "cbm/foi/foi_db_func/"
    path_data = f"{config.get_value(['paths', 'temp'])}foi/"

    progress = Output()

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

    foi_info = HTML(
        value="""FOI procedures need direct access to the database. <br>
        In case there no image is provided, access to object storage will be needed to generate the base image from sentinel images.
        """,
        placeholder='FOI Information',
    )

    # Connect to database
    db_info = Label(f"1. Connect to database and object storage.")
    db_select = Dropdown(options=[db for db in config.get_value(['db'])],
                         description='Configure:',
                         disabled=True,
                         layout=Layout(width='140px'))
    db_config = Button(value=False,
                       disabled=False,
                       button_style='info',
                       tooltip='Configure db connection.',
                       icon='cogs',
                       layout=Layout(width='40px'))
    db_box = HBox([db_select, db_config])

    parcels_table = RadioButtons(
        options=[('Upload .shp', 0), ('From database', 1)],
        #    value='pineapple', # Defaults to 'pineapple'
        #    layout={'width': 'max-content'}, # If the items' names are long
        #         description='Pizza topping:',
        disabled=False)
    par_box = HBox([])

    def on_parcels_table(method):
        if method.new == 0:
            par_box.children = []
        elif method.new == 1:
            par_box.children = []

    parcels_table.observe(on_parcels_table, 'value')

    # Generate or upload image.
    img_info = Label(
        f"3. Upload or generate raster base image. (Only upload is currently available)"
    )
    img_option = ToggleButtons(
        options=['Upload', 'Generate'],
        value=None,
        disabled=True,
        button_style='info',  # 'success', 'info', 'warning', 'danger' or ''
        tooltips=['Upnload your base image', 'Get from object storage'])

    img_dist_folder = Text(value=f"{path_data}raster/",
                           placeholder='tmp/',
                           description='Folder:',
                           disabled=False)
    img_select = FileUpload(
        description='Select file:',
        icon='plus',
        accept='.tif, .tiff',
        multiple=True  # True to accept multiple files upload else False
    )
    img_clear = Button(value=False,
                       disabled=False,
                       button_style='info',
                       tooltip='Clear selections.',
                       icon='broom',
                       layout=Layout(width='40px'))
    img_upload = Button(value=False,
                        disabled=False,
                        button_style='info',
                        tooltip='Upload foi base image (.tif)',
                        icon='fa-upload',
                        layout=Layout(width='40px'))

    img_box = HBox(
        [HBox([img_dist_folder, img_select, img_clear, img_upload])])

    # YAML File upload
    yml_select = FileUpload(description='Select file:',
                            icon='plus',
                            accept='.yml, .yaml, .txt',
                            multiple=False)
    yml_clear = Button(value=False,
                       disabled=False,
                       button_style='info',
                       tooltip='Clear selection.',
                       icon='broom',
                       layout=Layout(width='40px'))
    yml_upload = Button(value=False,
                        disabled=False,
                        button_style='info',
                        tooltip='Upload yaml file.',
                        icon='fa-upload',
                        layout=Layout(width='40px'))
    yml_box = HBox([yml_select, yml_clear, yml_upload])

    # Prepare procedures
    pre_info = Label("4. Prepare FOI procedure.")
    pre_ins_func = Button(value=False,
                          disabled=False,
                          button_style='info',
                          tooltip='Insert functions to database.',
                          icon='fa-share-square',
                          layout=Layout(width='40px'))
    pre_ins_func_box = HBox(
        [Label("Add functions to database:"), pre_ins_func])
    vector_file = Dropdown(
        options=[s for s in glob.glob(f'{path_data}vector/*') if '.shp' in s],
        description='Vector file:',
        disabled=False,
    )
    raster_file = Dropdown(
        options=[s for s in glob.glob(f'{path_data}raster/*') if '.tif' in s],
        description='Raster file:',
        disabled=False,
    )

    yaml_file = Dropdown(
        options=[s for s in glob.glob(f'{path_data}/*') if '.yml' in s],
        description='yaml file:',
        disabled=False,
    )

    # heterogeneity_threshold
    pre_heto_chec = HTML("""
    Minimum and maximum thresholds for heterogeneity checks. In the example,
    any parcel with percentage of pixels for one class between 30 and 70 from
    the total, will be considered heterogenous.
    """)
    pre_min_het = IntText(value=30,
                          description='MIN:',
                          tooltip="Minimum threshold for heterogeneity checks",
                          disabled=False,
                          layout=Layout(width='150px'))
    pre_max_het = IntText(value=70,
                          description='MAX:',
                          tooltip="Maximum threshold for heterogeneity checks",
                          disabled=False,
                          layout=Layout(width='150px'))
    pre_heto_chec_box = HBox([pre_min_het, pre_max_het])
    pre_min_area = IntText(value=2000,
                           description='area:',
                           tooltip="Minimum area for clusters selection.",
                           disabled=False,
                           layout=Layout(width='200px'))

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

    pre_box = VBox([
        pre_info, pre_ins_func_box,
        HBox([Label("Select the requared files:"), refresh_selections]),
        HTML("""a. Spatial data to be tested - parcels that will
            be checked for heterogeneity and cardinality."""),
        HBox([vector_file]),
        HTML("""b. Thematic raster - classification raster, or raster 
            from other source that will be used for testing heterogeneity and cardinality."""
             ),
        HBox([raster_file]),
        HTML(
            """c. YAML file that holds the classes form the thematic raster file - 
            can be also a simple list of values in the notebook 
            corespondence between pixel values and names for the classes"""),
        HBox([yaml_file, yml_box]), pre_heto_chec, pre_heto_chec_box,
        HBox([
            pre_min_area,
            HTML(
                "Minimum area for clusters selection - only clusters bigger from this threshold will be counted."
            )
        ])
    ])

    # Run procedures
    run_info = Label("5. Run FOI procedure.")
    run_proc = Button(
        description='Run FOI procedure',
        value=False,
        disabled=False,
        button_style='info',
        tooltip='Run',
        icon='play',
    )
    run_box = HBox([run_proc])

    def on_img_option_change(change):
        if img_option.value == 'Upload':
            img_box.children = [
                HBox([img_dist_folder, img_select, img_clear, img_upload])
            ]
        else:
            img_box.children = ()

    img_option.observe(on_img_option_change, 'value')

    @refresh_selections.on_click
    def refresh_selections_on_click(b):
        vector_file.options = [
            s for s in glob.glob(f'{path_data}vector/*') if '.shp' in s
        ]
        raster_file.options = [
            s for s in glob.glob(f'{path_data}raster/*') if '.tif' in s
        ]
        yaml_file.options = [
            s for s in glob.glob(f'{path_data}/*') if '.yml' in s
        ]

    @img_clear.on_click
    def img_clear_on_click(b):
        img_select.value.clear()
        img_select._counter = 0

    @img_upload.on_click
    def img_upload_on_click(b):
        progress.clear_output()
        os.makedirs(img_dist_folder.value, exist_ok=True)
        for key in img_select.value:
            content = img_select.value[key]['content']
            with open(f'{img_dist_folder.value}{key}', 'wb') as f:
                f.write(content)
        outlog("All files are uploaded.")

    @yml_clear.on_click
    def yml_clear_on_click(b):
        yml_select.value.clear()
        yml_select._counter = 0

    @yml_upload.on_click
    def yml_upload_on_click(b):
        progress.clear_output()
        yml_dist_folder = f'{path_data}'
        os.makedirs(yml_dist_folder, exist_ok=True)
        for key in yml_select.value:
            content = yml_select.value[key]['content']
            with open(f'{yml_dist_folder}{key}', 'wb') as f:
                f.write(content)
        outlog("The yaml file is uploaded.")

    db_conf_box = HBox([])

    @db_config.on_click
    def db_config_on_click(b):
        if db_conf_box.children == ():
            db_conf_box.children = [settings.direct_conn()]
        else:
            db_conf_box.children = ()

    @pre_ins_func.on_click
    def pre_ins_func_on_click(b):
        progress.clear_output()
        try:
            functions = glob.glob(f"{path_plug}*.func")
            db = config.get_value(['set', 'db_conn'])
            sche = config.get_value(['db', db, 'conn', 'sche'])
            user = config.get_value(['db', db, 'conn', 'user'])

            for f in functions:
                database.insert_function(
                    open(f).read().format(schema=sche, owner=user))
            finc_list = [
                f"ipycbm_{f.split('/')[-1].split('.')[0]}, " for f in functions
            ]
            outlog(
                f"The functions: {('').join(finc_list)}where added to the database"
            )
        except Exception as err:
            outlog("Could not add functions to dattabase.", err)

    @run_proc.on_click
    def run_proc_on_click(b):
        with progress:
            foi_proc.proc(vector_file.value, raster_file.value,
                          yaml_file.value, pre_min_het.value,
                          pre_max_het.value, pre_min_area.value)

    wbox = VBox([
        foi_info, db_info, db_box, db_conf_box,
        proc_func.upload_shp(path_data), img_info, img_option, img_box,
        pre_box, run_info, run_box, progress
    ])

    return wbox
    def interact_plot_inversion(self):

        mode = RadioButtons(description="mode",
                            options=["Run", "Explore"],
                            value=self.mode)
        mref = FloatSlider(min=-2,
                           max=2,
                           step=0.05,
                           value=self.mref,
                           continuous_update=False,
                           description="mref")
        percentage = FloatText(value=self.percentage, description="percentage")
        floor = FloatText(value=self.floor, description="floor")
        beta_min = FloatText(value=self.beta_min, description="beta_min")
        beta_max = FloatText(value=self.beta_max, description="beta_min")
        n_beta = IntText(value=self.n_beta,
                         min=10,
                         max=100,
                         description="n_beta")
        alpha_s = FloatText(value=self.alpha_s, description="alpha_s")
        alpha_x = FloatText(value=self.alpha_x, description="alpha_x")
        tikhonov = RadioButtons(options=["phi_d & phi_m", "phi_d vs phi_m"],
                                value=self.tikhonov,
                                description='tikhonov')
        data_option = RadioButtons(options=["obs & pred", "normalized misfit"],
                                   value="obs & pred",
                                   description="data")
        scale = RadioButtons(options=["linear", "log"],
                             value=self.scale_inv,
                             description='scale')
        i_beta = IntSlider(min=0,
                           max=self.n_beta - 1,
                           step=1,
                           value=self.i_beta,
                           continuous_update=False,
                           description='i_beta')
        chifact = FloatText(value=self.chifact, description='chifact')
        noise_option = RadioButtons(
            options=["error contaminated", "clean data"],
            value=self.noise_option,
            description='noise option')
        out = interactive_output(
            self.plot_inversion,
            {
                "mode": mode,
                "mref": mref,
                "percentage": percentage,
                "floor": floor,
                "beta_min": beta_min,
                "beta_max": beta_max,
                "n_beta": n_beta,
                "alpha_s": alpha_s,
                "alpha_x": alpha_x,
                "tikhonov": tikhonov,
                "i_beta": i_beta,
                "chifact": chifact,
                "floor": floor,
                "data_option": data_option,
                "tikhonov": tikhonov,
                "scale": scale,
                "noise_option": noise_option
            },
        )
        a = Button(description='Misfit',
                   layout=Layout(width='100%', height='30px'))
        b = Button(description='Model norm',
                   layout=Layout(width='100%', height='30px'))
        c = Button(description='Beta',
                   layout=Layout(width='100%', height='30px'))
        d = Button(description='Plotting options',
                   layout=Layout(width='92%', height='30px'))

        return VBox([
            HBox([mode, noise_option]),
            HBox([
                VBox([a, percentage, floor, chifact]),
                VBox([b, mref, alpha_s, alpha_x]),
                VBox([c, beta_min, beta_max, n_beta, i_beta])
            ]),
            VBox([
                d,
                HBox([data_option, tikhonov, scale]),
            ]),
            HBox([out])
        ])
예제 #29
0
    def create_parameter_widgets(self, augmentation_name):
        """
        augmentation_name - name of the augmentation you want to test
        """
        function = partial(self.test_aug, augmentation_name=augmentation_name)

        ui_s = []
        widget_dict = {}

        for param_name, values in self.aug_dict[augmentation_name].items():
            if values[-2] == "width":
                lower = values[1]
                upper = self.shape[1]
            elif values[-2] == "height":
                lower = values[1]
                upper = self.shape[0]
            elif values[-2] == "channels-1":
                lower = values[1]
                upper = self.channels - 1
            elif values[-1] == "max":
                lower = values[1]
                upper = max(self.shape)
            else:
                lower = values[1]
                upper = values[2]

            if values[-1] == "odd" and values[0] in ["int" "int_range"]:
                step = 2
            elif values[-1] != "odd" and (values[0] == "int"
                                          or values[0] == "int_range"):
                step = 1
            elif values[0] == "float" or values[0] == "float_range":
                step = 0.01

            if values[0] == "int":
                widget = IntSlider(
                    min=lower,
                    max=upper,
                    step=step,
                    orientation="horizontal",
                    # description=f'{param_name}:',
                    continuous_update=False,
                )

                widget_ = IntText(
                    description="",
                    continuous_update=False,
                    readout=True,
                    readout_format="d",
                )
                widgets.link((widget, "value"), (widget_, "value"))
                widgets_linked = VBox([widget, widget_])
                widgets_linked_with_description = HBox(
                    [Label(param_name), widgets_linked])
                ui_s.append(widgets_linked_with_description)

                setattr(widgets_linked_with_description, "value", widget.value)

            elif values[0] == "int_range":
                widget = IntRangeSlider(
                    value=[1, 1] if values[-1] == "odd" else [0, 0],
                    min=lower,
                    max=upper,
                    step=step,
                    # description=f'{param_name}:',
                    disabled=False,
                    continuous_update=False,
                    orientation="horizontal",
                    readout=True,
                    readout_format="d",
                )
                widget_with_description = HBox([Label(param_name), widget])
                setattr(widget_with_description, "value", widget.value)

                ui_s.append(widget_with_description)

            elif values[0] == "float":
                widget = FloatSlider(
                    value=0,
                    min=lower,
                    max=upper,
                    step=step,
                    # description=f'{param_name}:',
                    disabled=False,
                    continuous_update=False,
                    orientation="horizontal",
                    readout=True,
                    readout_format=".2f",
                )
                widget_ = FloatText(
                    description="",
                    continuous_update=False,
                    readout=True,
                    readout_format=".2f",
                )
                widgets.link((widget, "value"), (widget_, "value"))
                widgets_linked = VBox([widget, widget_])
                widgets_linked_with_description = HBox(
                    [Label(param_name), widgets_linked])
                ui_s.append(widgets_linked_with_description)

                setattr(widgets_linked_with_description, "value", widget.value)

            elif values[0] == "float_range":
                widget = FloatRangeSlider(
                    value=[0, 0],
                    min=lower,
                    max=upper,
                    step=step,
                    disabled=False,
                    continuous_update=False,
                    orientation="horizontal",
                    readout=True,
                    readout_format=".2f",
                )

                widget_with_description = HBox([Label(param_name), widget])
                ui_s.append(widget_with_description)
                setattr(widget_with_description, "value", widget.value)

            elif values[0] == "str" or values[0] == "bool":
                widget = RadioButtons(options=[*values[1]],
                                      value=values[1][1],
                                      disabled=False)
                widget_with_description = HBox([Label(param_name), widget])
                setattr(widget_with_description, "value", widget.value)
                ui_s.append(widget_with_description)

            # ui_s.append(widget)
            widget_dict[f"{param_name}"] = widget

        out = interactive_output(function, widget_dict)

        display(*ui_s, out)
예제 #30
0
def create_q_widget(q):
    
    #Import modules:
    from ipywidgets import RadioButtons, Checkbox, Output, VBox, HBox
    from IPython.display import clear_output
    
    #Set widget style for description width:
    style = {'description_width': '80px'}
    
    #Initialize description output:
    description_out = Output()
    
    #Add quiz question to the description output:
    with description_out:
        print(q.prompt)
    
    #Check what type of widget should be created:
    if q.widget_type == 'RadioButtons':
        
        #Create RadioButtons-widget:
        w = RadioButtons(options = q.list_of_options,
                         description = ' ',
                         disabled = False)
        
        #Set widget width:
        w.layout.width = '370px'
        
        #Define feedback output:
        feedback = Output()
        
        #Open feedback object:
        with feedback:
            
            #Clear previous feedback:
            clear_output()
            
            #Print new feedback:
            print('')
    
        
        #Return widget in VBox:
        return VBox([description_out, w, feedback])
        
    
    #If the selected type of widget is ""Checkbox:
    elif q.widget_type == 'Checkbox':
        
        #Create list to store HBoxes:
        hbox_ls = []
        
        #Create a list of HBoxes, where every HBox includes a
        #Checkbox-widget and its corresponding feedback-output():
        for option in q.list_of_options:
            
            #Create widget:
            w = Checkbox(value=False, description=option, style=style, disabled=False)
            
            #Define feedback output:
            feedback = Output()
            
            #Open feedback object:
            with feedback:

                #Clear previous feedback:
                clear_output()

                #Print new feedback:
                print('')
            
            #Add Checkbox-widget and output()-widget with feedback to list:
            hbox_ls.append(HBox([w, feedback]))
        
        
        #Return all horizontal boxes in a vertical box including the prompt:
        return VBox([description_out] + hbox_ls)


    else:
        print('Question object has unknown widget type!')