Example #1
0
    def __init__(self, grid, color_map, title, bounding_box, codim, U, vmins,
                 vmaxs, separate_colorbars, size):
        render_size = (300, 300)
        self.renderer = [
            Renderer(u,
                     grid,
                     render_size,
                     color_map,
                     title,
                     bounding_box=bounding_box,
                     codim=codim,
                     vmin=vmin,
                     vmax=vmax) for u, vmin, vmax in zip(U, vmins, vmaxs)
        ]
        bar_size = (100, render_size[1])
        if not separate_colorbars:
            self.colorbars = [
                ColorBarRenderer(render_size=bar_size,
                                 vmin=vmins[0],
                                 vmax=vmaxs[0],
                                 color_map=color_map)
            ]
            self.r_hbox_items = self.renderer + self.colorbars
        else:
            self.r_hbox_items = []
            self.colorbars = []
            for vmin, vmax, renderer in zip(vmins, vmaxs, self.renderer):
                cr = ColorBarRenderer(render_size=bar_size,
                                      vmin=vmin,
                                      vmax=vmax,
                                      color_map=color_map)
                self.r_hbox_items.append(widgets.HBox([renderer, cr]))
                self.colorbars.append(cr)
        layout = Layout(display='flex',
                        flex_flow='row wrap',
                        align_items='stretch',
                        justify_content='flex-start')
        children = [widgets.Box(self.r_hbox_items, layout=layout)]
        if size > 1:

            def _goto_idx(idx):
                for c in self.renderer:
                    c.goto(idx)

            play = Play(min=0,
                        max=size - 1,
                        step=1,
                        value=0,
                        description='Timestep:')
            interact(idx=play).widget(_goto_idx)
            slider = IntSlider(min=0,
                               max=size - 1,
                               step=1,
                               value=0,
                               description='Timestep:')
            widgets.jslink((play, 'value'), (slider, 'value'))
            controls = widgets.HBox([play, slider])
            children.append(controls)

        super().__init__(children=children)
Example #2
0
 def createCheckbox(self, checkboxlist, text):
     containerList = [(widgets.Checkbox(description=k))
                      for k in checkboxlist]
     containerList.insert(0, widgets.HTML(value=text))
     bigContainer = widgets.Box(children=(containerList))
     display(bigContainer)
     return bigContainer
    def plotConf(self):
        """ Plot configuration using nglview """

        v = nglview.show_ase(self.conf)
        v.add_representation("unitcell")
        boxy=widgets.Box([v],layout=self.box_layout)
        display(boxy)
Example #4
0
    def _create_multiselection_widget(self, key, disabled):
        # type: (str, bool) -> widgets.Box
        """Return a Box containing as many Checkbox widgets as
        parameter's options, with those in its "value" field checked.

        Keyword Arguments:
            key      -- name of the parameter
            disabled -- is the parameter/widget disabled?
        """
        itemWidgets = []
        for item in self._parameters[key]['options']:
            layoutWidth = '23%' if (len(item) <= 10) else '48%'
            inputWidget = _TaggedCheckbox(value=item in self[key],
                                          description=item,
                                          tag=key,
                                          style=self._style,
                                          layout=Layout(width=layoutWidth),
                                          disabled=disabled)
            # Add handler for when the "value" trait changes
            inputWidget.observe(self._multiselection_handler, names='value')
            itemWidgets.append(inputWidget)
        layout = Layout(width='46%',
                        display='flex',
                        flex_flow='row wrap',
                        justify_content='space-between')
        return widgets.Box(itemWidgets, layout=layout)
Example #5
0
def set_boards():
    '''修改故事推荐位'''
    def board_func(btn):
        boards = []
        for i in range(3):
            board = []
            for p in range(2):
                try:
                    board.append(
                        int(board_container.children[i].children[p].value))
                except ValueError:
                    board.append(
                        board_container.children[i].children[p].value.encode(
                            'utf-8'))  # noqa
            boards.append(board)
        r.boards = boards
        r.promo_title = board_container.children[3].value.encode('utf-8')
        r.promo_subtitle = board_container.children[4].value.encode('utf-8')
        hide_btn(btn)

    board_container = widgets.Box()
    btn = get_btn("故事推荐位")
    children = []
    for o, board in enumerate(r.boards):
        promo = widgets.Box()
        _children = []
        for index, o in enumerate(['StoryID', 'Title']):
            b = board[index]
            if isinstance(b, int):
                b = str(b)
            c = widgets.Text(description=o)
            c.value = b.decode('utf-8')
            _children.append(c)
        promo.children = _children
        children.append(promo)
    promo_title = widgets.Text(description="推荐位标题")
    promo_title.value = r.promo_title.decode('utf-8')
    promo_subtitle = widgets.Text(description="推荐位副标题")
    promo_subtitle.value = r.promo_subtitle.decode('utf-8')
    children.append(promo_title)
    children.append(promo_subtitle)
    children.append(btn)
    board_container.children = children
    btn.on_click(board_func)
    display(board_container)
    board_container._dom_classes = ('board', )
 def plotEnv(self,myEnvironment):
     env_atom_types = np.asarray(self.conf.get_chemical_symbols())[myEnvironment.indeces.astype(int)] #,np.array('C')] #Template[env_number].myindex)]
     env_atom_types = np.append(env_atom_types,np.asarray(self.conf.get_chemical_symbols())[myEnvironment.myindex])
     env_positions = np.vstack((myEnvironment.delta*10,np.array([0,0,0]) ) )
     env = ase.Atoms(env_atom_types,env_positions)
     v = nglview.show_ase(env)
     boxy=widgets.Box([v],layout=self.box_layout)
     display(boxy)
Example #7
0
def display_form(form_widgets: Sequence[widgets.Widget]) -> None:
    clear_output()
    box_layout = widgets.Layout(display='flex',
                                flex_flow='column',
                                align_items='stretch',
                                border='solid',
                                width='100%')
    box = widgets.Box(children=list(form_widgets), layout=box_layout)
    display(box)
Example #8
0
def FormAnnotator(ann,
                  annotate_fields=True,
                  annotate_types=True,
                  max_fields=80):
    """
    Widget for annotating a single HTML form.
    """
    assert annotate_fields or annotate_types
    form_types_inv = ann.form_schema.types_inv

    children = []

    if annotate_types:
        children += [FormTypeSelect(ann)]

    tpl = """
    <h4>
        {tp} <a href='{url}'>{url}</a>
        <small>{key} #{index}</small>
    </h4>
    """
    header = widgets.HTML(
        tpl.format(url=ann.url,
                   index=ann.index,
                   key=ann.key,
                   tp=form_types_inv.get(ann.type, '?')))
    children += [header]

    if annotate_fields:
        pages = []
        names = get_field_names(get_fields_to_annotate(ann.form))
        if len(names) > max_fields:
            children += [
                widgets.HTML("<h4>Too many fields ({})</h4>".format(
                    len(names)))
            ]
        else:
            for name in names:
                field_type_select = FieldTypeSelect(ann, name)
                html_view = HtmlView(ann.form, name)
                page = widgets.Box(children=[field_type_select, html_view])
                pages.append(page)

            field_tabs = widgets.Tab(children=pages, padding=4)
            for idx, name in enumerate(names):
                field_tabs.set_title(idx, name)

            children += [field_tabs]
    else:
        children += [HtmlView(ann.form)]

    return widgets.VBox(children, padding=8)
Example #9
0
    def __init__(self):
        self.all_years_data = self.get_data()

        ##Make initial widget
        self.container = widgets.Box()
        self.container.border_color = 'red'
        self.container.border_style = 'dotted'
        self.container.border_width = 3
        self.Search = widgets.Text(description='Search:',
                                   value='Enter school name here')
        self.container.children = [self.Search]
        display(self.container)
        self.Search.on_submit(self.update_dropdown)
Example #10
0
    def display_qubit_info(self, qubit_info: bool) -> None:
        """Displays the image that corresponds to the current qubit.

        Parameters
        ----------
        qubit_info: bool
        """
        if qubit_info:
            image_box = widgets.Box(layout=Layout(justify_content="center"))
            image_box.children = [
                self.qubit_plot_options_widgets["qubit_info_image_widget"]
            ]
            display(image_box)
Example #11
0
    def __init__(self, vizapp, filename=None):

        self._vizapp = vizapp

        self.mostable = None
        self.mostable_dir = None
        self.data = None
        self.html = None
        self.current_cutout = None

        #  Create File Menu
        self._menu_bar_file = widgets.Dropdown(
            options=['File', 'Load', 'Save'],
            value='File',
            description='',
            layout=widgets.Layout(width='10em'),
        )

        self._menu_bar_file.observe(self._on_change_menu_bar_file)
        self._menu_bar = widgets.HBox([self._menu_bar_file])

        #  Create Navigation Bar
        self._current_slit = widgets.Dropdown(
            options=[],
            description='Slit',
            layout=widgets.Layout(width='20em'),
        )
        self._current_slit.observe(self._on_change_current_slit)

        self._next_button = widgets.Button(description="Next")
        self._next_button.on_click(self._on_next)

        self._back_button = widgets.Button(description="Back")
        self._back_button.on_click(self._on_back)

        self._nav_bar = widgets.HBox(
            [self._current_slit, self._back_button, self._next_button])

        self._table = MOSVizTable(session=self._vizapp.glue_app.session)
        self._mos_widget = MOSVizWidget(session=self._vizapp.glue_app.session)

        self._viewer_box = widgets.VBox([self._mos_widget, self._table.show()])

        self._main_box = widgets.Box([
            widgets.VBox([self._nav_bar,
                          self._table.show(), self._mos_widget])
        ])

        if filename:
            self._vizapp.glue_app.load_data(filename)
Example #12
0
def set_doulist():
    '''修改豆列推荐位'''
    def doulist_func(btn):
        doulists = []
        for i in range(2):
            doulist = []
            doulist_id = doulist_container.children[i].children[0].value
            doulist.append(doulist_id)
            _stories = []
            for p in range(1, 6):
                _stories.append(
                    doulist_container.children[i].children[p].value)
            doulist.append(_stories)
            doulists.append(doulist)
        r.promo_ids = doulists
        hide_btn(btn)

    doulist_container = widgets.Box()
    btn = get_btn("豆列推荐位")
    children = []
    for doulist_id, stories_ids in r.promo_ids:
        doulist = widgets.Box()
        _children = []
        c = widgets.Text(description="豆列ID")
        c.value = str(doulist_id)
        _children.append(c)
        for sid in stories_ids:
            c = widgets.Text()
            c.value = str(sid)
            _children.append(c)
        doulist.children = _children
        children.append(doulist)
    children.append(btn)
    doulist_container.children = children
    btn.on_click(doulist_func)
    display(doulist_container)
    doulist_container._dom_classes = ('doulist', )
Example #13
0
    def __init__(self, config):
        self._config = config

        if path.isfile(self._config["filename"]):
            self._data = pd.read_csv(self._config["filename"])
        else:
            self._data = pd.DataFrame()
        
        self._boxes = []
        for field in self._config["fields"]:
            field["txt_value"] = widgets.Text()
            self._boxes.append(widgets.Box([
                widgets.Label(field["name"]),
                field["txt_value"],
            ]))
Example #14
0
def set_review():
    '''修改图文'''
    def review_func(btn):
        _review_ids = [review_container.children[i].value for i in range(3)]
        r.review_ids = _review_ids
        hide_btn(btn)

    review_container = widgets.Box()
    btn = get_btn("图文")
    children = []
    for o in range(3):
        c = widgets.Text(description="第{}条图文ID".format(o + 1))
        c.value = str(r.review_ids[o])
        children.append(c)
    children.append(btn)
    review_container.children = children
    btn.on_click(review_func)
    display(review_container)
Example #15
0
    def __init__(self, filename, vizapp):

        self._vizapp = vizapp

        self._vizapp.glue_app.load_data(filename)

        #
        #  Create File Menu
        #
        self._menu_bar_file = widgets.Dropdown(
            options=['File', 'Load', 'Save'],
            value='File',
            description='',
            layout=widgets.Layout(width='10em'),
        )
        self._menu_bar_file.observe(self._on_change_menu_bar_file)

        #
        #  Create Add Viewer Menu
        #
        self._menu_bar_viewer = widgets.Dropdown(
            options=['Add Viewer', '3D Viewer', '1D Viewer'],
            value='Add Viewer',
            description='',
            layout=widgets.Layout(width='10em'),
        )
        self._menu_bar_viewer.observe(self._on_change_menu_bar_viewer)

        # Add to menu bar
        self._menu_bar = widgets.HBox(
            [self._menu_bar_file, self._menu_bar_viewer])
        self._menu_bar.box_style = 'success'

        self._v1d = Viewer1D(self._vizapp)
        self._v3d = ViewerND(self._vizapp)

        self._main_box = widgets.Box([
            widgets.VBox([
                self._menu_bar,
                widgets.HBox([self._v3d.show(),
                              self._v1d.show()])
            ])
        ])
Example #16
0
def HtmlCode(form_html, field_name=None, max_height=None, **kwargs):
    """ Show HTML source code, optionally with a field highlighted """
    kw = {}
    if field_name is None:
        show_html = html_escape(form_html)
        kw['color'] = "#000"
    else:
        show_html = escaped_with_field_highlighted(form_html, field_name)
        kw['color'] = "#777"
    kw.update(kwargs)
    style = '; '.join([
        'white-space:pre-wrap', 'max-width:800px', 'word-wrap:break-word',
        'font-family:monospace', 'overflow:scroll',
        "max-height: {}px;".format(max_height) if max_height else ""
    ])

    html_widget = widgets.HTML(
        "<div style='{}'>{}</div>".format(style, show_html), **kw)
    return widgets.Box([html_widget], padding=8)
Example #17
0
def build_widgets(controls, visid):
    try:
        results = {'widgets': []}
        # add filters
        add_filter_widgets(controls, visid, results)
        # soon..  add others..

        if len(results['widgets']) == 0:
            # No widgets
            return

        widget_box = widgets.Box(
            children=[x for x in results['widgets'] if x is not None])
        return {'widget_box': widget_box}

    except KeyError:
        # no interactivity or filters.  Do Nothing
        return
    return
Example #18
0
    def render_form(self):
        clear_output()

        display(self._data)
        for field in self._config["fields"]:
            field["txt_value"].value = field["default"] if "default" in field else ""
        
        for box in self._boxes:
            display(box)

        btn_submit = widgets.Button(description="submit")
        btn_clear = widgets.Button(description="clear")

        btn_submit.on_click(self._cb_submit)
        btn_clear.on_click(self._cb_clear)

        display(widgets.Box([
            btn_submit,
            btn_clear,
        ]))
        if len(self._data) > 1:
            for plot in self._config["plots"]:
                self._data.plot(**plot)
Example #19
0
    def __init__(self, ipython,
                 regex_ignore=r'(VariableInspectorWindow|inspector)',
                 ignore_types=(types.ModuleType, types.FunctionType)):
        """Public constructor."""
        if VariableInspectorWindow.instance is not None:
            raise Exception("""Only one instance of the Variable Inspector can exist at a
                time.  Call close() on the active instance before creating a new instance.
                If you have lost the handle to the active instance, you can re-obtain it
                via `VariableInspectorWindow.instance`.""")

        VariableInspectorWindow.instance = self
        self.closed = False
        self.namespace = NamespaceMagics()
        self.namespace.shell = ipython.kernel.shell

        self._box = widgets.Box()
        self._box._dom_classes = ['inspector']
        self._box.background_color = '#fff'
        self._box.border_color = '#ccc'
        self._box.border_width = 1
        self._box.border_radius = 5

        self._modal_body = widgets.VBox()
        self._modal_body.overflow_y = 'scroll'

        self._modal_body_label = widgets.HTML(value = 'Not hooked')
        self._modal_body.children = [self._modal_body_label]

        self._box.children = [
            self._modal_body,
        ]

        self._ipython = ipython
        self._ipython.events.register('post_run_cell', self._fill)

        self.regex_ignore = regex_ignore
        self.ignore_types = ignore_types
Example #20
0
    def initiate(self):

        tab_children = []
        ###########################
        # data 1 box
        d1_vbox_childs = []
        ##
        ###
        d1_button_next = widgets.Button(description='next measurement')
        d1_button_prev = widgets.Button(description='prev measurement')

        d1_button_next.on_click(self.on_d1_botton_next)
        d1_button_prev.on_click(self.on_d1_botton_prev)

        d1_dropdown_fnames_options = [
            i.name for i in self.controller.data.dataset1.path2data_list
        ]
        d1_dropdown_fnames_value = self.controller.data.dataset1.path2active.name
        self.d1_dropdown_fnames = widgets.Dropdown(
            options=d1_dropdown_fnames_options,
            value=d1_dropdown_fnames_value,
            #     description='N',
            # disabled=disable_data_2,
        )

        self.d1_dropdown_fnames.observe(self.on_change_d1_dropdown_fnames)

        d1_box_h_1 = widgets.HBox(
            [d1_button_prev, d1_button_next, self.d1_dropdown_fnames])
        ###
        d1_vbox_childs.append(d1_box_h_1)

        ##
        ###
        d1_text_path = widgets.Text(placeholder='path name', disabled=False)
        self.d1_text_path = d1_text_path
        d1_vbox_childs.append(d1_text_path)

        ##
        d1_vbox = widgets.VBox(d1_vbox_childs)
        tab_children.append({'element': d1_vbox, 'title': 'iMet'})

        ############################
        # data 2 box
        if isinstance(self.controller.data.dataset2, type(None)):
            disable_data_2 = True
            d2_dropdown_fnames_options = []
            d2_dropdown_fnames_value = None
        else:
            disable_data_2 = False
            d2_dropdown_fnames_options = [
                i.name for i in self.controller.data.dataset2.path2data_list
            ]
            d2_dropdown_fnames_value = self.controller.data.dataset2.path2active.name

        d2_vbox_childs = []
        ##
        ###
        d2_button_next = widgets.Button(description='next measurement',
                                        disabled=disable_data_2)
        d2_button_prev = widgets.Button(description='prev measurement',
                                        disabled=disable_data_2)
        self.d2_dropdown_fnames = widgets.Dropdown(
            options=d2_dropdown_fnames_options,
            value=d2_dropdown_fnames_value,
            #     description='N',
            disabled=disable_data_2,
        )

        d2_button_next.on_click(self.on_d2_botton_next)
        d2_button_prev.on_click(self.on_d2_botton_prev)
        self.d2_dropdown_fnames.observe(self.on_change_d2_dropdown_fnames)

        d2_box_h_1 = widgets.HBox(
            [d2_button_prev, d2_button_next, self.d2_dropdown_fnames])
        ###
        d2_vbox_childs.append(d2_box_h_1)

        ##
        ###
        ## text field showing the path
        d2_text_path = widgets.Text(placeholder='path name', disabled=False)
        self.d2_text_path = d2_text_path

        d2_vbox_childs.append(d2_text_path)

        ##
        d2_vbox = widgets.VBox(d2_vbox_childs)
        tab_children.append({'element': d2_vbox, 'title': 'POPS'})

        # others box

        # Tab
        tab = widgets.Tab([child['element'] for child in tab_children])
        for e, child in enumerate(tab_children):
            tab.set_title(e, child['title'])

    # accordeon
        txt = 'keymap:\t'
        txt += ' - '.join([
            '{}:{}'.format(i[0], i[1])
            for i in self.controller.view.plot.keymap.items()
        ])
        box_layout = widgets.Layout(border='solid 1px')
        description = widgets.Box((widgets.Label(txt), ), layout=box_layout)
        # items = [widgets.Label('change point'), widgets.Label('followed by'), widgets.Label('')]
        self.gridbox = widgets.GridBox(
            [],
            layout=widgets.Layout(grid_template_columns="repeat(3, 200px)"))
        self.populate_gridbox_from_database()
        self.controller.tp_gb = self.gridbox

        self.button_gridbox_reinitiate = widgets.Button(
            description='sort by datetime')
        self.button_gridbox_reinitiate.on_click(
            self.populate_gridbox_from_database)
        # the old one

        # self.accordeon_start = widgets.Text(value='',
        #                                     placeholder='hit z key',
        #                                     description='start:',
        #                                     disabled=False
        #                                     )
        # self.accordeon_end = widgets.Text(value='',
        #                                     placeholder='hit x key',
        #                                     description='end:',
        #                                     disabled=False
        #                                     )
        # self.accordeon_alt = widgets.Text(value='',
        #                                   placeholder='hit a key',
        #                                   description='altitude:',
        #                                   disabled=False
        #                                   )
        # hbox_accordeon_start_stop = widgets.HBox([self.accordeon_start, self.accordeon_end])

        # self.dropdown_gps_bar_bad= widgets.Dropdown(options=['gps', 'baro', 'bad', 'bad_but_usable_gps', 'bad_but_usable_baro'],
        #                                             value='gps',
        #                                             description='which alt to use:',
        #                                             disabled=False,
        #                                             )

        # self.button_save_unsave_flight = widgets.Button(description = 'save/unsave flight')
        # self.button_save_unsave_flight.on_click(self.on_button_save_flight)

        # hbox_accordeon_alt_source = widgets.HBox([self.dropdown_gps_bar_bad, self.accordeon_alt])

        accordon_box = widgets.VBox(
            [description, self.button_gridbox_reinitiate, self.gridbox]
        )  #,hbox_accordeon_start_stop, hbox_accordeon_alt_source, self.button_save_unsave_flight])
        accordion_children = [accordon_box]
        accordion = widgets.Accordion(children=accordion_children)
        accordion.set_title(0, 'do_stuff')

        # messages
        self.messages = widgets.Textarea('\n'.join(self.controller._message),
                                         layout={'width': '100%'})
        # message_box = widgets.HBox([self.messages])
        # OverVbox

        overVbox = widgets.VBox([tab, accordion, self.messages])
        display(overVbox)
        ####################
        self.update_d1()
        self.update_d2()
        self.update_accordeon()
Example #21
0
#  -- Display
# ----------------------------------
box_layout = wdg.Layout(display='flex',
                        flex_flow='column',
                        flex_wrap='wrap',
                        align_content='stretch',
                        justify_content='center',
                        align_items='stretch',
                        width='28%')
outp_layout = wdg.Layout(display='flex',
                         flex_flow='column',
                         flex_wrap='wrap',
                         align_content='stretch',
                         justify_content='center',
                         align_items='stretch',
                         width='72%')
ui.picker.layout = wdg.Layout(display='flex',
                              flex_flow='column',
                              flex_wrap='wrap',
                              align_content='stretch',
                              justify_content='center',
                              align_items='stretch',
                              width='100%')
cc = [
    ui.cnct, ui.ip, ui.scan, ui.trace, ui.res, ui.bandwidth, ui.pts, ui.λ,
    ui.clr, ui.save, ui.picker
]
ctrl = wdg.Box(children=cc, layout=box_layout)
otp = wdg.Box(children=[figOSA], layout=outp_layout)
display(wdg.HBox([ctrl, otp]))
Example #22
0
def run_notebook():
    """Create the GUI controls and any control logic."""

    #Create Borg for others to communicate with
    analysis = SPAnalysis()

    # text box for entering UniProt queries
    query = widgets.Text(description="Query")

    # checkbox to select Swiss-Prot only searches
    reviewed_check = widgets.Checkbox(description="Search reviewed",
                                      value=True)

    # slider for the ratio
    ratio_slider = widgets.FloatSlider(description="Ratio",
                                       min=0.0,
                                       max=1.0,
                                       step=0.05,
                                       value=0.9)
    # bundle them up...
    controls = [
        query,
        reviewed_check,
        ratio_slider,
    ]
    #... and pass them to the container for display
    interface = widgets.Box(children=controls)
    display(interface)

    # Create the buttons...
    run_button = widgets.Button(description="Run", button_style='primary')
    clear_cache_button = widgets.Button(description="Clear cache",
                                        button_style='warning')
    button_container = widgets.Box(children=[run_button, clear_cache_button])

    #... and display them; CSS changes have to be run after the display() function
    display(button_container)

    #button_container.remove_class('vbox')
    #button_container.add_class('hbox')

    def on_run_button_clicked(b):
        #This Borg knows what the outer Borg, created
        #when starting the interface, knows. I.e. it
        #knows about previous searches -> caching!
        temp_analysis = SPAnalysis()

        querystr = query.value
        reviewed = reviewed_check.value
        ratio = ratio_slider.value
        temp_analysis.run_analysis(querystr, reviewed, ratio)

    def on_clear_cache_button_clicked(b):
        #This Borg knows what the outer Borg, created
        #when starting the interface, knows.
        #Deleting its cache means deleting the entire Borg cache
        temp_analysis = SPAnalysis()
        clear_output()
        try:
            temp_analysis.cache = {}
            print("Cached searches have been cleared.")
        except AttributeError:
            print("Cache is empty already.")

    run_button.on_click(on_run_button_clicked)
    clear_cache_button.on_click(on_clear_cache_button_clicked)
    def __init__(self):

        # Callback for the info button, opens up a dialog
        def info_button_pressed(obj):
            dialog_javascript_pattern = """
                require(
                    ["base/js/dialog"],
                    function(dialog) {
                        dialog.modal({
                            title: 'TITLE',
                            body: 'BODY',
                            buttons: {
                                'close': {}
                            }
                        });
                    });
            """

            title = "Learning rate"
            body = obj.tooltip
            msg_js = dialog_javascript_pattern.replace('TITLE', title).replace(
                'BODY', body)
            IPython.display.display(IPython.display.Javascript(msg_js))

        # Mockup parameters
        label_layout = Layout(width='200px')
        info_button = widgets.Button(
            description='info',
            icon='info',
            value="learningRate",
            tooltip=
            'A value used by the learning algorithm to determine how quickly the weights are adjusted. It determines the acquisition time for neurons with weights that are trained using the algorithm.'
        )
        info_button.on_click(info_button_pressed)
        w1 = widgets.Text(value="0.01")
        w2 = widgets.Dropdown(options=['ResNet18.dnn', 'AlexNet.dnn'])
        w3 = widgets.Checkbox(value=False)
        w4 = widgets.FloatSlider(value=0.5, min=0, max=1.0, step=0.05)
        w_box = widgets.VBox(children=[
            widgets.HBox(children=[
                widgets.HTML(
                    layout=label_layout,
                    value='<div align = "right"> learningRate: </div>',
                    tooltip='tooltip'), w1, info_button
            ]),
            widgets.HBox(children=[
                widgets.HTML(
                    layout=label_layout,
                    value='<p style="text-align:right"> pretrainedModelFileName'
                ), w2, info_button
            ]),
            widgets.HBox(children=[
                widgets.Label(layout=label_layout, value="boVerbose:"), w3,
                info_button
            ]),
            widgets.HBox(children=[
                widgets.Label(layout=label_layout, value="dropoutRate:"), w4,
                info_button
            ])
        ])

        # Tab widget
        page1 = widgets.Box(children=[w_box], padding=4)
        page2 = widgets.Box(children=[], padding=4)
        page3 = widgets.Box(children=[], padding=4)
        page4 = widgets.Box(children=[], padding=4)
        page5 = widgets.Box(children=[], padding=4)
        tabs = widgets.Tab(children=[page1, page2, page3, page4, page5])
        tabs.set_title(0, 'Trainer')
        tabs.set_title(1, 'Model')
        tabs.set_title(2, 'Dataset and Splitter')
        tabs.set_title(3, 'Evaluation')
        tabs.set_title(4, 'Deployment')
        params_ui = widgets.Tab(children=[tabs])
        params_ui.set_title(0, 'PARAMETERS')

        self.ui = params_ui
    def create_mod_radio(self):
        def params(_):
            if T9.value != '':
                myboxB.layout.display = 'none'
                names = []
                listsB = []
                myboxB.children = listsB
                for i in range(int(T9.value)):
                    names.append('T' + str(i + 10))
                    T10 = widgets.Text()
                    T10.disabled = True
                    T10.value = str(i)
                    T10.layout.width = "10%"
                    T11 = widgets.Text()
                    T11.value = ''
                    T11.layout.width = "15%"
                    T12 = widgets.Text()
                    T12.value = ''
                    T12.layout.width = "15%"
                    T13 = widgets.Text()
                    T13.value = ''
                    T13.layout.width = "15%"
                    T14 = widgets.Text()
                    T14.value = ''
                    T14.layout.width = "15%"
                    lists1 = [T10, T11, T12, T13, T14]
                    mybox1 = widgets.HBox(children=lists1)
                    listsB.append(mybox1)
                myboxB.children = listsB
                myboxB.layout.display = ''
            else:
                myboxB.layout.display = 'none'

        def dep(_):
            if T15.value != '':
                myboxB2.layout.display = 'none'
                names2 = []
                listsB2 = []
                myboxB2.children = listsB2
                for i in range(int(T15.value)):
                    names2.append('T' + str(i + 16))
                    T16 = widgets.Text()
                    T16.layout.width = "30%"
                    lists2 = [T16]
                    mybox2 = widgets.HBox(children=lists2)
                    listsB2.append(mybox2)
                myboxB2.children = listsB2
                myboxB2.layout.display = ''
            else:
                myboxB2.layout.display = 'none'

        def excl(_):
            if T17.value != '':
                myboxB3.layout.display = 'none'
                names3 = []
                listsB3 = []
                myboxB3.children = listsB3
                for i in range(int(T17.value)):
                    names2.append('T' + str(i + 18))
                    T18 = widgets.Text()
                    T18.layout.width = "30%"
                    T18.value = ''
                    lists3 = [T18]
                    mybox3 = widgets.HBox(children=lists3)
                    listsB3.append(mybox3)
                myboxB3.children = listsB3
                myboxB3.layout.display = ''
            else:
                myboxB3.layout.display = 'none'

        def fileloaded(_):
            os.chdir("..")
            import readconffile
            os.chdir("GUI")
            tt = self.RB.value
            if not (tt is None):
                BTC.disabled = False
                valRB = tt[tt.find('CA1'):len(tt)]
                expfilename = 'exp' + valRB[valRB.find('(') +
                                            1:valRB.find(')')] + '.txt'
                readconffile.filename = expfilename.replace("exp", "config")
                os.chdir("../data/config_files/")
                [
                    inputfilename, modfilename, parametersfilename, flagdata,
                    flagcut, nrtraces, Vrestf, esynf, nrparamsfit, paramnr,
                    paramname, paraminitval, paramsconstraints, nrdepnotfit,
                    depnotfit, nrdepfit, depfit, seedinitvaluef
                ] = readconffile.readconffile()
                os.chdir("../../GUI/")
                T1.value = expfilename
                l = list(self.file_widget.value.keys())
                if (len(l) > 0):
                    T2.value = l[0]
                T6.value = str(nrtraces)
                T7.value = str(Vrestf)
                T8.value = str(esynf)

        def writefile(_):
            for f in os.listdir("."):
                if f.startswith("config.txt"):
                    os.remove(f)
            with open('config.txt', 'w') as f:
                f.write('//name of file containing raw traces\n')
                f.write(T1.value.strip() + '\n')
                f.write('//name of mod file\n')
                f.write(T2.value.strip() + '\n')
                f.write('//name of parameters file\n')
                f.write(T3.value.strip() + '\n')
                f.write(
                    '//flagdata==0 data with one time column for all currents; ==1 data with one time column for each current\n'
                )
                f.write(T4.value.strip() + '\n')
                f.write(
                    '//flagcut==0 data not cutted; ==1 data cutted below 20% of max\n'
                )
                f.write(T5.value.strip() + '\n')
                f.write('//number of traces\n')
                f.write(T6.value.strip() + '\n')
                f.write('//PROTOCOL\n')
                f.write('//VCLAMP AMP\n')
                f.write(T7.value.strip() + '\n')
                f.write('//REVERSAL POTENTIAL\n')
                f.write(T8.value.strip() + '\n')
                f.write('//FITTING PARAMETERS AND INITIAL VALUES\n')
                f.write(T9.value.strip() + '\n')
                for i in range(int(T9.value.strip())):
                    f.write(myboxB.children[i].children[0].value + ' ' +
                            myboxB.children[i].children[1].value + ' ' +
                            myboxB.children[i].children[2].value)
                    f.write('\n')
                f.write('//CONSTRAINTS\n')
                for i in range(int(T9.value.strip())):
                    f.write(myboxB.children[i].children[3].value + ' ' +
                            myboxB.children[i].children[4].value)
                    f.write('\n')
                f.write('//DEPENDENCY RULES FOR PARAMETERS NOT FITTED\n')
                f.write(T15.value.strip() + '\n')
                for i in range(int(T15.value.strip())):
                    f.write(myboxB2.children[i].children[0].value)
                    f.write('\n')
                f.write('//EXCLUSION RULES\n')
                f.write(T17.value.strip() + '\n')
                for i in range(int(T17.value.strip())):
                    f.write(myboxB3.children[i].children[0].value)
                    f.write('\n')
                f.write('//seed\n')
                f.write(T19.value.strip() + '\n')
                f.write('\n')
            f.close()
            with open(list(self.file_widget.value.keys())[0], "wb") as fp:
                fp.write(self.file_widget.value[list(
                    self.file_widget.value.keys())[0]]['content'])

        def writefileifnotemptycell(_):
            BTC.disabled = True
            if T1.value.strip()!='' and T2.value.strip()!='' and T3.value.strip()!='' and T4.value.strip()!='' \
                and T5.value.strip()!='' and T6.value.strip()!='' and T7.value.strip()!='' and T8.value.strip()!='' and \
                T9.value.strip()!='' and T15.value.strip()!='' and T17.value.strip()!='' and T19.value.strip()!='':
                os.chdir("transfer")
                writefile(_)
                os.chdir("..")
            else:
                BTC.disabled = False

        def RB1click(_):
            if self.RB1.value == 'local':
                self.file_widget.layout.display = ''
                DM.visible = False
                HT.layout.display = ''
                tabs.layout.display = ''
            else:
                self.file_widget.layout.display = 'none'
                DM.visible = True
                HT.layout.display = 'none'
                tabs.layout.display = 'none'

        display(self.RB1)
        DM = widgets.Text()
        DM.value = 'ProbGABAAB_EMS_GEPH_g.mod'
        DM.visible = True
        DM.disabled = True
        display(DM)
        HM = widgets.HTML("""
            <input name="mioTesto" type="text" value="Select mod file" style="color: black; background-color: white;
            border: none; font-weight: bold" size="60" maxlength="400" disabled="true" id="testo" />
        """)
        H1 = widgets.HTML("""
            <input name="mioTesto" type="text" value="name of file containing raw traces" style="color: black; background-color: white;
            border: none; font-weight: bold" size="60" maxlength="400" disabled="true" id="testo" />
        """)
        T1 = widgets.Text()
        T1.value = ''
        T1.disabled = True
        H2 = widgets.HTML("""
            <input name="mioTesto" type="text" value="name of mod file" style="color: black; background-color: white;
            border: none; font-weight: bold" size="60" maxlength="400" disabled="true" id="testo" />
        """)
        T2 = widgets.Text()
        self.file_widget.layout.display = ''
        T2.value = ''
        T2.disabled = True
        H3 = widgets.HTML("""
            <input name="mioTesto" type="text" value="name of parameters file" style="color: black; background-color: white;
            border: none; font-weight: bold" size="60" maxlength="400" disabled="true" id="testo" />
        """)
        T3 = widgets.Text()
        T3.value = 'parameters.txt'
        H4 = widgets.HTML("""
            <input name="mioTesto" type="text" rows="2" 
            value="flagdata==0 data with one time column for all currents; ==1 data with one time column for each current"
            style="color: black; background-color: white; border: none; font-weight: bold" size="60" maxlength="400" disabled="true" id="testo" />
        """)
        H4 = widgets.HTML("""
            <textarea name="textarea" rows="2" disabled="true" style="width:400px; height:40px;
            color: black; background-color: white; border: none; font-weight: bold; resize: none">
            flagdata==0 data with one time column for all currents; ==1 data with one time column for each current</textarea>
        """)
        T4 = widgets.Text()
        T4.value = '0'
        H5 = widgets.HTML("""
            <textarea name="textarea" rows="2" disabled="true" style="width:400px; height:40px; color: black; background-color: white;
            border: none; font-weight: bold; resize: none">flagcut==0 data not cutted;\n ==1 data cutted below 20% of max</textarea>
        """)
        T5 = widgets.Text()
        T5.value = '1'
        H6 = widgets.HTML("""
            <input name="mioTesto" type="text" value="number of traces" style="color: black; background-color: white;
            border: none; font-weight: bold" size="60" maxlength="400" disabled="true" id="testo" />
            """)
        T6 = widgets.Text()
        T6.value = ''
        T6.disabled = True
        H7 = widgets.HTML("""
            <input name="mioTesto" type="text" value="PROTOCOL" style="color: black; background-color: white; border: none; 
            font-weight: bold" size="60" maxlength="400" disabled="true" id="testo" />
        """)
        H8 = widgets.HTML("""
            <input name="mioTesto" type="text" value="VCLAMP AMP" style="color: black; background-color: white;
            border: none; font-weight: bold" size="60" maxlength="400" disabled="true" id="testo" />
        """)
        T7 = widgets.Text()
        T7.value = ''
        T7.disabled = True
        H9 = widgets.HTML("""
            <input name="mioTesto" type="text" value="REVERSAL POTENTIAL" style="color: black; background-color: white;
            border: none; font-weight: bold" size="60" maxlength="400" disabled="true" id="testo" />
        """)
        T8 = widgets.Text()
        T8.value = ''
        T8.disabled = True
        H10 = widgets.HTML("""
            <input name="mioTesto" type="text" value="FITTING PARAMETERS INITIAL VALUES AND CONSTRAINTS" style="color: black;
            background-color: white; border: none; font-weight: bold" size="60" maxlength="400" disabled="true" id="testo" />"""
                           )
        H11 = widgets.HTML("""
            <textarea name="textarea" disabled="true" style="width:460px; height:15px; color: black; background-color: white;
            border: none; font-weight: bold; resize: none">nr of params, names of params, initial values, min, max</textarea>
        """)
        T9 = widgets.Text()
        T9.value = '0'
        T9.layout.width = "10%"
        lists = [
            H1, T1, H2, T2, H3, T3, H4, T4, H5, T5, H6, T6, H7, H8, T7, H9, T8,
            H10, H11, T9
        ]
        mybox = widgets.VBox(children=lists)

        names = []
        listsB = []
        for i in range(int(T9.value)):
            names.append('T' + str(i + 10))
            T10 = widgets.Text()
            T10.value = str(i)
            T10.layout.width = "10%"
            T10.disabled = True
            T11 = widgets.Text()
            T11.layout.value = ''
            T11.layout.width = "15%"
            T12 = widgets.Text()
            T12.value = ''
            T12.layout.width = "15%"
            T13 = widgets.Text()
            T13.value = ''
            T13.layout.width = "15%"
            T14 = widgets.Text()
            T14.value = ''
            T14.layout.width = "15%"
            lists1 = [T10, T11, T12, T13, T14]
            mybox1 = widgets.HBox(children=lists1)
            listsB.append(mybox1)

        myboxB = widgets.VBox(children=listsB)
        H12 = widgets.HTML("""
            <input name="mioTesto" type="text" value="DEPENDENCY RULES FOR PARAMETERS NOT FITTED" style="color: black; background-color: white;
            border: none; font-weight: bold" size="60" maxlength="400" disabled="true" id="testo" />
        """)
        T15 = widgets.Text()
        T15.value = '0'
        T15.layout.width = "10%"
        names2 = []
        listsB2 = []
        for i in range(int(T15.value)):
            names2.append('T' + str(i + 16))
            T16 = widgets.Text()
            T16.layout.width = "30%"
            lists2 = [T16]
            mybox2 = widgets.HBox(children=lists2)
            listsB2.append(mybox2)
        myboxB2 = widgets.VBox(children=listsB2)
        T15.observe(dep)
        H13 = widgets.HTML("""
            <input name="mioTesto" type="text" value="EXCLUSION RULES" style="color: black; background-color: white;
            border: none; font-weight: bold" size="60" maxlength="400" disabled="true" id="testo" />
        """)
        T17 = widgets.Text()
        T17.value = '0'
        T17.layout.width = "10%"
        names3 = []
        listsB3 = []
        for i in range(int(T17.value)):
            names2.append('T' + str(i + 18))
            T18 = widgets.Text()
            T18.layout.width = "30%"
            lists3 = [T18]
            mybox3 = widgets.HBox(children=lists3)
            listsB3.append(mybox3)

        myboxB3 = widgets.VBox(children=listsB3)
        T17.observe(excl)
        T9.observe(params)
        H14 = widgets.HTML("""
            <input name="mioTesto" type="text" value="seed" style="color: black; background-color: white;
            border: none; font-weight: bold" size="60" maxlength="400" disabled="true" id="testo" />
        """)
        T19 = widgets.Text()
        T19.value = '1234567'
        T19.layout.width = "20%"

        H10.visible = False
        H11.visible = False
        T9.visible = False
        myboxB.layout.display = ''
        H12.visible = False
        T15.visible = False
        myboxB2.layout.display = ''
        H13.visible = False
        T17.visible = False
        myboxB3.layout.display = ''
        H14.visible = False
        T19.visible = False

        BTC = widgets.Button()
        BTC.description = 'Write config file'
        BTC.on_click(writefileifnotemptycell)
        BTC.disabled = True

        lists = [HM, self.file_widget]
        myboxpage1 = widgets.VBox(children=lists)
        page1 = widgets.Box(children=[myboxpage1])
        lists = [H1, T1, H2, T2, H6, T6, H7, H8, T7, H9, T8]
        myboxpage2 = widgets.VBox(children=lists)
        page2 = widgets.Box(children=[myboxpage2])
        lists = [
            H10, H11, T9, myboxB, H12, T15, myboxB2, H13, T17, myboxB3, H14,
            T19, BTC
        ]
        myboxpage3 = widgets.VBox(children=lists)
        page3 = widgets.Box(children=[myboxpage3])
        tabs = widgets.Tab(children=[page1, page2, page3])
        tabs.observe(fileloaded)
        HT = widgets.HTML("""
            <input name="mioTesto" type="text" value="Select local mod file and write config file" style="color: black;
            background-color: white; border: none; font-weight: bold" size="60" maxlength="400" disabled="true" id="testo" />
        """)
        HT.layout.display = 'none'
        display(HT)
        tabs.layout.display = 'none'
        display(tabs)

        tabs.set_title(0, 'First page')
        tabs.set_title(1, 'Second page')
        tabs.set_title(2, 'Third page')
        self.RB1.on_trait_change(RB1click, 'value')
Example #25
0
    def visualize_tracker(tracker: "Tracker", sequence: "Sequence"):
        from IPython.display import display
        from ipywidgets import widgets
        from vot.utilities.draw import ImageDrawHandle

        def encode_image(handle):
            with io.BytesIO() as output:
                handle.snapshot.save(output, format="PNG")
                return output.getvalue()

        handle = ImageDrawHandle(sequence.frame(0).image())

        button_restart = widgets.Button(description='Restart')
        button_next = widgets.Button(description='Next')
        button_play = widgets.Button(description='Run')
        frame = widgets.Label(value="")
        frame.layout.display = "none"
        frame2 = widgets.Label(value="")
        image = widgets.Image(value=encode_image(handle), format="png", width=sequence.size[0] * 2, height=sequence.size[1] * 2)

        state = dict(frame=0, auto=False, alive=True, region=None)
        condition = Condition()

        buttons = widgets.HBox(children=(frame, button_restart, button_next, button_play, frame2))

        image.value = encode_image(handle)

        def run():

            runtime = tracker.runtime()

            while state["alive"]:

                if state["frame"] == 0:
                    state["region"], _, _ = runtime.initialize(sequence.frame(0), sequence.groundtruth(0))
                else:
                    state["region"], _, _ = runtime.update(sequence.frame(state["frame"]))

                update_image()

                with condition:
                    condition.wait()

                    if state["frame"] == sequence.length:
                        state["alive"] = False
                        continue

                    state["frame"] = state["frame"] + 1


        def update_image():
            handle.image(sequence.frame(state["frame"]).image())
            handle.style(color="green").region(sequence.frame(state["frame"]).groundtruth())
            if state["region"]:
                handle.style(color="red").region(state["region"])
            image.value = encode_image(handle)
            frame.value = "Frame: " + str(state["frame"] - 1)

        def on_click(button):
            if button == button_next:
                with condition:
                    state["auto"] = False
                    condition.notify()
            if button == button_restart:
                with condition:
                    state["frame"] = 0
                    condition.notify()
            if button == button_play:
                with condition:
                    state["auto"] = not state["auto"]
                    button.description = "Stop" if state["auto"] else "Run"
                    condition.notify()

        button_next.on_click(on_click)
        button_restart.on_click(on_click)
        button_play.on_click(on_click)
        widgets.jslink((frame, "value"), (frame2, "value"))

        def on_update(_):
            with condition:
                if state["auto"]:
                    condition.notify()

        frame2.observe(on_update, names=("value", ))

        thread = Thread(target=run)
        display(widgets.Box([widgets.VBox(children=(image, buttons))]))
        thread.start()
Example #26
0
    def __init__(self, text, to_replace, tree=False, inst=luecke):
        # to_replace ist dictionary mit 'word':'alternative list'
        instbox = widgets.HTML(value='<i>{}</i>'.format(inst), layout=widgets.Layout(justify_content="center")) 

        repl = to_replace
        textlist = text.split(" ")
        self.richtig = text
        zusammen =  []
        self.selection = []
        self.wid_list = []
        
        def on_change_drop(change):
            if change['type'] == 'change' and change['name']=='value':
                    index = self.wid_list.index(change.owner)
                    self.selection[index] = change['new']
            button.style.button_color = None        
        
        for word in textlist:
            try: 
                choice = repl[word]
                if not word in choice:
                    choice.append(word)
                choice.sort()
                choice.append(" ")
                zw = ' '.join(zusammen)
                self.wid_list.append(widgets.HTML(value='<h4 style="font-size:14px;">{}</h4>'.format(zw), width='auto'))
                self.selection.append(zw)                     
                zusammen = []
                dropdown =widgets.Dropdown(options = choice, value=choice[len(choice)-1], layout=widgets.Layout(width="150px"))  
                self.wid_list.append(dropdown)
                dropdown.observe(on_change_drop)
                self.selection.append(" ")
                
            except KeyError:
                zusammen.append(word)
        
        zw = ' '.join(zusammen)
        self.wid_list.append(widgets.HTML(value='<h4 style="font-size:14px;">{}</h4>'.format(zw)))
        self.selection.append(zw)  
        
        box_layout = widgets.Layout(display='inline-flex', flex_flow='row wrap', align_items='stretch',flex='flex-grow', justify_content='flex-start', align_content="stretch")
        box = widgets.Box(children=self.wid_list, layout=box_layout)
        
        button = widgets.Button(description="Korrekt?",layout=widgets.Layout(width="250px"))
        
        
        super().__init__(children=[instbox,box,button])
        
                
        def on_button_clicked(b):
                sel = ' '.join(self.selection)
                if  sel == self.richtig:
                    b.style.button_color = 'lightgreen'
                    # if tree:
                    #     out=""
                    #     for elem in self.richtig:
                    #         out = out + elem
                        
                    #     t = ParentedTree.fromstring(out)
                    #     display(t)
                else:
                    b.style.button_color = 'red'
        
        button.on_click(on_button_clicked)
    def createUI(self):
        dd = {}

        # === Connection ===
        # ==============================
        # connection button
        dd['cnct'] = wdg.Checkbox(value=False, description="Connected")
        # IP Address
        dd['ip'] = wdg.Text(value='10.0.0.11', description='IP:')
        # Model connected
        dd['model'] = wdg.Textarea(value='',
                                   rows=9,
                                   placeholder='',
                                   description='Model',
                                   disabled=True)

        # === Scan ===
        # ==============================
        # Scan type
        dd['refresh_trace'] = wdg.Button(
            description='Refresh Trace',
            button_style='info',
            tooltip='Fetch the current trace on the instrument',
            display='flex',
            flex_flow='row',
            justify_content='space-between',
            align_items='stretch',
        )
        # dd['refresh'].add_class("osa_scan_button")

        dd['scan'] = wdg.ToggleButtons(options=['Single', 'Repeat', 'Stop'],
                                       value='Stop',
                                       display='flex',
                                       flex_flow='row',
                                       justify_content='space-between',
                                       align_items='stretch',
                                       description='Scan:',
                                       button_style='info')
        # dd['scan'].add_class("osa_scan_button")

        # === Setup ===
        # ==============================
        # Wavelength range

        dd['refresh_setup'] = wdg.Button(
            description='Refresh Setup',
            button_style='info',
            tooltip='Fetch the current setup of the instrument',
            display='flex',
            flex_flow='row',
            justify_content='space-between',
            align_items='stretch',
        )

        dd['λ'] = wdg.IntRangeSlider(value=(0, 2000),
                                     min=0,
                                     max=2000,
                                     step=5,
                                     description='λ',
                                     continuous_update=False)

        # Number of pts
        dd['pts'] = wdg.IntSlider(value=50000,
                                  min=1,
                                  max=100000,
                                  step=100,
                                  description='Points:',
                                  continuous_update=False)
        # dd['pts'].add_class("osa_wavelength")
        # Resolution
        dd['res'] = wdg.Dropdown(options=[
            'Norm/Hold', 'Norm/Auto', 'Mid', 'High 1', 'High 2', 'High 3'
        ],
                                 description='Resolution:')

        # Bandiwth
        self._Bdwt_val = {
            0.02: '0.02 nm',
            0.05: '0.05 nm',
            0.1: '0.1 nm',
            0.2: '0.2 nm',
            0.5: '0.5 nm',
            1: '1 nm',
            2: '2 nm'
        }
        dd['bandwidth'] = wdg.SelectionSlider(description='Bandwidth:',
                                              options=self._Bdwt_val.values(),
                                              continuous_update=False)

        # dd['bandwidth'].add_class("osa_bandwidth")
        # === Trace ===
        # ==============================
        # freq/wavelength swith
        dd['freq_scale'] = wdg.ToggleButtons(
            options=['Wavelength', 'Frequency'],
            value='Wavelength',
            description='X scale',
            disabled=False,
            button_style='')
        # Trace selection
        dd['trace'] = wdg.Dropdown(
            options=['Trace A', 'Trace B', 'Trace C', 'Trace D'],
            value='Trace A',
            description='Trace:')

        # clear traces
        dd['clr'] = wdg.Button(
            description='Clear Traces',
            button_style='danger',
            tooltip='',
        )
        # delete saved trace
        # clear traces
        dd['clr_keep'] = wdg.Button(
            description='Clear Saved',
            button_style='warning',
            tooltip='',
        )
        # keep current
        dd['keep'] = wdg.Button(
            description='Keep Trace',
            button_style='success',
            tooltip='Click me',
        )
        # === Save ===
        # ==============================
        # save
        # freq/wavelength swith
        dd['to_save'] = wdg.ToggleButtons(options=['PC', 'OSA'],
                                          value='PC',
                                          description='Data',
                                          disabled=False,
                                          button_style='')
        dd['save'] = wdg.Button(description='Save Spectra',
                                button_style='info')
        dd['picker'] = FileChooser(os.path.abspath('./../'), width=300)
        dd['picker'].use_dir_icons = True
        dd['picker'].rows = 8
        dd['picker'].width = 200

        self.ui = _dic2struct(dd)

        # -- setup the style of the UI --
        # --------------------------------
        self.ui.trace.layout = {
            'width': '285px',
            'margin': '20px 7px 20px 0px'
        }
        self.ui.trace.style = {"description_width": "45px"}

        self.ui.keep.layout = {'width': '300px', 'margin': '0px 0px 20px 0px'}
        self.ui.clr_keep.layout = {
            'width': '300px',
            'margin': '0px 0px 20px 0px'
        }
        self.ui.clr.layout = {'width': '300px', 'margin': '0px 0px 20px 0px'}

        self.ui.freq_scale.layout = {
            'width': '300px',
            'margin': '0px 0px 20px 0px'
        }
        self.ui.freq_scale.style = {
            "button_width": "95px",
            "description_width": "45px"
        }

        self.ui.refresh_trace.layout = {
            'width': '300px',
            'margin': '40px 0px 20px 0px'
        }
        self.ui.refresh_trace.style = {"button_width": "55px"}

        self.ui.scan.layout = {'width': '300px', 'margin': '20px 0px 20px 0px'}
        self.ui.scan.style = {
            "button_width": "55px",
            "description_width": "45px"
        }

        self.ui.ip.layout = {'width': '300px', 'margin': '0px 0px 20px 0px'}
        self.ui.ip.style = {"description_width": "45px"}

        self.ui.model.layout = {'width': '300px', 'margin': '0px 0px 20px 0px'}
        self.ui.model.style = {"description_width": "45px"}

        self.ui.cnct.layout = {'width': '300px', 'margin': '20px 0px 20px 0px'}
        self.ui.cnct.style = {"description_width": "45px"}

        self.ui.refresh_setup.layout = {
            'width': '300px',
            'margin': '20px 0px 20px 0px'
        }
        self.ui.res.layout = {'width': '300px', 'margin': '20px 0px 20px 0px'}
        self.ui.res.style = {"description_width": "70px"}
        self.ui.bandwidth.layout = {
            'width': '300px',
            'margin': '0px 0px 20px 0px'
        }
        self.ui.bandwidth.style = {"description_width": "70px"}
        self.ui.pts.layout = {'width': '300px', 'margin': '0px 0px 20px 0px'}
        self.ui.pts.style = {"description_width": "70px"}

        self.ui.λ.layout = {'width': '300px', 'margin': '0px 0px 20px 0px'}
        self.ui.λ.style = {"description_width": "70px"}

        self.ui.to_save.layout = {
            'width': '300px',
            'margin': '20px 0px 20px 0px'
        }
        self.ui.to_save.style = {
            "button_width": "90px",
            "description_width": "45px"
        }
        self.ui.save.layout = {'width': '300px', 'margin': '0px 0px 20px 0px'}
        self.ui.picker.layout = wdg.Layout(display='inline',
                                           flex_flow='column',
                                           flex_wrap='wrap',
                                           align_content='stretch',
                                           justify_content='center',
                                           align_items='stretch',
                                           width='300px')
        self.ui.picker.width = 200
        self.ui.picker.rows = 8

        # -- diplaying with style --

        box_layout = wdg.Layout(display='flex',
                                flex_flow='column',
                                flex_wrap='wrap',
                                align_content='stretch',
                                justify_content='center',
                                align_items='stretch',
                                width='28%',
                                height='500px')
        outp_layout = wdg.Layout(display='flex',
                                 flex_flow='column',
                                 flex_wrap='wrap',
                                 align_content='stretch',
                                 justify_content='center',
                                 align_items='stretch',
                                 width='72%')

        figure = wdg.Box(children=[self.figOSA], layout=outp_layout)

        v_layout = wdg.Layout(display='flex',
                              flex_flow='column',
                              align_items='center',
                              align_content='center',
                              width='100%')

        items = [wdg.Label('') for i in range(4)]
        left_box = wdg.VBox([items[0], items[1]])
        right_box = wdg.VBox([items[2], items[3]])
        spacer = wdg.HBox([left_box, right_box])

        Connection = wdg.VBox([self.ui.cnct, self.ui.ip, self.ui.model],
                              layout=v_layout)
        Scan = wdg.VBox([self.ui.refresh_trace, self.ui.scan], layout=v_layout)
        Setup = wdg.VBox([
            self.ui.refresh_setup, self.ui.res, self.ui.bandwidth, self.ui.pts,
            self.ui.λ
        ],
                         layout=v_layout)
        Trace = wdg.VBox([
            self.ui.trace, self.ui.freq_scale, self.ui.keep, self.ui.clr_keep,
            self.ui.clr
        ],
                         layout=v_layout)
        Save = wdg.VBox([self.ui.to_save, self.ui.save, self.ui.picker],
                        layout=v_layout)
        children = [Connection, Scan, Setup, Trace, Save]

        tab = wdg.Tab(layout=box_layout)
        tab.children = children
        titles = ['Connection', 'Scan', 'Setup', 'Trace', 'Save']
        for it, tt in enumerate(titles):
            tab.set_title(it, tt)
        end_layout = wdg.Layout(display='flex',
                                flex_flow='row',
                                align_items='center',
                                align_content='center',
                                width='100%')
        endUI = wdg.HBox([tab, figure], layout=end_layout)

        # -- Dispaying --
        display(endUI)
Example #28
0
            #print("hallo",f)
            clear_output()
            play(synth(f))

    button.on_click(partial(on_button_clicked, f))
    buttons.append(button)
    midi_buttons.append(midi_button)
    freq_buttons.append(freq_button)

# We place all buttons horizontally.
print("The top line shows the MIDI numbers")
print("The second line shows the frequencies of the tones in Hz")
print("The bottom section is a synthesizer keyboard with the notes on it")
print("Hit a note on the keyboard to hear it")
piano = widgets.VBox([
    widgets.Box(midi_buttons),
    widgets.Box(freq_buttons),
    widgets.Box(buttons), output
])
piano

# ### Finally play a simple melody

# In[ ]:

melody = [
    'C4', 'D4', 'E4', 'C4', 'E4', 'F4', 'G4', 'G4', 'C4', 'D4', 'E4', 'C4',
    'E4', 'F4', 'G4', 'G4'
]
y = []
for note in melody: