Python ipywidgets.Dropdown() Examples

The following are 30 code examples of ipywidgets.Dropdown(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ipywidgets , or try the search function .
Example #1
Source File: selection.py    From notebook-molecular-visualization with Apache License 2.0 6 votes vote down vote up
def __init__(self, mol):
        super().__init__(mol)

        self.selection_type = ipy.Dropdown(description='Clicks select:',
                                           value=self.viewer.selection_type,
                                           options=('Atom', 'Residue', 'Chain'))

        traitlets.link((self.selection_type, 'value'), (self.viewer, 'selection_type'))

        self.residue_listname = ipy.Label('Selected residues:', layout=ipy.Layout(width='100%'))
        self.residue_list = ipy.SelectMultiple(options=list(), height='150px')
        self.viewer.observe(self._update_reslist, 'selected_atom_indices')

        self.residue_list.observe(self.remove_atomlist_highlight, 'value')
        self.atom_list.observe(self.remove_reslist_highlight, 'value')

        self.subtools.children = [self.representation_buttons]
        self.subtools.layout.flex_flow = 'column'
        self.toolpane.children = [self.selection_type,
                                  HBox([self.select_all_atoms_button, self.select_none]),
                                  self.atom_listname,
                                  self.atom_list,
                                  self.residue_listname,
                                  self.residue_list] 
Example #2
Source File: Viewer.py    From meshplot with GNU General Public License v3.0 6 votes vote down vote up
def add_text(self, text, shading={}):
        self.update_shading(shading)
        tt = p3s.TextTexture(string=text, color=self.s["text_color"])
        sm = p3s.SpriteMaterial(map=tt)
        self.text = p3s.Sprite(material=sm, scaleToTexture=True)
        self.scene.add(self.text)

    #def add_widget(self, widget, callback):
    #    self.widgets.append(widget)
    #    widget.observe(callback, names='value')

#    def add_dropdown(self, options, default, desc, cb):
#        widget = widgets.Dropdown(options=options, value=default, description=desc)
#        self.__widgets.append(widget)
#        widget.observe(cb, names="value")
#        display(widget)

#    def add_button(self, text, cb):
#        button = widgets.Button(description=text)
#        self.__widgets.append(button)
#        button.on_click(cb)
#        display(button) 
Example #3
Source File: test_interaction.py    From pySINDy with MIT License 6 votes vote down vote up
def test_dict():
    for d in [
        dict(a=5),
        dict(a=5, b='b', c=dict),
    ]:
        c = interactive(f, d=d)
        w = c.children[0]
        check = dict(
            cls=widgets.Dropdown,
            description='d',
            value=next(iter(d.values())),
            options=d,
            _options_labels=tuple(d.keys()),
            _options_values=tuple(d.values()),
        )
        check_widget(w, **check) 
Example #4
Source File: structureViewer.py    From mmtf-pyspark with Apache License 2.0 6 votes vote down vote up
def metal_distance_widget(df_concat):
    '''Plot an violinplot of metal-element distances with ipywidgets

    Parameters
    ----------
    df_concat : Dataframe
       dataframe of metal-elements distances

    '''
    metals = df_concat['Metal'].unique().tolist()
    m_widget = Dropdown(options = metals, description = "Metals")

    def metal_distance_violinplot(metal):
        df_metal = df_concat[df_concat["Metal"] == metal].copy()
        df_metal['Element'] = df_metal['Element'].apply(lambda x: metal+"-"+x)

        # Set fonts
        fig, ax = plt.subplots()
        fig.set_size_inches(15,6)
        subplot = sns.violinplot(x="Element", y="Distance", palette="muted", data=df_metal, ax=ax)
        subplot.set(xlabel="Metal Interactions", ylabel="Distance", title=f"{metal} to Elements Distances Violin Plot")

    return interact(metal_distance_violinplot, metal=m_widget); 
Example #5
Source File: test_interaction.py    From pySINDy with MIT License 6 votes vote down vote up
def test_default_out_of_bounds():
    @annotate(f=(0, 10.), h={'a': 1}, j=['hi', 'there'])
    def f(f='hi', h=5, j='other'):
        pass

    c = interactive(f)
    check_widgets(c,
        f=dict(
            cls=widgets.FloatSlider,
            value=5.,
        ),
        h=dict(
            cls=widgets.Dropdown,
            options={'a': 1},
            value=1,
        ),
        j=dict(
            cls=widgets.Dropdown,
            options=('hi', 'there'),
            value='hi',
        ),
    ) 
Example #6
Source File: widget.py    From altair_widgets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _generate_controller(self, ndims):
        marks = _get_marks()
        # mark button
        mark_choose = widgets.Dropdown(options=marks, description="Marks")
        mark_choose.observe(self._update, names="value")
        mark_choose.layout.width = "20%"
        mark_choose.row = -1
        mark_choose.title = "mark"

        # mark options button
        mark_but = widgets.Button(description="options")
        mark_but.layout.width = "10%"
        mark_but.row = -1
        mark_but.title = "mark_button"

        # Mark options
        mark_opt = widgets.VBox(children=[], visible=False)
        mark_but.on_click(self._show_advanced)
        mark_opt.title = "mark_options"
        mark_opt.layout.width = "300px"

        add_dim = widgets.Button(description="add encoding")
        add_dim.on_click(self._add_dim)

        dims = [self._create_shelf(i=i) for i in range(ndims)]

        choices = dims + [widgets.HBox([add_dim, mark_choose, mark_but, mark_opt])]
        return widgets.VBox(choices) 
Example #7
Source File: ABuWGBuyFactor.py    From abu with GNU General Public License v3.0 5 votes vote down vote up
def _init_widget(self):
        """构建AbuWeekMonthBuy策略参数界面"""

        self.description = widgets.Textarea(
            value=u'固定周期买入策略:\n'
                  u'根据参数每周买入一次或者每一个月买入一次\n'
                  u'需要与特定\'选股策略\'和\'卖出策略\'形成配合\n,'
                  u'单独使用固定周期买入策略意义不大',
            description=u'定期买入',
            disabled=False,
            layout=self.description_layout
        )

        is_buy_month_label = widgets.Label(u'可更改买入定期,默认定期一个月', layout=self.label_layout)
        self.is_buy_month = widgets.Dropdown(
            options={u'定期一个月': True, u'定期一个周': False},
            value=True,
            description=u'定期时长:',
        )
        is_buy_month_box = widgets.VBox([is_buy_month_label, self.is_buy_month])

        self.widget = widgets.VBox([self.description, is_buy_month_box, self.add],  # border='solid 1px',
                                   layout=self.widget_layout) 
Example #8
Source File: ABuWGSMTool.py    From abu with GNU General Public License v3.0 5 votes vote down vote up
def init_market_corr_ui(self):
        """全市场相关分析ui"""

        with self._init_widget_list_action(self.corr_market_analyse, u'全市场相关分析', 1) as widget_list:
            self.corr_market = widgets.Dropdown(
                options={u'美股': EMarketTargetType.E_MARKET_TARGET_US.value,
                         u'A股': EMarketTargetType.E_MARKET_TARGET_CN.value,
                         u'港股': EMarketTargetType.E_MARKET_TARGET_HK.value,
                         u'国内期货': EMarketTargetType.E_MARKET_TARGET_FUTURES_CN.value,
                         u'国际期货': EMarketTargetType.E_MARKET_TARGET_FUTURES_GLOBAL.value,
                         u'数字货币': EMarketTargetType.E_MARKET_TARGET_TC.value},
                value=ABuEnv.g_market_target.value,
                description=u'分析市场:',
            )
            market_tip1 = widgets.Label(value=u'分析市场的选择可以和分析目标不在同一市场', layout=self.label_layout)
            market_tip2 = widgets.Label(value=u'如分析目标为美股股票,分析市场也可选A股', layout=self.label_layout)
            market_box = widgets.VBox([market_tip1, market_tip2, self.corr_market])
            widget_list.append(market_box)

            tip_label1 = widgets.Label(u'全市场相关分析不支持开放数据模式', layout=self.label_layout)
            tip_label2 = widgets.Label(u'非沙盒模式需先用\'数据下载界面操作\'进行下载', layout=self.label_layout)
            self.corr_market_data_mode = widgets.RadioButtons(
                options={u'沙盒数据模式': True, u'本地数据模式': False},
                value=True,
                description=u'数据模式:',
                disabled=False
            )
            corr_market_box = widgets.VBox([tip_label1, tip_label2, self.corr_market_data_mode])
            widget_list.append(corr_market_box)

            self.corr_market_mode = widgets.RadioButtons(
                options={u'皮尔逊相关系数计算': 'pears', u'斯皮尔曼相关系数计算': 'sperm', u'基于+-符号相关系数': 'sign',
                         u'移动时间加权相关系数': 'rolling'},
                value='pears',
                description=u'相关模式:',
                disabled=False
            )
            widget_list.append(self.corr_market_mode)

        return widgets.VBox(widget_list,  # border='solid 1px',
                            layout=self.tool_layout) 
Example #9
Source File: ABuWGSellFactor.py    From abu with GNU General Public License v3.0 5 votes vote down vote up
def _init_widget(self):
        """构建AbuFactorSellNDay策略参数界面"""
        self.description = widgets.Textarea(
            value=u'持有N天后卖出策略:\n'
                  u'卖出策略,不管交易现在什么结果,买入后只持有N天\n'
                  u'需要与特定\'买入策略\'形成配合\n,'
                  u'单独使用N天卖出策略意义不大',
            description=u'N天卖出',
            disabled=False,
            layout=self.description_layout
        )
        sell_n_label = widgets.Label(u'设定买入后只持有天数,默认1', layout=self.label_layout)
        self.sell_n = widgets.IntText(
            value=1,
            description=u'N天',
            disabled=False
        )
        sell_n_box = widgets.VBox([sell_n_label, self.sell_n])

        is_sell_today_label = widgets.Label(u'设定买入n天后,当天还是隔天卖出', layout=self.label_layout)
        self.is_sell_today = widgets.Dropdown(
            options={u'N天后隔天卖出': False, u'N天后当天卖出': True},
            value=False,
            description=u'当天隔天:',
        )
        is_sell_today_box = widgets.VBox([is_sell_today_label, self.is_sell_today])

        self.widget = widgets.VBox([self.description, sell_n_box, is_sell_today_box, self.add_box],
                                   # border='solid 1px',
                                   layout=self.widget_layout) 
Example #10
Source File: ABuWGUmp.py    From abu with GNU General Public License v3.0 5 votes vote down vote up
def _init_feature_ui(self):
        """裁判特征采集界面初始化"""
        ml_feature_description = widgets.Textarea(
            value=u'裁判特征采集\n'
                  u'裁判是建立在机器学习技术基础上的,所以必然会涉及到特征,abu量化系统支持在回测过程中生成特征数据,切分训练测试集,'
                  u'甚至成交买单快照图片,通过打开下面的开关即可在生成最终的输出结果数据订单信息上加上买入时刻的很多信息,'
                  u'比如价格位置、趋势走向、波动情况等等特征, 注意需要生成特征后回测速度效率会降低\n'
                  u'如在下拉选择中选中\'回测过程生成交易特征\'在回测完成后将保存回测结果,通过在\'裁判特征训练\'可进行查看并进行'
                  u'裁判训练',
            disabled=False,
            layout=widgets.Layout(height='150px')
        )

        self.enable_ml_feature = widgets.Dropdown(
            options={u'回测过程不生成交易特征': 0,
                     u'回测过程生成交易特征': 1},
            value=0,
            description=u'特征生成:',
        )
        return widgets.VBox([ml_feature_description, self.enable_ml_feature]) 
Example #11
Source File: visualization.py    From minian with GNU General Public License v3.0 5 votes vote down vote up
def _widgets(self):
        sel_anm = iwgt.Dropdown(options=self.ls_anm, description='Animal:')
        sel_ss = iwgt.Dropdown(options=self.ls_ss, description='Session:')
        bt_mask0 = iwgt.Button(description="Update Template")
        bt_mask = iwgt.Button(description="Update Target")
        bt_mask0.on_click(self._save_mask0)
        bt_mask.on_click(self._save_mask)
        iwgt.interactive(self.str_sel.event, anm=sel_anm, ss=sel_ss)
        return iwgt.HBox([sel_anm, sel_ss, bt_mask0, bt_mask]) 
Example #12
Source File: ontologysearch.py    From tellurium with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        self.ch = bioservices.ChEBI()
        self.kegg = bioservices.KEGG()

        self.wOntologySelect = w.Dropdown(description='Ontology:', options=['ChEBI', 'KEGG.Reaction'])
        self.wSearchTerm = w.Text(description='Search Term:', value="glucose")
        self.wSearchTerm.on_submit(self.search)
        self.wSearchButton = w.Button(description='Search')
        self.wSearchButton.on_click(self.search)

        self.wResultsSelect = w.Select(description='Results:', width='100%')
        self.wResultsSelect.on_trait_change(self.selectedTerm)
        self.wResultsURL = w.Textarea(description='URL:', width='100%')
        self.wResults = w.VBox(children=[
                self.wResultsSelect,
                self.wResultsURL
        ], width='100%')
        for ch in self.wResults.children:
            ch.font_family = 'monospace'
            ch.color = '#AAAAAA'
            ch.background_color = 'black'

        # <Container>
        self.wContainer = w.VBox([
            self.wOntologySelect,
            self.wSearchTerm,
            self.wSearchButton,
            self.wResults
        ])

        # display the container
        display(self.wContainer)
        self.init_display() 
Example #13
Source File: options.py    From dask-gateway with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _widget(self):
        import ipywidgets

        return ipywidgets.Dropdown(value=self.value, options=self.options) 
Example #14
Source File: peakfinder2D_gui.py    From pyxem with GNU General Public License v3.0 5 votes vote down vote up
def create_choices_widget(self):
        from ipywidgets import Dropdown

        dropdown = Dropdown(
            options=list(self.method_names), value=self._method, description="Method",
        )

        def on_method_change(change):
            self._method = dropdown.value
            self.create_param_widgets()
            self.replot_peaks()

        dropdown.observe(on_method_change, names="value")
        display(dropdown) 
Example #15
Source File: widget.py    From altair_widgets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _controllers_for(opt):
    """
    Give a string representing the parameter represented, find the appropriate
    command.

    """
    colors = [None, "blue", "red", "green", "black"]
    controllers = {
        "type": widgets.Dropdown(
            options=["auto detect"] + _get_types(), description="type"
        ),
        "bin": widgets.Checkbox(description="bin"),
        "aggregate": widgets.Dropdown(
            options=[None] + _get_functions(), description="aggregate"
        ),
        "zero": widgets.Checkbox(description="zero"),
        "text": widgets.Text(description="text value"),
        "scale": widgets.Dropdown(options=["linear", "log"], description="scale"),
        "color": widgets.Dropdown(options=colors, description="main color"),
        "applyColorToBackground": widgets.Checkbox(
            description="applyColorToBackground"
        ),
        "shortTimeLabels": widgets.Checkbox(description="shortTimeLabels"),
    }

    for title, controller in controllers.items():
        controller.title = title
        if "Checkbox" in str(controller):
            # traits = dir(controller.layout)
            # traits = [t for t in traits if t[0] != '_']
            controller.layout.max_width = "200ex"
            # controller.layout.min_width = '100ex'
            # controller.layout.width = '150ex'

    return controllers[opt] 
Example #16
Source File: data.py    From jupyter-innotater with MIT License 5 votes vote down vote up
def _create_widget(self):
        if self.dropdown:
            return Dropdown(options=self.classes, layout=self.layout, disabled=self.disabled)
        return Select(options=self.classes, layout=self.layout, disabled=self.disabled) 
Example #17
Source File: test_interaction.py    From pySINDy with MIT License 5 votes vote down vote up
def test_list_str():
    values = ['hello', 'there', 'guy']
    first = values[0]
    c = interactive(f, lis=values)
    nt.assert_equal(len(c.children), 2)
    d = dict(
        cls=widgets.Dropdown,
        value=first,
        options=tuple(values),
        _options_labels=tuple(values),
        _options_values=tuple(values),
    )
    check_widgets(c, lis=d) 
Example #18
Source File: case.py    From psst with MIT License 5 votes vote down vote up
def __init__(self, case, *args, **kwargs):

        self.case = case

        super(CaseView, self).__init__(**kwargs)

        self.generator_names = ipyw.Dropdown(
            options=list(self.case.gen.index)
        )

        children = [
            self.generator_names,
        ]

        self.children = children 
Example #19
Source File: dataset.py    From avocado with MIT License 5 votes vote down vote up
def plot_interactive(self):
        """Make an interactive plot of the light curves in the dataset.

        This requires the ipywidgets package to be set up, and has only been
        tested in jupyter-lab.
        """
        from ipywidgets import interact, IntSlider, Dropdown

        object_classes = {"": None}
        for object_class in np.unique(self.metadata["class"]):
            object_classes[object_class] = object_class

        idx_widget = IntSlider(min=0, max=1)
        class_widget = Dropdown(options=object_classes, index=0)

        def update_idx_range(*args):
            if class_widget.value is None:
                idx_widget.max = len(self.metadata) - 1
            else:
                idx_widget.max = (
                    np.sum(self.metadata["class"] == class_widget.value) - 1
                )

        class_widget.observe(update_idx_range, "value")

        update_idx_range()

        interact(
            self.plot_light_curve,
            index=idx_widget,
            object_class=class_widget,
            show_gp=True,
            uncertainties=True,
            verbose=False,
            subtract_background=True,
        ) 
Example #20
Source File: explorer.py    From scqubits with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def interact(self):
        """Drives the interactive display of the plot explorer panels"""
        param_min = self.param_vals[0]
        param_max = self.param_vals[-1]
        param_step = self.param_vals[1] - self.param_vals[0]

        qbt_indices = [index for (index, subsystem) in self.sweep.qbt_subsys_list]
        osc_indices = [index for (index, subsystem) in self.sweep.osc_subsys_list]

        param_slider = ipywidgets.FloatSlider(min=param_min, max=param_max, step=param_step,
                                              description=self.param_name, continuous_update=False)
        photon_slider = ipywidgets.IntSlider(value=1, min=1, max=4, description='photon number')
        initial_slider = ipywidgets.IntSlider(value=0, min=0, max=self.evals_count, description='initial state index')
        final_slider = ipywidgets.IntSlider(value=1, min=1, max=self.evals_count, description='final state index')

        qbt_dropdown = ipywidgets.Dropdown(options=qbt_indices, description='qubit subsys')
        osc_dropdown = ipywidgets.Dropdown(options=osc_indices, description='oscillator subsys')

        def update_min_final_index(*args):
            final_slider.min = initial_slider.value + 1

        initial_slider.observe(update_min_final_index, 'value')

        out = ipywidgets.interactive_output(self.plot_explorer_panels,
                                            {'param_val': param_slider,
                                             'photonnumber': photon_slider,
                                             'initial_index': initial_slider,
                                             'final_index': final_slider,
                                             'qbt_index': qbt_dropdown,
                                             'osc_index': osc_dropdown
                                             })

        left_box = ipywidgets.VBox([param_slider])
        mid_box = ipywidgets.VBox([initial_slider, final_slider, photon_slider])
        right_box = ipywidgets.VBox([qbt_dropdown, osc_dropdown])

        user_interface = ipywidgets.HBox([left_box, mid_box, right_box])
        display(user_interface, out) 
Example #21
Source File: widget.py    From altair_widgets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _create_shelf(self, i=0):
        """
        Creates shelf to plot a dimension (includes buttons
        for data column, encoding, data type, aggregate)

        """
        encodings = _get_encodings()

        cols = widgets.Dropdown(options=self.columns, description="encode")
        encoding = widgets.Dropdown(
            options=encodings, description="as", value=encodings[i]
        )
        encoding.layout.width = "20%"

        adv = widgets.VBox(children=[], visible=False, layout=Layout(visibility="hidden"))

        button = widgets.Button(description="options", disabled=True)
        button.on_click(self._show_advanced)
        button.layout.width = "10%"

        # The callbacks when the button is clicked
        encoding.observe(self._update, names="value")
        cols.observe(self._update, names="value")

        # Making sure we know what row we're in in the callbacks
        encoding.row = cols.row = button.row = adv.row = i

        # Have the titles so we know what button we're editing
        encoding.title = "encoding"
        cols.title = "field"
        button.title = "button"
        adv.title = "advanced"

        return widgets.HBox([cols, encoding, button, adv]) 
Example #22
Source File: test_interaction.py    From pySINDy with MIT License 5 votes vote down vote up
def test_list_int():
    values = [3, 1, 2]
    first = values[0]
    c = interactive(f, lis=values)
    nt.assert_equal(len(c.children), 2)
    d = dict(
        cls=widgets.Dropdown,
        value=first,
        options=tuple(values),
        _options_labels=tuple(str(v) for v in values),
        _options_values=tuple(values),
    )
    check_widgets(c, lis=d) 
Example #23
Source File: test_interaction.py    From pySINDy with MIT License 5 votes vote down vote up
def test_list_tuple():
    values = [(3, 300), (1, 100), (2, 200)]
    first = values[0][1]
    c = interactive(f, lis=values)
    nt.assert_equal(len(c.children), 2)
    d = dict(
        cls=widgets.Dropdown,
        value=first,
        options=tuple(values),
        _options_labels=("3", "1", "2"),
        _options_values=(300, 100, 200),
    )
    check_widgets(c, lis=d) 
Example #24
Source File: test_interaction.py    From pySINDy with MIT License 5 votes vote down vote up
def test_ordereddict():
    from collections import OrderedDict
    items = [(3, 300), (1, 100), (2, 200)]
    first = items[0][1]
    values = OrderedDict(items)
    c = interactive(f, lis=values)
    nt.assert_equal(len(c.children), 2)
    d = dict(
        cls=widgets.Dropdown,
        value=first,
        options=values,
        _options_labels=("3", "1", "2"),
        _options_values=(300, 100, 200),
    )
    check_widgets(c, lis=d) 
Example #25
Source File: test_interaction.py    From pySINDy with MIT License 5 votes vote down vote up
def test_iterable_tuple():
    values = [(3, 300), (1, 100), (2, 200)]
    first = values[0][1]
    c = interactive(f, lis=iter(values))
    nt.assert_equal(len(c.children), 2)
    d = dict(
        cls=widgets.Dropdown,
        value=first,
        options=tuple(values),
        _options_labels=("3", "1", "2"),
        _options_values=(300, 100, 200),
    )
    check_widgets(c, lis=d) 
Example #26
Source File: test_interaction.py    From pySINDy with MIT License 5 votes vote down vote up
def test_mapping():
    from collections import Mapping, OrderedDict
    class TestMapping(Mapping):
        def __init__(self, values):
            self.values = values
        def __getitem__(self):
            raise NotImplementedError
        def __len__(self):
            raise NotImplementedError
        def __iter__(self):
            raise NotImplementedError
        def items(self):
            return self.values

    items = [(3, 300), (1, 100), (2, 200)]
    first = items[0][1]
    values = TestMapping(items)
    c = interactive(f, lis=values)
    nt.assert_equal(len(c.children), 2)
    d = dict(
        cls=widgets.Dropdown,
        value=first,
        options=tuple(items),
        _options_labels=("3", "1", "2"),
        _options_values=(300, 100, 200),
    )
    check_widgets(c, lis=d) 
Example #27
Source File: test_interaction.py    From pySINDy with MIT License 5 votes vote down vote up
def test_default_values():
    @annotate(n=10, f=(0, 10.), g=5, h=OrderedDict([('a',1), ('b',2)]), j=['hi', 'there'])
    def f(n, f=4.5, g=1, h=2, j='there'):
        pass

    c = interactive(f)
    check_widgets(c,
        n=dict(
            cls=widgets.IntSlider,
            value=10,
        ),
        f=dict(
            cls=widgets.FloatSlider,
            value=4.5,
        ),
        g=dict(
            cls=widgets.IntSlider,
            value=5,
        ),
        h=dict(
            cls=widgets.Dropdown,
            options=OrderedDict([('a',1), ('b',2)]),
            value=2
        ),
        j=dict(
            cls=widgets.Dropdown,
            options=('hi', 'there'),
            value='there'
        ),
    ) 
Example #28
Source File: test_widget_selection.py    From pySINDy with MIT License 5 votes vote down vote up
def test_construction(self):
        Dropdown() 
Example #29
Source File: file_info_database.py    From qkit with GNU General Public License v2.0 4 votes vote down vote up
def show(self, show_raw=False):
            """
            used to show the data base as a qgrid object or if not installed pandas data frame
            :return: data frame as qgrid object or pandas object
            """
            self.wait()
            if self.found_qgrid:
                if LooseVersion(qd.__version__) < LooseVersion("1.3.0") and LooseVersion(pd.__version__) >= LooseVersion("1.0"):
                    logging.warning("qgrid < v1.3 is incompatible with pandas > v1.0. Check for a new version of qgrid or downgrade pandas to v0.25.3")
                    self.found_qgrid = False
            if self.found_qgrid:
                from IPython.display import display
                import ipywidgets as widgets
                rows = [d for d in self.column_sorting if d in list(self.df.keys()) and d not in self.columns_ignore]
                rows += [d for d in list(self.df.keys()) if d not in self.column_sorting and d not in self.columns_ignore]
            
                _openSelected = widgets.Button(description='open selected', disabled=False,
                                               button_style='', tooltip='open selected')
                _openSelected.on_click(self._on_openSelected_clicked)
            
                _batch_modifier = widgets.Button(description='for all selected rows',
                                                 tooltip='Change the selected attribute to the specified value for all rows selected.')
                _batch_modifier.key_dd = widgets.Dropdown(options=rows, description="Set")
                _batch_modifier.value_tf = widgets.Text(value='', placeholder='Value', description='to:')
                _batch_modifier.on_click(self._batch_change_attribute)
            
                display(widgets.HBox([_openSelected, _batch_modifier.key_dd, _batch_modifier.value_tf, _batch_modifier]))
            
                if show_raw or "rating" not in self.df.keys():
                    df = self.df.copy()
                else:
                    df = self.df.copy()[self.df['rating'] > 0]
                self.grid = qd.show_grid(df[rows], show_toolbar=False, grid_options={'enableColumnReorder': True})
                self.grid.observe(self._on_row_selected, names=['_selected_rows'])
                self.grid.observe(self._grid_observer, names=[
                    '_selected_rows'])  # Quick fix to also work with newer versions of qgrid. Should be changed to the .on() event mechanism at some point, but this requires newer qgrid version.
                return self.grid
            else:
                if show_raw or "rating" not in self.df.keys():
                    return self.df
                else:
                    return self.df[self.df['rating'] > 0] 
Example #30
Source File: orbital_viewer.py    From notebook-molecular-visualization with Apache License 2.0 4 votes vote down vote up
def _make_ui_pane(self, hostheight):
        layout = ipy.Layout(width='325px',
                            height=str(int(hostheight.rstrip('px')) - 50) + 'px')
        #element_height = str(int(hostheight.rstrip('px')) - 125) + 'px'
        element_height = None
        # NOTE - element_height was used for the listbox-style orblist.
        #   HOWEVER ipywidgets 6.0 only displays those as a dropdown.
        #   This is therefore disabled until we can display listboxes again. -- AMV 7/16

        # Orbital set selector
        self.status_element = ipy.HTML(layout=ipy.Layout(width='inherit', height='20px'))
        orbtype_label = ipy.Label("Orbital set:")
        self.type_dropdown = ipy.Dropdown(options=list(self.wfn.orbitals.keys()))
        initialtype = 'canonical'
        if initialtype not in self.type_dropdown.options:
            initialtype = next(iter(self.type_dropdown.options.keys()))
        self.type_dropdown.value = initialtype
        self.type_dropdown.observe(self.new_orb_type, 'value')

        # List of orbitals in this set
        orblist_label = ipy.Label("Orbital:")
        self.orblist = ipy.Dropdown(options={None: None},
                                    layout=ipy.Layout(width=layout.width, height=element_height))
        traitlets.link((self.orblist, 'value'), (self, 'current_orbital'))

        # Isovalue selector
        isoval_label = ipy.Label('Isovalue:')
        self.isoval_selector = ipy.FloatSlider(min=0.0, max=0.075,
                                               value=0.01, step=0.00075,
                                               readout_format='.4f',
                                               layout=ipy.Layout(width=layout.width))
        traitlets.link((self.isoval_selector, 'value'), (self, 'isoval'))

        # Opacity selector
        opacity_label = ipy.Label('Opacity:')
        self.opacity_selector = ipy.FloatSlider(min=0.0, max=1.0,
                                               value=0.8, step=0.01,
                                               readout_format='.2f',
                                               layout=ipy.Layout(width=layout.width))
        traitlets.link((self.opacity_selector, 'value'), (self, 'orb_opacity'))

        # Resolution selector
        resolution_label = ipy.Label("Grid resolution:", layout=ipy.Layout(width=layout.width))
        self.orb_resolution = ipy.Text(layout=ipy.Layout(width='75px',
                                                         positioning='bottom'))
        self.orb_resolution.value = str(self.numpoints)
        self.resolution_button = ipy.Button(description='Update resolution')
        self.resolution_button.on_click(self.change_resolution)
        traitlets.directional_link((self, 'numpoints'), (self.orb_resolution, 'value'),
                                   transform=str)

        self.uipane = ipy.VBox([self.status_element,
                                orbtype_label, self.type_dropdown,
                                orblist_label, self.orblist,
                                isoval_label, self.isoval_selector,
                                opacity_label, self.opacity_selector,
                                resolution_label, self.orb_resolution, self.resolution_button])
        self.new_orb_type()
        self.type_dropdown.observe(self.new_orb_type, 'value')
        return self.uipane